@0xsequence/relayer 2.3.39 → 3.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/.turbo/turbo-build.log +5 -0
  2. package/CHANGELOG.md +3926 -0
  3. package/LICENSE +0 -17
  4. package/README.md +1 -2
  5. package/dist/index.d.ts +4 -0
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +3 -0
  8. package/dist/preconditions/codec.d.ts +12 -0
  9. package/dist/preconditions/codec.d.ts.map +1 -0
  10. package/dist/preconditions/codec.js +125 -0
  11. package/dist/preconditions/index.d.ts +4 -0
  12. package/dist/preconditions/index.d.ts.map +1 -0
  13. package/dist/preconditions/index.js +3 -0
  14. package/dist/preconditions/selectors.d.ts +7 -0
  15. package/dist/preconditions/selectors.d.ts.map +1 -0
  16. package/dist/preconditions/selectors.js +27 -0
  17. package/dist/preconditions/types.d.ts +70 -0
  18. package/dist/preconditions/types.d.ts.map +1 -0
  19. package/dist/preconditions/types.js +203 -0
  20. package/dist/relayer/index.d.ts +45 -0
  21. package/dist/relayer/index.d.ts.map +1 -0
  22. package/dist/relayer/index.js +3 -0
  23. package/dist/relayer/relayer.d.ts +26 -0
  24. package/dist/relayer/relayer.d.ts.map +1 -0
  25. package/dist/relayer/relayer.js +7 -0
  26. package/dist/relayer/rpc-relayer/index.d.ts +38 -0
  27. package/dist/relayer/rpc-relayer/index.d.ts.map +1 -0
  28. package/dist/relayer/rpc-relayer/index.js +375 -0
  29. package/dist/{declarations/src → relayer}/rpc-relayer/relayer.gen.d.ts +3 -2
  30. package/dist/relayer/rpc-relayer/relayer.gen.d.ts.map +1 -0
  31. package/dist/relayer/rpc-relayer/relayer.gen.js +1246 -0
  32. package/dist/relayer/standard/abi.d.ts +73 -0
  33. package/dist/relayer/standard/abi.d.ts.map +1 -0
  34. package/dist/relayer/standard/abi.js +10 -0
  35. package/dist/relayer/standard/eip6963.d.ts +31 -0
  36. package/dist/relayer/standard/eip6963.d.ts.map +1 -0
  37. package/dist/relayer/standard/eip6963.js +51 -0
  38. package/dist/relayer/standard/index.d.ts +5 -0
  39. package/dist/relayer/standard/index.d.ts.map +1 -0
  40. package/dist/relayer/standard/index.js +4 -0
  41. package/dist/relayer/standard/local.d.ts +60 -0
  42. package/dist/relayer/standard/local.d.ts.map +1 -0
  43. package/dist/relayer/standard/local.js +285 -0
  44. package/dist/relayer/standard/pk-relayer.d.ts +28 -0
  45. package/dist/relayer/standard/pk-relayer.d.ts.map +1 -0
  46. package/dist/relayer/standard/pk-relayer.js +112 -0
  47. package/dist/relayer/standard/sequence.d.ts +27 -0
  48. package/dist/relayer/standard/sequence.d.ts.map +1 -0
  49. package/dist/relayer/standard/sequence.js +84 -0
  50. package/package.json +28 -25
  51. package/src/index.ts +3 -111
  52. package/src/preconditions/codec.ts +190 -0
  53. package/src/preconditions/index.ts +3 -0
  54. package/src/preconditions/selectors.ts +38 -0
  55. package/src/preconditions/types.ts +201 -0
  56. package/src/relayer/index.ts +60 -0
  57. package/src/relayer/relayer.ts +37 -0
  58. package/src/relayer/rpc-relayer/index.ts +449 -0
  59. package/src/{rpc-relayer → relayer/rpc-relayer}/relayer.gen.ts +483 -258
  60. package/src/relayer/standard/abi.ts +13 -0
  61. package/src/relayer/standard/eip6963.ts +74 -0
  62. package/src/relayer/standard/index.ts +4 -0
  63. package/src/relayer/standard/local.ts +353 -0
  64. package/src/relayer/standard/pk-relayer.ts +138 -0
  65. package/src/relayer/standard/sequence.ts +110 -0
  66. package/test/preconditions/codec.test.ts +531 -0
  67. package/test/preconditions/preconditions.test.ts +283 -0
  68. package/test/preconditions/selectors.test.ts +415 -0
  69. package/test/preconditions/types.test.ts +443 -0
  70. package/test/relayer/relayer.test.ts +355 -0
  71. package/tsconfig.json +10 -0
  72. package/dist/0xsequence-relayer.cjs.d.ts +0 -2
  73. package/dist/0xsequence-relayer.cjs.dev.js +0 -1865
  74. package/dist/0xsequence-relayer.cjs.js +0 -7
  75. package/dist/0xsequence-relayer.cjs.prod.js +0 -1865
  76. package/dist/0xsequence-relayer.esm.js +0 -1852
  77. package/dist/declarations/src/index.d.ts +0 -42
  78. package/dist/declarations/src/local-relayer.d.ts +0 -35
  79. package/dist/declarations/src/provider-relayer.d.ts +0 -47
  80. package/dist/declarations/src/rpc-relayer/index.d.ts +0 -72
  81. package/src/local-relayer.ts +0 -125
  82. package/src/provider-relayer.ts +0 -284
  83. package/src/rpc-relayer/index.ts +0 -380
