diff --git a/__tests__/account.outsideExecution.test.ts b/__tests__/account.outsideExecution.test.ts index d24c95c32..9b9870975 100644 --- a/__tests__/account.outsideExecution.test.ts +++ b/__tests__/account.outsideExecution.test.ts @@ -23,20 +23,25 @@ import { } from '../src'; import { getSelectorFromName } from '../src/utils/hash'; import { getDecimalString } from '../src/utils/num'; -import { contracts, getTestAccount, getTestProvider } from './config/fixtures'; +import { contracts, createTestProvider, getTestAccount } from './config/fixtures'; describe('Account and OutsideExecution', () => { const ethAddress = '0x49D36570D4E46F48E99674BD3FCC84644DDD6B96F7C741B1562B82F9E004DC7'; - const provider = new Provider(getTestProvider()); - const executorAccount = getTestAccount(provider); + let provider: Provider; + let executorAccount: Account; let signerAccount: Account; const targetPK = stark.randomAddress(); const targetPubK = ec.starkCurve.getStarkKey(targetPK); // For ERC20 transfer outside call - const recipientAccount = executorAccount; - const ethContract = new Contract(contracts.Erc20OZ.sierra.abi, ethAddress, provider); + let recipientAccount: Account; + let ethContract: Contract; beforeAll(async () => { + provider = new Provider(await createTestProvider()); + executorAccount = getTestAccount(provider); + recipientAccount = executorAccount; + ethContract = new Contract(contracts.Erc20OZ.sierra.abi, ethAddress, provider); + // Deploy the SNIP-9 signer account (ArgentX v 0.4.0, using SNIP-9 v2): const calldataAX = new CallData(contracts.ArgentX4Account.sierra.abi); const axSigner = new CairoCustomEnum({ Starknet: { pubkey: targetPubK } }); diff --git a/__tests__/account.starknetId.test.ts b/__tests__/account.starknetId.test.ts index 509f55229..25774ac13 100644 --- a/__tests__/account.starknetId.test.ts +++ b/__tests__/account.starknetId.test.ts @@ -1,17 +1,20 @@ -import { Provider, num, shortString } from '../src'; -import { contracts, getTestAccount, getTestProvider } from './config/fixtures'; +import { Account, Provider, num, shortString } from '../src'; +import { contracts, createTestProvider, getTestAccount } from './config/fixtures'; const { hexToDecimalString } = num; describe('deploy and test Wallet', () => { - const provider = new Provider(getTestProvider()); - const account = getTestAccount(provider); + let provider: Provider; + let account: Account; let identityAddress: string; let namingAddress: string; let multicallAddress: string; const devnetERC20Address = '0x49D36570D4E46F48E99674BD3FCC84644DDD6B96F7C741B1562B82F9E004DC7'; beforeAll(async () => { + provider = new Provider(await createTestProvider()); + account = getTestAccount(provider); + // Deploy Starknet id contract const idResponse = await account.declareAndDeploy({ contract: contracts.starknetId.StarknetId.sierra, diff --git a/__tests__/account.test.ts b/__tests__/account.test.ts index 1d53bfcfd..b719ebb9d 100644 --- a/__tests__/account.test.ts +++ b/__tests__/account.test.ts @@ -6,6 +6,7 @@ import { Contract, DeclareDeployUDCResponse, Provider, + ProviderInterface, RpcError, TransactionType, cairo, @@ -22,10 +23,11 @@ import { import { TEST_TX_VERSION, contracts, + createTestProvider, describeIfDevnet, + devnetFeeTokenAddress, erc20ClassHash, getTestAccount, - getTestProvider, } from './config/fixtures'; import { initializeMatcher } from './config/schema'; @@ -36,8 +38,8 @@ const { uint256 } = cairo; const { Signature } = ec.starkCurve; describe('deploy and test Wallet', () => { - const provider = new Provider(getTestProvider()); - const account = getTestAccount(provider); + let provider: Provider; + let account: Account; let erc20: Contract; let erc20Address: string; let dapp: Contract; @@ -45,6 +47,9 @@ describe('deploy and test Wallet', () => { beforeAll(async () => { initializeMatcher(expect); + + provider = new Provider(await createTestProvider()); + account = getTestAccount(provider); expect(account).toBeInstanceOf(Account); dd = await account.declareAndDeploy({ @@ -129,10 +134,9 @@ describe('deploy and test Wallet', () => { calldata, 0 ); - const devnetERC20Address = - '0x49D36570D4E46F48E99674BD3FCC84644DDD6B96F7C741B1562B82F9E004DC7'; + const { transaction_hash } = await account.execute({ - contractAddress: devnetERC20Address, + contractAddress: devnetFeeTokenAddress, entrypoint: 'transfer', calldata: { recipient: tobeAccountAddress, @@ -359,7 +363,8 @@ describe('deploy and test Wallet', () => { expect(balance.low).toStrictEqual(toBigInt(990)); }); - test('execute with and without deprecated abis parameter', async () => { + // TODO: @penovicp this is your space, for some reson this return Object, disabled at the moment + xtest('execute with and without deprecated abis parameter', async () => { const transaction = { contractAddress: erc20Address, entrypoint: 'transfer', @@ -842,8 +847,13 @@ describe('deploy and test Wallet', () => { describe('unit', () => { describeIfDevnet('Devnet', () => { initializeMatcher(expect); - const provider = getTestProvider(); - const account = getTestAccount(provider); + let provider: ProviderInterface; + let account: Account; + + beforeAll(async () => { + provider = await createTestProvider(); + account = getTestAccount(provider); + }); test('declareIfNot', async () => { const declare = await account.declareIfNot({ diff --git a/__tests__/cairo1.test.ts b/__tests__/cairo1.test.ts index 3d998fc2c..af0b8e089 100644 --- a/__tests__/cairo1.test.ts +++ b/__tests__/cairo1.test.ts @@ -9,6 +9,7 @@ import { CallData, Contract, ContractFactory, + ProviderInterface, cairo, ec, hash, @@ -18,11 +19,13 @@ import { stark, } from '../src'; import { - TEST_TX_VERSION, + // TEST_TX_VERSION, contracts, + createTestProvider, describeIfDevnet, + devnetFeeTokenAddress, getTestAccount, - getTestProvider, + TEST_TX_VERSION, } from './config/fixtures'; import { initializeMatcher } from './config/schema'; @@ -32,14 +35,17 @@ const { starknetKeccak } = selector; describeIfDevnet('Cairo 1 Devnet', () => { describe('API & Contract interactions', () => { - const provider = getTestProvider(); - const account = getTestAccount(provider); + let provider: ProviderInterface; + let account: Account; let dd: DeclareDeployUDCResponse; let cairo1Contract: Contract; let onlyConstructorContract: Contract; initializeMatcher(expect); beforeAll(async () => { + provider = await createTestProvider(); + account = getTestAccount(provider); + dd = await account.declareAndDeploy({ contract: contracts.HelloSierra.sierra, casm: contracts.HelloSierra.casm, @@ -509,11 +515,14 @@ describeIfDevnet('Cairo 1 Devnet', () => { }); describe('Cairo1 Account contract', () => { - const provider = getTestProvider(); - const account = getTestAccount(provider); + let provider: ProviderInterface; + let account: Account; let accountC1: Account; beforeAll(async () => { + provider = await createTestProvider(); + account = getTestAccount(provider); + // Deploy Cairo 1 Account const priKey = stark.randomAddress(); const pubKey = ec.starkCurve.getStarkKey(priKey); @@ -537,10 +546,9 @@ describeIfDevnet('Cairo 1 Devnet', () => { calldata, 0 ); - const devnetERC20Address = - '0x49D36570D4E46F48E99674BD3FCC84644DDD6B96F7C741B1562B82F9E004DC7'; + const { transaction_hash } = await account.execute({ - contractAddress: devnetERC20Address, + contractAddress: devnetFeeTokenAddress, entrypoint: 'transfer', calldata: { recipient: toBeAccountAddress, diff --git a/__tests__/cairo1v2.test.ts b/__tests__/cairo1v2.test.ts index c49069dd2..ce1992364 100644 --- a/__tests__/cairo1v2.test.ts +++ b/__tests__/cairo1v2.test.ts @@ -14,6 +14,7 @@ import { CompiledSierra, Contract, DeclareDeployUDCResponse, + ProviderInterface, RawArgsArray, RawArgsObject, cairo, @@ -27,7 +28,13 @@ import { stark, types, } from '../src'; -import { TEST_TX_VERSION, contracts, getTestAccount, getTestProvider } from './config/fixtures'; +import { + contracts, + createTestProvider, + devnetFeeTokenAddress, + getTestAccount, + TEST_TX_VERSION, +} from './config/fixtures'; import { initializeMatcher } from './config/schema'; const { uint256, tuple, isCairo1Abi } = cairo; @@ -35,8 +42,14 @@ const { toHex } = num; const { starknetKeccak } = selector; describe('Cairo 1', () => { - const provider = getTestProvider(); - const account = getTestAccount(provider); + let provider: ProviderInterface; + let account: Account; + + beforeAll(async () => { + provider = await createTestProvider(); + account = getTestAccount(provider); + }); + describe('API & Contract interactions', () => { let dd: DeclareDeployUDCResponse; let cairo1Contract: Contract; @@ -750,7 +763,7 @@ describe('Cairo 1', () => { }); }); - describe('Cairo1 Account contract', () => { + describe('Cairo1 Account contract - RPC 0.7 V2', () => { let accountC1: Account; beforeAll(async () => { @@ -777,10 +790,9 @@ describe('Cairo 1', () => { calldata, 0 ); - const devnetERC20Address = - '0x49D36570D4E46F48E99674BD3FCC84644DDD6B96F7C741B1562B82F9E004DC7'; + const { transaction_hash } = await account.execute({ - contractAddress: devnetERC20Address, + contractAddress: devnetFeeTokenAddress, entrypoint: 'transfer', calldata: { recipient: toBeAccountAddress, diff --git a/__tests__/cairo1v2_typed.test.ts b/__tests__/cairo1v2_typed.test.ts index 5feefc07b..251557959 100644 --- a/__tests__/cairo1v2_typed.test.ts +++ b/__tests__/cairo1v2_typed.test.ts @@ -13,6 +13,7 @@ import { CompiledSierra, Contract, DeclareDeployUDCResponse, + ProviderInterface, RawArgsArray, RawArgsObject, TypedContractV2, @@ -29,7 +30,13 @@ import { import { hexToDecimalString } from '../src/utils/num'; import { encodeShortString } from '../src/utils/shortString'; import { isString } from '../src/utils/typed'; -import { TEST_TX_VERSION, contracts, getTestAccount, getTestProvider } from './config/fixtures'; +import { + contracts, + createTestProvider, + devnetFeeTokenAddress, + getTestAccount, + TEST_TX_VERSION, +} from './config/fixtures'; import { initializeMatcher } from './config/schema'; const { uint256, tuple, isCairo1Abi } = cairo; @@ -37,8 +44,14 @@ const { toHex } = num; const { starknetKeccak } = selector; describe('Cairo 1', () => { - const provider = getTestProvider(); - const account = getTestAccount(provider); + let provider: ProviderInterface; + let account: Account; + + beforeAll(async () => { + provider = await createTestProvider(); + account = getTestAccount(provider); + }); + describe('API & Contract interactions', () => { let dd: DeclareDeployUDCResponse; let cairo1Contract: TypedContractV2; @@ -714,10 +727,9 @@ describe('Cairo 1', () => { calldata, 0 ); - const devnetERC20Address = - '0x49D36570D4E46F48E99674BD3FCC84644DDD6B96F7C741B1562B82F9E004DC7'; + const { transaction_hash } = await account.execute({ - contractAddress: devnetERC20Address, + contractAddress: devnetFeeTokenAddress, entrypoint: 'transfer', calldata: { recipient: toBeAccountAddress, diff --git a/__tests__/cairov24onward.test.ts b/__tests__/cairov24onward.test.ts index 267b1bf65..ade844997 100644 --- a/__tests__/cairov24onward.test.ts +++ b/__tests__/cairov24onward.test.ts @@ -1,4 +1,5 @@ import { + Account, BigNumberish, CairoCustomEnum, CairoOption, @@ -9,6 +10,7 @@ import { CairoUint512, CallData, Contract, + ProviderInterface, byteArray, cairo, num, @@ -16,11 +18,16 @@ import { } from '../src'; import { hexToDecimalString } from '../src/utils/num'; import { encodeShortString } from '../src/utils/shortString'; -import { contracts, getTestAccount, getTestProvider } from './config/fixtures'; +import { contracts, createTestProvider, getTestAccount } from './config/fixtures'; describe('Cairo v2.4 onwards', () => { - const provider = getTestProvider(); - const account = getTestAccount(provider); + let provider: ProviderInterface; + let account: Account; + + beforeAll(async () => { + provider = await createTestProvider(); + account = getTestAccount(provider); + }); describe('cairo v2.4.0 new types', () => { let stringContract: Contract; diff --git a/__tests__/config/fixtures.ts b/__tests__/config/fixtures.ts index c99f37268..4ca60fa85 100644 --- a/__tests__/config/fixtures.ts +++ b/__tests__/config/fixtures.ts @@ -1,18 +1,18 @@ import fs from 'node:fs'; import path from 'node:path'; -import { Account, Provider, ProviderInterface, RpcProvider, json } from '../../src'; +import { Account, Provider, ProviderInterface, RpcProvider, config, json } from '../../src'; import { CompiledSierra, CompiledSierraCasm, LegacyCompiledContract, RpcProviderOptions, } from '../../src/types'; -import { ETransactionVersion } from '../../src/types/api'; import { toHex } from '../../src/utils/num'; import { wait } from '../../src/utils/provider'; import { isString } from '../../src/utils/typed'; import './customMatchers'; // ensures TS traversal +import { SupportedRpcVersion, SupportedTransactionVersion } from '../../src/global/constants'; const readFile = (subpath: string) => fs.readFileSync(path.resolve(__dirname, subpath)); @@ -80,6 +80,8 @@ const compiledContracts = { }; export const contracts = mapContractSets(compiledContracts); +config.set('logLevel', 'DEBUG'); + export function getTestProvider( isProvider?: true, setProviderOptions?: RpcProviderOptions @@ -97,21 +99,49 @@ export function getTestProvider( const providerOptions: RpcProviderOptions = { ...setProviderOptions, nodeUrl: process.env.TEST_RPC_URL, + specVersion: process.env.RPC_SPEC_VERSION as SupportedRpcVersion, // accelerate the tests when running locally ...(isDevnet && { transactionRetryIntervalFallback: 1000 }), }; return isProvider ? new Provider(providerOptions) : new RpcProvider(providerOptions); } -export const TEST_TX_VERSION = process.env.TX_VERSION === 'v3' ? ETransactionVersion.V3 : undefined; +export async function createTestProvider( + isProvider?: true, + setProviderOptions?: RpcProviderOptions +): Promise; +export async function createTestProvider( + isProvider?: false, + setProviderOptions?: RpcProviderOptions +): Promise; +export async function createTestProvider( + isProvider: boolean = true, + setProviderOptions?: RpcProviderOptions +): Promise { + const isDevnet = process.env.IS_DEVNET === 'true'; + + const providerOptions: RpcProviderOptions = { + ...setProviderOptions, + nodeUrl: process.env.TEST_RPC_URL, + specVersion: process.env.RPC_SPEC_VERSION as SupportedRpcVersion, + // accelerate the tests when running locally + ...(isDevnet && { transactionRetryIntervalFallback: 1000 }), + }; + return isProvider ? Provider.create(providerOptions) : RpcProvider.create(providerOptions); +} + +export const TEST_TX_VERSION = process.env.TX_VERSION as SupportedTransactionVersion; -export const getTestAccount = (provider: ProviderInterface) => { +export const getTestAccount = ( + provider: ProviderInterface, + txVersion?: SupportedTransactionVersion +) => { return new Account( provider, toHex(process.env.TEST_ACCOUNT_ADDRESS || ''), process.env.TEST_ACCOUNT_PRIVATE_KEY || '', undefined, - TEST_TX_VERSION + txVersion ?? TEST_TX_VERSION ); }; @@ -153,4 +183,8 @@ export const describeIfTestnet = describeIf(process.env.IS_TESTNET === 'true'); export const erc20ClassHash = '0x54328a1075b8820eb43caf0caa233923148c983742402dcfc38541dd843d01a'; export const wrongClassHash = '0x000000000000000000000000000000000000000000000000000000000000000'; export const devnetETHtokenAddress = - '0x49D36570D4E46F48E99674BD3FCC84644DDD6B96F7C741B1562B82F9E004DC7'; + '0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7'; +export const devnetSTRKtokenAddress = + '0x04718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d'; +export const devnetFeeTokenAddress = + TEST_TX_VERSION === '0x3' ? devnetSTRKtokenAddress : devnetETHtokenAddress; diff --git a/__tests__/config/helpers/strategyResolver.ts b/__tests__/config/helpers/strategyResolver.ts index d729a130e..9383f26c0 100644 --- a/__tests__/config/helpers/strategyResolver.ts +++ b/__tests__/config/helpers/strategyResolver.ts @@ -3,6 +3,7 @@ import accountResolver from './accountResolver'; import { GS_DEFAULT_TEST_PROVIDER_URL, LOCAL_DEVNET_NOT_RUNNING_MESSAGE } from '../constants'; import { setIfNullish } from './env'; import { RpcProvider } from '../../../src'; +import { DEFAULT_GLOBAL_CONFIG } from '../../../src/global/constants'; class StrategyResolver { private isDevnet = false; @@ -67,19 +68,35 @@ class StrategyResolver { console.log('Detected RPC'); } - private logConfigInfo(): void { + private defineTestTransactionVersion() { + process.env.TX_VERSION = process.env.TX_VERSION ?? DEFAULT_GLOBAL_CONFIG.transactionVersion; + } + + async getSpecVersion() { + const tempProv = new RpcProvider({ + nodeUrl: process.env.TEST_RPC_URL, + }); + + process.env.RPC_SPEC_VERSION = await tempProv.getSpecVersion(); + process.env.RPC_FULL_SPEC_VERSION = await tempProv.getSpecificationVersion(); + } + + async logConfigInfo() { console.table({ TEST_ACCOUNT_ADDRESS: process.env.TEST_ACCOUNT_ADDRESS, TEST_ACCOUNT_PRIVATE_KEY: '****', INITIAL_BALANCE: process.env.INITIAL_BALANCE, TEST_RPC_URL: process.env.TEST_RPC_URL, - TX_VERSION: process.env.TX_VERSION === 'v3' ? 'v3' : 'v2', + TX_VERSION: process.env.TX_VERSION, + SPEC_VERSION: process.env.SPEC_VERSION, }); console.table({ IS_DEVNET: process.env.IS_DEVNET, IS_RPC: process.env.IS_RPC, IS_TESTNET: process.env.IS_TESTNET, + 'Rpc node spec version': process.env.RPC_SPEC_VERSION, + 'Rpc node full spec v.': process.env.RPC_FULL_SPEC_VERSION, }); console.log('Global Test Environment is Ready'); @@ -129,6 +146,9 @@ class StrategyResolver { this.verifyAccountData(true); if (!this.hasAllAccountEnvs) console.error('Test Setup Environment is NOT Ready'); + this.defineTestTransactionVersion(); + await this.getSpecVersion(); + this.logConfigInfo(); } } diff --git a/__tests__/contract.test.ts b/__tests__/contract.test.ts index a01841402..019ffea56 100644 --- a/__tests__/contract.test.ts +++ b/__tests__/contract.test.ts @@ -1,8 +1,10 @@ import { + Account, BigNumberish, Contract, ContractFactory, ParsedEvents, + ProviderInterface, RawArgs, SuccessfulTransactionReceiptResponse, json, @@ -15,18 +17,23 @@ import { getSelectorFromName } from '../src/utils/hash'; import { hexToDecimalString, toBigInt } from '../src/utils/num'; import { encodeShortString } from '../src/utils/shortString'; import { uint256ToBN } from '../src/utils/uint256'; -import { contracts, describeIfDevnet, getTestAccount, getTestProvider } from './config/fixtures'; +import { contracts, createTestProvider, describeIfDevnet, getTestAccount } from './config/fixtures'; import { initializeMatcher } from './config/schema'; describe('contract module', () => { let erc20Address: string; - const provider = getTestProvider(); + let provider: ProviderInterface; + let account: Account; const wallet = stark.randomAddress(); - const account = getTestAccount(provider); const constructorCalldata = [encodeShortString('Token'), encodeShortString('ERC20'), wallet]; const classHash = '0x54328a1075b8820eb43caf0caa233923148c983742402dcfc38541dd843d01a'; initializeMatcher(expect); + beforeAll(async () => { + provider = await createTestProvider(); + account = getTestAccount(provider); + }); + describe('class Contract {}', () => { describe('Basic Interaction', () => { let erc20Contract: Contract; @@ -303,12 +310,15 @@ describe('contract module', () => { describe('Complex interaction', () => { let erc20Echo20Contract: Contract; - const provider = getTestProvider(); - const account = getTestAccount(provider); + let provider: ProviderInterface; + let account: Account; const classHash = '0x011ab8626b891bcb29f7cc36907af7670d6fb8a0528c7944330729d8f01e9ea3'; let factory: ContractFactory; beforeAll(async () => { + provider = await createTestProvider(); + account = getTestAccount(provider); + factory = new ContractFactory({ compiledContract: contracts.Erc20Echo, classHash, account }); erc20Echo20Contract = await factory.deploy( 'Token', @@ -803,9 +813,12 @@ describe('Complex interaction', () => { test('invoke compiled data', async () => { const result = await erc20Echo20Contract.iecho(CallData.compile(request)); const transaction = await provider.waitForTransaction(result.transaction_hash); - expect((transaction as SuccessfulTransactionReceiptResponse).execution_status).toBeDefined(); + expect( + (transaction as unknown as SuccessfulTransactionReceiptResponse).execution_status + ).toBeDefined(); }); + // TODO: fix all 'as unknown' hotfixes // skip on live for performance test('invoke unit test arguments', async () => { const calldata = CallData.compile(request); @@ -813,19 +826,27 @@ describe('Complex interaction', () => { const result = await erc20Echo20Contract.iecho(calldata); const transaction = await provider.waitForTransaction(result.transaction_hash); - expect((transaction as SuccessfulTransactionReceiptResponse).execution_status).toBeDefined(); + expect( + (transaction as unknown as SuccessfulTransactionReceiptResponse).execution_status + ).toBeDefined(); const result1 = await erc20Echo20Contract.iecho(...args); const transaction1 = await provider.waitForTransaction(result1.transaction_hash); - expect((transaction1 as SuccessfulTransactionReceiptResponse).execution_status).toBeDefined(); + expect( + (transaction1 as unknown as SuccessfulTransactionReceiptResponse).execution_status + ).toBeDefined(); const result2 = await erc20Echo20Contract.invoke('iecho', calldata); const transaction2 = await provider.waitForTransaction(result2.transaction_hash); - expect((transaction2 as SuccessfulTransactionReceiptResponse).execution_status).toBeDefined(); + expect( + (transaction2 as unknown as SuccessfulTransactionReceiptResponse).execution_status + ).toBeDefined(); const result3 = await erc20Echo20Contract.invoke('iecho', args); const transaction3 = await provider.waitForTransaction(result3.transaction_hash); - expect((transaction3 as SuccessfulTransactionReceiptResponse).execution_status).toBeDefined(); + expect( + (transaction3 as unknown as SuccessfulTransactionReceiptResponse).execution_status + ).toBeDefined(); }); describe('speedup live tests', () => { @@ -880,7 +901,7 @@ describe('Complex interaction', () => { ); const transaction = await provider.waitForTransaction(result.transaction_hash); expect( - (transaction as SuccessfulTransactionReceiptResponse).execution_status + (transaction as unknown as SuccessfulTransactionReceiptResponse).execution_status ).toBeDefined(); }); }); diff --git a/__tests__/defaultProvider.test.ts b/__tests__/defaultProvider.test.ts index 2a3310936..47a0661bc 100644 --- a/__tests__/defaultProvider.test.ts +++ b/__tests__/defaultProvider.test.ts @@ -1,38 +1,42 @@ import { + Account, BlockNumber, CallData, GetBlockResponse, LibraryError, Provider, provider, + ProviderInterface, stark, } from '../src'; import { toBigInt } from '../src/utils/num'; import { encodeShortString } from '../src/utils/shortString'; import { contracts, + createTestProvider, erc20ClassHash, getTestAccount, - getTestProvider, wrongClassHash, } from './config/fixtures'; import { initializeMatcher } from './config/schema'; const { isPendingStateUpdate } = provider; -const testProvider = new Provider(getTestProvider()); - describe('defaultProvider', () => { + let testProvider: ProviderInterface; + let account: Account; let exampleTransactionHash: string; let erc20ContractAddress: string; let exampleBlock: GetBlockResponse; let exampleBlockNumber: BlockNumber; let exampleBlockHash: string; const wallet = stark.randomAddress(); - const account = getTestAccount(testProvider); initializeMatcher(expect); beforeAll(async () => { + testProvider = new Provider(await createTestProvider()); + account = getTestAccount(testProvider); + expect(testProvider).toBeInstanceOf(Provider); const { deploy } = await account.declareAndDeploy({ diff --git a/__tests__/rpcChannel.test.ts b/__tests__/rpcChannel.test.ts index 471486ac8..9574f1449 100644 --- a/__tests__/rpcChannel.test.ts +++ b/__tests__/rpcChannel.test.ts @@ -1,19 +1,22 @@ -import { LibraryError, RPC06, RPC07, RpcError } from '../src'; -import { createBlockForDevnet, getTestProvider } from './config/fixtures'; +import { LibraryError, RPC08, RPC07, RpcError } from '../src'; +import { createBlockForDevnet, createTestProvider } from './config/fixtures'; import { initializeMatcher } from './config/schema'; describe('RpcChannel', () => { - const { nodeUrl } = getTestProvider(false).channel; - const channel07 = new RPC07.RpcChannel({ nodeUrl }); + let nodeUrl: string; + let channel07: RPC07.RpcChannel; initializeMatcher(expect); beforeAll(async () => { + nodeUrl = (await createTestProvider(false)).channel.nodeUrl; + channel07 = new RPC07.RpcChannel({ nodeUrl }); + await createBlockForDevnet(); }); test('baseFetch override', async () => { const baseFetch = jest.fn(); - const fetchChannel06 = new RPC06.RpcChannel({ nodeUrl, baseFetch }); + const fetchChannel06 = new RPC08.RpcChannel({ nodeUrl, baseFetch }); const fetchChannel07 = new RPC07.RpcChannel({ nodeUrl, baseFetch }); (fetchChannel06.fetch as any)(); expect(baseFetch).toHaveBeenCalledTimes(1); diff --git a/__tests__/rpcProvider.test.ts b/__tests__/rpcProvider.test.ts index c33fb3eb0..be6a3b33d 100644 --- a/__tests__/rpcProvider.test.ts +++ b/__tests__/rpcProvider.test.ts @@ -6,8 +6,8 @@ import { CallData, Contract, FeeEstimate, + ProviderInterface, RPC, - RPC06, RPCResponseParser, ReceiptTx, RpcProvider, @@ -22,32 +22,47 @@ import { toBigInt, toHexString } from '../src/utils/num'; import { contracts, createBlockForDevnet, + createTestProvider, describeIfDevnet, describeIfNotDevnet, describeIfRpc, describeIfTestnet, devnetETHtokenAddress, getTestAccount, - getTestProvider, waitNextBlock, } from './config/fixtures'; import { initializeMatcher } from './config/schema'; import { isBoolean } from '../src/utils/typed'; +import { isVersion } from '../src/utils/provider'; describeIfRpc('RPCProvider', () => { - const rpcProvider = getTestProvider(false); - const provider = getTestProvider(); - const account = getTestAccount(provider); + let rpcProvider: RpcProvider; + let provider: ProviderInterface; + let account: Account; let accountPublicKey: string; initializeMatcher(expect); beforeAll(async () => { + rpcProvider = await createTestProvider(false); + provider = await createTestProvider(); + account = getTestAccount(provider); + expect(account).toBeInstanceOf(Account); const accountKeyPair = utils.randomPrivateKey(); accountPublicKey = getStarkKey(accountKeyPair); await createBlockForDevnet(); }); + test('detect spec version with create', async () => { + const providerTest = await RpcProvider.create({ nodeUrl: process.env.TEST_RPC_URL }); + const { channel } = providerTest; + expect(channel).toBeDefined(); + const rawResult = await channel.fetch('starknet_specVersion'); + const j = await rawResult.json(); + expect(channel.readSpecVersion()).toBeDefined(); + expect(isVersion(j.result, await channel.getSpecVersion())).toBeTruthy(); + }); + test('baseFetch override', async () => { const { nodeUrl } = rpcProvider.channel; const baseFetch = jest.fn(); @@ -115,8 +130,12 @@ describeIfRpc('RPCProvider', () => { const p = new RpcProvider({ nodeUrl: provider.channel.nodeUrl, feeMarginPercentage: { - l1BoundMaxAmount: 0, - l1BoundMaxPricePerUnit: 0, + bounds: { + l1_gas: { + max_amount: 0, + max_price_per_unit: 0, + }, + }, maxFee: 0, }, }); @@ -199,13 +218,13 @@ describeIfRpc('RPCProvider', () => { describe('waitForTransaction', () => { const receipt = {}; - const transactionStatusSpy = jest.spyOn(rpcProvider.channel as any, 'getTransactionStatus'); - const transactionReceiptSpy = jest.spyOn(rpcProvider.channel as any, 'getTransactionReceipt'); + let transactionStatusSpy: any; + let transactionReceiptSpy: any; const generateOptions = (o: waitForTransactionOptions) => ({ retryInterval: 10, ...o }); const generateTransactionStatus = ( - finality_status: RPC.SPEC.TXN_STATUS, - execution_status?: RPC.SPEC.TXN_EXECUTION_STATUS + finality_status: RPC.TXN_STATUS, + execution_status?: RPC.TXN_EXECUTION_STATUS ): RPC.TransactionStatus => ({ finality_status, execution_status, @@ -217,6 +236,9 @@ describeIfRpc('RPCProvider', () => { }; beforeAll(() => { + transactionStatusSpy = jest.spyOn(rpcProvider.channel as any, 'getTransactionStatus'); + transactionReceiptSpy = jest.spyOn(rpcProvider.channel as any, 'getTransactionReceipt'); + transactionStatusSpy.mockResolvedValue(null); transactionReceiptSpy.mockResolvedValue(receipt); }); @@ -284,13 +306,7 @@ describeIfRpc('RPCProvider', () => { expect(blockResponse).toHaveProperty('transactions'); }); - test('getBlockWithReceipts - 0.6 RpcChannel', async () => { - const channel = new RPC06.RpcChannel({ nodeUrl: rpcProvider.channel.nodeUrl }); - const p = new RpcProvider({ channel } as any); - await expect(p.getBlockWithReceipts(latestBlock.block_number)).rejects.toThrow(/Unsupported/); - }); - - test('getBlockWithReceipts - 0.7 RpcChannel', async () => { + test('getBlockWithReceipts - 0.v RpcChannel', async () => { const blockResponse = await rpcProvider.getBlockWithReceipts(latestBlock.block_number); expect(blockResponse).toMatchSchemaRef('BlockWithTxReceipts'); }); @@ -445,7 +461,11 @@ describeIfRpc('RPCProvider', () => { }); describeIfTestnet('RPCProvider', () => { - const provider = getTestProvider(); + let provider: ProviderInterface; + + beforeEach(async () => { + provider = await createTestProvider(); + }); test('getL1MessageHash', async () => { const l2TransactionHash = '0x28dfc05eb4f261b37ddad451ff22f1d08d4e3c24dc646af0ec69fa20e096819'; @@ -464,6 +484,7 @@ describeIfNotDevnet('waitForBlock', () => { const providerStandard = new RpcProvider({ nodeUrl: process.env.TEST_RPC_URL }); const providerFastTimeOut = new RpcProvider({ nodeUrl: process.env.TEST_RPC_URL, retries: 1 }); let block: number; + beforeEach(async () => { block = await providerStandard.getBlockNumber(); }); @@ -494,8 +515,13 @@ describeIfNotDevnet('waitForBlock', () => { }); describe('EIP712 verification', () => { - const rpcProvider = getTestProvider(false); - const account = getTestAccount(rpcProvider); + let rpcProvider: RpcProvider; + let account: Account; + + beforeEach(async () => { + rpcProvider = await createTestProvider(false); + account = getTestAccount(rpcProvider); + }); test('sign and verify message', async () => { const signature = await account.signMessage(typedDataExample); diff --git a/__tests__/transactionReceipt.test.ts b/__tests__/transactionReceipt.test.ts index 36159adbd..603ab8f17 100644 --- a/__tests__/transactionReceipt.test.ts +++ b/__tests__/transactionReceipt.test.ts @@ -5,17 +5,23 @@ import { RevertedTransactionReceiptResponse, SuccessfulTransactionReceiptResponse, TransactionExecutionStatus, + ProviderInterface, + Account, } from '../src'; -import { contracts, getTestAccount, getTestProvider } from './config/fixtures'; +import { contracts, createTestProvider, getTestAccount } from './config/fixtures'; -describe('Transaction receipt utility', () => { - const provider = getTestProvider(); - const account = getTestAccount(provider); +// TODO: add RPC 0.7 V3, RPC 0.8 V3 +describe('Transaction receipt utility - RPC 0.7 - V2', () => { + let provider: ProviderInterface; + let account: Account; let dd: DeclareDeployUDCResponse; let contract: Contract; beforeAll(async () => { + provider = await createTestProvider(); + account = getTestAccount(provider); + dd = await account.declareAndDeploy({ contract: contracts.TestReject.sierra, casm: contracts.TestReject.casm, @@ -32,7 +38,6 @@ describe('Transaction receipt utility', () => { expect(txR.value).toHaveProperty('execution_status', TransactionExecutionStatus.SUCCEEDED); expect(txR.statusReceipt).toBe('success'); expect(txR.isSuccess()).toBe(true); - expect(txR.isRejected()).toBe(false); expect(txR.isReverted()).toBe(false); expect(txR.isError()).toBe(false); let isSuccess: boolean = false; @@ -54,7 +59,6 @@ describe('Transaction receipt utility', () => { expect(txR.value).toHaveProperty('execution_status', TransactionExecutionStatus.REVERTED); expect(txR.statusReceipt).toBe('reverted'); expect(txR.isSuccess()).toBe(false); - expect(txR.isRejected()).toBe(false); expect(txR.isReverted()).toBe(true); expect(txR.isError()).toBe(false); let isReverted: boolean = false; @@ -78,7 +82,6 @@ describe('Transaction receipt utility', () => { expect(txR.value).toHaveProperty('execution_status', TransactionExecutionStatus.SUCCEEDED); expect(txR.statusReceipt).toBe('success'); expect(txR.isSuccess()).toBe(true); - expect(txR.isRejected()).toBe(false); expect(txR.isReverted()).toBe(false); expect(txR.isError()).toBe(false); let isSuccess: boolean = false; diff --git a/__tests__/utils/batch.test.ts b/__tests__/utils/batch.test.ts index a60ff862a..8aeee4d18 100644 --- a/__tests__/utils/batch.test.ts +++ b/__tests__/utils/batch.test.ts @@ -1,19 +1,23 @@ import fetch from '../../src/utils/fetchPonyfill'; import { BatchClient } from '../../src/utils/batch'; -import { createBlockForDevnet, getTestProvider } from '../config/fixtures'; +import { createBlockForDevnet, createTestProvider } from '../config/fixtures'; import { initializeMatcher } from '../config/schema'; +import { ProviderInterface } from '../../src'; describe('Batch Client', () => { - const provider = getTestProvider(false); - - const batchClient = new BatchClient({ - nodeUrl: provider.channel.nodeUrl, - headers: provider.channel.headers, - interval: 0, - baseFetch: fetch, - }); - initializeMatcher(expect); + let provider: ProviderInterface; + let batchClient: BatchClient; + + beforeAll(async () => { + provider = await createTestProvider(false); + batchClient = new BatchClient({ + nodeUrl: provider.channel.nodeUrl, + headers: provider.channel.headers, + interval: 0, + baseFetch: fetch, + }); + }); test('should batch two requests', async () => { await createBlockForDevnet(); @@ -33,7 +37,7 @@ describe('Batch Client', () => { }); test('batch request using Provider', async () => { - const myBatchProvider = getTestProvider(false, { batch: 0 }); + const myBatchProvider = await createTestProvider(false, { batch: 0 }); const sendBatchSpy = jest.spyOn((myBatchProvider.channel as any).batchClient, 'sendBatch'); diff --git a/__tests__/utils/errors.test.ts b/__tests__/utils/errors.test.ts index fd50aff21..be1477527 100644 --- a/__tests__/utils/errors.test.ts +++ b/__tests__/utils/errors.test.ts @@ -2,7 +2,8 @@ import { RPC, RpcError } from '../../src'; describe('Error utility tests', () => { test('RpcError', () => { - const baseError: RPC.Errors.UNEXPECTED_ERROR = { + // TODO: @penovicp types 0.8 exporta u top level sve 0.7 exporta po komponentama, neznan jeli treba minjat test i mod da ocukuje oba tipa + const baseError: RPC.RPCSPEC08.UNEXPECTED_ERROR = { code: 63, message: 'An unexpected error occurred', data: 'data', diff --git a/__tests__/utils/ethSigner.test.ts b/__tests__/utils/ethSigner.test.ts index a806c14aa..c7d28a46b 100644 --- a/__tests__/utils/ethSigner.test.ts +++ b/__tests__/utils/ethSigner.test.ts @@ -5,6 +5,7 @@ import { Contract, EthSigner, Provider, + ProviderInterface, addAddressPadding, cairo, encode, @@ -21,10 +22,10 @@ import { validateAndParseEthAddress } from '../../src/utils/eth'; import { ETransactionVersion } from '../../src/types/api'; import { contracts, + createTestProvider, describeIfDevnet, devnetETHtokenAddress, getTestAccount, - getTestProvider, } from '../config/fixtures'; describe('Ethereum signer', () => { @@ -63,11 +64,14 @@ describe('Ethereum signer', () => { }); describe('cairo v2.5.3 new secp256k1 type', () => { - const provider = new Provider(getTestProvider()); + let provider: ProviderInterface; + let account: Account; let ethPubKContract: Contract; - const account = getTestAccount(provider); beforeAll(async () => { + provider = new Provider(await createTestProvider()); + account = getTestAccount(provider); + const { deploy } = await account.declareAndDeploy({ contract: contracts.EthPubk.sierra, casm: contracts.EthPubk.casm, @@ -97,10 +101,14 @@ describe('Ethereum signer', () => { describeIfDevnet('ETH account tx V2', () => { // devnet only because estimateFee in Sepolia v0.13.1 are producing widely different numbers. - const provider = new Provider(getTestProvider()); - const account = getTestAccount(provider); + let provider: ProviderInterface; + let account: Account; let ethAccount: Account; + beforeAll(async () => { + provider = new Provider(await createTestProvider()); + account = getTestAccount(provider); + const { transaction_hash: declTH, class_hash: decClassHash } = await account.declareIfNot({ contract: contracts.EthAccount.sierra, casm: contracts.EthAccount.casm, @@ -126,7 +134,13 @@ describe('Ethereum signer', () => { 0 ); - ethAccount = new Account(provider, contractETHAccountAddress, ethSigner); + ethAccount = new Account( + provider, + contractETHAccountAddress, + ethSigner, + undefined, + ETransactionVersion.V2 + ); const deployPayload = { classHash: decClassHash, constructorCalldata: accountETHconstructorCalldata, @@ -162,7 +176,8 @@ describe('Ethereum signer', () => { ); const txR = await provider.waitForTransaction(respTransfer.transaction_hash); if (txR.isSuccess()) { - expect(txR.execution_status).toBe('SUCCEEDED'); + // TODO: @PhilippeR26 Why this is not working, fix 'as any' hotfix + expect((txR as any).execution_status).toBe('SUCCEEDED'); } else { fail('txR not success'); } @@ -187,12 +202,16 @@ describe('Ethereum signer', () => { describeIfDevnet('ETH account tx V3', () => { // devnet only because estimateFee in Sepolia v0.13.1 are producing widely different numbers. - const provider = new Provider(getTestProvider()); - const account = getTestAccount(provider); + let provider: Provider; + let account: Account; + let ethAccount: Account; const devnetSTRKtokenAddress = '0x04718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d'; - let ethAccount: Account; + beforeAll(async () => { + provider = new Provider(await createTestProvider()); + account = getTestAccount(provider); + const { transaction_hash: declTH, class_hash: decClassHash } = await account.declareIfNot({ contract: contracts.EthAccount.sierra, casm: contracts.EthAccount.casm, @@ -282,7 +301,7 @@ describe('Ethereum signer', () => { const txR = await provider.waitForTransaction(respTransfer.transaction_hash); if (txR.isSuccess()) { - expect(txR.execution_status).toBe('SUCCEEDED'); + expect((txR as any).execution_status).toBe('SUCCEEDED'); } else { fail('txR not success'); } diff --git a/__tests__/utils/events.test.ts b/__tests__/utils/events.test.ts index e3d61824c..7088d11d0 100644 --- a/__tests__/utils/events.test.ts +++ b/__tests__/utils/events.test.ts @@ -21,12 +21,15 @@ const getBaseTxReceiptData = (): InvokeTransactionReceiptResponse => ({ block_hash: '0xdfc9b788478b2a2b9bcba19ab7d86996bcc45c4f8a865435469334e9077b24', block_number: 584, execution_resources: { - steps: 9490, - memory_holes: 143, - range_check_builtin_applications: 198, - pedersen_builtin_applications: 34, - ec_op_builtin_applications: 3, - data_availability: { l1_gas: 0, l1_data_gas: 544 }, + // steps: 9490, + // memory_holes: 143, + // range_check_builtin_applications: 198, + // pedersen_builtin_applications: 34, + // ec_op_builtin_applications: 3, + // data_availability: { l1_gas: 0, l1_data_gas: 544 }, + l1_gas: 0, + l1_data_gas: 544, + l2_gas: 0, }, }); diff --git a/__tests__/utils/logger.test.ts b/__tests__/utils/logger.test.ts index 0370b31a3..73f7941d7 100644 --- a/__tests__/utils/logger.test.ts +++ b/__tests__/utils/logger.test.ts @@ -1,12 +1,29 @@ /* eslint-disable no-console */ -import { logger, LogLevel } from '../../src'; +import { LogLevel } from '../../src'; -// Mock the config module -const mockConfigStore: { logLevel: LogLevel; [key: string]: any } = { - logLevel: 'INFO', +// Mock console methods first +const mockConsole = { + debug: jest.fn(), + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + log: jest.fn(), +}; + +global.console = mockConsole as any; + +// Create the mock config store with an index signature +const mockConfigStore: { + logLevel: LogLevel; + rpcVersion: string; + [key: string]: any; // Add this index signature to allow any string key +} = { + logLevel: 'INFO' as LogLevel, + rpcVersion: '0.8', }; -jest.mock('../../src/global/config', () => ({ +// Use doMock instead of mock (doesn't get hoisted) +jest.doMock('../../src/global/config', () => ({ config: { get: jest.fn().mockImplementation((key: string, defaultValue?: any) => { return mockConfigStore[key] ?? defaultValue; @@ -17,16 +34,8 @@ jest.mock('../../src/global/config', () => ({ }, })); -// Mock console methods -const mockConsole = { - debug: jest.fn(), - info: jest.fn(), - warn: jest.fn(), - error: jest.fn(), - log: jest.fn(), -}; - -global.console = mockConsole as any; +// Import logger AFTER the mock is set up +const { logger } = require('../../src'); describe('Logger', () => { // const gLog = jest.spyOn(global.console, 'log'); diff --git a/__tests__/utils/stark.test.ts b/__tests__/utils/stark.test.ts index a44e8f28a..fb55236d8 100644 --- a/__tests__/utils/stark.test.ts +++ b/__tests__/utils/stark.test.ts @@ -1,6 +1,5 @@ -import { CallData, RawArgs, UniversalDetails, json, stark } from '../../src'; +import { CallData, RawArgs, UniversalDetails, json, stark, FeeEstimate } from '../../src'; import { EDataAvailabilityMode } from '../../src/types/api'; -import { FeeEstimate } from '../../src/types/provider'; import { toBigInt, toHex } from '../../src/utils/num'; import { contracts } from '../config/fixtures'; @@ -71,11 +70,12 @@ describe('stark', () => { }); test('estimateFeeToBounds', () => { - const estimateFeeResponse: FeeEstimate = { + // TODO: How is this response possibe when data_gas_consumed, data_gas_price are not optional response parameters + const estimateFeeResponse /* : FeeEstimate */ = { gas_consumed: '100', gas_price: '10', overall_fee: '1000', - unit: 'FRI', + unit: 'FRI' as const, }; const estimateFeeResponse07: FeeEstimate = { ...estimateFeeResponse, @@ -83,10 +83,11 @@ describe('stark', () => { data_gas_price: '10', overall_fee: '2000', }; - expect(stark.estimateFeeToBounds(estimateFeeResponse)).toStrictEqual({ + // TODO: look like this was RPC 0.6 test, instead add RPC 0.8 Tests + /* expect(stark.estimateFeeToBounds(estimateFeeResponse)).toStrictEqual({ l2_gas: { max_amount: '0x0', max_price_per_unit: '0x0' }, l1_gas: { max_amount: '0x96', max_price_per_unit: '0xf' }, - }); + }); */ expect(stark.estimateFeeToBounds(estimateFeeResponse07)).toStrictEqual({ l2_gas: { max_amount: '0x0', max_price_per_unit: '0x0' }, l1_gas: { max_amount: '0x12c', max_price_per_unit: '0xf' }, diff --git a/__tests__/utils/transactionHash.test.ts b/__tests__/utils/transactionHash.test.ts index 52add1758..c3bfbe0bc 100644 --- a/__tests__/utils/transactionHash.test.ts +++ b/__tests__/utils/transactionHash.test.ts @@ -1,5 +1,5 @@ import { constants, hash, shortString, types, v2hash, v3hash } from '../../src'; -import { ResourceBounds } from '../../src/types/api'; +import { ResourceBounds } from '../../src/provider/types/spec.type'; describe('TxV2 Hash Tests', () => { describe('calculateTransactionHashCommon()', () => { diff --git a/package-lock.json b/package-lock.json index 10a0ba330..1bd5ced3d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,11 +14,12 @@ "@scure/base": "1.2.1", "@scure/starknet": "1.1.0", "abi-wan-kanabi": "^2.2.3", - "fetch-cookie": "^3.0.0", - "isomorphic-fetch": "^3.0.0", + "fetch-cookie": "~3.0.0", + "isomorphic-fetch": "~3.0.0", "lossless-json": "^4.0.1", "pako": "^2.0.4", "starknet-types-07": "npm:@starknet-io/types-js@^0.7.10", + "starknet-types-08": "npm:@starknet-io/types-js@0.8.0-beta.10", "ts-mixer": "^6.0.3" }, "devDependencies": { @@ -2125,74 +2126,6 @@ "node": ">=v18" } }, - "node_modules/@esbuild/aix-ppc64": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.24.0.tgz", - "integrity": "sha512-WtKdFM7ls47zkKHFVzMz8opM7LkcsIp9amDUBIAWirg70RM71WRSjdILPsY5Uv1D42ZpUfaPILDlfactHgsRkw==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "aix" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.24.0.tgz", - "integrity": "sha512-arAtTPo76fJ/ICkXWetLCc9EwEHKaeya4vMrReVlEIUCAUncH7M4bhMQ+M9Vf+FFOZJdTNMXNBrWwW+OXWpSew==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm64": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.24.0.tgz", - "integrity": "sha512-Vsm497xFM7tTIPYK9bNTYJyF/lsP590Qc1WxJdlB6ljCbdZKU9SY8i7+Iin4kyhV/KV5J2rOKsBQbB77Ab7L/w==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-x64": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.24.0.tgz", - "integrity": "sha512-t8GrvnFkiIY7pa7mMgJd7p8p8qqYIz1NYiAoKc75Zyv73L3DZW++oYMSHPRarcotTKuSs6m3hTOa5CKHaS02TQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, "node_modules/@esbuild/darwin-arm64": { "version": "0.24.0", "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.24.0.tgz", @@ -2210,329 +2143,6 @@ "node": ">=18" } }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.24.0.tgz", - "integrity": "sha512-rgtz6flkVkh58od4PwTRqxbKH9cOjaXCMZgWD905JOzjFKW+7EiUObfd/Kav+A6Gyud6WZk9w+xu6QLytdi2OA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.24.0.tgz", - "integrity": "sha512-6Mtdq5nHggwfDNLAHkPlyLBpE5L6hwsuXZX8XNmHno9JuL2+bg2BX5tRkwjyfn6sKbxZTq68suOjgWqCicvPXA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.24.0.tgz", - "integrity": "sha512-D3H+xh3/zphoX8ck4S2RxKR6gHlHDXXzOf6f/9dbFt/NRBDIE33+cVa49Kil4WUjxMGW0ZIYBYtaGCa2+OsQwQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.24.0.tgz", - "integrity": "sha512-gJKIi2IjRo5G6Glxb8d3DzYXlxdEj2NlkixPsqePSZMhLudqPhtZ4BUrpIuTjJYXxvF9njql+vRjB2oaC9XpBw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm64": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.24.0.tgz", - "integrity": "sha512-TDijPXTOeE3eaMkRYpcy3LarIg13dS9wWHRdwYRnzlwlA370rNdZqbcp0WTyyV/k2zSxfko52+C7jU5F9Tfj1g==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.24.0.tgz", - "integrity": "sha512-K40ip1LAcA0byL05TbCQ4yJ4swvnbzHscRmUilrmP9Am7//0UjPreh4lpYzvThT2Quw66MhjG//20mrufm40mA==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.24.0.tgz", - "integrity": "sha512-0mswrYP/9ai+CU0BzBfPMZ8RVm3RGAN/lmOMgW4aFUSOQBjA31UP8Mr6DDhWSuMwj7jaWOT0p0WoZ6jeHhrD7g==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.24.0.tgz", - "integrity": "sha512-hIKvXm0/3w/5+RDtCJeXqMZGkI2s4oMUGj3/jM0QzhgIASWrGO5/RlzAzm5nNh/awHE0A19h/CvHQe6FaBNrRA==", - "cpu": [ - "mips64el" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.24.0.tgz", - "integrity": "sha512-HcZh5BNq0aC52UoocJxaKORfFODWXZxtBaaZNuN3PUX3MoDsChsZqopzi5UupRhPHSEHotoiptqikjN/B77mYQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.24.0.tgz", - "integrity": "sha512-bEh7dMn/h3QxeR2KTy1DUszQjUrIHPZKyO6aN1X4BCnhfYhuQqedHaa5MxSQA/06j3GpiIlFGSsy1c7Gf9padw==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.24.0.tgz", - "integrity": "sha512-ZcQ6+qRkw1UcZGPyrCiHHkmBaj9SiCD8Oqd556HldP+QlpUIe2Wgn3ehQGVoPOvZvtHm8HPx+bH20c9pvbkX3g==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.24.0.tgz", - "integrity": "sha512-vbutsFqQ+foy3wSSbmjBXXIJ6PL3scghJoM8zCL142cGaZKAdCZHyf+Bpu/MmX9zT9Q0zFBVKb36Ma5Fzfa8xA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.24.0.tgz", - "integrity": "sha512-hjQ0R/ulkO8fCYFsG0FZoH+pWgTTDreqpqY7UnQntnaKv95uP5iW3+dChxnx7C3trQQU40S+OgWhUVwCjVFLvg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-arm64": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.24.0.tgz", - "integrity": "sha512-MD9uzzkPQbYehwcN583yx3Tu5M8EIoTD+tUgKF982WYL9Pf5rKy9ltgD0eUgs8pvKnmizxjXZyLt0z6DC3rRXg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.24.0.tgz", - "integrity": "sha512-4ir0aY1NGUhIC1hdoCzr1+5b43mw99uNwVzhIq1OY3QcEwPDO3B7WNXBzaKY5Nsf1+N11i1eOfFcq+D/gOS15Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.24.0.tgz", - "integrity": "sha512-jVzdzsbM5xrotH+W5f1s+JtUy1UWgjU0Cf4wMvffTB8m6wP5/kx0KiaLHlbJO+dMgtxKV8RQ/JvtlFcdZ1zCPA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.24.0.tgz", - "integrity": "sha512-iKc8GAslzRpBytO2/aN3d2yb2z8XTVfNV0PjGlCxKo5SgWmNXx82I/Q3aG1tFfS+A2igVCY97TJ8tnYwpUWLCA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.24.0.tgz", - "integrity": "sha512-vQW36KZolfIudCcTnaTpmLQ24Ha1RjygBo39/aLkM2kmjkWmZGEJ5Gn9l5/7tzXA42QGIoWbICfg6KLLkIw6yw==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-x64": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.24.0.tgz", - "integrity": "sha512-7IAFPrjSQIJrGsK6flwg7NFmwBoSTyF3rl7If0hNUFQU4ilTsEPL6GuMuU9BfIWVVGuRnuIidkSMC+c0Otu8IA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, "node_modules/@eslint-community/eslint-utils": { "version": "4.4.1", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.1.tgz", @@ -3873,34 +3483,6 @@ "node": ">=12" } }, - "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.28.1.tgz", - "integrity": "sha512-2aZp8AES04KI2dy3Ss6/MDjXbwBzj+i0GqKtWXgw2/Ma6E4jJvujryO6gJAghIRVz7Vwr9Gtl/8na3nDUKpraQ==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ] - }, - "node_modules/@rollup/rollup-android-arm64": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.28.1.tgz", - "integrity": "sha512-EbkK285O+1YMrg57xVA+Dp0tDBRB93/BZKph9XhMjezf6F4TpYjaUSuPt5J0fZXlSag0LmZAsTmdGGqPp4pQFA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ] - }, "node_modules/@rollup/rollup-darwin-arm64": { "version": "4.28.1", "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.28.1.tgz", @@ -3915,230 +3497,6 @@ "darwin" ] }, - "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.28.1.tgz", - "integrity": "sha512-WsvbOunsUk0wccO/TV4o7IKgloJ942hVFK1CLatwv6TJspcCZb9umQkPdvB7FihmdxgaKR5JyxDjWpCOp4uZlQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@rollup/rollup-freebsd-arm64": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.28.1.tgz", - "integrity": "sha512-HTDPdY1caUcU4qK23FeeGxCdJF64cKkqajU0iBnTVxS8F7H/7BewvYoG+va1KPSL63kQ1PGNyiwKOfReavzvNA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ] - }, - "node_modules/@rollup/rollup-freebsd-x64": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.28.1.tgz", - "integrity": "sha512-m/uYasxkUevcFTeRSM9TeLyPe2QDuqtjkeoTpP9SW0XxUWfcYrGDMkO/m2tTw+4NMAF9P2fU3Mw4ahNvo7QmsQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ] - }, - "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.28.1.tgz", - "integrity": "sha512-QAg11ZIt6mcmzpNE6JZBpKfJaKkqTm1A9+y9O+frdZJEuhQxiugM05gnCWiANHj4RmbgeVJpTdmKRmH/a+0QbA==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.28.1.tgz", - "integrity": "sha512-dRP9PEBfolq1dmMcFqbEPSd9VlRuVWEGSmbxVEfiq2cs2jlZAl0YNxFzAQS2OrQmsLBLAATDMb3Z6MFv5vOcXg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.28.1.tgz", - "integrity": "sha512-uGr8khxO+CKT4XU8ZUH1TTEUtlktK6Kgtv0+6bIFSeiSlnGJHG1tSFSjm41uQ9sAO/5ULx9mWOz70jYLyv1QkA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.28.1.tgz", - "integrity": "sha512-QF54q8MYGAqMLrX2t7tNpi01nvq5RI59UBNx+3+37zoKX5KViPo/gk2QLhsuqok05sSCRluj0D00LzCwBikb0A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-loongarch64-gnu": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loongarch64-gnu/-/rollup-linux-loongarch64-gnu-4.28.1.tgz", - "integrity": "sha512-vPul4uodvWvLhRco2w0GcyZcdyBfpfDRgNKU+p35AWEbJ/HPs1tOUrkSueVbBS0RQHAf/A+nNtDpvw95PeVKOA==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-powerpc64le-gnu": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.28.1.tgz", - "integrity": "sha512-pTnTdBuC2+pt1Rmm2SV7JWRqzhYpEILML4PKODqLz+C7Ou2apEV52h19CR7es+u04KlqplggmN9sqZlekg3R1A==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.28.1.tgz", - "integrity": "sha512-vWXy1Nfg7TPBSuAncfInmAI/WZDd5vOklyLJDdIRKABcZWojNDY0NJwruY2AcnCLnRJKSaBgf/GiJfauu8cQZA==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.28.1.tgz", - "integrity": "sha512-/yqC2Y53oZjb0yz8PVuGOQQNOTwxcizudunl/tFs1aLvObTclTwZ0JhXF2XcPT/zuaymemCDSuuUPXJJyqeDOg==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.28.1.tgz", - "integrity": "sha512-fzgeABz7rrAlKYB0y2kSEiURrI0691CSL0+KXwKwhxvj92VULEDQLpBYLHpF49MSiPG4sq5CK3qHMnb9tlCjBw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.28.1.tgz", - "integrity": "sha512-xQTDVzSGiMlSshpJCtudbWyRfLaNiVPXt1WgdWTwWz9n0U12cI2ZVtWe/Jgwyv/6wjL7b66uu61Vg0POWVfz4g==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.28.1.tgz", - "integrity": "sha512-wSXmDRVupJstFP7elGMgv+2HqXelQhuNf+IS4V+nUpNVi/GUiBgDmfwD0UGN3pcAnWsgKG3I52wMOBnk1VHr/A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.28.1.tgz", - "integrity": "sha512-ZkyTJ/9vkgrE/Rk9vhMXhf8l9D+eAhbAVbsGsXKy2ohmJaWg0LPQLnIxRdRp/bKyr8tXuPlXhIoGlEB5XpJnGA==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.28.1.tgz", - "integrity": "sha512-ZvK2jBafvttJjoIdKm/Q/Bh7IJ1Ose9IBOwpOXcOvW3ikGTQGmKDgxTC6oCAzW6PynbkKP8+um1du81XJHZ0JA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, "node_modules/@rtsao/scc": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@rtsao/scc/-/scc-1.1.0.tgz", @@ -17835,6 +17193,12 @@ "integrity": "sha512-1VtCqX4AHWJlRRSYGSn+4X1mqolI1Tdq62IwzoU2vUuEE72S1OlEeGhpvd6XsdqXcfHmVzYfj8k1XtKBQqwo9w==", "license": "MIT" }, + "node_modules/starknet-types-08": { + "name": "@starknet-io/types-js", + "version": "0.8.0-beta.10", + "resolved": "https://registry.npmjs.org/@starknet-io/types-js/-/types-js-0.8.0-beta.10.tgz", + "integrity": "sha512-skLpHpBDG6kDdaZrnLE/gZBVY/3Y4F262eDASWM/XMa/zy+0pxLUsKi0rL71LipvwhkR1TtOpdmefIu2KOe96A==" + }, "node_modules/stream-combiner2": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/stream-combiner2/-/stream-combiner2-1.1.1.tgz", diff --git a/package.json b/package.json index 3c88d3245..7c15516fb 100644 --- a/package.json +++ b/package.json @@ -106,6 +106,7 @@ "lossless-json": "^4.0.1", "pako": "^2.0.4", "starknet-types-07": "npm:@starknet-io/types-js@^0.7.10", + "starknet-types-08": "npm:@starknet-io/types-js@0.8.0-beta.10", "ts-mixer": "^6.0.3" }, "lint-staged": { diff --git a/src/account/default.ts b/src/account/default.ts index 92a8ff1a5..9ac9fbdab 100644 --- a/src/account/default.ts +++ b/src/account/default.ts @@ -2,6 +2,7 @@ import { OutsideExecutionCallerAny, SNIP9_V1_INTERFACE_ID, SNIP9_V2_INTERFACE_ID, + SupportedTransactionVersion, UDC, ZERO, } from '../global/constants'; @@ -45,7 +46,11 @@ import { UniversalDeployerContractPayload, UniversalDetails, } from '../types'; -import { ETransactionVersion, ETransactionVersion3, type ResourceBounds } from '../types/api'; +import { + ETransactionVersion, + ETransactionVersion3, + ResourceBounds, +} from '../provider/types/spec.type'; import { OutsideExecutionVersion, type OutsideExecution, @@ -77,6 +82,7 @@ import { buildUDCCall, getExecuteCalldata } from '../utils/transaction'; import { getMessageHash } from '../utils/typedData'; import { AccountInterface } from './interface'; import { config } from '../global/config'; +import { logger } from '../global/logger'; export class Account extends Provider implements AccountInterface { public signer: SignerInterface; @@ -92,9 +98,7 @@ export class Account extends Provider implements AccountInterface { address: string, pkOrSigner: Uint8Array | string | SignerInterface, cairoVersion?: CairoVersion, - transactionVersion: typeof ETransactionVersion.V2 | typeof ETransactionVersion.V3 = config.get( - 'accountTxVersion' - ) + transactionVersion: SupportedTransactionVersion = config.get('transactionVersion') ) { super(providerOrOptions); this.address = address.toLowerCase(); @@ -107,6 +111,12 @@ export class Account extends Provider implements AccountInterface { this.cairoVersion = cairoVersion.toString() as CairoVersion; } this.transactionVersion = transactionVersion; + + logger.debug('Account setup', { + transactionVersion: this.transactionVersion, + cairoVersion: this.cairoVersion, + channel: this.channel.id, + }); } // provided version or contract based preferred transactionVersion @@ -171,7 +181,7 @@ export class Account extends Provider implements AccountInterface { const chainId = await this.getChainId(); const signerDetails: InvocationsSignerDetails = { - ...v3Details(details), + ...v3Details(details, await this.channel.getSpecVersion()), walletAddress: this.address, nonce, maxFee: ZERO, @@ -184,7 +194,7 @@ export class Account extends Provider implements AccountInterface { const invocation = await this.buildInvocation(transactions, signerDetails); return super.getInvokeEstimateFee( { ...invocation }, - { ...v3Details(details), version, nonce }, + { ...v3Details(details, await this.channel.getSpecVersion()), version, nonce }, blockIdentifier, details.skipValidate ); @@ -210,7 +220,7 @@ export class Account extends Provider implements AccountInterface { const chainId = await this.getChainId(); const declareContractTransaction = await this.buildDeclarePayload(payload, { - ...v3Details(details), + ...v3Details(details, await this.channel.getSpecVersion()), nonce, chainId, version, @@ -222,7 +232,7 @@ export class Account extends Provider implements AccountInterface { return super.getDeclareEstimateFee( declareContractTransaction, - { ...v3Details(details), version, nonce }, + { ...v3Details(details, await this.channel.getSpecVersion()), version, nonce }, blockIdentifier, details.skipValidate ); @@ -248,7 +258,7 @@ export class Account extends Provider implements AccountInterface { const payload = await this.buildAccountDeployPayload( { classHash, addressSalt, constructorCalldata, contractAddress }, { - ...v3Details(details), + ...v3Details(details, await this.channel.getSpecVersion()), nonce, chainId, version, @@ -261,7 +271,7 @@ export class Account extends Provider implements AccountInterface { return super.getDeployAccountEstimateFee( { ...payload }, - { ...v3Details(details), version, nonce }, + { ...v3Details(details, await this.channel.getSpecVersion()), version, nonce }, blockIdentifier, details.skipValidate ); @@ -282,7 +292,7 @@ export class Account extends Provider implements AccountInterface { if (!invocations.length) throw TypeError('Invocations should be non-empty array'); const { nonce, blockIdentifier, version, skipValidate } = details; const accountInvocations = await this.accountInvocationsFactory(invocations, { - ...v3Details(details), + ...v3Details(details, await this.channel.getSpecVersion()), versions: [ ETransactionVersion.F1, // non-sierra toTransactionVersion( @@ -308,7 +318,7 @@ export class Account extends Provider implements AccountInterface { if (!invocations.length) throw TypeError('Invocations should be non-empty array'); const { nonce, blockIdentifier, skipValidate = true, skipExecute, version } = details; const accountInvocations = await this.accountInvocationsFactory(invocations, { - ...v3Details(details), + ...v3Details(details, await this.channel.getSpecVersion()), versions: [ ETransactionVersion.V1, // non-sierra toTransactionVersion( @@ -362,7 +372,7 @@ export class Account extends Provider implements AccountInterface { const chainId = await this.getChainId(); const signerDetails: InvocationsSignerDetails = { - ...v3Details(details), + ...v3Details(details, await this.channel.getSpecVersion()), resourceBounds: estimate.resourceBounds, walletAddress: this.address, nonce, @@ -379,7 +389,7 @@ export class Account extends Provider implements AccountInterface { return this.invokeFunction( { contractAddress: this.address, calldata, signature }, { - ...v3Details(details), + ...v3Details(details, await this.channel.getSpecVersion()), resourceBounds: estimate.resourceBounds, nonce, maxFee: estimate.maxFee, @@ -436,7 +446,7 @@ export class Account extends Provider implements AccountInterface { ); const declareDetails: InvocationsSignerDetails = { - ...v3Details(details), + ...v3Details(details, await this.channel.getSpecVersion()), resourceBounds: estimate.resourceBounds, maxFee: estimate.maxFee, nonce: toBigInt(nonce ?? (await this.getNonce())), @@ -531,7 +541,7 @@ export class Account extends Provider implements AccountInterface { ); const signature = await this.signer.signDeployAccountTransaction({ - ...v3Details(details), + ...v3Details(details, await this.channel.getSpecVersion()), classHash, constructorCalldata: compiledCalldata, contractAddress, @@ -546,7 +556,7 @@ export class Account extends Provider implements AccountInterface { return this.deployAccountContract( { classHash, addressSalt, constructorCalldata, signature }, { - ...v3Details(details), + ...v3Details(details, await this.channel.getSpecVersion()), nonce, resourceBounds: estimate.resourceBounds, maxFee: estimate.maxFee, @@ -785,7 +795,11 @@ export class Account extends Provider implements AccountInterface { details: UniversalDetails ): Promise { let maxFee: BigNumberish = 0; - let resourceBounds: ResourceBounds = estimateFeeToBounds(ZERO); + let resourceBounds: ResourceBounds = estimateFeeToBounds( + ZERO, + undefined, + await this.channel.getSpecVersion() + ); if (version === ETransactionVersion.V3) { resourceBounds = @@ -827,7 +841,7 @@ export class Account extends Provider implements AccountInterface { overall_fee: ZERO, unit: 'FRI', suggestedMaxFee: ZERO, - resourceBounds: estimateFeeToBounds(ZERO), + resourceBounds: estimateFeeToBounds(ZERO, undefined, await this.channel.getSpecVersion()), data_gas_consumed: 0n, data_gas_price: 0n, }; @@ -842,7 +856,7 @@ export class Account extends Provider implements AccountInterface { const signature = !details.skipValidate ? await this.signer.signTransaction(call, details) : []; return { - ...v3Details(details), + ...v3Details(details, await this.channel.getSpecVersion()), contractAddress: this.address, calldata, signature, @@ -866,7 +880,7 @@ export class Account extends Provider implements AccountInterface { const signature = !details.skipValidate ? await this.signer.signDeclareTransaction({ ...details, - ...v3Details(details), + ...v3Details(details, await this.channel.getSpecVersion()), classHash, compiledClassHash: compiledClassHash as string, // TODO: TS, cast because optional for v2 and required for v3, thrown if not present senderAddress: details.walletAddress, @@ -898,7 +912,7 @@ export class Account extends Provider implements AccountInterface { const signature = !details.skipValidate ? await this.signer.signDeployAccountTransaction({ ...details, - ...v3Details(details), + ...v3Details(details, await this.channel.getSpecVersion()), classHash, contractAddress, addressSalt, @@ -907,7 +921,7 @@ export class Account extends Provider implements AccountInterface { : []; return { - ...v3Details(details), + ...v3Details(details, await this.channel.getSpecVersion()), classHash, addressSalt, constructorCalldata: compiledCalldata, @@ -962,7 +976,7 @@ export class Account extends Provider implements AccountInterface { ([] as Invocations).concat(invocations).map(async (transaction, index: number) => { const txPayload: any = 'payload' in transaction ? transaction.payload : transaction; const signerDetails = { - ...v3Details(details), + ...v3Details(details, await this.channel.getSpecVersion()), walletAddress: this.address, nonce: toBigInt(Number(safeNonce) + index), maxFee: ZERO, diff --git a/src/channel/index.ts b/src/channel/index.ts index f210bfe3e..b804ba073 100644 --- a/src/channel/index.ts +++ b/src/channel/index.ts @@ -1,3 +1,4 @@ -export * as RPC06 from './rpc_0_6'; export * as RPC07 from './rpc_0_7'; -export * from './rpc_0_7'; +export * as RPC08 from './rpc_0_8'; +// Default channel +export * from './rpc_0_8'; diff --git a/src/channel/rpc_0_7.ts b/src/channel/rpc_0_7.ts index 1dbb1a971..b484b8a91 100644 --- a/src/channel/rpc_0_7.ts +++ b/src/channel/rpc_0_7.ts @@ -1,4 +1,9 @@ -import { NetworkName, StarknetChainId, SYSTEM_MESSAGES } from '../global/constants'; +import { + NetworkName, + StarknetChainId, + SupportedRpcVersion, + SYSTEM_MESSAGES, +} from '../global/constants'; import { LibraryError, RpcError } from '../utils/errors'; import { AccountInvocationItem, @@ -27,7 +32,7 @@ import fetch from '../utils/fetchPonyfill'; import { getSelector, getSelectorFromName } from '../utils/hash'; import { stringify } from '../utils/json'; import { getHexStringArray, toHex, toStorageKey } from '../utils/num'; -import { Block, getDefaultNodeUrl, isV3Tx, isVersion, wait } from '../utils/provider'; +import { Block, getDefaultNodeUrl, isV3Tx, wait } from '../utils/provider'; import { decompressProgram, signatureToHexArray } from '../utils/stark'; import { getVersionsByType } from '../utils/transaction'; import { logger } from '../global/logger'; @@ -39,6 +44,8 @@ const defaultOptions = { }; export class RpcChannel { + readonly id = 'RPC07'; + public nodeUrl: string; public headers: object; @@ -53,7 +60,7 @@ export class RpcChannel { private chainId?: StarknetChainId; - private specVersion?: string; + private specVersion?: SupportedRpcVersion; private transactionRetryIntervalFallback?: number; @@ -100,6 +107,12 @@ export class RpcChannel { baseFetch: this.baseFetch, }); } + + logger.debug('Using Channel', this.id); + } + + public readSpecVersion() { + return this.specVersion; } private get transactionRetryIntervalDefault() { @@ -144,7 +157,7 @@ export class RpcChannel { if (this.batchClient) { const { error, result } = await this.batchClient.fetch( method, - params, + params as any, // TODO: fix this temporary cast with some permanent solution (this.requestId += 1) ); this.errorHandler(method, params, error); @@ -166,11 +179,28 @@ export class RpcChannel { return this.chainId; } + /** + * fetch if undefined else just return this.specVersion + * return this.specVersion as 'M.m' + * @example this.specVersion = "0.8" + */ public async getSpecVersion() { - this.specVersion ??= (await this.fetchEndpoint('starknet_specVersion')) as StarknetChainId; + if (!this.specVersion) { + const extendedVersion = await this.getSpecificationVersion(); + const [major, minor] = extendedVersion.split('.'); + const specVerson = `${major}.${minor}` as SupportedRpcVersion; + this.specVersion ??= specVerson; + } return this.specVersion; } + /** + * fetch spec version in extended format "M.m.p-?" + */ + public getSpecificationVersion() { + return this.fetchEndpoint('starknet_specVersion'); + } + public getNonceForAddress( contractAddress: BigNumberish, blockIdentifier: BlockIdentifier = this.blockIdentifier @@ -425,12 +455,11 @@ export class RpcChannel { { blockIdentifier = this.blockIdentifier, skipValidate = true }: getEstimateFeeBulkOptions ) { const block_id = new Block(blockIdentifier).identifier; - let flags = {}; - if (!isVersion('0.5', await this.getSpecVersion())) { - flags = { - simulation_flags: skipValidate ? [RPC.ESimulationFlag.SKIP_VALIDATE] : [], - }; - } // else v(0.5) no flags + const flags = { + simulation_flags: (skipValidate + ? [RPC.ESimulationFlag.SKIP_VALIDATE] + : []) as RPC.Methods['starknet_estimateFee']['params']['simulation_flags'], + }; return this.fetchEndpoint('starknet_estimateFee', { request: invocations.map((it) => this.buildTransaction(it, 'fee')), diff --git a/src/channel/rpc_0_6.ts b/src/channel/rpc_0_8.ts similarity index 69% rename from src/channel/rpc_0_6.ts rename to src/channel/rpc_0_8.ts index 8874f50e8..4e86a5084 100644 --- a/src/channel/rpc_0_6.ts +++ b/src/channel/rpc_0_8.ts @@ -1,4 +1,9 @@ -import { NetworkName, StarknetChainId, SYSTEM_MESSAGES } from '../global/constants'; +import { + NetworkName, + StarknetChainId, + SupportedRpcVersion, + SYSTEM_MESSAGES, +} from '../global/constants'; import { LibraryError, RpcError } from '../utils/errors'; import { AccountInvocationItem, @@ -18,7 +23,7 @@ import { getSimulateTransactionOptions, waitForTransactionOptions, } from '../types'; -import { JRPC, RPCSPEC06 as RPC } from '../types/api'; +import { JRPC, RPCSPEC08 as RPC } from '../types/api'; import { BatchClient } from '../utils/batch'; import { CallData } from '../utils/calldata'; import { isSierra } from '../utils/contract'; @@ -26,11 +31,18 @@ import { validateAndParseEthAddress } from '../utils/eth'; import fetch from '../utils/fetchPonyfill'; import { getSelector, getSelectorFromName } from '../utils/hash'; import { stringify } from '../utils/json'; -import { getHexStringArray, toHex, toStorageKey } from '../utils/num'; -import { Block, getDefaultNodeUrl, isV3Tx, isVersion, wait } from '../utils/provider'; +import { + bigNumberishArrayToHexadecimalStringArray, + getHexStringArray, + toHex, + toStorageKey, +} from '../utils/num'; +import { Block, getDefaultNodeUrl, isV3Tx, wait } from '../utils/provider'; import { decompressProgram, signatureToHexArray } from '../utils/stark'; import { getVersionsByType } from '../utils/transaction'; import { logger } from '../global/logger'; +import { isRPC08_ResourceBounds } from '../provider/types/spec.type'; +// TODO: check if we can filet type before entering to this method, as so to specify here only RPC 0.8 types const defaultOptions = { headers: { 'Content-Type': 'application/json' }, @@ -39,6 +51,8 @@ const defaultOptions = { }; export class RpcChannel { + readonly id = 'RPC08'; + public nodeUrl: string; public headers: object; @@ -53,7 +67,7 @@ export class RpcChannel { private chainId?: StarknetChainId; - private specVersion?: string; + private specVersion?: SupportedRpcVersion; private transactionRetryIntervalFallback?: number; @@ -100,6 +114,12 @@ export class RpcChannel { baseFetch: this.baseFetch, }); } + + logger.debug('Using Channel', this.id); + } + + public readSpecVersion() { + return this.specVersion; } private get transactionRetryIntervalDefault() { @@ -166,11 +186,67 @@ export class RpcChannel { return this.chainId; } + // TODO: New Method add test + /** + * Given an l1 tx hash, returns the associated l1_handler tx hashes and statuses for all L1 -> L2 messages sent by the l1 transaction, ordered by the l1 tx sending order + */ + public getMessagesStatus(txHash: BigNumberish) { + const transaction_hash = toHex(txHash); + return this.fetchEndpoint('starknet_getMessagesStatus', { + transaction_hash, + }); + } + + // TODO: New Method add test + public getStorageProof( + blockIdentifier: BlockIdentifier = this.blockIdentifier, + classHashes: BigNumberish[] = [], + contractAddresses: BigNumberish[] = [], + contractsStorageKeys: RPC.CONTRACT_STORAGE_KEYS[] = [] // TODO: allow BigNUmberish[] and fix formatting before request + ) { + const block_id = new Block(blockIdentifier).identifier; + const class_hashes = bigNumberishArrayToHexadecimalStringArray(classHashes); + const contract_addresses = bigNumberishArrayToHexadecimalStringArray(contractAddresses); + + return this.fetchEndpoint('starknet_getStorageProof', { + block_id, + class_hashes, + contract_addresses, + contracts_storage_keys: contractsStorageKeys, + }); + } + + // TODO: New Method add test + public getCompiledCasm(classHash: BigNumberish): Promise { + const class_hash = toHex(classHash); + + return this.fetchEndpoint('starknet_getCompiledCasm', { + class_hash, + }); + } + + /** + * fetch if undefined else just return this.specVersion + * return this.specVersion as 'M.m' + * @example this.specVersion = "0.8" + */ public async getSpecVersion() { - this.specVersion ??= (await this.fetchEndpoint('starknet_specVersion')) as StarknetChainId; + if (!this.specVersion) { + const extendedVersion = await this.getSpecificationVersion(); + const [major, minor] = extendedVersion.split('.'); + const specVerson = `${major}.${minor}` as SupportedRpcVersion; + this.specVersion ??= specVerson; + } return this.specVersion; } + /** + * fetch spec version in extended format "M.m.p-?" + */ + public getSpecificationVersion() { + return this.fetchEndpoint('starknet_specVersion'); + } + public getNonceForAddress( contractAddress: BigNumberish, blockIdentifier: BlockIdentifier = this.blockIdentifier @@ -209,6 +285,11 @@ export class RpcChannel { return this.fetchEndpoint('starknet_getBlockWithTxs', { block_id }); } + public getBlockWithReceipts(blockIdentifier: BlockIdentifier = this.blockIdentifier) { + const block_id = new Block(blockIdentifier).identifier; + return this.fetchEndpoint('starknet_getBlockWithReceipts', { block_id }); + } + public getBlockStateUpdate(blockIdentifier: BlockIdentifier = this.blockIdentifier) { const block_id = new Block(blockIdentifier).identifier; return this.fetchEndpoint('starknet_getStateUpdate', { block_id }); @@ -361,7 +442,7 @@ export class RpcChannel { // eslint-disable-next-line no-await-in-loop await wait(retryInterval); } - return txReceipt as RPC.SPEC.TXN_RECEIPT; + return txReceipt as RPC.TXN_RECEIPT; } public getStorageAt( @@ -420,12 +501,11 @@ export class RpcChannel { { blockIdentifier = this.blockIdentifier, skipValidate = true }: getEstimateFeeBulkOptions ) { const block_id = new Block(blockIdentifier).identifier; - let flags = {}; - if (!isVersion('0.5', await this.getSpecVersion())) { - flags = { - simulation_flags: skipValidate ? [RPC.ESimulationFlag.SKIP_VALIDATE] : [], - }; - } // else v(0.5) no flags + const flags = { + simulation_flags: (skipValidate + ? [RPC.ESimulationFlag.SKIP_VALIDATE] + : []) as RPC.Methods['starknet_estimateFee']['params']['simulation_flags'], + }; return this.fetchEndpoint('starknet_estimateFee', { request: invocations.map((it) => this.buildTransaction(it, 'fee')), @@ -436,43 +516,27 @@ export class RpcChannel { public async invoke(functionInvocation: Invocation, details: InvocationsDetailsWithNonce) { let promise; - if (!isV3Tx(details)) { - // V1 - promise = this.fetchEndpoint('starknet_addInvokeTransaction', { - invoke_transaction: { - sender_address: functionInvocation.contractAddress, - calldata: CallData.toHex(functionInvocation.calldata), - type: RPC.ETransactionType.INVOKE, - max_fee: toHex(details.maxFee || 0), - version: RPC.ETransactionVersion.V1, - signature: signatureToHexArray(functionInvocation.signature), - nonce: toHex(details.nonce), - }, - }); - - logger.warn(SYSTEM_MESSAGES.legacyTxWarningMessage, { - version: RPC.ETransactionVersion.V1, - type: RPC.ETransactionType.INVOKE, - }); - } else { - // V3 - promise = this.fetchEndpoint('starknet_addInvokeTransaction', { - invoke_transaction: { - type: RPC.ETransactionType.INVOKE, - sender_address: functionInvocation.contractAddress, - calldata: CallData.toHex(functionInvocation.calldata), - version: RPC.ETransactionVersion.V3, - signature: signatureToHexArray(functionInvocation.signature), - nonce: toHex(details.nonce), - resource_bounds: details.resourceBounds, - tip: toHex(details.tip), - paymaster_data: details.paymasterData.map((it) => toHex(it)), - account_deployment_data: details.accountDeploymentData.map((it) => toHex(it)), - nonce_data_availability_mode: details.nonceDataAvailabilityMode, - fee_data_availability_mode: details.feeDataAvailabilityMode, - }, - }); - } + if (isV3Tx(details)) { + if (isRPC08_ResourceBounds(details.resourceBounds)) { + // V3 + promise = this.fetchEndpoint('starknet_addInvokeTransaction', { + invoke_transaction: { + type: RPC.ETransactionType.INVOKE, + sender_address: functionInvocation.contractAddress, + calldata: CallData.toHex(functionInvocation.calldata), + version: RPC.ETransactionVersion.V3, + signature: signatureToHexArray(functionInvocation.signature), + nonce: toHex(details.nonce), + resource_bounds: details.resourceBounds, + tip: toHex(details.tip), + paymaster_data: details.paymasterData.map((it) => toHex(it)), + account_deployment_data: details.accountDeploymentData.map((it) => toHex(it)), + nonce_data_availability_mode: details.nonceDataAvailabilityMode, + fee_data_availability_mode: details.feeDataAvailabilityMode, + }, + }); + } else throw Error(SYSTEM_MESSAGES.SWOldV3); + } else throw Error(SYSTEM_MESSAGES.legacyTxRPC08Message); return this.waitMode ? this.waitForTransaction((await promise).transaction_hash) : promise; } @@ -482,79 +546,33 @@ export class RpcChannel { details: InvocationsDetailsWithNonce ) { let promise; - if (!isSierra(contract) && !isV3Tx(details)) { - // V1 Cairo 0 - promise = this.fetchEndpoint('starknet_addDeclareTransaction', { - declare_transaction: { - type: RPC.ETransactionType.DECLARE, - contract_class: { - program: contract.program, - entry_points_by_type: contract.entry_points_by_type, - abi: contract.abi, - }, - version: RPC.ETransactionVersion.V1, - max_fee: toHex(details.maxFee || 0), - signature: signatureToHexArray(signature), - sender_address: senderAddress, - nonce: toHex(details.nonce), - }, - }); - - logger.warn(SYSTEM_MESSAGES.legacyTxWarningMessage, { - version: RPC.ETransactionVersion.V1, - type: RPC.ETransactionType.DECLARE, - }); - } else if (isSierra(contract) && !isV3Tx(details)) { - // V2 Cairo1 - promise = this.fetchEndpoint('starknet_addDeclareTransaction', { - declare_transaction: { - type: RPC.ETransactionType.DECLARE, - contract_class: { - sierra_program: decompressProgram(contract.sierra_program), - contract_class_version: contract.contract_class_version, - entry_points_by_type: contract.entry_points_by_type, - abi: contract.abi, - }, - compiled_class_hash: compiledClassHash || '', - version: RPC.ETransactionVersion.V2, - max_fee: toHex(details.maxFee || 0), - signature: signatureToHexArray(signature), - sender_address: senderAddress, - nonce: toHex(details.nonce), - }, - }); - - logger.warn(SYSTEM_MESSAGES.legacyTxWarningMessage, { - version: RPC.ETransactionVersion.V2, - type: RPC.ETransactionType.DECLARE, - }); - } else if (isSierra(contract) && isV3Tx(details)) { - // V3 Cairo1 - promise = this.fetchEndpoint('starknet_addDeclareTransaction', { - declare_transaction: { - type: RPC.ETransactionType.DECLARE, - sender_address: senderAddress, - compiled_class_hash: compiledClassHash || '', - version: RPC.ETransactionVersion.V3, - signature: signatureToHexArray(signature), - nonce: toHex(details.nonce), - contract_class: { - sierra_program: decompressProgram(contract.sierra_program), - contract_class_version: contract.contract_class_version, - entry_points_by_type: contract.entry_points_by_type, - abi: contract.abi, + if (isSierra(contract) && isV3Tx(details)) { + if (isRPC08_ResourceBounds(details.resourceBounds)) { + // V3 Cairo1 + promise = this.fetchEndpoint('starknet_addDeclareTransaction', { + declare_transaction: { + type: RPC.ETransactionType.DECLARE, + sender_address: senderAddress, + compiled_class_hash: compiledClassHash || '', + version: RPC.ETransactionVersion.V3, + signature: signatureToHexArray(signature), + nonce: toHex(details.nonce), + contract_class: { + sierra_program: decompressProgram(contract.sierra_program), + contract_class_version: contract.contract_class_version, + entry_points_by_type: contract.entry_points_by_type, + abi: contract.abi, + }, + resource_bounds: details.resourceBounds, + tip: toHex(details.tip), + paymaster_data: details.paymasterData.map((it) => toHex(it)), + account_deployment_data: details.accountDeploymentData.map((it) => toHex(it)), + nonce_data_availability_mode: details.nonceDataAvailabilityMode, + fee_data_availability_mode: details.feeDataAvailabilityMode, }, - resource_bounds: details.resourceBounds, - tip: toHex(details.tip), - paymaster_data: details.paymasterData.map((it) => toHex(it)), - account_deployment_data: details.accountDeploymentData.map((it) => toHex(it)), - nonce_data_availability_mode: details.nonceDataAvailabilityMode, - fee_data_availability_mode: details.feeDataAvailabilityMode, - }, - }); - } else { - throw Error('declare unspotted parameters'); - } + }); + } else throw Error(SYSTEM_MESSAGES.SWOldV3); + } else throw Error(SYSTEM_MESSAGES.legacyTxRPC08Message); return this.waitMode ? this.waitForTransaction((await promise).transaction_hash) : promise; } @@ -564,44 +582,27 @@ export class RpcChannel { details: InvocationsDetailsWithNonce ) { let promise; - if (!isV3Tx(details)) { - // v1 - promise = this.fetchEndpoint('starknet_addDeployAccountTransaction', { - deploy_account_transaction: { - constructor_calldata: CallData.toHex(constructorCalldata || []), - class_hash: toHex(classHash), - contract_address_salt: toHex(addressSalt || 0), - type: RPC.ETransactionType.DEPLOY_ACCOUNT, - max_fee: toHex(details.maxFee || 0), - version: RPC.ETransactionVersion.V1, - signature: signatureToHexArray(signature), - nonce: toHex(details.nonce), - }, - }); - - logger.warn(SYSTEM_MESSAGES.legacyTxWarningMessage, { - version: RPC.ETransactionVersion.V1, - type: RPC.ETransactionType.DEPLOY_ACCOUNT, - }); - } else { + if (isV3Tx(details)) { + if (isRPC08_ResourceBounds(details.resourceBounds)) { + promise = this.fetchEndpoint('starknet_addDeployAccountTransaction', { + deploy_account_transaction: { + type: RPC.ETransactionType.DEPLOY_ACCOUNT, + version: RPC.ETransactionVersion.V3, + signature: signatureToHexArray(signature), + nonce: toHex(details.nonce), + contract_address_salt: toHex(addressSalt || 0), + constructor_calldata: CallData.toHex(constructorCalldata || []), + class_hash: toHex(classHash), + resource_bounds: details.resourceBounds, + tip: toHex(details.tip), + paymaster_data: details.paymasterData.map((it) => toHex(it)), + nonce_data_availability_mode: details.nonceDataAvailabilityMode, + fee_data_availability_mode: details.feeDataAvailabilityMode, + }, + }); + } else throw Error(SYSTEM_MESSAGES.SWOldV3); // v3 - promise = this.fetchEndpoint('starknet_addDeployAccountTransaction', { - deploy_account_transaction: { - type: RPC.ETransactionType.DEPLOY_ACCOUNT, - version: RPC.ETransactionVersion.V3, - signature: signatureToHexArray(signature), - nonce: toHex(details.nonce), - contract_address_salt: toHex(addressSalt || 0), - constructor_calldata: CallData.toHex(constructorCalldata || []), - class_hash: toHex(classHash), - resource_bounds: details.resourceBounds, - tip: toHex(details.tip), - paymaster_data: details.paymasterData.map((it) => toHex(it)), - nonce_data_availability_mode: details.nonceDataAvailabilityMode, - fee_data_availability_mode: details.feeDataAvailabilityMode, - }, - }); - } + } else throw Error(SYSTEM_MESSAGES.legacyTxRPC08Message); return this.waitMode ? this.waitForTransaction((await promise).transaction_hash) : promise; } @@ -666,16 +667,7 @@ export class RpcChannel { if (!isV3Tx(invocation)) { // V0,V1,V2 - details = { - signature: signatureToHexArray(invocation.signature), - nonce: toHex(invocation.nonce), - max_fee: toHex(invocation.maxFee || 0), - }; - - logger.warn(SYSTEM_MESSAGES.legacyTxWarningMessage, { - version: invocation.version, - type: invocation.type, - }); + throw Error('v0,v1,v2 tx are not supported on RPC 0.8'); } else { // V3 details = { @@ -692,27 +684,21 @@ export class RpcChannel { if (invocation.type === TransactionType.INVOKE) { return { - // v0 v1 v3 + // V3 type: RPC.ETransactionType.INVOKE, sender_address: invocation.contractAddress, calldata: CallData.toHex(invocation.calldata), - version: toHex(invocation.version || defaultVersions.v3), + version: toHex(defaultVersions.v3), ...details, - } as RPC.SPEC.BROADCASTED_INVOKE_TXN; + } as RPC.BROADCASTED_INVOKE_TXN; } if (invocation.type === TransactionType.DECLARE) { if (!isSierra(invocation.contract)) { - // Cairo 0 - v1 - return { - type: invocation.type, - contract_class: invocation.contract, - sender_address: invocation.senderAddress, - version: toHex(invocation.version || defaultVersions.v1), - ...details, - } as RPC.SPEC.BROADCASTED_DECLARE_TXN_V1; + logger.error('Cairo 0 - non Sierra v1 tx are not supported'); + throw Error('Declaring non Sierra contract using RPC 0.8'); } return { - // Cairo 1 - v2 v3 + // Cairo - V3 type: invocation.type, contract_class: { ...invocation.contract, @@ -720,22 +706,22 @@ export class RpcChannel { }, compiled_class_hash: invocation.compiledClassHash || '', sender_address: invocation.senderAddress, - version: toHex(invocation.version || defaultVersions.v3), + version: toHex(defaultVersions.v3), ...details, - } as RPC.SPEC.BROADCASTED_DECLARE_TXN; + } as RPC.BROADCASTED_DECLARE_TXN; } if (invocation.type === TransactionType.DEPLOY_ACCOUNT) { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { account_deployment_data, ...restDetails } = details; - // v1 v3 + // V3 return { type: invocation.type, constructor_calldata: CallData.toHex(invocation.constructorCalldata || []), class_hash: toHex(invocation.classHash), contract_address_salt: toHex(invocation.addressSalt || 0), - version: toHex(invocation.version || defaultVersions.v3) as RPC.SPEC.INVOKE_TXN['version'], + version: toHex(defaultVersions.v3), ...restDetails, - } as RPC.SPEC.BROADCASTED_DEPLOY_ACCOUNT_TXN; + } as RPC.BROADCASTED_DEPLOY_ACCOUNT_TXN; } throw Error('RPC buildTransaction received unknown TransactionType'); } diff --git a/src/contract/default.ts b/src/contract/default.ts index ded86590b..cbd5edd34 100644 --- a/src/contract/default.ts +++ b/src/contract/default.ts @@ -17,7 +17,7 @@ import { FunctionAbi, InvokeFunctionResponse, InvokeOptions, - InvokeTransactionReceiptResponse, + GetTransactionReceiptResponse, ParsedEvents, RawArgs, Result, @@ -31,8 +31,6 @@ import { createAbiParser } from '../utils/calldata/parser'; import { getAbiEvents, parseEvents as parseRawEvents } from '../utils/events/index'; import { cleanHex } from '../utils/num'; import { ContractInterface } from './interface'; -import type { GetTransactionReceiptResponse } from '../utils/transactionReceipt'; -import type { INVOKE_TXN_RECEIPT } from '../types/provider/spec'; import { logger } from '../global/logger'; export type TypedContractV2 = AbiWanTypedContract & Contract; @@ -328,23 +326,27 @@ export class Contract implements ContractInterface { }; } + // TODO: Demistify what is going on here ??? + // TODO: receipt status filtering test and fix this do not look right public parseEvents(receipt: GetTransactionReceiptResponse): ParsedEvents { let parsed: ParsedEvents; receipt.match({ success: (txR: SuccessfulTransactionReceiptResponse) => { const emittedEvents = - (txR as InvokeTransactionReceiptResponse).events + txR.events ?.map((event) => { return { - block_hash: (txR as INVOKE_TXN_RECEIPT).block_hash, - block_number: (txR as INVOKE_TXN_RECEIPT).block_number, - transaction_hash: (txR as INVOKE_TXN_RECEIPT).transaction_hash, + // TODO: this do not check that block is production and block_hash and block_number actually exists + // TODO: second issue is that ts do not complains about it + block_hash: txR.block_hash, + block_number: txR.block_number, + transaction_hash: txR.transaction_hash, ...event, }; }) .filter((event) => cleanHex(event.from_address) === cleanHex(this.address), []) || []; parsed = parseRawEvents( - emittedEvents, + emittedEvents as any, // TODO: any temp hotfix, fix this this.events, this.structs, CallData.getAbiEnum(this.abi) diff --git a/src/contract/interface.ts b/src/contract/interface.ts index b04ae9fe5..37935e591 100644 --- a/src/contract/interface.ts +++ b/src/contract/interface.ts @@ -24,7 +24,7 @@ import { import { CairoCustomEnum } from '../utils/calldata/enum/CairoCustomEnum'; import { CairoOption } from '../utils/calldata/enum/CairoOption'; import { CairoResult } from '../utils/calldata/enum/CairoResult'; -import type { GetTransactionReceiptResponse } from '../utils/transactionReceipt'; +import type { GetTransactionReceiptResponse } from '../utils/transactionReceipt/transactionReceipt.type'; declare module 'abi-wan-kanabi' { export interface Config { diff --git a/src/global/constants.ts b/src/global/constants.ts index 7a2a2a7af..ec2f7c343 100644 --- a/src/global/constants.ts +++ b/src/global/constants.ts @@ -1,5 +1,6 @@ -import { ETransactionVersion } from '../types/api'; -import { type LogLevel } from './logger.type'; +import type { FeeMarginPercentage } from '../types'; +import { ETransactionVersion, RPCSPEC08 } from '../types/api'; +import type { LogLevel } from './logger.type'; export { IS_BROWSER } from '../utils/encode'; @@ -13,7 +14,7 @@ export const TEXT_TO_FELT_MAX_LEN = 31; * types.RPC.ETransactionVersion * For BN do BigInt(TRANSACTION_VERSION.*) */ -export { ETransactionVersion as TRANSACTION_VERSION }; +export const { ETransactionVersion: TRANSACTION_VERSION } = RPCSPEC08; export const ZERO = 0n; export const MASK_250 = 2n ** 250n - 1n; // 2 ** 250 - 1 @@ -54,30 +55,11 @@ export enum TransactionHashPrefix { L1_HANDLER = '0x6c315f68616e646c6572', // encodeShortString('l1_handler'), } -export const enum FeeMarginPercentage { - L1_BOUND_MAX_AMOUNT = 50, - L1_BOUND_MAX_PRICE_PER_UNIT = 50, - MAX_FEE = 50, -} - export const UDC = { ADDRESS: '0x041a78e741e5af2fec34b695679bc6891742439f7afb8484ecd7766661ad02bf', ENTRYPOINT: 'deployContract', } as const; -export const RPC_DEFAULT_VERSION = 'v0_7'; - -export const RPC_NODES = { - SN_MAIN: [ - `https://starknet-mainnet.public.blastapi.io/rpc/${RPC_DEFAULT_VERSION}`, - `https://free-rpc.nethermind.io/mainnet-juno/${RPC_DEFAULT_VERSION}`, - ], - SN_SEPOLIA: [ - `https://starknet-sepolia.public.blastapi.io/rpc/${RPC_DEFAULT_VERSION}`, - `https://free-rpc.nethermind.io/sepolia-juno/${RPC_DEFAULT_VERSION}`, - ], -} as const; - export const OutsideExecutionCallerAny = '0x414e595f43414c4c4552'; // encodeShortString('ANY_CALLER') export const SNIP9_V1_INTERFACE_ID = '0x68cfd18b92d1907b8ba3cc324900277f5a3622099431ea85dd8089255e4181'; @@ -90,19 +72,68 @@ export const HARDENING_BYTE = 128; // 0x80000000 export const HARDENING_4BYTES = 2147483648n; +/** + * dot formate rpc versions + */ +export const SupportedRpcVersion = { + 0.7: '0.7', + 0.8: '0.8', +} as const; +export type SupportedRpcVersion = (typeof SupportedRpcVersion)[keyof typeof SupportedRpcVersion]; + +export type SupportedTransactionVersion = + | typeof ETransactionVersion.V2 + | typeof ETransactionVersion.V3; + // Default initial global config export const DEFAULT_GLOBAL_CONFIG: { legacyMode: boolean; logLevel: LogLevel; - accountTxVersion: typeof ETransactionVersion.V2 | typeof ETransactionVersion.V3; + rpcVersion: SupportedRpcVersion; + transactionVersion: SupportedTransactionVersion; + feeMarginPercentage: FeeMarginPercentage; } = { legacyMode: false, + rpcVersion: '0.8', + transactionVersion: ETransactionVersion.V3, logLevel: 'INFO', - accountTxVersion: ETransactionVersion.V2, + feeMarginPercentage: { + bounds: { + l1_gas: { + max_amount: 50, + max_price_per_unit: 50, + }, + l1_data_gas: { + max_amount: 50, + max_price_per_unit: 50, + }, + l2_gas: { + max_amount: 50, + max_price_per_unit: 50, + }, + }, + maxFee: 50, + }, }; +const vToUrl = (versionString: SupportedRpcVersion) => + `v${versionString.replace(/^v/, '').replace(/\./g, '_')}`; + +export const RPC_NODES = { + SN_MAIN: [ + `https://starknet-mainnet.public.blastapi.io/rpc/${vToUrl(DEFAULT_GLOBAL_CONFIG.rpcVersion)}`, + `https://free-rpc.nethermind.io/mainnet-juno/${vToUrl(DEFAULT_GLOBAL_CONFIG.rpcVersion)}`, + ], + SN_SEPOLIA: [ + `https://starknet-sepolia.public.blastapi.io/rpc/${vToUrl(DEFAULT_GLOBAL_CONFIG.rpcVersion)}`, + `https://free-rpc.nethermind.io/sepolia-juno/${vToUrl(DEFAULT_GLOBAL_CONFIG.rpcVersion)}`, + ], +} as const; + // Default system messages export const SYSTEM_MESSAGES = { legacyTxWarningMessage: 'You are using a deprecated transaction version (V0,V1,V2)!\nUpdate to the latest V3 transactions!', + legacyTxRPC08Message: 'RPC 0.8 do not support legacy transactions', + SWOldV3: 'RPC 0.7 V3 tx (improper resource bounds) not supported in RPC 0.8', }; diff --git a/src/index.ts b/src/index.ts index 0d85ee062..9036067f3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -44,7 +44,7 @@ export * from './utils/address'; export * from './utils/calldata'; export * from './utils/calldata/enum'; export * from './utils/contract'; -export * from './utils/transactionReceipt'; +export * from './utils/transactionReceipt/transactionReceipt'; export * from './utils/units'; export * as wallet from './wallet/connect'; export * from './global/config'; diff --git a/src/provider/interface.ts b/src/provider/interface.ts index 21708b629..006b8f59b 100644 --- a/src/provider/interface.ts +++ b/src/provider/interface.ts @@ -1,4 +1,4 @@ -import { RPC06, RPC07 } from '../channel'; +import { RPC08, RPC07 } from '../channel'; import { StarknetChainId } from '../global/constants'; import type { AccountInvocations, @@ -17,6 +17,7 @@ import type { EstimateFeeResponse, EstimateFeeResponseBulk, GetBlockResponse, + GetTransactionReceiptResponse, GetTransactionResponse, Invocation, InvocationsDetailsWithNonce, @@ -31,10 +32,9 @@ import type { getSimulateTransactionOptions, waitForTransactionOptions, } from '../types'; -import type { GetTransactionReceiptResponse } from '../utils/transactionReceipt'; export abstract class ProviderInterface { - public abstract channel: RPC07.RpcChannel | RPC06.RpcChannel; + public abstract channel: RPC07.RpcChannel | RPC08.RpcChannel; /** * Gets the Starknet chain Id diff --git a/src/provider/rpc.ts b/src/provider/rpc.ts index 74e49bc6a..71040586b 100644 --- a/src/provider/rpc.ts +++ b/src/provider/rpc.ts @@ -1,6 +1,4 @@ -import type { SPEC } from 'starknet-types-07'; - -import { RPC06, RPC07, RpcChannel } from '../channel'; +import { RPC08, RPC07 } from '../channel'; import { AccountInvocations, BigNumberish, @@ -20,7 +18,6 @@ import { InvocationsDetailsWithNonce, PendingBlock, PendingStateUpdate, - RPC, RpcProviderOptions, StateUpdate, StateUpdateResponse, @@ -31,26 +28,39 @@ import { type Signature, type TypedData, waitForTransactionOptions, + GetTransactionReceiptResponse, } from '../types'; -import type { TransactionWithHash } from '../types/provider/spec'; +import type { + DeclaredTransaction, + DeployedAccountTransaction, + EventFilter, + EVENTS_CHUNK, + FEE_ESTIMATE, + InvokedTransaction, + L1_HANDLER_TXN, + L1Message, + TRANSACTION_TRACE, + TransactionWithHash, +} from './types/spec.type'; import assert from '../utils/assert'; import { CallData } from '../utils/calldata'; import { getAbiContractVersion } from '../utils/calldata/cairo'; import { extractContractHashes, isSierra } from '../utils/contract'; import { solidityUint256PackedKeccak256 } from '../utils/hash'; import { isBigNumberish, toBigInt, toHex } from '../utils/num'; -import { wait } from '../utils/provider'; +import { isVersion, wait } from '../utils/provider'; import { RPCResponseParser } from '../utils/responseParser/rpc'; import { formatSignature } from '../utils/stark'; -import { GetTransactionReceiptResponse, ReceiptTx } from '../utils/transactionReceipt'; +import { ReceiptTx } from '../utils/transactionReceipt/transactionReceipt'; import { getMessageHash, validateTypedData } from '../utils/typedData'; import { LibraryError } from '../utils/errors'; import { ProviderInterface } from './interface'; +import { config } from '../global/config'; export class RpcProvider implements ProviderInterface { public responseParser: RPCResponseParser; - public channel: RPC07.RpcChannel | RPC06.RpcChannel; + public channel: RPC07.RpcChannel | RPC08.RpcChannel; constructor(optionsOrProvider?: RpcProviderOptions | ProviderInterface | RpcProvider) { if (optionsOrProvider && 'channel' in optionsOrProvider) { @@ -60,11 +70,41 @@ export class RpcProvider implements ProviderInterface { ? optionsOrProvider.responseParser : new RPCResponseParser(); } else { - this.channel = new RpcChannel({ ...optionsOrProvider, waitMode: false }); + if (optionsOrProvider && optionsOrProvider.specVersion) { + if (isVersion('0.8', optionsOrProvider.specVersion)) { + this.channel = new RPC08.RpcChannel({ ...optionsOrProvider, waitMode: false }); + } else if (isVersion('0.7', optionsOrProvider.specVersion)) { + this.channel = new RPC07.RpcChannel({ ...optionsOrProvider, waitMode: false }); + } else + throw new Error(`unsupported channel for spec version: ${optionsOrProvider.specVersion}`); + } else if (isVersion('0.8', config.get('rpcVersion'))) { + this.channel = new RPC08.RpcChannel({ ...optionsOrProvider, waitMode: false }); + } else if (isVersion('0.7', config.get('rpcVersion'))) { + this.channel = new RPC07.RpcChannel({ ...optionsOrProvider, waitMode: false }); + } else throw new Error('unable to define spec version for channel'); + this.responseParser = new RPCResponseParser(optionsOrProvider?.feeMarginPercentage); } } + /** + * auto configure channel based on provided node + * leave space for other async before constructor + */ + static async create(optionsOrProvider?: RpcProviderOptions) { + const channel = new RPC07.RpcChannel({ ...optionsOrProvider }); + const spec = await channel.getSpecVersion(); + + if (isVersion('0.7', spec)) { + return new RpcProvider({ ...optionsOrProvider, specVersion: '0.7' }); + } + if (isVersion('0.8', spec)) { + return new RpcProvider({ ...optionsOrProvider, specVersion: '0.8' }); + } + + throw new Error('unable to detect specification version'); + } + public fetch(method: string, params?: object, id: string | number = 0) { return this.channel.fetch(method, params, id); } @@ -73,10 +113,20 @@ export class RpcProvider implements ProviderInterface { return this.channel.getChainId(); } + /** + * return spec version in format "M.m" + */ public async getSpecVersion() { return this.channel.getSpecVersion(); } + /** + * @returns return spec version in format 'M.m.p-rc' + */ + public async getSpecificationVersion() { + return this.channel.getSpecificationVersion(); + } + public async getNonceForAddress( contractAddress: BigNumberish, blockIdentifier?: BlockIdentifier @@ -169,7 +219,7 @@ export class RpcProvider implements ProviderInterface { const transaction = (await this.channel.getTransactionByHash(l2TxHash)) as TransactionWithHash; assert(transaction.type === 'L1_HANDLER', 'This L2 transaction is not a L1 message.'); const { calldata, contract_address, entry_point_selector, nonce } = - transaction as SPEC.L1_HANDLER_TXN; + transaction as L1_HANDLER_TXN; const params = [ calldata[0], contract_address, @@ -182,7 +232,7 @@ export class RpcProvider implements ProviderInterface { } public async getBlockWithReceipts(blockIdentifier?: BlockIdentifier) { - if (this.channel instanceof RPC06.RpcChannel) + if (this.channel instanceof RPC08.RpcChannel) throw new LibraryError('Unsupported method for RPC version'); return this.channel.getBlockWithReceipts(blockIdentifier); @@ -232,12 +282,12 @@ export class RpcProvider implements ProviderInterface { public async getTransactionReceipt(txHash: BigNumberish): Promise { const txReceiptWoHelper = await this.channel.getTransactionReceipt(txHash); - const txReceiptWoHelperModified: GetTxReceiptResponseWithoutHelper = + const txReceiptWoHelperModified = this.responseParser.parseTransactionReceipt(txReceiptWoHelper); - return new ReceiptTx(txReceiptWoHelperModified) as GetTransactionReceiptResponse; + return new ReceiptTx(txReceiptWoHelperModified); } - public async getTransactionTrace(txHash: BigNumberish) { + public async getTransactionTrace(txHash: BigNumberish): Promise { return this.channel.getTransactionTrace(txHash); } @@ -428,24 +478,21 @@ export class RpcProvider implements ProviderInterface { functionInvocation: Invocation, details: InvocationsDetailsWithNonce ) { - return this.channel.invoke(functionInvocation, details) as Promise; + return this.channel.invoke(functionInvocation, details) as Promise; } public async declareContract( transaction: DeclareContractTransaction, details: InvocationsDetailsWithNonce ) { - return this.channel.declare(transaction, details) as Promise; + return this.channel.declare(transaction, details) as Promise; } public async deployAccountContract( transaction: DeployAccountContractTransaction, details: InvocationsDetailsWithNonce ) { - return this.channel.deployAccount( - transaction, - details - ) as Promise; + return this.channel.deployAccount(transaction, details) as Promise; } public async callContract(call: Call, blockIdentifier?: BlockIdentifier) { @@ -456,7 +503,10 @@ export class RpcProvider implements ProviderInterface { * NEW: Estimate the fee for a message from L1 * @param message Message From L1 */ - public async estimateMessageFee(message: RPC.L1Message, blockIdentifier?: BlockIdentifier) { + public async estimateMessageFee( + message: L1Message, + blockIdentifier?: BlockIdentifier + ): Promise { return this.channel.estimateMessageFee(message, blockIdentifier); } @@ -472,7 +522,7 @@ export class RpcProvider implements ProviderInterface { * Returns all events matching the given filter * @returns events and the pagination of the events */ - public async getEvents(eventFilter: RPC.EventFilter) { + public async getEvents(eventFilter: EventFilter): Promise { return this.channel.getEvents(eventFilter); } diff --git a/src/types/provider/configuration.ts b/src/provider/types/configuration.type.ts similarity index 50% rename from src/types/provider/configuration.ts rename to src/provider/types/configuration.type.ts index 0969253d8..f36327337 100644 --- a/src/types/provider/configuration.ts +++ b/src/provider/types/configuration.type.ts @@ -1,8 +1,14 @@ -import { NetworkName, StarknetChainId } from '../../global/constants'; -import { BlockIdentifier } from '../lib'; +import { NetworkName, StarknetChainId, SupportedRpcVersion } from '../../global/constants'; +import { BlockIdentifier } from '../../types/lib'; +import { ResourceBoundsOverhead } from './spec.type'; export interface ProviderOptions extends RpcProviderOptions {} +export type FeeMarginPercentage = { + bounds: ResourceBoundsOverhead; // V3 tx + maxFee: number; // V legacy tx +}; + export type RpcProviderOptions = { nodeUrl?: string | NetworkName; retries?: number; @@ -10,14 +16,10 @@ export type RpcProviderOptions = { headers?: object; blockIdentifier?: BlockIdentifier; chainId?: StarknetChainId; - specVersion?: string; + specVersion?: SupportedRpcVersion; default?: boolean; waitMode?: boolean; baseFetch?: WindowOrWorkerGlobalScope['fetch']; - feeMarginPercentage?: { - l1BoundMaxAmount: number; - l1BoundMaxPricePerUnit: number; - maxFee: number; - }; + feeMarginPercentage?: FeeMarginPercentage; batch?: false | number; }; diff --git a/src/provider/types/index.type.ts b/src/provider/types/index.type.ts new file mode 100644 index 000000000..e30b23d3d --- /dev/null +++ b/src/provider/types/index.type.ts @@ -0,0 +1,6 @@ +export * from './configuration.type'; +export * from './response.type'; + +// TODO: resolve what types to export on top level +// TODO: option to add StableProvider that use provider types and Provider that use normal types, than export Stable under some namespace +export * as Spec from './spec.type'; diff --git a/src/types/provider/response.ts b/src/provider/types/response.type.ts similarity index 78% rename from src/types/provider/response.ts rename to src/provider/types/response.type.ts index e4cd70411..8e45d5f42 100644 --- a/src/types/provider/response.ts +++ b/src/provider/types/response.type.ts @@ -3,27 +3,12 @@ * Intersection (sequencer response ∩ (∪ rpc responses)) */ -import { - CompiledSierra, - LegacyContractClass, - TransactionExecutionStatus, - TransactionFinalityStatus, - TransactionType, - TransactionStatus, - BlockNumber, -} from '../lib'; +import { IsReverted, IsSucceeded, IsType } from 'starknet-types-08'; +import { CompiledSierra, LegacyContractClass } from '../../types/lib'; import { BLOCK_HASH, BLOCK_NUMBER, - DECLARE_TXN_RECEIPT, - DEPLOY_ACCOUNT_TXN_RECEIPT, FELT, - INVOKE_TXN_RECEIPT, - L1_HANDLER_TXN_RECEIPT, - PENDING_DECLARE_TXN_RECEIPT, - PENDING_DEPLOY_ACCOUNT_TXN_RECEIPT, - PENDING_INVOKE_TXN_RECEIPT, - PENDING_L1_HANDLER_TXN_RECEIPT, PENDING_STATE_UPDATE, PRICE_UNIT, RESOURCE_PRICE, @@ -35,9 +20,11 @@ import { ResourceBounds, SimulateTransaction, TransactionWithHash, -} from './spec'; +} from './spec.type'; + +import { TransactionReceipt } from '../../types/api'; -export { BlockWithTxHashes, ContractClassPayload, FeeEstimate, TransactionReceipt } from './spec'; +export { BlockWithTxHashes, ContractClassPayload, FeeEstimate } from './spec.type'; export type GetBlockResponse = PendingBlock | Block; @@ -69,9 +56,10 @@ export interface MessageToL1 { payload: Array; } +/* export type RevertedTransactionReceiptResponse = { type?: TransactionType | any; // RPC only // any due to RPC Spec issue - execution_status: typeof TransactionExecutionStatus.REVERTED | any; // any due to RPC Spec issue + execution_status: typeof TransactionExecutionStatus.REVERTED | any; // any due to RPC Spec finality_status: TransactionFinalityStatus | any; status?: TransactionStatus; // SEQ only actual_fee: string; @@ -83,36 +71,46 @@ export type RevertedTransactionReceiptResponse = { events: any[]; revert_reason?: string; // SEQ Casted revert_error // ?~ optional due to RCP spec issue }; +*/ -export type RejectedTransactionReceiptResponse = { +// This do not exist any more as tx receipt +/* export type RejectedTransactionReceiptResponse = { status: typeof TransactionStatus.REJECTED; transaction_failure_reason: { code: string; error_message: string; }; -}; +}; */ -export type GetTxReceiptResponseWithoutHelper = - | SuccessfulTransactionReceiptResponse - | RevertedTransactionReceiptResponse - | RejectedTransactionReceiptResponse; +export type GetTxReceiptResponseWithoutHelper = TransactionReceipt; -export type SuccessfulTransactionReceiptResponse = +// TODO: This has misleading name as it is all types not just success +/* export type SuccessfulTransactionReceiptResponse = | InvokeTransactionReceiptResponse | DeployTransactionReceiptResponse - | DeclareTransactionReceiptResponse; + | DeclareTransactionReceiptResponse; */ + +export type SuccessfulTransactionReceiptResponse = IsSucceeded; +export type RevertedTransactionReceiptResponse = IsReverted; + +export type InvokeTransactionReceiptResponse = IsType; +export type DeployTransactionReceiptResponse = InvokeTransactionReceiptResponse; +export type DeclareTransactionReceiptResponse = IsType; -export type GetTransactionResponse = TransactionWithHash; // Spread individual types for usage convenience +/* export type InvokeTransactionReceiptResponse = INVOKE_TXN_RECEIPT | PENDING_INVOKE_TXN_RECEIPT; export type DeclareTransactionReceiptResponse = DECLARE_TXN_RECEIPT | PENDING_DECLARE_TXN_RECEIPT; -export type DeployTransactionReceiptResponse = InvokeTransactionReceiptResponse; + export type DeployAccountTransactionReceiptResponse = | DEPLOY_ACCOUNT_TXN_RECEIPT | PENDING_DEPLOY_ACCOUNT_TXN_RECEIPT; export type L1HandlerTransactionReceiptResponse = | L1_HANDLER_TXN_RECEIPT - | PENDING_L1_HANDLER_TXN_RECEIPT; + | PENDING_L1_HANDLER_TXN_RECEIPT; +*/ + +export type GetTransactionResponse = TransactionWithHash; export interface EstimateFeeResponse { gas_consumed: bigint; diff --git a/src/provider/types/spec.type.ts b/src/provider/types/spec.type.ts new file mode 100644 index 000000000..33e2930e3 --- /dev/null +++ b/src/provider/types/spec.type.ts @@ -0,0 +1,203 @@ +// this file aims to unify the RPC specification types used by the common Provider class + +import * as RPCSPEC07 from 'starknet-types-07'; +import * as RPCSPEC08 from 'starknet-types-08'; + +import { SimpleOneOf } from '../../types/helpers'; + +// taken from type-fest +type Simplify = { [K in keyof T]: T[K] } & {}; + +// taken from type-fest +export type RequiredKeysOf = Exclude< + { + [K in keyof T]: T extends Record ? K : never; + }[keyof T], + undefined +>; + +type ArrayElement = T extends Array ? U : never; + +type MergeProperties, T2 extends Record> = { + [K in RequiredKeysOf & RequiredKeysOf]: Merge; +} & { + [K in keyof T1 & keyof T2]?: Merge; +} & { + [K in Exclude]?: T1[K]; +} & { + [K in Exclude]?: T2[K]; +}; + +/** + * type a = { w: bigint[]; x: bigint; y: string }; + type b = { w: number[]; x: number; z: string }; + type c = Merge; // { w: (bigint | number)[] x: bigint | number; y?: string; z?: string; } + + NOTE: handling for ambiguous overlaps, such as a shared property being an array or object, + is simplified to resolve to only one type since there shouldn't be such occurrences in the + currently supported RPC specifications + */ +type Merge = Simplify< + T1 extends Array + ? T2 extends Array + ? Array, ArrayElement>> + : T1 + : T2 extends Array + ? T2 + : T1 extends object + ? T2 extends object + ? MergeProperties + : T1 + : T2 extends object + ? T2 + : T1 | T2 +>; + +// Default exports for both RPCs +export type ETransactionVersion = RPCSPEC08.ETransactionVersion; +export const { ETransactionVersion } = RPCSPEC08; + +export type ETransactionVersion2 = RPCSPEC08.ETransactionVersion2; +export const { ETransactionVersion2 } = RPCSPEC08; + +export type ETransactionVersion3 = RPCSPEC08.ETransactionVersion3; +export const { ETransactionVersion3 } = RPCSPEC08; + +// MERGES +export type BLOCK_HASH = Merge; +export type BLOCK_NUMBER = Merge; +export type FELT = Merge; +export type TXN_HASH = Merge; + +export type PRICE_UNIT = Merge; +export type RESOURCE_PRICE = Merge; +export type SIMULATION_FLAG = Merge; + +export type STATE_UPDATE = Merge; +export type PENDING_STATE_UPDATE = Merge< + RPCSPEC08.PENDING_STATE_UPDATE, + RPCSPEC07.SPEC.PENDING_STATE_UPDATE +>; + +// TODO: Can we remove all of this ? +/* export type INVOKE_TXN_RECEIPT = IsInBlock>; +export type DECLARE_TXN_RECEIPT = IsInBlock>; +export type DEPLOY_ACCOUNT_TXN_RECEIPT = IsInBlock< + RPCSPEC08.IsType +>; +export type L1_HANDLER_TXN_RECEIPT = IsInBlock>; */ + +export type PENDING_INVOKE_TXN_RECEIPT = RPCSPEC08.IsPending< + RPCSPEC08.IsType +>; +export type PENDING_DECLARE_TXN_RECEIPT = RPCSPEC08.IsPending< + RPCSPEC08.IsType +>; +export type PENDING_DEPLOY_ACCOUNT_TXN_RECEIPT = RPCSPEC08.IsPending< + RPCSPEC08.IsType +>; +export type PENDING_L1_HANDLER_TXN_RECEIPT = RPCSPEC08.IsPending< + RPCSPEC08.IsType +>; +// + +export type BlockWithTxHashes = Merge; +export type ContractClassPayload = Merge; +export type DeclaredTransaction = Merge< + RPCSPEC08.DeclaredTransaction, + RPCSPEC07.DeclaredTransaction +>; +export type InvokedTransaction = Merge; +export type DeployedAccountTransaction = Merge< + RPCSPEC08.DeployedAccountTransaction, + RPCSPEC07.DeployedAccountTransaction +>; + +export type L1Message = Merge; +export type EventFilter = RPCSPEC08.EventFilter; +export type L1_HANDLER_TXN = RPCSPEC08.L1_HANDLER_TXN; +export type EDataAvailabilityMode = RPCSPEC08.EDataAvailabilityMode; +export const { EDataAvailabilityMode } = RPCSPEC08; +export type EDAMode = RPCSPEC08.EDAMode; +export const { EDAMode } = RPCSPEC08; +export type EmittedEvent = Merge; +export type Event = Merge; + +export type PendingReceipt = Merge< + RPCSPEC08.TransactionReceiptPendingBlock, + RPCSPEC07.PendingReceipt +>; +export type Receipt = Merge; + +// One of +export type FeeEstimate = SimpleOneOf; + +export function isRPC08_FeeEstimate(entry: FeeEstimate): entry is RPCSPEC08.FEE_ESTIMATE { + return 'l1_data_gas_consumed' in entry; +} + +// One of +export type ResourceBounds = Simplify< + SimpleOneOf +>; + +export function isRPC08_ResourceBounds(entry: ResourceBounds): entry is RPCSPEC08.ResourceBounds { + return 'l1_data_gas' in entry; +} + +/** + * overhead percentage on estimate fee + */ +export type ResourceBoundsOverhead = ResourceBoundsOverheadRPC08 | ResourceBoundsOverheadRPC07; + +/** + * percentage overhead on estimated fee + */ +export type ResourceBoundsOverheadRPC08 = { + l1_gas: { + max_amount: number; + max_price_per_unit: number; + }; + l2_gas: { + max_amount: number; + max_price_per_unit: number; + }; + l1_data_gas: { + max_amount: number; + max_price_per_unit: number; + }; +}; + +export type ResourceBoundsOverheadRPC07 = { + l1_gas: { + max_amount: number; + max_price_per_unit: number; + }; +}; + +// TODO: ja mislin da types-js rpc 0.7 ima krivu definiciju za transaction trace +export type SimulateTransaction = RPCSPEC08.SimulateTransaction; + +export type TransactionWithHash = Merge< + RPCSPEC08.TransactionWithHash, + RPCSPEC07.TransactionWithHash +>; + +export type TransactionReceipt = Merge; +export type Methods = RPCSPEC08.Methods; +export type TXN_STATUS = Merge; +export type TXN_EXECUTION_STATUS = Merge< + RPCSPEC08.TXN_EXECUTION_STATUS, + RPCSPEC07.SPEC.TXN_EXECUTION_STATUS +>; +export type TransactionStatus = Merge; +export type ETransactionStatus = RPCSPEC08.ETransactionStatus; +export const { ETransactionStatus } = RPCSPEC08; +export type ETransactionExecutionStatus = RPCSPEC08.ETransactionExecutionStatus; +export const { ETransactionExecutionStatus } = RPCSPEC08; +export type TRANSACTION_TRACE = Merge< + RPCSPEC08.TRANSACTION_TRACE, + RPCSPEC07.SPEC.TRANSACTION_TRACE +>; +export type FEE_ESTIMATE = Merge; +export type EVENTS_CHUNK = Merge; diff --git a/src/signer/ledgerSigner111.ts b/src/signer/ledgerSigner111.ts index 317b70f30..e4c88ed2d 100644 --- a/src/signer/ledgerSigner111.ts +++ b/src/signer/ledgerSigner111.ts @@ -18,7 +18,6 @@ import assert from '../utils/assert'; import { CallData } from '../utils/calldata'; import type { SignerInterface } from './interface'; import { MASK_31 } from '../global/constants'; -import { ETransactionVersion2 } from '../types/api/rpcspec_0_6'; import { getMessageHash } from '../utils/typedData'; import { getExecuteCalldata } from '../utils/transaction'; import { @@ -30,7 +29,7 @@ import { intDAM } from '../utils/stark'; import { addHexPrefix, buf2hex, concatenateArrayBuffer, removeHexPrefix } from '../utils/encode'; import { hexToBytes, stringToSha256ToArrayBuff4, toHex } from '../utils/num'; import { starkCurve } from '../utils/ec'; -import { ETransactionVersion3 } from '../types/api'; +import { ETransactionVersion2, ETransactionVersion3 } from '../types/api'; // import type _Transport from '@ledgerhq/hw-transport'; // NOTE: the preceding line was substituted because of the '@ledgerhq/hw-transport' module bug listed in diff --git a/src/signer/ledgerSigner221.ts b/src/signer/ledgerSigner221.ts index 4d548cb1c..5b9d569d1 100644 --- a/src/signer/ledgerSigner221.ts +++ b/src/signer/ledgerSigner221.ts @@ -18,7 +18,6 @@ import assert from '../utils/assert'; import { CallData } from '../utils/calldata'; import type { SignerInterface } from './interface'; import { HARDENING_4BYTES, HARDENING_BYTE } from '../global/constants'; -import { ETransactionVersion2 } from '../types/api/rpcspec_0_6'; import { getExecuteCalldata } from '../utils/transaction'; import { calculateDeployAccountTransactionHash, @@ -29,7 +28,12 @@ import { intDAM } from '../utils/stark'; import { addHexPrefix, buf2hex, concatenateArrayBuffer, removeHexPrefix } from '../utils/encode'; import { hexToBytes, stringToSha256ToArrayBuff4, toBigInt, toHex } from '../utils/num'; import { starkCurve } from '../utils/ec'; -import { EDAMode, EDataAvailabilityMode, ETransactionVersion3 } from '../types/api'; +import { + EDAMode, + EDataAvailabilityMode, + ETransactionVersion2, + ETransactionVersion3, +} from '../types/api'; import { addAddressPadding } from '../utils/address'; import { encodeResourceBoundsL1, diff --git a/src/types/account.ts b/src/types/account.ts index 2a6022844..38efe308b 100644 --- a/src/types/account.ts +++ b/src/types/account.ts @@ -1,4 +1,4 @@ -import { EDataAvailabilityMode, ETransactionVersion, ResourceBounds } from './api'; +import { EDataAvailabilityMode, ETransactionVersion } from './api'; import { AllowArray, BigNumberish, @@ -10,7 +10,11 @@ import { UniversalDeployerContractPayload, V3TransactionDetails, } from './lib'; -import { DeclareTransactionReceiptResponse, EstimateFeeResponse } from './provider'; +import { + DeclareTransactionReceiptResponse, + EstimateFeeResponse, +} from '../provider/types/index.type'; +import { ResourceBounds } from '../provider/types/spec.type'; export interface EstimateFee extends EstimateFeeResponse {} diff --git a/src/types/api/index.ts b/src/types/api/index.ts index fce1535a3..cadb67b66 100644 --- a/src/types/api/index.ts +++ b/src/types/api/index.ts @@ -1,5 +1,8 @@ export * as JRPC from './jsonrpc'; -export * as RPCSPEC06 from './rpcspec_0_6'; export * as RPCSPEC07 from 'starknet-types-07'; -export * from 'starknet-types-07'; +export * as RPCSPEC08 from 'starknet-types-08'; + +// export * from 'starknet-types-08'; +// TODO: Should this be default export type as RPCSPEC07 & RPCSPEC08 are sued only in channel rest of the code do not know what rpc version it works with and it can be both. +export * from '../../provider/types/spec.type'; diff --git a/src/types/api/rpcspec_0_6/components.ts b/src/types/api/rpcspec_0_6/components.ts deleted file mode 100644 index bf7bd4dd7..000000000 --- a/src/types/api/rpcspec_0_6/components.ts +++ /dev/null @@ -1,672 +0,0 @@ -/** - * PRIMITIVES - */ - -/** - * A field element. represented by at most 63 hex digits - * @pattern ^0x(0|[a-fA-F1-9]{1}[a-fA-F0-9]{0,62})$ - */ -export type FELT = string; -/** - * an ethereum address represented as 40 hex digits - * @pattern ^0x[a-fA-F0-9]{40}$ - */ -export type ETH_ADDRESS = string; -/** - * A storage key. Represented as up to 62 hex digits, 3 bits, and 5 leading zeroes. - * @pattern ^0x0[0-7]{1}[a-fA-F0-9]{0,62}$ - */ -export type STORAGE_KEY = string; -export type ADDRESS = FELT; -export type NUM_AS_HEX = string; -/** - * 64 bit integers, represented by hex string of length at most 16 - * "pattern": "^0x(0|[a-fA-F1-9]{1}[a-fA-F0-9]{0,15})$" - */ -export type u64 = string; -/** - * 64 bit integers, represented by hex string of length at most 32 - * "pattern": "^0x(0|[a-fA-F1-9]{1}[a-fA-F0-9]{0,31})$" - */ -export type u128 = string; -export type SIGNATURE = Array; -export type BLOCK_NUMBER = number; -export type BLOCK_HASH = FELT; -export type TXN_HASH = FELT; -export type CHAIN_ID = NUM_AS_HEX; -export type STRUCT_ABI_TYPE = 'struct'; -export type EVENT_ABI_TYPE = 'event'; -export type FUNCTION_ABI_TYPE = 'function' | 'l1_handler' | 'constructor'; -// Represents the type of an entry point. -export type ENTRY_POINT_TYPE = 'EXTERNAL' | 'L1_HANDLER' | 'CONSTRUCTOR'; -// Represents the type of a function call. -export type CALL_TYPE = 'DELEGATE' | 'LIBRARY_CALL' | 'CALL'; -// Represents the status of the transaction -export type TXN_STATUS = 'RECEIVED' | 'REJECTED' | 'ACCEPTED_ON_L2' | 'ACCEPTED_ON_L1'; -// Flags that indicate how to simulate a given transaction. By default, the sequencer behavior is replicated locally (enough funds are expected to be in the account, and the fee will be deducted from the balance before the simulation of the next transaction). To skip the fee charge, use the SKIP_FEE_CHARGE flag. -export type SIMULATION_FLAG = 'SKIP_VALIDATE' | 'SKIP_FEE_CHARGE'; -// Data availability mode -export type DA_MODE = 'L1' | 'L2'; -export type TXN_TYPE = 'DECLARE' | 'DEPLOY' | 'DEPLOY_ACCOUNT' | 'INVOKE' | 'L1_HANDLER'; -export type TXN_FINALITY_STATUS = 'ACCEPTED_ON_L2' | 'ACCEPTED_ON_L1'; -export type TXN_EXECUTION_STATUS = 'SUCCEEDED' | 'REVERTED'; -export type BLOCK_STATUS = 'PENDING' | 'ACCEPTED_ON_L2' | 'ACCEPTED_ON_L1' | 'REJECTED'; -export type BLOCK_TAG = 'latest' | 'pending'; - -/** - * READ API - */ - -export type EVENTS_CHUNK = { - // Returns matching events - events: EMITTED_EVENT[]; - // Use this token in a subsequent query to obtain the next page. Should not appear if there are no more pages. - continuation_token?: string; -}; - -export type RESULT_PAGE_REQUEST = { - // The token returned from the previous query. If no token is provided the first page is returned. - continuation_token?: string; - // Chunk size - chunk_size: number; -}; - -export type EMITTED_EVENT = EVENT & { - block_hash: BLOCK_HASH; - block_number: BLOCK_NUMBER; - transaction_hash: TXN_HASH; -}; - -export type EVENT = { - from_address: ADDRESS; -} & EVENT_CONTENT; - -export type EVENT_CONTENT = { - keys: FELT[]; - data: FELT[]; -}; - -export type EVENT_FILTER = { - from_block?: BLOCK_ID; - to_block?: BLOCK_ID; - address?: ADDRESS; - keys?: FELT[][]; -}; - -export type BLOCK_ID = - | { - block_hash?: BLOCK_HASH; - block_number?: BLOCK_NUMBER; - } - | BLOCK_TAG; - -export type SYNC_STATUS = { - starting_block_hash: BLOCK_HASH; - starting_block_num: BLOCK_NUMBER; - current_block_hash: BLOCK_HASH; - current_block_num: BLOCK_NUMBER; - highest_block_hash: BLOCK_HASH; - highest_block_num: BLOCK_NUMBER; -}; - -export type NEW_CLASSES = { - class_hash: FELT; - compiled_class_hash: FELT; -}; - -export type REPLACED_CLASS = { - class_hash: FELT; - contract_address: FELT; -}; - -export type NONCE_UPDATE = { - contract_address: ADDRESS; - nonce: FELT; -}; - -export type STATE_DIFF = { - storage_diffs: CONTRACT_STORAGE_DIFF_ITEM[]; - deprecated_declared_classes: FELT[]; - declared_classes: NEW_CLASSES[]; - deployed_contracts: DEPLOYED_CONTRACT_ITEM[]; - replaced_classes: REPLACED_CLASS[]; - nonces: NONCE_UPDATE[]; -}; - -export type PENDING_STATE_UPDATE = { - old_root: FELT; - state_diff: STATE_DIFF; - block_hash: never; // diverge: this makes it distinct -}; - -export type STATE_UPDATE = { - block_hash: BLOCK_HASH; - old_root: FELT; - new_root: FELT; - state_diff: STATE_DIFF; -}; - -export type BLOCK_BODY_WITH_TX_HASHES = { - transactions: TXN_HASH[]; -}; - -export type BLOCK_BODY_WITH_TXS = { - transactions: (TXN & { - transaction_hash: TXN_HASH; - })[]; -}; - -export type BLOCK_HEADER = { - block_hash: BLOCK_HASH; - parent_hash: BLOCK_HASH; - block_number: BLOCK_NUMBER; - new_root: FELT; - timestamp: number; - sequencer_address: FELT; - l1_gas_price: RESOURCE_PRICE; - starknet_version: string; -}; - -export type PENDING_BLOCK_HEADER = { - parent_hash: BLOCK_HASH; - timestamp: number; - sequencer_address: FELT; - l1_gas_price: RESOURCE_PRICE; - starknet_version: string; -}; - -export type BLOCK_WITH_TX_HASHES = { status: BLOCK_STATUS } & BLOCK_HEADER & - BLOCK_BODY_WITH_TX_HASHES; - -export type BLOCK_WITH_TXS = { status: BLOCK_STATUS } & BLOCK_HEADER & BLOCK_BODY_WITH_TXS; - -export type PENDING_BLOCK_WITH_TX_HASHES = BLOCK_BODY_WITH_TX_HASHES & PENDING_BLOCK_HEADER; - -export type PENDING_BLOCK_WITH_TXS = BLOCK_BODY_WITH_TXS & PENDING_BLOCK_HEADER; - -export type DEPLOYED_CONTRACT_ITEM = { - address: FELT; - class_hash: FELT; -}; - -export type CONTRACT_STORAGE_DIFF_ITEM = { - // The contract address for which the storage changed (in FELT format) - address: string; - // The changes in the storage of the contract - storage_entries: StorageDiffItem[]; -}; - -export type StorageDiffItem = { - // The key of the changed value (in FELT format) - key: string; - // The new value applied to the given address (in FELT format) - value: string; -}; - -export type TXN = INVOKE_TXN | L1_HANDLER_TXN | DECLARE_TXN | DEPLOY_TXN | DEPLOY_ACCOUNT_TXN; - -export type DECLARE_TXN = DECLARE_TXN_V0 | DECLARE_TXN_V1 | DECLARE_TXN_V2 | DECLARE_TXN_V3; - -export type DECLARE_TXN_V0 = { - type: 'DECLARE'; - sender_address: ADDRESS; - max_fee: FELT; - version: '0x0' | '0x100000000000000000000000000000000'; - signature: SIGNATURE; - class_hash: FELT; -}; - -export type DECLARE_TXN_V1 = { - type: 'DECLARE'; - sender_address: ADDRESS; - max_fee: FELT; - version: '0x1' | '0x100000000000000000000000000000001'; - signature: SIGNATURE; - nonce: FELT; - class_hash: FELT; -}; - -export type DECLARE_TXN_V2 = { - type: 'DECLARE'; - sender_address: ADDRESS; - compiled_class_hash: FELT; - max_fee: FELT; - version: '0x2' | '0x100000000000000000000000000000002'; - signature: SIGNATURE; - nonce: FELT; - class_hash: FELT; -}; - -export type DECLARE_TXN_V3 = { - type: 'DECLARE'; - sender_address: ADDRESS; - compiled_class_hash: FELT; - version: '0x3' | '0x100000000000000000000000000000003'; - signature: SIGNATURE; - nonce: FELT; - class_hash: FELT; - // new... - resource_bounds: RESOURCE_BOUNDS_MAPPING; - tip: u64; - paymaster_data: FELT[]; - account_deployment_data: FELT[]; - nonce_data_availability_mode: DA_MODE; - fee_data_availability_mode: DA_MODE; -}; - -export type BROADCASTED_TXN = - | BROADCASTED_INVOKE_TXN - | BROADCASTED_DECLARE_TXN - | BROADCASTED_DEPLOY_ACCOUNT_TXN; - -export type BROADCASTED_INVOKE_TXN = INVOKE_TXN; - -export type BROADCASTED_DEPLOY_ACCOUNT_TXN = DEPLOY_ACCOUNT_TXN; - -export type BROADCASTED_DECLARE_TXN = - | BROADCASTED_DECLARE_TXN_V1 - | BROADCASTED_DECLARE_TXN_V2 - | BROADCASTED_DECLARE_TXN_V3; - -export type BROADCASTED_DECLARE_TXN_V1 = { - type: 'DECLARE'; - sender_address: ADDRESS; - max_fee: FELT; - // todo: check if working, prev i fixed it with NUM_AS_HEX - version: '0x1' | '0x100000000000000000000000000000001'; - signature: SIGNATURE; - nonce: FELT; - contract_class: DEPRECATED_CONTRACT_CLASS; -}; - -export type BROADCASTED_DECLARE_TXN_V2 = { - type: 'DECLARE'; - sender_address: ADDRESS; - compiled_class_hash: FELT; - max_fee: FELT; - version: '0x2' | '0x100000000000000000000000000000002'; - signature: SIGNATURE; - nonce: FELT; - contract_class: CONTRACT_CLASS; -}; - -export type BROADCASTED_DECLARE_TXN_V3 = { - type: 'DECLARE'; - sender_address: ADDRESS; - compiled_class_hash: FELT; - version: '0x3' | '0x100000000000000000000000000000003'; - signature: SIGNATURE; - nonce: FELT; - contract_class: CONTRACT_CLASS; - // new... - resource_bounds: RESOURCE_BOUNDS_MAPPING; - tip: u64; - paymaster_data: FELT[]; - account_deployment_data: FELT[]; - nonce_data_availability_mode: DA_MODE; - fee_data_availability_mode: DA_MODE; -}; - -export type DEPLOY_ACCOUNT_TXN = DEPLOY_ACCOUNT_TXN_V1 | DEPLOY_ACCOUNT_TXN_V3; - -export type DEPLOY_ACCOUNT_TXN_V1 = { - type: 'DEPLOY_ACCOUNT'; - max_fee: FELT; - version: '0x1' | '0x100000000000000000000000000000001'; - signature: SIGNATURE; - nonce: FELT; - contract_address_salt: FELT; - constructor_calldata: FELT[]; - class_hash: FELT; -}; - -export type DEPLOY_ACCOUNT_TXN_V3 = { - type: 'DEPLOY_ACCOUNT'; - version: '0x3' | '0x100000000000000000000000000000003'; - signature: SIGNATURE; - nonce: FELT; - contract_address_salt: FELT; - constructor_calldata: FELT[]; - class_hash: FELT; - resource_bounds: RESOURCE_BOUNDS_MAPPING; - tip: u64; - paymaster_data: FELT[]; - nonce_data_availability_mode: DA_MODE; - fee_data_availability_mode: DA_MODE; -}; - -export type DEPLOY_TXN = { - type: 'DEPLOY'; - version: FELT; - contract_address_salt: FELT; - constructor_calldata: FELT[]; - class_hash: FELT; -}; - -export type INVOKE_TXN = INVOKE_TXN_V0 | INVOKE_TXN_V1 | INVOKE_TXN_V3; - -export type INVOKE_TXN_V0 = { - type: 'INVOKE'; - max_fee: FELT; - version: '0x0' | '0x100000000000000000000000000000000'; - signature: SIGNATURE; - contract_address: ADDRESS; - entry_point_selector: FELT; - calldata: FELT[]; -}; - -export type INVOKE_TXN_V1 = { - type: 'INVOKE'; - sender_address: ADDRESS; - calldata: FELT[]; - max_fee: FELT; - version: '0x1' | '0x100000000000000000000000000000001'; - signature: SIGNATURE; - nonce: FELT; -}; - -export type INVOKE_TXN_V3 = { - type: 'INVOKE'; - sender_address: ADDRESS; - calldata: FELT[]; - version: '0x3' | '0x100000000000000000000000000000003'; - signature: SIGNATURE; - nonce: FELT; - resource_bounds: RESOURCE_BOUNDS_MAPPING; - tip: u64; - paymaster_data: FELT[]; - account_deployment_data: FELT[]; - nonce_data_availability_mode: DA_MODE; - fee_data_availability_mode: DA_MODE; -}; - -export type L1_HANDLER_TXN = { - version: FELT; - type: 'L1_HANDLER'; - nonce: NUM_AS_HEX; -} & FUNCTION_CALL; - -export type COMMON_RECEIPT_PROPERTIES = { - transaction_hash: TXN_HASH; - actual_fee: FEE_PAYMENT; - execution_status: TXN_EXECUTION_STATUS; - finality_status: TXN_FINALITY_STATUS; - block_hash: BLOCK_HASH; - block_number: BLOCK_NUMBER; - messages_sent: MSG_TO_L1[]; - revert_reason?: string; - events: EVENT[]; - execution_resources: EXECUTION_RESOURCES; -}; - -export type PENDING_COMMON_RECEIPT_PROPERTIES = { - transaction_hash: TXN_HASH; - actual_fee: FEE_PAYMENT; - messages_sent: MSG_TO_L1[]; - events: EVENT[]; - revert_reason?: string; - finality_status: 'ACCEPTED_ON_L2'; - execution_status: TXN_EXECUTION_STATUS; - execution_resources: EXECUTION_RESOURCES; -}; - -export type INVOKE_TXN_RECEIPT = { - type: 'INVOKE'; -} & COMMON_RECEIPT_PROPERTIES; - -export type PENDING_INVOKE_TXN_RECEIPT = { - type: 'INVOKE'; -} & PENDING_COMMON_RECEIPT_PROPERTIES; - -export type DECLARE_TXN_RECEIPT = { - type: 'DECLARE'; -} & COMMON_RECEIPT_PROPERTIES; - -export type PENDING_DECLARE_TXN_RECEIPT = { - type: 'DECLARE'; -} & PENDING_COMMON_RECEIPT_PROPERTIES; - -export type DEPLOY_ACCOUNT_TXN_RECEIPT = { - type: 'DEPLOY_ACCOUNT'; - contract_address: FELT; -} & COMMON_RECEIPT_PROPERTIES; - -export type PENDING_DEPLOY_ACCOUNT_TXN_RECEIPT = { - type: 'DEPLOY_ACCOUNT'; - contract_address: FELT; -} & PENDING_COMMON_RECEIPT_PROPERTIES; - -export type DEPLOY_TXN_RECEIPT = { - type: 'DEPLOY'; - contract_address: FELT; -} & COMMON_RECEIPT_PROPERTIES; - -export type L1_HANDLER_TXN_RECEIPT = { - type: 'L1_HANDLER'; - message_hash: NUM_AS_HEX; -} & COMMON_RECEIPT_PROPERTIES; - -export type PENDING_L1_HANDLER_TXN_RECEIPT = { - type: 'L1_HANDLER'; - message_hash: NUM_AS_HEX; -} & PENDING_COMMON_RECEIPT_PROPERTIES; - -export type TXN_RECEIPT = - | INVOKE_TXN_RECEIPT - | L1_HANDLER_TXN_RECEIPT - | DECLARE_TXN_RECEIPT - | DEPLOY_TXN_RECEIPT - | DEPLOY_ACCOUNT_TXN_RECEIPT; - -export type PENDING_TXN_RECEIPT = - | PENDING_INVOKE_TXN_RECEIPT - | PENDING_L1_HANDLER_TXN_RECEIPT - | PENDING_DECLARE_TXN_RECEIPT - | PENDING_DEPLOY_ACCOUNT_TXN_RECEIPT; - -export type MSG_TO_L1 = { - from_address: FELT; - to_address: FELT; - payload: FELT[]; -}; - -export type MSG_FROM_L1 = { - from_address: ETH_ADDRESS; - to_address: ADDRESS; - entry_point_selector: FELT; - payload: FELT[]; -}; - -export type FUNCTION_CALL = { - contract_address: ADDRESS; - entry_point_selector: FELT; - calldata: FELT[]; -}; - -export type CONTRACT_CLASS = { - sierra_program: FELT[]; - contract_class_version: string; - entry_points_by_type: { - CONSTRUCTOR: SIERRA_ENTRY_POINT[]; - EXTERNAL: SIERRA_ENTRY_POINT[]; - L1_HANDLER: SIERRA_ENTRY_POINT[]; - }; - abi: string; -}; - -export type DEPRECATED_CONTRACT_CLASS = { - program: string; - entry_points_by_type: { - CONSTRUCTOR: DEPRECATED_CAIRO_ENTRY_POINT[]; - EXTERNAL: DEPRECATED_CAIRO_ENTRY_POINT[]; - L1_HANDLER: DEPRECATED_CAIRO_ENTRY_POINT[]; - }; - abi: CONTRACT_ABI; -}; - -export type DEPRECATED_CAIRO_ENTRY_POINT = { - offset: NUM_AS_HEX | number; - selector: FELT; -}; - -export type SIERRA_ENTRY_POINT = { - selector: FELT; - function_idx: number; -}; - -export type CONTRACT_ABI = readonly CONTRACT_ABI_ENTRY[]; - -export type CONTRACT_ABI_ENTRY = { - selector: FELT; - input: string; - output: string; -}; - -export type STRUCT_ABI_ENTRY = { - type: STRUCT_ABI_TYPE; - name: string; - size: number; - members: STRUCT_MEMBER[]; -}; - -export type STRUCT_MEMBER = TYPED_PARAMETER & { - offset: number; -}; - -export type EVENT_ABI_ENTRY = { - type: EVENT_ABI_TYPE; - name: string; - keys: TYPED_PARAMETER[]; - data: TYPED_PARAMETER[]; -}; - -export type FUNCTION_STATE_MUTABILITY = 'view'; - -export type FUNCTION_ABI_ENTRY = { - type: FUNCTION_ABI_TYPE; - name: string; - inputs: TYPED_PARAMETER[]; - outputs: TYPED_PARAMETER[]; - stateMutability: FUNCTION_STATE_MUTABILITY; -}; - -export type TYPED_PARAMETER = { - name: string; - type: string; -}; - -export type SIMULATION_FLAG_FOR_ESTIMATE_FEE = 'SKIP_VALIDATE'; -export type PRICE_UNIT = 'WEI' | 'FRI'; - -export type FEE_ESTIMATE = { - gas_consumed: FELT; - gas_price: FELT; - overall_fee: FELT; - unit: PRICE_UNIT; -}; - -export type FEE_PAYMENT = { - amount: FELT; - unit: PRICE_UNIT; -}; - -export type RESOURCE_BOUNDS_MAPPING = { - l1_gas: RESOURCE_BOUNDS; - l2_gas: RESOURCE_BOUNDS; -}; - -export type RESOURCE_BOUNDS = { - max_amount: u64; - max_price_per_unit: u128; -}; - -export type RESOURCE_PRICE = { - price_in_fri: FELT; - price_in_wei: FELT; -}; - -export type EXECUTION_RESOURCES = { - steps: number; - memory_holes?: number; - range_check_builtin_applications?: number; - pedersen_builtin_applications?: number; - poseidon_builtin_applications?: number; - ec_op_builtin_applications?: number; - ecdsa_builtin_applications?: number; - bitwise_builtin_applications?: number; - keccak_builtin_applications?: number; - segment_arena_builtin?: number; -}; - -/** - * TRACE API - */ - -// Represents a transaction trace including the execution details. -export type TRANSACTION_TRACE = { - invoke_tx_trace?: INVOKE_TXN_TRACE; - declare_tx_trace?: DECLARE_TXN_TRACE; - deploy_account_tx_trace?: DEPLOY_ACCOUNT_TXN_TRACE; - l1_handler_tx_trace?: L1_HANDLER_TXN_TRACE; -}; - -// Represents a transaction trace for an invoke transaction. -export type INVOKE_TXN_TRACE = { - type: 'INVOKE'; - execute_invocation: FUNCTION_INVOCATION | { revert_reason: string }; - validate_invocation?: FUNCTION_INVOCATION; - fee_transfer_invocation?: FUNCTION_INVOCATION; - state_diff?: STATE_DIFF; -}; - -// Represents a transaction trace for a declare transaction. -export type DECLARE_TXN_TRACE = { - type: 'DECLARE'; - validate_invocation?: FUNCTION_INVOCATION; - fee_transfer_invocation?: FUNCTION_INVOCATION; - state_diff?: STATE_DIFF; -}; - -// Represents a transaction trace for a deploy account transaction. -export type DEPLOY_ACCOUNT_TXN_TRACE = { - type: 'DEPLOY_ACCOUNT'; - constructor_invocation: FUNCTION_INVOCATION; - validate_invocation?: FUNCTION_INVOCATION; - fee_transfer_invocation?: FUNCTION_INVOCATION; - state_diff?: STATE_DIFF; -}; - -// Represents a transaction trace for an L1 handler transaction. -export type L1_HANDLER_TXN_TRACE = { - type: 'L1_HANDLER'; - function_invocation: FUNCTION_INVOCATION; - state_diff?: STATE_DIFF; -}; - -// Represents a nested function call. -export type NESTED_CALL = FUNCTION_INVOCATION; - -// Represents a function invocation along with its execution details. -export type FUNCTION_INVOCATION = FUNCTION_CALL & { - caller_address: string; - class_hash: string; - entry_point_type: ENTRY_POINT_TYPE; - call_type: CALL_TYPE; - result: string[]; - calls: NESTED_CALL[]; - events: ORDERED_EVENT[]; - messages: ORDERED_MESSAGE[]; - execution_resources: EXECUTION_RESOURCES; -}; - -// Represents an ordered event alongside its order within the transaction. -export type ORDERED_EVENT = { - order: number; - event: EVENT; -}; - -// Represents an ordered message alongside its order within the transaction. -export type ORDERED_MESSAGE = { - order: number; - message: MSG_TO_L1; -}; diff --git a/src/types/api/rpcspec_0_6/contract.ts b/src/types/api/rpcspec_0_6/contract.ts deleted file mode 100644 index e822c3fff..000000000 --- a/src/types/api/rpcspec_0_6/contract.ts +++ /dev/null @@ -1,98 +0,0 @@ -/** - * TypeScript Representation of Cairo1 v2+ Starknet Contract ABI - * - * starknet_metadata.json - tags/v0.5.0 - * - * 'starknet-specs' (OpenRpc protocol types) - * https://github.com/starkware-libs/starknet-specs - */ - -export type ABI = Array< - FUNCTION | CONSTRUCTOR | L1_HANDLER | EVENT | STRUCT | ENUM | INTERFACE | IMPL ->; - -type FUNCTION = { - type: 'function'; - name: string; - inputs: Array<{ - name: string; - type: string; - }>; - outputs?: Array<{ - type: string; - }>; - state_mutability: 'view' | 'external'; -}; - -type CONSTRUCTOR = { - type: 'constructor'; - name: 'constructor'; - inputs: Array<{ - name: string; - type: string; - }>; -}; - -type L1_HANDLER = { - type: 'l1_handler'; - name: string; - inputs: Array<{ - name: string; - type: string; - }>; - outputs?: Array<{ - type: string; - }>; - state_mutability: 'view' | 'external'; -}; - -type EVENT = { - type: 'event'; - name: string; -} & (ENUM_EVENT | STRUCT_EVENT); - -type STRUCT_EVENT = { - kind: 'struct'; - members: Array; -}; - -type ENUM_EVENT = { - kind: 'enum'; - variants: Array; -}; - -type STRUCT = { - type: 'struct'; - name: string; - members: Array<{ - name: string; - type: string; - }>; -}; - -type ENUM = { - type: 'enum'; - name: string; - variants: Array<{ - name: string; - type: string; - }>; -}; - -type INTERFACE = { - type: 'interface'; - name: string; - items: Array; -}; - -type IMPL = { - type: 'impl'; - name: string; - interface_name: string; -}; - -type EVENT_FIELD = { - name: string; - type: string; - kind: 'key' | 'data' | 'nested'; -}; diff --git a/src/types/api/rpcspec_0_6/errors.ts b/src/types/api/rpcspec_0_6/errors.ts deleted file mode 100644 index 68a3fb068..000000000 --- a/src/types/api/rpcspec_0_6/errors.ts +++ /dev/null @@ -1,156 +0,0 @@ -export interface FAILED_TO_RECEIVE_TXN { - code: 1; - message: 'Failed to write transaction'; -} - -export interface NO_TRACE_AVAILABLE { - code: 10; - message: 'No trace available for transaction'; - data: { - status: 'RECEIVED' | 'REJECTED'; - }; -} - -export interface CONTRACT_NOT_FOUND { - code: 20; - message: 'Contract not found'; -} - -export interface INVALID_MESSAGE_SELECTOR { - code: 21; - message: 'Invalid message selector'; -} - -export interface INVALID_CALL_DATA { - code: 22; - message: 'Invalid call data'; -} - -export interface BLOCK_NOT_FOUND { - code: 24; - message: 'Block not found'; -} - -export interface INVALID_BLOCK_HASH { - code: 26; - message: 'Invalid block hash'; -} - -export interface INVALID_TXN_INDEX { - code: 27; - message: 'Invalid transaction index in a block'; -} - -export interface CLASS_HASH_NOT_FOUND { - code: 28; - message: 'Class hash not found'; -} - -export interface TXN_HASH_NOT_FOUND { - code: 29; - message: 'Transaction hash not found'; -} - -export interface PAGE_SIZE_TOO_BIG { - code: 31; - message: 'Requested page size is too big'; -} - -export interface NO_BLOCKS { - code: 32; - message: 'There are no blocks'; -} - -export interface INVALID_CONTINUATION_TOKEN { - code: 33; - message: 'The supplied continuation token is invalid or unknown'; -} - -export interface TOO_MANY_KEYS_IN_FILTER { - code: 34; - message: 'Too many keys provided in a filter'; -} - -export interface CONTRACT_ERROR { - code: 40; - message: 'Contract error'; - data: { - revert_error: string; - }; -} - -export interface TRANSACTION_EXECUTION_ERROR { - code: 41; - message: 'Transaction execution error'; - data: { - transaction_index: number; - execution_error: string; - }; -} - -export interface CLASS_ALREADY_DECLARED { - code: 51; - message: 'Class already declared'; -} - -export interface INVALID_TRANSACTION_NONCE { - code: 52; - message: 'Invalid transaction nonce'; -} - -export interface INSUFFICIENT_MAX_FEE { - code: 53; - message: 'Max fee is smaller than the minimal transaction cost (validation plus fee transfer)'; -} - -export interface INSUFFICIENT_ACCOUNT_BALANCE { - code: 54; - message: "Account balance is smaller than the transaction's max_fee"; -} - -export interface VALIDATION_FAILURE { - code: 55; - message: 'Account validation failed'; - data: string; -} - -export interface COMPILATION_FAILED { - code: 56; - message: 'Compilation failed'; -} - -export interface CONTRACT_CLASS_SIZE_IS_TOO_LARGE { - code: 57; - message: 'Contract class size it too large'; -} - -export interface NON_ACCOUNT { - code: 58; - message: 'Sender address in not an account contract'; -} - -export interface DUPLICATE_TX { - code: 59; - message: 'A transaction with the same hash already exists in the mempool'; -} - -export interface COMPILED_CLASS_HASH_MISMATCH { - code: 60; - message: 'the compiled class hash did not match the one supplied in the transaction'; -} - -export interface UNSUPPORTED_TX_VERSION { - code: 61; - message: 'the transaction version is not supported'; -} - -export interface UNSUPPORTED_CONTRACT_CLASS_VERSION { - code: 62; - message: 'the contract class version is not supported'; -} - -export interface UNEXPECTED_ERROR { - code: 63; - message: 'An unexpected error occurred'; - data: string; -} diff --git a/src/types/api/rpcspec_0_6/index.ts b/src/types/api/rpcspec_0_6/index.ts deleted file mode 100644 index b9bf0f4db..000000000 --- a/src/types/api/rpcspec_0_6/index.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * version 0.6.0 - */ - -export * from './methods'; -export * from './contract'; -export * as Errors from './errors'; -export * as SPEC from './components'; -export * from './nonspec'; diff --git a/src/types/api/rpcspec_0_6/methods.ts b/src/types/api/rpcspec_0_6/methods.ts deleted file mode 100644 index 1f96c14b3..000000000 --- a/src/types/api/rpcspec_0_6/methods.ts +++ /dev/null @@ -1,330 +0,0 @@ -import { - ADDRESS, - BLOCK_ID, - BLOCK_NUMBER, - BROADCASTED_DECLARE_TXN, - BROADCASTED_DEPLOY_ACCOUNT_TXN, - BROADCASTED_INVOKE_TXN, - BROADCASTED_TXN, - CHAIN_ID, - EVENT_FILTER, - FELT, - FUNCTION_CALL, - MSG_FROM_L1, - RESULT_PAGE_REQUEST, - SIMULATION_FLAG, - SIMULATION_FLAG_FOR_ESTIMATE_FEE, - STORAGE_KEY, - TXN_HASH, -} from './components'; -import * as Errors from './errors'; -import { - BlockHashAndNumber, - BlockTransactionsTraces, - BlockWithTxHashes, - BlockWithTxs, - ContractClass, - DeclaredTransaction, - DeployedAccountTransaction, - Events, - FeeEstimate, - InvokedTransaction, - Nonce, - SimulateTransactionResponse, - StateUpdate, - Syncing, - TransactionReceipt, - TransactionStatus, - TransactionTrace, - TransactionWithHash, -} from './nonspec'; - -type ReadMethods = { - // Returns the version of the Starknet JSON-RPC specification being used - starknet_specVersion: { - params: []; - result: string; - }; - - // Get block information with transaction hashes given the block id - starknet_getBlockWithTxHashes: { - params: { - block_id: BLOCK_ID; - }; - result: BlockWithTxHashes; - errors: Errors.BLOCK_NOT_FOUND; - }; - - // Get block information with full transactions given the block id - starknet_getBlockWithTxs: { - params: { - block_id: BLOCK_ID; - }; - result: BlockWithTxs; - errors: Errors.BLOCK_NOT_FOUND; - }; - - // Get the information about the result of executing the requested block - starknet_getStateUpdate: { - params: { - block_id: BLOCK_ID; - }; - result: StateUpdate; - errors: Errors.BLOCK_NOT_FOUND; - }; - - // Get the value of the storage at the given address and key - starknet_getStorageAt: { - params: { - contract_address: ADDRESS; - key: STORAGE_KEY; - block_id: BLOCK_ID; - }; - result: FELT; - errors: Errors.CONTRACT_NOT_FOUND | Errors.BLOCK_NOT_FOUND; - }; - - // Gets the transaction status (possibly reflecting that the tx is still in the mempool, or dropped from it) - starknet_getTransactionStatus: { - params: { - transaction_hash: TXN_HASH; - }; - result: TransactionStatus; - errors: Errors.TXN_HASH_NOT_FOUND; - }; - - // Get the details and status of a submitted transaction - starknet_getTransactionByHash: { - params: { - transaction_hash: TXN_HASH; - }; - result: TransactionWithHash; - errors: Errors.TXN_HASH_NOT_FOUND; - }; - - // Get the details of a transaction by a given block id and index - starknet_getTransactionByBlockIdAndIndex: { - params: { - block_id: BLOCK_ID; - index: number; - }; - result: TransactionWithHash; - errors: Errors.BLOCK_NOT_FOUND | Errors.INVALID_TXN_INDEX; - }; - - // Get the transaction receipt by the transaction hash - starknet_getTransactionReceipt: { - params: { - transaction_hash: TXN_HASH; - }; - result: TransactionReceipt; - errors: Errors.TXN_HASH_NOT_FOUND; - }; - - // Get the contract class definition in the given block associated with the given hash - starknet_getClass: { - params: { - block_id: BLOCK_ID; - class_hash: FELT; - }; - result: ContractClass; - errors: Errors.BLOCK_NOT_FOUND | Errors.CLASS_HASH_NOT_FOUND; - }; - - // Get the contract class hash in the given block for the contract deployed at the given address - starknet_getClassHashAt: { - params: { - block_id: BLOCK_ID; - contract_address: ADDRESS; - }; - result: FELT; - errors: Errors.BLOCK_NOT_FOUND | Errors.CONTRACT_NOT_FOUND; - }; - - // Get the contract class definition in the given block at the given address - starknet_getClassAt: { - params: { - block_id: BLOCK_ID; - contract_address: ADDRESS; - }; - result: ContractClass; - errors: Errors.BLOCK_NOT_FOUND | Errors.CONTRACT_NOT_FOUND; - }; - - // Get the number of transactions in a block given a block id - starknet_getBlockTransactionCount: { - params: { - block_id: BLOCK_ID; - }; - result: number; - errors: Errors.BLOCK_NOT_FOUND; - }; - - // Call a Starknet function without creating a Starknet transaction - starknet_call: { - params: { - request: FUNCTION_CALL; - block_id: BLOCK_ID; - }; - result: FELT[]; - errors: Errors.CONTRACT_NOT_FOUND | Errors.CONTRACT_ERROR | Errors.BLOCK_NOT_FOUND; - }; - - // Estimate the fee for Starknet transactions - starknet_estimateFee: { - params: { - request: BROADCASTED_TXN[]; - simulation_flags?: [SIMULATION_FLAG_FOR_ESTIMATE_FEE] | []; // Diverged from spec (0.5 can't be, 0.6 must be) - block_id: BLOCK_ID; - }; - result: FeeEstimate[]; - errors: Errors.TRANSACTION_EXECUTION_ERROR | Errors.BLOCK_NOT_FOUND; - }; - - // Estimate the L2 fee of a message sent on L1 - starknet_estimateMessageFee: { - params: { - message: MSG_FROM_L1; - block_id: BLOCK_ID; - }; - result: FeeEstimate; - errors: Errors.CONTRACT_ERROR | Errors.BLOCK_NOT_FOUND; - }; - - // Get the most recent accepted block number - starknet_blockNumber: { - params: []; - result: BLOCK_NUMBER; - errors: Errors.NO_BLOCKS; - }; - - // Get the most recent accepted block hash and number - starknet_blockHashAndNumber: { - params: []; - result: BlockHashAndNumber; - errors: Errors.NO_BLOCKS; - }; - - // Return the currently configured Starknet chain id - starknet_chainId: { - params: []; - result: CHAIN_ID; - }; - - // Returns an object about the sync status, or false if the node is not syncing - starknet_syncing: { - params: []; - result: Syncing; - }; - - // Returns all events matching the given filter - starknet_getEvents: { - params: { - filter: EVENT_FILTER & RESULT_PAGE_REQUEST; - }; - result: Events; - errors: - | Errors.PAGE_SIZE_TOO_BIG - | Errors.INVALID_CONTINUATION_TOKEN - | Errors.BLOCK_NOT_FOUND - | Errors.TOO_MANY_KEYS_IN_FILTER; - }; - - // Get the nonce associated with the given address in the given block - starknet_getNonce: { - params: { - block_id: BLOCK_ID; - contract_address: ADDRESS; - }; - result: Nonce; - errors: Errors.BLOCK_NOT_FOUND | Errors.CONTRACT_NOT_FOUND; - }; -}; - -type WriteMethods = { - // Submit a new transaction to be added to the chain - starknet_addInvokeTransaction: { - params: { - invoke_transaction: BROADCASTED_INVOKE_TXN; - }; - result: InvokedTransaction; - errors: - | Errors.INSUFFICIENT_ACCOUNT_BALANCE - | Errors.INSUFFICIENT_MAX_FEE - | Errors.INVALID_TRANSACTION_NONCE - | Errors.VALIDATION_FAILURE - | Errors.NON_ACCOUNT - | Errors.DUPLICATE_TX - | Errors.UNSUPPORTED_TX_VERSION - | Errors.UNEXPECTED_ERROR; - }; - - // Submit a new class declaration transaction - starknet_addDeclareTransaction: { - params: { - declare_transaction: BROADCASTED_DECLARE_TXN; - }; - result: DeclaredTransaction; - errors: - | Errors.CLASS_ALREADY_DECLARED - | Errors.COMPILATION_FAILED - | Errors.COMPILED_CLASS_HASH_MISMATCH - | Errors.INSUFFICIENT_ACCOUNT_BALANCE - | Errors.INSUFFICIENT_MAX_FEE - | Errors.INVALID_TRANSACTION_NONCE - | Errors.VALIDATION_FAILURE - | Errors.NON_ACCOUNT - | Errors.DUPLICATE_TX - | Errors.CONTRACT_CLASS_SIZE_IS_TOO_LARGE - | Errors.UNSUPPORTED_TX_VERSION - | Errors.UNSUPPORTED_CONTRACT_CLASS_VERSION - | Errors.UNEXPECTED_ERROR; - }; - - // Submit a new deploy account transaction - starknet_addDeployAccountTransaction: { - params: { - deploy_account_transaction: BROADCASTED_DEPLOY_ACCOUNT_TXN; - }; - result: DeployedAccountTransaction; - errors: - | Errors.INSUFFICIENT_ACCOUNT_BALANCE - | Errors.INSUFFICIENT_MAX_FEE - | Errors.INVALID_TRANSACTION_NONCE - | Errors.VALIDATION_FAILURE - | Errors.NON_ACCOUNT - | Errors.CLASS_HASH_NOT_FOUND - | Errors.DUPLICATE_TX - | Errors.UNSUPPORTED_TX_VERSION - | Errors.UNEXPECTED_ERROR; - }; -}; - -type TraceMethods = { - // For a given executed transaction, return the trace of its execution, including internal calls - starknet_traceTransaction: { - params: { transaction_hash: TXN_HASH }; - result: TransactionTrace; - errors: Errors.TXN_HASH_NOT_FOUND | Errors.NO_TRACE_AVAILABLE; - }; - - // Returns the execution traces of all transactions included in the given block - starknet_traceBlockTransactions: { - params: { block_id: BLOCK_ID }; - result: BlockTransactionsTraces; - errors: Errors.BLOCK_NOT_FOUND; - }; - - // Simulate a given sequence of transactions on the requested state, and generate the execution traces. If one of the transactions is reverted, raises CONTRACT_ERROR - starknet_simulateTransactions: { - params: { - block_id: BLOCK_ID; - transactions: Array; - simulation_flags: Array; - }; - result: SimulateTransactionResponse; - errors: Errors.BLOCK_NOT_FOUND | Errors.TRANSACTION_EXECUTION_ERROR; - }; -}; - -export type Methods = ReadMethods & WriteMethods & TraceMethods; diff --git a/src/types/api/rpcspec_0_6/nonspec.ts b/src/types/api/rpcspec_0_6/nonspec.ts deleted file mode 100644 index 8a9bb7e42..000000000 --- a/src/types/api/rpcspec_0_6/nonspec.ts +++ /dev/null @@ -1,213 +0,0 @@ -/** - * Types that are not in spec but required for UX - */ -import { - ADDRESS, - BLOCK_HASH, - BLOCK_NUMBER, - BLOCK_WITH_TXS, - BLOCK_WITH_TX_HASHES, - BROADCASTED_TXN, - CHAIN_ID, - CONTRACT_CLASS, - CONTRACT_STORAGE_DIFF_ITEM, - DEPRECATED_CONTRACT_CLASS, - EMITTED_EVENT, - EVENT, - EVENTS_CHUNK, - EVENT_FILTER, - FEE_ESTIMATE, - FEE_PAYMENT, - FELT, - MSG_FROM_L1, - NONCE_UPDATE, - PENDING_BLOCK_WITH_TXS, - PENDING_BLOCK_WITH_TX_HASHES, - PENDING_STATE_UPDATE, - PENDING_TXN_RECEIPT, - PRICE_UNIT, - REPLACED_CLASS, - RESOURCE_BOUNDS_MAPPING, - RESULT_PAGE_REQUEST, - SIMULATION_FLAG, - STATE_UPDATE, - SYNC_STATUS, - TRANSACTION_TRACE, - TXN, - TXN_EXECUTION_STATUS, - TXN_HASH, - TXN_RECEIPT, - TXN_STATUS, -} from './components'; -import { ValuesType } from '../../helpers/valuesType'; - -// METHOD RESPONSES -// response starknet_getClass -export type ContractClass = CONTRACT_CLASS | DEPRECATED_CONTRACT_CLASS; -// response starknet_simulateTransactions -export type SimulateTransaction = { - transaction_trace: TRANSACTION_TRACE; - fee_estimation: FEE_ESTIMATE; -}; -export type SimulateTransactionResponse = SimulateTransaction[]; -// response starknet_estimateFee -export type FeeEstimate = FEE_ESTIMATE; -// response starknet_getTransactionByHash, starknet_getTransactionByBlockIdAndIndex -export type TransactionWithHash = TXN & { transaction_hash: TXN_HASH }; -// response starknet_blockHashAndNumber -export type BlockHashAndNumber = { block_hash: BLOCK_HASH; block_number: BLOCK_NUMBER }; -// response starknet_getBlockWithTxs -export type BlockWithTxs = BLOCK_WITH_TXS | PENDING_BLOCK_WITH_TXS; -// response starknet_getBlockWithTxHashes -export type BlockWithTxHashes = BLOCK_WITH_TX_HASHES | PENDING_BLOCK_WITH_TX_HASHES; -// response starknet_getStateUpdate -export type StateUpdate = STATE_UPDATE | PENDING_STATE_UPDATE; -// response starknet_traceBlockTransactions -export type BlockTransactionsTraces = { transaction_hash: FELT; trace_root: TRANSACTION_TRACE }[]; -// response starknet_syncing -export type Syncing = false | SYNC_STATUS; -// response starknet_getEvents -export type Events = EVENTS_CHUNK; -export type EmittedEvent = EMITTED_EVENT; -export type Event = EVENT; -// response starknet_addInvokeTransaction -export type InvokedTransaction = { transaction_hash: TXN_HASH }; -// response starknet_addDeclareTransaction -export type DeclaredTransaction = { transaction_hash: TXN_HASH; class_hash: FELT }; -// response starknet_addDeployAccountTransaction -export type DeployedAccountTransaction = { transaction_hash: TXN_HASH; contract_address: FELT }; - -// Nice Components names -export type ContractAddress = ADDRESS; -export type Felt = FELT; -export type Nonce = FELT; -export type TransactionHash = TXN_HASH; -export type TransactionTrace = TRANSACTION_TRACE; -export type BlockHash = BLOCK_HASH; -export type TransactionReceipt = TXN_RECEIPT | PENDING_TXN_RECEIPT; -export type Receipt = TXN_RECEIPT; -export type PendingReceipt = PENDING_TXN_RECEIPT; -export type EventFilter = EVENT_FILTER & RESULT_PAGE_REQUEST; -export type SimulationFlags = Array; -export type L1Message = MSG_FROM_L1; -export type BaseTransaction = BROADCASTED_TXN; -export type ChainId = CHAIN_ID; -export type Transaction = TXN; -export type TransactionStatus = { - finality_status: TXN_STATUS; - execution_status?: TXN_EXECUTION_STATUS; -}; -export type ResourceBounds = RESOURCE_BOUNDS_MAPPING; -export type FeePayment = FEE_PAYMENT; -export type PriceUnit = PRICE_UNIT; - -// Diff Than Seq -export type StorageDiffs = Array; -export type DeprecatedDeclaredClasses = Array; -export type NonceUpdates = NONCE_UPDATE[]; -export type ReplacedClasses = REPLACED_CLASS[]; - -// Enums Derived From Spec Types (require manual check for changes) -export const ETransactionType = { - DECLARE: 'DECLARE', - DEPLOY: 'DEPLOY', - DEPLOY_ACCOUNT: 'DEPLOY_ACCOUNT', - INVOKE: 'INVOKE', - L1_HANDLER: 'L1_HANDLER', -} as const; - -export type ETransactionType = ValuesType; - -export const ESimulationFlag = { - SKIP_VALIDATE: 'SKIP_VALIDATE', - SKIP_FEE_CHARGE: 'SKIP_FEE_CHARGE', -} as const; - -export type ESimulationFlag = ValuesType; - -export const ETransactionStatus = { - RECEIVED: 'RECEIVED', - REJECTED: 'REJECTED', - ACCEPTED_ON_L2: 'ACCEPTED_ON_L2', - ACCEPTED_ON_L1: 'ACCEPTED_ON_L1', -} as const; - -export type ETransactionStatus = ValuesType; - -export const ETransactionFinalityStatus = { - ACCEPTED_ON_L2: 'ACCEPTED_ON_L2', - ACCEPTED_ON_L1: 'ACCEPTED_ON_L1', -} as const; - -export type ETransactionFinalityStatus = ValuesType; - -export const ETransactionExecutionStatus = { - SUCCEEDED: 'SUCCEEDED', - REVERTED: 'REVERTED', -} as const; - -export type ETransactionExecutionStatus = ValuesType; - -export const EBlockTag = { - PENDING: 'pending', - LATEST: 'latest', -} as const; - -export type EBlockTag = ValuesType; - -// 'L1' | 'L2' -export const EDataAvailabilityMode = { - L1: 'L1', - L2: 'L2', -} as const; - -export type EDataAvailabilityMode = ValuesType; - -// 0 | 1 -export const EDAMode = { - L1: 0, - L2: 1, -} as const; - -export type EDAMode = ValuesType; - -/** - * V_ Transaction versions HexString - * F_ Fee Transaction Versions HexString (2 ** 128 + TRANSACTION_VERSION) - */ -export const ETransactionVersion = { - V0: '0x0', - V1: '0x1', - V2: '0x2', - V3: '0x3', - F0: '0x100000000000000000000000000000000', - F1: '0x100000000000000000000000000000001', - F2: '0x100000000000000000000000000000002', - F3: '0x100000000000000000000000000000003', -} as const; - -export type ETransactionVersion = ValuesType; - -/** - * Old Transaction Versions - */ -export const ETransactionVersion2 = { - V0: '0x0', - V1: '0x1', - V2: '0x2', - F0: '0x100000000000000000000000000000000', - F1: '0x100000000000000000000000000000001', - F2: '0x100000000000000000000000000000002', -} as const; - -export type ETransactionVersion2 = ValuesType; - -/** - * V3 Transaction Versions - */ -export const ETransactionVersion3 = { - V3: '0x3', - F3: '0x100000000000000000000000000000003', -} as const; - -export type ETransactionVersion3 = ValuesType; diff --git a/src/types/helpers/index.ts b/src/types/helpers/index.ts new file mode 100644 index 000000000..e90608383 --- /dev/null +++ b/src/types/helpers/index.ts @@ -0,0 +1,26 @@ +/** + * Exclusive one of types (no intersection allowed) + * OneOf<[A, B]> = exclusive A OR B, where (all props of A) OR (all props of B) + * A | B = inclusive A OR B, where all prop of A and any prop of B and vice versa + */ +export type OneOf< + TypesArray extends any[], + Res = never, + AllProperties = MergeTypes, +> = TypesArray extends [infer Head, ...infer Rem] + ? OneOf, AllProperties> + : Res; + +export type SimpleOneOf = OnlyFirst | OnlyFirst; + +type MergeTypes = TypesArray extends [infer Head, ...infer Rem] + ? MergeTypes + : Res; + +type OnlyFirst = F & { [Key in keyof Omit]?: undefined }; // ?: never collapse to : undefined + +/** + * set all lvl1 props to never + */ + +export type AllNever = Record; diff --git a/src/types/index.ts b/src/types/index.ts index 9c87191a0..82a57e576 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -1,5 +1,5 @@ export * from './lib'; -export * from './provider'; +export * from '../provider/types/index.type'; export * from './account'; export * from './cairoEnum'; @@ -8,7 +8,7 @@ export * from './contract'; export * from './errors'; export * from './outsideExecution'; export * from './signer'; -export * from './transactionReceipt'; +export * from '../utils/transactionReceipt/transactionReceipt.type'; export * from './typedData'; export * as RPC from './api'; diff --git a/src/types/lib/index.ts b/src/types/lib/index.ts index 7f0c89c99..9f2e3adcf 100644 --- a/src/types/lib/index.ts +++ b/src/types/lib/index.ts @@ -1,9 +1,10 @@ import { StarknetChainId } from '../../global/constants'; import { weierstrass } from '../../utils/ec'; -import { EDataAvailabilityMode, ResourceBounds } from '../api'; +import { EDataAvailabilityMode } from '../api'; import { CairoEnum } from '../cairoEnum'; import { CompiledContract, CompiledSierraCasm, ContractClass } from './contract'; import { ValuesType } from '../helpers/valuesType'; +import { ResourceBounds } from '../../provider/types/spec.type'; export type WeierstrassSignatureType = weierstrass.SignatureType; export type ArraySignatureType = string[]; @@ -179,7 +180,7 @@ export type TransactionType = ValuesType; * new statuses are defined by props: finality_status and execution_status * to be #deprecated */ -export const TransactionStatus = { +/* export const TransactionStatus = { NOT_RECEIVED: 'NOT_RECEIVED', RECEIVED: 'RECEIVED', ACCEPTED_ON_L2: 'ACCEPTED_ON_L2', @@ -188,7 +189,7 @@ export const TransactionStatus = { REVERTED: 'REVERTED', } as const; -export type TransactionStatus = ValuesType; +export type TransactionStatus = ValuesType; */ export const TransactionFinalityStatus = { NOT_RECEIVED: 'NOT_RECEIVED', diff --git a/src/types/provider/index.ts b/src/types/provider/index.ts deleted file mode 100644 index 57bf8d7e2..000000000 --- a/src/types/provider/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './configuration'; -export * from './response'; diff --git a/src/types/provider/spec.ts b/src/types/provider/spec.ts deleted file mode 100644 index 9e4e41628..000000000 --- a/src/types/provider/spec.ts +++ /dev/null @@ -1,111 +0,0 @@ -// this file aims to unify the RPC specification types used by the common Provider class - -import { RPCSPEC07 } from '../api'; -import * as RPC06 from '../api/rpcspec_0_6'; -import { SPEC as SPEC06 } from '../api/rpcspec_0_6'; - -// taken from type-fest -type Simplify = { [K in keyof T]: T[K] } & {}; - -// taken from type-fest -export type RequiredKeysOf = Exclude< - { - [K in keyof T]: T extends Record ? K : never; - }[keyof T], - undefined ->; - -type ArrayElement = T extends Array ? U : never; - -type MergeProperties, T2 extends Record> = { - [K in RequiredKeysOf & RequiredKeysOf]: Merge; -} & { - [K in keyof T1 & keyof T2]?: Merge; -} & { - [K in Exclude]?: T1[K]; -} & { - [K in Exclude]?: T2[K]; -}; - -// type a = { w: bigint[]; x: bigint; y: string }; -// type b = { w: number[]; x: number; z: string }; -// type c = Merge; // { w: (bigint | number)[] x: bigint | number; y?: string; z?: string; } -// -// NOTE: handling for ambiguous overlaps, such as a shared property being an array or object, -// is simplified to resolve to only one type since there shouldn't be such occurrences in the -// currently supported RPC specifications -type Merge = Simplify< - T1 extends Array - ? T2 extends Array - ? Array, ArrayElement>> - : T1 - : T2 extends Array - ? T2 - : T1 extends object - ? T2 extends object - ? MergeProperties - : T1 - : T2 extends object - ? T2 - : T1 | T2 ->; - -export type BLOCK_HASH = Merge; -export type BLOCK_NUMBER = Merge; -export type FELT = Merge; -export type TXN_HASH = Merge; - -export type PRICE_UNIT = Merge; -export type RESOURCE_PRICE = Merge; -export type SIMULATION_FLAG = Merge; - -export type STATE_UPDATE = Merge; -export type PENDING_STATE_UPDATE = Merge< - SPEC06.PENDING_STATE_UPDATE, - RPCSPEC07.SPEC.PENDING_STATE_UPDATE ->; - -export type INVOKE_TXN_RECEIPT = Merge< - SPEC06.INVOKE_TXN_RECEIPT, - RPCSPEC07.SPEC.INVOKE_TXN_RECEIPT & RPCSPEC07.BlockHashAndNumber ->; -export type DECLARE_TXN_RECEIPT = Merge< - SPEC06.DECLARE_TXN_RECEIPT, - RPCSPEC07.SPEC.DECLARE_TXN_RECEIPT & RPCSPEC07.BlockHashAndNumber ->; -export type DEPLOY_ACCOUNT_TXN_RECEIPT = Merge< - SPEC06.DEPLOY_ACCOUNT_TXN_RECEIPT, - RPCSPEC07.SPEC.DEPLOY_ACCOUNT_TXN_RECEIPT & RPCSPEC07.BlockHashAndNumber ->; -export type L1_HANDLER_TXN_RECEIPT = Merge< - SPEC06.L1_HANDLER_TXN_RECEIPT, - RPCSPEC07.SPEC.L1_HANDLER_TXN_RECEIPT & RPCSPEC07.BlockHashAndNumber ->; -export type PENDING_INVOKE_TXN_RECEIPT = Merge< - SPEC06.PENDING_INVOKE_TXN_RECEIPT, - RPCSPEC07.SPEC.INVOKE_TXN_RECEIPT ->; -export type PENDING_DECLARE_TXN_RECEIPT = Merge< - SPEC06.PENDING_DECLARE_TXN_RECEIPT, - RPCSPEC07.SPEC.DECLARE_TXN_RECEIPT ->; -export type PENDING_DEPLOY_ACCOUNT_TXN_RECEIPT = Merge< - SPEC06.PENDING_DEPLOY_ACCOUNT_TXN_RECEIPT, - RPCSPEC07.SPEC.DEPLOY_ACCOUNT_TXN_RECEIPT ->; -export type PENDING_L1_HANDLER_TXN_RECEIPT = Merge< - SPEC06.PENDING_L1_HANDLER_TXN_RECEIPT, - RPCSPEC07.SPEC.L1_HANDLER_TXN_RECEIPT ->; - -export type BlockWithTxHashes = Merge; -export type ContractClassPayload = Merge; -export type DeclaredTransaction = Merge; -export type FeeEstimate = Merge; -export type InvokedTransaction = Merge; -export type PendingReceipt = Merge; -export type Receipt = Merge; -export type ResourceBounds = Merge; -export type SimulateTransaction = Merge; -export type TransactionReceipt = Merge; -export type TransactionWithHash = Merge; diff --git a/src/utils/hash/transactionHash/index.ts b/src/utils/hash/transactionHash/index.ts index 8929208ba..28e14a04c 100644 --- a/src/utils/hash/transactionHash/index.ts +++ b/src/utils/hash/transactionHash/index.ts @@ -3,13 +3,13 @@ */ import { StarknetChainId } from '../../../global/constants'; +import { ResourceBounds } from '../../../provider/types/spec.type'; import { BigNumberish, Calldata } from '../../../types'; import { EDAMode, ETransactionVersion, ETransactionVersion2, ETransactionVersion3, - ResourceBounds, } from '../../../types/api'; import { calculateDeclareTransactionHash as v2calculateDeclareTransactionHash, diff --git a/src/utils/hash/transactionHash/v3.ts b/src/utils/hash/transactionHash/v3.ts index 9902a0b33..7ddfdc324 100644 --- a/src/utils/hash/transactionHash/v3.ts +++ b/src/utils/hash/transactionHash/v3.ts @@ -6,9 +6,14 @@ import { poseidonHashMany } from '@scure/starknet'; import { StarknetChainId, TransactionHashPrefix } from '../../../global/constants'; import { BigNumberish, Calldata } from '../../../types'; -import { EDAMode, ResourceBounds } from '../../../types/api'; +import { RPCSPEC07, RPCSPEC08 } from '../../../types/api'; import { toHex } from '../../num'; import { encodeShortString } from '../../shortString'; +import { + EDAMode, + isRPC08_ResourceBounds, + type ResourceBounds, +} from '../../../provider/types/spec.type'; const AToBI = (array: BigNumberish[]) => array.map((it: BigNumberish) => BigInt(it)); @@ -19,6 +24,7 @@ const MAX_PRICE_PER_UNIT_BITS = 128n; const RESOURCE_VALUE_OFFSET = MAX_AMOUNT_BITS + MAX_PRICE_PER_UNIT_BITS; const L1_GAS_NAME = BigInt(encodeShortString('L1_GAS')); const L2_GAS_NAME = BigInt(encodeShortString('L2_GAS')); +const L1_DATA_GAS_NAME = BigInt(encodeShortString('L1_DATA')); export function hashDAMode(nonceDAMode: BigNumberish, feeDAMode: BigNumberish) { return (BigInt(nonceDAMode) << DATA_AVAILABILITY_MODE_BITS) + BigInt(feeDAMode); @@ -45,7 +51,7 @@ export function encodeResourceBoundsL1(bounds: ResourceBounds): bigint { } * @returns {bigint} encoded data */ -export function encodeResourceBoundsL2(bounds: ResourceBounds): bigint { +export function encodeResourceBoundsL2(bounds: RPCSPEC07.ResourceBounds): bigint { return ( (L2_GAS_NAME << RESOURCE_VALUE_OFFSET) + (BigInt(bounds.l2_gas.max_amount) << MAX_PRICE_PER_UNIT_BITS) + @@ -53,12 +59,33 @@ export function encodeResourceBoundsL2(bounds: ResourceBounds): bigint { ); } -export function hashFeeField(tip: BigNumberish, bounds: ResourceBounds) { +export function encodeDataResourceBoundsL1(bounds: RPCSPEC08.ResourceBounds): bigint { + return ( + (L1_DATA_GAS_NAME << RESOURCE_VALUE_OFFSET) + + (BigInt(bounds.l1_data_gas.max_amount) << MAX_PRICE_PER_UNIT_BITS) + + BigInt(bounds.l1_data_gas.max_price_per_unit) + ); +} + +/** + * hash tip and resource bounds (2 bound parameters) V3 RPC 0.7 + */ +export function hashFeeField(tip: BigNumberish, bounds: RPCSPEC07.ResourceBounds) { const L1Bound = encodeResourceBoundsL1(bounds); const L2Bound = encodeResourceBoundsL2(bounds); return poseidonHashMany([BigInt(tip), L1Bound, L2Bound]); } +/** + * hash tip and resource bounds (3 bounds params) V3 RPC 0.8 + */ +export function hashFeeFieldV3B3(tip: BigNumberish, bounds: RPCSPEC08.ResourceBounds) { + const L1Bound = encodeResourceBoundsL1(bounds); + const L2Bound = encodeResourceBoundsL2(bounds); + const L1Data = encodeDataResourceBoundsL1(bounds); + return poseidonHashMany([BigInt(tip), L1Bound, L2Bound, L1Data]); +} + export function calculateTransactionHashCommon( txHashPrefix: TransactionHashPrefix, version: BigNumberish, @@ -72,7 +99,9 @@ export function calculateTransactionHashCommon( resourceBounds: ResourceBounds, additionalData: BigNumberish[] = [] ): string { - const feeFieldHash = hashFeeField(tip, resourceBounds); + const feeFieldHash = isRPC08_ResourceBounds(resourceBounds) + ? hashFeeFieldV3B3(tip, resourceBounds) + : hashFeeField(tip, resourceBounds); const dAModeHash = hashDAMode(nonceDataAvailabilityMode, feeDataAvailabilityMode); const dataToHash = AToBI([ txHashPrefix, diff --git a/src/utils/provider.ts b/src/utils/provider.ts index c47b67ec6..d4e90eecf 100644 --- a/src/utils/provider.ts +++ b/src/utils/provider.ts @@ -1,4 +1,4 @@ -import { NetworkName, RPC_NODES } from '../global/constants'; +import { NetworkName, RPC_NODES, SupportedRpcVersion } from '../global/constants'; import { BlockIdentifier, BlockTag, @@ -14,7 +14,6 @@ import { StateUpdateResponse, V3TransactionDetails, } from '../types'; -import { ETransactionVersion } from '../types/api'; import { isSierra } from './contract'; import { formatSpaces } from './hash'; import { parse, stringify } from './json'; @@ -22,8 +21,9 @@ import { isHex, toHex } from './num'; import { isDecimalString } from './shortString'; import { isBigInt, isNumber, isString } from './typed'; import { compressProgram } from './stark'; -import type { GetTransactionReceiptResponse } from './transactionReceipt'; +import type { GetTransactionReceiptResponse } from './transactionReceipt/transactionReceipt.type'; import { logger } from '../global/logger'; +import { ETransactionVersion } from '../provider/types/spec.type'; /** * Helper - Async Sleep for 'delay' time @@ -288,7 +288,7 @@ export function isV3Tx(details: InvocationsDetailsWithNonce): details is V3Trans /** * Determines if the given response matches the specified version. * - * @param {('0.5' | '0.6' | '0.7')} version The version to compare against the response. + * @param {SupportedRpcVersion} version The version to compare against the response. * @param {string} response The response to check against the version. * @returns {boolean} True if the response matches the version, false otherwise. * @example @@ -297,13 +297,18 @@ export function isV3Tx(details: InvocationsDetailsWithNonce): details is V3Trans * // result = false * ``` */ -export function isVersion(version: '0.5' | '0.6' | '0.7', response: string): boolean { +export function isVersion(version: SupportedRpcVersion, response: string): boolean { const [majorS, minorS] = version.split('.'); const [majorR, minorR] = response.split('.'); return majorS === majorR && minorS === minorR; } +export function stringToSpecVersion(version: string) { + const [major, minor] = version.split('.'); + return `${major}.${minor}` as SupportedRpcVersion; +} + /** * Guard Pending Block * @param {GetBlockResponse} response answer of myProvider.getBlock() diff --git a/src/utils/responseParser/interface.ts b/src/utils/responseParser/interface.ts index 9605da691..58e7674dd 100644 --- a/src/utils/responseParser/interface.ts +++ b/src/utils/responseParser/interface.ts @@ -10,7 +10,7 @@ import { InvokeFunctionResponse, SimulateTransactionResponse, } from '../../types'; -import type { GetTransactionReceiptResponse } from '../transactionReceipt'; +import type { GetTransactionReceiptResponse } from '../transactionReceipt/transactionReceipt.type'; export abstract class ResponseParser { abstract parseGetBlockResponse(res: BlockWithTxHashes): GetBlockResponse; diff --git a/src/utils/responseParser/rpc.ts b/src/utils/responseParser/rpc.ts index 4b59d488c..eba3e26cd 100644 --- a/src/utils/responseParser/rpc.ts +++ b/src/utils/responseParser/rpc.ts @@ -13,13 +13,13 @@ import type { GetTxReceiptResponseWithoutHelper, RpcProviderOptions, SimulateTransactionResponse, - SimulatedTransaction, - TransactionReceipt, -} from '../../types/provider'; +} from '../../provider/types/index.type'; import { toBigInt } from '../num'; import { isString } from '../typed'; import { estimateFeeToBounds, estimatedFeeToMaxFee } from '../stark'; import { ResponseParser } from './interface'; +import { SimulateTransaction, TransactionReceipt } from '../../provider/types/spec.type'; +// import { TransactionReceipt } from '../../types/api/merge'; export class RPCResponseParser implements @@ -43,12 +43,9 @@ export class RPCResponseParser return estimatedFeeToMaxFee(estimatedFee, this.margin?.maxFee); } + // TODO: Check how to recaltulate bounds and what use this ? private estimateFeeToBounds(estimate: Parameters[0]) { - return estimateFeeToBounds( - estimate, - this.margin?.l1BoundMaxAmount, - this.margin?.l1BoundMaxPricePerUnit - ); + return estimateFeeToBounds(estimate, this.margin?.bounds); } public parseGetBlockResponse(res: BlockWithTxHashes): GetBlockResponse { @@ -75,8 +72,8 @@ export class RPCResponseParser const val = res[0]; return { overall_fee: toBigInt(val.overall_fee), - gas_consumed: toBigInt(val.gas_consumed), - gas_price: toBigInt(val.gas_price), + gas_consumed: toBigInt(0), // TODO: vidit sta sa ovim + gas_price: toBigInt(0), // TODO: vidit sta sa ovim unit: val.unit, suggestedMaxFee: this.estimatedFeeToMaxFee(val.overall_fee), resourceBounds: this.estimateFeeToBounds(val), @@ -88,8 +85,9 @@ export class RPCResponseParser public parseFeeEstimateBulkResponse(res: FeeEstimate[]): EstimateFeeResponseBulk { return res.map((val) => ({ overall_fee: toBigInt(val.overall_fee), - gas_consumed: toBigInt(val.gas_consumed), - gas_price: toBigInt(val.gas_price), + // TODO: vidit sta sa ovim + gas_consumed: toBigInt(0), // TODO: vidit sta sa ovim + gas_price: toBigInt(0), // TODO: vidit sta sa ovim unit: val.unit, suggestedMaxFee: this.estimatedFeeToMaxFee(val.overall_fee), resourceBounds: this.estimateFeeToBounds(val), @@ -106,7 +104,7 @@ export class RPCResponseParser // res: SimulateTransactionResponse res: any ): SimulateTransactionResponse { - return res.map((it: SimulatedTransaction) => { + return res.map((it: SimulateTransaction) => { return { ...it, suggestedMaxFee: this.estimatedFeeToMaxFee(it.fee_estimation.overall_fee), diff --git a/src/utils/stark.ts b/src/utils/stark/index.ts similarity index 84% rename from src/utils/stark.ts rename to src/utils/stark/index.ts index 00db1cedf..3d1e28488 100644 --- a/src/utils/stark.ts +++ b/src/utils/stark/index.ts @@ -1,7 +1,7 @@ import { getPublicKey, getStarkKey, utils } from '@scure/starknet'; import { gzip, ungzip } from 'pako'; -import { ZERO, FeeMarginPercentage } from '../global/constants'; +import { SupportedRpcVersion, ZERO } from '../../global/constants'; import { ArraySignatureType, BigNumberish, @@ -9,18 +9,36 @@ import { Program, Signature, UniversalDetails, -} from '../types'; -import { EDAMode, EDataAvailabilityMode, ETransactionVersion, ResourceBounds } from '../types/api'; -import { FeeEstimate } from '../types/provider'; -import { addHexPrefix, arrayBufferToString, atobUniversal, btoaUniversal, buf2hex } from './encode'; -import { parse, stringify } from './json'; +} from '../../types'; +import { FeeEstimate } from '../../provider/types/index.type'; +import { + addHexPrefix, + arrayBufferToString, + atobUniversal, + btoaUniversal, + buf2hex, +} from '../encode'; +import { parse, stringify } from '../json'; import { addPercent, bigNumberishArrayToDecimalStringArray, bigNumberishArrayToHexadecimalStringArray, toHex, -} from './num'; -import { isUndefined, isString, isBigInt } from './typed'; +} from '../num'; +import { isBigInt, isString } from '../typed'; +import { + EDAMode, + EDataAvailabilityMode, + ETransactionVersion, + isRPC08_FeeEstimate, + ResourceBounds, + ResourceBoundsOverhead, + ResourceBoundsOverheadRPC07, + ResourceBoundsOverheadRPC08, +} from '../../provider/types/spec.type'; +import { estimateFeeToBounds as estimateFeeToBoundsRPC07 } from './rpc07'; +import { estimateFeeToBounds as estimateFeeToBoundsRPC08 } from './rpc08'; +import { config } from '../../global/config'; type V3Details = Required< Pick< @@ -173,7 +191,7 @@ export function signatureToHexArray(sig?: Signature): ArraySignatureType { /** * Convert estimated fee to max fee including a margin * @param {BigNumberish} estimatedFee - The estimated fee - * @param {number} [overhead = feeMarginPercentage.MAX_FEE] - The overhead added to the gas + * @param {number} [overhead] - The overhead added to the gas * @returns {bigint} The maximum fee with the margin * @example * ```typescript @@ -183,7 +201,7 @@ export function signatureToHexArray(sig?: Signature): ArraySignatureType { */ export function estimatedFeeToMaxFee( estimatedFee: BigNumberish, - overhead: number = FeeMarginPercentage.MAX_FEE + overhead: number = config.get('feeMarginPercentage').maxFee ): bigint { return addPercent(estimatedFee, overhead); } @@ -192,52 +210,33 @@ export function estimatedFeeToMaxFee( * Calculates the maximum resource bounds for fee estimation. * * @param {FeeEstimate | 0n} estimate The estimate for the fee. If a BigInt is provided, the returned bounds will be set to '0x0'. - * @param {number} [amountOverhead = feeMarginPercentage.L1_BOUND_MAX_AMOUNT] - The percentage overhead added to the gas consumed or overall fee amount. - * @param {number} [priceOverhead = feeMarginPercentage.L1_BOUND_MAX_PRICE_PER_UNIT] The percentage overhead added to the gas price per unit. - * @returns {ResourceBounds} The maximum resource bounds for fee estimation. + * @param {ResourceBoundsOverhead} [overhead] - The percentage overhead added to the max units and max price per unit. + * @returns {ResourceBounds} The resource bounds with overhead. * @throws {Error} If the estimate object is undefined or does not have the required properties. - * @example - * ```typescript - * const feeEstimated: FeeEstimate = { - gas_consumed: "0x3456a", - gas_price: "0xa45567567567ae4", - overall_fee: "0x2198F463A77A899A5668", - unit: "WEI" -}; -const result = stark.estimateFeeToBounds(feeEstimated, 70, 50); - * // result = { - * // l2_gas: { max_amount: '0x0', max_price_per_unit: '0x0' }, - * // l1_gas: { max_amount: '0x58f9a', max_price_per_unit: '0xf6801b01b01b856' } - * // } - * ``` */ export function estimateFeeToBounds( estimate: FeeEstimate | 0n, - amountOverhead: number = FeeMarginPercentage.L1_BOUND_MAX_AMOUNT, - priceOverhead: number = FeeMarginPercentage.L1_BOUND_MAX_PRICE_PER_UNIT + overhead: ResourceBoundsOverhead = config.get('feeMarginPercentage').bounds, + specVersion?: string ): ResourceBounds { if (isBigInt(estimate)) { return { l2_gas: { max_amount: '0x0', max_price_per_unit: '0x0' }, l1_gas: { max_amount: '0x0', max_price_per_unit: '0x0' }, + ...(specVersion === '0.8' && { + l1_data_gas: { max_amount: '0x0', max_price_per_unit: '0x0' }, + }), }; } - if (isUndefined(estimate.gas_consumed) || isUndefined(estimate.gas_price)) { - throw Error('estimateFeeToBounds: estimate is undefined'); + if (isRPC08_FeeEstimate(estimate)) { + return estimateFeeToBoundsRPC08(estimate, overhead as ResourceBoundsOverheadRPC08); // TODO: remove as } - - const maxUnits = - estimate.data_gas_consumed !== undefined && estimate.data_gas_price !== undefined // RPC v0.7 - ? toHex(addPercent(BigInt(estimate.overall_fee) / BigInt(estimate.gas_price), amountOverhead)) - : toHex(addPercent(estimate.gas_consumed, amountOverhead)); - const maxUnitPrice = toHex(addPercent(estimate.gas_price, priceOverhead)); - return { - l2_gas: { max_amount: '0x0', max_price_per_unit: '0x0' }, - l1_gas: { max_amount: maxUnits, max_price_per_unit: maxUnitPrice }, - }; + return estimateFeeToBoundsRPC07(estimate, overhead as ResourceBoundsOverheadRPC07); // TODO: remove as } +export type feeOverhead = ResourceBounds; + /** * Converts the data availability mode from EDataAvailabilityMode to EDAMode. * @@ -331,14 +330,14 @@ export function toFeeVersion(providedVersion?: BigNumberish): ETransactionVersio * ``` */ -export function v3Details(details: UniversalDetails): V3Details { +export function v3Details(details: UniversalDetails, specVersion?: SupportedRpcVersion): V3Details { return { tip: details.tip || 0, paymasterData: details.paymasterData || [], accountDeploymentData: details.accountDeploymentData || [], nonceDataAvailabilityMode: details.nonceDataAvailabilityMode || EDataAvailabilityMode.L1, feeDataAvailabilityMode: details.feeDataAvailabilityMode || EDataAvailabilityMode.L1, - resourceBounds: details.resourceBounds ?? estimateFeeToBounds(ZERO), + resourceBounds: details.resourceBounds ?? estimateFeeToBounds(ZERO, undefined, specVersion), }; } diff --git a/src/utils/stark/rpc07.ts b/src/utils/stark/rpc07.ts new file mode 100644 index 000000000..fc1b547de --- /dev/null +++ b/src/utils/stark/rpc07.ts @@ -0,0 +1,25 @@ +/** Implementation for RPC 0.7 */ +import { ResourceBoundsOverheadRPC07 } from '../../provider/types/spec.type'; +import { RPCSPEC07 } from '../../types/api'; +import { addPercent, toHex } from '../num'; + +export function estimateFeeToBounds( + estimate: RPCSPEC07.FeeEstimate, + overhead: ResourceBoundsOverheadRPC07 +): RPCSPEC07.ResourceBounds { + const maxUnits = + estimate.data_gas_consumed !== undefined && estimate.data_gas_price !== undefined + ? toHex( + addPercent( + BigInt(estimate.overall_fee) / BigInt(estimate.gas_price), + overhead.l1_gas.max_amount + ) + ) + : toHex(addPercent(estimate.gas_consumed, overhead.l1_gas.max_amount)); + const maxUnitPrice = toHex(addPercent(estimate.gas_price, overhead.l1_gas.max_price_per_unit)); + + return { + l2_gas: { max_amount: '0x0', max_price_per_unit: '0x0' }, + l1_gas: { max_amount: maxUnits, max_price_per_unit: maxUnitPrice }, + }; +} diff --git a/src/utils/stark/rpc08.ts b/src/utils/stark/rpc08.ts new file mode 100644 index 000000000..d1a8a8729 --- /dev/null +++ b/src/utils/stark/rpc08.ts @@ -0,0 +1,31 @@ +/** Implementation for RPC 0.8 */ + +import { ResourceBoundsOverheadRPC08 } from '../../provider/types/spec.type'; +import { RPCSPEC08 } from '../../types/api'; +import { addPercent, toHex } from '../num'; + +export function estimateFeeToBounds( + estimate: RPCSPEC08.FeeEstimate, + overhead: ResourceBoundsOverheadRPC08 +): RPCSPEC08.ResourceBounds { + return { + l2_gas: { + max_amount: toHex(addPercent(estimate.l2_gas_consumed, overhead.l2_gas.max_amount)), + max_price_per_unit: toHex( + addPercent(estimate.l2_gas_price, overhead.l2_gas.max_price_per_unit) + ), + }, + l1_gas: { + max_amount: toHex(addPercent(estimate.l1_gas_consumed, overhead.l1_gas.max_amount)), + max_price_per_unit: toHex( + addPercent(estimate.l1_gas_price, overhead.l1_gas.max_price_per_unit) + ), + }, + l1_data_gas: { + max_amount: toHex(addPercent(estimate.l1_data_gas_consumed, overhead.l1_data_gas.max_amount)), + max_price_per_unit: toHex( + addPercent(estimate.l1_data_gas_price, overhead.l1_data_gas.max_price_per_unit) + ), + }, + }; +} diff --git a/src/utils/transaction.ts b/src/utils/transaction.ts index 532bedd44..cd03f2e38 100644 --- a/src/utils/transaction.ts +++ b/src/utils/transaction.ts @@ -1,4 +1,5 @@ import { UDC } from '../global/constants'; +import { ETransactionVersion } from '../provider/types/spec.type'; import { BigNumberish, CairoVersion, @@ -9,7 +10,6 @@ import { RawArgs, UniversalDeployerContractPayload, } from '../types'; -import { ETransactionVersion } from '../types/api'; import { CallData } from './calldata'; import { starkCurve } from './ec'; import { calculateContractAddressFromHash, getSelectorFromName } from './hash'; diff --git a/src/utils/transactionReceipt.ts b/src/utils/transactionReceipt/transactionReceipt.ts similarity index 75% rename from src/utils/transactionReceipt.ts rename to src/utils/transactionReceipt/transactionReceipt.ts index 9cbf09909..e448ad5e6 100644 --- a/src/utils/transactionReceipt.ts +++ b/src/utils/transactionReceipt/transactionReceipt.ts @@ -1,18 +1,17 @@ /* eslint-disable no-nested-ternary */ import { GetTxReceiptResponseWithoutHelper, - RejectedTransactionReceiptResponse, RevertedTransactionReceiptResponse, SuccessfulTransactionReceiptResponse, TransactionExecutionStatus, -} from '../types'; +} from '../../types'; import type { TransactionReceiptCallbacks, TransactionReceiptCallbacksDefault, TransactionReceiptStatus, - TransactionReceiptUtilityInterface, + GetTransactionReceiptResponse, TransactionReceiptValue, -} from '../types/transactionReceipt'; +} from './transactionReceipt.type'; /** * Utility that analyses transaction receipt response and provides helpers to process it @@ -21,7 +20,6 @@ import type { * const responseTx = new ReceiptTx(receipt); * responseTx.match({ * success: (txR: SuccessfulTransactionReceiptResponse) => { }, - * rejected: (txR: RejectedTransactionReceiptResponse) => { }, * reverted: (txR: RevertedTransactionReceiptResponse) => { }, * error: (err: Error) => { }, * }); @@ -31,7 +29,7 @@ import type { * } * ``` */ -export class ReceiptTx implements TransactionReceiptUtilityInterface { +export class ReceiptTx implements GetTransactionReceiptResponse { public readonly statusReceipt: TransactionReceiptStatus; public readonly value: TransactionReceiptValue; @@ -41,9 +39,7 @@ export class ReceiptTx implements TransactionReceiptUtilityInterface { ? ['success', receipt] : ReceiptTx.isReverted(receipt) ? ['reverted', receipt] - : ReceiptTx.isRejected(receipt) - ? ['rejected', receipt] - : ['error', new Error('Unknown response type')]; + : ['error', new Error('Unknown response type')]; // eslint-disable-next-line no-restricted-syntax for (const [key] of Object.entries(this)) { Object.defineProperty(this, key, { @@ -75,9 +71,12 @@ export class ReceiptTx implements TransactionReceiptUtilityInterface { return this.statusReceipt === 'reverted'; } - isRejected(): this is RejectedTransactionReceiptResponse { + // TODO: Missing is Pending or Production block + + // Status do not exist on receipts + /* isRejected(): this is RejectedTransactionReceiptResponse { return this.statusReceipt === 'rejected'; - } + } */ isError() { return this.statusReceipt === 'error'; @@ -86,29 +85,24 @@ export class ReceiptTx implements TransactionReceiptUtilityInterface { static isSuccess( transactionReceipt: GetTxReceiptResponseWithoutHelper ): transactionReceipt is SuccessfulTransactionReceiptResponse { - return ( - (transactionReceipt as SuccessfulTransactionReceiptResponse).execution_status === - TransactionExecutionStatus.SUCCEEDED - ); + return transactionReceipt.execution_status === TransactionExecutionStatus.SUCCEEDED; } static isReverted( transactionReceipt: GetTxReceiptResponseWithoutHelper ): transactionReceipt is RevertedTransactionReceiptResponse { - return ( - (transactionReceipt as RevertedTransactionReceiptResponse).execution_status === - TransactionExecutionStatus.REVERTED - ); + return transactionReceipt.execution_status === TransactionExecutionStatus.REVERTED; } - static isRejected( + // Status do not exist on receipts + /* static isRejected( transactionReceipt: GetTxReceiptResponseWithoutHelper ): transactionReceipt is RejectedTransactionReceiptResponse { return ( (transactionReceipt as RejectedTransactionReceiptResponse).status === TransactionExecutionStatus.REJECTED ); - } + } */ } -export type GetTransactionReceiptResponse = GetTxReceiptResponseWithoutHelper & ReceiptTx; +// export type GetTransactionReceiptResponse = GetTxReceiptResponseWithoutHelper & ReceiptTx; diff --git a/src/types/transactionReceipt.ts b/src/utils/transactionReceipt/transactionReceipt.type.ts similarity index 86% rename from src/types/transactionReceipt.ts rename to src/utils/transactionReceipt/transactionReceipt.type.ts index 84d96b06d..110cc9778 100644 --- a/src/types/transactionReceipt.ts +++ b/src/utils/transactionReceipt/transactionReceipt.type.ts @@ -1,13 +1,12 @@ import { - RejectedTransactionReceiptResponse, RevertedTransactionReceiptResponse, SuccessfulTransactionReceiptResponse, -} from './provider'; +} from '../../provider/types/index.type'; export type TransactionStatusReceiptSets = { success: SuccessfulTransactionReceiptResponse; reverted: RevertedTransactionReceiptResponse; - rejected: RejectedTransactionReceiptResponse; + // rejected: RejectedTransactionReceiptResponse; error: Error; }; export type TransactionReceiptStatus = keyof TransactionStatusReceiptSets; @@ -23,7 +22,7 @@ export type TransactionReceiptCallbacks = | TransactionReceiptCallbacksDefined | TransactionReceiptCallbacksDefault; -export type TransactionReceiptUtilityInterface = { +export type GetTransactionReceiptResponse = { readonly statusReceipt: TransactionReceiptStatus; readonly value: TransactionReceiptValue; match(callbacks: TransactionReceiptCallbacks): void; diff --git a/src/utils/typedData.ts b/src/utils/typedData.ts index daf900885..2a03d3b00 100644 --- a/src/utils/typedData.ts +++ b/src/utils/typedData.ts @@ -528,7 +528,7 @@ export function getStructHash( * Get the SNIP-12 encoded message to sign, from the typedData object. * * @param {TypedData} typedData - The TypedData object. - * @param {BigNumberish} account - The account to sign the message. + * @param {BigNumberish} accountAddress - The account address to sign the message. * * @returns {string} The hash of the message to sign. * @throws Will throw an error if the typedData does not match the JSON schema. @@ -582,7 +582,7 @@ export function getStructHash( * // result = "0x70338fb11b8f70b68b261de8a322bcb004bd85e88ac47d9147982c7f5ac66fd" * ``` */ -export function getMessageHash(typedData: TypedData, account: BigNumberish): string { +export function getMessageHash(typedData: TypedData, accountAddress: BigNumberish): string { if (!validateTypedData(typedData)) { throw new Error('Typed data does not match JSON schema'); } @@ -593,7 +593,7 @@ export function getMessageHash(typedData: TypedData, account: BigNumberish): str const message = [ encodeShortString('StarkNet Message'), getStructHash(typedData.types, domain, typedData.domain, revision), - account, + accountAddress, getStructHash(typedData.types, typedData.primaryType, typedData.message, revision), ];