starknet 4.17.0 → 4.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +2 -10
  3. package/dist/index.d.ts +27 -9
  4. package/dist/index.global.js +30 -13
  5. package/dist/index.global.js.map +1 -1
  6. package/dist/index.js +30 -13
  7. package/dist/index.js.map +1 -1
  8. package/dist/index.mjs +30 -13
  9. package/dist/index.mjs.map +1 -1
  10. package/package.json +5 -1
  11. package/.babelrc +0 -6
  12. package/.commitlintrc +0 -22
  13. package/.eslintignore +0 -2
  14. package/.eslintrc +0 -28
  15. package/.prettierrc +0 -6
  16. package/.releaserc +0 -28
  17. package/CODE_OF_CONDUCT.md +0 -128
  18. package/CONTRIBUTING.md +0 -52
  19. package/__mocks__/Account.json +0 -25486
  20. package/__mocks__/ERC20.json +0 -40027
  21. package/__mocks__/TestDapp.json +0 -12962
  22. package/__mocks__/contract.json +0 -33191
  23. package/__mocks__/l1l2_compiled.json +0 -10107
  24. package/__mocks__/multicall.json +0 -8139
  25. package/__mocks__/naming_compiled.json +0 -53283
  26. package/__mocks__/starknetId_compiled.json +0 -44703
  27. package/__mocks__/typedDataExample.json +0 -35
  28. package/__mocks__/typedDataSessionExample.json +0 -42
  29. package/__mocks__/typedDataStructArrayExample.json +0 -44
  30. package/__tests__/account.test.ts +0 -345
  31. package/__tests__/contract.test.ts +0 -249
  32. package/__tests__/defaultProvider.test.ts +0 -177
  33. package/__tests__/fixtures.ts +0 -84
  34. package/__tests__/jest.setup.ts +0 -30
  35. package/__tests__/rpcProvider.test.ts +0 -132
  36. package/__tests__/sequencerProvider.test.ts +0 -123
  37. package/__tests__/utils/__snapshots__/ellipticalCurve.test.ts.snap +0 -5
  38. package/__tests__/utils/__snapshots__/utils.browser.test.ts.snap +0 -5
  39. package/__tests__/utils/__snapshots__/utils.test.ts.snap +0 -5
  40. package/__tests__/utils/address.test.ts +0 -45
  41. package/__tests__/utils/ellipticalCurve.test.ts +0 -91
  42. package/__tests__/utils/merkle.test.ts +0 -256
  43. package/__tests__/utils/shortString.test.ts +0 -22
  44. package/__tests__/utils/starknetId.test.ts +0 -53
  45. package/__tests__/utils/transactionHash.test.ts +0 -17
  46. package/__tests__/utils/typedData.test.ts +0 -223
  47. package/__tests__/utils/uint256.test.ts +0 -32
  48. package/__tests__/utils/utils.browser.test.ts +0 -29
  49. package/__tests__/utils/utils.test.ts +0 -141
  50. package/img/logo.svg +0 -17
  51. package/index.d.ts +0 -2683
  52. package/index.global.js +0 -23192
  53. package/index.global.js.map +0 -1
  54. package/index.js +0 -4910
  55. package/index.js.map +0 -1
  56. package/index.mjs +0 -4852
  57. package/index.mjs.map +0 -1
  58. package/src/account/default.ts +0 -501
  59. package/src/account/index.ts +0 -2
  60. package/src/account/interface.ts +0 -309
  61. package/src/constants.ts +0 -2065
  62. package/src/contract/contractFactory.ts +0 -88
  63. package/src/contract/default.ts +0 -425
  64. package/src/contract/index.ts +0 -3
  65. package/src/contract/interface.ts +0 -106
  66. package/src/index.ts +0 -26
  67. package/src/provider/default.ts +0 -187
  68. package/src/provider/errors.ts +0 -14
  69. package/src/provider/index.ts +0 -9
  70. package/src/provider/interface.ts +0 -281
  71. package/src/provider/rpc.ts +0 -482
  72. package/src/provider/sequencer.ts +0 -523
  73. package/src/provider/utils.ts +0 -100
  74. package/src/signer/default.ts +0 -99
  75. package/src/signer/index.ts +0 -2
  76. package/src/signer/interface.ts +0 -77
  77. package/src/types/account.ts +0 -43
  78. package/src/types/api/index.ts +0 -10
  79. package/src/types/api/openrpc.ts +0 -607
  80. package/src/types/api/rpc.ts +0 -45
  81. package/src/types/api/sequencer.ts +0 -369
  82. package/src/types/contract.ts +0 -5
  83. package/src/types/index.ts +0 -8
  84. package/src/types/lib.ts +0 -143
  85. package/src/types/provider.ts +0 -134
  86. package/src/types/signer.ts +0 -24
  87. package/src/utils/address.ts +0 -44
  88. package/src/utils/calldata.ts +0 -250
  89. package/src/utils/ellipticCurve.ts +0 -120
  90. package/src/utils/encode.ts +0 -66
  91. package/src/utils/events.ts +0 -32
  92. package/src/utils/fetchPonyfill.ts +0 -5
  93. package/src/utils/hash.ts +0 -235
  94. package/src/utils/json.ts +0 -15
  95. package/src/utils/merkle.ts +0 -69
  96. package/src/utils/number.ts +0 -98
  97. package/src/utils/provider.ts +0 -28
  98. package/src/utils/responseParser/index.ts +0 -28
  99. package/src/utils/responseParser/rpc.ts +0 -70
  100. package/src/utils/responseParser/sequencer.ts +0 -135
  101. package/src/utils/shortString.ts +0 -21
  102. package/src/utils/stark.ts +0 -57
  103. package/src/utils/starknetId.ts +0 -116
  104. package/src/utils/transaction.ts +0 -56
  105. package/src/utils/typedData/index.ts +0 -247
  106. package/src/utils/typedData/types.ts +0 -37
  107. package/src/utils/typedData/utils.ts +0 -16
  108. package/src/utils/uint256.ts +0 -32
  109. package/src/utils/url.ts +0 -53
  110. package/tsconfig.eslint.json +0 -4
  111. package/tsup.config.ts +0 -9
  112. package/www/README.md +0 -41
  113. package/www/babel.config.js +0 -3
  114. package/www/code-examples/account.js +0 -65
  115. package/www/code-examples/amm.js +0 -44
  116. package/www/code-examples/erc20.js +0 -13
  117. package/www/code-examples/package-lock.json +0 -336
  118. package/www/code-examples/package.json +0 -15
  119. package/www/docs/API/_category_.json +0 -5
  120. package/www/docs/API/account.md +0 -463
  121. package/www/docs/API/changelog.md +0 -15
  122. package/www/docs/API/contract.md +0 -135
  123. package/www/docs/API/contractFactory.md +0 -45
  124. package/www/docs/API/index.md +0 -3
  125. package/www/docs/API/provider.md +0 -725
  126. package/www/docs/API/signer.md +0 -105
  127. package/www/docs/API/utils.md +0 -374
  128. package/www/docusaurus.config.js +0 -130
  129. package/www/guides/account.md +0 -140
  130. package/www/guides/cra.md +0 -3
  131. package/www/guides/erc20.md +0 -163
  132. package/www/guides/intro.md +0 -63
  133. package/www/package-lock.json +0 -20405
  134. package/www/package.json +0 -43
  135. package/www/sidebars.js +0 -31
  136. package/www/src/components/HomepageFeatures/index.tsx +0 -67
  137. package/www/src/components/HomepageFeatures/styles.module.css +0 -10
  138. package/www/src/css/custom.css +0 -39
  139. package/www/src/pages/index.module.css +0 -23
  140. package/www/src/pages/index.tsx +0 -40
  141. package/www/src/pages/markdown-page.md +0 -7
  142. package/www/static/.nojekyll +0 -0
  143. package/www/static/img/docusaurus.png +0 -0
  144. package/www/static/img/favicon.ico +0 -0
  145. package/www/static/img/logo.svg +0 -17
  146. package/www/static/img/starknet-1.png +0 -0
  147. package/www/static/img/starknet-2.png +0 -0
  148. package/www/static/img/starknet-3.png +0 -0
  149. package/www/static/img/tutorial/docsVersionDropdown.png +0 -0
  150. package/www/static/img/tutorial/localeDropdown.png +0 -0
