starknet 3.15.2 → 3.15.5

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,28 @@
1
+ ## [3.15.5](https://github.com/0xs34n/starknet.js/compare/v3.15.4...v3.15.5) (2022-06-27)
2
+
3
+ ### Bug Fixes
4
+
5
+ - add return statement ([468a0bf](https://github.com/0xs34n/starknet.js/commit/468a0bfbbc1a9c88383ed2ba0f0bc02b0e5e3a9b))
6
+ - don't enforce bigInt ([efef507](https://github.com/0xs34n/starknet.js/commit/efef5071ebceb5247f5f1995d3c1006d422c02ee))
7
+ - **GatewayError:** export from index ([69addd5](https://github.com/0xs34n/starknet.js/commit/69addd5a2eb30816f5e43ffd71e190838ad5a409))
8
+ - **GatewayError:** use ts-custom-error to support "err instanceof GatewayError" ([092abbc](https://github.com/0xs34n/starknet.js/commit/092abbcff5f5270a0be0b79a8e87645637298c56))
9
+ - **test:** error 500 as number instead of bigInt ([b539144](https://github.com/0xs34n/starknet.js/commit/b5391448cf04d93c4d914ad52d850591a423fe42))
10
+
11
+ ## [3.15.4](https://github.com/0xs34n/starknet.js/compare/v3.15.3...v3.15.4) (2022-06-20)
12
+
13
+ ### Bug Fixes
14
+
15
+ - **parseResponse:** revert the changes from parseResponse ([d51996f](https://github.com/0xs34n/starknet.js/commit/d51996fa7635428ad4ffe271aa56f202ddcd4179))
16
+ - **provider:** allow the user to handle the contract errors ([5190f7a](https://github.com/0xs34n/starknet.js/commit/5190f7a20fb35382756d86cc67d3fab5c2d541ff))
17
+ - **test:** fix callContract() test ([b11c5da](https://github.com/0xs34n/starknet.js/commit/b11c5daf7fec6e8207dbc0be534aade8e00d5021))
18
+
19
+ ## [3.15.3](https://github.com/0xs34n/starknet.js/compare/v3.15.2...v3.15.3) (2022-06-20)
20
+
21
+ ### Bug Fixes
22
+
23
+ - **dev:** regenerated package-lock.json ([849cb1e](https://github.com/0xs34n/starknet.js/commit/849cb1ea3ffd7ba10b40b232d0ebc46b6599c7ea))
24
+ - use cross-fetch only for jest ([83be37a](https://github.com/0xs34n/starknet.js/commit/83be37a9e3328a44abd9583b8167c3cb8d882790))
25
+
1
26
  ## [3.15.2](https://github.com/0xs34n/starknet.js/compare/v3.15.1...v3.15.2) (2022-06-18)
2
27
 
3
28
  ### 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,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');
@@ -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
  });
@@ -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,38 +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) {
200
- if (res.status >= 400) {
201
- throw Error(res.statusText);
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
202
212
  }
203
- return res.text();
204
- })
205
- .then(function (res) {
206
213
  if (endpoint === 'estimate_fee') {
207
- return (0, json_1.parse)(res, function (_, v) {
208
- if (v && typeof v === 'bigint') {
209
- return (0, number_1.toBN)(v.toString());
210
- }
211
- return v;
212
- });
214
+ return [2 /*return*/, (0, json_1.parseAlwaysAsBig)(textResponse, function (_, v) {
215
+ if (v && typeof v === 'bigint') {
216
+ return (0, number_1.toBN)(v.toString());
217
+ }
218
+ return v;
219
+ })];
213
220
  }
214
- return (0, json_1.parse)(res);
215
- })
216
- .catch(function (err) {
217
- throw Error("Could not ".concat(method, " from endpoint `").concat(url, "`: ").concat(err.message));
218
- })];
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
+ }
219
233
  });
220
234
  });
221
235
  };
@@ -1,4 +1,5 @@
1
1
  import { Provider } from './default';
2
2
  export * from './default';
3
+ export { GatewayError } from './utils';
3
4
  export * from './interface';
4
5
  export declare const defaultProvider: Provider;
@@ -14,8 +14,10 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.defaultProvider = void 0;
17
+ exports.defaultProvider = exports.GatewayError = void 0;
18
18
  var default_1 = require("./default");
19
19
  __exportStar(require("./default"), exports);
20
+ var utils_1 = require("./utils");
21
+ Object.defineProperty(exports, "GatewayError", { enumerable: true, get: function () { return utils_1.GatewayError; } });
20
22
  __exportStar(require("./interface"), exports);
21
23
  exports.defaultProvider = new default_1.Provider();
@@ -1,3 +1,4 @@
1
+ import { CustomError } from 'ts-custom-error';
1
2
  import type { BlockNumber } from '../types';
2
3
  import { BigNumberish } from '../utils/number';
3
4
  /**
@@ -39,4 +40,8 @@ export declare function getBlockIdentifier(blockIdentifier: BlockIdentifier): Bl
39
40
  * @returns block identifier for API request
40
41
  */
41
42
  export declare function getFormattedBlockIdentifier(blockIdentifier?: BlockIdentifier): string;
43
+ export declare class GatewayError extends CustomError {
44
+ errorCode: string;
45
+ constructor(message: string, errorCode: string);
46
+ }
42
47
  export {};
@@ -1,6 +1,22 @@
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;
19
+ var ts_custom_error_1 = require("ts-custom-error");
4
20
  var number_1 = require("../utils/number");
5
21
  /**
6
22
  *
@@ -77,3 +93,13 @@ function getFormattedBlockIdentifier(blockIdentifier) {
77
93
  return "blockHash=".concat((0, number_1.toHex)((0, number_1.toBN)(blockIdentifierObject.data)));
78
94
  }
79
95
  exports.getFormattedBlockIdentifier = getFormattedBlockIdentifier;
96
+ var GatewayError = /** @class */ (function (_super) {
97
+ __extends(GatewayError, _super);
98
+ function GatewayError(message, errorCode) {
99
+ var _this = _super.call(this, message) || this;
100
+ _this.errorCode = errorCode;
101
+ return _this;
102
+ }
103
+ return GatewayError;
104
+ }(ts_custom_error_1.CustomError));
105
+ exports.GatewayError = GatewayError;
@@ -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.2",
3
+ "version": "3.15.5",
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,11 +71,11 @@
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",
75
77
  "pako": "^2.0.4",
78
+ "ts-custom-error": "^3.2.0",
76
79
  "url-join": "^4.0.1"
77
80
  },
78
81
  "lint-staged": {
@@ -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,46 +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
- if (res.status >= 400) {
318
- throw Error(res.statusText);
319
- }
320
- return res.text();
321
- })
322
- .then(function (res) {
323
- if (endpoint === 'estimate_fee') {
324
- 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.parseAlwaysAsBig)(textResponse, function (_, v) {
325
348
  if (v && typeof v === 'bigint') {
326
349
  return (0, number_1.toBN)(v.toString());
327
350
  }
328
351
  return v;
329
- });
330
- }
331
- return (0, json_1.parse)(res);
332
- })
333
- .catch(function (err) {
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) {
334
362
  throw Error(
335
363
  'Could not '
336
364
  .concat(method, ' from endpoint `')
337
365
  .concat(url, '`: ')
338
- .concat(err.message)
366
+ .concat(err_1.message)
339
367
  );
340
- }),
341
- ];
368
+ }
369
+ throw err_1;
370
+ case 5:
371
+ return [2 /*return*/];
372
+ }
342
373
  });
