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