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