starknet 3.15.1 → 3.15.4

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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,27 @@
1
+ ## [3.15.4](https://github.com/0xs34n/starknet.js/compare/v3.15.3...v3.15.4) (2022-06-20)
2
+
3
+ ### Bug Fixes
4
+
5
+ - **parseResponse:** revert the changes from parseResponse ([d51996f](https://github.com/0xs34n/starknet.js/commit/d51996fa7635428ad4ffe271aa56f202ddcd4179))
6
+ - **provider:** allow the user to handle the contract errors ([5190f7a](https://github.com/0xs34n/starknet.js/commit/5190f7a20fb35382756d86cc67d3fab5c2d541ff))
7
+ - **test:** fix callContract() test ([b11c5da](https://github.com/0xs34n/starknet.js/commit/b11c5daf7fec6e8207dbc0be534aade8e00d5021))
8
+
9
+ ## [3.15.3](https://github.com/0xs34n/starknet.js/compare/v3.15.2...v3.15.3) (2022-06-20)
10
+
11
+ ### Bug Fixes
12
+
13
+ - **dev:** regenerated package-lock.json ([849cb1e](https://github.com/0xs34n/starknet.js/commit/849cb1ea3ffd7ba10b40b232d0ebc46b6599c7ea))
14
+ - use cross-fetch only for jest ([83be37a](https://github.com/0xs34n/starknet.js/commit/83be37a9e3328a44abd9583b8167c3cb8d882790))
15
+
16
+ ## [3.15.2](https://github.com/0xs34n/starknet.js/compare/v3.15.1...v3.15.2) (2022-06-18)
17
+
18
+ ### Bug Fixes
19
+
20
+ - **cleanup:** cleanup ([a15b6c6](https://github.com/0xs34n/starknet.js/commit/a15b6c6bf13ce7af699c293d697b5136188388c3))
21
+ - **errorcode:** fixed error code >=400 instead of !=200 ([0f16595](https://github.com/0xs34n/starknet.js/commit/0f1659543ba95ce7cac31a5182dad2e33325d4c1))
22
+ - **fetchEndpoint:** error handling and test case fix ([629479f](https://github.com/0xs34n/starknet.js/commit/629479f877aa7d6f39c8d31b2c9449563aadd0e7))
23
+ - **verify:** return false when 500 returned from the gateway ([de3e004](https://github.com/0xs34n/starknet.js/commit/de3e00461730d6fa112046169470d7a603baa296))
24
+
1
25
  ## [3.15.1](https://github.com/0xs34n/starknet.js/compare/v3.15.0...v3.15.1) (2022-06-17)
2
26
 
3
27
  ### Bug Fixes
@@ -128,9 +128,15 @@ describe('deploy and test Wallet', () => {
128
128
  expect(toBN(response.number as string).toString()).toStrictEqual('57');
129
129
  });
130
130
 
131
- test('sign and verify offchain message', async () => {
131
+ test('sign and verify offchain message fail', async () => {
132
132
  const signature = await account.signMessage(typedDataExample);
133
+ // change the signature to make it invalid
134
+ signature[0] += '123';
135
+ expect(await account.verifyMessage(typedDataExample, signature)).toBe(false);
136
+ });
133
137
 
138
+ test('sign and verify offchain message', async () => {
139
+ const signature = await account.signMessage(typedDataExample);
134
140
  expect(await account.verifyMessage(typedDataExample, signature)).toBe(true);
135
141
  });
136
142
 
@@ -17,12 +17,13 @@ const DEFAULT_TEST_ACCOUNT_ADDRESS = // run `starknet-devnet --seed 0` and this
17
17
  '0x65d53c8ec4178096167b35a08e16e548d8075cb08ad7bc63d07966ca13569dc';
18
18
  const DEFAULT_TEST_ACCOUNT_PRIVATE_KEY = '0xe3e70682c2094cac629f6fbed82c07cd';
19
19
 
20
- export const getTestProvider = () => {
21
- const baseUrl = process.env.TEST_PROVIDER_BASE_URL || DEFAULT_TEST_PROVIDER_BASE_URL;
20
+ const BASE_URL = process.env.TEST_PROVIDER_BASE_URL || DEFAULT_TEST_PROVIDER_BASE_URL;
21
+ export const IS_DEVNET = !BASE_URL.includes('starknet.io');
22
22
 
23
- const provider = new Provider({ baseUrl });
23
+ export const getTestProvider = () => {
24
+ const provider = new Provider({ baseUrl: BASE_URL });
24
25
 
25
- if (baseUrl.includes('localhost') || baseUrl.includes('127.0.0.1')) {
26
+ if (IS_DEVNET) {
26
27
  // accelerate the tests when running locally
27
28
  const originalWaitForTransaction = provider.waitForTransaction.bind(provider);
28
29
  provider.waitForTransaction = (txHash, retryInterval) => {
@@ -43,3 +44,7 @@ export const getTestAccount = () => {
43
44
 
44
45
  return new Account(provider, testAccountAddress, ec.getKeyPair(testAccountPrivateKey));
45
46
  };
47
+
48
+ export const testIf = (condition: boolean) => (condition ? test : test.skip);
49
+ export const testIfDevnet = testIf(IS_DEVNET);
50
+ export const testIfNotDevnet = testIf(!IS_DEVNET);
@@ -1,6 +1,9 @@
1
1
  /* eslint-disable no-console */
2
+ import fetch from 'cross-fetch';
2
3
  import { register } from 'fetch-intercept';
3
4
 
5
+ global.fetch = fetch;
6
+
4
7
  jest.setTimeout(50 * 60 * 1000);
5
8
 
6
9
  if (process.env.DEBUG === 'true') {
@@ -1,13 +1,17 @@
1
1
  import { BlockNumber, stark } from '../src';
2
2
  import { toBN } from '../src/utils/number';
3
- import { compiledErc20, compiledOpenZeppelinAccount, getTestProvider } from './fixtures';
3
+ import {
4
+ IS_DEVNET,
5
+ compiledErc20,
6
+ compiledOpenZeppelinAccount,
7
+ getTestProvider,
8
+ testIfNotDevnet,
9
+ } from './fixtures';
4
10
 
5
11
  const { compileCalldata } = stark;
6
12
 
7
13
  const provider = getTestProvider();
8
14
 
9
- const testIf = (condition: boolean) => (condition ? test : test.skip);
10
-
11
15
  describe('defaultProvider', () => {
12
16
  let exampleTransactionHash: string;
13
17
  let exampleContractAddress: string;
@@ -30,7 +34,7 @@ describe('defaultProvider', () => {
30
34
  });
31
35
 
32
36
  describe('feeder gateway endpoints', () => {
33
- testIf(provider.baseUrl.includes('starknet.io'))('getContractAddresses()', async () => {
37
+ testIfNotDevnet('getContractAddresses()', async () => {
34
38
  // not supported in starknet-devnet
35
39
  const { GpsStatementVerifier, Starknet } = await provider.getContractAddresses();
36
40
  expect(typeof GpsStatementVerifier).toBe('string');
@@ -103,6 +107,28 @@ describe('defaultProvider', () => {
103
107
  ).resolves.not.toThrow();
104
108
  });
105
109
 
110
+ test('callContract() - gateway error', async () => {
111
+ const promise = provider.callContract({
112
+ contractAddress: exampleContractAddress,
113
+ entrypoint: 'non_existent_entrypoint',
114
+ calldata: compileCalldata({
115
+ user: '0xdeadbeef',
116
+ }),
117
+ });
118
+ expect(promise).rejects.toHaveProperty('errorCode');
119
+ expect(promise).rejects.toThrowErrorMatchingInlineSnapshot(
120
+ `"Entry point 0x23b0c8b3d98aa73d8a35f5303fe77d132c6d04279e63f6e1d6aac5946e04612 not found in contract with class hash 0x2864c45bd4ba3e66d8f7855adcadf07205c88f43806ffca664f1f624765207e."`
121
+ );
122
+
123
+ try {
124
+ await promise;
125
+ } catch (e) {
126
+ expect(e.errorCode).toMatchInlineSnapshot(
127
+ IS_DEVNET ? `500n` : `"StarknetErrorCode.ENTRY_POINT_NOT_FOUND_IN_CONTRACT"`
128
+ );
129
+ }
130
+ });
131
+
106
132
  test('transaction trace', async () => {
107
133
  const transactionTrace = await provider.getTransactionTrace(exampleTransactionHash);
108
134
  expect(transactionTrace).toHaveProperty('function_invocation');
@@ -1,4 +1,6 @@
1
1
  import typedDataExample from '../../__mocks__/typedDataExample.json';
2
+ import { number } from '../../src';
3
+ import { BigNumberish } from '../../src/utils/number';
2
4
  import { encodeType, getMessageHash, getStructHash, getTypeHash } from '../../src/utils/typedData';
3
5
 
4
6
  describe('typedData', () => {
@@ -34,4 +36,66 @@ describe('typedData', () => {
34
36
  `"0x6fcff244f63e38b9d88b9e3378d44757710d1b244282b435cb472053c8d78d0"`
35
37
  );
36
38
  });
39
+
40
+ interface StringStruct {
41
+ len: BigNumberish;
42
+ data: BigNumberish[];
43
+ }
44
+ function stringToStringStruct(str: string): StringStruct {
45
+ const len = str.length;
46
+ const data = str.split('').map((char) => number.toHex(number.toBN(char.charCodeAt(0))));
47
+ return { len, data };
48
+ }
49
+
50
+ const typedDataStringExample = {
51
+ types: {
52
+ StarkNetDomain: [
53
+ { name: 'name', type: 'felt' },
54
+ { name: 'version', type: 'felt' },
55
+ { name: 'chainId', type: 'felt' },
56
+ ],
57
+ Person: [
58
+ { name: 'name', type: 'felt' },
59
+ { name: 'wallet', type: 'felt' },
60
+ ],
61
+ String: [
62
+ { name: 'len', type: 'felt' },
63
+ { name: 'data', type: 'felt*' },
64
+ ],
65
+ Mail: [
66
+ { name: 'from', type: 'Person' },
67
+ { name: 'to', type: 'Person' },
68
+ { name: 'contents', type: 'String' },
69
+ ],
70
+ },
71
+ primaryType: 'Mail',
72
+ domain: {
73
+ name: 'StarkNet Mail',
74
+ version: '1',
75
+ chainId: 1,
76
+ },
77
+ message: {
78
+ from: {
79
+ name: 'Cow',
80
+ wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826',
81
+ },
82
+ to: {
83
+ name: 'Bob',
84
+ wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB',
85
+ },
86
+ contents: stringToStringStruct(
87
+ 'this is way longer than just 32 characters, to test if that is possible within a typedData struct.'
88
+ ),
89
+ },
90
+ };
91
+
92
+ test('should transform strings correctly', () => {
93
+ const hash = getMessageHash(
94
+ typedDataStringExample,
95
+ '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826'
96
+ );
97
+ expect(hash).toMatchInlineSnapshot(
98
+ `"0x70338fb11b8f70b68b261de8a322bcb004bd85e88ac47d9147982c7f5ac66fd"`
99
+ );
100
+ });
37
101
  });
@@ -67,7 +67,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
67
67
  };
68
68
  Object.defineProperty(exports, "__esModule", { value: true });
69
69
  exports.Provider = void 0;
70
- var cross_fetch_1 = __importDefault(require("cross-fetch"));
71
70
  var url_join_1 = __importDefault(require("url-join"));
72
71
  var constants_1 = require("../constants");
73
72
  var hash_1 = require("../utils/hash");
@@ -184,30 +183,53 @@ var Provider = /** @class */ (function () {
184
183
  // typescript type magiuc to create a nice fitting function interface
185
184
  var _b = __read(_a, 2), query = _b[0], request = _b[1]; // when both query and request are needed, we cant omit anything
186
185
  return __awaiter(this, void 0, void 0, function () {
187
- var baseUrl, method, queryString, headers, url;
186
+ var baseUrl, method, queryString, headers, url, res, textResponse, responseBody, errorCode, err_1;
188
187
  return __generator(this, function (_c) {
189
- baseUrl = this.getFetchUrl(endpoint);
190
- method = this.getFetchMethod(endpoint);
191
- queryString = this.getQueryString(query);
192
- headers = this.getHeaders(method);
193
- url = (0, url_join_1.default)(baseUrl, endpoint, queryString);
194
- return [2 /*return*/, (0, cross_fetch_1.default)(url, {
195
- method: method,
196
- body: (0, json_1.stringify)(request),
197
- headers: headers,
198
- })
199
- .then(function (res) { return res.text(); })
200
- .then(function (res) {
188
+ switch (_c.label) {
189
+ case 0:
190
+ baseUrl = this.getFetchUrl(endpoint);
191
+ method = this.getFetchMethod(endpoint);
192
+ queryString = this.getQueryString(query);
193
+ headers = this.getHeaders(method);
194
+ url = (0, url_join_1.default)(baseUrl, endpoint, queryString);
195
+ _c.label = 1;
196
+ case 1:
197
+ _c.trys.push([1, 4, , 5]);
198
+ return [4 /*yield*/, fetch(url, {
199
+ method: method,
200
+ body: (0, json_1.stringify)(request),
201
+ headers: headers,
202
+ })];
203
+ case 2:
204
+ res = _c.sent();
205
+ return [4 /*yield*/, res.text()];
206
+ case 3:
207
+ textResponse = _c.sent();
208
+ if (!res.ok) {
209
+ responseBody = (0, json_1.parse)(textResponse);
210
+ errorCode = responseBody.code || (responseBody === null || responseBody === void 0 ? void 0 : responseBody.status_code);
211
+ throw new utils_1.GatewayError(responseBody.message, errorCode); // Caught locally, and re-thrown for the user
212
+ }
201
213
  if (endpoint === 'estimate_fee') {
202
- return (0, json_1.parse)(res, function (_, v) {
203
- if (v && typeof v === 'bigint') {
204
- return (0, number_1.toBN)(v.toString());
205
- }
206
- return v;
207
- });
214
+ return [2 /*return*/, (0, json_1.parse)(textResponse, function (_, v) {
215
+ if (v && typeof v === 'bigint') {
216
+ return (0, number_1.toBN)(v.toString());
217
+ }
218
+ return v;
219
+ })];
208
220
  }
209
- return (0, json_1.parse)(res);
210
- })];
221
+ return [2 /*return*/, (0, json_1.parse)(textResponse)];
222
+ case 4:
223
+ err_1 = _c.sent();
224
+ if (err_1 instanceof utils_1.GatewayError) {
225
+ throw err_1;
226
+ }
227
+ if (err_1 instanceof Error) {
228
+ throw Error("Could not ".concat(method, " from endpoint `").concat(url, "`: ").concat(err_1.message));
229
+ }
230
+ throw err_1;
231
+ case 5: return [2 /*return*/];
232
+ }
211
233
  });
212
234
  });
213
235
  };
@@ -39,4 +39,8 @@ export declare function getBlockIdentifier(blockIdentifier: BlockIdentifier): Bl
39
39
  * @returns block identifier for API request
40
40
  */
41
41
  export declare function getFormattedBlockIdentifier(blockIdentifier?: BlockIdentifier): string;
42
+ export declare class GatewayError extends Error {
43
+ errorCode: string;
44
+ constructor(message: string, errorCode: string);
45
+ }
42
46
  export {};
@@ -1,6 +1,21 @@
1
1
  "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
2
17
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getFormattedBlockIdentifier = exports.getBlockIdentifier = exports.txIdentifier = exports.formatHash = void 0;
18
+ exports.GatewayError = exports.getFormattedBlockIdentifier = exports.getBlockIdentifier = exports.txIdentifier = exports.formatHash = void 0;
4
19
  var number_1 = require("../utils/number");
5
20
  /**
6
21
  *
@@ -42,7 +57,7 @@ function getBlockIdentifier(blockIdentifier) {
42
57
  if (blockIdentifier === 'pending') {
43
58
  return { type: 'BLOCK_NUMBER', data: 'pending' };
44
59
  }
45
- if (typeof blockIdentifier === 'number') {
60
+ if (typeof blockIdentifier === 'number' || typeof blockIdentifier === 'bigint') {
46
61
  return { type: 'BLOCK_NUMBER', data: blockIdentifier };
47
62
  }
48
63
  if (typeof blockIdentifier === 'string' && blockIdentifier.startsWith('0x')) {
@@ -77,3 +92,13 @@ function getFormattedBlockIdentifier(blockIdentifier) {
77
92
  return "blockHash=".concat((0, number_1.toHex)((0, number_1.toBN)(blockIdentifierObject.data)));
78
93
  }
79
94
  exports.getFormattedBlockIdentifier = getFormattedBlockIdentifier;
95
+ var GatewayError = /** @class */ (function (_super) {
96
+ __extends(GatewayError, _super);
97
+ function GatewayError(message, errorCode) {
98
+ var _this = _super.call(this, message) || this;
99
+ _this.errorCode = errorCode;
100
+ return _this;
101
+ }
102
+ return GatewayError;
103
+ }(Error));
104
+ exports.GatewayError = GatewayError;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "starknet",
3
- "version": "3.15.1",
3
+ "version": "3.15.4",
4
4
  "description": "JavaScript library for StarkNet",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -43,14 +43,17 @@
43
43
  "@types/minimalistic-assert": "^1.0.1",
44
44
  "@types/pako": "^2.0.0",
45
45
  "@types/url-join": "^4.0.1",
46
+ "@types/whatwg-fetch": "^0.0.33",
46
47
  "@typescript-eslint/eslint-plugin": "^5.28.0",
47
48
  "@typescript-eslint/parser": "^5.28.0",
49
+ "cross-fetch": "^3.1.5",
48
50
  "eslint": "^8.17.0",
49
51
  "eslint-config-airbnb-base": "^15.0.0",
50
52
  "eslint-config-airbnb-typescript": "^17.0.0",
51
53
  "eslint-config-prettier": "^8.5.0",
52
54
  "eslint-plugin-import": "^2.26.0",
53
55
  "eslint-plugin-prettier": "^4.0.0",
56
+ "fetch-intercept": "^2.4.0",
54
57
  "husky": "^8.0.1",
55
58
  "import-sort-style-module": "^6.0.0",
56
59
  "jest": "^28.1.1",
@@ -68,7 +71,6 @@
68
71
  "cross-fetch": "^3.1.5",
69
72
  "elliptic": "^6.5.4",
70
73
  "ethereum-cryptography": "^1.0.3",
71
- "fetch-intercept": "^2.4.0",
72
74
  "hash.js": "^1.1.7",
73
75
  "json-bigint": "^1.0.0",
74
76
  "minimalistic-assert": "^1.0.1",
@@ -173,7 +173,6 @@ var __importDefault =
173
173
  };
174
174
  Object.defineProperty(exports, '__esModule', { value: true });
175
175
  exports.Provider = void 0;
176
- var cross_fetch_1 = __importDefault(require('cross-fetch'));
177
176
  var url_join_1 = __importDefault(require('url-join'));
178
177
  var constants_1 = require('../constants');
179
178
  var hash_1 = require('../utils/hash');
@@ -299,35 +298,78 @@ var Provider = /** @class */ (function () {
299
298
  query = _b[0],
300
299
  request = _b[1]; // when both query and request are needed, we cant omit anything
301
300
  return __awaiter(this, void 0, void 0, function () {
302
- var baseUrl, method, queryString, headers, url;
301
+ var baseUrl,
302
+ method,
303
+ queryString,
304
+ headers,
305
+ url,
306
+ res,
307
+ textResponse,
308
+ responseBody,
309
+ errorCode,
310
+ err_1;
303
311
  return __generator(this, function (_c) {
304
- baseUrl = this.getFetchUrl(endpoint);
305
- method = this.getFetchMethod(endpoint);
306
- queryString = this.getQueryString(query);
307
- headers = this.getHeaders(method);
308
- url = (0, url_join_1.default)(baseUrl, endpoint, queryString);
309
- return [
310
- 2 /*return*/,
311
- (0, cross_fetch_1.default)(url, {
312
- method: method,
313
- body: (0, json_1.stringify)(request),
314
- headers: headers,
315
- })
316
- .then(function (res) {
317
- return res.text();
318
- })
319
- .then(function (res) {
320
- if (endpoint === 'estimate_fee') {
321
- return (0, json_1.parse)(res, function (_, v) {
312
+ switch (_c.label) {
313
+ case 0:
314
+ baseUrl = this.getFetchUrl(endpoint);
315
+ method = this.getFetchMethod(endpoint);
316
+ queryString = this.getQueryString(query);
317
+ headers = this.getHeaders(method);
318
+ url = (0, url_join_1.default)(baseUrl, endpoint, queryString);
319
+ _c.label = 1;
320
+ case 1:
321
+ _c.trys.push([1, 4, , 5]);
322
+ return [
323
+ 4 /*yield*/,
324
+ fetch(url, {
325
+ method: method,
326
+ body: (0, json_1.stringify)(request),
327
+ headers: headers,
328
+ }),
329
+ ];
330
+ case 2:
331
+ res = _c.sent();
332
+ return [4 /*yield*/, res.text()];
333
+ case 3:
334
+ textResponse = _c.sent();
335
+ if (!res.ok) {
336
+ responseBody = (0, json_1.parse)(textResponse);
337
+ errorCode =
338
+ responseBody.code ||
339
+ (responseBody === null || responseBody === void 0
340
+ ? void 0
341
+ : responseBody.status_code);
342
+ throw new utils_1.GatewayError(responseBody.message, errorCode); // Caught locally, and re-thrown for the user
343
+ }
344
+ if (endpoint === 'estimate_fee') {
345
+ return [
346
+ 2 /*return*/,
347
+ (0, json_1.parse)(textResponse, function (_, v) {
322
348
  if (v && typeof v === 'bigint') {
323
349
  return (0, number_1.toBN)(v.toString());
324
350
  }
325
351
  return v;
326
- });
327
- }
328
- return (0, json_1.parse)(res);
329
- }),
330
- ];
352
+ }),
353
+ ];
354
+ }
355
+ return [2 /*return*/, (0, json_1.parse)(textResponse)];
356
+ case 4:
357
+ err_1 = _c.sent();
358
+ if (err_1 instanceof utils_1.GatewayError) {
359
+ throw err_1;
360
+ }
361
+ if (err_1 instanceof Error) {
362
+ throw Error(
363
+ 'Could not '
364
+ .concat(method, ' from endpoint `')
365
+ .concat(url, '`: ')
366
+ .concat(err_1.message)
367
+ );
368
+ }
369
+ throw err_1;
370
+ case 5:
371
+ return [2 /*return*/];
372
+ }
331
373
  });
332
374
  });
333
375
  };
@@ -41,4 +41,8 @@ export declare function getBlockIdentifier(blockIdentifier: BlockIdentifier): Bl
41
41
  * @returns block identifier for API request
42
42
  */
43
43
  export declare function getFormattedBlockIdentifier(blockIdentifier?: BlockIdentifier): string;
44
+ export declare class GatewayError extends Error {
45
+ errorCode: string;
46
+ constructor(message: string, errorCode: string);
47
+ }
44
48
  export {};
package/provider/utils.js CHANGED
@@ -1,6 +1,32 @@
1
1
  'use strict';
2
+ var __extends =
3
+ (this && this.__extends) ||
4
+ (function () {
5
+ var extendStatics = function (d, b) {
6
+ extendStatics =
7
+ Object.setPrototypeOf ||
8
+ ({ __proto__: [] } instanceof Array &&
9
+ function (d, b) {
10
+ d.__proto__ = b;
11
+ }) ||
12
+ function (d, b) {
13
+ for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
14
+ };
15
+ return extendStatics(d, b);
16
+ };
17
+ return function (d, b) {
18
+ if (typeof b !== 'function' && b !== null)
19
+ throw new TypeError('Class extends value ' + String(b) + ' is not a constructor or null');
20
+ extendStatics(d, b);
21
+ function __() {
22
+ this.constructor = d;
23
+ }
24
+ d.prototype = b === null ? Object.create(b) : ((__.prototype = b.prototype), new __());
25
+ };
26
+ })();
2
27
  Object.defineProperty(exports, '__esModule', { value: true });
3
- exports.getFormattedBlockIdentifier =
28
+ exports.GatewayError =
29
+ exports.getFormattedBlockIdentifier =
4
30
  exports.getBlockIdentifier =
5
31
  exports.txIdentifier =
6
32
  exports.formatHash =
@@ -45,7 +71,7 @@ function getBlockIdentifier(blockIdentifier) {
45
71
  if (blockIdentifier === 'pending') {
46
72
  return { type: 'BLOCK_NUMBER', data: 'pending' };
47
73
  }
48
- if (typeof blockIdentifier === 'number') {
74
+ if (typeof blockIdentifier === 'number' || typeof blockIdentifier === 'bigint') {
49
75
  return { type: 'BLOCK_NUMBER', data: blockIdentifier };
50
76
  }
51
77
  if (typeof blockIdentifier === 'string' && blockIdentifier.startsWith('0x')) {
@@ -82,3 +108,13 @@ function getFormattedBlockIdentifier(blockIdentifier) {
82
108
  return 'blockHash='.concat((0, number_1.toHex)((0, number_1.toBN)(blockIdentifierObject.data)));
83
109
  }
84
110
  exports.getFormattedBlockIdentifier = getFormattedBlockIdentifier;
111
+ var GatewayError = /** @class */ (function (_super) {
112
+ __extends(GatewayError, _super);
113
+ function GatewayError(message, errorCode) {
114
+ var _this = _super.call(this, message) || this;
115
+ _this.errorCode = errorCode;
116
+ return _this;
117
+ }
118
+ return GatewayError;
119
+ })(Error);
120
+ exports.GatewayError = GatewayError;
@@ -1,4 +1,3 @@
1
- import fetch from 'cross-fetch';
2
1
  import urljoin from 'url-join';
3
2
 
4
3
  import { ONE, StarknetChainId, ZERO } from '../constants';
@@ -25,7 +24,7 @@ import { parse, stringify } from '../utils/json';
25
24
  import { BigNumberish, bigNumberishArrayToDecimalStringArray, toBN, toHex } from '../utils/number';
26
25
  import { compressProgram, randomAddress } from '../utils/stark';
27
26
  import { ProviderInterface } from './interface';
28
- import { BlockIdentifier, getFormattedBlockIdentifier } from './utils';
27
+ import { BlockIdentifier, GatewayError, getFormattedBlockIdentifier } from './utils';
29
28
 
30
29
  type NetworkName = 'mainnet-alpha' | 'goerli-alpha';
31
30
 
@@ -154,23 +153,39 @@ export class Provider implements ProviderInterface {
154
153
  const headers = this.getHeaders(method);
155
154
  const url = urljoin(baseUrl, endpoint, queryString);
156
155
 
157
- return fetch(url, {
158
- method,
159
- body: stringify(request),
160
- headers,
161
- })
162
- .then((res) => res.text())
163
- .then((res) => {
164
- if (endpoint === 'estimate_fee') {
165
- return parse(res, (_, v) => {
166
- if (v && typeof v === 'bigint') {
167
- return toBN(v.toString());
168
- }
169
- return v;
170
- });
171
- }
172
- return parse(res) as Endpoints[T]['RESPONSE'];
156
+ try {
157
+ const res = await fetch(url, {
158
+ method,
159
+ body: stringify(request),
160
+ headers,
173
161
  });
162
+ const textResponse = await res.text();
163
+ if (!res.ok) {
164
+ // This will allow user to handle contract errors
165
+ const responseBody = parse(textResponse);
166
+
167
+ const errorCode = responseBody.code || ((responseBody as any)?.status_code as string); // starknet-devnet uses status_code instead of code; They need to fix that
168
+ throw new GatewayError(responseBody.message, errorCode); // Caught locally, and re-thrown for the user
169
+ }
170
+
171
+ if (endpoint === 'estimate_fee') {
172
+ return parse(textResponse, (_, v) => {
173
+ if (v && typeof v === 'bigint') {
174
+ return toBN(v.toString());
175
+ }
176
+ return v;
177
+ });
178
+ }
179
+ return parse(textResponse) as Endpoints[T]['RESPONSE'];
180
+ } catch (err) {
181
+ if (err instanceof GatewayError) {
182
+ throw err;
183
+ }
184
+ if (err instanceof Error) {
185
+ throw Error(`Could not ${method} from endpoint \`${url}\`: ${err.message}`);
186
+ }
187
+ throw err;
188
+ }
174
189
  }
175
190
 
176
191
  /**
@@ -49,7 +49,7 @@ export function getBlockIdentifier(blockIdentifier: BlockIdentifier): BlockIdent
49
49
  if (blockIdentifier === 'pending') {
50
50
  return { type: 'BLOCK_NUMBER', data: 'pending' };
51
51
  }
52
- if (typeof blockIdentifier === 'number') {
52
+ if (typeof blockIdentifier === 'number' || typeof blockIdentifier === 'bigint') {
53
53
  return { type: 'BLOCK_NUMBER', data: blockIdentifier };
54
54
  }
55
55
  if (typeof blockIdentifier === 'string' && blockIdentifier.startsWith('0x')) {
@@ -82,3 +82,9 @@ export function getFormattedBlockIdentifier(blockIdentifier: BlockIdentifier = n
82
82
  }
83
83
  return `blockHash=${toHex(toBN(blockIdentifierObject.data))}`;
84
84
  }
85
+
86
+ export class GatewayError extends Error {
87
+ constructor(message: string, public errorCode: string) {
88
+ super(message);
89
+ }
90
+ }
@@ -14,6 +14,8 @@ the address helpers can be imported using:
14
14
  import { address } from 'starknet.js';
15
15
  ```
16
16
 
17
+ <br/>
18
+
17
19
  ### `getChecksumAddress(address: BigNumberish): string`
18
20
 
19
21
  This function accepts an address as a `BigNumberish` and returns the checksummed address as a string.
@@ -29,6 +31,235 @@ const checksummedAddress = address.getChecksumAddress(addressToCheck);
29
31
  console.log(checksummedAddress); // 0x02FD23D9182193775423497Fc0c472E156C57C69E4089a1967fb288a2D84e914
30
32
  ```
31
33
 
34
+ <br/>
35
+
32
36
  ### `validateChecksumAddress(address: string): boolean`
33
37
 
34
38
  This function validates the checksum address. It returns true if the address is valid, false otherwise.
39
+
40
+ <hr />
41
+
42
+ ## `stark`
43
+
44
+ Functions for stark specific manipulations.
45
+
46
+ <br/>
47
+
48
+ ### `compressProgram(jsonProgram: Program | string): CompressedProgram`
49
+
50
+ Function to compress compiled cairo program. Accepts a json file representing the compiled cairo program and returns a compressed cairo program.
51
+
52
+ <br/>
53
+
54
+ ### `randomAddress(): string`
55
+
56
+ Function that generates a random contract address.
57
+
58
+ <br/>
59
+
60
+ ### `makeAddress(input: string): string`
61
+
62
+ Function that turns an incompatible address string into stark address format. Returns a string.
63
+
64
+ Example: `0xdFD0F27FCe99b50909de0bDD328Aed6eAbe76BC5` -> `0xdfd0f27fce99b50909de0bdd328aed6eabe76bc5`
65
+
66
+ <br/>
67
+
68
+ ### `formatSignature(sig?: Signature): string[]`
69
+
70
+ Function that formats a Signature to BigNum and then to string array. Returns a string array.
71
+
72
+ <br/>
73
+
74
+ ### `compileCalldata(args: RawArgs): Calldata`
75
+
76
+ Function that creates calldata that gets sent to the contract.
77
+
78
+ ```js
79
+ await this.callContract({
80
+ contractAddress: this.address,
81
+ entrypoint: 'is_valid_signature',
82
+ calldata: compileCalldata({
83
+ hash: toBN(hash).toString(),
84
+ signature: signature.map((x) => toBN(x).toString()),
85
+ }),
86
+ });
87
+ ```
88
+
89
+ <br/>
90
+
91
+ ### `estimatedFeeToMaxFee(estimatedFee: BigNumberish, overhead: number = 0.5): BN`
92
+
93
+ Function that calculates and returns maximum fee based on the previously estimated one.
94
+
95
+ Returns a BN.
96
+
97
+ <hr />
98
+
99
+ ## `number`
100
+
101
+ Various number formatting functions.
102
+
103
+ `BN` is the `BigNum` representation imported from `bn.js` library.
104
+
105
+ ```js
106
+ export type BigNumberish = string | number | BN;
107
+ ```
108
+
109
+ <br/>
110
+
111
+ ### `isHex(hex: string): boolean`
112
+
113
+ Check if number is in hex format.
114
+
115
+ <br/>
116
+
117
+ ### `toBN(number: BigNumberish, base?: number | 'hex'): BN`
118
+
119
+ Converts BigNumberish to BN. Returns a BN.
120
+
121
+ <br/>
122
+
123
+ ### `toHex(number: BN): string`
124
+
125
+ Converts BN to hex. Returns a string.
126
+
127
+ <br/>
128
+
129
+ ### `hexToDecimalString(hex: string): string`
130
+
131
+ Converts hex string to decimal string.
132
+
133
+ <br/>
134
+
135
+ ### `toFelt(num: BigNumberish): string`
136
+
137
+ Converts BN to Felt. Returns a string.
138
+
139
+ <br/>
140
+
141
+ ### `assertInRange(input: BigNumberish, lowerBound: BigNumberish, upperBound: BigNumberish, inputName = '')`
142
+
143
+ Asserts input is equal to or greater then `lowerBound` and lower then `upperBound`. Assert message specifies inputName.
144
+ `input`, `lowerBound`, and `upperBound` should be of type BN.
145
+ `inputName` should be a string.
146
+
147
+ <br/>
148
+
149
+ ### `bigNumberishArrayToDecimalStringArray(rawCalldata: BigNumberish[]): string[]`
150
+
151
+ Convert BigNumberish array to decimal array. Used for signature conversion.
152
+
153
+ ```js
154
+ const signature = await this.signer.signTransaction(transactions, signerDetails);
155
+
156
+ {
157
+ contract_address: this.address,
158
+ entry_point_selector: getSelectorFromName('__execute__'),
159
+ calldata,
160
+ version: toHex(version),
161
+ signature: bigNumberishArrayToDecimalStringArray(signature),
162
+ }
163
+ ```
164
+
165
+ <hr />
166
+
167
+ ## `uint256`
168
+
169
+ ```js
170
+ // Represents an integer in the range [0, 2^256).
171
+ export interface Uint256 {
172
+ // The low 128 bits of the value.
173
+ low: BigNumberish;
174
+ // The high 128 bits of the value.
175
+ high: BigNumberish;
176
+ }
177
+ ```
178
+
179
+ <br/>
180
+
181
+ ### `uint256ToBN(uint256: Uint256): BN`
182
+
183
+ Function to convert `Uint256` to `BN` (big number), which uses the `bn.js` library.
184
+
185
+ <br/>
186
+
187
+ ### `isUint256(bn: BigNumberish): boolean`
188
+
189
+ Function to check if `BN` is smaller or equal to `2**256-1`.
190
+
191
+ <br/>
192
+
193
+ ### `bnToUint256(bignumber: BigNumberish): Uint256`
194
+
195
+ Function to convert `BN` to `Uint256`.
196
+
197
+ <hr />
198
+
199
+ ## `hash`
200
+
201
+ Various hashing helpers.
202
+
203
+ ### `starknetKeccak(value: string): BN`
204
+
205
+ Function to get the starknet keccak hash from a string. Returns starknet keccak hash as BigNumber.
206
+ nction to get the starknet keccak hash from a string. Returns starknet keccak hash as BigNumber.
207
+
208
+ <br/>
209
+
210
+ ### `getSelectorFromName(funcName: string)`
211
+
212
+ Function to get the hex selector from a given function name. Returns hex selector of given abi function name.
213
+
214
+ <br/>
215
+
216
+ ### `pedersen(input: [BigNumberish, BigNumberish])`
217
+
218
+ <br/>
219
+
220
+ Function to get the Pedersen hash for two arguments. Returns a string.
221
+
222
+ ### `computeHashOnElements(data: BigNumberish[])`
223
+
224
+ <br/>
225
+
226
+ Function to compute a Pedersen hash on a array of elements. Returns a string.
227
+
228
+ <br/>
229
+
230
+ ### `calculateTransactionHashCommon(txHashPrefix: TransactionHashPrefix, version: BigNumberish,contractAddress: BigNumberish, entryPointSelector: BigNumberish, calldata: BigNumberish[], maxFee: BigNumberish, chainId: StarknetChainId, additionalData: BigNumberish[] = []): string`
231
+
232
+ Calculates the transaction hash in the StarkNet network - a unique identifier of the transaction.
233
+
234
+ Called internally in `calculateDeployTransactionHash` and `calculcateTransactionHash`.
235
+
236
+ <br/>
237
+
238
+ ### `calculateDeployTransactionHash(contractAddress: BigNumberish, constructorCalldata: BigNumberish[], version: BigNumberish, chainId: StarknetChainId): string`
239
+
240
+ Function that calculates the deployment transaction hash in the StarkNet network.
241
+
242
+ Internally calls `calculateTransactionHashCommon` with `TransactionHashPrefix.DEPLOY`.
243
+
244
+ <br/>
245
+
246
+ ### `calculcateTransactionHash(contractAddress: BigNumberish, version: BigNumberish, entryPointSelector: BigNumberish, calldata: BigNumberish[], maxFee: BigNumberish, chainId: StarknetChainId): string`
247
+
248
+ Function that internally calls `calculateTransactionHashCommon`, with `TransactionHashPrefix.INVOKE`.
249
+
250
+ ```js
251
+ const hashMsg = calculcateTransactionHash(
252
+ account,
253
+ transactionVersion,
254
+ getSelectorFromName('__execute__'),
255
+ calldata,
256
+ maxFee,
257
+ StarknetChainId.TESTNET
258
+ );
259
+ ```
260
+
261
+ <br/>
262
+
263
+ ### `calculateContractAddressFromHash(salt: BigNumberish, classHash: BigNumberish, constructorCalldata: RawCalldata, deployerAddress: BigNumberish)`
264
+
265
+ Function that calculates contract address from hash. Returns a string.