343
374
  });
344
375
  };
@@ -1,4 +1,5 @@
1
1
  import { Provider } from './default';
2
2
  export * from './default';
3
+ export { GatewayError } from './utils';
3
4
  export * from './interface';
4
5
  export declare const defaultProvider: Provider;
package/provider/index.js CHANGED
@@ -27,8 +27,15 @@ var __exportStar =
27
27
  __createBinding(exports, m, p);
28
28
  };
29
29
  Object.defineProperty(exports, '__esModule', { value: true });
30
- exports.defaultProvider = void 0;
30
+ exports.defaultProvider = exports.GatewayError = void 0;
31
31
  var default_1 = require('./default');
32
32
  __exportStar(require('./default'), exports);
33
+ var utils_1 = require('./utils');
34
+ Object.defineProperty(exports, 'GatewayError', {
35
+ enumerable: true,
36
+ get: function () {
37
+ return utils_1.GatewayError;
38
+ },
39
+ });
33
40
  __exportStar(require('./interface'), exports);
34
41
  exports.defaultProvider = new default_1.Provider();
@@ -1,3 +1,5 @@
1
+ import { CustomError } from 'ts-custom-error';
2
+
1
3
  import type { BlockNumber } from '../types';
2
4
  import { BigNumberish } from '../utils/number';
