@0xsequence/relayer 2.3.35 → 3.0.0-beta.2

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