starknet 3.15.3 → 3.15.6

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.6](https://github.com/0xs34n/starknet.js/compare/v3.15.5...v3.15.6) (2022-06-28)
2
+
3
+ ### Bug Fixes
4
+
5
+ - throw http error when parsing fails ([898574f](https://github.com/0xs34n/starknet.js/commit/898574f0087bf653b5d74bbe3dc52a0cb6efc432))
6
+
7
+ ## [3.15.5](https://github.com/0xs34n/starknet.js/compare/v3.15.4...v3.15.5) (2022-06-27)
8
+
9
+ ### Bug Fixes
10
+
11
+ - add return statement ([468a0bf](https://github.com/0xs34n/starknet.js/commit/468a0bfbbc1a9c88383ed2ba0f0bc02b0e5e3a9b))
12
+ - don't enforce bigInt ([efef507](https://github.com/0xs34n/starknet.js/commit/efef5071ebceb5247f5f1995d3c1006d422c02ee))
13
+ - **GatewayError:** export from index ([69addd5](https://github.com/0xs34n/starknet.js/commit/69addd5a2eb30816f5e43ffd71e190838ad5a409))
14
+ - **GatewayError:** use ts-custom-error to support "err instanceof GatewayError" ([092abbc](https://github.com/0xs34n/starknet.js/commit/092abbcff5f5270a0be0b79a8e87645637298c56))
15
+ - **test:** error 500 as number instead of bigInt ([b539144](https://github.com/0xs34n/starknet.js/commit/b5391448cf04d93c4d914ad52d850591a423fe42))
16
+
17
+ ## [3.15.4](https://github.com/0xs34n/starknet.js/compare/v3.15.3...v3.15.4) (2022-06-20)
18
+
19
+ ### Bug Fixes
20
+
21
+ - **parseResponse:** revert the changes from parseResponse ([d51996f](https://github.com/0xs34n/starknet.js/commit/d51996fa7635428ad4ffe271aa56f202ddcd4179))
22
+ - **provider:** allow the user to handle the contract errors ([5190f7a](https://github.com/0xs34n/starknet.js/commit/5190f7a20fb35382756d86cc67d3fab5c2d541ff))
23
+ - **test:** fix callContract() test ([b11c5da](https://github.com/0xs34n/starknet.js/commit/b11c5daf7fec6e8207dbc0be534aade8e00d5021))
24
+
1
25
  ## [3.15.3](https://github.com/0xs34n/starknet.js/compare/v3.15.2...v3.15.3) (2022-06-20)
2
26
 
3
27
  ### Bug Fixes
@@ -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,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');
@@ -42,8 +46,16 @@ describe('defaultProvider', () => {
42
46
  test(`getBlock(blockHash=undefined, blockNumber=${exampleBlockNumber})`, () => {
43
47
  return expect(provider.getBlock(exampleBlockNumber)).resolves.not.toThrow();
44
48
  });
45
- test('getBlock(blockHash=undefined, blockNumber=null)', () => {
46
- return expect(provider.getBlock()).resolves.not.toThrow();
49
+ test('getBlock(blockHash=undefined, blockNumber=null)', async () => {
50
+ const block = await provider.getBlock();
51
+
52
+ expect(block).not.toBeNull();
53
+
54
+ const { block_number, timestamp } = block;
55
+
56
+ expect(typeof block_number).toEqual('number');
57
+
58
+ return expect(typeof timestamp).toEqual('number');
47
59
  });
48
60
  test('getBlock() -> { blockNumber }', async () => {
49
61
  const block = await provider.getBlock();
@@ -103,6 +115,28 @@ describe('defaultProvider', () => {
103
115
  ).resolves.not.toThrow();
104
116
  });
105
117
 
118
+ test('callContract() - gateway error', async () => {
119
+ const promise = provider.callContract({
120
+ contractAddress: exampleContractAddress,
121
+ entrypoint: 'non_existent_entrypoint',
122
+ calldata: compileCalldata({
123
+ user: '0xdeadbeef',
124
+ }),
125
+ });
126
+ expect(promise).rejects.toHaveProperty('errorCode');
127
+ expect(promise).rejects.toThrowErrorMatchingInlineSnapshot(
128
+ `"Entry point 0x23b0c8b3d98aa73d8a35f5303fe77d132c6d04279e63f6e1d6aac5946e04612 not found in contract with class hash 0x2864c45bd4ba3e66d8f7855adcadf07205c88f43806ffca664f1f624765207e."`
129
+ );
130
+
131
+ try {
132
+ await promise;
133
+ } catch (e) {
134
+ expect(e.errorCode).toMatchInlineSnapshot(
135
+ IS_DEVNET ? `500` : `"StarknetErrorCode.ENTRY_POINT_NOT_FOUND_IN_CONTRACT"`
136
+ );
137
+ }
138
+ });
139
+
106
140
  test('transaction trace', async () => {
107
141
  const transactionTrace = await provider.getTransactionTrace(exampleTransactionHash);
108
142
  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
  });
@@ -73,6 +73,7 @@ var hash_1 = require("../utils/hash");
73
73
  var json_1 = require("../utils/json");
74
74
  var number_1 = require("../utils/number");
75
75
  var stark_1 = require("../utils/stark");
76
+ var errors_1 = require("./errors");
76
77
  var interface_1 = require("./interface");
77
78
  var utils_1 = require("./utils");
78
79
  function wait(delay) {
@@ -183,38 +184,61 @@ var Provider = /** @class */ (function () {
183
184
  // typescript type magiuc to create a nice fitting function interface
184
185
  var _b = __read(_a, 2), query = _b[0], request = _b[1]; // when both query and request are needed, we cant omit anything
185
186
  return __awaiter(this, void 0, void 0, function () {
186
- var baseUrl, method, queryString, headers, url;
187
+ var baseUrl, method, queryString, headers, url, res, textResponse, responseBody, errorCode, err_1;
187
188
  return __generator(this, function (_c) {
188
- baseUrl = this.getFetchUrl(endpoint);
189
- method = this.getFetchMethod(endpoint);
190
- queryString = this.getQueryString(query);
191
- headers = this.getHeaders(method);
192
- url = (0, url_join_1.default)(baseUrl, endpoint, queryString);
193
- return [2 /*return*/, fetch(url, {
194
- method: method,
195
- body: (0, json_1.stringify)(request),
196
- headers: headers,
197
- })
198
- .then(function (res) {
199
- if (res.status >= 400) {
200
- throw Error(res.statusText);
189
+ switch (_c.label) {
190
+ case 0:
191
+ baseUrl = this.getFetchUrl(endpoint);
192
+ method = this.getFetchMethod(endpoint);
193
+ queryString = this.getQueryString(query);
194
+ headers = this.getHeaders(method);
195
+ url = (0, url_join_1.default)(baseUrl, endpoint, queryString);
196
+ _c.label = 1;
197
+ case 1:
198
+ _c.trys.push([1, 4, , 5]);
199
+ return [4 /*yield*/, fetch(url, {
200
+ method: method,
201
+ body: (0, json_1.stringify)(request),
202
+ headers: headers,
203
+ })];
204
+ case 2:
205
+ res = _c.sent();
206
+ return [4 /*yield*/, res.text()];
207
+ case 3:
208
+ textResponse = _c.sent();
209
+ if (!res.ok) {
210
+ responseBody = void 0;
211
+ try {
212
+ responseBody = (0, json_1.parse)(textResponse);
213
+ }
214
+ catch (_d) {
215
+ // if error parsing fails, return an http error
216
+ throw new errors_1.HttpError(res.statusText, res.status);
217
+ }
218
+ errorCode = responseBody.code || (responseBody === null || responseBody === void 0 ? void 0 : responseBody.status_code);
219
+ throw new errors_1.GatewayError(responseBody.message, errorCode); // Caught locally, and re-thrown for the user
201
220
  }
202
- return res.text();
203
- })
204
- .then(function (res) {
205
221
  if (endpoint === 'estimate_fee') {
206
- return (0, json_1.parse)(res, function (_, v) {
207
- if (v && typeof v === 'bigint') {
208
- return (0, number_1.toBN)(v.toString());
209
- }
210
- return v;
211
- });
222
+ return [2 /*return*/, (0, json_1.parseAlwaysAsBig)(textResponse, function (_, v) {
223
+ if (v && typeof v === 'bigint') {
224
+ return (0, number_1.toBN)(v.toString());
225
+ }
226
+ return v;
227
+ })];
212
228
  }
213
- return (0, json_1.parse)(res);
214
- })
215
- .catch(function (err) {
216
- throw Error("Could not ".concat(method, " from endpoint `").concat(url, "`: ").concat(err.message));
217
- })];
229
+ return [2 /*return*/, (0, json_1.parse)(textResponse)];
230
+ case 4:
231
+ err_1 = _c.sent();
232
+ // rethrow custom errors
233
+ if (err_1 instanceof errors_1.GatewayError || err_1 instanceof errors_1.HttpError) {
234
+ throw err_1;
235
+ }
236
+ if (err_1 instanceof Error) {
237
+ throw Error("Could not ".concat(method, " from endpoint `").concat(url, "`: ").concat(err_1.message));
238
+ }
239
+ throw err_1;
240
+ case 5: return [2 /*return*/];
241
+ }
218
242
  });
219
243
  });
220
244
  };
@@ -0,0 +1,9 @@
1
+ import { CustomError } from 'ts-custom-error';
2
+ export declare class GatewayError extends CustomError {
3
+ errorCode: string;
4
+ constructor(message: string, errorCode: string);
5
+ }
6
+ export declare class HttpError extends CustomError {
7
+ errorCode: number;
8
+ constructor(message: string, errorCode: number);
9
+ }
@@ -0,0 +1,40 @@
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
+ })();
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.HttpError = exports.GatewayError = void 0;
19
+ /* eslint-disable max-classes-per-file */
20
+ var ts_custom_error_1 = require("ts-custom-error");
21
+ var GatewayError = /** @class */ (function (_super) {
22
+ __extends(GatewayError, _super);
23
+ function GatewayError(message, errorCode) {
24
+ var _this = _super.call(this, message) || this;
25
+ _this.errorCode = errorCode;
26
+ return _this;
27
+ }
28
+ return GatewayError;
29
+ }(ts_custom_error_1.CustomError));
30
+ exports.GatewayError = GatewayError;
31
+ var HttpError = /** @class */ (function (_super) {
32
+ __extends(HttpError, _super);
33
+ function HttpError(message, errorCode) {
34
+ var _this = _super.call(this, message) || this;
35
+ _this.errorCode = errorCode;
36
+ return _this;
37
+ }
38
+ return HttpError;
39
+ }(ts_custom_error_1.CustomError));
40
+ exports.HttpError = HttpError;
@@ -1,4 +1,5 @@
1
1
  import { Provider } from './default';
2
2
  export * from './default';
3
+ export * from './errors';
3
4
  export * from './interface';
4
5
  export declare const defaultProvider: Provider;
@@ -17,5 +17,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.defaultProvider = void 0;
18
18
  var default_1 = require("./default");
19
19
  __exportStar(require("./default"), exports);
20
+ __exportStar(require("./errors"), exports);
20
21
  __exportStar(require("./interface"), exports);
21
22
  exports.defaultProvider = new default_1.Provider();
@@ -1,8 +1,11 @@
1
- declare const parse: (text: string, reviver?: ((this: any, key: string, value: any) => any) | undefined) => any, stringify: {
1
+ export declare const parse: (text: string, reviver?: ((this: any, key: string, value: any) => any) | undefined) => any, stringify: {
2
+ (value: any, replacer?: ((this: any, key: string, value: any) => any) | undefined, space?: string | number | undefined): string;
3
+ (value: any, replacer?: (string | number)[] | null | undefined, space?: string | number | undefined): string;
4
+ };
5
+ export declare const parseAlwaysAsBig: (text: string, reviver?: ((this: any, key: string, value: any) => any) | undefined) => any, stringifyAlwaysAsBig: {
2
6
  (value: any, replacer?: ((this: any, key: string, value: any) => any) | undefined, space?: string | number | undefined): string;
3
7
  (value: any, replacer?: (string | number)[] | null | undefined, space?: string | number | undefined): string;
4
8
  };
5
- export { parse, stringify };
6
9
  declare const _default: {
7
10
  parse: (text: string, reviver?: ((this: any, key: string, value: any) => any) | undefined) => any;
8
11
  stringify: {
@@ -2,15 +2,18 @@
2
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
+ var _a, _b;
5
6
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.stringify = exports.parse = void 0;
7
+ exports.stringifyAlwaysAsBig = exports.parseAlwaysAsBig = exports.stringify = exports.parse = void 0;
7
8
  var json_bigint_1 = __importDefault(require("json-bigint"));
8
- var _a = (0, json_bigint_1.default)({
9
- alwaysParseAsBig: true,
10
- useNativeBigInt: true,
11
- protoAction: 'preserve',
12
- constructorAction: 'preserve',
13
- }), parse = _a.parse, stringify = _a.stringify;
14
- exports.parse = parse;
15
- exports.stringify = stringify;
16
- exports.default = { parse: parse, stringify: stringify };
9
+ var json = function (alwaysParseAsBig) {
10
+ return (0, json_bigint_1.default)({
11
+ alwaysParseAsBig: alwaysParseAsBig,
12
+ useNativeBigInt: true,
13
+ protoAction: 'preserve',
14
+ constructorAction: 'preserve',
15
+ });
16
+ };
17
+ exports.parse = (_a = json(false), _a.parse), exports.stringify = _a.stringify;
18
+ exports.parseAlwaysAsBig = (_b = json(true), _b.parse), exports.stringifyAlwaysAsBig = _b.stringify;
19
+ exports.default = { parse: exports.parse, stringify: exports.stringify };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "starknet",
3
- "version": "3.15.3",
3
+ "version": "3.15.6",
4
4
  "description": "JavaScript library for StarkNet",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -75,6 +75,7 @@
75
75
  "json-bigint": "^1.0.0",
76
76
  "minimalistic-assert": "^1.0.1",
77
77
  "pako": "^2.0.4",
78
+ "ts-custom-error": "^3.2.0",
78
79
  "url-join": "^4.0.1"
79
80
  },
80
81
  "lint-staged": {
@@ -179,6 +179,7 @@ var hash_1 = require('../utils/hash');
179
179
  var json_1 = require('../utils/json');
180
180
  var number_1 = require('../utils/number');
181
181
  var stark_1 = require('../utils/stark');
182
+ var errors_1 = require('./errors');
182
183
  var interface_1 = require('./interface');
183
184
  var utils_1 = require('./utils');
184
185
  function wait(delay) {
@@ -298,46 +299,85 @@ var Provider = /** @class */ (function () {
298
299
  query = _b[0],
299
300
  request = _b[1]; // when both query and request are needed, we cant omit anything
300
301
  return __awaiter(this, void 0, void 0, function () {
301
- var baseUrl, method, queryString, headers, url;
302
+ var baseUrl,
303
+ method,
304
+ queryString,
305
+ headers,
306
+ url,
307
+ res,
308
+ textResponse,
309
+ responseBody,
310
+ errorCode,
311
+ err_1;
302
312
  return __generator(this, function (_c) {
303
- baseUrl = this.getFetchUrl(endpoint);
304
- method = this.getFetchMethod(endpoint);
305
- queryString = this.getQueryString(query);
306
- headers = this.getHeaders(method);
307
- url = (0, url_join_1.default)(baseUrl, endpoint, queryString);
308
- return [
309
- 2 /*return*/,
310
- fetch(url, {
311
- method: method,
312
- body: (0, json_1.stringify)(request),
313
- headers: headers,
314
- })
315
- .then(function (res) {
316
- if (res.status >= 400) {
317
- throw Error(res.statusText);
313
+ switch (_c.label) {
314
+ case 0:
315
+ baseUrl = this.getFetchUrl(endpoint);
316
+ method = this.getFetchMethod(endpoint);
317
+ queryString = this.getQueryString(query);
318
+ headers = this.getHeaders(method);
319
+ url = (0, url_join_1.default)(baseUrl, endpoint, queryString);
320
+ _c.label = 1;
321
+ case 1:
322
+ _c.trys.push([1, 4, , 5]);
323
+ return [
324
+ 4 /*yield*/,
325
+ fetch(url, {
326
+ method: method,
327
+ body: (0, json_1.stringify)(request),
328
+ headers: headers,
329
+ }),
330
+ ];
331
+ case 2:
332
+ res = _c.sent();
333
+ return [4 /*yield*/, res.text()];
334
+ case 3:
335
+ textResponse = _c.sent();
336
+ if (!res.ok) {
337
+ responseBody = void 0;
338
+ try {
339
+ responseBody = (0, json_1.parse)(textResponse);
340
+ } catch (_d) {
341
+ // if error parsing fails, return an http error
342
+ throw new errors_1.HttpError(res.statusText, res.status);
318
343
  }
319
- return res.text();
320
- })
321
- .then(function (res) {
322
- if (endpoint === 'estimate_fee') {
323
- return (0, json_1.parse)(res, function (_, v) {
344
+ errorCode =
345
+ responseBody.code ||
346
+ (responseBody === null || responseBody === void 0
347
+ ? void 0
348
+ : responseBody.status_code);
349
+ throw new errors_1.GatewayError(responseBody.message, errorCode); // Caught locally, and re-thrown for the user
350
+ }
351
+ if (endpoint === 'estimate_fee') {
352
+ return [
353
+ 2 /*return*/,
354
+ (0, json_1.parseAlwaysAsBig)(textResponse, function (_, v) {
324
355
  if (v && typeof v === 'bigint') {
325
356
  return (0, number_1.toBN)(v.toString());
326
357
  }
327
358
  return v;
328
- });
329
- }
330
- return (0, json_1.parse)(res);
331
- })
332
- .catch(function (err) {
359
+ }),
360
+ ];
361
+ }
362
+ return [2 /*return*/, (0, json_1.parse)(textResponse)];
363
+ case 4:
364
+ err_1 = _c.sent();
365
+ // rethrow custom errors
366
+ if (err_1 instanceof errors_1.GatewayError || err_1 instanceof errors_1.HttpError) {
367
+ throw err_1;
368
+ }
369
+ if (err_1 instanceof Error) {
333
370
  throw Error(
334
371
  'Could not '
335
372
  .concat(method, ' from endpoint `')
336
373
  .concat(url, '`: ')
337
- .concat(err.message)
374
+ .concat(err_1.message)
338
375
  );
339
- }),
340
- ];
376
+ }
377
+ throw err_1;
378
+ case 5:
379
+ return [2 /*return*/];
380
+ }
341
381
  });
342
382
  });
343
383
  };
@@ -0,0 +1,9 @@
1
+ import { CustomError } from 'ts-custom-error';
2
+ export declare class GatewayError extends CustomError {
3
+ errorCode: string;
4
+ constructor(message: string, errorCode: string);
5
+ }
6
+ export declare class HttpError extends CustomError {
7
+ errorCode: number;
8
+ constructor(message: string, errorCode: number);
9
+ }
@@ -0,0 +1,50 @@
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
+ })();
27
+ Object.defineProperty(exports, '__esModule', { value: true });
28
+ exports.HttpError = exports.GatewayError = void 0;
29
+ /* eslint-disable max-classes-per-file */
30
+ var ts_custom_error_1 = require('ts-custom-error');
31
+ var GatewayError = /** @class */ (function (_super) {
32
+ __extends(GatewayError, _super);
33
+ function GatewayError(message, errorCode) {
34
+ var _this = _super.call(this, message) || this;
35
+ _this.errorCode = errorCode;
36
+ return _this;
37
+ }
38
+ return GatewayError;
39
+ })(ts_custom_error_1.CustomError);
40
+ exports.GatewayError = GatewayError;
41
+ var HttpError = /** @class */ (function (_super) {
42
+ __extends(HttpError, _super);
43
+ function HttpError(message, errorCode) {
44
+ var _this = _super.call(this, message) || this;
45
+ _this.errorCode = errorCode;
46
+ return _this;
47
+ }
48
+ return HttpError;
49
+ })(ts_custom_error_1.CustomError);
50
+ exports.HttpError = HttpError;
@@ -1,4 +1,5 @@
1
1
  import { Provider } from './default';
2
2
  export * from './default';
3
+ export * from './errors';
3
4
  export * from './interface';
4
5
  export declare const defaultProvider: Provider;
package/provider/index.js CHANGED
@@ -30,5 +30,6 @@ Object.defineProperty(exports, '__esModule', { value: true });
30
30
  exports.defaultProvider = void 0;
31
31
  var default_1 = require('./default');
32
32
  __exportStar(require('./default'), exports);
33
+ __exportStar(require('./errors'), exports);
33
34
  __exportStar(require('./interface'), exports);
34
35
  exports.defaultProvider = new default_1.Provider();
@@ -20,9 +20,10 @@ import {
20
20
  TransactionReceiptResponse,
21
21
  } from '../types';
22
22
  import { getSelectorFromName } from '../utils/hash';
23
- import { parse, stringify } from '../utils/json';
23
+ import { parse, parseAlwaysAsBig, stringify } from '../utils/json';
24
24
  import { BigNumberish, bigNumberishArrayToDecimalStringArray, toBN, toHex } from '../utils/number';
25
25
  import { compressProgram, randomAddress } from '../utils/stark';
26
+ import { GatewayError, HttpError } from './errors';
26
27
  import { ProviderInterface } from './interface';
27
28
  import { BlockIdentifier, getFormattedBlockIdentifier } from './utils';
28
29
 
@@ -153,31 +154,46 @@ export class Provider implements ProviderInterface {
153
154
  const headers = this.getHeaders(method);
154
155
  const url = urljoin(baseUrl, endpoint, queryString);
155
156
 
156
- return fetch(url, {
157
- method,
158
- body: stringify(request),
159
- headers,
160
- })
161
- .then((res) => {
162
- if (res.status >= 400) {
163
- throw Error(res.statusText);
164
- }
165
- return res.text();
166
- })
167
- .then((res) => {
168
- if (endpoint === 'estimate_fee') {
169
- return parse(res, (_, v) => {
170
- if (v && typeof v === 'bigint') {
171
- return toBN(v.toString());
172
- }
173
- return v;
174
- });
157
+ try {
158
+ const res = await fetch(url, {
159
+ method,
160
+ body: stringify(request),
161
+ headers,
162
+ });
163
+ const textResponse = await res.text();
164
+ if (!res.ok) {
165
+ // This will allow user to handle contract errors
166
+ let responseBody: any;
167
+ try {
168
+ responseBody = parse(textResponse);
169
+ } catch {
170
+ // if error parsing fails, return an http error
171
+ throw new HttpError(res.statusText, res.status);
175
172
  }
176
- return parse(res) as Endpoints[T]['RESPONSE'];
177
- })
178
- .catch((err) => {
173
+
174
+ const errorCode = responseBody.code || ((responseBody as any)?.status_code as string); // starknet-devnet uses status_code instead of code; They need to fix that
175
+ throw new GatewayError(responseBody.message, errorCode); // Caught locally, and re-thrown for the user
176
+ }
177
+
178
+ if (endpoint === 'estimate_fee') {
179
+ return parseAlwaysAsBig(textResponse, (_, v) => {
180
+ if (v && typeof v === 'bigint') {
181
+ return toBN(v.toString());
182
+ }
183
+ return v;
184
+ });
185
+ }
186
+ return parse(textResponse) as Endpoints[T]['RESPONSE'];
187
+ } catch (err) {
188
+ // rethrow custom errors
189
+ if (err instanceof GatewayError || err instanceof HttpError) {
190
+ throw err;
191
+ }
192
+ if (err instanceof Error) {
179
193
  throw Error(`Could not ${method} from endpoint \`${url}\`: ${err.message}`);
180
- });
194
+ }
195
+ throw err;
196
+ }
181
197
  }
182
198
 
183
199
  /**
@@ -0,0 +1,14 @@
1
+ /* eslint-disable max-classes-per-file */
2
+ import { CustomError } from 'ts-custom-error';
3
+
4
+ export class GatewayError extends CustomError {
5
+ constructor(message: string, public errorCode: string) {
6
+ super(message);
7
+ }
8
+ }
9
+
10
+ export class HttpError extends CustomError {
11
+ constructor(message: string, public errorCode: number) {
12
+ super(message);
13
+ }
14
+ }
@@ -1,6 +1,7 @@
1
1
  import { Provider } from './default';
2
2
 
3
3
  export * from './default';
4
+ export * from './errors';
4
5
  export * from './interface';
5
6
 
6
7
  export const defaultProvider = new Provider();
package/src/utils/json.ts CHANGED
@@ -1,11 +1,15 @@
1
1
  import Json from 'json-bigint';
2
2
 
3
- const { parse, stringify } = Json({
4
- alwaysParseAsBig: true,
5
- useNativeBigInt: true,
6
- protoAction: 'preserve',
7
- constructorAction: 'preserve',
8
- });
3
+ const json = (alwaysParseAsBig: boolean) => {
4
+ return Json({
5
+ alwaysParseAsBig,
6
+ useNativeBigInt: true,
7
+ protoAction: 'preserve',
8
+ constructorAction: 'preserve',
9
+ });
10
+ };
11
+
12
+ export const { parse, stringify } = json(false);
13
+ export const { parse: parseAlwaysAsBig, stringify: stringifyAlwaysAsBig } = json(true);
9
14
 
10
- export { parse, stringify };
11
15
  export default { parse, stringify };
package/utils/json.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- declare const parse: (
1
+ export declare const parse: (
2
2
  text: string,
3
3
  reviver?: ((this: any, key: string, value: any) => any) | undefined
4
4
  ) => any,
@@ -14,7 +14,22 @@ declare const parse: (
14
14
  space?: string | number | undefined
15
15
  ): string;
16
16
  };
17
- export { parse, stringify };
17
+ export declare const parseAlwaysAsBig: (
18
+ text: string,
19
+ reviver?: ((this: any, key: string, value: any) => any) | undefined
20
+ ) => any,
21
+ stringifyAlwaysAsBig: {
22
+ (
23
+ value: any,
24
+ replacer?: ((this: any, key: string, value: any) => any) | undefined,
25
+ space?: string | number | undefined
26
+ ): string;
27
+ (
28
+ value: any,
29
+ replacer?: (string | number)[] | null | undefined,
30
+ space?: string | number | undefined
31
+ ): string;
32
+ };
18
33
  declare const _default: {
19
34
  parse: (text: string, reviver?: ((this: any, key: string, value: any) => any) | undefined) => any;
20
35
  stringify: {
package/utils/json.js CHANGED
@@ -4,17 +4,23 @@ var __importDefault =
4
4
  function (mod) {
5
5
  return mod && mod.__esModule ? mod : { default: mod };
6
6
  };
7
+ var _a, _b;
7
8
  Object.defineProperty(exports, '__esModule', { value: true });
8
- exports.stringify = exports.parse = void 0;
9
+ exports.stringifyAlwaysAsBig =
10
+ exports.parseAlwaysAsBig =
11
+ exports.stringify =
12
+ exports.parse =
13
+ void 0;
9
14
  var json_bigint_1 = __importDefault(require('json-bigint'));
10
- var _a = (0, json_bigint_1.default)({
11
- alwaysParseAsBig: true,
15
+ var json = function (alwaysParseAsBig) {
16
+ return (0, json_bigint_1.default)({
17
+ alwaysParseAsBig: alwaysParseAsBig,
12
18
  useNativeBigInt: true,
13
19
  protoAction: 'preserve',
14
20
  constructorAction: 'preserve',
15
- }),
16
- parse = _a.parse,
17
- stringify = _a.stringify;
18
- exports.parse = parse;
19
- exports.stringify = stringify;
20
- exports.default = { parse: parse, stringify: stringify };
21
+ });
22
+ };
23
+ (exports.parse = ((_a = json(false)), _a.parse)), (exports.stringify = _a.stringify);
24
+ (exports.parseAlwaysAsBig = ((_b = json(true)), _b.parse)),
25
+ (exports.stringifyAlwaysAsBig = _b.stringify);
26
+ exports.default = { parse: exports.parse, stringify: exports.stringify };
@@ -59,7 +59,7 @@ Function that generates a random contract address.
59
59
 
60
60
  ### `makeAddress(input: string): string`
61
61
 
62
- Function that turns an incompatible address string into stark address format. Returns a string.
62
+ Function that turns an incompatible address string into stark address format. Returns a string.
63
63
 
64
64
  Example: `0xdFD0F27FCe99b50909de0bDD328Aed6eAbe76BC5` -> `0xdfd0f27fce99b50909de0bdd328aed6eabe76bc5`
65
65
 
@@ -90,7 +90,7 @@ await this.callContract({
90
90
 
91
91
  ### `estimatedFeeToMaxFee(estimatedFee: BigNumberish, overhead: number = 0.5): BN`
92
92
 
93
- Function that calculates and returns maximum fee based on the previously estimated one.
93
+ Function that calculates and returns maximum fee based on the previously estimated one.
94
94
 
95
95
  Returns a BN.
96
96
 
@@ -150,7 +150,7 @@ Asserts input is equal to or greater then `lowerBound` and lower then `upperBoun
150
150
 
151
151
  Convert BigNumberish array to decimal array. Used for signature conversion.
152
152
 
153
- ``` js
153
+ ```js
154
154
  const signature = await this.signer.signTransaction(transactions, signerDetails);
155
155
 
156
156
  {
@@ -229,7 +229,7 @@ Function to compute a Pedersen hash on a array of elements. Returns a string.
229
229
 
230
230
  ### `calculateTransactionHashCommon(txHashPrefix: TransactionHashPrefix, version: BigNumberish,contractAddress: BigNumberish, entryPointSelector: BigNumberish, calldata: BigNumberish[], maxFee: BigNumberish, chainId: StarknetChainId, additionalData: BigNumberish[] = []): string`
231
231
 
232
- Calculates the transaction hash in the StarkNet network - a unique identifier of the transaction.
232
+ Calculates the transaction hash in the StarkNet network - a unique identifier of the transaction.
233
233
 
234
234
  Called internally in `calculateDeployTransactionHash` and `calculcateTransactionHash`.
235
235
 
@@ -262,4 +262,4 @@ const hashMsg = calculcateTransactionHash(
262
262
 
263
263
  ### `calculateContractAddressFromHash(salt: BigNumberish, classHash: BigNumberish, constructorCalldata: RawCalldata, deployerAddress: BigNumberish)`
264
264
 
265
- Function that calculates contract address from hash. Returns a string.
265
+ Function that calculates contract address from hash. Returns a string.
@@ -31,7 +31,7 @@ You can also get a key pair from a private key using `getKeyPair(pk: BigNumberis
31
31
 
32
32
  ```javascript
33
33
  const starkKeyPair = ec.genKeyPair();
34
- const starkKeyPub = ec.getStarkKey(starkKeyPair);;
34
+ const starkKeyPub = ec.getStarkKey(starkKeyPair);
35
35
  ```
36
36
 
37
37
  ## Deploy Account Contract