@@ -1,1852 +0,0 @@
1
- import { logger, getFetchRequest, bigintReplacer, toHexString } from '@0xsequence/utils';
2
- import { ethers } from 'ethers';
3
- import { walletContracts } from '@0xsequence/abi';
4
- import { commons } from '@0xsequence/core';
5
-
6
- function _extends() {
7
- return _extends = Object.assign ? Object.assign.bind() : function (n) {
8
- for (var e = 1; e < arguments.length; e++) {
9
- var t = arguments[e];
10
- for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
11
- }
12
- return n;
13
- }, _extends.apply(null, arguments);
14
- }
15
-
16
- const DEFAULT_GAS_LIMIT = 800000n;
17
- const ProviderRelayerDefaults = {
18
- waitPollRate: 1000,
19
- deltaBlocksLog: 12,
20
- fromBlockLog: -1024
21
- };
22
- function isProviderRelayerOptions(obj) {
23
- return typeof obj === 'object' && isAbstractProvider$1(obj.provider);
24
- }
25
- class ProviderRelayer {
26
- constructor(options) {
27
- this.provider = void 0;
28
- this.waitPollRate = void 0;
29
- this.deltaBlocksLog = void 0;
30
- this.fromBlockLog = void 0;
31
- const opts = _extends({}, ProviderRelayerDefaults, options);
32
- this.provider = opts.provider;
33
- this.waitPollRate = opts.waitPollRate;
34
- this.deltaBlocksLog = opts.deltaBlocksLog;
35
- this.fromBlockLog = opts.fromBlockLog;
36
- }
37
- async simulate(wallet, ...transactions) {
38
- var _this = this;
39
- return (await Promise.all(transactions.map(async function (tx) {
40
- // Respect gasLimit request of the transaction (as long as its not 0)
41
- if (tx.gasLimit && BigInt(tx.gasLimit || 0) !== 0n) {
42
- return tx.gasLimit;
43
- }
44
-
45
- // Fee can't be estimated locally for delegateCalls
46
- if (tx.delegateCall) {
47
- return DEFAULT_GAS_LIMIT;
48
- }
49
-
50
- // Fee can't be estimated for self-called if wallet hasn't been deployed
51
- if (tx.to === wallet && (await _this.provider.getCode(wallet).then(code => ethers.getBytes(code).length === 0))) {
52
- return DEFAULT_GAS_LIMIT;
53
- }
54
- if (!_this.provider) {
55
- throw new Error('signer.provider is not set, but is required');
56
- }
57
-
58
- // TODO: If the wallet address has been deployed, gas limits can be
59
- // estimated with more accurately by using self-calls with the batch transactions one by one
60
- return _this.provider.estimateGas({
61
- from: wallet,
62
- to: tx.to,
63
- data: tx.data,
64
- value: tx.value
65
- });
66
- }))).map(gasLimit => ({
67
- executed: true,
68
- succeeded: true,
69
- gasUsed: Number(gasLimit),
70
- gasLimit: Number(gasLimit)
71
- }));
72
- }
73
- async getNonce(address, space, blockTag) {
74
- if (!this.provider) {
75
- throw new Error('provider is not set');
76
- }
77
- if ((await this.provider.getCode(address)) === '0x') {
78
- return 0;
79
- }
80
- if (space === undefined) {
81
- space = 0;
82
- }
83
- const module = new ethers.Contract(address, walletContracts.mainModule.abi, this.provider);
84
- const nonce = await module.readNonce(space, {
85
- blockTag: blockTag
86
- });
87
- return commons.transaction.encodeNonce(space, nonce);
88
- }
89
- async wait(metaTxnId, timeoutDuration, delay = this.waitPollRate, maxFails = 5) {
90
- var _this2 = this;
91
- if (typeof metaTxnId !== 'string') {
92
- metaTxnId = commons.transaction.intendedTransactionID(metaTxnId);
93
- }
94
- let timedOut = false;
95
- const retry = async function retry(f, errorMessage) {
96
- let fails = 0;
97
- while (!timedOut) {
98
- try {
99
- return await f();
100
- } catch (error) {
101
- fails++;
102
- if (maxFails !== undefined && fails >= maxFails) {
103
- logger.error(`giving up after ${fails} failed attempts${errorMessage ? `: ${errorMessage}` : ''}`, error);
104
- throw error;
105
- } else {
106
- logger.warn(`attempt #${fails} failed${errorMessage ? `: ${errorMessage}` : ''}`, error);
107
- }
108
- }
109
- if (delay > 0) {
110
- await new Promise(resolve => setTimeout(resolve, delay));
111
- }
112
- }
113
- throw new Error(`timed out after ${fails} failed attempts${errorMessage ? `: ${errorMessage}` : ''}`);
114
- };
115
- const waitReceipt = async function waitReceipt() {
116
- // Transactions can only get executed on nonce change
117
- // get all nonce changes and look for metaTxnIds in between logs
118
- let lastBlock = _this2.fromBlockLog;
119
- if (lastBlock < 0) {
120
- const block = await retry(() => _this2.provider.getBlockNumber(), 'unable to get latest block number');
121
- lastBlock = block + lastBlock;
122
- }
123
- if (typeof metaTxnId !== 'string') {
124
- throw new Error('impossible');
125
- }
126
- const normalMetaTxnId = metaTxnId.replace('0x', '');
127
- while (!timedOut) {
128
- const block = await retry(() => _this2.provider.getBlockNumber(), 'unable to get latest block number');
129
- const logs = await retry(() => _this2.provider.getLogs({
130
- fromBlock: Math.max(0, lastBlock - _this2.deltaBlocksLog),
131
- toBlock: block,
132
- // Nonce change event topic
133
- topics: ['0x1f180c27086c7a39ea2a7b25239d1ab92348f07ca7bb59d1438fcf527568f881']
134
- }), `unable to get NonceChange logs for blocks ${Math.max(0, lastBlock - _this2.deltaBlocksLog)} to ${block}`);
135
- lastBlock = block;
136
-
137
- // Get receipts of all transactions
138
- const txs = await Promise.all(logs.map(l => retry(() => _this2.provider.getTransactionReceipt(l.transactionHash), `unable to get receipt for transaction ${l.transactionHash}`)));
139
-
140
- // Find a transaction with a TxExecuted log
141
- const found = txs.find(tx => tx == null ? void 0 : tx.logs.find(l => l.topics.length === 0 && l.data.replace('0x', '') === normalMetaTxnId || l.topics.length === 1 &&
142
- // TxFailed event topic
143
- l.topics[0] === '0x3dbd1590ea96dd3253a91f24e64e3a502e1225d602a5731357bc12643070ccd7' && l.data.length >= 64 && l.data.replace('0x', '').startsWith(normalMetaTxnId)));
144
-
145
- // If found return that
146
- if (found) {
147
- const response = await retry(() => _this2.provider.getTransaction(found.hash), `unable to get transaction ${found.hash}`);
148
- if (!response) {
149
- throw new Error(`Transaction response not found for ${metaTxnId}`);
150
- }
151
-
152
- // NOTE: we have to do this, because ethers-v6 uses private fields
153
- // and we can't just extend the class and override the method, so
154
- // we just modify the response object directly by adding the receipt to it.
155
- const out = response;
156
- out.receipt = found;
157
- return out;
158
- }
159
-
160
- // Otherwise wait and try again
161
- if (!timedOut) {
162
- await new Promise(r => setTimeout(r, delay));
163
- }
164
- }
165
- throw new Error(`Timeout waiting for transaction receipt ${metaTxnId}`);
166
- };
167
- if (timeoutDuration !== undefined) {
168
- return Promise.race([waitReceipt(), new Promise((_, reject) => setTimeout(() => {
169
- timedOut = true;
170
- reject(`Timeout waiting for transaction receipt ${metaTxnId}`);
171
- }, timeoutDuration))]);
172
- } else {
173
- return waitReceipt();
174
- }
175
- }
176
- }
177
- function isAbstractProvider$1(provider) {
178
- return provider && typeof provider === 'object' && typeof provider.getNetwork === 'function' && typeof provider.getBlockNumber === 'function';
179
- }
180
-
181
- function isLocalRelayerOptions(obj) {
182
- return typeof obj === 'object' && isAbstractSigner(obj.signer);
183
- }
184
- class LocalRelayer extends ProviderRelayer {
185
- constructor(options) {
186
- super(isAbstractSigner(options) ? {
187
- provider: options.provider
188
- } : _extends({}, options, {
189
- provider: options.signer.provider
190
- }));
191
- this.signer = void 0;
192
- this.txnOptions = void 0;
193
- this.signer = isAbstractSigner(options) ? options : options.signer;
194
- if (!this.signer.provider) throw new Error('Signer must have a provider');
195
- }
196
- async getFeeOptions(_address, ..._transactions) {
197
- return {
198
- options: []
199
- };
200
- }
201
- async getFeeOptionsRaw(_entrypoint, _data, _options) {
202
- return {
203
- options: []
204
- };
205
- }
206
- async gasRefundOptions(address, ...transactions) {
207
- const {
208
- options
209
- } = await this.getFeeOptions(address, ...transactions);
210
- return options;
211
- }
212
- setTransactionOptions(transactionRequest) {
213
- this.txnOptions = transactionRequest;
214
- }
215
- async relay(signedTxs, quote, waitForReceipt = true) {
216
- if (quote !== undefined) {
217
- logger.warn(`LocalRelayer doesn't accept fee quotes`);
218
- }
219
- const data = commons.transaction.encodeBundleExecData(signedTxs);
220
-
221
- // TODO: think about computing gas limit individually, summing together and passing across
222
- // NOTE: we expect that all txns have set their gasLimit ahead of time through proper estimation
223
- // const gasLimit = signedTxs.transactions.reduce((sum, tx) => sum + tx.gasLimit, 0n)
224
- // txRequest.gasLimit = gasLimit
225
-
226
- const responsePromise = this.signer.sendTransaction(_extends({
227
- to: signedTxs.entrypoint,
228
- data
229
- }, this.txnOptions, {
230
- gasLimit: 9000000
231
- }));
232
- if (waitForReceipt) {
233
- const response = await responsePromise;
234
- response.receipt = await response.wait();
235
- return response;
236
- } else {
237
- return responsePromise;
238
- }
239
- }
240
- async getMetaTransactions(projectId, page) {
241
- return {
242
- page: {
243
- page: 0,
244
- pageSize: 100
245
- },
246
- transactions: []
247
- };
248
- }
249
- async getTransactionCost(projectId, from, to) {
250
- return {
251
- cost: 0
252
- };
253
- }
254
- async listGasSponsors(args) {
255
- return {
256
- page: {
257
- page: 0,
258
- pageSize: 100
259
- },
260
- gasSponsors: []
261
- };
262
- }
263
- async addGasSponsor(args) {
264
- return {
265
- status: true,
266
- gasSponsor: {}
267
- };
268
- }
269
- async updateGasSponsor(args) {
270
- return {
271
- status: true,
272
- gasSponsor: {}
273
- };
274
- }
275
- async removeGasSponsor(args) {
276
- return {
277
- status: true
278
- };
279
- }
280
- }
281
- function isAbstractSigner(signer) {
282
- return signer && typeof signer === 'object' && typeof signer.provider === 'object' && typeof signer.getAddress === 'function' && typeof signer.connect === 'function';
283
- }
284
-
285
- /* eslint-disable */
286
- // sequence-relayer v0.4.1 7f8a4b83b00e0b6849c76c2ff0e23931e26b3d9f
287
- // --
288
- // Code generated by Webrpc-gen@v0.31.2 with typescript generator. DO NOT EDIT.
289
- //
290
- // webrpc-gen -schema=relayer.ridl -target=typescript -client -out=./clients/relayer.gen.ts -compat
291
-
292
- // Webrpc description and code-gen version
293
- const WebrpcVersion = 'v1';
294
-
295
- // Schema version of your RIDL schema
296
- const WebrpcSchemaVersion = 'v0.4.1';
297
-
298
- // Schema hash generated from your RIDL schema
299
- const WebrpcSchemaHash = '7f8a4b83b00e0b6849c76c2ff0e23931e26b3d9f';
300
-
301
- //
302
- // Client interface
303
- //
304
-
305
- //
306
- // Schema types
307
- //
308
-
309
- let ETHTxnStatus = /*#__PURE__*/function (ETHTxnStatus) {
310
- ETHTxnStatus["UNKNOWN"] = "UNKNOWN";
311
- ETHTxnStatus["DROPPED"] = "DROPPED";
312
- ETHTxnStatus["QUEUED"] = "QUEUED";
313
- ETHTxnStatus["SENT"] = "SENT";
314
- ETHTxnStatus["SUCCEEDED"] = "SUCCEEDED";
315
- ETHTxnStatus["PARTIALLY_FAILED"] = "PARTIALLY_FAILED";
316
- ETHTxnStatus["FAILED"] = "FAILED";
317
- ETHTxnStatus["PENDING_PRECONDITION"] = "PENDING_PRECONDITION";
318
- return ETHTxnStatus;
319
- }({});
320
- let TransferType = /*#__PURE__*/function (TransferType) {
321
- TransferType["SEND"] = "SEND";
322
- TransferType["RECEIVE"] = "RECEIVE";
323
- TransferType["BRIDGE_DEPOSIT"] = "BRIDGE_DEPOSIT";
324
- TransferType["BRIDGE_WITHDRAW"] = "BRIDGE_WITHDRAW";
325
- TransferType["BURN"] = "BURN";
326
- TransferType["UNKNOWN"] = "UNKNOWN";
327
- return TransferType;
328
- }({});
329
- let SimulateStatus = /*#__PURE__*/function (SimulateStatus) {
330
- SimulateStatus["SKIPPED"] = "SKIPPED";
331
- SimulateStatus["SUCCEEDED"] = "SUCCEEDED";
332
- SimulateStatus["FAILED"] = "FAILED";
333
- SimulateStatus["ABORTED"] = "ABORTED";
334
- SimulateStatus["REVERTED"] = "REVERTED";
335
- SimulateStatus["NOT_ENOUGH_GAS"] = "NOT_ENOUGH_GAS";
336
- return SimulateStatus;
337
- }({});
338
- let FeeTokenType = /*#__PURE__*/function (FeeTokenType) {
339
- FeeTokenType["UNKNOWN"] = "UNKNOWN";
340
- FeeTokenType["ERC20_TOKEN"] = "ERC20_TOKEN";
341
- FeeTokenType["ERC1155_TOKEN"] = "ERC1155_TOKEN";
342
- return FeeTokenType;
343
- }({});
344
- let SortOrder = /*#__PURE__*/function (SortOrder) {
345
- SortOrder["DESC"] = "DESC";
346
- SortOrder["ASC"] = "ASC";
347
- return SortOrder;
348
- }({});
349
- //
350
- // Client
351
- //
352
-
353
- class Relayer {
354
- constructor(hostname, fetch) {
355
- this.hostname = void 0;
356
- this.fetch = void 0;
357
- this.path = '/rpc/Relayer/';
358
- this.queryKey = {
359
- ping: () => ['Relayer', 'ping'],
360
- version: () => ['Relayer', 'version'],
361
- runtimeStatus: () => ['Relayer', 'runtimeStatus'],
362
- getSequenceContext: () => ['Relayer', 'getSequenceContext'],
363
- getChainID: () => ['Relayer', 'getChainID'],
364
- sendMetaTxn: req => ['Relayer', 'sendMetaTxn', req],
365
- getMetaTxnNonce: req => ['Relayer', 'getMetaTxnNonce', req],
366
- getMetaTxnReceipt: req => ['Relayer', 'getMetaTxnReceipt', req],
367
- simulate: req => ['Relayer', 'simulate', req],
368
- simulateV3: req => ['Relayer', 'simulateV3', req],
369
- updateMetaTxnGasLimits: req => ['Relayer', 'updateMetaTxnGasLimits', req],
370
- feeTokens: () => ['Relayer', 'feeTokens'],
371
- feeOptions: req => ['Relayer', 'feeOptions', req],
372
- getMetaTxnNetworkFeeOptions: req => ['Relayer', 'getMetaTxnNetworkFeeOptions', req],
373
- getMetaTransactions: req => ['Relayer', 'getMetaTransactions', req],
374
- getTransactionCost: req => ['Relayer', 'getTransactionCost', req],
375
- sentTransactions: req => ['Relayer', 'sentTransactions', req],
376
- pendingTransactions: req => ['Relayer', 'pendingTransactions', req],
377
- getGasTank: req => ['Relayer', 'getGasTank', req],
378
- addGasTank: req => ['Relayer', 'addGasTank', req],
379
- updateGasTank: req => ['Relayer', 'updateGasTank', req],
380
- nextGasTankBalanceAdjustmentNonce: req => ['Relayer', 'nextGasTankBalanceAdjustmentNonce', req],
381
- adjustGasTankBalance: req => ['Relayer', 'adjustGasTankBalance', req],
382
- getGasTankBalanceAdjustment: req => ['Relayer', 'getGasTankBalanceAdjustment', req],
383
- listGasTankBalanceAdjustments: req => ['Relayer', 'listGasTankBalanceAdjustments', req],
384
- listGasSponsors: req => ['Relayer', 'listGasSponsors', req],
385
- getGasSponsor: req => ['Relayer', 'getGasSponsor', req],
386
- addGasSponsor: req => ['Relayer', 'addGasSponsor', req],
387
- updateGasSponsor: req => ['Relayer', 'updateGasSponsor', req],
388
- removeGasSponsor: req => ['Relayer', 'removeGasSponsor', req],
389
- addressGasSponsors: req => ['Relayer', 'addressGasSponsors', req],
390
- getProjectBalance: req => ['Relayer', 'getProjectBalance', req],
391
- adjustProjectBalance: req => ['Relayer', 'adjustProjectBalance', req]
392
- };
393
- this.ping = (headers, signal) => {
394
- return this.fetch(this.url('Ping'), createHttpRequest('{}', headers, signal)).then(res => {
395
- return buildResponse(res).then(_data => {
396
- return JsonDecode(_data, 'PingReturn');
397
- });
398
- }, error => {
399
- throw WebrpcRequestFailedError.new({
400
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
401
- });
402
- });
403
- };
404
- this.version = (headers, signal) => {
405
- return this.fetch(this.url('Version'), createHttpRequest('{}', headers, signal)).then(res => {
406
- return buildResponse(res).then(_data => {
407
- return JsonDecode(_data, 'VersionReturn');
408
- });
409
- }, error => {
410
- throw WebrpcRequestFailedError.new({
411
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
412
- });
413
- });
414
- };
415
- this.runtimeStatus = (headers, signal) => {
416
- return this.fetch(this.url('RuntimeStatus'), createHttpRequest('{}', headers, signal)).then(res => {
417
- return buildResponse(res).then(_data => {
418
- return JsonDecode(_data, 'RuntimeStatusReturn');
419
- });
420
- }, error => {
421
- throw WebrpcRequestFailedError.new({
422
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
423
- });
424
- });
425
- };
426
- this.getSequenceContext = (headers, signal) => {
427
- return this.fetch(this.url('GetSequenceContext'), createHttpRequest('{}', headers, signal)).then(res => {
428
- return buildResponse(res).then(_data => {
429
- return JsonDecode(_data, 'GetSequenceContextReturn');
430
- });
431
- }, error => {
432
- throw WebrpcRequestFailedError.new({
433
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
434
- });
435
- });
436
- };
437
- this.getChainID = (headers, signal) => {
438
- return this.fetch(this.url('GetChainID'), createHttpRequest('{}', headers, signal)).then(res => {
439
- return buildResponse(res).then(_data => {
440
- return JsonDecode(_data, 'GetChainIDReturn');
441
- });
442
- }, error => {
443
- throw WebrpcRequestFailedError.new({
444
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
445
- });
446
- });
447
- };
448
- this.sendMetaTxn = (req, headers, signal) => {
449
- return this.fetch(this.url('SendMetaTxn'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
450
- return buildResponse(res).then(_data => {
451
- return JsonDecode(_data, 'SendMetaTxnReturn');
452
- });
453
- }, error => {
454
- throw WebrpcRequestFailedError.new({
455
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
456
- });
457
- });
458
- };
459
- this.getMetaTxnNonce = (req, headers, signal) => {
460
- return this.fetch(this.url('GetMetaTxnNonce'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
461
- return buildResponse(res).then(_data => {
462
- return JsonDecode(_data, 'GetMetaTxnNonceReturn');
463
- });
464
- }, error => {
465
- throw WebrpcRequestFailedError.new({
466
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
467
- });
468
- });
469
- };
470
- this.getMetaTxnReceipt = (req, headers, signal) => {
471
- return this.fetch(this.url('GetMetaTxnReceipt'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
472
- return buildResponse(res).then(_data => {
473
- return JsonDecode(_data, 'GetMetaTxnReceiptReturn');
474
- });
475
- }, error => {
476
- throw WebrpcRequestFailedError.new({
477
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
478
- });
479
- });
480
- };
481
- this.simulate = (req, headers, signal) => {
482
- return this.fetch(this.url('Simulate'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
483
- return buildResponse(res).then(_data => {
484
- return JsonDecode(_data, 'SimulateReturn');
485
- });
486
- }, error => {
487
- throw WebrpcRequestFailedError.new({
488
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
489
- });
490
- });
491
- };
492
- this.simulateV3 = (req, headers, signal) => {
493
- return this.fetch(this.url('SimulateV3'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
494
- return buildResponse(res).then(_data => {
495
- return JsonDecode(_data, 'SimulateV3Return');
496
- });
497
- }, error => {
498
- throw WebrpcRequestFailedError.new({
499
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
500
- });
501
- });
502
- };
503
- this.updateMetaTxnGasLimits = (req, headers, signal) => {
504
- return this.fetch(this.url('UpdateMetaTxnGasLimits'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
505
- return buildResponse(res).then(_data => {
506
- return JsonDecode(_data, 'UpdateMetaTxnGasLimitsReturn');
507
- });
508
- }, error => {
509
- throw WebrpcRequestFailedError.new({
510
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
511
- });
512
- });
513
- };
514
- this.feeTokens = (headers, signal) => {
515
- return this.fetch(this.url('FeeTokens'), createHttpRequest('{}', headers, signal)).then(res => {
516
- return buildResponse(res).then(_data => {
517
- return JsonDecode(_data, 'FeeTokensReturn');
518
- });
519
- }, error => {
520
- throw WebrpcRequestFailedError.new({
521
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
522
- });
523
- });
524
- };
525
- this.feeOptions = (req, headers, signal) => {
526
- return this.fetch(this.url('FeeOptions'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
527
- return buildResponse(res).then(_data => {
528
- return JsonDecode(_data, 'FeeOptionsReturn');
529
- });
530
- }, error => {
531
- throw WebrpcRequestFailedError.new({
532
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
533
- });
534
- });
535
- };
536
- this.getMetaTxnNetworkFeeOptions = (req, headers, signal) => {
537
- return this.fetch(this.url('GetMetaTxnNetworkFeeOptions'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
538
- return buildResponse(res).then(_data => {
539
- return JsonDecode(_data, 'GetMetaTxnNetworkFeeOptionsReturn');
540
- });
541
- }, error => {
542
- throw WebrpcRequestFailedError.new({
543
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
544
- });
545
- });
546
- };
547
- this.getMetaTransactions = (req, headers, signal) => {
548
- return this.fetch(this.url('GetMetaTransactions'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
549
- return buildResponse(res).then(_data => {
550
- return JsonDecode(_data, 'GetMetaTransactionsReturn');
551
- });
552
- }, error => {
553
- throw WebrpcRequestFailedError.new({
554
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
555
- });
556
- });
557
- };
558
- this.getTransactionCost = (req, headers, signal) => {
559
- return this.fetch(this.url('GetTransactionCost'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
560
- return buildResponse(res).then(_data => {
561
- return JsonDecode(_data, 'GetTransactionCostReturn');
562
- });
563
- }, error => {
564
- throw WebrpcRequestFailedError.new({
565
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
566
- });
567
- });
568
- };
569
- this.sentTransactions = (req, headers, signal) => {
570
- return this.fetch(this.url('SentTransactions'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
571
- return buildResponse(res).then(_data => {
572
- return JsonDecode(_data, 'SentTransactionsReturn');
573
- });
574
- }, error => {
575
- throw WebrpcRequestFailedError.new({
576
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
577
- });
578
- });
579
- };
580
- this.pendingTransactions = (req, headers, signal) => {
581
- return this.fetch(this.url('PendingTransactions'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
582
- return buildResponse(res).then(_data => {
583
- return JsonDecode(_data, 'PendingTransactionsReturn');
584
- });
585
- }, error => {
586
- throw WebrpcRequestFailedError.new({
587
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
588
- });
589
- });
590
- };
591
- this.getGasTank = (req, headers, signal) => {
592
- return this.fetch(this.url('GetGasTank'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
593
- return buildResponse(res).then(_data => {
594
- return JsonDecode(_data, 'GetGasTankReturn');
595
- });
596
- }, error => {
597
- throw WebrpcRequestFailedError.new({
598
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
599
- });
600
- });
601
- };
602
- this.addGasTank = (req, headers, signal) => {
603
- return this.fetch(this.url('AddGasTank'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
604
- return buildResponse(res).then(_data => {
605
- return JsonDecode(_data, 'AddGasTankReturn');
606
- });
607
- }, error => {
608
- throw WebrpcRequestFailedError.new({
609
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
610
- });
611
- });
612
- };
613
- this.updateGasTank = (req, headers, signal) => {
614
- return this.fetch(this.url('UpdateGasTank'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
615
- return buildResponse(res).then(_data => {
616
- return JsonDecode(_data, 'UpdateGasTankReturn');
617
- });
618
- }, error => {
619
- throw WebrpcRequestFailedError.new({
620
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
621
- });
622
- });
623
- };
624
- this.nextGasTankBalanceAdjustmentNonce = (req, headers, signal) => {
625
- return this.fetch(this.url('NextGasTankBalanceAdjustmentNonce'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
626
- return buildResponse(res).then(_data => {
627
- return JsonDecode(_data, 'NextGasTankBalanceAdjustmentNonceReturn');
628
- });
629
- }, error => {
630
- throw WebrpcRequestFailedError.new({
631
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
632
- });
633
- });
634
- };
635
- this.adjustGasTankBalance = (req, headers, signal) => {
636
- return this.fetch(this.url('AdjustGasTankBalance'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
637
- return buildResponse(res).then(_data => {
638
- return JsonDecode(_data, 'AdjustGasTankBalanceReturn');
639
- });
640
- }, error => {
641
- throw WebrpcRequestFailedError.new({
642
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
643
- });
644
- });
645
- };
646
- this.getGasTankBalanceAdjustment = (req, headers, signal) => {
647
- return this.fetch(this.url('GetGasTankBalanceAdjustment'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
648
- return buildResponse(res).then(_data => {
649
- return JsonDecode(_data, 'GetGasTankBalanceAdjustmentReturn');
650
- });
651
- }, error => {
652
- throw WebrpcRequestFailedError.new({
653
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
654
- });
655
- });
656
- };
657
- this.listGasTankBalanceAdjustments = (req, headers, signal) => {
658
- return this.fetch(this.url('ListGasTankBalanceAdjustments'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
659
- return buildResponse(res).then(_data => {
660
- return JsonDecode(_data, 'ListGasTankBalanceAdjustmentsReturn');
661
- });
662
- }, error => {
663
- throw WebrpcRequestFailedError.new({
664
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
665
- });
666
- });
667
- };
668
- this.listGasSponsors = (req, headers, signal) => {
669
- return this.fetch(this.url('ListGasSponsors'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
670
- return buildResponse(res).then(_data => {
671
- return JsonDecode(_data, 'ListGasSponsorsReturn');
672
- });
673
- }, error => {
674
- throw WebrpcRequestFailedError.new({
675
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
676
- });
677
- });
678
- };
679
- this.getGasSponsor = (req, headers, signal) => {
680
- return this.fetch(this.url('GetGasSponsor'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
681
- return buildResponse(res).then(_data => {
682
- return JsonDecode(_data, 'GetGasSponsorReturn');
683
- });
684
- }, error => {
685
- throw WebrpcRequestFailedError.new({
686
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
687
- });
688
- });
689
- };
690
- this.addGasSponsor = (req, headers, signal) => {
691
- return this.fetch(this.url('AddGasSponsor'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
692
- return buildResponse(res).then(_data => {
693
- return JsonDecode(_data, 'AddGasSponsorReturn');
694
- });
695
- }, error => {
696
- throw WebrpcRequestFailedError.new({
697
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
698
- });
699
- });
700
- };
701
- this.updateGasSponsor = (req, headers, signal) => {
702
- return this.fetch(this.url('UpdateGasSponsor'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
703
- return buildResponse(res).then(_data => {
704
- return JsonDecode(_data, 'UpdateGasSponsorReturn');
705
- });
706
- }, error => {
707
- throw WebrpcRequestFailedError.new({
708
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
709
- });
710
- });
711
- };
712
- this.removeGasSponsor = (req, headers, signal) => {
713
- return this.fetch(this.url('RemoveGasSponsor'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
714
- return buildResponse(res).then(_data => {
715
- return JsonDecode(_data, 'RemoveGasSponsorReturn');
716
- });
717
- }, error => {
718
- throw WebrpcRequestFailedError.new({
719
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
720
- });
721
- });
722
- };
723
- this.addressGasSponsors = (req, headers, signal) => {
724
- return this.fetch(this.url('AddressGasSponsors'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
725
- return buildResponse(res).then(_data => {
726
- return JsonDecode(_data, 'AddressGasSponsorsReturn');
727
- });
728
- }, error => {
729
- throw WebrpcRequestFailedError.new({
730
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
731
- });
732
- });
733
- };
734
- this.getProjectBalance = (req, headers, signal) => {
735
- return this.fetch(this.url('GetProjectBalance'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
736
- return buildResponse(res).then(_data => {
737
- return JsonDecode(_data, 'GetProjectBalanceReturn');
738
- });
739
- }, error => {
740
- throw WebrpcRequestFailedError.new({
741
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
742
- });
743
- });
744
- };
745
- this.adjustProjectBalance = (req, headers, signal) => {
746
- return this.fetch(this.url('AdjustProjectBalance'), createHttpRequest(JsonEncode(req), headers, signal)).then(res => {
747
- return buildResponse(res).then(_data => {
748
- return JsonDecode(_data, 'AdjustProjectBalanceReturn');
749
- });
750
- }, error => {
751
- throw WebrpcRequestFailedError.new({
752
- cause: `fetch(): ${error instanceof Error ? error.message : String(error)}`
753
- });
754
- });
755
- };
756
- this.hostname = hostname.replace(/\/*$/, '');
757
- this.fetch = (input, init) => fetch(input, init);
758
- }
759
- url(name) {
760
- return this.hostname + this.path + name;
761
- }
762
- }
763
- const createHttpRequest = (body = '{}', headers = {}, signal = null) => {
764
- const reqHeaders = _extends({}, headers, {
765
- 'Content-Type': 'application/json',
766
- [WebrpcHeader]: WebrpcHeaderValue
767
- });
768
- return {
769
- method: 'POST',
770
- headers: reqHeaders,
771
- body,
772
- signal
773
- };
774
- };
775
- const buildResponse = res => {
776
- return res.text().then(text => {
777
- let data;
778
- try {
779
- data = JSON.parse(text);
780
- } catch (error) {
781
- throw WebrpcBadResponseError.new({
782
- status: res.status,
783
- cause: `JSON.parse(): ${error instanceof Error ? error.message : String(error)}: response text: ${text}`
784
- });
785
- }
786
- if (!res.ok) {
787
- const code = typeof data.code === 'number' ? data.code : 0;
788
- throw (webrpcErrorByCode[code] || WebrpcError).new(data);
789
- }
790
- return data;
791
- });
792
- };
793
- //
794
- // BigInt helpers
795
- //
796
-
797
- const BIG_INT_FIELDS = {
798
- SendMetaTxnArgs: [['preconditions', 'TransactionPrecondition[]']],
799
- TransactionPrecondition: ['minAmount'],
800
- Transactions: [['preconditions', 'TransactionPrecondition[]']]
801
- };
802
-
803
- // Decode in-place: mutate object graph; throw if expected numeric string is invalid.
804
- function decodeType(typ, obj) {
805
- if (obj == null || typeof obj !== 'object') return obj;
806
- const descs = BIG_INT_FIELDS[typ] || [];
807
- if (!descs.length) return obj;
808
- for (const d of descs) {
809
- if (Array.isArray(d)) {
810
- const [fieldName, nestedType] = d;
811
- if (fieldName.endsWith('[]')) {
812
- const base = fieldName.slice(0, -2);
813
- const arr = obj[base];
814
- if (Array.isArray(arr)) {
815
- for (let i = 0; i < arr.length; i++) arr[i] = decodeType(nestedType, arr[i]);
816
- }
817
- } else if (obj[fieldName]) {
818
- // Handle nestedType that might be an array type like 'Message[]'
819
- if (nestedType.endsWith('[]')) {
820
- const baseType = nestedType.slice(0, -2);
821
- const arr = obj[fieldName];
822
- if (Array.isArray(arr)) {
823
- for (let i = 0; i < arr.length; i++) arr[i] = decodeType(baseType, arr[i]);
824
- }
825
- } else {
826
- obj[fieldName] = decodeType(nestedType, obj[fieldName]);
827
- }
828
- }
829
- continue;
830
- }
831
- if (d.endsWith('[]')) {
832
- const base = d.slice(0, -2);
833
- const arr = obj[base];
834
- if (Array.isArray(arr)) {
835
- for (let i = 0; i < arr.length; i++) {
836
- const _v = arr[i];
837
- if (typeof _v === 'string') {
838
- try {
839
- arr[i] = BigInt(_v);
840
- } catch (e) {
841
- throw WebrpcBadResponseError.new({
842
- cause: `Invalid bigint value for ${base}[${i}]: ${_v}`
843
- });
844
- }
845
- }
846
- }
847
- }
848
- continue;
849
- }
850
- const v = obj[d];
851
- if (typeof v === 'string') {
852
- try {
853
- obj[d] = BigInt(v);
854
- } catch (e) {
855
- throw WebrpcBadResponseError.new({
856
- cause: `Invalid bigint value for ${d}: ${v}`
857
- });
858
- }
859
- }
860
- }
861
- return obj;
862
- }
863
-
864
- // Encode object to JSON with BigInts converted to decimal strings.
865
- const JsonEncode = obj => {
866
- return JSON.stringify(obj, (key, value) => typeof value === 'bigint' ? value.toString() : value);
867
- };
868
-
869
- // Decode data (JSON string or already-parsed object) and convert declared BigInt string fields back to BigInt.
870
- const JsonDecode = (data, typ = '') => {
871
- let parsed = data;
872
- if (typeof data === 'string') {
873
- try {
874
- parsed = JSON.parse(data);
875
- } catch (err) {
876
- throw WebrpcBadResponseError.new({
877
- cause: `JsonDecode: JSON.parse failed: ${err.message}`
878
- });
879
- }
880
- }
881
- return decodeType(typ, parsed);
882
- };
883
-
884
- //
885
- // Errors
886
- //
887
-
888
- class WebrpcError extends Error {
889
- constructor(error = {}) {
890
- super(error.message);
891
- this.code = void 0;
892
- this.status = void 0;
893
- this.name = error.name || 'WebrpcEndpointError';
894
- this.code = typeof error.code === 'number' ? error.code : 0;
895
- this.message = error.message || `endpoint error`;
896
- this.status = typeof error.status === 'number' ? error.status : 400;
897
- if (error.cause !== undefined) this.cause = error.cause;
898
- Object.setPrototypeOf(this, WebrpcError.prototype);
899
- }
900
- static new(payload) {
901
- return new this({
902
- message: payload.message,
903
- code: payload.code,
904
- status: payload.status,
905
- cause: payload.cause
906
- });
907
- }
908
- }
909
- class WebrpcEndpointError extends WebrpcError {
910
- constructor(error = {}) {
911
- super(error);
912
- this.name = error.name || 'WebrpcEndpoint';
913
- this.code = typeof error.code === 'number' ? error.code : 0;
914
- this.message = error.message || `endpoint error`;
915
- this.status = typeof error.status === 'number' ? error.status : 400;
916
- if (error.cause !== undefined) this.cause = error.cause;
917
- Object.setPrototypeOf(this, WebrpcEndpointError.prototype);
918
- }
919
- }
920
- class WebrpcRequestFailedError extends WebrpcError {
921
- constructor(error = {}) {
922
- super(error);
923
- this.name = error.name || 'WebrpcRequestFailed';
924
- this.code = typeof error.code === 'number' ? error.code : -1;
925
- this.message = error.message || `request failed`;
926
- this.status = typeof error.status === 'number' ? error.status : 400;
927
- if (error.cause !== undefined) this.cause = error.cause;
928
- Object.setPrototypeOf(this, WebrpcRequestFailedError.prototype);
929
- }
930
- }
931
- class WebrpcBadRouteError extends WebrpcError {
932
- constructor(error = {}) {
933
- super(error);
934
- this.name = error.name || 'WebrpcBadRoute';
935
- this.code = typeof error.code === 'number' ? error.code : -2;
936
- this.message = error.message || `bad route`;
937
- this.status = typeof error.status === 'number' ? error.status : 404;
938
- if (error.cause !== undefined) this.cause = error.cause;
939
- Object.setPrototypeOf(this, WebrpcBadRouteError.prototype);
940
- }
941
- }
942
- class WebrpcBadMethodError extends WebrpcError {
943
- constructor(error = {}) {
944
- super(error);
945
- this.name = error.name || 'WebrpcBadMethod';
946
- this.code = typeof error.code === 'number' ? error.code : -3;
947
- this.message = error.message || `bad method`;
948
- this.status = typeof error.status === 'number' ? error.status : 405;
949
- if (error.cause !== undefined) this.cause = error.cause;
950
- Object.setPrototypeOf(this, WebrpcBadMethodError.prototype);
951
- }
952
- }
953
- class WebrpcBadRequestError extends WebrpcError {
954
- constructor(error = {}) {
955
- super(error);
956
- this.name = error.name || 'WebrpcBadRequest';
957
- this.code = typeof error.code === 'number' ? error.code : -4;
958
- this.message = error.message || `bad request`;
959
- this.status = typeof error.status === 'number' ? error.status : 400;
960
- if (error.cause !== undefined) this.cause = error.cause;
961
- Object.setPrototypeOf(this, WebrpcBadRequestError.prototype);
962
- }
963
- }
964
- class WebrpcBadResponseError extends WebrpcError {
965
- constructor(error = {}) {
966
- super(error);
967
- this.name = error.name || 'WebrpcBadResponse';
968
- this.code = typeof error.code === 'number' ? error.code : -5;
969
- this.message = error.message || `bad response`;
970
- this.status = typeof error.status === 'number' ? error.status : 500;
971
- if (error.cause !== undefined) this.cause = error.cause;
972
- Object.setPrototypeOf(this, WebrpcBadResponseError.prototype);
973
- }
974
- }
975
- class WebrpcServerPanicError extends WebrpcError {
976
- constructor(error = {}) {
977
- super(error);
978
- this.name = error.name || 'WebrpcServerPanic';
979
- this.code = typeof error.code === 'number' ? error.code : -6;
980
- this.message = error.message || `server panic`;
981
- this.status = typeof error.status === 'number' ? error.status : 500;
982
- if (error.cause !== undefined) this.cause = error.cause;
983
- Object.setPrototypeOf(this, WebrpcServerPanicError.prototype);
984
- }
985
- }
986
- class WebrpcInternalErrorError extends WebrpcError {
987
- constructor(error = {}) {
988
- super(error);
989
- this.name = error.name || 'WebrpcInternalError';
990
- this.code = typeof error.code === 'number' ? error.code : -7;
991
- this.message = error.message || `internal error`;
992
- this.status = typeof error.status === 'number' ? error.status : 500;
993
- if (error.cause !== undefined) this.cause = error.cause;
994
- Object.setPrototypeOf(this, WebrpcInternalErrorError.prototype);
995
- }
996
- }
997
- class WebrpcClientAbortedError extends WebrpcError {
998
- constructor(error = {}) {
999
- super(error);
1000
- this.name = error.name || 'WebrpcClientAborted';
1001
- this.code = typeof error.code === 'number' ? error.code : -8;
1002
- this.message = error.message || `request aborted by client`;
1003
- this.status = typeof error.status === 'number' ? error.status : 400;
1004
- if (error.cause !== undefined) this.cause = error.cause;
1005
- Object.setPrototypeOf(this, WebrpcClientAbortedError.prototype);
1006
- }
1007
- }
1008
- class WebrpcStreamLostError extends WebrpcError {
1009
- constructor(error = {}) {
1010
- super(error);
1011
- this.name = error.name || 'WebrpcStreamLost';
1012
- this.code = typeof error.code === 'number' ? error.code : -9;
1013
- this.message = error.message || `stream lost`;
1014
- this.status = typeof error.status === 'number' ? error.status : 400;
1015
- if (error.cause !== undefined) this.cause = error.cause;
1016
- Object.setPrototypeOf(this, WebrpcStreamLostError.prototype);
1017
- }
1018
- }
1019
- class WebrpcStreamFinishedError extends WebrpcError {
1020
- constructor(error = {}) {
1021
- super(error);
1022
- this.name = error.name || 'WebrpcStreamFinished';
1023
- this.code = typeof error.code === 'number' ? error.code : -10;
1024
- this.message = error.message || `stream finished`;
1025
- this.status = typeof error.status === 'number' ? error.status : 200;
1026
- if (error.cause !== undefined) this.cause = error.cause;
1027
- Object.setPrototypeOf(this, WebrpcStreamFinishedError.prototype);
1028
- }
1029
- }
1030
-
1031
- //
1032
- // Schema errors
1033
- //
1034
-
1035
- class UnauthorizedError extends WebrpcError {
1036
- constructor(error = {}) {
1037
- super(error);
1038
- this.name = error.name || 'Unauthorized';
1039
- this.code = typeof error.code === 'number' ? error.code : 1000;
1040
- this.message = error.message || `Unauthorized access`;
1041
- this.status = typeof error.status === 'number' ? error.status : 401;
1042
- if (error.cause !== undefined) this.cause = error.cause;
1043
- Object.setPrototypeOf(this, UnauthorizedError.prototype);
1044
- }
1045
- }
1046
- class PermissionDeniedError extends WebrpcError {
1047
- constructor(error = {}) {
1048
- super(error);
1049
- this.name = error.name || 'PermissionDenied';
1050
- this.code = typeof error.code === 'number' ? error.code : 1001;
1051
- this.message = error.message || `Permission denied`;
1052
- this.status = typeof error.status === 'number' ? error.status : 403;
1053
- if (error.cause !== undefined) this.cause = error.cause;
1054
- Object.setPrototypeOf(this, PermissionDeniedError.prototype);
1055
- }
1056
- }
1057
- class SessionExpiredError extends WebrpcError {
1058
- constructor(error = {}) {
1059
- super(error);
1060
- this.name = error.name || 'SessionExpired';
1061
- this.code = typeof error.code === 'number' ? error.code : 1002;
1062
- this.message = error.message || `Session expired`;
1063
- this.status = typeof error.status === 'number' ? error.status : 403;
1064
- if (error.cause !== undefined) this.cause = error.cause;
1065
- Object.setPrototypeOf(this, SessionExpiredError.prototype);
1066
- }
1067
- }
1068
- class MethodNotFoundError extends WebrpcError {
1069
- constructor(error = {}) {
1070
- super(error);
1071
- this.name = error.name || 'MethodNotFound';
1072
- this.code = typeof error.code === 'number' ? error.code : 1003;
1073
- this.message = error.message || `Method not found`;
1074
- this.status = typeof error.status === 'number' ? error.status : 404;
1075
- if (error.cause !== undefined) this.cause = error.cause;
1076
- Object.setPrototypeOf(this, MethodNotFoundError.prototype);
1077
- }
1078
- }
1079
- class RequestConflictError extends WebrpcError {
1080
- constructor(error = {}) {
1081
- super(error);
1082
- this.name = error.name || 'RequestConflict';
1083
- this.code = typeof error.code === 'number' ? error.code : 1004;
1084
- this.message = error.message || `Conflict with target resource`;
1085
- this.status = typeof error.status === 'number' ? error.status : 409;
1086
- if (error.cause !== undefined) this.cause = error.cause;
1087
- Object.setPrototypeOf(this, RequestConflictError.prototype);
1088
- }
1089
- }
1090
- class AbortedError extends WebrpcError {
1091
- constructor(error = {}) {
1092
- super(error);
1093
- this.name = error.name || 'Aborted';
1094
- this.code = typeof error.code === 'number' ? error.code : 1005;
1095
- this.message = error.message || `Request aborted`;
1096
- this.status = typeof error.status === 'number' ? error.status : 400;
1097
- if (error.cause !== undefined) this.cause = error.cause;
1098
- Object.setPrototypeOf(this, AbortedError.prototype);
1099
- }
1100
- }
1101
- class GeoblockedError extends WebrpcError {
1102
- constructor(error = {}) {
1103
- super(error);
1104
- this.name = error.name || 'Geoblocked';
1105
- this.code = typeof error.code === 'number' ? error.code : 1006;
1106
- this.message = error.message || `Geoblocked region`;
1107
- this.status = typeof error.status === 'number' ? error.status : 451;
1108
- if (error.cause !== undefined) this.cause = error.cause;
1109
- Object.setPrototypeOf(this, GeoblockedError.prototype);
1110
- }
1111
- }
1112
- class RateLimitedError extends WebrpcError {
1113
- constructor(error = {}) {
1114
- super(error);
1115
- this.name = error.name || 'RateLimited';
1116
- this.code = typeof error.code === 'number' ? error.code : 1007;
1117
- this.message = error.message || `Rate-limited. Please slow down.`;
1118
- this.status = typeof error.status === 'number' ? error.status : 429;
1119
- if (error.cause !== undefined) this.cause = error.cause;
1120
- Object.setPrototypeOf(this, RateLimitedError.prototype);
1121
- }
1122
- }
1123
- class ProjectNotFoundError extends WebrpcError {
1124
- constructor(error = {}) {
1125
- super(error);
1126
- this.name = error.name || 'ProjectNotFound';
1127
- this.code = typeof error.code === 'number' ? error.code : 1008;
1128
- this.message = error.message || `Project not found`;
1129
- this.status = typeof error.status === 'number' ? error.status : 401;
1130
- if (error.cause !== undefined) this.cause = error.cause;
1131
- Object.setPrototypeOf(this, ProjectNotFoundError.prototype);
1132
- }
1133
- }
1134
- class AccessKeyNotFoundError extends WebrpcError {
1135
- constructor(error = {}) {
1136
- super(error);
1137
- this.name = error.name || 'AccessKeyNotFound';
1138
- this.code = typeof error.code === 'number' ? error.code : 1101;
1139
- this.message = error.message || `Access key not found`;
1140
- this.status = typeof error.status === 'number' ? error.status : 401;
1141
- if (error.cause !== undefined) this.cause = error.cause;
1142
- Object.setPrototypeOf(this, AccessKeyNotFoundError.prototype);
1143
- }
1144
- }
1145
- class AccessKeyMismatchError extends WebrpcError {
1146
- constructor(error = {}) {
1147
- super(error);
1148
- this.name = error.name || 'AccessKeyMismatch';
1149
- this.code = typeof error.code === 'number' ? error.code : 1102;
1150
- this.message = error.message || `Access key mismatch`;
1151
- this.status = typeof error.status === 'number' ? error.status : 409;
1152
- if (error.cause !== undefined) this.cause = error.cause;
1153
- Object.setPrototypeOf(this, AccessKeyMismatchError.prototype);
1154
- }
1155
- }
1156
- class InvalidOriginError extends WebrpcError {
1157
- constructor(error = {}) {
1158
- super(error);
1159
- this.name = error.name || 'InvalidOrigin';
1160
- this.code = typeof error.code === 'number' ? error.code : 1103;
1161
- this.message = error.message || `Invalid origin for Access Key`;
1162
- this.status = typeof error.status === 'number' ? error.status : 403;
1163
- if (error.cause !== undefined) this.cause = error.cause;
1164
- Object.setPrototypeOf(this, InvalidOriginError.prototype);
1165
- }
1166
- }
1167
- class InvalidServiceError extends WebrpcError {
1168
- constructor(error = {}) {
1169
- super(error);
1170
- this.name = error.name || 'InvalidService';
1171
- this.code = typeof error.code === 'number' ? error.code : 1104;
1172
- this.message = error.message || `Service not enabled for Access key`;
1173
- this.status = typeof error.status === 'number' ? error.status : 403;
1174
- if (error.cause !== undefined) this.cause = error.cause;
1175
- Object.setPrototypeOf(this, InvalidServiceError.prototype);
1176
- }
1177
- }
1178
- class UnauthorizedUserError extends WebrpcError {
1179
- constructor(error = {}) {
1180
- super(error);
1181
- this.name = error.name || 'UnauthorizedUser';
1182
- this.code = typeof error.code === 'number' ? error.code : 1105;
1183
- this.message = error.message || `Unauthorized user`;
1184
- this.status = typeof error.status === 'number' ? error.status : 403;
1185
- if (error.cause !== undefined) this.cause = error.cause;
1186
- Object.setPrototypeOf(this, UnauthorizedUserError.prototype);
1187
- }
1188
- }
1189
- class QuotaExceededError extends WebrpcError {
1190
- constructor(error = {}) {
1191
- super(error);
1192
- this.name = error.name || 'QuotaExceeded';
1193
- this.code = typeof error.code === 'number' ? error.code : 1200;
1194
- this.message = error.message || `Quota request exceeded`;
1195
- this.status = typeof error.status === 'number' ? error.status : 429;
1196
- if (error.cause !== undefined) this.cause = error.cause;
1197
- Object.setPrototypeOf(this, QuotaExceededError.prototype);
1198
- }
1199
- }
1200
- class QuotaRateLimitError extends WebrpcError {
1201
- constructor(error = {}) {
1202
- super(error);
1203
- this.name = error.name || 'QuotaRateLimit';
1204
- this.code = typeof error.code === 'number' ? error.code : 1201;
1205
- this.message = error.message || `Quota rate limit exceeded`;
1206
- this.status = typeof error.status === 'number' ? error.status : 429;
1207
- if (error.cause !== undefined) this.cause = error.cause;
1208
- Object.setPrototypeOf(this, QuotaRateLimitError.prototype);
1209
- }
1210
- }
1211
- class NoDefaultKeyError extends WebrpcError {
1212
- constructor(error = {}) {
1213
- super(error);
1214
- this.name = error.name || 'NoDefaultKey';
1215
- this.code = typeof error.code === 'number' ? error.code : 1300;
1216
- this.message = error.message || `No default access key found`;
1217
- this.status = typeof error.status === 'number' ? error.status : 403;
1218
- if (error.cause !== undefined) this.cause = error.cause;
1219
- Object.setPrototypeOf(this, NoDefaultKeyError.prototype);
1220
- }
1221
- }
1222
- class MaxAccessKeysError extends WebrpcError {
1223
- constructor(error = {}) {
1224
- super(error);
1225
- this.name = error.name || 'MaxAccessKeys';
1226
- this.code = typeof error.code === 'number' ? error.code : 1301;
1227
- this.message = error.message || `Access keys limit reached`;
1228
- this.status = typeof error.status === 'number' ? error.status : 403;
1229
- if (error.cause !== undefined) this.cause = error.cause;
1230
- Object.setPrototypeOf(this, MaxAccessKeysError.prototype);
1231
- }
1232
- }
1233
- class AtLeastOneKeyError extends WebrpcError {
1234
- constructor(error = {}) {
1235
- super(error);
1236
- this.name = error.name || 'AtLeastOneKey';
1237
- this.code = typeof error.code === 'number' ? error.code : 1302;
1238
- this.message = error.message || `You need at least one Access Key`;
1239
- this.status = typeof error.status === 'number' ? error.status : 403;
1240
- if (error.cause !== undefined) this.cause = error.cause;
1241
- Object.setPrototypeOf(this, AtLeastOneKeyError.prototype);
1242
- }
1243
- }
1244
- class TimeoutError extends WebrpcError {
1245
- constructor(error = {}) {
1246
- super(error);
1247
- this.name = error.name || 'Timeout';
1248
- this.code = typeof error.code === 'number' ? error.code : 1900;
1249
- this.message = error.message || `Request timed out`;
1250
- this.status = typeof error.status === 'number' ? error.status : 408;
1251
- if (error.cause !== undefined) this.cause = error.cause;
1252
- Object.setPrototypeOf(this, TimeoutError.prototype);
1253
- }
1254
- }
1255
- class InvalidArgumentError extends WebrpcError {
1256
- constructor(error = {}) {
1257
- super(error);
1258
- this.name = error.name || 'InvalidArgument';
1259
- this.code = typeof error.code === 'number' ? error.code : 2001;
1260
- this.message = error.message || `Invalid argument`;
1261
- this.status = typeof error.status === 'number' ? error.status : 400;
1262
- if (error.cause !== undefined) this.cause = error.cause;
1263
- Object.setPrototypeOf(this, InvalidArgumentError.prototype);
1264
- }
1265
- }
1266
- class UnavailableError extends WebrpcError {
1267
- constructor(error = {}) {
1268
- super(error);
1269
- this.name = error.name || 'Unavailable';
1270
- this.code = typeof error.code === 'number' ? error.code : 2002;
1271
- this.message = error.message || `Unavailable resource`;
1272
- this.status = typeof error.status === 'number' ? error.status : 400;
1273
- if (error.cause !== undefined) this.cause = error.cause;
1274
- Object.setPrototypeOf(this, UnavailableError.prototype);
1275
- }
1276
- }
1277
- class QueryFailedError extends WebrpcError {
1278
- constructor(error = {}) {
1279
- super(error);
1280
- this.name = error.name || 'QueryFailed';
1281
- this.code = typeof error.code === 'number' ? error.code : 2003;
1282
- this.message = error.message || `Query failed`;
1283
- this.status = typeof error.status === 'number' ? error.status : 400;
1284
- if (error.cause !== undefined) this.cause = error.cause;
1285
- Object.setPrototypeOf(this, QueryFailedError.prototype);
1286
- }
1287
- }
1288
- class NotFoundError extends WebrpcError {
1289
- constructor(error = {}) {
1290
- super(error);
1291
- this.name = error.name || 'NotFound';
1292
- this.code = typeof error.code === 'number' ? error.code : 3000;
1293
- this.message = error.message || `Resource not found`;
1294
- this.status = typeof error.status === 'number' ? error.status : 400;
1295
- if (error.cause !== undefined) this.cause = error.cause;
1296
- Object.setPrototypeOf(this, NotFoundError.prototype);
1297
- }
1298
- }
1299
- class InsufficientFeeError extends WebrpcError {
1300
- constructor(error = {}) {
1301
- super(error);
1302
- this.name = error.name || 'InsufficientFee';
1303
- this.code = typeof error.code === 'number' ? error.code : 3004;
1304
- this.message = error.message || `Insufficient fee`;
1305
- this.status = typeof error.status === 'number' ? error.status : 402;
1306
- if (error.cause !== undefined) this.cause = error.cause;
1307
- Object.setPrototypeOf(this, InsufficientFeeError.prototype);
1308
- }
1309
- }
1310
- class NotEnoughBalanceError extends WebrpcError {
1311
- constructor(error = {}) {
1312
- super(error);
1313
- this.name = error.name || 'NotEnoughBalance';
1314
- this.code = typeof error.code === 'number' ? error.code : 3005;
1315
- this.message = error.message || `Not enough balance`;
1316
- this.status = typeof error.status === 'number' ? error.status : 402;
1317
- if (error.cause !== undefined) this.cause = error.cause;
1318
- Object.setPrototypeOf(this, NotEnoughBalanceError.prototype);
1319
- }
1320
- }
1321
- class SimulationFailedError extends WebrpcError {
1322
- constructor(error = {}) {
1323
- super(error);
1324
- this.name = error.name || 'SimulationFailed';
1325
- this.code = typeof error.code === 'number' ? error.code : 3006;
1326
- this.message = error.message || `Simulation failed`;
1327
- this.status = typeof error.status === 'number' ? error.status : 400;
1328
- if (error.cause !== undefined) this.cause = error.cause;
1329
- Object.setPrototypeOf(this, SimulationFailedError.prototype);
1330
- }
1331
- }
1332
- let errors = /*#__PURE__*/function (errors) {
1333
- errors["WebrpcEndpoint"] = "WebrpcEndpoint";
1334
- errors["WebrpcRequestFailed"] = "WebrpcRequestFailed";
1335
- errors["WebrpcBadRoute"] = "WebrpcBadRoute";
1336
- errors["WebrpcBadMethod"] = "WebrpcBadMethod";
1337
- errors["WebrpcBadRequest"] = "WebrpcBadRequest";
1338
- errors["WebrpcBadResponse"] = "WebrpcBadResponse";
1339
- errors["WebrpcServerPanic"] = "WebrpcServerPanic";
1340
- errors["WebrpcInternalError"] = "WebrpcInternalError";
1341
- errors["WebrpcClientAborted"] = "WebrpcClientAborted";
1342
- errors["WebrpcStreamLost"] = "WebrpcStreamLost";
1343
- errors["WebrpcStreamFinished"] = "WebrpcStreamFinished";
1344
- errors["Unauthorized"] = "Unauthorized";
1345
- errors["PermissionDenied"] = "PermissionDenied";
1346
- errors["SessionExpired"] = "SessionExpired";
1347
- errors["MethodNotFound"] = "MethodNotFound";
1348
- errors["RequestConflict"] = "RequestConflict";
1349
- errors["Aborted"] = "Aborted";
1350
- errors["Geoblocked"] = "Geoblocked";
1351
- errors["RateLimited"] = "RateLimited";
1352
- errors["ProjectNotFound"] = "ProjectNotFound";
1353
- errors["AccessKeyNotFound"] = "AccessKeyNotFound";
1354
- errors["AccessKeyMismatch"] = "AccessKeyMismatch";
1355
- errors["InvalidOrigin"] = "InvalidOrigin";
1356
- errors["InvalidService"] = "InvalidService";
1357
- errors["UnauthorizedUser"] = "UnauthorizedUser";
1358
- errors["QuotaExceeded"] = "QuotaExceeded";
1359
- errors["QuotaRateLimit"] = "QuotaRateLimit";
1360
- errors["NoDefaultKey"] = "NoDefaultKey";
1361
- errors["MaxAccessKeys"] = "MaxAccessKeys";
1362
- errors["AtLeastOneKey"] = "AtLeastOneKey";
1363
- errors["Timeout"] = "Timeout";
1364
- errors["InvalidArgument"] = "InvalidArgument";
1365
- errors["Unavailable"] = "Unavailable";
1366
- errors["QueryFailed"] = "QueryFailed";
1367
- errors["NotFound"] = "NotFound";
1368
- errors["InsufficientFee"] = "InsufficientFee";
1369
- errors["NotEnoughBalance"] = "NotEnoughBalance";
1370
- errors["SimulationFailed"] = "SimulationFailed";
1371
- return errors;
1372
- }({});
1373
- let WebrpcErrorCodes = /*#__PURE__*/function (WebrpcErrorCodes) {
1374
- WebrpcErrorCodes[WebrpcErrorCodes["WebrpcEndpoint"] = 0] = "WebrpcEndpoint";
1375
- WebrpcErrorCodes[WebrpcErrorCodes["WebrpcRequestFailed"] = -1] = "WebrpcRequestFailed";
1376
- WebrpcErrorCodes[WebrpcErrorCodes["WebrpcBadRoute"] = -2] = "WebrpcBadRoute";
1377
- WebrpcErrorCodes[WebrpcErrorCodes["WebrpcBadMethod"] = -3] = "WebrpcBadMethod";
1378
- WebrpcErrorCodes[WebrpcErrorCodes["WebrpcBadRequest"] = -4] = "WebrpcBadRequest";
1379
- WebrpcErrorCodes[WebrpcErrorCodes["WebrpcBadResponse"] = -5] = "WebrpcBadResponse";
1380
- WebrpcErrorCodes[WebrpcErrorCodes["WebrpcServerPanic"] = -6] = "WebrpcServerPanic";
1381
- WebrpcErrorCodes[WebrpcErrorCodes["WebrpcInternalError"] = -7] = "WebrpcInternalError";
1382
- WebrpcErrorCodes[WebrpcErrorCodes["WebrpcClientAborted"] = -8] = "WebrpcClientAborted";
1383
- WebrpcErrorCodes[WebrpcErrorCodes["WebrpcStreamLost"] = -9] = "WebrpcStreamLost";
1384
- WebrpcErrorCodes[WebrpcErrorCodes["WebrpcStreamFinished"] = -10] = "WebrpcStreamFinished";
1385
- WebrpcErrorCodes[WebrpcErrorCodes["Unauthorized"] = 1000] = "Unauthorized";
1386
- WebrpcErrorCodes[WebrpcErrorCodes["PermissionDenied"] = 1001] = "PermissionDenied";
1387
- WebrpcErrorCodes[WebrpcErrorCodes["SessionExpired"] = 1002] = "SessionExpired";
1388
- WebrpcErrorCodes[WebrpcErrorCodes["MethodNotFound"] = 1003] = "MethodNotFound";
1389
- WebrpcErrorCodes[WebrpcErrorCodes["RequestConflict"] = 1004] = "RequestConflict";
1390
- WebrpcErrorCodes[WebrpcErrorCodes["Aborted"] = 1005] = "Aborted";
1391
- WebrpcErrorCodes[WebrpcErrorCodes["Geoblocked"] = 1006] = "Geoblocked";
1392
- WebrpcErrorCodes[WebrpcErrorCodes["RateLimited"] = 1007] = "RateLimited";
1393
- WebrpcErrorCodes[WebrpcErrorCodes["ProjectNotFound"] = 1008] = "ProjectNotFound";
1394
- WebrpcErrorCodes[WebrpcErrorCodes["AccessKeyNotFound"] = 1101] = "AccessKeyNotFound";
1395
- WebrpcErrorCodes[WebrpcErrorCodes["AccessKeyMismatch"] = 1102] = "AccessKeyMismatch";
1396
- WebrpcErrorCodes[WebrpcErrorCodes["InvalidOrigin"] = 1103] = "InvalidOrigin";
1397
- WebrpcErrorCodes[WebrpcErrorCodes["InvalidService"] = 1104] = "InvalidService";
1398
- WebrpcErrorCodes[WebrpcErrorCodes["UnauthorizedUser"] = 1105] = "UnauthorizedUser";
1399
- WebrpcErrorCodes[WebrpcErrorCodes["QuotaExceeded"] = 1200] = "QuotaExceeded";
1400
- WebrpcErrorCodes[WebrpcErrorCodes["QuotaRateLimit"] = 1201] = "QuotaRateLimit";
1401
- WebrpcErrorCodes[WebrpcErrorCodes["NoDefaultKey"] = 1300] = "NoDefaultKey";
1402
- WebrpcErrorCodes[WebrpcErrorCodes["MaxAccessKeys"] = 1301] = "MaxAccessKeys";
1403
- WebrpcErrorCodes[WebrpcErrorCodes["AtLeastOneKey"] = 1302] = "AtLeastOneKey";
1404
- WebrpcErrorCodes[WebrpcErrorCodes["Timeout"] = 1900] = "Timeout";
1405
- WebrpcErrorCodes[WebrpcErrorCodes["InvalidArgument"] = 2001] = "InvalidArgument";
1406
- WebrpcErrorCodes[WebrpcErrorCodes["Unavailable"] = 2002] = "Unavailable";
1407
- WebrpcErrorCodes[WebrpcErrorCodes["QueryFailed"] = 2003] = "QueryFailed";
1408
- WebrpcErrorCodes[WebrpcErrorCodes["NotFound"] = 3000] = "NotFound";
1409
- WebrpcErrorCodes[WebrpcErrorCodes["InsufficientFee"] = 3004] = "InsufficientFee";
1410
- WebrpcErrorCodes[WebrpcErrorCodes["NotEnoughBalance"] = 3005] = "NotEnoughBalance";
1411
- WebrpcErrorCodes[WebrpcErrorCodes["SimulationFailed"] = 3006] = "SimulationFailed";
1412
- return WebrpcErrorCodes;
1413
- }({});
1414
- const webrpcErrorByCode = {
1415
- [0]: WebrpcEndpointError,
1416
- [-1]: WebrpcRequestFailedError,
1417
- [-2]: WebrpcBadRouteError,
1418
- [-3]: WebrpcBadMethodError,
1419
- [-4]: WebrpcBadRequestError,
1420
- [-5]: WebrpcBadResponseError,
1421
- [-6]: WebrpcServerPanicError,
1422
- [-7]: WebrpcInternalErrorError,
1423
- [-8]: WebrpcClientAbortedError,
1424
- [-9]: WebrpcStreamLostError,
1425
- [-10]: WebrpcStreamFinishedError,
1426
- [1000]: UnauthorizedError,
1427
- [1001]: PermissionDeniedError,
1428
- [1002]: SessionExpiredError,
1429
- [1003]: MethodNotFoundError,
1430
- [1004]: RequestConflictError,
1431
- [1005]: AbortedError,
1432
- [1006]: GeoblockedError,
1433
- [1007]: RateLimitedError,
1434
- [1008]: ProjectNotFoundError,
1435
- [1101]: AccessKeyNotFoundError,
1436
- [1102]: AccessKeyMismatchError,
1437
- [1103]: InvalidOriginError,
1438
- [1104]: InvalidServiceError,
1439
- [1105]: UnauthorizedUserError,
1440
- [1200]: QuotaExceededError,
1441
- [1201]: QuotaRateLimitError,
1442
- [1300]: NoDefaultKeyError,
1443
- [1301]: MaxAccessKeysError,
1444
- [1302]: AtLeastOneKeyError,
1445
- [1900]: TimeoutError,
1446
- [2001]: InvalidArgumentError,
1447
- [2002]: UnavailableError,
1448
- [2003]: QueryFailedError,
1449
- [3000]: NotFoundError,
1450
- [3004]: InsufficientFeeError,
1451
- [3005]: NotEnoughBalanceError,
1452
- [3006]: SimulationFailedError
1453
- };
1454
-
1455
- //
1456
- // Webrpc
1457
- //
1458
-
1459
- const WebrpcHeader = 'Webrpc';
1460
- const WebrpcHeaderValue = 'webrpc@v0.31.2;gen-typescript@v0.23.1;sequence-relayer@v0.4.1';
1461
- function VersionFromHeader(headers) {
1462
- const headerValue = headers.get(WebrpcHeader);
1463
- if (!headerValue) {
1464
- return {
1465
- WebrpcGenVersion: '',
1466
- codeGenName: '',
1467
- codeGenVersion: '',
1468
- schemaName: '',
1469
- schemaVersion: ''
1470
- };
1471
- }
1472
- return parseWebrpcGenVersions(headerValue);
1473
- }
1474
- function parseWebrpcGenVersions(header) {
1475
- const versions = header.split(';');
1476
- if (versions.length < 3) {
1477
- return {
1478
- WebrpcGenVersion: '',
1479
- codeGenName: '',
1480
- codeGenVersion: '',
1481
- schemaName: '',
1482
- schemaVersion: ''
1483
- };
1484
- }
1485
- const [_, WebrpcGenVersion] = versions[0].split('@');
1486
- const [codeGenName, codeGenVersion] = versions[1].split('@');
1487
- const [schemaName, schemaVersion] = versions[2].split('@');
1488
- return {
1489
- WebrpcGenVersion: WebrpcGenVersion != null ? WebrpcGenVersion : '',
1490
- codeGenName: codeGenName != null ? codeGenName : '',
1491
- codeGenVersion: codeGenVersion != null ? codeGenVersion : '',
1492
- schemaName: schemaName != null ? schemaName : '',
1493
- schemaVersion: schemaVersion != null ? schemaVersion : ''
1494
- };
1495
- }
1496
-
1497
- var relayer_gen = /*#__PURE__*/Object.freeze({
1498
- __proto__: null,
1499
- WebrpcVersion: WebrpcVersion,
1500
- WebrpcSchemaVersion: WebrpcSchemaVersion,
1501
- WebrpcSchemaHash: WebrpcSchemaHash,
1502
- ETHTxnStatus: ETHTxnStatus,
1503
- TransferType: TransferType,
1504
- SimulateStatus: SimulateStatus,
1505
- FeeTokenType: FeeTokenType,
1506
- SortOrder: SortOrder,
1507
- Relayer: Relayer,
1508
- JsonEncode: JsonEncode,
1509
- JsonDecode: JsonDecode,
1510
- WebrpcError: WebrpcError,
1511
- WebrpcEndpointError: WebrpcEndpointError,
1512
- WebrpcRequestFailedError: WebrpcRequestFailedError,
1513
- WebrpcBadRouteError: WebrpcBadRouteError,
1514
- WebrpcBadMethodError: WebrpcBadMethodError,
1515
- WebrpcBadRequestError: WebrpcBadRequestError,
1516
- WebrpcBadResponseError: WebrpcBadResponseError,
1517
- WebrpcServerPanicError: WebrpcServerPanicError,
1518
- WebrpcInternalErrorError: WebrpcInternalErrorError,
1519
- WebrpcClientAbortedError: WebrpcClientAbortedError,
1520
- WebrpcStreamLostError: WebrpcStreamLostError,
1521
- WebrpcStreamFinishedError: WebrpcStreamFinishedError,
1522
- UnauthorizedError: UnauthorizedError,
1523
- PermissionDeniedError: PermissionDeniedError,
1524
- SessionExpiredError: SessionExpiredError,
1525
- MethodNotFoundError: MethodNotFoundError,
1526
- RequestConflictError: RequestConflictError,
1527
- AbortedError: AbortedError,
1528
- GeoblockedError: GeoblockedError,
1529
- RateLimitedError: RateLimitedError,
1530
- ProjectNotFoundError: ProjectNotFoundError,
1531
- AccessKeyNotFoundError: AccessKeyNotFoundError,
1532
- AccessKeyMismatchError: AccessKeyMismatchError,
1533
- InvalidOriginError: InvalidOriginError,
1534
- InvalidServiceError: InvalidServiceError,
1535
- UnauthorizedUserError: UnauthorizedUserError,
1536
- QuotaExceededError: QuotaExceededError,
1537
- QuotaRateLimitError: QuotaRateLimitError,
1538
- NoDefaultKeyError: NoDefaultKeyError,
1539
- MaxAccessKeysError: MaxAccessKeysError,
1540
- AtLeastOneKeyError: AtLeastOneKeyError,
1541
- TimeoutError: TimeoutError,
1542
- InvalidArgumentError: InvalidArgumentError,
1543
- UnavailableError: UnavailableError,
1544
- QueryFailedError: QueryFailedError,
1545
- NotFoundError: NotFoundError,
1546
- InsufficientFeeError: InsufficientFeeError,
1547
- NotEnoughBalanceError: NotEnoughBalanceError,
1548
- SimulationFailedError: SimulationFailedError,
1549
- errors: errors,
1550
- WebrpcErrorCodes: WebrpcErrorCodes,
1551
- webrpcErrorByCode: webrpcErrorByCode,
1552
- WebrpcHeader: WebrpcHeader,
1553
- WebrpcHeaderValue: WebrpcHeaderValue,
1554
- VersionFromHeader: VersionFromHeader
1555
- });
1556
-
1557
- const FINAL_STATUSES = [ETHTxnStatus.DROPPED, ETHTxnStatus.SUCCEEDED, ETHTxnStatus.PARTIALLY_FAILED, ETHTxnStatus.FAILED];
1558
- const FAILED_STATUSES = [ETHTxnStatus.DROPPED, ETHTxnStatus.PARTIALLY_FAILED, ETHTxnStatus.FAILED];
1559
- function isRpcRelayerOptions(obj) {
1560
- return obj.url !== undefined && typeof obj.url === 'string' && obj.provider !== undefined && isAbstractProvider(obj.provider);
1561
- }
1562
-
1563
- // TODO: rename to SequenceRelayer
1564
- class RpcRelayer {
1565
- constructor(options) {
1566
- this.options = options;
1567
- this.service = void 0;
1568
- this.provider = void 0;
1569
- this._fetch = (input, init) => {
1570
- // automatically include jwt and access key auth header to requests
1571
- // if its been set on the api client
1572
- const headers = {};
1573
- const {
1574
- jwtAuth,
1575
- projectAccessKey
1576
- } = this.options;
1577
- if (jwtAuth && jwtAuth.length > 0) {
1578
- headers['Authorization'] = `BEARER ${jwtAuth}`;
1579
- }
1580
- if (projectAccessKey && projectAccessKey.length > 0) {
1581
- headers['X-Access-Key'] = projectAccessKey;
1582
- }
1583
-
1584
- // before the request is made
1585
- init.headers = _extends({}, headers, init.headers);
1586
- return fetch(input, init);
1587
- };
1588
- this.service = new Relayer(options.url, this._fetch);
1589
- if (isAbstractProvider(options.provider)) {
1590
- this.provider = options.provider;
1591
- } else {
1592
- const {
1593
- jwtAuth,
1594
- projectAccessKey
1595
- } = this.options;
1596
- const fetchRequest = getFetchRequest(options.provider.url, projectAccessKey, jwtAuth);
1597
- this.provider = new ethers.JsonRpcProvider(fetchRequest, undefined, {
1598
- staticNetwork: true
1599
- });
1600
- }
1601
- }
1602
- async waitReceipt(metaTxnId, delay = 1000, maxFails = 5, isCancelled) {
1603
- if (typeof metaTxnId !== 'string') {
1604
- metaTxnId = commons.transaction.intendedTransactionID(metaTxnId);
1605
- }
1606
- logger.info(`[rpc-relayer/waitReceipt] waiting for ${metaTxnId}`);
1607
- let fails = 0;
1608
- while (isCancelled === undefined || !isCancelled()) {
1609
- try {
1610
- const {
1611
- receipt
1612
- } = await this.service.getMetaTxnReceipt({
1613
- metaTxID: metaTxnId
1614
- });
1615
- if (receipt && receipt.txnReceipt && receipt.txnReceipt !== 'null' && FINAL_STATUSES.includes(receipt.status)) {
1616
- return {
1617
- receipt
1618
- };
1619
- }
1620
- } catch (e) {
1621
- fails++;
1622
- if (fails === maxFails) {
1623
- throw e;
1624
- }
1625
- }
1626
- if (isCancelled === undefined || !isCancelled()) {
1627
- await new Promise(resolve => setTimeout(resolve, delay));
1628
- }
1629
- }
1630
- throw new Error(`Cancelled waiting for transaction receipt ${metaTxnId}`);
1631
- }
1632
- async simulate(wallet, ...transactions) {
1633
- const coder = ethers.AbiCoder.defaultAbiCoder();
1634
- const encoded = coder.encode([commons.transaction.MetaTransactionsType], [commons.transaction.sequenceTxAbiEncode(transactions)]);
1635
- return (await this.service.simulate({
1636
- wallet,
1637
- transactions: encoded
1638
- })).results;
1639
- }
1640
- async getFeeOptions(address, ...transactions) {
1641
- // NOTE/TODO: for a given `service` the feeTokens will not change between execution, so we should memoize this value
1642
- // for a short-period of time, perhaps for 1 day or in memory. Perhaps one day we can make this happen automatically
1643
- // with http cache response for this endpoint and service-worker.. lots of approaches
1644
- const feeTokens = await this.service.feeTokens();
1645
- if (feeTokens.isFeeRequired) {
1646
- const symbols = feeTokens.tokens.map(token => token.symbol).join(', ');
1647
- logger.info(`[rpc-relayer/getFeeOptions] relayer fees are required, accepted tokens are ${symbols}`);
1648
- const nonce = await this.getNonce(address);
1649
- if (!this.provider) {
1650
- logger.warn(`[rpc-relayer/getFeeOptions] provider not set, needed for stub signature`);
1651
- throw new Error('provider is not set');
1652
- }
1653
- const {
1654
- options,
1655
- quote
1656
- } = await this.service.feeOptions({
1657
- wallet: address,
1658
- to: address,
1659
- data: commons.transaction.encodeBundleExecData({
1660
- entrypoint: address,
1661
- transactions,
1662
- nonce
1663
- })
1664
- });
1665
- logger.info(`[rpc-relayer/getFeeOptions] got refund options ${JSON.stringify(options, bigintReplacer)}`);
1666
- return {
1667
- options,
1668
- quote: {
1669
- _tag: 'FeeQuote',
1670
- _quote: quote
1671
- }
1672
- };
1673
- } else {
1674
- logger.info(`[rpc-relayer/getFeeOptions] relayer fees are not required`);
1675
- return {
1676
- options: []
1677
- };
1678
- }
1679
- }
1680
- async getFeeOptionsRaw(entrypoint, data, options) {
1681
- const {
1682
- options: feeOptions,
1683
- quote
1684
- } = await this.service.feeOptions({
1685
- wallet: entrypoint,
1686
- to: entrypoint,
1687
- data: ethers.hexlify(data),
1688
- simulate: options == null ? void 0 : options.simulate
1689
- }, _extends({}, options != null && options.projectAccessKey ? {
1690
- 'X-Access-Key': options.projectAccessKey
1691
- } : undefined));
1692
- return {
1693
- options: feeOptions,
1694
- quote: {
1695
- _tag: 'FeeQuote',
1696
- _quote: quote
1697
- }
1698
- };
1699
- }
1700
- async gasRefundOptions(address, ...transactions) {
1701
- const {
1702
- options
1703
- } = await this.getFeeOptions(address, ...transactions);
1704
- return options;
1705
- }
1706
- async getNonce(address, space) {
1707
- logger.info(`[rpc-relayer/getNonce] get nonce for wallet ${address} space: ${space}`);
1708
- const encodedNonce = space !== undefined ? toHexString(BigInt(space)) : undefined;
1709
- const resp = await this.service.getMetaTxnNonce({
1710
- walletContractAddress: address,
1711
- space: encodedNonce
1712
- });
1713
- const nonce = BigInt(resp.nonce);
1714
- const [decodedSpace, decodedNonce] = commons.transaction.decodeNonce(nonce);
1715
- logger.info(`[rpc-relayer/getNonce] got next nonce for wallet ${address} ${decodedNonce} space: ${decodedSpace}`);
1716
- return nonce;
1717
- }
1718
- async relay(signedTxs, quote, waitForReceipt = true, projectAccessKey) {
1719
- var _this = this;
1720
- logger.info(`[rpc-relayer/relay] relaying signed meta-transactions ${JSON.stringify(signedTxs, bigintReplacer)} with quote ${JSON.stringify(quote, bigintReplacer)}`);
1721
- let typecheckedQuote;
1722
- if (quote !== undefined) {
1723
- if (typeof quote._quote === 'string') {
1724
- typecheckedQuote = quote._quote;
1725
- } else {
1726
- logger.warn('[rpc-relayer/relay] ignoring invalid fee quote');
1727
- }
1728
- }
1729
- if (!this.provider) {
1730
- logger.warn(`[rpc-relayer/relay] provider not set, failed relay`);
1731
- throw new Error('provider is not set');
1732
- }
1733
- const data = commons.transaction.encodeBundleExecData(signedTxs);
1734
- const metaTxn = await this.service.sendMetaTxn({
1735
- call: {
1736
- walletAddress: signedTxs.intent.wallet,
1737
- contract: signedTxs.entrypoint,
1738
- input: data
1739
- },
1740
- quote: typecheckedQuote
1741
- }, _extends({}, projectAccessKey ? {
1742
- 'X-Access-Key': projectAccessKey
1743
- } : undefined));
1744
- logger.info(`[rpc-relayer/relay] got relay result ${JSON.stringify(metaTxn, bigintReplacer)}`);
1745
- if (waitForReceipt) {
1746
- return this.wait(signedTxs.intent.id);
1747
- } else {
1748
- const response = {
1749
- hash: signedTxs.intent.id,
1750
- confirmations: 0,
1751
- from: signedTxs.intent.wallet,
1752
- wait: _confirmations => Promise.reject(new Error('impossible'))
1753
- };
1754
- const wait = async function wait(confirmations) {
1755
- var _waitResponse$receipt;
1756
- if (!_this.provider) {
1757
- throw new Error('cannot wait for receipt, relayer has no provider set');
1758
- }
1759
- const waitResponse = await _this.wait(signedTxs.intent.id);
1760
- const transactionHash = (_waitResponse$receipt = waitResponse.receipt) == null ? void 0 : _waitResponse$receipt.transactionHash;
1761
- if (!transactionHash) {
1762
- throw new Error('cannot wait for receipt, unknown native transaction hash');
1763
- }
1764
- Object.assign(response, waitResponse);
1765
- return _this.provider.waitForTransaction(transactionHash, confirmations);
1766
- };
1767
- response.wait = wait;
1768
-
1769
- // NOTE: we just ignore these errors which come from the private fields
1770
- // of ethers-v6 .. but, we should probably rework this instead..
1771
- // @ts-ignore
1772
- return response;
1773
- }
1774
- }
1775
- async wait(metaTxnId, timeout, delay = 1000, maxFails = 5) {
1776
- var _this2 = this;
1777
- let timedOut = false;
1778
- const {
1779
- receipt
1780
- } = await (timeout !== undefined ? Promise.race([this.waitReceipt(metaTxnId, delay, maxFails, () => timedOut), new Promise((_, reject) => setTimeout(() => {
1781
- timedOut = true;
1782
- reject(`Timeout waiting for transaction receipt ${metaTxnId}`);
1783
- }, timeout))]) : this.waitReceipt(metaTxnId, delay, maxFails));
1784
- if (!receipt.txnReceipt || FAILED_STATUSES.includes(receipt.status)) {
1785
- throw new MetaTransactionResponseException(receipt);
1786
- }
1787
- const txReceipt = JSON.parse(receipt.txnReceipt);
1788
-
1789
- // NOTE: we just ignore these errors which come from the private fields
1790
- // of ethers-v6 .. but, we should probably rework this instead..
1791
- // @ts-ignore
1792
- return {
1793
- blockHash: txReceipt.blockHash,
1794
- blockNumber: Number(txReceipt.blockNumber),
1795
- confirmations: 1,
1796
- from: typeof metaTxnId === 'string' ? undefined : metaTxnId.intent.wallet,
1797
- hash: txReceipt.transactionHash,
1798
- raw: receipt.txnReceipt,
1799
- receipt: txReceipt,
1800
- // extended type which is Sequence-specific. Contains the decoded metaTxReceipt
1801
- wait: async function (confirmations) {
1802
- return _this2.provider.waitForTransaction(txReceipt.transactionHash, confirmations);
1803
- }
1804
- };
1805
- }
1806
- async getMetaTransactions(projectId, page) {
1807
- return this.service.getMetaTransactions({
1808
- projectId,
1809
- page
1810
- });
1811
- }
1812
- async getTransactionCost(projectId, from, to) {
1813
- return this.service.getTransactionCost({
1814
- projectId,
1815
- from,
1816
- to
1817
- });
1818
- }
1819
- async listGasSponsors(args) {
1820
- return this.service.listGasSponsors(args);
1821
- }
1822
- async addGasSponsor(args) {
1823
- return this.service.addGasSponsor(args);
1824
- }
1825
- async updateGasSponsor(args) {
1826
- return this.service.updateGasSponsor(args);
1827
- }
1828
- async removeGasSponsor(args) {
1829
- return this.service.removeGasSponsor(args);
1830
- }
1831
- }
1832
- class MetaTransactionResponseException {
1833
- constructor(receipt) {
1834
- this.receipt = receipt;
1835
- }
1836
- }
1837
- function isAbstractProvider(provider) {
1838
- return provider && typeof provider === 'object' && typeof provider.getNetwork === 'function' && typeof provider.getBlockNumber === 'function';
1839
- }
1840
-
1841
- // A fee quote is simply an opaque value that can be obtained via Relayer.getFeeOptions(), and
1842
- // returned back to the same relayer via Relayer.relay(). Fee quotes should be treated as an
1843
- // implementation detail of the relayer that produces them.
1844
- //
1845
- // This interface exists for type-safety purposes to protect against passing non-FeeQuotes to
1846
- // Relayer.relay(), or any other functions that call it indirectly (e.g. Account.sendTransaction).
1847
-
1848
- function isRelayer(cand) {
1849
- return typeof cand === 'object' && typeof cand.simulate === 'function' && typeof cand.getFeeOptions === 'function' && typeof cand.gasRefundOptions === 'function' && typeof cand.getNonce === 'function' && typeof cand.relay === 'function' && typeof cand.wait === 'function';
1850
- }
1851
-
1852
- export { LocalRelayer, ProviderRelayer, ProviderRelayerDefaults, RpcRelayer, relayer_gen as RpcRelayerProto, isLocalRelayerOptions, isProviderRelayerOptions, isRelayer, isRpcRelayerOptions, relayer_gen as proto };