3
5
  /**
@@ -41,4 +43,8 @@ export declare function getBlockIdentifier(blockIdentifier: BlockIdentifier): Bl
41
43
  * @returns block identifier for API request
42
44
  */
43
45
  export declare function getFormattedBlockIdentifier(blockIdentifier?: BlockIdentifier): string;
46
+ export declare class GatewayError extends CustomError {
47
+ errorCode: string;
48
+ constructor(message: string, errorCode: string);
49
+ }
44
50
  export {};
package/provider/utils.js CHANGED
@@ -1,10 +1,37 @@
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 =
7
33
  void 0;
34
+ var ts_custom_error_1 = require('ts-custom-error');
8
35
  var number_1 = require('../utils/number');
9
36
  /**
10
37
  *
@@ -82,3 +109,13 @@ function getFormattedBlockIdentifier(blockIdentifier) {
82
109
  return 'blockHash='.concat((0, number_1.toHex)((0, number_1.toBN)(blockIdentifierObject.data)));
83
110
  }
84
111
  exports.getFormattedBlockIdentifier = getFormattedBlockIdentifier;
112
+ var GatewayError = /** @class */ (function (_super) {
113
+ __extends(GatewayError, _super);
114
+ function GatewayError(message, errorCode) {
115
+ var _this = _super.call(this, message) || this;
116
+ _this.errorCode = errorCode;
117
+ return _this;
118
+ }
119
+ return GatewayError;
120
+ })(ts_custom_error_1.CustomError);
121
+ 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';
@@ -21,11 +20,11 @@ import {
21
20
  TransactionReceiptResponse,
22
21
  } from '../types';
23
22
  import { getSelectorFromName } from '../utils/hash';
24
- import { parse, stringify } from '../utils/json';
23
+ import { parse, parseAlwaysAsBig, 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,31 +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) => {
163
- if (res.status >= 400) {
164
- throw Error(res.statusText);
165
- }
166
- return res.text();
167
- })
168
- .then((res) => {
169
- if (endpoint === 'estimate_fee') {
170
- return parse(res, (_, v) => {
171
- if (v && typeof v === 'bigint') {
172
- return toBN(v.toString());
173
- }
174
- return v;
175
- });
176
- }
177
- return parse(res) as Endpoints[T]['RESPONSE'];
178
- })
179
- .catch((err) => {
180
- throw Error(`Could not ${method} from endpoint \`${url}\`: ${err.message}`);
156
+ try {
157
+ const res = await fetch(url, {
158
+ method,
159
+ body: stringify(request),
160
+ headers,
181
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 parseAlwaysAsBig(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
+ }
182
189
  }
183
190
 
184
191
  /**
@@ -1,6 +1,7 @@
1
1
  import { Provider } from './default';
2
2
 
3
3
  export * from './default';
4
+ export { GatewayError } from './utils';
4
5
  export * from './interface';
5
6
 
6
7
  export const defaultProvider = new Provider();
@@ -1,3 +1,5 @@
1
+ import { CustomError } from 'ts-custom-error';
2
+
1
3
  import type { BlockNumber } from '../types';
2
4
  import { BigNumberish, toBN, toHex } from '../utils/number';
3
5
 
@@ -82,3 +84,9 @@ export function getFormattedBlockIdentifier(blockIdentifier: BlockIdentifier = n
82
84
  }
83
85
  return `blockHash=${toHex(toBN(blockIdentifierObject.data))}`;
84
86
  }
87
+
88
+ export class GatewayError extends CustomError {
89
+ constructor(message: string, public errorCode: string) {
90
+ super(message);
91
+ }
92
+ }
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 };
@@ -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.
@@ -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