@0xsequence/relayer 2.3.16 → 2.3.18

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