@@ -1,523 +0,0 @@
1
- import urljoin from 'url-join';
2
-
3
- import { StarknetChainId } from '../constants';
4
- import {
5
- Call,
6
- CallContractResponse,
7
- CallL1Handler,
8
- ContractClass,
9
- DeclareContractResponse,
10
- DeclareContractTransaction,
11
- DeployAccountContractTransaction,
12
- DeployContractResponse,
13
- EstimateFeeResponse,
14
- GetBlockResponse,
15
- GetContractAddressesResponse,
16
- GetTransactionReceiptResponse,
17
- GetTransactionResponse,
18
- GetTransactionStatusResponse,
19
- GetTransactionTraceResponse,
20
- Invocation,
21
- InvocationsDetailsWithNonce,
22
- InvokeFunctionResponse,
23
- Sequencer,
24
- } from '../types';
25
- import fetch from '../utils/fetchPonyfill';
26
- import { getSelector, getSelectorFromName } from '../utils/hash';
27
- import { parse, parseAlwaysAsBig, stringify } from '../utils/json';
28
- import {
29
- BigNumberish,
30
- bigNumberishArrayToDecimalStringArray,
31
- getDecimalString,
32
- getHexString,
33
- getHexStringArray,
34
- toBN,
35
- toHex,
36
- } from '../utils/number';
37
- import { parseContract, wait } from '../utils/provider';
38
- import { SequencerAPIResponseParser } from '../utils/responseParser/sequencer';
39
- import { randomAddress } from '../utils/stark';
40
- import { buildUrl } from '../utils/url';
41
- import { GatewayError, HttpError } from './errors';
42
- import { ProviderInterface } from './interface';
43
- import { Block, BlockIdentifier } from './utils';
44
-
45
- type NetworkName = 'mainnet-alpha' | 'goerli-alpha' | 'goerli-alpha-2';
46
-
47
- export type SequencerProviderOptions = {
48
- headers?: object;
49
- blockIdentifier?: BlockIdentifier;
50
- } & (
51
- | {
52
- network: NetworkName | StarknetChainId;
53
- chainId?: StarknetChainId;
54
- }
55
- | {
56
- baseUrl: string;
57
- feederGatewayUrl?: string;
58
- gatewayUrl?: string;
59
- chainId?: StarknetChainId;
60
- }
61
- );
62
-
63
- function isEmptyQueryObject(obj?: Record<any, any>): obj is undefined {
64
- return (
65
- obj === undefined ||
66
- Object.keys(obj).length === 0 ||
67
- (Object.keys(obj).length === 1 &&
68
- Object.entries(obj).every(([k, v]) => k === 'blockIdentifier' && v === null))
69
- );
70
- }
71
-
72
- const defaultOptions = {
73
- network: 'goerli-alpha-2' as NetworkName,
74
- blockIdentifier: 'pending',
75
- };
76
-
77
- export class SequencerProvider implements ProviderInterface {
78
- public baseUrl: string;
79
-
80
- public feederGatewayUrl: string;
81
-
82
- public gatewayUrl: string;
83
-
84
- public chainId: StarknetChainId;
85
-
86
- public headers: object | undefined;
87
-
88
- private responseParser = new SequencerAPIResponseParser();
89
-
90
- private blockIdentifier: BlockIdentifier;
91
-
92
- constructor(optionsOrProvider: SequencerProviderOptions = defaultOptions) {
93
- if ('network' in optionsOrProvider) {
94
- this.baseUrl = SequencerProvider.getNetworkFromName(optionsOrProvider.network);
95
- this.feederGatewayUrl = buildUrl(this.baseUrl, 'feeder_gateway');
96
- this.gatewayUrl = buildUrl(this.baseUrl, 'gateway');
97
- } else {
98
- this.baseUrl = optionsOrProvider.baseUrl;
99
- this.feederGatewayUrl = buildUrl(
100
- this.baseUrl,
101
- 'feeder_gateway',
102
- optionsOrProvider.feederGatewayUrl
103
- );
104
- this.gatewayUrl = buildUrl(this.baseUrl, 'gateway', optionsOrProvider.gatewayUrl);
105
- }
106
- this.chainId =
107
- optionsOrProvider?.chainId ?? SequencerProvider.getChainIdFromBaseUrl(this.baseUrl);
108
- this.headers = optionsOrProvider.headers;
109
- this.blockIdentifier = optionsOrProvider?.blockIdentifier || defaultOptions.blockIdentifier;
110
- }
111
-
112
- protected static getNetworkFromName(name: NetworkName | StarknetChainId) {
113
- switch (name) {
114
- case 'mainnet-alpha' || StarknetChainId.MAINNET:
115
- return 'https://alpha-mainnet.starknet.io';
116
- case 'goerli-alpha' || StarknetChainId.TESTNET:
117
- return 'https://alpha4.starknet.io';
118
- case 'goerli-alpha-2' || StarknetChainId.TESTNET2:
119
- return 'https://alpha4-2.starknet.io';
120
- default:
121
- return 'https://alpha4.starknet.io';
122
- }
123
- }
124
-
125
- protected static getChainIdFromBaseUrl(baseUrl: string): StarknetChainId {
126
- try {
127
- const url = new URL(baseUrl);
128
- if (url.host.includes('mainnet.starknet.io')) {
129
- return StarknetChainId.MAINNET;
130
- }
131
- if (url.host.includes('alpha4-2.starknet.io')) {
132
- return StarknetChainId.TESTNET2;
133
- }
134
- } catch {
135
- // eslint-disable-next-line no-console
136
- console.error(`Could not parse baseUrl: ${baseUrl}`);
137
- }
138
- return StarknetChainId.TESTNET;
139
- }
140
-
141
- private getFetchUrl(endpoint: keyof Sequencer.Endpoints) {
142
- const gatewayUrlEndpoints = ['add_transaction'];
143
-
144
- return gatewayUrlEndpoints.includes(endpoint) ? this.gatewayUrl : this.feederGatewayUrl;
145
- }
146
-
147
- private getFetchMethod(endpoint: keyof Sequencer.Endpoints) {
148
- const postMethodEndpoints = [
149
- 'add_transaction',
150
- 'call_contract',
151
- 'estimate_fee',
152
- 'estimate_message_fee',
153
- ];
154
-
155
- return postMethodEndpoints.includes(endpoint) ? 'POST' : 'GET';
156
- }
157
-
158
- private getQueryString(query?: Record<string, any>): string {
159
- if (isEmptyQueryObject(query)) {
160
- return '';
161
- }
162
- const queryString = Object.entries(query)
163
- .map(([key, value]) => {
164
- if (key === 'blockIdentifier') {
165
- const block = new Block(value);
166
- return `${block.queryIdentifier}`;
167
- }
168
- return `${key}=${value}`;
169
- })
170
- .join('&');
171
-
172
- return `?${queryString}`;
173
- }
174
-
175
- private getHeaders(method: 'POST' | 'GET'): object | undefined {
176
- if (method === 'POST') {
177
- return {
178
- 'Content-Type': 'application/json',
179
- ...this.headers,
180
- };
181
- }
182
- return this.headers;
183
- }
184
-
185
- // typesafe fetch
186
- protected async fetchEndpoint<T extends keyof Sequencer.Endpoints>(
187
- endpoint: T,
188
- // typescript type magic to create a nice fitting function interface
189
- ...[query, request]: Sequencer.Endpoints[T]['QUERY'] extends never
190
- ? Sequencer.Endpoints[T]['REQUEST'] extends never
191
- ? [] // when no query and no request is needed, we can omit the query and request parameters
192
- : [undefined, Sequencer.Endpoints[T]['REQUEST']]
193
- : Sequencer.Endpoints[T]['REQUEST'] extends never
194
- ? [Sequencer.Endpoints[T]['QUERY']] // when no request is needed, we can omit the request parameter
195
- : [Sequencer.Endpoints[T]['QUERY'], Sequencer.Endpoints[T]['REQUEST']] // when both query and request are needed, we cant omit anything
196
- ): Promise<Sequencer.Endpoints[T]['RESPONSE']> {
197
- const baseUrl = this.getFetchUrl(endpoint);
198
- const method = this.getFetchMethod(endpoint);
199
- const queryString = this.getQueryString(query);
200
- const headers = this.getHeaders(method);
201
- const url = urljoin(baseUrl, endpoint, queryString);
202
-
203
- try {
204
- const res = await fetch(url, {
205
- method,
206
- body: stringify(request),
207
- headers: headers as Record<string, string>,
208
- });
209
- const textResponse = await res.text();
210
- if (!res.ok) {
211
- // This will allow user to handle contract errors
212
- let responseBody: any;
213
- try {
214
- responseBody = parse(textResponse);
215
- } catch {
216
- // if error parsing fails, return an http error
217
- throw new HttpError(res.statusText, res.status);
218
- }
219
-
220
- const errorCode = responseBody.code || ((responseBody as any)?.status_code as string); // starknet-devnet uses status_code instead of code; They need to fix that
221
- throw new GatewayError(responseBody.message, errorCode); // Caught locally, and re-thrown for the user
222
- }
223
-
224
- if (endpoint === 'estimate_fee') {
225
- return parseAlwaysAsBig(textResponse, (_, v) => {
226
- if (v && typeof v === 'bigint') {
227
- return toBN(v.toString());
228
- }
229
- return v;
230
- });
231
- }
232
- return parse(textResponse) as Sequencer.Endpoints[T]['RESPONSE'];
233
- } catch (err) {
234
- // rethrow custom errors
235
- if (err instanceof GatewayError || err instanceof HttpError) {
236
- throw err;
237
- }
238
- if (err instanceof Error) {
239
- throw Error(`Could not ${method} from endpoint \`${url}\`: ${err.message}`);
240
- }
241
- throw err;
242
- }
243
- }
244
-
245
- public async getChainId(): Promise<StarknetChainId> {
246
- return Promise.resolve(this.chainId);
247
- }
248
-
249
- public async callContract(
250
- { contractAddress, entrypoint: entryPointSelector, calldata = [] }: Call,
251
- blockIdentifier: BlockIdentifier = this.blockIdentifier
252
- ): Promise<CallContractResponse> {
253
- return this.fetchEndpoint(
254
- 'call_contract',
255
- { blockIdentifier },
256
- {
257
- signature: [],
258
- contract_address: contractAddress,
259
- entry_point_selector: getSelectorFromName(entryPointSelector),
260
- calldata,
261
- }
262
- ).then(this.responseParser.parseCallContractResponse);
263
- }
264
-
265
- public async getBlock(
266
- blockIdentifier: BlockIdentifier = this.blockIdentifier
267
- ): Promise<GetBlockResponse> {
268
- return this.fetchEndpoint('get_block', { blockIdentifier }).then(
269
- this.responseParser.parseGetBlockResponse
270
- );
271
- }
272
-
273
- public async getNonceForAddress(
274
- contractAddress: string,
275
- blockIdentifier: BlockIdentifier = this.blockIdentifier
276
- ): Promise<BigNumberish> {
277
- return this.fetchEndpoint('get_nonce', { contractAddress, blockIdentifier });
278
- }
279
-
280
- public async getStorageAt(
281
- contractAddress: string,
282
- key: BigNumberish,
283
- blockIdentifier: BlockIdentifier = this.blockIdentifier
284
- ): Promise<BigNumberish> {
285
- const parsedKey = toBN(key).toString(10);
286
- return this.fetchEndpoint('get_storage_at', {
287
- blockIdentifier,
288
- contractAddress,
289
- key: parsedKey,
290
- });
291
- }
292
-
293
- public async getTransaction(txHash: BigNumberish): Promise<GetTransactionResponse> {
294
- const txHashHex = toHex(toBN(txHash));
295
- return this.fetchEndpoint('get_transaction', { transactionHash: txHashHex }).then((value) =>
296
- this.responseParser.parseGetTransactionResponse(value)
297
- );
298
- }
299
-
300
- public async getTransactionReceipt(txHash: BigNumberish): Promise<GetTransactionReceiptResponse> {
301
- const txHashHex = toHex(toBN(txHash));
302
- return this.fetchEndpoint('get_transaction_receipt', { transactionHash: txHashHex }).then(
303
- this.responseParser.parseGetTransactionReceiptResponse
304
- );
305
- }
306
-
307
- public async getClassAt(
308
- contractAddress: string,
309
- blockIdentifier: BlockIdentifier = this.blockIdentifier
310
- ): Promise<ContractClass> {
311
- return this.fetchEndpoint('get_full_contract', { blockIdentifier, contractAddress }).then(
312
- parseContract
313
- );
314
- }
315
-
316
- public async getClassHashAt(
317
- contractAddress: string,
318
- blockIdentifier: BlockIdentifier = this.blockIdentifier
319
- ): Promise<string> {
320
- return this.fetchEndpoint('get_class_hash_at', { blockIdentifier, contractAddress });
321
- }
322
-
323
- public async getClassByHash(classHash: string): Promise<ContractClass> {
324
- return this.fetchEndpoint('get_class_by_hash', { classHash }).then(parseContract);
325
- }
326
-
327
- public async invokeFunction(
328
- functionInvocation: Invocation,
329
- details: InvocationsDetailsWithNonce
330
- ): Promise<InvokeFunctionResponse> {
331
- return this.fetchEndpoint('add_transaction', undefined, {
332
- type: 'INVOKE_FUNCTION',
333
- contract_address: functionInvocation.contractAddress,
334
- calldata: bigNumberishArrayToDecimalStringArray(functionInvocation.calldata ?? []),
335
- signature: bigNumberishArrayToDecimalStringArray(functionInvocation.signature ?? []),
336
- nonce: toHex(toBN(details.nonce)),
337
- max_fee: toHex(toBN(details.maxFee || 0)),
338
- version: toHex(toBN(details.version || 1)),
339
- }).then(this.responseParser.parseInvokeFunctionResponse);
340
- }
341
-
342
- public async deployAccountContract(
343
- { classHash, constructorCalldata, addressSalt, signature }: DeployAccountContractTransaction,
344
- details: InvocationsDetailsWithNonce
345
- ): Promise<DeployContractResponse> {
346
- return this.fetchEndpoint('add_transaction', undefined, {
347
- type: 'DEPLOY_ACCOUNT',
348
- contract_address_salt: addressSalt ?? randomAddress(),
349
- constructor_calldata: bigNumberishArrayToDecimalStringArray(constructorCalldata ?? []),
350
- class_hash: toHex(toBN(classHash)),
351
- max_fee: toHex(toBN(details.maxFee || 0)),
352
- version: toHex(toBN(details.version || 0)),
353
- nonce: toHex(toBN(details.nonce)),
354
- signature: bigNumberishArrayToDecimalStringArray(signature || []),
355
- }).then(this.responseParser.parseDeployContractResponse);
356
- }
357
-
358
- public async declareContract(
359
- { senderAddress, contractDefinition, signature }: DeclareContractTransaction,
360
- details: InvocationsDetailsWithNonce
361
- ): Promise<DeclareContractResponse> {
362
- return this.fetchEndpoint('add_transaction', undefined, {
363
- type: 'DECLARE',
364
- contract_class: contractDefinition,
365
- nonce: toHex(toBN(details.nonce)),
366
- signature: bigNumberishArrayToDecimalStringArray(signature || []),
367
- sender_address: senderAddress,
368
- max_fee: toHex(toBN(details.maxFee || 0)),
369
- version: toHex(toBN(details.version || 1)),
370
- }).then(this.responseParser.parseDeclareContractResponse);
371
- }
372
-
373
- public async getEstimateFee(
374
- invocation: Invocation,
375
- invocationDetails: InvocationsDetailsWithNonce,
376
- blockIdentifier: BlockIdentifier = this.blockIdentifier
377
- ): Promise<EstimateFeeResponse> {
378
- return this.getInvokeEstimateFee(invocation, invocationDetails, blockIdentifier);
379
- }
380
-
381
- public async getInvokeEstimateFee(
382
- invocation: Invocation,
383
- invocationDetails: InvocationsDetailsWithNonce,
384
- blockIdentifier: BlockIdentifier = this.blockIdentifier
385
- ): Promise<EstimateFeeResponse> {
386
- return this.fetchEndpoint(
387
- 'estimate_fee',
388
- { blockIdentifier },
389
- {
390
- type: 'INVOKE_FUNCTION',
391
- contract_address: invocation.contractAddress,
392
- calldata: invocation.calldata ?? [],
393
- signature: bigNumberishArrayToDecimalStringArray(invocation.signature || []),
394
- version: toHex(toBN(invocationDetails?.version || 1)),
395
- nonce: toHex(toBN(invocationDetails.nonce)),
396
- }
397
- ).then(this.responseParser.parseFeeEstimateResponse);
398
- }
399
-
400
- public async getDeclareEstimateFee(
401
- { senderAddress, contractDefinition, signature }: DeclareContractTransaction,
402
- details: InvocationsDetailsWithNonce,
403
- blockIdentifier: BlockIdentifier = this.blockIdentifier
404
- ): Promise<EstimateFeeResponse> {
405
- return this.fetchEndpoint(
406
- 'estimate_fee',
407
- { blockIdentifier },
408
- {
409
- type: 'DECLARE',
410
- sender_address: senderAddress,
411
- contract_class: contractDefinition,
412
- signature: bigNumberishArrayToDecimalStringArray(signature || []),
413
- version: toHex(toBN(details?.version || 1)),
414
- nonce: toHex(toBN(details.nonce)),
415
- }
416
- ).then(this.responseParser.parseFeeEstimateResponse);
417
- }
418
-
419
- public async getDeployAccountEstimateFee(
420
- { classHash, addressSalt, constructorCalldata, signature }: DeployAccountContractTransaction,
421
- details: InvocationsDetailsWithNonce,
422
- blockIdentifier: BlockIdentifier = this.blockIdentifier
423
- ): Promise<EstimateFeeResponse> {
424
- return this.fetchEndpoint(
425
- 'estimate_fee',
426
- { blockIdentifier },
427
- {
428
- type: 'DEPLOY_ACCOUNT',
429
- class_hash: toHex(toBN(classHash)),
430
- constructor_calldata: bigNumberishArrayToDecimalStringArray(constructorCalldata || []),
431
- contract_address_salt: toHex(toBN(addressSalt || 0)),
432
- signature: bigNumberishArrayToDecimalStringArray(signature || []),
433
- version: toHex(toBN(details?.version || 0)),
434
- nonce: toHex(toBN(details.nonce)),
435
- }
436
- ).then(this.responseParser.parseFeeEstimateResponse);
437
- }
438
-
439
- public async getCode(
440
- contractAddress: string,
441
- blockIdentifier: BlockIdentifier = this.blockIdentifier
442
- ): Promise<Sequencer.GetCodeResponse> {
443
- return this.fetchEndpoint('get_code', { contractAddress, blockIdentifier });
444
- }
445
-
446
- public async waitForTransaction(
447
- txHash: BigNumberish,
448
- retryInterval: number = 8000,
449
- successStates = ['ACCEPTED_ON_L1', 'ACCEPTED_ON_L2', 'PENDING']
450
- ) {
451
- const errorStates = ['REJECTED', 'NOT_RECEIVED'];
452
- let onchain = false;
453
- let res;
454
-
455
- while (!onchain) {
456
- // eslint-disable-next-line no-await-in-loop
457
- await wait(retryInterval);
458
- // eslint-disable-next-line no-await-in-loop
459
- res = await this.getTransactionStatus(txHash);
460
-
461
- if (successStates.includes(res.tx_status)) {
462
- onchain = true;
463
- } else if (errorStates.includes(res.tx_status)) {
464
- const message = res.tx_failure_reason
465
- ? `${res.tx_status}: ${res.tx_failure_reason.code}\n${res.tx_failure_reason.error_message}`
466
- : res.tx_status;
467
- const error = new Error(message) as Error & { response: GetTransactionStatusResponse };
468
- error.response = res;
469
- throw error;
470
- }
471
- }
472
- const txReceipt = await this.getTransactionReceipt(txHash);
473
- return txReceipt;
474
- }
475
-
476
- /**
477
- * Gets the status of a transaction.
478
- *
479
- * [Reference](https://github.com/starkware-libs/cairo-lang/blob/f464ec4797361b6be8989e36e02ec690e74ef285/src/starkware/starknet/services/api/feeder_gateway/feeder_gateway_client.py#L48-L52)
480
- *
481
- * @param txHash
482
- * @returns the transaction status object { block_number, tx_status: NOT_RECEIVED | RECEIVED | PENDING | REJECTED | ACCEPTED_ONCHAIN }
483
- */
484
- public async getTransactionStatus(txHash: BigNumberish): Promise<GetTransactionStatusResponse> {
485
- const txHashHex = toHex(toBN(txHash));
486
- return this.fetchEndpoint('get_transaction_status', { transactionHash: txHashHex });
487
- }
488
-
489
- /**
490
- * Gets the smart contract address on the goerli testnet.
491
- *
492
- * [Reference](https://github.com/starkware-libs/cairo-lang/blob/f464ec4797361b6be8989e36e02ec690e74ef285/src/starkware/starknet/services/api/feeder_gateway/feeder_gateway_client.py#L13-L15)
493
- * @returns starknet smart contract addresses
494
- */
495
- public async getContractAddresses(): Promise<GetContractAddressesResponse> {
496
- return this.fetchEndpoint('get_contract_addresses');
497
- }
498
-
499
- /**
500
- * Gets the transaction trace from a tx id.
501
- *
502
- * @param txHash
503
- * @returns the transaction trace
504
- */
505
- public async getTransactionTrace(txHash: BigNumberish): Promise<GetTransactionTraceResponse> {
506
- const txHashHex = toHex(toBN(txHash));
507
- return this.fetchEndpoint('get_transaction_trace', { transactionHash: txHashHex });
508
- }
509
-
510
- public async estimateMessageFee(
511
- { from_address, to_address, entry_point_selector, payload }: CallL1Handler,
512
- blockIdentifier: BlockIdentifier = this.blockIdentifier
513
- ): Promise<Sequencer.EstimateFeeResponse> {
514
- const validCallL1Handler = {
515
- from_address: getDecimalString(from_address),
516
- to_address: getHexString(to_address),
517
- entry_point_selector: getSelector(entry_point_selector),
518
- payload: getHexStringArray(payload),
519
- };
520
-
521
- return this.fetchEndpoint('estimate_message_fee', { blockIdentifier }, validCallL1Handler);
522
- }
523
- }
@@ -1,100 +0,0 @@
1
- /* eslint-disable max-classes-per-file */
2
- import { BN } from 'bn.js';
3
-
4
- import type { BlockNumber } from '../types';
5
- import { BigNumberish, isHex, toBN, toHex } from '../utils/number';
6
-
7
- /**
8
- *
9
- * [Reference](https://github.com/starkware-libs/cairo-lang/blob/fc97bdd8322a7df043c87c371634b26c15ed6cee/src/starkware/starknet/services/api/feeder_gateway/feeder_gateway_client.py#L148-L153)
10
- *
11
- * @param hashValue
12
- * @param hashField
13
- */
14
- export function formatHash(hashValue: BigNumberish): string {
15
- if (typeof hashValue === 'string') return hashValue;
16
- return toHex(toBN(hashValue));
17
- }
18
-
19
- /**
20
- *
21
- * [Reference](https://github.com/starkware-libs/cairo-lang/blob/fc97bdd8322a7df043c87c371634b26c15ed6cee/src/starkware/starknet/services/api/feeder_gateway/feeder_gateway_client.py#L156-L161)
22
- * @param txHash
23
- * @param txId
24
- */
25
- export function txIdentifier(txHash?: BigNumberish, txId?: BigNumberish): string {
26
- if (!txHash) {
27
- return `transactionId=${JSON.stringify(txId)}`;
28
- }
29
- const hashString = formatHash(txHash);
30
-
31
- return `transactionHash=${hashString}`;
32
- }
33
-
34
- // hex string and BN are detected as block hashes
35
- // decimal string and number are detected as block numbers
36
- // null appends nothing to the request url
37
-
38
- export type BlockIdentifier = BlockNumber | BigNumberish;
39
- export const validBlockTags = ['latest', 'pending'];
40
-
41
- export class Block {
42
- hash: BlockIdentifier = null;
43
-
44
- number: BlockIdentifier = null;
45
-
46
- tag: BlockIdentifier = null;
47
-
48
- private setIdentifier(__identifier: BlockIdentifier) {
49
- if (typeof __identifier === 'string' && isHex(__identifier)) {
50
- this.hash = __identifier;
51
- } else if (BN.isBN(__identifier)) {
52
- this.hash = toHex(__identifier);
53
- } else if (typeof __identifier === 'number') {
54
- this.number = __identifier;
55
- } else if (typeof __identifier === 'string' && validBlockTags.includes(__identifier)) {
56
- this.tag = __identifier;
57
- } else {
58
- // default
59
- this.tag = 'pending';
60
- }
61
- }
62
-
63
- constructor(_identifier: BlockIdentifier) {
64
- this.setIdentifier(_identifier);
65
- }
66
-
67
- // TODO: fix any
68
- get queryIdentifier(): any {
69
- if (this.number !== null) {
70
- return `blockNumber=${this.number}`;
71
- }
72
-
73
- if (this.hash !== null) {
74
- return `blockHash=${this.hash}`;
75
- }
76
-
77
- return `blockNumber=${this.tag}`;
78
- }
79
-
80
- // TODO: fix any
81
- get identifier(): any {
82
- if (this.number !== null) {
83
- return { block_number: this.number };
84
- }
85
-
86
- if (this.hash !== null) {
87
- return { block_hash: this.hash };
88
- }
89
-
90
- return this.tag;
91
- }
92
-
93
- set identifier(_identifier: BlockIdentifier) {
94
- this.setIdentifier(_identifier);
95
- }
96
-
97
- valueOf = () => this.number;
98
-
99
- toString = () => this.hash;
100
- }