@0xsquid/react-hooks 8.3.1-embed-tanstack-build.1 → 8.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/core/constants.d.ts +1 -0
  2. package/dist/core/index.d.ts +1 -1
  3. package/dist/core/types/transaction.d.ts +19 -1
  4. package/dist/hooks/hedera/useHederaAccountActivation.d.ts +10 -0
  5. package/dist/hooks/index.d.ts +2 -1
  6. package/dist/hooks/tokens/useNativeBalance.d.ts +2 -0
  7. package/dist/hooks/transaction/useGetRoute.d.ts +18 -7
  8. package/dist/{index-CBdXaMut.js → index-BdrSk8Ed.js} +4870 -12873
  9. package/dist/index-BdrSk8Ed.js.map +1 -0
  10. package/dist/{index-CHFbvaAT.js → index-BxJVsDEs.js} +4773 -12780
  11. package/dist/index-BxJVsDEs.js.map +1 -0
  12. package/dist/{index.es-CJQ994zu.js → index.es-CFf55ppw.js} +5 -4
  13. package/dist/index.es-CFf55ppw.js.map +1 -0
  14. package/dist/{index.es-Db1itMBd.js → index.es-DhiQj1ju.js} +5 -4
  15. package/dist/index.es-DhiQj1ju.js.map +1 -0
  16. package/dist/index.esm.js +4 -3
  17. package/dist/index.esm.js.map +1 -1
  18. package/dist/index.js +18 -3
  19. package/dist/index.js.map +1 -1
  20. package/dist/{secretService-C_xxV54S.js → secretService-D0xrwhEv.js} +5 -4
  21. package/dist/{secretService-C_xxV54S.js.map → secretService-D0xrwhEv.js.map} +1 -1
  22. package/dist/{secretService-BEHJHJzr.js → secretService-DRTd4cda.js} +5 -4
  23. package/dist/{secretService-BEHJHJzr.js.map → secretService-DRTd4cda.js.map} +1 -1
  24. package/dist/services/index.d.ts +1 -0
  25. package/dist/services/internal/hederaService.d.ts +2 -0
  26. package/dist/services/internal/routeService.d.ts +8 -0
  27. package/dist/services/internal/transactionService.d.ts +14 -1
  28. package/dist/{stellarService.client-DKE1A5qx.js → stellarService.client-CRFUb2R6.js} +5 -4
  29. package/dist/{stellarService.client-DKe-JCHP.js.map → stellarService.client-CRFUb2R6.js.map} +1 -1
  30. package/dist/{stellarService.client-DKe-JCHP.js → stellarService.client-xMf7fjCz.js} +5 -4
  31. package/dist/{stellarService.client-DKE1A5qx.js.map → stellarService.client-xMf7fjCz.js.map} +1 -1
  32. package/package.json +4 -4
  33. package/dist/browser-BpOc5ZYm.js +0 -728
  34. package/dist/browser-BpOc5ZYm.js.map +0 -1
  35. package/dist/browser-C2k8mMWG.js +0 -731
  36. package/dist/browser-C2k8mMWG.js.map +0 -1
  37. package/dist/clsx.m-5lBZSkly.js +0 -13
  38. package/dist/clsx.m-5lBZSkly.js.map +0 -1
  39. package/dist/clsx.m-C1RYtb0y.js +0 -10
  40. package/dist/clsx.m-C1RYtb0y.js.map +0 -1
  41. package/dist/index-CBdXaMut.js.map +0 -1
  42. package/dist/index-CHFbvaAT.js.map +0 -1
  43. package/dist/index-CJc-nZ2s.js +0 -20967
  44. package/dist/index-CJc-nZ2s.js.map +0 -1
  45. package/dist/index-CQhbmLAK.js +0 -20945
  46. package/dist/index-CQhbmLAK.js.map +0 -1
  47. package/dist/index-Dehij_6h.js +0 -4628
  48. package/dist/index-Dehij_6h.js.map +0 -1
  49. package/dist/index-T4Aq984K.js +0 -4630
  50. package/dist/index-T4Aq984K.js.map +0 -1
  51. package/dist/index.es-CJQ994zu.js.map +0 -1
  52. package/dist/index.es-Db1itMBd.js.map +0 -1
  53. package/dist/metamask-sdk-BD7Q6BkI.js +0 -6353
  54. package/dist/metamask-sdk-BD7Q6BkI.js.map +0 -1
  55. package/dist/metamask-sdk-DFVIZ2SC.js +0 -6359
  56. package/dist/metamask-sdk-DFVIZ2SC.js.map +0 -1
@@ -1,4630 +0,0 @@
1
- 'use strict';
2
-
3
- var index = require('./index-CBdXaMut.js');
4
- var clsx_m = require('./clsx.m-5lBZSkly.js');
5
- require('@0xsquid/squid-types');
6
- require('viem');
7
- require('react');
8
- require('@cosmjs/encoding');
9
- require('bitcoinjs-lib');
10
- require('@bitcoinerlab/secp256k1');
11
- require('axios');
12
- require('@walletconnect/modal');
13
- require('@walletconnect/universal-provider');
14
- require('ripple-address-codec');
15
- require('@solana/spl-token');
16
- require('@solana/wallet-standard-wallet-adapter-base');
17
- require('@solana/web3.js');
18
- require('@stellar/stellar-sdk');
19
- require('@mysten/wallet-standard');
20
- require('ethers');
21
- require('bignumber.js');
22
- require('countries-list');
23
- require('currency-symbol-map');
24
- require('fuse.js');
25
- require('zustand');
26
- require('zustand/middleware');
27
- require('@safe-global/safe-apps-sdk');
28
- require('@wallet-standard/core');
29
- require('@mysten/slush-wallet');
30
- require('viem/utils');
31
- require('@cosmjs/stargate');
32
- require('@mysten/sui/client');
33
- require('viem/actions');
34
- require('@cosmjs/proto-signing');
35
- require('@mysten/sui/transactions');
36
- require('@cosmjs/cosmwasm-stargate');
37
- require('@injectivelabs/sdk-ts/dist/cjs/core/stargate/index.js');
38
- require('@0xsquid/sdk');
39
- require('viem/chains');
40
-
41
- // Copyright (c) 2018-2024 Coinbase, Inc. <https://www.coinbase.com/>
42
- // TODO: clean up, or possibly deprecate Storage class
43
- class ScopedLocalStorage {
44
- constructor(scope, module) {
45
- this.scope = scope;
46
- this.module = module;
47
- }
48
- storeObject(key, item) {
49
- this.setItem(key, JSON.stringify(item));
50
- }
51
- loadObject(key) {
52
- const item = this.getItem(key);
53
- return item ? JSON.parse(item) : undefined;
54
- }
55
- setItem(key, value) {
56
- localStorage.setItem(this.scopedKey(key), value);
57
- }
58
- getItem(key) {
59
- return localStorage.getItem(this.scopedKey(key));
60
- }
61
- removeItem(key) {
62
- localStorage.removeItem(this.scopedKey(key));
63
- }
64
- clear() {
65
- const prefix = this.scopedKey('');
66
- const keysToRemove = [];
67
- for (let i = 0; i < localStorage.length; i++) {
68
- const key = localStorage.key(i);
69
- if (typeof key === 'string' && key.startsWith(prefix)) {
70
- keysToRemove.push(key);
71
- }
72
- }
73
- keysToRemove.forEach((key) => localStorage.removeItem(key));
74
- }
75
- scopedKey(key) {
76
- return `-${this.scope}${this.module ? `:${this.module}` : ''}:${key}`;
77
- }
78
- static clearAll() {
79
- new ScopedLocalStorage('CBWSDK').clear();
80
- new ScopedLocalStorage('walletlink').clear();
81
- }
82
- }
83
-
84
- const standardErrorCodes = {
85
- rpc: {
86
- invalidInput: -32e3,
87
- resourceNotFound: -32001,
88
- resourceUnavailable: -32002,
89
- transactionRejected: -32003,
90
- methodNotSupported: -32004,
91
- limitExceeded: -32005,
92
- parse: -32700,
93
- invalidRequest: -32600,
94
- methodNotFound: -32601,
95
- invalidParams: -32602,
96
- internal: -32603,
97
- },
98
- provider: {
99
- userRejectedRequest: 4001,
100
- unauthorized: 4100,
101
- unsupportedMethod: 4200,
102
- disconnected: 4900,
103
- chainDisconnected: 4901,
104
- unsupportedChain: 4902,
105
- },
106
- };
107
- const errorValues = {
108
- '-32700': {
109
- standard: 'JSON RPC 2.0',
110
- message: 'Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.',
111
- },
112
- '-32600': {
113
- standard: 'JSON RPC 2.0',
114
- message: 'The JSON sent is not a valid Request object.',
115
- },
116
- '-32601': {
117
- standard: 'JSON RPC 2.0',
118
- message: 'The method does not exist / is not available.',
119
- },
120
- '-32602': {
121
- standard: 'JSON RPC 2.0',
122
- message: 'Invalid method parameter(s).',
123
- },
124
- '-32603': {
125
- standard: 'JSON RPC 2.0',
126
- message: 'Internal JSON-RPC error.',
127
- },
128
- '-32000': {
129
- standard: 'EIP-1474',
130
- message: 'Invalid input.',
131
- },
132
- '-32001': {
133
- standard: 'EIP-1474',
134
- message: 'Resource not found.',
135
- },
136
- '-32002': {
137
- standard: 'EIP-1474',
138
- message: 'Resource unavailable.',
139
- },
140
- '-32003': {
141
- standard: 'EIP-1474',
142
- message: 'Transaction rejected.',
143
- },
144
- '-32004': {
145
- standard: 'EIP-1474',
146
- message: 'Method not supported.',
147
- },
148
- '-32005': {
149
- standard: 'EIP-1474',
150
- message: 'Request limit exceeded.',
151
- },
152
- '4001': {
153
- standard: 'EIP-1193',
154
- message: 'User rejected the request.',
155
- },
156
- '4100': {
157
- standard: 'EIP-1193',
158
- message: 'The requested account and/or method has not been authorized by the user.',
159
- },
160
- '4200': {
161
- standard: 'EIP-1193',
162
- message: 'The requested method is not supported by this Ethereum provider.',
163
- },
164
- '4900': {
165
- standard: 'EIP-1193',
166
- message: 'The provider is disconnected from all chains.',
167
- },
168
- '4901': {
169
- standard: 'EIP-1193',
170
- message: 'The provider is disconnected from the specified chain.',
171
- },
172
- '4902': {
173
- standard: 'EIP-3085',
174
- message: 'Unrecognized chain ID.',
175
- },
176
- };
177
-
178
- const FALLBACK_MESSAGE = 'Unspecified error message.';
179
- const JSON_RPC_SERVER_ERROR_MESSAGE = 'Unspecified server error.';
180
- /**
181
- * Gets the message for a given code, or a fallback message if the code has
182
- * no corresponding message.
183
- */
184
- function getMessageFromCode(code, fallbackMessage = FALLBACK_MESSAGE) {
185
- if (code && Number.isInteger(code)) {
186
- const codeString = code.toString();
187
- if (hasKey(errorValues, codeString)) {
188
- return errorValues[codeString].message;
189
- }
190
- if (isJsonRpcServerError(code)) {
191
- return JSON_RPC_SERVER_ERROR_MESSAGE;
192
- }
193
- }
194
- return fallbackMessage;
195
- }
196
- /**
197
- * Returns whether the given code is valid.
198
- * A code is only valid if it has a message.
199
- */
200
- function isValidCode(code) {
201
- if (!Number.isInteger(code)) {
202
- return false;
203
- }
204
- const codeString = code.toString();
205
- if (errorValues[codeString]) {
206
- return true;
207
- }
208
- if (isJsonRpcServerError(code)) {
209
- return true;
210
- }
211
- return false;
212
- }
213
- function serialize(error, { shouldIncludeStack = false } = {}) {
214
- const serialized = {};
215
- if (error &&
216
- typeof error === 'object' &&
217
- !Array.isArray(error) &&
218
- hasKey(error, 'code') &&
219
- isValidCode(error.code)) {
220
- const _error = error;
221
- serialized.code = _error.code;
222
- if (_error.message && typeof _error.message === 'string') {
223
- serialized.message = _error.message;
224
- if (hasKey(_error, 'data')) {
225
- serialized.data = _error.data;
226
- }
227
- }
228
- else {
229
- serialized.message = getMessageFromCode(serialized.code);
230
- serialized.data = { originalError: assignOriginalError(error) };
231
- }
232
- }
233
- else {
234
- serialized.code = standardErrorCodes.rpc.internal;
235
- serialized.message = hasStringProperty(error, 'message') ? error.message : FALLBACK_MESSAGE;
236
- serialized.data = { originalError: assignOriginalError(error) };
237
- }
238
- if (shouldIncludeStack) {
239
- serialized.stack = hasStringProperty(error, 'stack') ? error.stack : undefined;
240
- }
241
- return serialized;
242
- }
243
- // Internal
244
- function isJsonRpcServerError(code) {
245
- return code >= -32099 && code <= -32e3;
246
- }
247
- function assignOriginalError(error) {
248
- if (error && typeof error === 'object' && !Array.isArray(error)) {
249
- return Object.assign({}, error);
250
- }
251
- return error;
252
- }
253
- function hasKey(obj, key) {
254
- return Object.prototype.hasOwnProperty.call(obj, key);
255
- }
256
- function hasStringProperty(obj, prop) {
257
- return (typeof obj === 'object' && obj !== null && prop in obj && typeof obj[prop] === 'string');
258
- }
259
-
260
- const standardErrors = {
261
- rpc: {
262
- parse: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.parse, arg),
263
- invalidRequest: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.invalidRequest, arg),
264
- invalidParams: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.invalidParams, arg),
265
- methodNotFound: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.methodNotFound, arg),
266
- internal: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.internal, arg),
267
- server: (opts) => {
268
- if (!opts || typeof opts !== 'object' || Array.isArray(opts)) {
269
- throw new Error('Ethereum RPC Server errors must provide single object argument.');
270
- }
271
- const { code } = opts;
272
- if (!Number.isInteger(code) || code > -32005 || code < -32099) {
273
- throw new Error('"code" must be an integer such that: -32099 <= code <= -32005');
274
- }
275
- return getEthJsonRpcError(code, opts);
276
- },
277
- invalidInput: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.invalidInput, arg),
278
- resourceNotFound: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.resourceNotFound, arg),
279
- resourceUnavailable: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.resourceUnavailable, arg),
280
- transactionRejected: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.transactionRejected, arg),
281
- methodNotSupported: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.methodNotSupported, arg),
282
- limitExceeded: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.limitExceeded, arg),
283
- },
284
- provider: {
285
- userRejectedRequest: (arg) => {
286
- return getEthProviderError(standardErrorCodes.provider.userRejectedRequest, arg);
287
- },
288
- unauthorized: (arg) => {
289
- return getEthProviderError(standardErrorCodes.provider.unauthorized, arg);
290
- },
291
- unsupportedMethod: (arg) => {
292
- return getEthProviderError(standardErrorCodes.provider.unsupportedMethod, arg);
293
- },
294
- disconnected: (arg) => {
295
- return getEthProviderError(standardErrorCodes.provider.disconnected, arg);
296
- },
297
- chainDisconnected: (arg) => {
298
- return getEthProviderError(standardErrorCodes.provider.chainDisconnected, arg);
299
- },
300
- unsupportedChain: (arg) => {
301
- return getEthProviderError(standardErrorCodes.provider.unsupportedChain, arg);
302
- },
303
- custom: (opts) => {
304
- if (!opts || typeof opts !== 'object' || Array.isArray(opts)) {
305
- throw new Error('Ethereum Provider custom errors must provide single object argument.');
306
- }
307
- const { code, message, data } = opts;
308
- if (!message || typeof message !== 'string') {
309
- throw new Error('"message" must be a nonempty string');
310
- }
311
- return new EthereumProviderError(code, message, data);
312
- },
313
- },
314
- };
315
- // Internal
316
- function getEthJsonRpcError(code, arg) {
317
- const [message, data] = parseOpts(arg);
318
- return new EthereumRpcError(code, message || getMessageFromCode(code), data);
319
- }
320
- function getEthProviderError(code, arg) {
321
- const [message, data] = parseOpts(arg);
322
- return new EthereumProviderError(code, message || getMessageFromCode(code), data);
323
- }
324
- function parseOpts(arg) {
325
- if (arg) {
326
- if (typeof arg === 'string') {
327
- return [arg];
328
- }
329
- else if (typeof arg === 'object' && !Array.isArray(arg)) {
330
- const { message, data } = arg;
331
- if (message && typeof message !== 'string') {
332
- throw new Error('Must specify string message.');
333
- }
334
- return [message || undefined, data];
335
- }
336
- }
337
- return [];
338
- }
339
- class EthereumRpcError extends Error {
340
- constructor(code, message, data) {
341
- if (!Number.isInteger(code)) {
342
- throw new Error('"code" must be an integer.');
343
- }
344
- if (!message || typeof message !== 'string') {
345
- throw new Error('"message" must be a nonempty string.');
346
- }
347
- super(message);
348
- this.code = code;
349
- if (data !== undefined) {
350
- this.data = data;
351
- }
352
- }
353
- }
354
- class EthereumProviderError extends EthereumRpcError {
355
- /**
356
- * Create an Ethereum Provider JSON-RPC error.
357
- * `code` must be an integer in the 1000 <= 4999 range.
358
- */
359
- constructor(code, message, data) {
360
- if (!isValidEthProviderCode(code)) {
361
- throw new Error('"code" must be an integer such that: 1000 <= code <= 4999');
362
- }
363
- super(code, message, data);
364
- }
365
- }
366
- function isValidEthProviderCode(code) {
367
- return Number.isInteger(code) && code >= 1000 && code <= 4999;
368
- }
369
-
370
- function OpaqueType() {
371
- return (value) => value;
372
- }
373
- const HexString = OpaqueType();
374
- const AddressString = OpaqueType();
375
- const BigIntString = OpaqueType();
376
- function IntNumber(num) {
377
- return Math.floor(num);
378
- }
379
-
380
- /* eslint-disable @typescript-eslint/no-explicit-any */
381
- // Copyright (c) 2018-2023 Coinbase, Inc. <https://www.coinbase.com/>
382
- const INT_STRING_REGEX = /^[0-9]*$/;
383
- const HEXADECIMAL_STRING_REGEX = /^[a-f0-9]*$/;
384
- /**
385
- * @param length number of bytes
386
- */
387
- function randomBytesHex(length) {
388
- return uint8ArrayToHex(crypto.getRandomValues(new Uint8Array(length)));
389
- }
390
- function uint8ArrayToHex(value) {
391
- return [...value].map((b) => b.toString(16).padStart(2, '0')).join('');
392
- }
393
- function hexStringToUint8Array(hexString) {
394
- return new Uint8Array(hexString.match(/.{1,2}/g).map((byte) => Number.parseInt(byte, 16)));
395
- }
396
- function hexStringFromBuffer(buf, includePrefix = false) {
397
- const hex = buf.toString('hex');
398
- return HexString(includePrefix ? `0x${hex}` : hex);
399
- }
400
- function encodeToHexString(str) {
401
- return hexStringFromBuffer(ensureBuffer(str), true);
402
- }
403
- function bigIntStringFromBigInt(bi) {
404
- return BigIntString(bi.toString(10));
405
- }
406
- function hexStringFromNumber(num) {
407
- return HexString(`0x${BigInt(num).toString(16)}`);
408
- }
409
- function has0xPrefix(str) {
410
- return str.startsWith('0x') || str.startsWith('0X');
411
- }
412
- function strip0x(hex) {
413
- if (has0xPrefix(hex)) {
414
- return hex.slice(2);
415
- }
416
- return hex;
417
- }
418
- function prepend0x(hex) {
419
- if (has0xPrefix(hex)) {
420
- return `0x${hex.slice(2)}`;
421
- }
422
- return `0x${hex}`;
423
- }
424
- function isHexString$1(hex) {
425
- if (typeof hex !== 'string') {
426
- return false;
427
- }
428
- const s = strip0x(hex).toLowerCase();
429
- return HEXADECIMAL_STRING_REGEX.test(s);
430
- }
431
- function ensureHexString(hex, includePrefix = false) {
432
- if (typeof hex === 'string') {
433
- const s = strip0x(hex).toLowerCase();
434
- if (HEXADECIMAL_STRING_REGEX.test(s)) {
435
- return HexString(includePrefix ? `0x${s}` : s);
436
- }
437
- }
438
- throw standardErrors.rpc.invalidParams(`"${String(hex)}" is not a hexadecimal string`);
439
- }
440
- function ensureEvenLengthHexString(hex, includePrefix = false) {
441
- let h = ensureHexString(hex, false);
442
- if (h.length % 2 === 1) {
443
- h = HexString(`0${h}`);
444
- }
445
- return includePrefix ? HexString(`0x${h}`) : h;
446
- }
447
- function ensureAddressString(str) {
448
- if (typeof str === 'string') {
449
- const s = strip0x(str).toLowerCase();
450
- if (isHexString$1(s) && s.length === 40) {
451
- return AddressString(prepend0x(s));
452
- }
453
- }
454
- throw standardErrors.rpc.invalidParams(`Invalid Ethereum address: ${String(str)}`);
455
- }
456
- function ensureBuffer(str) {
457
- if (Buffer.isBuffer(str)) {
458
- return str;
459
- }
460
- if (typeof str === 'string') {
461
- if (isHexString$1(str)) {
462
- const s = ensureEvenLengthHexString(str, false);
463
- return Buffer.from(s, 'hex');
464
- }
465
- return Buffer.from(str, 'utf8');
466
- }
467
- throw standardErrors.rpc.invalidParams(`Not binary data: ${String(str)}`);
468
- }
469
- function ensureIntNumber(num) {
470
- if (typeof num === 'number' && Number.isInteger(num)) {
471
- return IntNumber(num);
472
- }
473
- if (typeof num === 'string') {
474
- if (INT_STRING_REGEX.test(num)) {
475
- return IntNumber(Number(num));
476
- }
477
- if (isHexString$1(num)) {
478
- return IntNumber(Number(BigInt(ensureEvenLengthHexString(num, true))));
479
- }
480
- }
481
- throw standardErrors.rpc.invalidParams(`Not an integer: ${String(num)}`);
482
- }
483
- function ensureBigInt(val) {
484
- if (val !== null && (typeof val === 'bigint' || isBigNumber(val))) {
485
- return BigInt(val.toString(10));
486
- }
487
- if (typeof val === 'number') {
488
- return BigInt(ensureIntNumber(val));
489
- }
490
- if (typeof val === 'string') {
491
- if (INT_STRING_REGEX.test(val)) {
492
- return BigInt(val);
493
- }
494
- if (isHexString$1(val)) {
495
- return BigInt(ensureEvenLengthHexString(val, true));
496
- }
497
- }
498
- throw standardErrors.rpc.invalidParams(`Not an integer: ${String(val)}`);
499
- }
500
- function ensureParsedJSONObject(val) {
501
- if (typeof val === 'string') {
502
- return JSON.parse(val);
503
- }
504
- if (typeof val === 'object') {
505
- return val;
506
- }
507
- throw standardErrors.rpc.invalidParams(`Not a JSON string or an object: ${String(val)}`);
508
- }
509
- function isBigNumber(val) {
510
- if (val == null || typeof val.constructor !== 'function') {
511
- return false;
512
- }
513
- const { constructor } = val;
514
- return typeof constructor.config === 'function' && typeof constructor.EUCLID === 'number';
515
- }
516
-
517
- async function generateKeyPair() {
518
- return crypto.subtle.generateKey({
519
- name: 'ECDH',
520
- namedCurve: 'P-256',
521
- }, true, ['deriveKey']);
522
- }
523
- async function deriveSharedSecret(ownPrivateKey, peerPublicKey) {
524
- return crypto.subtle.deriveKey({
525
- name: 'ECDH',
526
- public: peerPublicKey,
527
- }, ownPrivateKey, {
528
- name: 'AES-GCM',
529
- length: 256,
530
- }, false, ['encrypt', 'decrypt']);
531
- }
532
- async function encrypt(sharedSecret, plainText) {
533
- const iv = crypto.getRandomValues(new Uint8Array(12));
534
- const cipherText = await crypto.subtle.encrypt({
535
- name: 'AES-GCM',
536
- iv,
537
- }, sharedSecret, new TextEncoder().encode(plainText));
538
- return { iv, cipherText };
539
- }
540
- async function decrypt(sharedSecret, { iv, cipherText }) {
541
- const plainText = await crypto.subtle.decrypt({
542
- name: 'AES-GCM',
543
- iv,
544
- }, sharedSecret, cipherText);
545
- return new TextDecoder().decode(plainText);
546
- }
547
- function getFormat(keyType) {
548
- switch (keyType) {
549
- case 'public':
550
- return 'spki';
551
- case 'private':
552
- return 'pkcs8';
553
- }
554
- }
555
- async function exportKeyToHexString(type, key) {
556
- const format = getFormat(type);
557
- const exported = await crypto.subtle.exportKey(format, key);
558
- return uint8ArrayToHex(new Uint8Array(exported));
559
- }
560
- async function importKeyFromHexString(type, hexString) {
561
- const format = getFormat(type);
562
- const arrayBuffer = hexStringToUint8Array(hexString).buffer;
563
- return await crypto.subtle.importKey(format, new Uint8Array(arrayBuffer), {
564
- name: 'ECDH',
565
- namedCurve: 'P-256',
566
- }, true, type === 'private' ? ['deriveKey'] : []);
567
- }
568
- async function encryptContent(content, sharedSecret) {
569
- const serialized = JSON.stringify(content, (_, value) => {
570
- if (!(value instanceof Error))
571
- return value;
572
- const error = value;
573
- return Object.assign(Object.assign({}, (error.code ? { code: error.code } : {})), { message: error.message });
574
- });
575
- return encrypt(sharedSecret, serialized);
576
- }
577
- async function decryptContent(encryptedData, sharedSecret) {
578
- return JSON.parse(await decrypt(sharedSecret, encryptedData));
579
- }
580
-
581
- const OWN_PRIVATE_KEY = {
582
- storageKey: 'ownPrivateKey',
583
- keyType: 'private',
584
- };
585
- const OWN_PUBLIC_KEY = {
586
- storageKey: 'ownPublicKey',
587
- keyType: 'public',
588
- };
589
- const PEER_PUBLIC_KEY = {
590
- storageKey: 'peerPublicKey',
591
- keyType: 'public',
592
- };
593
- class SCWKeyManager {
594
- constructor() {
595
- this.storage = new ScopedLocalStorage('CBWSDK', 'SCWKeyManager');
596
- this.ownPrivateKey = null;
597
- this.ownPublicKey = null;
598
- this.peerPublicKey = null;
599
- this.sharedSecret = null;
600
- }
601
- async getOwnPublicKey() {
602
- await this.loadKeysIfNeeded();
603
- return this.ownPublicKey;
604
- }
605
- // returns null if the shared secret is not yet derived
606
- async getSharedSecret() {
607
- await this.loadKeysIfNeeded();
608
- return this.sharedSecret;
609
- }
610
- async setPeerPublicKey(key) {
611
- this.sharedSecret = null;
612
- this.peerPublicKey = key;
613
- await this.storeKey(PEER_PUBLIC_KEY, key);
614
- await this.loadKeysIfNeeded();
615
- }
616
- async clear() {
617
- this.ownPrivateKey = null;
618
- this.ownPublicKey = null;
619
- this.peerPublicKey = null;
620
- this.sharedSecret = null;
621
- this.storage.removeItem(OWN_PUBLIC_KEY.storageKey);
622
- this.storage.removeItem(OWN_PRIVATE_KEY.storageKey);
623
- this.storage.removeItem(PEER_PUBLIC_KEY.storageKey);
624
- }
625
- async generateKeyPair() {
626
- const newKeyPair = await generateKeyPair();
627
- this.ownPrivateKey = newKeyPair.privateKey;
628
- this.ownPublicKey = newKeyPair.publicKey;
629
- await this.storeKey(OWN_PRIVATE_KEY, newKeyPair.privateKey);
630
- await this.storeKey(OWN_PUBLIC_KEY, newKeyPair.publicKey);
631
- }
632
- async loadKeysIfNeeded() {
633
- if (this.ownPrivateKey === null) {
634
- this.ownPrivateKey = await this.loadKey(OWN_PRIVATE_KEY);
635
- }
636
- if (this.ownPublicKey === null) {
637
- this.ownPublicKey = await this.loadKey(OWN_PUBLIC_KEY);
638
- }
639
- if (this.ownPrivateKey === null || this.ownPublicKey === null) {
640
- await this.generateKeyPair();
641
- }
642
- if (this.peerPublicKey === null) {
643
- this.peerPublicKey = await this.loadKey(PEER_PUBLIC_KEY);
644
- }
645
- if (this.sharedSecret === null) {
646
- if (this.ownPrivateKey === null || this.peerPublicKey === null)
647
- return;
648
- this.sharedSecret = await deriveSharedSecret(this.ownPrivateKey, this.peerPublicKey);
649
- }
650
- }
651
- // storage methods
652
- async loadKey(item) {
653
- const key = this.storage.getItem(item.storageKey);
654
- if (!key)
655
- return null;
656
- return importKeyFromHexString(item.keyType, key);
657
- }
658
- async storeKey(item, key) {
659
- const hexString = await exportKeyToHexString(item.keyType, key);
660
- this.storage.setItem(item.storageKey, hexString);
661
- }
662
- }
663
-
664
- const VERSION = '4.2.3';
665
- const NAME = '@coinbase/wallet-sdk';
666
-
667
- async function fetchRPCRequest(request, rpcUrl) {
668
- const requestBody = Object.assign(Object.assign({}, request), { jsonrpc: '2.0', id: crypto.randomUUID() });
669
- const res = await window.fetch(rpcUrl, {
670
- method: 'POST',
671
- body: JSON.stringify(requestBody),
672
- mode: 'cors',
673
- headers: {
674
- 'Content-Type': 'application/json',
675
- 'X-Cbw-Sdk-Version': VERSION,
676
- 'X-Cbw-Sdk-Platform': NAME,
677
- },
678
- });
679
- const { result, error } = await res.json();
680
- if (error)
681
- throw error;
682
- return result;
683
- }
684
- function getCoinbaseInjectedLegacyProvider() {
685
- const window = globalThis;
686
- return window.coinbaseWalletExtension;
687
- }
688
- function getInjectedEthereum() {
689
- var _a, _b;
690
- try {
691
- const window = globalThis;
692
- return (_a = window.ethereum) !== null && _a !== void 0 ? _a : (_b = window.top) === null || _b === void 0 ? void 0 : _b.ethereum;
693
- }
694
- catch (_c) {
695
- return undefined;
696
- }
697
- }
698
- function getCoinbaseInjectedProvider({ metadata, preference, }) {
699
- var _a, _b;
700
- const { appName, appLogoUrl, appChainIds } = metadata;
701
- if (preference.options !== 'smartWalletOnly') {
702
- const extension = getCoinbaseInjectedLegacyProvider();
703
- if (extension) {
704
- (_a = extension.setAppInfo) === null || _a === void 0 ? void 0 : _a.call(extension, appName, appLogoUrl, appChainIds, preference);
705
- return extension;
706
- }
707
- }
708
- const ethereum = getInjectedEthereum();
709
- if (ethereum === null || ethereum === void 0 ? void 0 : ethereum.isCoinbaseBrowser) {
710
- (_b = ethereum.setAppInfo) === null || _b === void 0 ? void 0 : _b.call(ethereum, appName, appLogoUrl, appChainIds, preference);
711
- return ethereum;
712
- }
713
- return undefined;
714
- }
715
- /**
716
- * Validates the arguments for an invalid request and returns an error if any validation fails.
717
- * Valid request args are defined here: https://eips.ethereum.org/EIPS/eip-1193#request
718
- * @param args The request arguments to validate.
719
- * @returns An error object if the arguments are invalid, otherwise undefined.
720
- */
721
- function checkErrorForInvalidRequestArgs(args) {
722
- if (!args || typeof args !== 'object' || Array.isArray(args)) {
723
- throw standardErrors.rpc.invalidParams({
724
- message: 'Expected a single, non-array, object argument.',
725
- data: args,
726
- });
727
- }
728
- const { method, params } = args;
729
- if (typeof method !== 'string' || method.length === 0) {
730
- throw standardErrors.rpc.invalidParams({
731
- message: "'args.method' must be a non-empty string.",
732
- data: args,
733
- });
734
- }
735
- if (params !== undefined &&
736
- !Array.isArray(params) &&
737
- (typeof params !== 'object' || params === null)) {
738
- throw standardErrors.rpc.invalidParams({
739
- message: "'args.params' must be an object or array if provided.",
740
- data: args,
741
- });
742
- }
743
- switch (method) {
744
- case 'eth_sign':
745
- case 'eth_signTypedData_v2':
746
- case 'eth_subscribe':
747
- case 'eth_unsubscribe':
748
- throw standardErrors.provider.unsupportedMethod();
749
- }
750
- }
751
-
752
- const ACCOUNTS_KEY = 'accounts';
753
- const ACTIVE_CHAIN_STORAGE_KEY = 'activeChain';
754
- const AVAILABLE_CHAINS_STORAGE_KEY = 'availableChains';
755
- const WALLET_CAPABILITIES_STORAGE_KEY = 'walletCapabilities';
756
- class SCWSigner {
757
- constructor(params) {
758
- var _a, _b, _c;
759
- this.metadata = params.metadata;
760
- this.communicator = params.communicator;
761
- this.callback = params.callback;
762
- this.keyManager = new SCWKeyManager();
763
- this.storage = new ScopedLocalStorage('CBWSDK', 'SCWStateManager');
764
- this.accounts = (_a = this.storage.loadObject(ACCOUNTS_KEY)) !== null && _a !== void 0 ? _a : [];
765
- this.chain = this.storage.loadObject(ACTIVE_CHAIN_STORAGE_KEY) || {
766
- id: (_c = (_b = params.metadata.appChainIds) === null || _b === void 0 ? void 0 : _b[0]) !== null && _c !== void 0 ? _c : 1,
767
- };
768
- this.handshake = this.handshake.bind(this);
769
- this.request = this.request.bind(this);
770
- this.createRequestMessage = this.createRequestMessage.bind(this);
771
- this.decryptResponseMessage = this.decryptResponseMessage.bind(this);
772
- }
773
- async handshake(args) {
774
- var _a, _b;
775
- const handshakeMessage = await this.createRequestMessage({
776
- handshake: {
777
- method: args.method,
778
- params: Object.assign({}, this.metadata, (_a = args.params) !== null && _a !== void 0 ? _a : {}),
779
- },
780
- });
781
- const response = await this.communicator.postRequestAndWaitForResponse(handshakeMessage);
782
- // store peer's public key
783
- if ('failure' in response.content)
784
- throw response.content.failure;
785
- const peerPublicKey = await importKeyFromHexString('public', response.sender);
786
- await this.keyManager.setPeerPublicKey(peerPublicKey);
787
- const decrypted = await this.decryptResponseMessage(response);
788
- const result = decrypted.result;
789
- if ('error' in result)
790
- throw result.error;
791
- const accounts = result.value;
792
- this.accounts = accounts;
793
- this.storage.storeObject(ACCOUNTS_KEY, accounts);
794
- (_b = this.callback) === null || _b === void 0 ? void 0 : _b.call(this, 'accountsChanged', accounts);
795
- }
796
- async request(request) {
797
- var _a;
798
- if (this.accounts.length === 0) {
799
- throw standardErrors.provider.unauthorized();
800
- }
801
- switch (request.method) {
802
- case 'eth_requestAccounts':
803
- (_a = this.callback) === null || _a === void 0 ? void 0 : _a.call(this, 'connect', { chainId: hexStringFromNumber(this.chain.id) });
804
- return this.accounts;
805
- case 'eth_accounts':
806
- return this.accounts;
807
- case 'eth_coinbase':
808
- return this.accounts[0];
809
- case 'net_version':
810
- return this.chain.id;
811
- case 'eth_chainId':
812
- return hexStringFromNumber(this.chain.id);
813
- case 'wallet_getCapabilities':
814
- return this.storage.loadObject(WALLET_CAPABILITIES_STORAGE_KEY);
815
- case 'wallet_switchEthereumChain':
816
- return this.handleSwitchChainRequest(request);
817
- case 'eth_ecRecover':
818
- case 'personal_sign':
819
- case 'personal_ecRecover':
820
- case 'eth_signTransaction':
821
- case 'eth_sendTransaction':
822
- case 'eth_signTypedData_v1':
823
- case 'eth_signTypedData_v3':
824
- case 'eth_signTypedData_v4':
825
- case 'eth_signTypedData':
826
- case 'wallet_addEthereumChain':
827
- case 'wallet_watchAsset':
828
- case 'wallet_sendCalls':
829
- case 'wallet_showCallsStatus':
830
- case 'wallet_grantPermissions':
831
- return this.sendRequestToPopup(request);
832
- default:
833
- if (!this.chain.rpcUrl)
834
- throw standardErrors.rpc.internal('No RPC URL set for chain');
835
- return fetchRPCRequest(request, this.chain.rpcUrl);
836
- }
837
- }
838
- async sendRequestToPopup(request) {
839
- var _a, _b;
840
- // Open the popup before constructing the request message.
841
- // This is to ensure that the popup is not blocked by some browsers (i.e. Safari)
842
- await ((_b = (_a = this.communicator).waitForPopupLoaded) === null || _b === void 0 ? void 0 : _b.call(_a));
843
- const response = await this.sendEncryptedRequest(request);
844
- const decrypted = await this.decryptResponseMessage(response);
845
- const result = decrypted.result;
846
- if ('error' in result)
847
- throw result.error;
848
- return result.value;
849
- }
850
- async cleanup() {
851
- var _a, _b;
852
- this.storage.clear();
853
- await this.keyManager.clear();
854
- this.accounts = [];
855
- this.chain = {
856
- id: (_b = (_a = this.metadata.appChainIds) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : 1,
857
- };
858
- }
859
- /**
860
- * @returns `null` if the request was successful.
861
- * https://eips.ethereum.org/EIPS/eip-3326#wallet_switchethereumchain
862
- */
863
- async handleSwitchChainRequest(request) {
864
- var _a;
865
- const params = request.params;
866
- if (!params || !((_a = params[0]) === null || _a === void 0 ? void 0 : _a.chainId)) {
867
- throw standardErrors.rpc.invalidParams();
868
- }
869
- const chainId = ensureIntNumber(params[0].chainId);
870
- const localResult = this.updateChain(chainId);
871
- if (localResult)
872
- return null;
873
- const popupResult = await this.sendRequestToPopup(request);
874
- if (popupResult === null) {
875
- this.updateChain(chainId);
876
- }
877
- return popupResult;
878
- }
879
- async sendEncryptedRequest(request) {
880
- const sharedSecret = await this.keyManager.getSharedSecret();
881
- if (!sharedSecret) {
882
- throw standardErrors.provider.unauthorized('No valid session found, try requestAccounts before other methods');
883
- }
884
- const encrypted = await encryptContent({
885
- action: request,
886
- chainId: this.chain.id,
887
- }, sharedSecret);
888
- const message = await this.createRequestMessage({ encrypted });
889
- return this.communicator.postRequestAndWaitForResponse(message);
890
- }
891
- async createRequestMessage(content) {
892
- const publicKey = await exportKeyToHexString('public', await this.keyManager.getOwnPublicKey());
893
- return {
894
- id: crypto.randomUUID(),
895
- sender: publicKey,
896
- content,
897
- timestamp: new Date(),
898
- };
899
- }
900
- async decryptResponseMessage(message) {
901
- var _a, _b;
902
- const content = message.content;
903
- // throw protocol level error
904
- if ('failure' in content) {
905
- throw content.failure;
906
- }
907
- const sharedSecret = await this.keyManager.getSharedSecret();
908
- if (!sharedSecret) {
909
- throw standardErrors.provider.unauthorized('Invalid session');
910
- }
911
- const response = await decryptContent(content.encrypted, sharedSecret);
912
- const availableChains = (_a = response.data) === null || _a === void 0 ? void 0 : _a.chains;
913
- if (availableChains) {
914
- const chains = Object.entries(availableChains).map(([id, rpcUrl]) => ({
915
- id: Number(id),
916
- rpcUrl,
917
- }));
918
- this.storage.storeObject(AVAILABLE_CHAINS_STORAGE_KEY, chains);
919
- this.updateChain(this.chain.id, chains);
920
- }
921
- const walletCapabilities = (_b = response.data) === null || _b === void 0 ? void 0 : _b.capabilities;
922
- if (walletCapabilities) {
923
- this.storage.storeObject(WALLET_CAPABILITIES_STORAGE_KEY, walletCapabilities);
924
- }
925
- return response;
926
- }
927
- updateChain(chainId, newAvailableChains) {
928
- var _a;
929
- const chains = newAvailableChains !== null && newAvailableChains !== void 0 ? newAvailableChains : this.storage.loadObject(AVAILABLE_CHAINS_STORAGE_KEY);
930
- const chain = chains === null || chains === void 0 ? void 0 : chains.find((chain) => chain.id === chainId);
931
- if (!chain)
932
- return false;
933
- if (chain !== this.chain) {
934
- this.chain = chain;
935
- this.storage.storeObject(ACTIVE_CHAIN_STORAGE_KEY, chain);
936
- (_a = this.callback) === null || _a === void 0 ? void 0 : _a.call(this, 'chainChanged', hexStringFromNumber(chain.id));
937
- }
938
- return true;
939
- }
940
- }
941
-
942
- var sha3 = {};
943
-
944
- var _assert = {};
945
-
946
- Object.defineProperty(_assert, "__esModule", { value: true });
947
- _assert.isBytes = isBytes$1;
948
- _assert.number = number;
949
- _assert.bool = bool;
950
- _assert.bytes = bytes$1;
951
- _assert.hash = hash;
952
- _assert.exists = exists$1;
953
- _assert.output = output$1;
954
- function number(n) {
955
- if (!Number.isSafeInteger(n) || n < 0)
956
- throw new Error(`positive integer expected, not ${n}`);
957
- }
958
- function bool(b) {
959
- if (typeof b !== 'boolean')
960
- throw new Error(`boolean expected, not ${b}`);
961
- }
962
- // copied from utils
963
- function isBytes$1(a) {
964
- return (a instanceof Uint8Array ||
965
- (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
966
- }
967
- function bytes$1(b, ...lengths) {
968
- if (!isBytes$1(b))
969
- throw new Error('Uint8Array expected');
970
- if (lengths.length > 0 && !lengths.includes(b.length))
971
- throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);
972
- }
973
- function hash(h) {
974
- if (typeof h !== 'function' || typeof h.create !== 'function')
975
- throw new Error('Hash should be wrapped by utils.wrapConstructor');
976
- number(h.outputLen);
977
- number(h.blockLen);
978
- }
979
- function exists$1(instance, checkFinished = true) {
980
- if (instance.destroyed)
981
- throw new Error('Hash instance has been destroyed');
982
- if (checkFinished && instance.finished)
983
- throw new Error('Hash#digest() has already been called');
984
- }
985
- function output$1(out, instance) {
986
- bytes$1(out);
987
- const min = instance.outputLen;
988
- if (out.length < min) {
989
- throw new Error(`digestInto() expects output buffer of length at least ${min}`);
990
- }
991
- }
992
- const assert = { number, bool, bytes: bytes$1, hash, exists: exists$1, output: output$1 };
993
- _assert.default = assert;
994
-
995
- var _u64 = {};
996
-
997
- Object.defineProperty(_u64, "__esModule", { value: true });
998
- _u64.add5L = _u64.add5H = _u64.add4H = _u64.add4L = _u64.add3H = _u64.add3L = _u64.rotlBL = _u64.rotlBH = _u64.rotlSL = _u64.rotlSH = _u64.rotr32L = _u64.rotr32H = _u64.rotrBL = _u64.rotrBH = _u64.rotrSL = _u64.rotrSH = _u64.shrSL = _u64.shrSH = _u64.toBig = void 0;
999
- _u64.fromBig = fromBig;
1000
- _u64.split = split;
1001
- _u64.add = add;
1002
- const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
1003
- const _32n = /* @__PURE__ */ BigInt(32);
1004
- // We are not using BigUint64Array, because they are extremely slow as per 2022
1005
- function fromBig(n, le = false) {
1006
- if (le)
1007
- return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
1008
- return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
1009
- }
1010
- function split(lst, le = false) {
1011
- let Ah = new Uint32Array(lst.length);
1012
- let Al = new Uint32Array(lst.length);
1013
- for (let i = 0; i < lst.length; i++) {
1014
- const { h, l } = fromBig(lst[i], le);
1015
- [Ah[i], Al[i]] = [h, l];
1016
- }
1017
- return [Ah, Al];
1018
- }
1019
- const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
1020
- _u64.toBig = toBig;
1021
- // for Shift in [0, 32)
1022
- const shrSH = (h, _l, s) => h >>> s;
1023
- _u64.shrSH = shrSH;
1024
- const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
1025
- _u64.shrSL = shrSL;
1026
- // Right rotate for Shift in [1, 32)
1027
- const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
1028
- _u64.rotrSH = rotrSH;
1029
- const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
1030
- _u64.rotrSL = rotrSL;
1031
- // Right rotate for Shift in (32, 64), NOTE: 32 is special case.
1032
- const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
1033
- _u64.rotrBH = rotrBH;
1034
- const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
1035
- _u64.rotrBL = rotrBL;
1036
- // Right rotate for shift===32 (just swaps l&h)
1037
- const rotr32H = (_h, l) => l;
1038
- _u64.rotr32H = rotr32H;
1039
- const rotr32L = (h, _l) => h;
1040
- _u64.rotr32L = rotr32L;
1041
- // Left rotate for Shift in [1, 32)
1042
- const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
1043
- _u64.rotlSH = rotlSH;
1044
- const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
1045
- _u64.rotlSL = rotlSL;
1046
- // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
1047
- const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
1048
- _u64.rotlBH = rotlBH;
1049
- const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
1050
- _u64.rotlBL = rotlBL;
1051
- // JS uses 32-bit signed integers for bitwise operations which means we cannot
1052
- // simple take carry out of low bit sum by shift, we need to use division.
1053
- function add(Ah, Al, Bh, Bl) {
1054
- const l = (Al >>> 0) + (Bl >>> 0);
1055
- return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
1056
- }
1057
- // Addition with more than 2 elements
1058
- const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
1059
- _u64.add3L = add3L;
1060
- const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
1061
- _u64.add3H = add3H;
1062
- const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
1063
- _u64.add4L = add4L;
1064
- const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
1065
- _u64.add4H = add4H;
1066
- const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
1067
- _u64.add5L = add5L;
1068
- const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
1069
- _u64.add5H = add5H;
1070
- // prettier-ignore
1071
- const u64 = {
1072
- fromBig, split, toBig,
1073
- shrSH, shrSL,
1074
- rotrSH, rotrSL, rotrBH, rotrBL,
1075
- rotr32H, rotr32L,
1076
- rotlSH, rotlSL, rotlBH, rotlBL,
1077
- add, add3L, add3H, add4L, add4H, add5H, add5L,
1078
- };
1079
- _u64.default = u64;
1080
-
1081
- var utils = {};
1082
-
1083
- var crypto$1 = {};
1084
-
1085
- Object.defineProperty(crypto$1, "__esModule", { value: true });
1086
- crypto$1.crypto = void 0;
1087
- crypto$1.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
1088
-
1089
- (function (exports) {
1090
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1091
- Object.defineProperty(exports, "__esModule", { value: true });
1092
- exports.Hash = exports.nextTick = exports.byteSwapIfBE = exports.byteSwap = exports.isLE = exports.rotl = exports.rotr = exports.createView = exports.u32 = exports.u8 = void 0;
1093
- exports.isBytes = isBytes;
1094
- exports.byteSwap32 = byteSwap32;
1095
- exports.bytesToHex = bytesToHex;
1096
- exports.hexToBytes = hexToBytes;
1097
- exports.asyncLoop = asyncLoop;
1098
- exports.utf8ToBytes = utf8ToBytes;
1099
- exports.toBytes = toBytes;
1100
- exports.concatBytes = concatBytes;
1101
- exports.checkOpts = checkOpts;
1102
- exports.wrapConstructor = wrapConstructor;
1103
- exports.wrapConstructorWithOpts = wrapConstructorWithOpts;
1104
- exports.wrapXOFConstructorWithOpts = wrapXOFConstructorWithOpts;
1105
- exports.randomBytes = randomBytes;
1106
- // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
1107
- // node.js versions earlier than v19 don't declare it in global scope.
1108
- // For node.js, package.json#exports field mapping rewrites import
1109
- // from `crypto` to `cryptoNode`, which imports native module.
1110
- // Makes the utils un-importable in browsers without a bundler.
1111
- // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
1112
- const crypto_1 = crypto$1;
1113
- const _assert_js_1 = _assert;
1114
- // export { isBytes } from './_assert.js';
1115
- // We can't reuse isBytes from _assert, because somehow this causes huge perf issues
1116
- function isBytes(a) {
1117
- return (a instanceof Uint8Array ||
1118
- (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
1119
- }
1120
- // Cast array to different type
1121
- const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
1122
- exports.u8 = u8;
1123
- const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
1124
- exports.u32 = u32;
1125
- // Cast array to view
1126
- const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
1127
- exports.createView = createView;
1128
- // The rotate right (circular right shift) operation for uint32
1129
- const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
1130
- exports.rotr = rotr;
1131
- // The rotate left (circular left shift) operation for uint32
1132
- const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0);
1133
- exports.rotl = rotl;
1134
- exports.isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
1135
- // The byte swap operation for uint32
1136
- const byteSwap = (word) => ((word << 24) & 0xff000000) |
1137
- ((word << 8) & 0xff0000) |
1138
- ((word >>> 8) & 0xff00) |
1139
- ((word >>> 24) & 0xff);
1140
- exports.byteSwap = byteSwap;
1141
- // Conditionally byte swap if on a big-endian platform
1142
- exports.byteSwapIfBE = exports.isLE ? (n) => n : (n) => (0, exports.byteSwap)(n);
1143
- // In place byte swap for Uint32Array
1144
- function byteSwap32(arr) {
1145
- for (let i = 0; i < arr.length; i++) {
1146
- arr[i] = (0, exports.byteSwap)(arr[i]);
1147
- }
1148
- }
1149
- // Array where index 0xf0 (240) is mapped to string 'f0'
1150
- const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
1151
- /**
1152
- * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
1153
- */
1154
- function bytesToHex(bytes) {
1155
- (0, _assert_js_1.bytes)(bytes);
1156
- // pre-caching improves the speed 6x
1157
- let hex = '';
1158
- for (let i = 0; i < bytes.length; i++) {
1159
- hex += hexes[bytes[i]];
1160
- }
1161
- return hex;
1162
- }
1163
- // We use optimized technique to convert hex string to byte array
1164
- const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
1165
- function asciiToBase16(char) {
1166
- if (char >= asciis._0 && char <= asciis._9)
1167
- return char - asciis._0;
1168
- if (char >= asciis._A && char <= asciis._F)
1169
- return char - (asciis._A - 10);
1170
- if (char >= asciis._a && char <= asciis._f)
1171
- return char - (asciis._a - 10);
1172
- return;
1173
- }
1174
- /**
1175
- * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
1176
- */
1177
- function hexToBytes(hex) {
1178
- if (typeof hex !== 'string')
1179
- throw new Error('hex string expected, got ' + typeof hex);
1180
- const hl = hex.length;
1181
- const al = hl / 2;
1182
- if (hl % 2)
1183
- throw new Error('padded hex string expected, got unpadded hex of length ' + hl);
1184
- const array = new Uint8Array(al);
1185
- for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
1186
- const n1 = asciiToBase16(hex.charCodeAt(hi));
1187
- const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
1188
- if (n1 === undefined || n2 === undefined) {
1189
- const char = hex[hi] + hex[hi + 1];
1190
- throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
1191
- }
1192
- array[ai] = n1 * 16 + n2;
1193
- }
1194
- return array;
1195
- }
1196
- // There is no setImmediate in browser and setTimeout is slow.
1197
- // call of async fn will return Promise, which will be fullfiled only on
1198
- // next scheduler queue processing step and this is exactly what we need.
1199
- const nextTick = async () => { };
1200
- exports.nextTick = nextTick;
1201
- // Returns control to thread each 'tick' ms to avoid blocking
1202
- async function asyncLoop(iters, tick, cb) {
1203
- let ts = Date.now();
1204
- for (let i = 0; i < iters; i++) {
1205
- cb(i);
1206
- // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
1207
- const diff = Date.now() - ts;
1208
- if (diff >= 0 && diff < tick)
1209
- continue;
1210
- await (0, exports.nextTick)();
1211
- ts += diff;
1212
- }
1213
- }
1214
- /**
1215
- * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
1216
- */
1217
- function utf8ToBytes(str) {
1218
- if (typeof str !== 'string')
1219
- throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
1220
- return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
1221
- }
1222
- /**
1223
- * Normalizes (non-hex) string or Uint8Array to Uint8Array.
1224
- * Warning: when Uint8Array is passed, it would NOT get copied.
1225
- * Keep in mind for future mutable operations.
1226
- */
1227
- function toBytes(data) {
1228
- if (typeof data === 'string')
1229
- data = utf8ToBytes(data);
1230
- (0, _assert_js_1.bytes)(data);
1231
- return data;
1232
- }
1233
- /**
1234
- * Copies several Uint8Arrays into one.
1235
- */
1236
- function concatBytes(...arrays) {
1237
- let sum = 0;
1238
- for (let i = 0; i < arrays.length; i++) {
1239
- const a = arrays[i];
1240
- (0, _assert_js_1.bytes)(a);
1241
- sum += a.length;
1242
- }
1243
- const res = new Uint8Array(sum);
1244
- for (let i = 0, pad = 0; i < arrays.length; i++) {
1245
- const a = arrays[i];
1246
- res.set(a, pad);
1247
- pad += a.length;
1248
- }
1249
- return res;
1250
- }
1251
- // For runtime check if class implements interface
1252
- class Hash {
1253
- // Safe version that clones internal state
1254
- clone() {
1255
- return this._cloneInto();
1256
- }
1257
- }
1258
- exports.Hash = Hash;
1259
- const toStr = {}.toString;
1260
- function checkOpts(defaults, opts) {
1261
- if (opts !== undefined && toStr.call(opts) !== '[object Object]')
1262
- throw new Error('Options should be object or undefined');
1263
- const merged = Object.assign(defaults, opts);
1264
- return merged;
1265
- }
1266
- function wrapConstructor(hashCons) {
1267
- const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
1268
- const tmp = hashCons();
1269
- hashC.outputLen = tmp.outputLen;
1270
- hashC.blockLen = tmp.blockLen;
1271
- hashC.create = () => hashCons();
1272
- return hashC;
1273
- }
1274
- function wrapConstructorWithOpts(hashCons) {
1275
- const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
1276
- const tmp = hashCons({});
1277
- hashC.outputLen = tmp.outputLen;
1278
- hashC.blockLen = tmp.blockLen;
1279
- hashC.create = (opts) => hashCons(opts);
1280
- return hashC;
1281
- }
1282
- function wrapXOFConstructorWithOpts(hashCons) {
1283
- const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
1284
- const tmp = hashCons({});
1285
- hashC.outputLen = tmp.outputLen;
1286
- hashC.blockLen = tmp.blockLen;
1287
- hashC.create = (opts) => hashCons(opts);
1288
- return hashC;
1289
- }
1290
- /**
1291
- * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
1292
- */
1293
- function randomBytes(bytesLength = 32) {
1294
- if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') {
1295
- return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
1296
- }
1297
- // Legacy Node.js compatibility
1298
- if (crypto_1.crypto && typeof crypto_1.crypto.randomBytes === 'function') {
1299
- return crypto_1.crypto.randomBytes(bytesLength);
1300
- }
1301
- throw new Error('crypto.getRandomValues must be defined');
1302
- }
1303
-
1304
- } (utils));
1305
-
1306
- Object.defineProperty(sha3, "__esModule", { value: true });
1307
- sha3.shake256 = sha3.shake128 = sha3.keccak_512 = sha3.keccak_384 = sha3.keccak_256 = sha3.keccak_224 = sha3.sha3_512 = sha3.sha3_384 = sha3.sha3_256 = sha3.sha3_224 = sha3.Keccak = void 0;
1308
- sha3.keccakP = keccakP;
1309
- const _assert_js_1 = _assert;
1310
- const _u64_js_1 = _u64;
1311
- const utils_js_1 = utils;
1312
- // SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.
1313
- // It's called a sponge function.
1314
- // Various per round constants calculations
1315
- const SHA3_PI = [];
1316
- const SHA3_ROTL = [];
1317
- const _SHA3_IOTA = [];
1318
- const _0n = /* @__PURE__ */ BigInt(0);
1319
- const _1n = /* @__PURE__ */ BigInt(1);
1320
- const _2n = /* @__PURE__ */ BigInt(2);
1321
- const _7n = /* @__PURE__ */ BigInt(7);
1322
- const _256n = /* @__PURE__ */ BigInt(256);
1323
- const _0x71n = /* @__PURE__ */ BigInt(0x71);
1324
- for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
1325
- // Pi
1326
- [x, y] = [y, (2 * x + 3 * y) % 5];
1327
- SHA3_PI.push(2 * (5 * y + x));
1328
- // Rotational
1329
- SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);
1330
- // Iota
1331
- let t = _0n;
1332
- for (let j = 0; j < 7; j++) {
1333
- R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;
1334
- if (R & _2n)
1335
- t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);
1336
- }
1337
- _SHA3_IOTA.push(t);
1338
- }
1339
- const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ (0, _u64_js_1.split)(_SHA3_IOTA, true);
1340
- // Left rotation (without 0, 32, 64)
1341
- const rotlH = (h, l, s) => (s > 32 ? (0, _u64_js_1.rotlBH)(h, l, s) : (0, _u64_js_1.rotlSH)(h, l, s));
1342
- const rotlL = (h, l, s) => (s > 32 ? (0, _u64_js_1.rotlBL)(h, l, s) : (0, _u64_js_1.rotlSL)(h, l, s));
1343
- // Same as keccakf1600, but allows to skip some rounds
1344
- function keccakP(s, rounds = 24) {
1345
- const B = new Uint32Array(5 * 2);
1346
- // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
1347
- for (let round = 24 - rounds; round < 24; round++) {
1348
- // Theta θ
1349
- for (let x = 0; x < 10; x++)
1350
- B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
1351
- for (let x = 0; x < 10; x += 2) {
1352
- const idx1 = (x + 8) % 10;
1353
- const idx0 = (x + 2) % 10;
1354
- const B0 = B[idx0];
1355
- const B1 = B[idx0 + 1];
1356
- const Th = rotlH(B0, B1, 1) ^ B[idx1];
1357
- const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
1358
- for (let y = 0; y < 50; y += 10) {
1359
- s[x + y] ^= Th;
1360
- s[x + y + 1] ^= Tl;
1361
- }
1362
- }
1363
- // Rho (ρ) and Pi (π)
1364
- let curH = s[2];
1365
- let curL = s[3];
1366
- for (let t = 0; t < 24; t++) {
1367
- const shift = SHA3_ROTL[t];
1368
- const Th = rotlH(curH, curL, shift);
1369
- const Tl = rotlL(curH, curL, shift);
1370
- const PI = SHA3_PI[t];
1371
- curH = s[PI];
1372
- curL = s[PI + 1];
1373
- s[PI] = Th;
1374
- s[PI + 1] = Tl;
1375
- }
1376
- // Chi (χ)
1377
- for (let y = 0; y < 50; y += 10) {
1378
- for (let x = 0; x < 10; x++)
1379
- B[x] = s[y + x];
1380
- for (let x = 0; x < 10; x++)
1381
- s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
1382
- }
1383
- // Iota (ι)
1384
- s[0] ^= SHA3_IOTA_H[round];
1385
- s[1] ^= SHA3_IOTA_L[round];
1386
- }
1387
- B.fill(0);
1388
- }
1389
- class Keccak extends utils_js_1.Hash {
1390
- // NOTE: we accept arguments in bytes instead of bits here.
1391
- constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
1392
- super();
1393
- this.blockLen = blockLen;
1394
- this.suffix = suffix;
1395
- this.outputLen = outputLen;
1396
- this.enableXOF = enableXOF;
1397
- this.rounds = rounds;
1398
- this.pos = 0;
1399
- this.posOut = 0;
1400
- this.finished = false;
1401
- this.destroyed = false;
1402
- // Can be passed from user as dkLen
1403
- (0, _assert_js_1.number)(outputLen);
1404
- // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
1405
- if (0 >= this.blockLen || this.blockLen >= 200)
1406
- throw new Error('Sha3 supports only keccak-f1600 function');
1407
- this.state = new Uint8Array(200);
1408
- this.state32 = (0, utils_js_1.u32)(this.state);
1409
- }
1410
- keccak() {
1411
- if (!utils_js_1.isLE)
1412
- (0, utils_js_1.byteSwap32)(this.state32);
1413
- keccakP(this.state32, this.rounds);
1414
- if (!utils_js_1.isLE)
1415
- (0, utils_js_1.byteSwap32)(this.state32);
1416
- this.posOut = 0;
1417
- this.pos = 0;
1418
- }
1419
- update(data) {
1420
- (0, _assert_js_1.exists)(this);
1421
- const { blockLen, state } = this;
1422
- data = (0, utils_js_1.toBytes)(data);
1423
- const len = data.length;
1424
- for (let pos = 0; pos < len;) {
1425
- const take = Math.min(blockLen - this.pos, len - pos);
1426
- for (let i = 0; i < take; i++)
1427
- state[this.pos++] ^= data[pos++];
1428
- if (this.pos === blockLen)
1429
- this.keccak();
1430
- }
1431
- return this;
1432
- }
1433
- finish() {
1434
- if (this.finished)
1435
- return;
1436
- this.finished = true;
1437
- const { state, suffix, pos, blockLen } = this;
1438
- // Do the padding
1439
- state[pos] ^= suffix;
1440
- if ((suffix & 0x80) !== 0 && pos === blockLen - 1)
1441
- this.keccak();
1442
- state[blockLen - 1] ^= 0x80;
1443
- this.keccak();
1444
- }
1445
- writeInto(out) {
1446
- (0, _assert_js_1.exists)(this, false);
1447
- (0, _assert_js_1.bytes)(out);
1448
- this.finish();
1449
- const bufferOut = this.state;
1450
- const { blockLen } = this;
1451
- for (let pos = 0, len = out.length; pos < len;) {
1452
- if (this.posOut >= blockLen)
1453
- this.keccak();
1454
- const take = Math.min(blockLen - this.posOut, len - pos);
1455
- out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
1456
- this.posOut += take;
1457
- pos += take;
1458
- }
1459
- return out;
1460
- }
1461
- xofInto(out) {
1462
- // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF
1463
- if (!this.enableXOF)
1464
- throw new Error('XOF is not possible for this instance');
1465
- return this.writeInto(out);
1466
- }
1467
- xof(bytes) {
1468
- (0, _assert_js_1.number)(bytes);
1469
- return this.xofInto(new Uint8Array(bytes));
1470
- }
1471
- digestInto(out) {
1472
- (0, _assert_js_1.output)(out, this);
1473
- if (this.finished)
1474
- throw new Error('digest() was already called');
1475
- this.writeInto(out);
1476
- this.destroy();
1477
- return out;
1478
- }
1479
- digest() {
1480
- return this.digestInto(new Uint8Array(this.outputLen));
1481
- }
1482
- destroy() {
1483
- this.destroyed = true;
1484
- this.state.fill(0);
1485
- }
1486
- _cloneInto(to) {
1487
- const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
1488
- to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
1489
- to.state32.set(this.state32);
1490
- to.pos = this.pos;
1491
- to.posOut = this.posOut;
1492
- to.finished = this.finished;
1493
- to.rounds = rounds;
1494
- // Suffix can change in cSHAKE
1495
- to.suffix = suffix;
1496
- to.outputLen = outputLen;
1497
- to.enableXOF = enableXOF;
1498
- to.destroyed = this.destroyed;
1499
- return to;
1500
- }
1501
- }
1502
- sha3.Keccak = Keccak;
1503
- const gen = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapConstructor)(() => new Keccak(blockLen, suffix, outputLen));
1504
- sha3.sha3_224 = gen(0x06, 144, 224 / 8);
1505
- /**
1506
- * SHA3-256 hash function
1507
- * @param message - that would be hashed
1508
- */
1509
- sha3.sha3_256 = gen(0x06, 136, 256 / 8);
1510
- sha3.sha3_384 = gen(0x06, 104, 384 / 8);
1511
- sha3.sha3_512 = gen(0x06, 72, 512 / 8);
1512
- sha3.keccak_224 = gen(0x01, 144, 224 / 8);
1513
- /**
1514
- * keccak-256 hash function. Different from SHA3-256.
1515
- * @param message - that would be hashed
1516
- */
1517
- sha3.keccak_256 = gen(0x01, 136, 256 / 8);
1518
- sha3.keccak_384 = gen(0x01, 104, 384 / 8);
1519
- sha3.keccak_512 = gen(0x01, 72, 512 / 8);
1520
- const genShake = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapXOFConstructorWithOpts)((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));
1521
- sha3.shake128 = genShake(0x1f, 168, 128 / 8);
1522
- sha3.shake256 = genShake(0x1f, 136, 256 / 8);
1523
-
1524
- // Extracted from https://github.com/ethereumjs/ethereumjs-util and stripped out irrelevant code
1525
- // Original code licensed under the Mozilla Public License Version 2.0
1526
-
1527
- /* eslint-disable */
1528
- //prettier-ignore
1529
- const { keccak_256 } = sha3;
1530
-
1531
- /**
1532
- * Returns a buffer filled with 0s
1533
- * @method zeros
1534
- * @param {Number} bytes the number of bytes the buffer should be
1535
- * @return {Buffer}
1536
- */
1537
- function zeros (bytes) {
1538
- return Buffer.allocUnsafe(bytes).fill(0)
1539
- }
1540
-
1541
- function bitLengthFromBigInt (num) {
1542
- return num.toString(2).length
1543
- }
1544
-
1545
- function bufferBEFromBigInt(num, length) {
1546
- let hex = num.toString(16);
1547
- // Ensure the hex string length is even
1548
- if (hex.length % 2 !== 0) hex = '0' + hex;
1549
- // Convert hex string to a byte array
1550
- const byteArray = hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16));
1551
- // Ensure the byte array is of the specified length
1552
- while (byteArray.length < length) {
1553
- byteArray.unshift(0); // Prepend with zeroes if shorter than required length
1554
- }
1555
-
1556
- return Buffer.from(byteArray);
1557
- }
1558
-
1559
- function twosFromBigInt(value, width) {
1560
- const isNegative = value < 0n;
1561
- let result;
1562
- if (isNegative) {
1563
- // Prepare a mask for the specified width to perform NOT operation
1564
- const mask = (1n << BigInt(width)) - 1n;
1565
- // Invert bits (using NOT) and add one
1566
- result = (~value & mask) + 1n;
1567
- } else {
1568
- result = value;
1569
- }
1570
- // Ensure the result fits in the specified width
1571
- result &= (1n << BigInt(width)) - 1n;
1572
-
1573
- return result;
1574
- }
1575
-
1576
- /**
1577
- * Left Pads an `Array` or `Buffer` with leading zeros till it has `length` bytes.
1578
- * Or it truncates the beginning if it exceeds.
1579
- * @method setLength
1580
- * @param {Buffer|Array} msg the value to pad
1581
- * @param {Number} length the number of bytes the output should be
1582
- * @param {Boolean} [right=false] whether to start padding form the left or right
1583
- * @return {Buffer|Array}
1584
- */
1585
- function setLength (msg, length, right) {
1586
- const buf = zeros(length);
1587
- msg = toBuffer(msg);
1588
- if (right) {
1589
- if (msg.length < length) {
1590
- msg.copy(buf);
1591
- return buf
1592
- }
1593
- return msg.slice(0, length)
1594
- } else {
1595
- if (msg.length < length) {
1596
- msg.copy(buf, length - msg.length);
1597
- return buf
1598
- }
1599
- return msg.slice(-length)
1600
- }
1601
- }
1602
-
1603
- /**
1604
- * Right Pads an `Array` or `Buffer` with leading zeros till it has `length` bytes.
1605
- * Or it truncates the beginning if it exceeds.
1606
- * @param {Buffer|Array} msg the value to pad
1607
- * @param {Number} length the number of bytes the output should be
1608
- * @return {Buffer|Array}
1609
- */
1610
- function setLengthRight (msg, length) {
1611
- return setLength(msg, length, true)
1612
- }
1613
-
1614
- /**
1615
- * Attempts to turn a value into a `Buffer`. As input it supports `Buffer`, `String`, `Number`, null/undefined, `BIgInt` and other objects with a `toArray()` method.
1616
- * @param {*} v the value
1617
- */
1618
- function toBuffer (v) {
1619
- if (!Buffer.isBuffer(v)) {
1620
- if (Array.isArray(v)) {
1621
- v = Buffer.from(v);
1622
- } else if (typeof v === 'string') {
1623
- if (isHexString(v)) {
1624
- v = Buffer.from(padToEven(stripHexPrefix(v)), 'hex');
1625
- } else {
1626
- v = Buffer.from(v);
1627
- }
1628
- } else if (typeof v === 'number') {
1629
- v = intToBuffer(v);
1630
- } else if (v === null || v === undefined) {
1631
- v = Buffer.allocUnsafe(0);
1632
- } else if (typeof v === 'bigint') {
1633
- v = bufferBEFromBigInt(v);
1634
- } else if (v.toArray) {
1635
- // TODO: bigint should be handled above, may remove this duplicate
1636
- // converts a BigInt to a Buffer
1637
- v = Buffer.from(v.toArray());
1638
- } else {
1639
- throw new Error('invalid type')
1640
- }
1641
- }
1642
- return v
1643
- }
1644
-
1645
- /**
1646
- * Converts a `Buffer` into a hex `String`
1647
- * @param {Buffer} buf
1648
- * @return {String}
1649
- */
1650
- function bufferToHex (buf) {
1651
- buf = toBuffer(buf);
1652
- return '0x' + buf.toString('hex')
1653
- }
1654
-
1655
- /**
1656
- * Creates Keccak hash of the input
1657
- * @param {Buffer|Array|String|Number} a the input data
1658
- * @param {Number} [bits=256] the Keccak width
1659
- * @return {Buffer}
1660
- */
1661
- function keccak (a, bits) {
1662
- a = toBuffer(a);
1663
- if (!bits) bits = 256;
1664
- if (bits !== 256) {
1665
- throw new Error('unsupported')
1666
- }
1667
- return Buffer.from(keccak_256(new Uint8Array(a)))
1668
- }
1669
-
1670
- function padToEven (str) {
1671
- return str.length % 2 ? '0' + str : str
1672
- }
1673
-
1674
- function isHexString (str) {
1675
- return typeof str === 'string' && str.match(/^0x[0-9A-Fa-f]*$/)
1676
- }
1677
-
1678
- function stripHexPrefix (str) {
1679
- if (typeof str === 'string' && str.startsWith('0x')) {
1680
- return str.slice(2)
1681
- }
1682
- return str
1683
- }
1684
-
1685
- var util$2 = {
1686
- zeros,
1687
- setLength,
1688
- setLengthRight,
1689
- isHexString,
1690
- stripHexPrefix,
1691
- toBuffer,
1692
- bufferToHex,
1693
- keccak,
1694
- bitLengthFromBigInt,
1695
- bufferBEFromBigInt,
1696
- twosFromBigInt
1697
- };
1698
-
1699
- // Extracted from https://github.com/ethereumjs/ethereumjs-abi and stripped out irrelevant code
1700
- // Original code licensed under the MIT License - Copyright (c) 2015 Alex Beregszaszi
1701
-
1702
- /* eslint-disable */
1703
- //prettier-ignore
1704
- const util$1 = util$2;
1705
-
1706
- // Convert from short to canonical names
1707
- // FIXME: optimise or make this nicer?
1708
- function elementaryName (name) {
1709
- if (name.startsWith('int[')) {
1710
- return 'int256' + name.slice(3)
1711
- } else if (name === 'int') {
1712
- return 'int256'
1713
- } else if (name.startsWith('uint[')) {
1714
- return 'uint256' + name.slice(4)
1715
- } else if (name === 'uint') {
1716
- return 'uint256'
1717
- } else if (name.startsWith('fixed[')) {
1718
- return 'fixed128x128' + name.slice(5)
1719
- } else if (name === 'fixed') {
1720
- return 'fixed128x128'
1721
- } else if (name.startsWith('ufixed[')) {
1722
- return 'ufixed128x128' + name.slice(6)
1723
- } else if (name === 'ufixed') {
1724
- return 'ufixed128x128'
1725
- }
1726
- return name
1727
- }
1728
-
1729
- // Parse N from type<N>
1730
- function parseTypeN (type) {
1731
- return Number.parseInt(/^\D+(\d+)$/.exec(type)[1], 10)
1732
- }
1733
-
1734
- // Parse N,M from type<N>x<M>
1735
- function parseTypeNxM (type) {
1736
- var tmp = /^\D+(\d+)x(\d+)$/.exec(type);
1737
- return [ Number.parseInt(tmp[1], 10), Number.parseInt(tmp[2], 10) ]
1738
- }
1739
-
1740
- // Parse N in type[<N>] where "type" can itself be an array type.
1741
- function parseTypeArray (type) {
1742
- var tmp = type.match(/(.*)\[(.*?)\]$/);
1743
- if (tmp) {
1744
- return tmp[2] === '' ? 'dynamic' : Number.parseInt(tmp[2], 10)
1745
- }
1746
- return null
1747
- }
1748
-
1749
- function parseNumber (arg) {
1750
- var type = typeof arg;
1751
- if (type === 'string' || type === 'number') {
1752
- return BigInt(arg)
1753
- } else if (type === 'bigint') {
1754
- return arg
1755
- } else {
1756
- throw new Error('Argument is not a number')
1757
- }
1758
- }
1759
-
1760
- // Encodes a single item (can be dynamic array)
1761
- // @returns: Buffer
1762
- function encodeSingle (type, arg) {
1763
- var size, num, ret, i;
1764
-
1765
- if (type === 'address') {
1766
- return encodeSingle('uint160', parseNumber(arg))
1767
- } else if (type === 'bool') {
1768
- return encodeSingle('uint8', arg ? 1 : 0)
1769
- } else if (type === 'string') {
1770
- return encodeSingle('bytes', new Buffer(arg, 'utf8'))
1771
- } else if (isArray(type)) {
1772
- // this part handles fixed-length ([2]) and variable length ([]) arrays
1773
- // NOTE: we catch here all calls to arrays, that simplifies the rest
1774
- if (typeof arg.length === 'undefined') {
1775
- throw new Error('Not an array?')
1776
- }
1777
- size = parseTypeArray(type);
1778
- if (size !== 'dynamic' && size !== 0 && arg.length > size) {
1779
- throw new Error('Elements exceed array size: ' + size)
1780
- }
1781
- ret = [];
1782
- type = type.slice(0, type.lastIndexOf('['));
1783
- if (typeof arg === 'string') {
1784
- arg = JSON.parse(arg);
1785
- }
1786
- for (i in arg) {
1787
- ret.push(encodeSingle(type, arg[i]));
1788
- }
1789
- if (size === 'dynamic') {
1790
- var length = encodeSingle('uint256', arg.length);
1791
- ret.unshift(length);
1792
- }
1793
- return Buffer.concat(ret)
1794
- } else if (type === 'bytes') {
1795
- arg = new Buffer(arg);
1796
-
1797
- ret = Buffer.concat([ encodeSingle('uint256', arg.length), arg ]);
1798
-
1799
- if ((arg.length % 32) !== 0) {
1800
- ret = Buffer.concat([ ret, util$1.zeros(32 - (arg.length % 32)) ]);
1801
- }
1802
-
1803
- return ret
1804
- } else if (type.startsWith('bytes')) {
1805
- size = parseTypeN(type);
1806
- if (size < 1 || size > 32) {
1807
- throw new Error('Invalid bytes<N> width: ' + size)
1808
- }
1809
-
1810
- return util$1.setLengthRight(arg, 32)
1811
- } else if (type.startsWith('uint')) {
1812
- size = parseTypeN(type);
1813
- if ((size % 8) || (size < 8) || (size > 256)) {
1814
- throw new Error('Invalid uint<N> width: ' + size)
1815
- }
1816
-
1817
- num = parseNumber(arg);
1818
- const bitLength = util$1.bitLengthFromBigInt(num);
1819
- if (bitLength > size) {
1820
- throw new Error('Supplied uint exceeds width: ' + size + ' vs ' + bitLength)
1821
- }
1822
-
1823
- if (num < 0) {
1824
- throw new Error('Supplied uint is negative')
1825
- }
1826
-
1827
- return util$1.bufferBEFromBigInt(num, 32);
1828
- } else if (type.startsWith('int')) {
1829
- size = parseTypeN(type);
1830
- if ((size % 8) || (size < 8) || (size > 256)) {
1831
- throw new Error('Invalid int<N> width: ' + size)
1832
- }
1833
-
1834
- num = parseNumber(arg);
1835
- const bitLength = util$1.bitLengthFromBigInt(num);
1836
- if (bitLength > size) {
1837
- throw new Error('Supplied int exceeds width: ' + size + ' vs ' + bitLength)
1838
- }
1839
-
1840
- const twos = util$1.twosFromBigInt(num, 256);
1841
-
1842
- return util$1.bufferBEFromBigInt(twos, 32);
1843
- } else if (type.startsWith('ufixed')) {
1844
- size = parseTypeNxM(type);
1845
-
1846
- num = parseNumber(arg);
1847
-
1848
- if (num < 0) {
1849
- throw new Error('Supplied ufixed is negative')
1850
- }
1851
-
1852
- return encodeSingle('uint256', num * BigInt(2) ** BigInt(size[1]))
1853
- } else if (type.startsWith('fixed')) {
1854
- size = parseTypeNxM(type);
1855
-
1856
- return encodeSingle('int256', parseNumber(arg) * BigInt(2) ** BigInt(size[1]))
1857
- }
1858
-
1859
- throw new Error('Unsupported or invalid type: ' + type)
1860
- }
1861
-
1862
- // Is a type dynamic?
1863
- function isDynamic (type) {
1864
- // FIXME: handle all types? I don't think anything is missing now
1865
- return (type === 'string') || (type === 'bytes') || (parseTypeArray(type) === 'dynamic')
1866
- }
1867
-
1868
- // Is a type an array?
1869
- function isArray (type) {
1870
- return type.lastIndexOf(']') === type.length - 1
1871
- }
1872
-
1873
- // Encode a method/event with arguments
1874
- // @types an array of string type names
1875
- // @args an array of the appropriate values
1876
- function rawEncode (types, values) {
1877
- var output = [];
1878
- var data = [];
1879
-
1880
- var headLength = 32 * types.length;
1881
-
1882
- for (var i in types) {
1883
- var type = elementaryName(types[i]);
1884
- var value = values[i];
1885
- var cur = encodeSingle(type, value);
1886
-
1887
- // Use the head/tail method for storing dynamic data
1888
- if (isDynamic(type)) {
1889
- output.push(encodeSingle('uint256', headLength));
1890
- data.push(cur);
1891
- headLength += cur.length;
1892
- } else {
1893
- output.push(cur);
1894
- }
1895
- }
1896
-
1897
- return Buffer.concat(output.concat(data))
1898
- }
1899
-
1900
- function solidityPack (types, values) {
1901
- if (types.length !== values.length) {
1902
- throw new Error('Number of types are not matching the values')
1903
- }
1904
-
1905
- var size, num;
1906
- var ret = [];
1907
-
1908
- for (var i = 0; i < types.length; i++) {
1909
- var type = elementaryName(types[i]);
1910
- var value = values[i];
1911
-
1912
- if (type === 'bytes') {
1913
- ret.push(value);
1914
- } else if (type === 'string') {
1915
- ret.push(new Buffer(value, 'utf8'));
1916
- } else if (type === 'bool') {
1917
- ret.push(new Buffer(value ? '01' : '00', 'hex'));
1918
- } else if (type === 'address') {
1919
- ret.push(util$1.setLength(value, 20));
1920
- } else if (type.startsWith('bytes')) {
1921
- size = parseTypeN(type);
1922
- if (size < 1 || size > 32) {
1923
- throw new Error('Invalid bytes<N> width: ' + size)
1924
- }
1925
-
1926
- ret.push(util$1.setLengthRight(value, size));
1927
- } else if (type.startsWith('uint')) {
1928
- size = parseTypeN(type);
1929
- if ((size % 8) || (size < 8) || (size > 256)) {
1930
- throw new Error('Invalid uint<N> width: ' + size)
1931
- }
1932
-
1933
- num = parseNumber(value);
1934
- const bitLength = util$1.bitLengthFromBigInt(num);
1935
- if (bitLength > size) {
1936
- throw new Error('Supplied uint exceeds width: ' + size + ' vs ' + bitLength)
1937
- }
1938
-
1939
- ret.push(util$1.bufferBEFromBigInt(num, size / 8));
1940
- } else if (type.startsWith('int')) {
1941
- size = parseTypeN(type);
1942
- if ((size % 8) || (size < 8) || (size > 256)) {
1943
- throw new Error('Invalid int<N> width: ' + size)
1944
- }
1945
-
1946
- num = parseNumber(value);
1947
- const bitLength = util$1.bitLengthFromBigInt(num);
1948
- if (bitLength > size) {
1949
- throw new Error('Supplied int exceeds width: ' + size + ' vs ' + bitLength)
1950
- }
1951
-
1952
- const twos = util$1.twosFromBigInt(num, size);
1953
- ret.push(util$1.bufferBEFromBigInt(twos, size / 8));
1954
- } else {
1955
- // FIXME: support all other types
1956
- throw new Error('Unsupported or invalid type: ' + type)
1957
- }
1958
- }
1959
-
1960
- return Buffer.concat(ret)
1961
- }
1962
-
1963
- function soliditySHA3 (types, values) {
1964
- return util$1.keccak(solidityPack(types, values))
1965
- }
1966
-
1967
- var abi$1 = {
1968
- rawEncode,
1969
- solidityPack,
1970
- soliditySHA3
1971
- };
1972
-
1973
- /* eslint-disable */
1974
-
1975
- //prettier-ignore
1976
-
1977
- const util = util$2;
1978
- const abi = abi$1;
1979
-
1980
- const TYPED_MESSAGE_SCHEMA = {
1981
- type: 'object',
1982
- properties: {
1983
- types: {
1984
- type: 'object',
1985
- additionalProperties: {
1986
- type: 'array',
1987
- items: {
1988
- type: 'object',
1989
- properties: {
1990
- name: {type: 'string'},
1991
- type: {type: 'string'},
1992
- },
1993
- required: ['name', 'type'],
1994
- },
1995
- },
1996
- },
1997
- primaryType: {type: 'string'},
1998
- domain: {type: 'object'},
1999
- message: {type: 'object'},
2000
- },
2001
- required: ['types', 'primaryType', 'domain', 'message'],
2002
- };
2003
-
2004
- /**
2005
- * A collection of utility functions used for signing typed data
2006
- */
2007
- const TypedDataUtils = {
2008
- /**
2009
- * Encodes an object by encoding and concatenating each of its members
2010
- *
2011
- * @param {string} primaryType - Root type
2012
- * @param {Object} data - Object to encode
2013
- * @param {Object} types - Type definitions
2014
- * @returns {string} - Encoded representation of an object
2015
- */
2016
- encodeData (primaryType, data, types, useV4 = true) {
2017
- const encodedTypes = ['bytes32'];
2018
- const encodedValues = [this.hashType(primaryType, types)];
2019
-
2020
- if(useV4) {
2021
- const encodeField = (name, type, value) => {
2022
- if (types[type] !== undefined) {
2023
- return ['bytes32', value == null ?
2024
- '0x0000000000000000000000000000000000000000000000000000000000000000' :
2025
- util.keccak(this.encodeData(type, value, types, useV4))]
2026
- }
2027
-
2028
- if(value === undefined)
2029
- throw new Error(`missing value for field ${name} of type ${type}`)
2030
-
2031
- if (type === 'bytes') {
2032
- return ['bytes32', util.keccak(value)]
2033
- }
2034
-
2035
- if (type === 'string') {
2036
- // convert string to buffer - prevents ethUtil from interpreting strings like '0xabcd' as hex
2037
- if (typeof value === 'string') {
2038
- value = Buffer.from(value, 'utf8');
2039
- }
2040
- return ['bytes32', util.keccak(value)]
2041
- }
2042
-
2043
- if (type.lastIndexOf(']') === type.length - 1) {
2044
- const parsedType = type.slice(0, type.lastIndexOf('['));
2045
- const typeValuePairs = value.map(item =>
2046
- encodeField(name, parsedType, item));
2047
- return ['bytes32', util.keccak(abi.rawEncode(
2048
- typeValuePairs.map(([type]) => type),
2049
- typeValuePairs.map(([, value]) => value),
2050
- ))]
2051
- }
2052
-
2053
- return [type, value]
2054
- };
2055
-
2056
- for (const field of types[primaryType]) {
2057
- const [type, value] = encodeField(field.name, field.type, data[field.name]);
2058
- encodedTypes.push(type);
2059
- encodedValues.push(value);
2060
- }
2061
- } else {
2062
- for (const field of types[primaryType]) {
2063
- let value = data[field.name];
2064
- if (value !== undefined) {
2065
- if (field.type === 'bytes') {
2066
- encodedTypes.push('bytes32');
2067
- value = util.keccak(value);
2068
- encodedValues.push(value);
2069
- } else if (field.type === 'string') {
2070
- encodedTypes.push('bytes32');
2071
- // convert string to buffer - prevents ethUtil from interpreting strings like '0xabcd' as hex
2072
- if (typeof value === 'string') {
2073
- value = Buffer.from(value, 'utf8');
2074
- }
2075
- value = util.keccak(value);
2076
- encodedValues.push(value);
2077
- } else if (types[field.type] !== undefined) {
2078
- encodedTypes.push('bytes32');
2079
- value = util.keccak(this.encodeData(field.type, value, types, useV4));
2080
- encodedValues.push(value);
2081
- } else if (field.type.lastIndexOf(']') === field.type.length - 1) {
2082
- throw new Error('Arrays currently unimplemented in encodeData')
2083
- } else {
2084
- encodedTypes.push(field.type);
2085
- encodedValues.push(value);
2086
- }
2087
- }
2088
- }
2089
- }
2090
-
2091
- return abi.rawEncode(encodedTypes, encodedValues)
2092
- },
2093
-
2094
- /**
2095
- * Encodes the type of an object by encoding a comma delimited list of its members
2096
- *
2097
- * @param {string} primaryType - Root type to encode
2098
- * @param {Object} types - Type definitions
2099
- * @returns {string} - Encoded representation of the type of an object
2100
- */
2101
- encodeType (primaryType, types) {
2102
- let result = '';
2103
- let deps = this.findTypeDependencies(primaryType, types).filter(dep => dep !== primaryType);
2104
- deps = [primaryType].concat(deps.sort());
2105
- for (const type of deps) {
2106
- const children = types[type];
2107
- if (!children) {
2108
- throw new Error('No type definition specified: ' + type)
2109
- }
2110
- result += type + '(' + types[type].map(({ name, type }) => type + ' ' + name).join(',') + ')';
2111
- }
2112
- return result
2113
- },
2114
-
2115
- /**
2116
- * Finds all types within a type definition object
2117
- *
2118
- * @param {string} primaryType - Root type
2119
- * @param {Object} types - Type definitions
2120
- * @param {Array} results - current set of accumulated types
2121
- * @returns {Array} - Set of all types found in the type definition
2122
- */
2123
- findTypeDependencies (primaryType, types, results = []) {
2124
- primaryType = primaryType.match(/^\w*/)[0];
2125
- if (results.includes(primaryType) || types[primaryType] === undefined) { return results }
2126
- results.push(primaryType);
2127
- for (const field of types[primaryType]) {
2128
- for (const dep of this.findTypeDependencies(field.type, types, results)) {
2129
- !results.includes(dep) && results.push(dep);
2130
- }
2131
- }
2132
- return results
2133
- },
2134
-
2135
- /**
2136
- * Hashes an object
2137
- *
2138
- * @param {string} primaryType - Root type
2139
- * @param {Object} data - Object to hash
2140
- * @param {Object} types - Type definitions
2141
- * @returns {Buffer} - Hash of an object
2142
- */
2143
- hashStruct (primaryType, data, types, useV4 = true) {
2144
- return util.keccak(this.encodeData(primaryType, data, types, useV4))
2145
- },
2146
-
2147
- /**
2148
- * Hashes the type of an object
2149
- *
2150
- * @param {string} primaryType - Root type to hash
2151
- * @param {Object} types - Type definitions
2152
- * @returns {string} - Hash of an object
2153
- */
2154
- hashType (primaryType, types) {
2155
- return util.keccak(this.encodeType(primaryType, types))
2156
- },
2157
-
2158
- /**
2159
- * Removes properties from a message object that are not defined per EIP-712
2160
- *
2161
- * @param {Object} data - typed message object
2162
- * @returns {Object} - typed message object with only allowed fields
2163
- */
2164
- sanitizeData (data) {
2165
- const sanitizedData = {};
2166
- for (const key in TYPED_MESSAGE_SCHEMA.properties) {
2167
- data[key] && (sanitizedData[key] = data[key]);
2168
- }
2169
- if (sanitizedData.types) {
2170
- sanitizedData.types = Object.assign({ EIP712Domain: [] }, sanitizedData.types);
2171
- }
2172
- return sanitizedData
2173
- },
2174
-
2175
- /**
2176
- * Returns the hash of a typed message as per EIP-712 for signing
2177
- *
2178
- * @param {Object} typedData - Types message data to sign
2179
- * @returns {string} - sha3 hash for signing
2180
- */
2181
- hash (typedData, useV4 = true) {
2182
- const sanitizedData = this.sanitizeData(typedData);
2183
- const parts = [Buffer.from('1901', 'hex')];
2184
- parts.push(this.hashStruct('EIP712Domain', sanitizedData.domain, sanitizedData.types, useV4));
2185
- if (sanitizedData.primaryType !== 'EIP712Domain') {
2186
- parts.push(this.hashStruct(sanitizedData.primaryType, sanitizedData.message, sanitizedData.types, useV4));
2187
- }
2188
- return util.keccak(Buffer.concat(parts))
2189
- },
2190
- };
2191
-
2192
- var ethEip712Util = {
2193
- TYPED_MESSAGE_SCHEMA,
2194
- TypedDataUtils,
2195
-
2196
- hashForSignTypedDataLegacy: function (msgParams) {
2197
- return typedSignatureHashLegacy(msgParams.data)
2198
- },
2199
-
2200
- hashForSignTypedData_v3: function (msgParams) {
2201
- return TypedDataUtils.hash(msgParams.data, false)
2202
- },
2203
-
2204
- hashForSignTypedData_v4: function (msgParams) {
2205
- return TypedDataUtils.hash(msgParams.data)
2206
- },
2207
- };
2208
-
2209
- /**
2210
- * @param typedData - Array of data along with types, as per EIP712.
2211
- * @returns Buffer
2212
- */
2213
- function typedSignatureHashLegacy(typedData) {
2214
- const error = new Error('Expect argument to be non-empty array');
2215
- if (typeof typedData !== 'object' || !typedData.length) throw error
2216
-
2217
- const data = typedData.map(function (e) {
2218
- return e.type === 'bytes' ? util.toBuffer(e.value) : e.value
2219
- });
2220
- const types = typedData.map(function (e) { return e.type });
2221
- const schema = typedData.map(function (e) {
2222
- if (!e.name) throw error
2223
- return e.type + ' ' + e.name
2224
- });
2225
-
2226
- return abi.soliditySHA3(
2227
- ['bytes32', 'bytes32'],
2228
- [
2229
- abi.soliditySHA3(new Array(typedData.length).fill('string'), schema),
2230
- abi.soliditySHA3(types, data)
2231
- ]
2232
- )
2233
- }
2234
-
2235
- var eip712 = /*@__PURE__*/index.getDefaultExportFromCjs(ethEip712Util);
2236
-
2237
- const WALLET_USER_NAME_KEY = 'walletUsername';
2238
- const LOCAL_STORAGE_ADDRESSES_KEY = 'Addresses';
2239
- const APP_VERSION_KEY = 'AppVersion';
2240
-
2241
- // Copyright (c) 2018-2023 Coinbase, Inc. <https://www.coinbase.com/>
2242
- function isErrorResponse(response) {
2243
- return response.errorMessage !== undefined;
2244
- }
2245
-
2246
- // Copyright (c) 2018-2023 Coinbase, Inc. <https://www.coinbase.com/>
2247
- class WalletLinkCipher {
2248
- // @param secret hex representation of 32-byte secret
2249
- constructor(secret) {
2250
- this.secret = secret;
2251
- }
2252
- /**
2253
- *
2254
- * @param plainText string to be encrypted
2255
- * returns hex string representation of bytes in the order: initialization vector (iv),
2256
- * auth tag, encrypted plaintext. IV is 12 bytes. Auth tag is 16 bytes. Remaining bytes are the
2257
- * encrypted plainText.
2258
- */
2259
- async encrypt(plainText) {
2260
- const secret = this.secret;
2261
- if (secret.length !== 64)
2262
- throw Error(`secret must be 256 bits`);
2263
- const ivBytes = crypto.getRandomValues(new Uint8Array(12));
2264
- const secretKey = await crypto.subtle.importKey('raw', hexStringToUint8Array(secret), { name: 'aes-gcm' }, false, ['encrypt', 'decrypt']);
2265
- const enc = new TextEncoder();
2266
- // Will return encrypted plainText with auth tag (ie MAC or checksum) appended at the end
2267
- const encryptedResult = await window.crypto.subtle.encrypt({
2268
- name: 'AES-GCM',
2269
- iv: ivBytes,
2270
- }, secretKey, enc.encode(plainText));
2271
- const tagLength = 16;
2272
- const authTag = encryptedResult.slice(encryptedResult.byteLength - tagLength);
2273
- const encryptedPlaintext = encryptedResult.slice(0, encryptedResult.byteLength - tagLength);
2274
- const authTagBytes = new Uint8Array(authTag);
2275
- const encryptedPlaintextBytes = new Uint8Array(encryptedPlaintext);
2276
- const concatted = new Uint8Array([...ivBytes, ...authTagBytes, ...encryptedPlaintextBytes]);
2277
- return uint8ArrayToHex(concatted);
2278
- }
2279
- /**
2280
- *
2281
- * @param cipherText hex string representation of bytes in the order: initialization vector (iv),
2282
- * auth tag, encrypted plaintext. IV is 12 bytes. Auth tag is 16 bytes.
2283
- */
2284
- async decrypt(cipherText) {
2285
- const secret = this.secret;
2286
- if (secret.length !== 64)
2287
- throw Error(`secret must be 256 bits`);
2288
- return new Promise((resolve, reject) => {
2289
- void (async function () {
2290
- const secretKey = await crypto.subtle.importKey('raw', hexStringToUint8Array(secret), { name: 'aes-gcm' }, false, ['encrypt', 'decrypt']);
2291
- const encrypted = hexStringToUint8Array(cipherText);
2292
- const ivBytes = encrypted.slice(0, 12);
2293
- const authTagBytes = encrypted.slice(12, 28);
2294
- const encryptedPlaintextBytes = encrypted.slice(28);
2295
- const concattedBytes = new Uint8Array([...encryptedPlaintextBytes, ...authTagBytes]);
2296
- const algo = {
2297
- name: 'AES-GCM',
2298
- iv: new Uint8Array(ivBytes),
2299
- };
2300
- try {
2301
- const decrypted = await window.crypto.subtle.decrypt(algo, secretKey, concattedBytes);
2302
- const decoder = new TextDecoder();
2303
- resolve(decoder.decode(decrypted));
2304
- }
2305
- catch (err) {
2306
- reject(err);
2307
- }
2308
- })();
2309
- });
2310
- }
2311
- }
2312
-
2313
- class WalletLinkHTTP {
2314
- constructor(linkAPIUrl, sessionId, sessionKey) {
2315
- this.linkAPIUrl = linkAPIUrl;
2316
- this.sessionId = sessionId;
2317
- const credentials = `${sessionId}:${sessionKey}`;
2318
- this.auth = `Basic ${btoa(credentials)}`;
2319
- }
2320
- // mark unseen events as seen
2321
- async markUnseenEventsAsSeen(events) {
2322
- return Promise.all(events.map((e) => fetch(`${this.linkAPIUrl}/events/${e.eventId}/seen`, {
2323
- method: 'POST',
2324
- headers: {
2325
- Authorization: this.auth,
2326
- },
2327
- }))).catch((error) => console.error('Unabled to mark event as failed:', error));
2328
- }
2329
- async fetchUnseenEvents() {
2330
- var _a;
2331
- const response = await fetch(`${this.linkAPIUrl}/events?unseen=true`, {
2332
- headers: {
2333
- Authorization: this.auth,
2334
- },
2335
- });
2336
- if (response.ok) {
2337
- const { events, error } = (await response.json());
2338
- if (error) {
2339
- throw new Error(`Check unseen events failed: ${error}`);
2340
- }
2341
- const responseEvents = (_a = events === null || events === void 0 ? void 0 : events.filter((e) => e.event === 'Web3Response').map((e) => ({
2342
- type: 'Event',
2343
- sessionId: this.sessionId,
2344
- eventId: e.id,
2345
- event: e.event,
2346
- data: e.data,
2347
- }))) !== null && _a !== void 0 ? _a : [];
2348
- this.markUnseenEventsAsSeen(responseEvents);
2349
- return responseEvents;
2350
- }
2351
- throw new Error(`Check unseen events failed: ${response.status}`);
2352
- }
2353
- }
2354
-
2355
- // Copyright (c) 2018-2023 Coinbase, Inc. <https://www.coinbase.com/>
2356
- var ConnectionState;
2357
- (function (ConnectionState) {
2358
- ConnectionState[ConnectionState["DISCONNECTED"] = 0] = "DISCONNECTED";
2359
- ConnectionState[ConnectionState["CONNECTING"] = 1] = "CONNECTING";
2360
- ConnectionState[ConnectionState["CONNECTED"] = 2] = "CONNECTED";
2361
- })(ConnectionState || (ConnectionState = {}));
2362
- class WalletLinkWebSocket {
2363
- setConnectionStateListener(listener) {
2364
- this.connectionStateListener = listener;
2365
- }
2366
- setIncomingDataListener(listener) {
2367
- this.incomingDataListener = listener;
2368
- }
2369
- /**
2370
- * Constructor
2371
- * @param url WebSocket server URL
2372
- * @param [WebSocketClass] Custom WebSocket implementation
2373
- */
2374
- constructor(url, WebSocketClass = WebSocket) {
2375
- this.WebSocketClass = WebSocketClass;
2376
- this.webSocket = null;
2377
- this.pendingData = [];
2378
- this.url = url.replace(/^http/, 'ws');
2379
- }
2380
- /**
2381
- * Make a websocket connection
2382
- * @returns a Promise that resolves when connected
2383
- */
2384
- async connect() {
2385
- if (this.webSocket) {
2386
- throw new Error('webSocket object is not null');
2387
- }
2388
- return new Promise((resolve, reject) => {
2389
- var _a;
2390
- let webSocket;
2391
- try {
2392
- this.webSocket = webSocket = new this.WebSocketClass(this.url);
2393
- }
2394
- catch (err) {
2395
- reject(err);
2396
- return;
2397
- }
2398
- (_a = this.connectionStateListener) === null || _a === void 0 ? void 0 : _a.call(this, ConnectionState.CONNECTING);
2399
- webSocket.onclose = (evt) => {
2400
- var _a;
2401
- this.clearWebSocket();
2402
- reject(new Error(`websocket error ${evt.code}: ${evt.reason}`));
2403
- (_a = this.connectionStateListener) === null || _a === void 0 ? void 0 : _a.call(this, ConnectionState.DISCONNECTED);
2404
- };
2405
- webSocket.onopen = (_) => {
2406
- var _a;
2407
- resolve();
2408
- (_a = this.connectionStateListener) === null || _a === void 0 ? void 0 : _a.call(this, ConnectionState.CONNECTED);
2409
- if (this.pendingData.length > 0) {
2410
- const pending = [...this.pendingData];
2411
- pending.forEach((data) => this.sendData(data));
2412
- this.pendingData = [];
2413
- }
2414
- };
2415
- webSocket.onmessage = (evt) => {
2416
- var _a, _b;
2417
- if (evt.data === 'h') {
2418
- (_a = this.incomingDataListener) === null || _a === void 0 ? void 0 : _a.call(this, {
2419
- type: 'Heartbeat',
2420
- });
2421
- }
2422
- else {
2423
- try {
2424
- const message = JSON.parse(evt.data);
2425
- (_b = this.incomingDataListener) === null || _b === void 0 ? void 0 : _b.call(this, message);
2426
- }
2427
- catch (_c) {
2428
- /* empty */
2429
- }
2430
- }
2431
- };
2432
- });
2433
- }
2434
- /**
2435
- * Disconnect from server
2436
- */
2437
- disconnect() {
2438
- var _a;
2439
- const { webSocket } = this;
2440
- if (!webSocket) {
2441
- return;
2442
- }
2443
- this.clearWebSocket();
2444
- (_a = this.connectionStateListener) === null || _a === void 0 ? void 0 : _a.call(this, ConnectionState.DISCONNECTED);
2445
- this.connectionStateListener = undefined;
2446
- this.incomingDataListener = undefined;
2447
- try {
2448
- webSocket.close();
2449
- }
2450
- catch (_b) {
2451
- // noop
2452
- }
2453
- }
2454
- /**
2455
- * Send data to server
2456
- * @param data text to send
2457
- */
2458
- sendData(data) {
2459
- const { webSocket } = this;
2460
- if (!webSocket) {
2461
- this.pendingData.push(data);
2462
- this.connect();
2463
- return;
2464
- }
2465
- webSocket.send(data);
2466
- }
2467
- clearWebSocket() {
2468
- const { webSocket } = this;
2469
- if (!webSocket) {
2470
- return;
2471
- }
2472
- this.webSocket = null;
2473
- webSocket.onclose = null;
2474
- webSocket.onerror = null;
2475
- webSocket.onmessage = null;
2476
- webSocket.onopen = null;
2477
- }
2478
- }
2479
-
2480
- // Copyright (c) 2018-2023 Coinbase, Inc. <https://www.coinbase.com/>
2481
- const HEARTBEAT_INTERVAL = 10000;
2482
- const REQUEST_TIMEOUT = 60000;
2483
- /**
2484
- * Coinbase Wallet Connection
2485
- */
2486
- class WalletLinkConnection {
2487
- /**
2488
- * Constructor
2489
- * @param session Session
2490
- * @param linkAPIUrl Coinbase Wallet link server URL
2491
- * @param listener WalletLinkConnectionUpdateListener
2492
- * @param [WebSocketClass] Custom WebSocket implementation
2493
- */
2494
- constructor({ session, linkAPIUrl, listener }) {
2495
- this.destroyed = false;
2496
- this.lastHeartbeatResponse = 0;
2497
- this.nextReqId = IntNumber(1);
2498
- /**
2499
- * true if connected and authenticated, else false
2500
- * runs listener when connected status changes
2501
- */
2502
- this._connected = false;
2503
- /**
2504
- * true if linked (a guest has joined before)
2505
- * runs listener when linked status changes
2506
- */
2507
- this._linked = false;
2508
- this.shouldFetchUnseenEventsOnConnect = false;
2509
- this.requestResolutions = new Map();
2510
- this.handleSessionMetadataUpdated = (metadata) => {
2511
- if (!metadata)
2512
- return;
2513
- // Map of metadata key to handler function
2514
- const handlers = new Map([
2515
- ['__destroyed', this.handleDestroyed],
2516
- ['EthereumAddress', this.handleAccountUpdated],
2517
- ['WalletUsername', this.handleWalletUsernameUpdated],
2518
- ['AppVersion', this.handleAppVersionUpdated],
2519
- [
2520
- 'ChainId', // ChainId and JsonRpcUrl are always updated together
2521
- (v) => metadata.JsonRpcUrl && this.handleChainUpdated(v, metadata.JsonRpcUrl),
2522
- ],
2523
- ]);
2524
- // call handler for each metadata key if value is defined
2525
- handlers.forEach((handler, key) => {
2526
- const value = metadata[key];
2527
- if (value === undefined)
2528
- return;
2529
- handler(value);
2530
- });
2531
- };
2532
- this.handleDestroyed = (__destroyed) => {
2533
- var _a;
2534
- if (__destroyed !== '1')
2535
- return;
2536
- (_a = this.listener) === null || _a === void 0 ? void 0 : _a.resetAndReload();
2537
- };
2538
- this.handleAccountUpdated = async (encryptedEthereumAddress) => {
2539
- var _a;
2540
- const address = await this.cipher.decrypt(encryptedEthereumAddress);
2541
- (_a = this.listener) === null || _a === void 0 ? void 0 : _a.accountUpdated(address);
2542
- };
2543
- this.handleMetadataUpdated = async (key, encryptedMetadataValue) => {
2544
- var _a;
2545
- const decryptedValue = await this.cipher.decrypt(encryptedMetadataValue);
2546
- (_a = this.listener) === null || _a === void 0 ? void 0 : _a.metadataUpdated(key, decryptedValue);
2547
- };
2548
- this.handleWalletUsernameUpdated = async (walletUsername) => {
2549
- this.handleMetadataUpdated(WALLET_USER_NAME_KEY, walletUsername);
2550
- };
2551
- this.handleAppVersionUpdated = async (appVersion) => {
2552
- this.handleMetadataUpdated(APP_VERSION_KEY, appVersion);
2553
- };
2554
- this.handleChainUpdated = async (encryptedChainId, encryptedJsonRpcUrl) => {
2555
- var _a;
2556
- const chainId = await this.cipher.decrypt(encryptedChainId);
2557
- const jsonRpcUrl = await this.cipher.decrypt(encryptedJsonRpcUrl);
2558
- (_a = this.listener) === null || _a === void 0 ? void 0 : _a.chainUpdated(chainId, jsonRpcUrl);
2559
- };
2560
- this.session = session;
2561
- this.cipher = new WalletLinkCipher(session.secret);
2562
- this.listener = listener;
2563
- const ws = new WalletLinkWebSocket(`${linkAPIUrl}/rpc`, WebSocket);
2564
- ws.setConnectionStateListener(async (state) => {
2565
- // attempt to reconnect every 5 seconds when disconnected
2566
- let connected = false;
2567
- switch (state) {
2568
- case ConnectionState.DISCONNECTED:
2569
- // if DISCONNECTED and not destroyed
2570
- if (!this.destroyed) {
2571
- const connect = async () => {
2572
- // wait 5 seconds
2573
- await new Promise((resolve) => setTimeout(resolve, 5000));
2574
- // check whether it's destroyed again
2575
- if (!this.destroyed) {
2576
- // reconnect
2577
- ws.connect().catch(() => {
2578
- connect();
2579
- });
2580
- }
2581
- };
2582
- connect();
2583
- }
2584
- break;
2585
- case ConnectionState.CONNECTED:
2586
- // perform authentication upon connection
2587
- // if CONNECTED, authenticate, and then check link status
2588
- connected = await this.handleConnected();
2589
- // send heartbeat every n seconds while connected
2590
- // if CONNECTED, start the heartbeat timer
2591
- // first timer event updates lastHeartbeat timestamp
2592
- // subsequent calls send heartbeat message
2593
- this.updateLastHeartbeat();
2594
- setInterval(() => {
2595
- this.heartbeat();
2596
- }, HEARTBEAT_INTERVAL);
2597
- // check for unseen events
2598
- if (this.shouldFetchUnseenEventsOnConnect) {
2599
- this.fetchUnseenEventsAPI();
2600
- }
2601
- break;
2602
- case ConnectionState.CONNECTING:
2603
- break;
2604
- }
2605
- // distinctUntilChanged
2606
- if (this.connected !== connected) {
2607
- this.connected = connected;
2608
- }
2609
- });
2610
- ws.setIncomingDataListener((m) => {
2611
- var _a;
2612
- switch (m.type) {
2613
- // handle server's heartbeat responses
2614
- case 'Heartbeat':
2615
- this.updateLastHeartbeat();
2616
- return;
2617
- // handle link status updates
2618
- case 'IsLinkedOK':
2619
- case 'Linked': {
2620
- const linked = m.type === 'IsLinkedOK' ? m.linked : undefined;
2621
- this.linked = linked || m.onlineGuests > 0;
2622
- break;
2623
- }
2624
- // handle session config updates
2625
- case 'GetSessionConfigOK':
2626
- case 'SessionConfigUpdated': {
2627
- this.handleSessionMetadataUpdated(m.metadata);
2628
- break;
2629
- }
2630
- case 'Event': {
2631
- this.handleIncomingEvent(m);
2632
- break;
2633
- }
2634
- }
2635
- // resolve request promises
2636
- if (m.id !== undefined) {
2637
- (_a = this.requestResolutions.get(m.id)) === null || _a === void 0 ? void 0 : _a(m);
2638
- }
2639
- });
2640
- this.ws = ws;
2641
- this.http = new WalletLinkHTTP(linkAPIUrl, session.id, session.key);
2642
- }
2643
- /**
2644
- * Make a connection to the server
2645
- */
2646
- connect() {
2647
- if (this.destroyed) {
2648
- throw new Error('instance is destroyed');
2649
- }
2650
- this.ws.connect();
2651
- }
2652
- /**
2653
- * Terminate connection, and mark as destroyed. To reconnect, create a new
2654
- * instance of WalletSDKConnection
2655
- */
2656
- async destroy() {
2657
- if (this.destroyed)
2658
- return;
2659
- await this.makeRequest({
2660
- type: 'SetSessionConfig',
2661
- id: IntNumber(this.nextReqId++),
2662
- sessionId: this.session.id,
2663
- metadata: { __destroyed: '1' },
2664
- }, { timeout: 1000 });
2665
- this.destroyed = true;
2666
- this.ws.disconnect();
2667
- this.listener = undefined;
2668
- }
2669
- get connected() {
2670
- return this._connected;
2671
- }
2672
- set connected(connected) {
2673
- this._connected = connected;
2674
- }
2675
- get linked() {
2676
- return this._linked;
2677
- }
2678
- set linked(linked) {
2679
- var _a, _b;
2680
- this._linked = linked;
2681
- if (linked)
2682
- (_a = this.onceLinked) === null || _a === void 0 ? void 0 : _a.call(this);
2683
- (_b = this.listener) === null || _b === void 0 ? void 0 : _b.linkedUpdated(linked);
2684
- }
2685
- setOnceLinked(callback) {
2686
- return new Promise((resolve) => {
2687
- if (this.linked) {
2688
- callback().then(resolve);
2689
- }
2690
- else {
2691
- this.onceLinked = () => {
2692
- callback().then(resolve);
2693
- this.onceLinked = undefined;
2694
- };
2695
- }
2696
- });
2697
- }
2698
- async handleIncomingEvent(m) {
2699
- var _a;
2700
- if (m.type !== 'Event' || m.event !== 'Web3Response') {
2701
- return;
2702
- }
2703
- const decryptedData = await this.cipher.decrypt(m.data);
2704
- const message = JSON.parse(decryptedData);
2705
- if (message.type !== 'WEB3_RESPONSE')
2706
- return;
2707
- const { id, response } = message;
2708
- (_a = this.listener) === null || _a === void 0 ? void 0 : _a.handleWeb3ResponseMessage(id, response);
2709
- }
2710
- async checkUnseenEvents() {
2711
- if (!this.connected) {
2712
- this.shouldFetchUnseenEventsOnConnect = true;
2713
- return;
2714
- }
2715
- await new Promise((resolve) => setTimeout(resolve, 250));
2716
- try {
2717
- await this.fetchUnseenEventsAPI();
2718
- }
2719
- catch (e) {
2720
- console.error('Unable to check for unseen events', e);
2721
- }
2722
- }
2723
- async fetchUnseenEventsAPI() {
2724
- this.shouldFetchUnseenEventsOnConnect = false;
2725
- const responseEvents = await this.http.fetchUnseenEvents();
2726
- responseEvents.forEach((e) => this.handleIncomingEvent(e));
2727
- }
2728
- /**
2729
- * Publish an event and emit event ID when successful
2730
- * @param event event name
2731
- * @param unencryptedData unencrypted event data
2732
- * @param callWebhook whether the webhook should be invoked
2733
- * @returns a Promise that emits event ID when successful
2734
- */
2735
- async publishEvent(event, unencryptedData, callWebhook = false) {
2736
- const data = await this.cipher.encrypt(JSON.stringify(Object.assign(Object.assign({}, unencryptedData), { origin: location.origin, relaySource: 'coinbaseWalletExtension' in window && window.coinbaseWalletExtension
2737
- ? 'injected_sdk'
2738
- : 'sdk' })));
2739
- const message = {
2740
- type: 'PublishEvent',
2741
- id: IntNumber(this.nextReqId++),
2742
- sessionId: this.session.id,
2743
- event,
2744
- data,
2745
- callWebhook,
2746
- };
2747
- return this.setOnceLinked(async () => {
2748
- const res = await this.makeRequest(message);
2749
- if (res.type === 'Fail') {
2750
- throw new Error(res.error || 'failed to publish event');
2751
- }
2752
- return res.eventId;
2753
- });
2754
- }
2755
- sendData(message) {
2756
- this.ws.sendData(JSON.stringify(message));
2757
- }
2758
- updateLastHeartbeat() {
2759
- this.lastHeartbeatResponse = Date.now();
2760
- }
2761
- heartbeat() {
2762
- if (Date.now() - this.lastHeartbeatResponse > HEARTBEAT_INTERVAL * 2) {
2763
- this.ws.disconnect();
2764
- return;
2765
- }
2766
- try {
2767
- this.ws.sendData('h');
2768
- }
2769
- catch (_a) {
2770
- // noop
2771
- }
2772
- }
2773
- async makeRequest(message, options = { timeout: REQUEST_TIMEOUT }) {
2774
- const reqId = message.id;
2775
- this.sendData(message);
2776
- // await server message with corresponding id
2777
- let timeoutId;
2778
- return Promise.race([
2779
- new Promise((_, reject) => {
2780
- timeoutId = window.setTimeout(() => {
2781
- reject(new Error(`request ${reqId} timed out`));
2782
- }, options.timeout);
2783
- }),
2784
- new Promise((resolve) => {
2785
- this.requestResolutions.set(reqId, (m) => {
2786
- clearTimeout(timeoutId); // clear the timeout
2787
- resolve(m);
2788
- this.requestResolutions.delete(reqId);
2789
- });
2790
- }),
2791
- ]);
2792
- }
2793
- async handleConnected() {
2794
- const res = await this.makeRequest({
2795
- type: 'HostSession',
2796
- id: IntNumber(this.nextReqId++),
2797
- sessionId: this.session.id,
2798
- sessionKey: this.session.key,
2799
- });
2800
- if (res.type === 'Fail')
2801
- return false;
2802
- this.sendData({
2803
- type: 'IsLinked',
2804
- id: IntNumber(this.nextReqId++),
2805
- sessionId: this.session.id,
2806
- });
2807
- this.sendData({
2808
- type: 'GetSessionConfig',
2809
- id: IntNumber(this.nextReqId++),
2810
- sessionId: this.session.id,
2811
- });
2812
- return true;
2813
- }
2814
- }
2815
-
2816
- class RelayEventManager {
2817
- constructor() {
2818
- this._nextRequestId = 0;
2819
- this.callbacks = new Map();
2820
- }
2821
- makeRequestId() {
2822
- // max nextId == max int32 for compatibility with mobile
2823
- this._nextRequestId = (this._nextRequestId + 1) % 0x7fffffff;
2824
- const id = this._nextRequestId;
2825
- const idStr = prepend0x(id.toString(16));
2826
- // unlikely that this will ever be an issue, but just to be safe
2827
- const callback = this.callbacks.get(idStr);
2828
- if (callback) {
2829
- this.callbacks.delete(idStr);
2830
- }
2831
- return id;
2832
- }
2833
- }
2834
-
2835
- // copied from utils
2836
- function isBytes(a) {
2837
- return (a instanceof Uint8Array ||
2838
- (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
2839
- }
2840
- function bytes(b, ...lengths) {
2841
- if (!isBytes(b))
2842
- throw new Error('Uint8Array expected');
2843
- if (lengths.length > 0 && !lengths.includes(b.length))
2844
- throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);
2845
- }
2846
- function exists(instance, checkFinished = true) {
2847
- if (instance.destroyed)
2848
- throw new Error('Hash instance has been destroyed');
2849
- if (checkFinished && instance.finished)
2850
- throw new Error('Hash#digest() has already been called');
2851
- }
2852
- function output(out, instance) {
2853
- bytes(out);
2854
- const min = instance.outputLen;
2855
- if (out.length < min) {
2856
- throw new Error(`digestInto() expects output buffer of length at least ${min}`);
2857
- }
2858
- }
2859
-
2860
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2861
- // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
2862
- // node.js versions earlier than v19 don't declare it in global scope.
2863
- // For node.js, package.json#exports field mapping rewrites import
2864
- // from `crypto` to `cryptoNode`, which imports native module.
2865
- // Makes the utils un-importable in browsers without a bundler.
2866
- // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
2867
- // Cast array to view
2868
- const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
2869
- // The rotate right (circular right shift) operation for uint32
2870
- const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
2871
- new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
2872
- // Array where index 0xf0 (240) is mapped to string 'f0'
2873
- const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
2874
- /**
2875
- * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
2876
- */
2877
- function bytesToHex(bytes$1) {
2878
- bytes(bytes$1);
2879
- // pre-caching improves the speed 6x
2880
- let hex = '';
2881
- for (let i = 0; i < bytes$1.length; i++) {
2882
- hex += hexes[bytes$1[i]];
2883
- }
2884
- return hex;
2885
- }
2886
- /**
2887
- * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
2888
- */
2889
- function utf8ToBytes(str) {
2890
- if (typeof str !== 'string')
2891
- throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
2892
- return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
2893
- }
2894
- /**
2895
- * Normalizes (non-hex) string or Uint8Array to Uint8Array.
2896
- * Warning: when Uint8Array is passed, it would NOT get copied.
2897
- * Keep in mind for future mutable operations.
2898
- */
2899
- function toBytes(data) {
2900
- if (typeof data === 'string')
2901
- data = utf8ToBytes(data);
2902
- bytes(data);
2903
- return data;
2904
- }
2905
- // For runtime check if class implements interface
2906
- class Hash {
2907
- // Safe version that clones internal state
2908
- clone() {
2909
- return this._cloneInto();
2910
- }
2911
- }
2912
- function wrapConstructor(hashCons) {
2913
- const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
2914
- const tmp = hashCons();
2915
- hashC.outputLen = tmp.outputLen;
2916
- hashC.blockLen = tmp.blockLen;
2917
- hashC.create = () => hashCons();
2918
- return hashC;
2919
- }
2920
-
2921
- /**
2922
- * Polyfill for Safari 14
2923
- */
2924
- function setBigUint64(view, byteOffset, value, isLE) {
2925
- if (typeof view.setBigUint64 === 'function')
2926
- return view.setBigUint64(byteOffset, value, isLE);
2927
- const _32n = BigInt(32);
2928
- const _u32_max = BigInt(0xffffffff);
2929
- const wh = Number((value >> _32n) & _u32_max);
2930
- const wl = Number(value & _u32_max);
2931
- const h = isLE ? 4 : 0;
2932
- const l = isLE ? 0 : 4;
2933
- view.setUint32(byteOffset + h, wh, isLE);
2934
- view.setUint32(byteOffset + l, wl, isLE);
2935
- }
2936
- /**
2937
- * Choice: a ? b : c
2938
- */
2939
- const Chi = (a, b, c) => (a & b) ^ (~a & c);
2940
- /**
2941
- * Majority function, true if any two inputs is true
2942
- */
2943
- const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
2944
- /**
2945
- * Merkle-Damgard hash construction base class.
2946
- * Could be used to create MD5, RIPEMD, SHA1, SHA2.
2947
- */
2948
- class HashMD extends Hash {
2949
- constructor(blockLen, outputLen, padOffset, isLE) {
2950
- super();
2951
- this.blockLen = blockLen;
2952
- this.outputLen = outputLen;
2953
- this.padOffset = padOffset;
2954
- this.isLE = isLE;
2955
- this.finished = false;
2956
- this.length = 0;
2957
- this.pos = 0;
2958
- this.destroyed = false;
2959
- this.buffer = new Uint8Array(blockLen);
2960
- this.view = createView(this.buffer);
2961
- }
2962
- update(data) {
2963
- exists(this);
2964
- const { view, buffer, blockLen } = this;
2965
- data = toBytes(data);
2966
- const len = data.length;
2967
- for (let pos = 0; pos < len;) {
2968
- const take = Math.min(blockLen - this.pos, len - pos);
2969
- // Fast path: we have at least one block in input, cast it to view and process
2970
- if (take === blockLen) {
2971
- const dataView = createView(data);
2972
- for (; blockLen <= len - pos; pos += blockLen)
2973
- this.process(dataView, pos);
2974
- continue;
2975
- }
2976
- buffer.set(data.subarray(pos, pos + take), this.pos);
2977
- this.pos += take;
2978
- pos += take;
2979
- if (this.pos === blockLen) {
2980
- this.process(view, 0);
2981
- this.pos = 0;
2982
- }
2983
- }
2984
- this.length += data.length;
2985
- this.roundClean();
2986
- return this;
2987
- }
2988
- digestInto(out) {
2989
- exists(this);
2990
- output(out, this);
2991
- this.finished = true;
2992
- // Padding
2993
- // We can avoid allocation of buffer for padding completely if it
2994
- // was previously not allocated here. But it won't change performance.
2995
- const { buffer, view, blockLen, isLE } = this;
2996
- let { pos } = this;
2997
- // append the bit '1' to the message
2998
- buffer[pos++] = 0b10000000;
2999
- this.buffer.subarray(pos).fill(0);
3000
- // we have less than padOffset left in buffer, so we cannot put length in
3001
- // current block, need process it and pad again
3002
- if (this.padOffset > blockLen - pos) {
3003
- this.process(view, 0);
3004
- pos = 0;
3005
- }
3006
- // Pad until full block byte with zeros
3007
- for (let i = pos; i < blockLen; i++)
3008
- buffer[i] = 0;
3009
- // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
3010
- // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
3011
- // So we just write lowest 64 bits of that value.
3012
- setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
3013
- this.process(view, 0);
3014
- const oview = createView(out);
3015
- const len = this.outputLen;
3016
- // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
3017
- if (len % 4)
3018
- throw new Error('_sha2: outputLen should be aligned to 32bit');
3019
- const outLen = len / 4;
3020
- const state = this.get();
3021
- if (outLen > state.length)
3022
- throw new Error('_sha2: outputLen bigger than state');
3023
- for (let i = 0; i < outLen; i++)
3024
- oview.setUint32(4 * i, state[i], isLE);
3025
- }
3026
- digest() {
3027
- const { buffer, outputLen } = this;
3028
- this.digestInto(buffer);
3029
- const res = buffer.slice(0, outputLen);
3030
- this.destroy();
3031
- return res;
3032
- }
3033
- _cloneInto(to) {
3034
- to || (to = new this.constructor());
3035
- to.set(...this.get());
3036
- const { blockLen, buffer, length, finished, destroyed, pos } = this;
3037
- to.length = length;
3038
- to.pos = pos;
3039
- to.finished = finished;
3040
- to.destroyed = destroyed;
3041
- if (length % blockLen)
3042
- to.buffer.set(buffer);
3043
- return to;
3044
- }
3045
- }
3046
-
3047
- // SHA2-256 need to try 2^128 hashes to execute birthday attack.
3048
- // BTC network is doing 2^67 hashes/sec as per early 2023.
3049
- // Round constants:
3050
- // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
3051
- // prettier-ignore
3052
- const SHA256_K = /* @__PURE__ */ new Uint32Array([
3053
- 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
3054
- 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
3055
- 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
3056
- 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
3057
- 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
3058
- 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
3059
- 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
3060
- 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
3061
- ]);
3062
- // Initial state:
3063
- // first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19
3064
- // prettier-ignore
3065
- const SHA256_IV = /* @__PURE__ */ new Uint32Array([
3066
- 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
3067
- ]);
3068
- // Temporary buffer, not used to store anything between runs
3069
- // Named this way because it matches specification.
3070
- const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
3071
- class SHA256 extends HashMD {
3072
- constructor() {
3073
- super(64, 32, 8, false);
3074
- // We cannot use array here since array allows indexing by variable
3075
- // which means optimizer/compiler cannot use registers.
3076
- this.A = SHA256_IV[0] | 0;
3077
- this.B = SHA256_IV[1] | 0;
3078
- this.C = SHA256_IV[2] | 0;
3079
- this.D = SHA256_IV[3] | 0;
3080
- this.E = SHA256_IV[4] | 0;
3081
- this.F = SHA256_IV[5] | 0;
3082
- this.G = SHA256_IV[6] | 0;
3083
- this.H = SHA256_IV[7] | 0;
3084
- }
3085
- get() {
3086
- const { A, B, C, D, E, F, G, H } = this;
3087
- return [A, B, C, D, E, F, G, H];
3088
- }
3089
- // prettier-ignore
3090
- set(A, B, C, D, E, F, G, H) {
3091
- this.A = A | 0;
3092
- this.B = B | 0;
3093
- this.C = C | 0;
3094
- this.D = D | 0;
3095
- this.E = E | 0;
3096
- this.F = F | 0;
3097
- this.G = G | 0;
3098
- this.H = H | 0;
3099
- }
3100
- process(view, offset) {
3101
- // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
3102
- for (let i = 0; i < 16; i++, offset += 4)
3103
- SHA256_W[i] = view.getUint32(offset, false);
3104
- for (let i = 16; i < 64; i++) {
3105
- const W15 = SHA256_W[i - 15];
3106
- const W2 = SHA256_W[i - 2];
3107
- const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
3108
- const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
3109
- SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
3110
- }
3111
- // Compression function main loop, 64 rounds
3112
- let { A, B, C, D, E, F, G, H } = this;
3113
- for (let i = 0; i < 64; i++) {
3114
- const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
3115
- const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
3116
- const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
3117
- const T2 = (sigma0 + Maj(A, B, C)) | 0;
3118
- H = G;
3119
- G = F;
3120
- F = E;
3121
- E = (D + T1) | 0;
3122
- D = C;
3123
- C = B;
3124
- B = A;
3125
- A = (T1 + T2) | 0;
3126
- }
3127
- // Add the compressed chunk to the current hash value
3128
- A = (A + this.A) | 0;
3129
- B = (B + this.B) | 0;
3130
- C = (C + this.C) | 0;
3131
- D = (D + this.D) | 0;
3132
- E = (E + this.E) | 0;
3133
- F = (F + this.F) | 0;
3134
- G = (G + this.G) | 0;
3135
- H = (H + this.H) | 0;
3136
- this.set(A, B, C, D, E, F, G, H);
3137
- }
3138
- roundClean() {
3139
- SHA256_W.fill(0);
3140
- }
3141
- destroy() {
3142
- this.set(0, 0, 0, 0, 0, 0, 0, 0);
3143
- this.buffer.fill(0);
3144
- }
3145
- }
3146
- /**
3147
- * SHA2-256 hash function
3148
- * @param message - data that would be hashed
3149
- */
3150
- const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
3151
-
3152
- // Copyright (c) 2018-2023 Coinbase, Inc. <https://www.coinbase.com/>
3153
- const STORAGE_KEY_SESSION_ID = 'session:id';
3154
- const STORAGE_KEY_SESSION_SECRET = 'session:secret';
3155
- const STORAGE_KEY_SESSION_LINKED = 'session:linked';
3156
- class WalletLinkSession {
3157
- constructor(storage, id, secret, linked = false) {
3158
- this.storage = storage;
3159
- this.id = id;
3160
- this.secret = secret;
3161
- this.key = bytesToHex(sha256(`${id}, ${secret} WalletLink`));
3162
- this._linked = !!linked;
3163
- }
3164
- static create(storage) {
3165
- const id = randomBytesHex(16);
3166
- const secret = randomBytesHex(32);
3167
- return new WalletLinkSession(storage, id, secret).save();
3168
- }
3169
- static load(storage) {
3170
- const id = storage.getItem(STORAGE_KEY_SESSION_ID);
3171
- const linked = storage.getItem(STORAGE_KEY_SESSION_LINKED);
3172
- const secret = storage.getItem(STORAGE_KEY_SESSION_SECRET);
3173
- if (id && secret) {
3174
- return new WalletLinkSession(storage, id, secret, linked === '1');
3175
- }
3176
- return null;
3177
- }
3178
- get linked() {
3179
- return this._linked;
3180
- }
3181
- set linked(val) {
3182
- this._linked = val;
3183
- this.persistLinked();
3184
- }
3185
- save() {
3186
- this.storage.setItem(STORAGE_KEY_SESSION_ID, this.id);
3187
- this.storage.setItem(STORAGE_KEY_SESSION_SECRET, this.secret);
3188
- this.persistLinked();
3189
- return this;
3190
- }
3191
- persistLinked() {
3192
- this.storage.setItem(STORAGE_KEY_SESSION_LINKED, this._linked ? '1' : '0');
3193
- }
3194
- }
3195
-
3196
- function isInIFrame() {
3197
- try {
3198
- return window.frameElement !== null;
3199
- }
3200
- catch (e) {
3201
- return false;
3202
- }
3203
- }
3204
- function getLocation() {
3205
- try {
3206
- if (isInIFrame() && window.top) {
3207
- return window.top.location;
3208
- }
3209
- return window.location;
3210
- }
3211
- catch (e) {
3212
- return window.location;
3213
- }
3214
- }
3215
- function isMobileWeb() {
3216
- var _a;
3217
- return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test((_a = window === null || window === void 0 ? void 0 : window.navigator) === null || _a === void 0 ? void 0 : _a.userAgent);
3218
- }
3219
- function isDarkMode() {
3220
- var _a, _b;
3221
- return (_b = (_a = window === null || window === void 0 ? void 0 : window.matchMedia) === null || _a === void 0 ? void 0 : _a.call(window, '(prefers-color-scheme: dark)').matches) !== null && _b !== void 0 ? _b : false;
3222
- }
3223
-
3224
- var css$2 = (() => `@namespace svg "http://www.w3.org/2000/svg";.-cbwsdk-css-reset,.-cbwsdk-css-reset *{animation:none;animation-delay:0;animation-direction:normal;animation-duration:0;animation-fill-mode:none;animation-iteration-count:1;animation-name:none;animation-play-state:running;animation-timing-function:ease;backface-visibility:visible;background:0;background-attachment:scroll;background-clip:border-box;background-color:rgba(0,0,0,0);background-image:none;background-origin:padding-box;background-position:0 0;background-position-x:0;background-position-y:0;background-repeat:repeat;background-size:auto auto;border:0;border-style:none;border-width:medium;border-color:inherit;border-bottom:0;border-bottom-color:inherit;border-bottom-left-radius:0;border-bottom-right-radius:0;border-bottom-style:none;border-bottom-width:medium;border-collapse:separate;border-image:none;border-left:0;border-left-color:inherit;border-left-style:none;border-left-width:medium;border-radius:0;border-right:0;border-right-color:inherit;border-right-style:none;border-right-width:medium;border-spacing:0;border-top:0;border-top-color:inherit;border-top-left-radius:0;border-top-right-radius:0;border-top-style:none;border-top-width:medium;box-shadow:none;box-sizing:border-box;caption-side:top;clear:none;clip:auto;color:inherit;columns:auto;column-count:auto;column-fill:balance;column-gap:normal;column-rule:medium none currentColor;column-rule-color:currentColor;column-rule-style:none;column-rule-width:none;column-span:1;column-width:auto;counter-increment:none;counter-reset:none;direction:ltr;empty-cells:show;float:none;font:normal;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;font-size:medium;font-style:normal;font-variant:normal;font-weight:normal;height:auto;hyphens:none;letter-spacing:normal;line-height:normal;list-style:none;list-style-image:none;list-style-position:outside;list-style-type:disc;margin:0;margin-bottom:0;margin-left:0;margin-right:0;margin-top:0;opacity:1;orphans:0;outline:0;outline-color:invert;outline-style:none;outline-width:medium;overflow:visible;overflow-x:visible;overflow-y:visible;padding:0;padding-bottom:0;padding-left:0;padding-right:0;padding-top:0;page-break-after:auto;page-break-before:auto;page-break-inside:auto;perspective:none;perspective-origin:50% 50%;pointer-events:auto;position:static;quotes:"\\201C" "\\201D" "\\2018" "\\2019";tab-size:8;table-layout:auto;text-align:inherit;text-align-last:auto;text-decoration:none;text-decoration-color:inherit;text-decoration-line:none;text-decoration-style:solid;text-indent:0;text-shadow:none;text-transform:none;transform:none;transform-style:flat;transition:none;transition-delay:0s;transition-duration:0s;transition-property:none;transition-timing-function:ease;unicode-bidi:normal;vertical-align:baseline;visibility:visible;white-space:normal;widows:0;word-spacing:normal;z-index:auto}.-cbwsdk-css-reset strong{font-weight:bold}.-cbwsdk-css-reset *{box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;line-height:1}.-cbwsdk-css-reset [class*=container]{margin:0;padding:0}.-cbwsdk-css-reset style{display:none}`)();
3225
-
3226
- // Copyright (c) 2018-2023 Coinbase, Inc. <https://www.coinbase.com/>
3227
- function injectCssReset() {
3228
- const styleEl = document.createElement('style');
3229
- styleEl.type = 'text/css';
3230
- styleEl.appendChild(document.createTextNode(css$2));
3231
- document.documentElement.appendChild(styleEl);
3232
- }
3233
-
3234
- var n,l$1,u$1,i$1,o$1,r$1,f$1,e$1,c$1,s$1,h$1={},v$1=[],p$1=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,y$1=Array.isArray;function d$1(n,l){for(var u in l)n[u]=l[u];return n}function w$1(n){n&&n.parentNode&&n.parentNode.removeChild(n);}function _(l,u,t){var i,o,r,f={};for(r in u)"key"==r?i=u[r]:"ref"==r?o=u[r]:f[r]=u[r];if(arguments.length>2&&(f.children=arguments.length>3?n.call(arguments,2):t),"function"==typeof l&&null!=l.defaultProps)for(r in l.defaultProps) void 0===f[r]&&(f[r]=l.defaultProps[r]);return g(l,f,i,o,null)}function g(n,t,i,o,r){var f={type:n,props:t,key:i,ref:o,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,constructor:void 0,__v:null==r?++u$1:r,__i:-1,__u:0};return null==r&&null!=l$1.vnode&&l$1.vnode(f),f}function b(n){return n.children}function k$1(n,l){this.props=n,this.context=l;}function x(n,l){if(null==l)return n.__?x(n.__,n.__i+1):null;for(var u;l<n.__k.length;l++)if(null!=(u=n.__k[l])&&null!=u.__e)return u.__e;return "function"==typeof n.type?x(n):null}function C$1(n){var l,u;if(null!=(n=n.__)&&null!=n.__c){for(n.__e=n.__c.base=null,l=0;l<n.__k.length;l++)if(null!=(u=n.__k[l])&&null!=u.__e){n.__e=n.__c.base=u.__e;break}return C$1(n)}}function S(n){(!n.__d&&(n.__d=true)&&i$1.push(n)&&!M.__r++||o$1!==l$1.debounceRendering)&&((o$1=l$1.debounceRendering)||r$1)(M);}function M(){var n,u,t,o,r,e,c,s;for(i$1.sort(f$1);n=i$1.shift();)n.__d&&(u=i$1.length,o=void 0,e=(r=(t=n).__v).__e,c=[],s=[],t.__P&&((o=d$1({},r)).__v=r.__v+1,l$1.vnode&&l$1.vnode(o),O(t.__P,o,r,t.__n,t.__P.namespaceURI,32&r.__u?[e]:null,c,null==e?x(r):e,!!(32&r.__u),s),o.__v=r.__v,o.__.__k[o.__i]=o,j$1(c,o,s),o.__e!=e&&C$1(o)),i$1.length>u&&i$1.sort(f$1));M.__r=0;}function P(n,l,u,t,i,o,r,f,e,c,s){var a,p,y,d,w,_=t&&t.__k||v$1,g=l.length;for(u.__d=e,$(u,l,_),e=u.__d,a=0;a<g;a++)null!=(y=u.__k[a])&&(p=-1===y.__i?h$1:_[y.__i]||h$1,y.__i=a,O(n,y,p,i,o,r,f,e,c,s),d=y.__e,y.ref&&p.ref!=y.ref&&(p.ref&&E(p.ref,null,y),s.push(y.ref,y.__c||d,y)),null==w&&null!=d&&(w=d),65536&y.__u||p.__k===y.__k?e=I(y,e,n):"function"==typeof y.type&&void 0!==y.__d?e=y.__d:d&&(e=d.nextSibling),y.__d=void 0,y.__u&=-196609);u.__d=e,u.__e=w;}function $(n,l,u){var t,i,o,r,f,e=l.length,c=u.length,s=c,a=0;for(n.__k=[],t=0;t<e;t++)null!=(i=l[t])&&"boolean"!=typeof i&&"function"!=typeof i?(r=t+a,(i=n.__k[t]="string"==typeof i||"number"==typeof i||"bigint"==typeof i||i.constructor==String?g(null,i,null,null,null):y$1(i)?g(b,{children:i},null,null,null):void 0===i.constructor&&i.__b>0?g(i.type,i.props,i.key,i.ref?i.ref:null,i.__v):i).__=n,i.__b=n.__b+1,o=null,-1!==(f=i.__i=L(i,u,r,s))&&(s--,(o=u[f])&&(o.__u|=131072)),null==o||null===o.__v?(-1==f&&a--,"function"!=typeof i.type&&(i.__u|=65536)):f!==r&&(f==r-1?a--:f==r+1?a++:(f>r?a--:a++,i.__u|=65536))):i=n.__k[t]=null;if(s)for(t=0;t<c;t++)null!=(o=u[t])&&0==(131072&o.__u)&&(o.__e==n.__d&&(n.__d=x(o)),N(o,o));}function I(n,l,u){var t,i;if("function"==typeof n.type){for(t=n.__k,i=0;t&&i<t.length;i++)t[i]&&(t[i].__=n,l=I(t[i],l,u));return l}n.__e!=l&&(l&&n.type&&!u.contains(l)&&(l=x(n)),u.insertBefore(n.__e,l||null),l=n.__e);do{l=l&&l.nextSibling;}while(null!=l&&8===l.nodeType);return l}function L(n,l,u,t){var i=n.key,o=n.type,r=u-1,f=u+1,e=l[u];if(null===e||e&&i==e.key&&o===e.type&&0==(131072&e.__u))return u;if(("function"!=typeof o||o===b||i)&&t>(null!=e&&0==(131072&e.__u)?1:0))for(;r>=0||f<l.length;){if(r>=0){if((e=l[r])&&0==(131072&e.__u)&&i==e.key&&o===e.type)return r;r--;}if(f<l.length){if((e=l[f])&&0==(131072&e.__u)&&i==e.key&&o===e.type)return f;f++;}}return -1}function T(n,l,u){"-"===l[0]?n.setProperty(l,null==u?"":u):n[l]=null==u?"":"number"!=typeof u||p$1.test(l)?u:u+"px";}function A(n,l,u,t,i){var o;n:if("style"===l)if("string"==typeof u)n.style.cssText=u;else {if("string"==typeof t&&(n.style.cssText=t=""),t)for(l in t)u&&l in u||T(n.style,l,"");if(u)for(l in u)t&&u[l]===t[l]||T(n.style,l,u[l]);}else if("o"===l[0]&&"n"===l[1])o=l!==(l=l.replace(/(PointerCapture)$|Capture$/i,"$1")),l=l.toLowerCase()in n||"onFocusOut"===l||"onFocusIn"===l?l.toLowerCase().slice(2):l.slice(2),n.l||(n.l={}),n.l[l+o]=u,u?t?u.u=t.u:(u.u=e$1,n.addEventListener(l,o?s$1:c$1,o)):n.removeEventListener(l,o?s$1:c$1,o);else {if("http://www.w3.org/2000/svg"==i)l=l.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=l&&"height"!=l&&"href"!=l&&"list"!=l&&"form"!=l&&"tabIndex"!=l&&"download"!=l&&"rowSpan"!=l&&"colSpan"!=l&&"role"!=l&&"popover"!=l&&l in n)try{n[l]=null==u?"":u;break n}catch(n){}"function"==typeof u||(null==u||false===u&&"-"!==l[4]?n.removeAttribute(l):n.setAttribute(l,"popover"==l&&1==u?"":u));}}function F(n){return function(u){if(this.l){var t=this.l[u.type+n];if(null==u.t)u.t=e$1++;else if(u.t<t.u)return;return l$1.event&&(u=l$1.event(u)),"handleEvent"in t?t.handleEvent(u):t(u)}}}function O(n,u,t,i,o,r,f,e,c,s){var a,h,v,p,w,_,g,m,x,C,S,M,$,I,H,L,T=u.type;if(void 0!==u.constructor)return null;128&t.__u&&(c=!!(32&t.__u),r=[e=u.__e=t.__e]),(a=l$1.__b)&&a(u);n:if("function"==typeof T)try{if(m=u.props,x="prototype"in T&&T.prototype.render,C=(a=T.contextType)&&i[a.__c],S=a?C?C.props.value:a.__:i,t.__c?g=(h=u.__c=t.__c).__=h.__E:(x?u.__c=h=new T(m,S):(u.__c=h=new k$1(m,S),h.constructor=T,h.render=V),C&&C.sub(h),h.props=m,h.state||(h.state={}),h.context=S,h.__n=i,v=h.__d=!0,h.__h=[],h._sb=[]),x&&null==h.__s&&(h.__s=h.state),x&&null!=T.getDerivedStateFromProps&&(h.__s==h.state&&(h.__s=d$1({},h.__s)),d$1(h.__s,T.getDerivedStateFromProps(m,h.__s))),p=h.props,w=h.state,h.__v=u,v)x&&null==T.getDerivedStateFromProps&&null!=h.componentWillMount&&h.componentWillMount(),x&&null!=h.componentDidMount&&h.__h.push(h.componentDidMount);else {if(x&&null==T.getDerivedStateFromProps&&m!==p&&null!=h.componentWillReceiveProps&&h.componentWillReceiveProps(m,S),!h.__e&&(null!=h.shouldComponentUpdate&&!1===h.shouldComponentUpdate(m,h.__s,S)||u.__v===t.__v)){for(u.__v!==t.__v&&(h.props=m,h.state=h.__s,h.__d=!1),u.__e=t.__e,u.__k=t.__k,u.__k.some(function(n){n&&(n.__=u);}),M=0;M<h._sb.length;M++)h.__h.push(h._sb[M]);h._sb=[],h.__h.length&&f.push(h);break n}null!=h.componentWillUpdate&&h.componentWillUpdate(m,h.__s,S),x&&null!=h.componentDidUpdate&&h.__h.push(function(){h.componentDidUpdate(p,w,_);});}if(h.context=S,h.props=m,h.__P=n,h.__e=!1,$=l$1.__r,I=0,x){for(h.state=h.__s,h.__d=!1,$&&$(u),a=h.render(h.props,h.state,h.context),H=0;H<h._sb.length;H++)h.__h.push(h._sb[H]);h._sb=[];}else do{h.__d=!1,$&&$(u),a=h.render(h.props,h.state,h.context),h.state=h.__s;}while(h.__d&&++I<25);h.state=h.__s,null!=h.getChildContext&&(i=d$1(d$1({},i),h.getChildContext())),x&&!v&&null!=h.getSnapshotBeforeUpdate&&(_=h.getSnapshotBeforeUpdate(p,w)),P(n,y$1(L=null!=a&&a.type===b&&null==a.key?a.props.children:a)?L:[L],u,t,i,o,r,f,e,c,s),h.base=u.__e,u.__u&=-161,h.__h.length&&f.push(h),g&&(h.__E=h.__=null);}catch(n){if(u.__v=null,c||null!=r){for(u.__u|=c?160:128;e&&8===e.nodeType&&e.nextSibling;)e=e.nextSibling;r[r.indexOf(e)]=null,u.__e=e;}else u.__e=t.__e,u.__k=t.__k;l$1.__e(n,u,t);}else null==r&&u.__v===t.__v?(u.__k=t.__k,u.__e=t.__e):u.__e=z$1(t.__e,u,t,i,o,r,f,c,s);(a=l$1.diffed)&&a(u);}function j$1(n,u,t){u.__d=void 0;for(var i=0;i<t.length;i++)E(t[i],t[++i],t[++i]);l$1.__c&&l$1.__c(u,n),n.some(function(u){try{n=u.__h,u.__h=[],n.some(function(n){n.call(u);});}catch(n){l$1.__e(n,u.__v);}});}function z$1(u,t,i,o,r,f,e,c,s){var a,v,p,d,_,g,m,b=i.props,k=t.props,C=t.type;if("svg"===C?r="http://www.w3.org/2000/svg":"math"===C?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),null!=f)for(a=0;a<f.length;a++)if((_=f[a])&&"setAttribute"in _==!!C&&(C?_.localName===C:3===_.nodeType)){u=_,f[a]=null;break}if(null==u){if(null===C)return document.createTextNode(k);u=document.createElementNS(r,C,k.is&&k),c&&(l$1.__m&&l$1.__m(t,f),c=false),f=null;}if(null===C)b===k||c&&u.data===k||(u.data=k);else {if(f=f&&n.call(u.childNodes),b=i.props||h$1,!c&&null!=f)for(b={},a=0;a<u.attributes.length;a++)b[(_=u.attributes[a]).name]=_.value;for(a in b)if(_=b[a],"children"==a);else if("dangerouslySetInnerHTML"==a)p=_;else if(!(a in k)){if("value"==a&&"defaultValue"in k||"checked"==a&&"defaultChecked"in k)continue;A(u,a,null,_,r);}for(a in k)_=k[a],"children"==a?d=_:"dangerouslySetInnerHTML"==a?v=_:"value"==a?g=_:"checked"==a?m=_:c&&"function"!=typeof _||b[a]===_||A(u,a,_,b[a],r);if(v)c||p&&(v.__html===p.__html||v.__html===u.innerHTML)||(u.innerHTML=v.__html),t.__k=[];else if(p&&(u.innerHTML=""),P(u,y$1(d)?d:[d],t,i,o,"foreignObject"===C?"http://www.w3.org/1999/xhtml":r,f,e,f?f[0]:i.__k&&x(i,0),c,s),null!=f)for(a=f.length;a--;)w$1(f[a]);c||(a="value","progress"===C&&null==g?u.removeAttribute("value"):void 0!==g&&(g!==u[a]||"progress"===C&&!g||"option"===C&&g!==b[a])&&A(u,a,g,b[a],r),a="checked",void 0!==m&&m!==u[a]&&A(u,a,m,b[a],r));}return u}function E(n,u,t){try{if("function"==typeof n){var i="function"==typeof n.__u;i&&n.__u(),i&&null==u||(n.__u=n(u));}else n.current=u;}catch(n){l$1.__e(n,t);}}function N(n,u,t){var i,o;if(l$1.unmount&&l$1.unmount(n),(i=n.ref)&&(i.current&&i.current!==n.__e||E(i,null,u)),null!=(i=n.__c)){if(i.componentWillUnmount)try{i.componentWillUnmount();}catch(n){l$1.__e(n,u);}i.base=i.__P=null;}if(i=n.__k)for(o=0;o<i.length;o++)i[o]&&N(i[o],u,t||"function"!=typeof n.type);t||w$1(n.__e),n.__c=n.__=n.__e=n.__d=void 0;}function V(n,l,u){return this.constructor(n,u)}function q(u,t,i){var o,r,f,e;l$1.__&&l$1.__(u,t),r=(o="function"=="undefined")?null:t.__k,f=[],e=[],O(t,u=(t).__k=_(b,null,[u]),r||h$1,h$1,t.namespaceURI,r?null:t.firstChild?n.call(t.childNodes):null,f,r?r.__e:t.firstChild,o,e),j$1(f,u,e);}n=v$1.slice,l$1={__e:function(n,l,u,t){for(var i,o,r;l=l.__;)if((i=l.__c)&&!i.__)try{if((o=i.constructor)&&null!=o.getDerivedStateFromError&&(i.setState(o.getDerivedStateFromError(n)),r=i.__d),null!=i.componentDidCatch&&(i.componentDidCatch(n,t||{}),r=i.__d),r)return i.__E=i}catch(l){n=l;}throw n}},u$1=0,k$1.prototype.setState=function(n,l){var u;u=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=d$1({},this.state),"function"==typeof n&&(n=n(d$1({},u),this.props)),n&&d$1(u,n),null!=n&&this.__v&&(l&&this._sb.push(l),S(this));},k$1.prototype.forceUpdate=function(n){this.__v&&(this.__e=true,n&&this.__h.push(n),S(this));},k$1.prototype.render=b,i$1=[],r$1="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,f$1=function(n,l){return n.__v.__b-l.__v.__b},M.__r=0,e$1=0,c$1=F(false),s$1=F(true);
3235
-
3236
- var t,r,u,i,o=0,f=[],c=l$1,e=c.__b,a=c.__r,v=c.diffed,l=c.__c,m=c.unmount,s=c.__;function d(n,t){c.__h&&c.__h(r,n,o||t),o=0;var u=r.__H||(r.__H={__:[],__h:[]});return n>=u.__.length&&u.__.push({}),u.__[n]}function h(n){return o=1,p(D,n)}function p(n,u,i){var o=d(t++,2);if(o.t=n,!o.__c&&(o.__=[D(void 0,u),function(n){var t=o.__N?o.__N[0]:o.__[0],r=o.t(t,n);t!==r&&(o.__N=[r,o.__[1]],o.__c.setState({}));}],o.__c=r,!r.u)){var f=function(n,t,r){if(!o.__c.__H)return true;var u=o.__c.__H.__.filter(function(n){return !!n.__c});if(u.every(function(n){return !n.__N}))return !c||c.call(this,n,t,r);var i=o.__c.props!==n;return u.forEach(function(n){if(n.__N){var t=n.__[0];n.__=n.__N,n.__N=void 0,t!==n.__[0]&&(i=true);}}),c&&c.call(this,n,t,r)||i};r.u=true;var c=r.shouldComponentUpdate,e=r.componentWillUpdate;r.componentWillUpdate=function(n,t,r){if(this.__e){var u=c;c=void 0,f(n,t,r),c=u;}e&&e.call(this,n,t,r);},r.shouldComponentUpdate=f;}return o.__N||o.__}function y(n,u){var i=d(t++,3);!c.__s&&C(i.__H,u)&&(i.__=n,i.i=u,r.__H.__h.push(i));}function j(){for(var n;n=f.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(z),n.__H.__h.forEach(B),n.__H.__h=[];}catch(t){n.__H.__h=[],c.__e(t,n.__v);}}c.__b=function(n){r=null,e&&e(n);},c.__=function(n,t){n&&t.__k&&t.__k.__m&&(n.__m=t.__k.__m),s&&s(n,t);},c.__r=function(n){a&&a(n),t=0;var i=(r=n.__c).__H;i&&(u===r?(i.__h=[],r.__h=[],i.__.forEach(function(n){n.__N&&(n.__=n.__N),n.i=n.__N=void 0;})):(i.__h.forEach(z),i.__h.forEach(B),i.__h=[],t=0)),u=r;},c.diffed=function(n){v&&v(n);var t=n.__c;t&&t.__H&&(t.__H.__h.length&&(1!==f.push(t)&&i===c.requestAnimationFrame||((i=c.requestAnimationFrame)||w)(j)),t.__H.__.forEach(function(n){n.i&&(n.__H=n.i),n.i=void 0;})),u=r=null;},c.__c=function(n,t){t.some(function(n){try{n.__h.forEach(z),n.__h=n.__h.filter(function(n){return !n.__||B(n)});}catch(r){t.some(function(n){n.__h&&(n.__h=[]);}),t=[],c.__e(r,n.__v);}}),l&&l(n,t);},c.unmount=function(n){m&&m(n);var t,r=n.__c;r&&r.__H&&(r.__H.__.forEach(function(n){try{z(n);}catch(n){t=n;}}),r.__H=void 0,t&&c.__e(t,r.__v));};var k="function"==typeof requestAnimationFrame;function w(n){var t,r=function(){clearTimeout(u),k&&cancelAnimationFrame(t),setTimeout(n);},u=setTimeout(r,100);k&&(t=requestAnimationFrame(r));}function z(n){var t=r,u=n.__c;"function"==typeof u&&(n.__c=void 0,u()),r=t;}function B(n){var t=r;n.__c=n.__(),r=t;}function C(n,t){return !n||n.length!==t.length||t.some(function(t,r){return t!==n[r]})}function D(n,t){return "function"==typeof t?t(n):t}
3237
-
3238
- var css$1 = (() => `.-cbwsdk-css-reset .-gear-container{margin-left:16px !important;margin-right:9px !important;display:flex;align-items:center;justify-content:center;width:24px;height:24px;transition:opacity .25s}.-cbwsdk-css-reset .-gear-container *{user-select:none}.-cbwsdk-css-reset .-gear-container svg{opacity:0;position:absolute}.-cbwsdk-css-reset .-gear-icon{height:12px;width:12px;z-index:10000}.-cbwsdk-css-reset .-cbwsdk-snackbar{align-items:flex-end;display:flex;flex-direction:column;position:fixed;right:0;top:0;z-index:2147483647}.-cbwsdk-css-reset .-cbwsdk-snackbar *{user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance{display:flex;flex-direction:column;margin:8px 16px 0 16px;overflow:visible;text-align:left;transform:translateX(0);transition:opacity .25s,transform .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header:hover .-gear-container svg{opacity:1}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header{display:flex;align-items:center;background:#fff;overflow:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-cblogo{margin:8px 8px 8px 8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-message{color:#000;font-size:13px;line-height:1.5;user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu{background:#fff;transition:opacity .25s ease-in-out,transform .25s linear,visibility 0s;visibility:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;opacity:0;flex-direction:column;padding-left:8px;padding-right:8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:last-child{margin-bottom:8px !important}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover{background:#f5f7f8;border-radius:6px;transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover span{color:#050f19;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover svg path{fill:#000;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item{visibility:inherit;height:35px;margin-top:8px;margin-bottom:0;display:flex;flex-direction:row;align-items:center;padding:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item *{visibility:inherit;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover{background:rgba(223,95,103,.2);transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover svg path{fill:#df5f67;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover span{color:#df5f67;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-info{color:#aaa;font-size:13px;margin:0 8px 0 32px;position:absolute}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-hidden{opacity:0;text-align:left;transform:translateX(25%);transition:opacity .5s linear}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-expanded .-cbwsdk-snackbar-instance-menu{opacity:1;display:flex;transform:translateY(8px);visibility:visible}`)();
3239
-
3240
- // Copyright (c) 2018-2023 Coinbase, Inc. <https://www.coinbase.com/>
3241
- const cblogo = `data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEuNDkyIDEwLjQxOWE4LjkzIDguOTMgMCAwMTguOTMtOC45M2gxMS4xNjNhOC45MyA4LjkzIDAgMDE4LjkzIDguOTN2MTEuMTYzYTguOTMgOC45MyAwIDAxLTguOTMgOC45M0gxMC40MjJhOC45MyA4LjkzIDAgMDEtOC45My04LjkzVjEwLjQxOXoiIGZpbGw9IiMxNjUyRjAiLz48cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEwLjQxOSAwSDIxLjU4QzI3LjMzNSAwIDMyIDQuNjY1IDMyIDEwLjQxOVYyMS41OEMzMiAyNy4zMzUgMjcuMzM1IDMyIDIxLjU4MSAzMkgxMC40MkM0LjY2NSAzMiAwIDI3LjMzNSAwIDIxLjU4MVYxMC40MkMwIDQuNjY1IDQuNjY1IDAgMTAuNDE5IDB6bTAgMS40ODhhOC45MyA4LjkzIDAgMDAtOC45MyA4LjkzdjExLjE2M2E4LjkzIDguOTMgMCAwMDguOTMgOC45M0gyMS41OGE4LjkzIDguOTMgMCAwMDguOTMtOC45M1YxMC40MmE4LjkzIDguOTMgMCAwMC04LjkzLTguOTNIMTAuNDJ6IiBmaWxsPSIjZmZmIi8+PHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xNS45OTggMjYuMDQ5Yy01LjU0OSAwLTEwLjA0Ny00LjQ5OC0xMC4wNDctMTAuMDQ3IDAtNS41NDggNC40OTgtMTAuMDQ2IDEwLjA0Ny0xMC4wNDYgNS41NDggMCAxMC4wNDYgNC40OTggMTAuMDQ2IDEwLjA0NiAwIDUuNTQ5LTQuNDk4IDEwLjA0Ny0xMC4wNDYgMTAuMDQ3eiIgZmlsbD0iI2ZmZiIvPjxwYXRoIGQ9Ik0xMi43NjIgMTQuMjU0YzAtLjgyMi42NjctMS40ODkgMS40ODktMS40ODloMy40OTdjLjgyMiAwIDEuNDg4LjY2NiAxLjQ4OCAxLjQ4OXYzLjQ5N2MwIC44MjItLjY2NiAxLjQ4OC0xLjQ4OCAxLjQ4OGgtMy40OTdhMS40ODggMS40ODggMCAwMS0xLjQ4OS0xLjQ4OHYtMy40OTh6IiBmaWxsPSIjMTY1MkYwIi8+PC9zdmc+`;
3242
- const gearIcon = `data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEyIDYuNzV2LTEuNWwtMS43Mi0uNTdjLS4wOC0uMjctLjE5LS41Mi0uMzItLjc3bC44MS0xLjYyLTEuMDYtMS4wNi0xLjYyLjgxYy0uMjQtLjEzLS41LS4yNC0uNzctLjMyTDYuNzUgMGgtMS41bC0uNTcgMS43MmMtLjI3LjA4LS41My4xOS0uNzcuMzJsLTEuNjItLjgxLTEuMDYgMS4wNi44MSAxLjYyYy0uMTMuMjQtLjI0LjUtLjMyLjc3TDAgNS4yNXYxLjVsMS43Mi41N2MuMDguMjcuMTkuNTMuMzIuNzdsLS44MSAxLjYyIDEuMDYgMS4wNiAxLjYyLS44MWMuMjQuMTMuNS4yMy43Ny4zMkw1LjI1IDEyaDEuNWwuNTctMS43MmMuMjctLjA4LjUyLS4xOS43Ny0uMzJsMS42Mi44MSAxLjA2LTEuMDYtLjgxLTEuNjJjLjEzLS4yNC4yMy0uNS4zMi0uNzdMMTIgNi43NXpNNiA4LjVhMi41IDIuNSAwIDAxMC01IDIuNSAyLjUgMCAwMTAgNXoiIGZpbGw9IiMwNTBGMTkiLz48L3N2Zz4=`;
3243
- class Snackbar {
3244
- constructor() {
3245
- this.items = new Map();
3246
- this.nextItemKey = 0;
3247
- this.root = null;
3248
- this.darkMode = isDarkMode();
3249
- }
3250
- attach(el) {
3251
- this.root = document.createElement('div');
3252
- this.root.className = '-cbwsdk-snackbar-root';
3253
- el.appendChild(this.root);
3254
- this.render();
3255
- }
3256
- presentItem(itemProps) {
3257
- const key = this.nextItemKey++;
3258
- this.items.set(key, itemProps);
3259
- this.render();
3260
- return () => {
3261
- this.items.delete(key);
3262
- this.render();
3263
- };
3264
- }
3265
- clear() {
3266
- this.items.clear();
3267
- this.render();
3268
- }
3269
- render() {
3270
- if (!this.root) {
3271
- return;
3272
- }
3273
- q(_("div", null,
3274
- _(SnackbarContainer, { darkMode: this.darkMode }, Array.from(this.items.entries()).map(([key, itemProps]) => (_(SnackbarInstance, Object.assign({}, itemProps, { key: key })))))), this.root);
3275
- }
3276
- }
3277
- const SnackbarContainer = (props) => (_("div", { class: clsx_m.clsx('-cbwsdk-snackbar-container') },
3278
- _("style", null, css$1),
3279
- _("div", { class: "-cbwsdk-snackbar" }, props.children)));
3280
- const SnackbarInstance = ({ autoExpand, message, menuItems, }) => {
3281
- const [hidden, setHidden] = h(true);
3282
- const [expanded, setExpanded] = h(autoExpand !== null && autoExpand !== void 0 ? autoExpand : false);
3283
- y(() => {
3284
- const timers = [
3285
- window.setTimeout(() => {
3286
- setHidden(false);
3287
- }, 1),
3288
- window.setTimeout(() => {
3289
- setExpanded(true);
3290
- }, 10000),
3291
- ];
3292
- return () => {
3293
- timers.forEach(window.clearTimeout);
3294
- };
3295
- });
3296
- const toggleExpanded = () => {
3297
- setExpanded(!expanded);
3298
- };
3299
- return (_("div", { class: clsx_m.clsx('-cbwsdk-snackbar-instance', hidden && '-cbwsdk-snackbar-instance-hidden', expanded && '-cbwsdk-snackbar-instance-expanded') },
3300
- _("div", { class: "-cbwsdk-snackbar-instance-header", onClick: toggleExpanded },
3301
- _("img", { src: cblogo, class: "-cbwsdk-snackbar-instance-header-cblogo" }),
3302
- ' ',
3303
- _("div", { class: "-cbwsdk-snackbar-instance-header-message" }, message),
3304
- _("div", { class: "-gear-container" },
3305
- !expanded && (_("svg", { width: "24", height: "24", viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
3306
- _("circle", { cx: "12", cy: "12", r: "12", fill: "#F5F7F8" }))),
3307
- _("img", { src: gearIcon, class: "-gear-icon", title: "Expand" }))),
3308
- menuItems && menuItems.length > 0 && (_("div", { class: "-cbwsdk-snackbar-instance-menu" }, menuItems.map((action, i) => (_("div", { class: clsx_m.clsx('-cbwsdk-snackbar-instance-menu-item', action.isRed && '-cbwsdk-snackbar-instance-menu-item-is-red'), onClick: action.onClick, key: i },
3309
- _("svg", { width: action.svgWidth, height: action.svgHeight, viewBox: "0 0 10 11", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
3310
- _("path", { "fill-rule": action.defaultFillRule, "clip-rule": action.defaultClipRule, d: action.path, fill: "#AAAAAA" })),
3311
- _("span", { class: clsx_m.clsx('-cbwsdk-snackbar-instance-menu-item-info', action.isRed && '-cbwsdk-snackbar-instance-menu-item-info-is-red') }, action.info))))))));
3312
- };
3313
-
3314
- class WalletLinkRelayUI {
3315
- constructor() {
3316
- this.attached = false;
3317
- this.snackbar = new Snackbar();
3318
- }
3319
- attach() {
3320
- if (this.attached) {
3321
- throw new Error('Coinbase Wallet SDK UI is already attached');
3322
- }
3323
- const el = document.documentElement;
3324
- const container = document.createElement('div');
3325
- container.className = '-cbwsdk-css-reset';
3326
- el.appendChild(container);
3327
- this.snackbar.attach(container);
3328
- this.attached = true;
3329
- injectCssReset();
3330
- }
3331
- showConnecting(options) {
3332
- let snackbarProps;
3333
- if (options.isUnlinkedErrorState) {
3334
- snackbarProps = {
3335
- autoExpand: true,
3336
- message: 'Connection lost',
3337
- menuItems: [
3338
- {
3339
- isRed: false,
3340
- info: 'Reset connection',
3341
- svgWidth: '10',
3342
- svgHeight: '11',
3343
- path: 'M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z',
3344
- defaultFillRule: 'evenodd',
3345
- defaultClipRule: 'evenodd',
3346
- onClick: options.onResetConnection,
3347
- },
3348
- ],
3349
- };
3350
- }
3351
- else {
3352
- snackbarProps = {
3353
- message: 'Confirm on phone',
3354
- menuItems: [
3355
- {
3356
- isRed: true,
3357
- info: 'Cancel transaction',
3358
- svgWidth: '11',
3359
- svgHeight: '11',
3360
- path: 'M10.3711 1.52346L9.21775 0.370117L5.37109 4.21022L1.52444 0.370117L0.371094 1.52346L4.2112 5.37012L0.371094 9.21677L1.52444 10.3701L5.37109 6.53001L9.21775 10.3701L10.3711 9.21677L6.53099 5.37012L10.3711 1.52346Z',
3361
- defaultFillRule: 'inherit',
3362
- defaultClipRule: 'inherit',
3363
- onClick: options.onCancel,
3364
- },
3365
- {
3366
- isRed: false,
3367
- info: 'Reset connection',
3368
- svgWidth: '10',
3369
- svgHeight: '11',
3370
- path: 'M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z',
3371
- defaultFillRule: 'evenodd',
3372
- defaultClipRule: 'evenodd',
3373
- onClick: options.onResetConnection,
3374
- },
3375
- ],
3376
- };
3377
- }
3378
- return this.snackbar.presentItem(snackbarProps);
3379
- }
3380
- }
3381
-
3382
- var css = (() => `.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;transition:opacity .25s;background-color:rgba(10,11,13,.5)}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop-hidden{opacity:0}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box{display:block;position:fixed;top:50%;left:50%;transform:translate(-50%, -50%);padding:20px;border-radius:8px;background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box p{display:block;font-weight:400;font-size:14px;line-height:20px;padding-bottom:12px;color:#5b636e}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box button{appearance:none;border:none;background:none;color:#0052ff;padding:0;text-decoration:none;display:block;font-weight:600;font-size:16px;line-height:24px}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark{background-color:#0a0b0d;color:#fff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark button{color:#0052ff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light{background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light button{color:#0052ff}`)();
3383
-
3384
- class RedirectDialog {
3385
- constructor() {
3386
- this.root = null;
3387
- this.darkMode = isDarkMode();
3388
- }
3389
- attach() {
3390
- const el = document.documentElement;
3391
- this.root = document.createElement('div');
3392
- this.root.className = '-cbwsdk-css-reset';
3393
- el.appendChild(this.root);
3394
- injectCssReset();
3395
- }
3396
- present(props) {
3397
- this.render(props);
3398
- }
3399
- clear() {
3400
- this.render(null);
3401
- }
3402
- render(props) {
3403
- if (!this.root)
3404
- return;
3405
- q(null, this.root);
3406
- if (!props)
3407
- return;
3408
- q(_(RedirectDialogContent, Object.assign({}, props, { onDismiss: () => {
3409
- this.clear();
3410
- }, darkMode: this.darkMode })), this.root);
3411
- }
3412
- }
3413
- const RedirectDialogContent = ({ title, buttonText, darkMode, onButtonClick, onDismiss }) => {
3414
- const theme = darkMode ? 'dark' : 'light';
3415
- return (_(SnackbarContainer, { darkMode: darkMode },
3416
- _("div", { class: "-cbwsdk-redirect-dialog" },
3417
- _("style", null, css),
3418
- _("div", { class: "-cbwsdk-redirect-dialog-backdrop", onClick: onDismiss }),
3419
- _("div", { class: clsx_m.clsx('-cbwsdk-redirect-dialog-box', theme) },
3420
- _("p", null, title),
3421
- _("button", { onClick: onButtonClick }, buttonText)))));
3422
- };
3423
-
3424
- const CB_KEYS_URL = 'https://keys.coinbase.com/connect';
3425
- const WALLETLINK_URL = 'https://www.walletlink.org';
3426
- const CBW_MOBILE_DEEPLINK_URL = 'https://go.cb-w.com/walletlink';
3427
-
3428
- class WLMobileRelayUI {
3429
- constructor() {
3430
- this.attached = false;
3431
- this.redirectDialog = new RedirectDialog();
3432
- }
3433
- attach() {
3434
- if (this.attached) {
3435
- throw new Error('Coinbase Wallet SDK UI is already attached');
3436
- }
3437
- this.redirectDialog.attach();
3438
- this.attached = true;
3439
- }
3440
- redirectToCoinbaseWallet(walletLinkUrl) {
3441
- const url = new URL(CBW_MOBILE_DEEPLINK_URL);
3442
- url.searchParams.append('redirect_url', getLocation().href);
3443
- if (walletLinkUrl) {
3444
- url.searchParams.append('wl_url', walletLinkUrl);
3445
- }
3446
- const anchorTag = document.createElement('a');
3447
- anchorTag.target = 'cbw-opener';
3448
- anchorTag.href = url.href;
3449
- anchorTag.rel = 'noreferrer noopener';
3450
- anchorTag.click();
3451
- }
3452
- openCoinbaseWalletDeeplink(walletLinkUrl) {
3453
- this.redirectDialog.present({
3454
- title: 'Redirecting to Coinbase Wallet...',
3455
- buttonText: 'Open',
3456
- onButtonClick: () => {
3457
- this.redirectToCoinbaseWallet(walletLinkUrl);
3458
- },
3459
- });
3460
- setTimeout(() => {
3461
- this.redirectToCoinbaseWallet(walletLinkUrl);
3462
- }, 99);
3463
- }
3464
- showConnecting(_options) {
3465
- // it uses the return callback to clear the dialog
3466
- return () => {
3467
- this.redirectDialog.clear();
3468
- };
3469
- }
3470
- }
3471
-
3472
- // Copyright (c) 2018-2023 Coinbase, Inc. <https://www.coinbase.com/>
3473
- class WalletLinkRelay {
3474
- constructor(options) {
3475
- this.chainCallbackParams = { chainId: '', jsonRpcUrl: '' }; // to implement distinctUntilChanged
3476
- this.isMobileWeb = isMobileWeb();
3477
- this.linkedUpdated = (linked) => {
3478
- this.isLinked = linked;
3479
- const cachedAddresses = this.storage.getItem(LOCAL_STORAGE_ADDRESSES_KEY);
3480
- if (linked) {
3481
- // Only set linked session variable one way
3482
- this._session.linked = linked;
3483
- }
3484
- this.isUnlinkedErrorState = false;
3485
- if (cachedAddresses) {
3486
- const addresses = cachedAddresses.split(' ');
3487
- const wasConnectedViaStandalone = this.storage.getItem('IsStandaloneSigning') === 'true';
3488
- if (addresses[0] !== '' && !linked && this._session.linked && !wasConnectedViaStandalone) {
3489
- this.isUnlinkedErrorState = true;
3490
- }
3491
- }
3492
- };
3493
- this.metadataUpdated = (key, value) => {
3494
- this.storage.setItem(key, value);
3495
- };
3496
- this.chainUpdated = (chainId, jsonRpcUrl) => {
3497
- if (this.chainCallbackParams.chainId === chainId &&
3498
- this.chainCallbackParams.jsonRpcUrl === jsonRpcUrl) {
3499
- return;
3500
- }
3501
- this.chainCallbackParams = {
3502
- chainId,
3503
- jsonRpcUrl,
3504
- };
3505
- if (this.chainCallback) {
3506
- this.chainCallback(jsonRpcUrl, Number.parseInt(chainId, 10));
3507
- }
3508
- };
3509
- this.accountUpdated = (selectedAddress) => {
3510
- if (this.accountsCallback) {
3511
- this.accountsCallback([selectedAddress]);
3512
- }
3513
- if (WalletLinkRelay.accountRequestCallbackIds.size > 0) {
3514
- // We get the ethereum address from the metadata. If for whatever
3515
- // reason we don't get a response via an explicit web3 message
3516
- // we can still fulfill the eip1102 request.
3517
- Array.from(WalletLinkRelay.accountRequestCallbackIds.values()).forEach((id) => {
3518
- this.invokeCallback(id, {
3519
- method: 'requestEthereumAccounts',
3520
- result: [selectedAddress],
3521
- });
3522
- });
3523
- WalletLinkRelay.accountRequestCallbackIds.clear();
3524
- }
3525
- };
3526
- this.resetAndReload = this.resetAndReload.bind(this);
3527
- this.linkAPIUrl = options.linkAPIUrl;
3528
- this.storage = options.storage;
3529
- this.metadata = options.metadata;
3530
- this.accountsCallback = options.accountsCallback;
3531
- this.chainCallback = options.chainCallback;
3532
- const { session, ui, connection } = this.subscribe();
3533
- this._session = session;
3534
- this.connection = connection;
3535
- this.relayEventManager = new RelayEventManager();
3536
- this.ui = ui;
3537
- this.ui.attach();
3538
- }
3539
- subscribe() {
3540
- const session = WalletLinkSession.load(this.storage) || WalletLinkSession.create(this.storage);
3541
- const { linkAPIUrl } = this;
3542
- const connection = new WalletLinkConnection({
3543
- session,
3544
- linkAPIUrl,
3545
- listener: this,
3546
- });
3547
- const ui = this.isMobileWeb ? new WLMobileRelayUI() : new WalletLinkRelayUI();
3548
- connection.connect();
3549
- return { session, ui, connection };
3550
- }
3551
- resetAndReload() {
3552
- this.connection
3553
- .destroy()
3554
- .then(() => {
3555
- /**
3556
- * Only clear storage if the session id we have in memory matches the one on disk
3557
- * Otherwise, in the case where we have 2 tabs, another tab might have cleared
3558
- * storage already. In that case if we clear storage again, the user will be in
3559
- * a state where the first tab allows the user to connect but the session that
3560
- * was used isn't persisted. This leaves the user in a state where they aren't
3561
- * connected to the mobile app.
3562
- */
3563
- const storedSession = WalletLinkSession.load(this.storage);
3564
- if ((storedSession === null || storedSession === void 0 ? void 0 : storedSession.id) === this._session.id) {
3565
- ScopedLocalStorage.clearAll();
3566
- }
3567
- document.location.reload();
3568
- })
3569
- .catch((_) => { });
3570
- }
3571
- signEthereumTransaction(params) {
3572
- return this.sendRequest({
3573
- method: 'signEthereumTransaction',
3574
- params: {
3575
- fromAddress: params.fromAddress,
3576
- toAddress: params.toAddress,
3577
- weiValue: bigIntStringFromBigInt(params.weiValue),
3578
- data: hexStringFromBuffer(params.data, true),
3579
- nonce: params.nonce,
3580
- gasPriceInWei: params.gasPriceInWei ? bigIntStringFromBigInt(params.gasPriceInWei) : null,
3581
- maxFeePerGas: params.gasPriceInWei ? bigIntStringFromBigInt(params.gasPriceInWei) : null,
3582
- maxPriorityFeePerGas: params.gasPriceInWei
3583
- ? bigIntStringFromBigInt(params.gasPriceInWei)
3584
- : null,
3585
- gasLimit: params.gasLimit ? bigIntStringFromBigInt(params.gasLimit) : null,
3586
- chainId: params.chainId,
3587
- shouldSubmit: false,
3588
- },
3589
- });
3590
- }
3591
- signAndSubmitEthereumTransaction(params) {
3592
- return this.sendRequest({
3593
- method: 'signEthereumTransaction',
3594
- params: {
3595
- fromAddress: params.fromAddress,
3596
- toAddress: params.toAddress,
3597
- weiValue: bigIntStringFromBigInt(params.weiValue),
3598
- data: hexStringFromBuffer(params.data, true),
3599
- nonce: params.nonce,
3600
- gasPriceInWei: params.gasPriceInWei ? bigIntStringFromBigInt(params.gasPriceInWei) : null,
3601
- maxFeePerGas: params.maxFeePerGas ? bigIntStringFromBigInt(params.maxFeePerGas) : null,
3602
- maxPriorityFeePerGas: params.maxPriorityFeePerGas
3603
- ? bigIntStringFromBigInt(params.maxPriorityFeePerGas)
3604
- : null,
3605
- gasLimit: params.gasLimit ? bigIntStringFromBigInt(params.gasLimit) : null,
3606
- chainId: params.chainId,
3607
- shouldSubmit: true,
3608
- },
3609
- });
3610
- }
3611
- submitEthereumTransaction(signedTransaction, chainId) {
3612
- return this.sendRequest({
3613
- method: 'submitEthereumTransaction',
3614
- params: {
3615
- signedTransaction: hexStringFromBuffer(signedTransaction, true),
3616
- chainId,
3617
- },
3618
- });
3619
- }
3620
- getWalletLinkSession() {
3621
- return this._session;
3622
- }
3623
- sendRequest(request) {
3624
- let hideSnackbarItem = null;
3625
- const id = randomBytesHex(8);
3626
- const cancel = (error) => {
3627
- this.publishWeb3RequestCanceledEvent(id);
3628
- this.handleErrorResponse(id, request.method, error);
3629
- hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();
3630
- };
3631
- return new Promise((resolve, reject) => {
3632
- {
3633
- hideSnackbarItem = this.ui.showConnecting({
3634
- isUnlinkedErrorState: this.isUnlinkedErrorState,
3635
- onCancel: cancel,
3636
- onResetConnection: this.resetAndReload, // eslint-disable-line @typescript-eslint/unbound-method
3637
- });
3638
- }
3639
- this.relayEventManager.callbacks.set(id, (response) => {
3640
- hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();
3641
- if (isErrorResponse(response)) {
3642
- return reject(new Error(response.errorMessage));
3643
- }
3644
- resolve(response);
3645
- });
3646
- this.publishWeb3RequestEvent(id, request);
3647
- });
3648
- }
3649
- publishWeb3RequestEvent(id, request) {
3650
- const message = { type: 'WEB3_REQUEST', id, request };
3651
- this.publishEvent('Web3Request', message, true)
3652
- .then((_) => { })
3653
- .catch((err) => {
3654
- this.handleWeb3ResponseMessage(message.id, {
3655
- method: request.method,
3656
- errorMessage: err.message,
3657
- });
3658
- });
3659
- if (this.isMobileWeb) {
3660
- this.openCoinbaseWalletDeeplink(request.method);
3661
- }
3662
- }
3663
- // copied from MobileRelay
3664
- openCoinbaseWalletDeeplink(method) {
3665
- if (!(this.ui instanceof WLMobileRelayUI))
3666
- return;
3667
- // For mobile relay requests, open the Coinbase Wallet app
3668
- switch (method) {
3669
- case 'requestEthereumAccounts': // requestEthereumAccounts is handled via popup
3670
- case 'switchEthereumChain': // switchEthereumChain doesn't need to open the app
3671
- return;
3672
- default:
3673
- window.addEventListener('blur', () => {
3674
- window.addEventListener('focus', () => {
3675
- this.connection.checkUnseenEvents();
3676
- }, { once: true });
3677
- }, { once: true });
3678
- this.ui.openCoinbaseWalletDeeplink();
3679
- break;
3680
- }
3681
- }
3682
- publishWeb3RequestCanceledEvent(id) {
3683
- const message = {
3684
- type: 'WEB3_REQUEST_CANCELED',
3685
- id,
3686
- };
3687
- this.publishEvent('Web3RequestCanceled', message, false).then();
3688
- }
3689
- publishEvent(event, message, callWebhook) {
3690
- return this.connection.publishEvent(event, message, callWebhook);
3691
- }
3692
- handleWeb3ResponseMessage(id, response) {
3693
- if (response.method === 'requestEthereumAccounts') {
3694
- WalletLinkRelay.accountRequestCallbackIds.forEach((id) => this.invokeCallback(id, response));
3695
- WalletLinkRelay.accountRequestCallbackIds.clear();
3696
- return;
3697
- }
3698
- this.invokeCallback(id, response);
3699
- }
3700
- handleErrorResponse(id, method, error) {
3701
- var _a;
3702
- const errorMessage = (_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : 'Unspecified error message.';
3703
- this.handleWeb3ResponseMessage(id, {
3704
- method,
3705
- errorMessage,
3706
- });
3707
- }
3708
- invokeCallback(id, response) {
3709
- const callback = this.relayEventManager.callbacks.get(id);
3710
- if (callback) {
3711
- callback(response);
3712
- this.relayEventManager.callbacks.delete(id);
3713
- }
3714
- }
3715
- requestEthereumAccounts() {
3716
- const { appName, appLogoUrl } = this.metadata;
3717
- const request = {
3718
- method: 'requestEthereumAccounts',
3719
- params: {
3720
- appName,
3721
- appLogoUrl,
3722
- },
3723
- };
3724
- const id = randomBytesHex(8);
3725
- return new Promise((resolve, reject) => {
3726
- this.relayEventManager.callbacks.set(id, (response) => {
3727
- if (isErrorResponse(response)) {
3728
- return reject(new Error(response.errorMessage));
3729
- }
3730
- resolve(response);
3731
- });
3732
- WalletLinkRelay.accountRequestCallbackIds.add(id);
3733
- this.publishWeb3RequestEvent(id, request);
3734
- });
3735
- }
3736
- watchAsset(type, address, symbol, decimals, image, chainId) {
3737
- const request = {
3738
- method: 'watchAsset',
3739
- params: {
3740
- type,
3741
- options: {
3742
- address,
3743
- symbol,
3744
- decimals,
3745
- image,
3746
- },
3747
- chainId,
3748
- },
3749
- };
3750
- let hideSnackbarItem = null;
3751
- const id = randomBytesHex(8);
3752
- const cancel = (error) => {
3753
- this.publishWeb3RequestCanceledEvent(id);
3754
- this.handleErrorResponse(id, request.method, error);
3755
- hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();
3756
- };
3757
- {
3758
- hideSnackbarItem = this.ui.showConnecting({
3759
- isUnlinkedErrorState: this.isUnlinkedErrorState,
3760
- onCancel: cancel,
3761
- onResetConnection: this.resetAndReload, // eslint-disable-line @typescript-eslint/unbound-method
3762
- });
3763
- }
3764
- return new Promise((resolve, reject) => {
3765
- this.relayEventManager.callbacks.set(id, (response) => {
3766
- hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();
3767
- if (isErrorResponse(response)) {
3768
- return reject(new Error(response.errorMessage));
3769
- }
3770
- resolve(response);
3771
- });
3772
- this.publishWeb3RequestEvent(id, request);
3773
- });
3774
- }
3775
- addEthereumChain(chainId, rpcUrls, iconUrls, blockExplorerUrls, chainName, nativeCurrency) {
3776
- const request = {
3777
- method: 'addEthereumChain',
3778
- params: {
3779
- chainId,
3780
- rpcUrls,
3781
- blockExplorerUrls,
3782
- chainName,
3783
- iconUrls,
3784
- nativeCurrency,
3785
- },
3786
- };
3787
- let hideSnackbarItem = null;
3788
- const id = randomBytesHex(8);
3789
- const cancel = (error) => {
3790
- this.publishWeb3RequestCanceledEvent(id);
3791
- this.handleErrorResponse(id, request.method, error);
3792
- hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();
3793
- };
3794
- {
3795
- hideSnackbarItem = this.ui.showConnecting({
3796
- isUnlinkedErrorState: this.isUnlinkedErrorState,
3797
- onCancel: cancel,
3798
- onResetConnection: this.resetAndReload, // eslint-disable-line @typescript-eslint/unbound-method
3799
- });
3800
- }
3801
- return new Promise((resolve, reject) => {
3802
- this.relayEventManager.callbacks.set(id, (response) => {
3803
- hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();
3804
- if (isErrorResponse(response)) {
3805
- return reject(new Error(response.errorMessage));
3806
- }
3807
- resolve(response);
3808
- });
3809
- this.publishWeb3RequestEvent(id, request);
3810
- });
3811
- }
3812
- switchEthereumChain(chainId, address) {
3813
- const request = {
3814
- method: 'switchEthereumChain',
3815
- params: Object.assign({ chainId }, { address }),
3816
- };
3817
- let hideSnackbarItem = null;
3818
- const id = randomBytesHex(8);
3819
- const cancel = (error) => {
3820
- this.publishWeb3RequestCanceledEvent(id);
3821
- this.handleErrorResponse(id, request.method, error);
3822
- hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();
3823
- };
3824
- {
3825
- hideSnackbarItem = this.ui.showConnecting({
3826
- isUnlinkedErrorState: this.isUnlinkedErrorState,
3827
- onCancel: cancel,
3828
- onResetConnection: this.resetAndReload, // eslint-disable-line @typescript-eslint/unbound-method
3829
- });
3830
- }
3831
- return new Promise((resolve, reject) => {
3832
- this.relayEventManager.callbacks.set(id, (response) => {
3833
- hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();
3834
- if (isErrorResponse(response) && response.errorCode) {
3835
- return reject(standardErrors.provider.custom({
3836
- code: response.errorCode,
3837
- message: `Unrecognized chain ID. Try adding the chain using addEthereumChain first.`,
3838
- }));
3839
- }
3840
- else if (isErrorResponse(response)) {
3841
- return reject(new Error(response.errorMessage));
3842
- }
3843
- resolve(response);
3844
- });
3845
- this.publishWeb3RequestEvent(id, request);
3846
- });
3847
- }
3848
- }
3849
- WalletLinkRelay.accountRequestCallbackIds = new Set();
3850
-
3851
- // Copyright (c) 2018-2024 Coinbase, Inc. <https://www.coinbase.com/>
3852
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3853
- // @ts-nocheck
3854
- const DEFAULT_CHAIN_ID_KEY = 'DefaultChainId';
3855
- const DEFAULT_JSON_RPC_URL = 'DefaultJsonRpcUrl';
3856
- // original source: https://github.com/coinbase/coinbase-wallet-sdk/blob/v3.7.1/packages/wallet-sdk/src/provider/CoinbaseWalletProvider.ts
3857
- class WalletLinkSigner {
3858
- constructor(options) {
3859
- this._relay = null;
3860
- this._addresses = [];
3861
- this.metadata = options.metadata;
3862
- this._storage = new ScopedLocalStorage('walletlink', WALLETLINK_URL);
3863
- this.callback = options.callback || null;
3864
- const cachedAddresses = this._storage.getItem(LOCAL_STORAGE_ADDRESSES_KEY);
3865
- if (cachedAddresses) {
3866
- const addresses = cachedAddresses.split(' ');
3867
- if (addresses[0] !== '') {
3868
- this._addresses = addresses.map((address) => ensureAddressString(address));
3869
- }
3870
- }
3871
- this.initializeRelay();
3872
- }
3873
- getSession() {
3874
- const relay = this.initializeRelay();
3875
- const { id, secret } = relay.getWalletLinkSession();
3876
- return { id, secret };
3877
- }
3878
- async handshake() {
3879
- await this._eth_requestAccounts();
3880
- }
3881
- get selectedAddress() {
3882
- return this._addresses[0] || undefined;
3883
- }
3884
- get jsonRpcUrl() {
3885
- var _a;
3886
- return (_a = this._storage.getItem(DEFAULT_JSON_RPC_URL)) !== null && _a !== void 0 ? _a : undefined;
3887
- }
3888
- set jsonRpcUrl(value) {
3889
- this._storage.setItem(DEFAULT_JSON_RPC_URL, value);
3890
- }
3891
- updateProviderInfo(jsonRpcUrl, chainId) {
3892
- var _a;
3893
- this.jsonRpcUrl = jsonRpcUrl;
3894
- // emit chainChanged event if necessary
3895
- const originalChainId = this.getChainId();
3896
- this._storage.setItem(DEFAULT_CHAIN_ID_KEY, chainId.toString(10));
3897
- const chainChanged = ensureIntNumber(chainId) !== originalChainId;
3898
- if (chainChanged) {
3899
- (_a = this.callback) === null || _a === void 0 ? void 0 : _a.call(this, 'chainChanged', hexStringFromNumber(chainId));
3900
- }
3901
- }
3902
- async watchAsset(params) {
3903
- const request = (Array.isArray(params) ? params[0] : params);
3904
- if (!request.type) {
3905
- throw standardErrors.rpc.invalidParams('Type is required');
3906
- }
3907
- if ((request === null || request === void 0 ? void 0 : request.type) !== 'ERC20') {
3908
- throw standardErrors.rpc.invalidParams(`Asset of type '${request.type}' is not supported`);
3909
- }
3910
- if (!(request === null || request === void 0 ? void 0 : request.options)) {
3911
- throw standardErrors.rpc.invalidParams('Options are required');
3912
- }
3913
- if (!(request === null || request === void 0 ? void 0 : request.options.address)) {
3914
- throw standardErrors.rpc.invalidParams('Address is required');
3915
- }
3916
- const chainId = this.getChainId();
3917
- const { address, symbol, image, decimals } = request.options;
3918
- const relay = this.initializeRelay();
3919
- const result = await relay.watchAsset(request.type, address, symbol, decimals, image, chainId === null || chainId === void 0 ? void 0 : chainId.toString());
3920
- if (isErrorResponse(result))
3921
- return false;
3922
- return !!result.result;
3923
- }
3924
- async addEthereumChain(params) {
3925
- var _a, _b;
3926
- const request = params[0];
3927
- if (((_a = request.rpcUrls) === null || _a === void 0 ? void 0 : _a.length) === 0) {
3928
- throw standardErrors.rpc.invalidParams('please pass in at least 1 rpcUrl');
3929
- }
3930
- if (!request.chainName || request.chainName.trim() === '') {
3931
- throw standardErrors.rpc.invalidParams('chainName is a required field');
3932
- }
3933
- if (!request.nativeCurrency) {
3934
- throw standardErrors.rpc.invalidParams('nativeCurrency is a required field');
3935
- }
3936
- const chainIdNumber = Number.parseInt(request.chainId, 16);
3937
- if (chainIdNumber === this.getChainId()) {
3938
- return false;
3939
- }
3940
- const relay = this.initializeRelay();
3941
- const { rpcUrls = [], blockExplorerUrls = [], chainName, iconUrls = [], nativeCurrency, } = request;
3942
- const res = await relay.addEthereumChain(chainIdNumber.toString(), rpcUrls, iconUrls, blockExplorerUrls, chainName, nativeCurrency);
3943
- if (isErrorResponse(res))
3944
- return false;
3945
- if (((_b = res.result) === null || _b === void 0 ? void 0 : _b.isApproved) === true) {
3946
- this.updateProviderInfo(rpcUrls[0], chainIdNumber);
3947
- return null;
3948
- }
3949
- throw standardErrors.rpc.internal('unable to add ethereum chain');
3950
- }
3951
- async switchEthereumChain(params) {
3952
- const request = params[0];
3953
- const chainId = Number.parseInt(request.chainId, 16);
3954
- const relay = this.initializeRelay();
3955
- const res = await relay.switchEthereumChain(chainId.toString(10), this.selectedAddress || undefined);
3956
- if (isErrorResponse(res))
3957
- throw res;
3958
- const switchResponse = res.result;
3959
- if (switchResponse.isApproved && switchResponse.rpcUrl.length > 0) {
3960
- this.updateProviderInfo(switchResponse.rpcUrl, chainId);
3961
- }
3962
- return null;
3963
- }
3964
- async cleanup() {
3965
- this.callback = null;
3966
- if (this._relay) {
3967
- this._relay.resetAndReload();
3968
- }
3969
- this._storage.clear();
3970
- }
3971
- _setAddresses(addresses, _) {
3972
- var _a;
3973
- if (!Array.isArray(addresses)) {
3974
- throw new Error('addresses is not an array');
3975
- }
3976
- const newAddresses = addresses.map((address) => ensureAddressString(address));
3977
- if (JSON.stringify(newAddresses) === JSON.stringify(this._addresses)) {
3978
- return;
3979
- }
3980
- this._addresses = newAddresses;
3981
- (_a = this.callback) === null || _a === void 0 ? void 0 : _a.call(this, 'accountsChanged', newAddresses);
3982
- this._storage.setItem(LOCAL_STORAGE_ADDRESSES_KEY, newAddresses.join(' '));
3983
- }
3984
- async request(request) {
3985
- const params = request.params || [];
3986
- switch (request.method) {
3987
- case 'eth_accounts':
3988
- return [...this._addresses];
3989
- case 'eth_coinbase':
3990
- return this.selectedAddress || null;
3991
- case 'net_version':
3992
- return this.getChainId().toString(10);
3993
- case 'eth_chainId':
3994
- return hexStringFromNumber(this.getChainId());
3995
- case 'eth_requestAccounts':
3996
- return this._eth_requestAccounts();
3997
- case 'eth_ecRecover':
3998
- case 'personal_ecRecover':
3999
- return this.ecRecover(request);
4000
- case 'personal_sign':
4001
- return this.personalSign(request);
4002
- case 'eth_signTransaction':
4003
- return this._eth_signTransaction(params);
4004
- case 'eth_sendRawTransaction':
4005
- return this._eth_sendRawTransaction(params);
4006
- case 'eth_sendTransaction':
4007
- return this._eth_sendTransaction(params);
4008
- case 'eth_signTypedData_v1':
4009
- case 'eth_signTypedData_v3':
4010
- case 'eth_signTypedData_v4':
4011
- case 'eth_signTypedData':
4012
- return this.signTypedData(request);
4013
- case 'wallet_addEthereumChain':
4014
- return this.addEthereumChain(params);
4015
- case 'wallet_switchEthereumChain':
4016
- return this.switchEthereumChain(params);
4017
- case 'wallet_watchAsset':
4018
- return this.watchAsset(params);
4019
- default:
4020
- if (!this.jsonRpcUrl)
4021
- throw standardErrors.rpc.internal('No RPC URL set for chain');
4022
- return fetchRPCRequest(request, this.jsonRpcUrl);
4023
- }
4024
- }
4025
- _ensureKnownAddress(addressString) {
4026
- const addressStr = ensureAddressString(addressString);
4027
- const lowercaseAddresses = this._addresses.map((address) => ensureAddressString(address));
4028
- if (!lowercaseAddresses.includes(addressStr)) {
4029
- throw new Error('Unknown Ethereum address');
4030
- }
4031
- }
4032
- _prepareTransactionParams(tx) {
4033
- const fromAddress = tx.from ? ensureAddressString(tx.from) : this.selectedAddress;
4034
- if (!fromAddress) {
4035
- throw new Error('Ethereum address is unavailable');
4036
- }
4037
- this._ensureKnownAddress(fromAddress);
4038
- const toAddress = tx.to ? ensureAddressString(tx.to) : null;
4039
- const weiValue = tx.value != null ? ensureBigInt(tx.value) : BigInt(0);
4040
- const data = tx.data ? ensureBuffer(tx.data) : Buffer.alloc(0);
4041
- const nonce = tx.nonce != null ? ensureIntNumber(tx.nonce) : null;
4042
- const gasPriceInWei = tx.gasPrice != null ? ensureBigInt(tx.gasPrice) : null;
4043
- const maxFeePerGas = tx.maxFeePerGas != null ? ensureBigInt(tx.maxFeePerGas) : null;
4044
- const maxPriorityFeePerGas = tx.maxPriorityFeePerGas != null ? ensureBigInt(tx.maxPriorityFeePerGas) : null;
4045
- const gasLimit = tx.gas != null ? ensureBigInt(tx.gas) : null;
4046
- const chainId = tx.chainId ? ensureIntNumber(tx.chainId) : this.getChainId();
4047
- return {
4048
- fromAddress,
4049
- toAddress,
4050
- weiValue,
4051
- data,
4052
- nonce,
4053
- gasPriceInWei,
4054
- maxFeePerGas,
4055
- maxPriorityFeePerGas,
4056
- gasLimit,
4057
- chainId,
4058
- };
4059
- }
4060
- async ecRecover(request) {
4061
- const { method, params } = request;
4062
- if (!Array.isArray(params))
4063
- throw standardErrors.rpc.invalidParams();
4064
- const relay = this.initializeRelay();
4065
- const res = await relay.sendRequest({
4066
- method: 'ethereumAddressFromSignedMessage',
4067
- params: {
4068
- message: encodeToHexString(params[0]),
4069
- signature: encodeToHexString(params[1]),
4070
- addPrefix: method === 'personal_ecRecover',
4071
- },
4072
- });
4073
- if (isErrorResponse(res))
4074
- throw res;
4075
- return res.result;
4076
- }
4077
- getChainId() {
4078
- var _a;
4079
- return Number.parseInt((_a = this._storage.getItem(DEFAULT_CHAIN_ID_KEY)) !== null && _a !== void 0 ? _a : '1', 10);
4080
- }
4081
- async _eth_requestAccounts() {
4082
- var _a, _b;
4083
- if (this._addresses.length > 0) {
4084
- (_a = this.callback) === null || _a === void 0 ? void 0 : _a.call(this, 'connect', { chainId: hexStringFromNumber(this.getChainId()) });
4085
- return this._addresses;
4086
- }
4087
- const relay = this.initializeRelay();
4088
- const res = await relay.requestEthereumAccounts();
4089
- if (isErrorResponse(res))
4090
- throw res;
4091
- if (!res.result) {
4092
- throw new Error('accounts received is empty');
4093
- }
4094
- this._setAddresses(res.result);
4095
- (_b = this.callback) === null || _b === void 0 ? void 0 : _b.call(this, 'connect', { chainId: hexStringFromNumber(this.getChainId()) });
4096
- return this._addresses;
4097
- }
4098
- async personalSign({ params }) {
4099
- if (!Array.isArray(params))
4100
- throw standardErrors.rpc.invalidParams();
4101
- const address = params[1];
4102
- const rawData = params[0];
4103
- this._ensureKnownAddress(address);
4104
- const relay = this.initializeRelay();
4105
- const res = await relay.sendRequest({
4106
- method: 'signEthereumMessage',
4107
- params: {
4108
- address: ensureAddressString(address),
4109
- message: encodeToHexString(rawData),
4110
- addPrefix: true,
4111
- typedDataJson: null,
4112
- },
4113
- });
4114
- if (isErrorResponse(res))
4115
- throw res;
4116
- return res.result;
4117
- }
4118
- async _eth_signTransaction(params) {
4119
- const tx = this._prepareTransactionParams(params[0] || {});
4120
- const relay = this.initializeRelay();
4121
- const res = await relay.signEthereumTransaction(tx);
4122
- if (isErrorResponse(res))
4123
- throw res;
4124
- return res.result;
4125
- }
4126
- async _eth_sendRawTransaction(params) {
4127
- const signedTransaction = ensureBuffer(params[0]);
4128
- const relay = this.initializeRelay();
4129
- const res = await relay.submitEthereumTransaction(signedTransaction, this.getChainId());
4130
- if (isErrorResponse(res))
4131
- throw res;
4132
- return res.result;
4133
- }
4134
- async _eth_sendTransaction(params) {
4135
- const tx = this._prepareTransactionParams(params[0] || {});
4136
- const relay = this.initializeRelay();
4137
- const res = await relay.signAndSubmitEthereumTransaction(tx);
4138
- if (isErrorResponse(res))
4139
- throw res;
4140
- return res.result;
4141
- }
4142
- async signTypedData(request) {
4143
- const { method, params } = request;
4144
- if (!Array.isArray(params))
4145
- throw standardErrors.rpc.invalidParams();
4146
- const encode = (input) => {
4147
- const hashFuncMap = {
4148
- eth_signTypedData_v1: eip712.hashForSignTypedDataLegacy,
4149
- eth_signTypedData_v3: eip712.hashForSignTypedData_v3,
4150
- eth_signTypedData_v4: eip712.hashForSignTypedData_v4,
4151
- eth_signTypedData: eip712.hashForSignTypedData_v4,
4152
- };
4153
- return hexStringFromBuffer(hashFuncMap[method]({
4154
- data: ensureParsedJSONObject(input),
4155
- }), true);
4156
- };
4157
- const address = params[method === 'eth_signTypedData_v1' ? 1 : 0];
4158
- const rawData = params[method === 'eth_signTypedData_v1' ? 0 : 1];
4159
- this._ensureKnownAddress(address);
4160
- const relay = this.initializeRelay();
4161
- const res = await relay.sendRequest({
4162
- method: 'signEthereumMessage',
4163
- params: {
4164
- address: ensureAddressString(address),
4165
- message: encode(rawData),
4166
- typedDataJson: JSON.stringify(rawData, null, 2),
4167
- addPrefix: false,
4168
- },
4169
- });
4170
- if (isErrorResponse(res))
4171
- throw res;
4172
- return res.result;
4173
- }
4174
- initializeRelay() {
4175
- if (!this._relay) {
4176
- this._relay = new WalletLinkRelay({
4177
- linkAPIUrl: WALLETLINK_URL,
4178
- storage: this._storage,
4179
- metadata: this.metadata,
4180
- accountsCallback: this._setAddresses.bind(this),
4181
- chainCallback: this.updateProviderInfo.bind(this),
4182
- });
4183
- }
4184
- return this._relay;
4185
- }
4186
- }
4187
-
4188
- const SIGNER_TYPE_KEY = 'SignerType';
4189
- const storage = new ScopedLocalStorage('CBWSDK', 'SignerConfigurator');
4190
- function loadSignerType() {
4191
- return storage.getItem(SIGNER_TYPE_KEY);
4192
- }
4193
- function storeSignerType(signerType) {
4194
- storage.setItem(SIGNER_TYPE_KEY, signerType);
4195
- }
4196
- async function fetchSignerType(params) {
4197
- const { communicator, metadata, handshakeRequest, callback } = params;
4198
- listenForWalletLinkSessionRequest(communicator, metadata, callback).catch(() => { });
4199
- const request = {
4200
- id: crypto.randomUUID(),
4201
- event: 'selectSignerType',
4202
- data: Object.assign(Object.assign({}, params.preference), { handshakeRequest }),
4203
- };
4204
- const { data } = await communicator.postRequestAndWaitForResponse(request);
4205
- return data;
4206
- }
4207
- function createSigner(params) {
4208
- const { signerType, metadata, communicator, callback } = params;
4209
- switch (signerType) {
4210
- case 'scw': {
4211
- return new SCWSigner({
4212
- metadata,
4213
- callback,
4214
- communicator,
4215
- });
4216
- }
4217
- case 'walletlink': {
4218
- return new WalletLinkSigner({
4219
- metadata,
4220
- callback,
4221
- });
4222
- }
4223
- }
4224
- }
4225
- async function listenForWalletLinkSessionRequest(communicator, metadata, callback) {
4226
- await communicator.onMessage(({ event }) => event === 'WalletLinkSessionRequest');
4227
- // temporary walletlink signer instance to handle WalletLinkSessionRequest
4228
- // will revisit this when refactoring the walletlink signer
4229
- const walletlink = new WalletLinkSigner({
4230
- metadata,
4231
- callback,
4232
- });
4233
- // send wallet link session to popup
4234
- communicator.postMessage({
4235
- event: 'WalletLinkUpdate',
4236
- data: { session: walletlink.getSession() },
4237
- });
4238
- // wait for handshake to complete
4239
- await walletlink.handshake();
4240
- // send connected status to popup
4241
- communicator.postMessage({
4242
- event: 'WalletLinkUpdate',
4243
- data: { connected: true },
4244
- });
4245
- }
4246
-
4247
- const COOP_ERROR_MESSAGE = `Coinbase Wallet SDK requires the Cross-Origin-Opener-Policy header to not be set to 'same-origin'. This is to ensure that the SDK can communicate with the Coinbase Smart Wallet app.
4248
-
4249
- Please see https://www.smartwallet.dev/guides/tips/popup-tips#cross-origin-opener-policy for more information.`;
4250
- /**
4251
- * Creates a checker for the Cross-Origin-Opener-Policy (COOP).
4252
- *
4253
- * @returns An object with methods to get and check the Cross-Origin-Opener-Policy.
4254
- *
4255
- * @method getCrossOriginOpenerPolicy
4256
- * Retrieves current Cross-Origin-Opener-Policy.
4257
- * @throws Will throw an error if the policy has not been checked yet.
4258
- *
4259
- * @method checkCrossOriginOpenerPolicy
4260
- * Checks the Cross-Origin-Opener-Policy of the current environment.
4261
- * If in a non-browser environment, sets the policy to 'non-browser-env'.
4262
- * If in a browser environment, fetches the policy from the current origin.
4263
- * Logs an error if the policy is 'same-origin'.
4264
- */
4265
- const createCoopChecker = () => {
4266
- let crossOriginOpenerPolicy;
4267
- return {
4268
- getCrossOriginOpenerPolicy: () => {
4269
- if (crossOriginOpenerPolicy === undefined) {
4270
- return 'undefined';
4271
- }
4272
- return crossOriginOpenerPolicy;
4273
- },
4274
- checkCrossOriginOpenerPolicy: async () => {
4275
- if (typeof window === 'undefined') {
4276
- // Non-browser environment
4277
- crossOriginOpenerPolicy = 'non-browser-env';
4278
- return;
4279
- }
4280
- try {
4281
- const url = `${window.location.origin}${window.location.pathname}`;
4282
- const response = await fetch(url, {
4283
- method: 'HEAD',
4284
- });
4285
- if (!response.ok) {
4286
- throw new Error(`HTTP error! status: ${response.status}`);
4287
- }
4288
- const result = response.headers.get('Cross-Origin-Opener-Policy');
4289
- crossOriginOpenerPolicy = result !== null && result !== void 0 ? result : 'null';
4290
- if (crossOriginOpenerPolicy === 'same-origin') {
4291
- console.error(COOP_ERROR_MESSAGE);
4292
- }
4293
- }
4294
- catch (error) {
4295
- console.error('Error checking Cross-Origin-Opener-Policy:', error.message);
4296
- crossOriginOpenerPolicy = 'error';
4297
- }
4298
- },
4299
- };
4300
- };
4301
- const { checkCrossOriginOpenerPolicy, getCrossOriginOpenerPolicy } = createCoopChecker();
4302
-
4303
- const POPUP_WIDTH = 420;
4304
- const POPUP_HEIGHT = 540;
4305
- // Window Management
4306
- function openPopup(url) {
4307
- const left = (window.innerWidth - POPUP_WIDTH) / 2 + window.screenX;
4308
- const top = (window.innerHeight - POPUP_HEIGHT) / 2 + window.screenY;
4309
- appendAppInfoQueryParams(url);
4310
- const popup = window.open(url, 'Smart Wallet', `width=${POPUP_WIDTH}, height=${POPUP_HEIGHT}, left=${left}, top=${top}`);
4311
- popup === null || popup === void 0 ? void 0 : popup.focus();
4312
- if (!popup) {
4313
- throw standardErrors.rpc.internal('Pop up window failed to open');
4314
- }
4315
- return popup;
4316
- }
4317
- function closePopup(popup) {
4318
- if (popup && !popup.closed) {
4319
- popup.close();
4320
- }
4321
- }
4322
- function appendAppInfoQueryParams(url) {
4323
- const params = {
4324
- sdkName: NAME,
4325
- sdkVersion: VERSION,
4326
- origin: window.location.origin,
4327
- coop: getCrossOriginOpenerPolicy(),
4328
- };
4329
- for (const [key, value] of Object.entries(params)) {
4330
- url.searchParams.append(key, value.toString());
4331
- }
4332
- }
4333
-
4334
- /**
4335
- * Communicates with a popup window for Coinbase keys.coinbase.com (or another url)
4336
- * to send and receive messages.
4337
- *
4338
- * This class is responsible for opening a popup window, posting messages to it,
4339
- * and listening for responses.
4340
- *
4341
- * It also handles cleanup of event listeners and the popup window itself when necessary.
4342
- */
4343
- class Communicator {
4344
- constructor({ url = CB_KEYS_URL, metadata, preference }) {
4345
- this.popup = null;
4346
- this.listeners = new Map();
4347
- /**
4348
- * Posts a message to the popup window
4349
- */
4350
- this.postMessage = async (message) => {
4351
- const popup = await this.waitForPopupLoaded();
4352
- popup.postMessage(message, this.url.origin);
4353
- };
4354
- /**
4355
- * Posts a request to the popup window and waits for a response
4356
- */
4357
- this.postRequestAndWaitForResponse = async (request) => {
4358
- const responsePromise = this.onMessage(({ requestId }) => requestId === request.id);
4359
- this.postMessage(request);
4360
- return await responsePromise;
4361
- };
4362
- /**
4363
- * Listens for messages from the popup window that match a given predicate.
4364
- */
4365
- this.onMessage = async (predicate) => {
4366
- return new Promise((resolve, reject) => {
4367
- const listener = (event) => {
4368
- if (event.origin !== this.url.origin)
4369
- return; // origin validation
4370
- const message = event.data;
4371
- if (predicate(message)) {
4372
- resolve(message);
4373
- window.removeEventListener('message', listener);
4374
- this.listeners.delete(listener);
4375
- }
4376
- };
4377
- window.addEventListener('message', listener);
4378
- this.listeners.set(listener, { reject });
4379
- });
4380
- };
4381
- /**
4382
- * Closes the popup, rejects all requests and clears the listeners
4383
- */
4384
- this.disconnect = () => {
4385
- // Note: keys popup handles closing itself. this is a fallback.
4386
- closePopup(this.popup);
4387
- this.popup = null;
4388
- this.listeners.forEach(({ reject }, listener) => {
4389
- reject(standardErrors.provider.userRejectedRequest('Request rejected'));
4390
- window.removeEventListener('message', listener);
4391
- });
4392
- this.listeners.clear();
4393
- };
4394
- /**
4395
- * Waits for the popup window to fully load and then sends a version message.
4396
- */
4397
- this.waitForPopupLoaded = async () => {
4398
- if (this.popup && !this.popup.closed) {
4399
- // In case the user un-focused the popup between requests, focus it again
4400
- this.popup.focus();
4401
- return this.popup;
4402
- }
4403
- this.popup = openPopup(this.url);
4404
- this.onMessage(({ event }) => event === 'PopupUnload')
4405
- .then(this.disconnect)
4406
- .catch(() => { });
4407
- return this.onMessage(({ event }) => event === 'PopupLoaded')
4408
- .then((message) => {
4409
- this.postMessage({
4410
- requestId: message.id,
4411
- data: {
4412
- version: VERSION,
4413
- metadata: this.metadata,
4414
- preference: this.preference,
4415
- location: window.location.toString(),
4416
- },
4417
- });
4418
- })
4419
- .then(() => {
4420
- if (!this.popup)
4421
- throw standardErrors.rpc.internal();
4422
- return this.popup;
4423
- });
4424
- };
4425
- this.url = new URL(url);
4426
- this.metadata = metadata;
4427
- this.preference = preference;
4428
- }
4429
- }
4430
-
4431
- // TODO: error should not depend on walletlink. revisit this.
4432
- /**
4433
- * Serializes an error to a format that is compatible with the Ethereum JSON RPC error format.
4434
- * See https://docs.cloud.coinbase.com/wallet-sdk/docs/errors
4435
- * for more information.
4436
- */
4437
- function serializeError(error) {
4438
- const serialized = serialize(getErrorObject(error), {
4439
- shouldIncludeStack: true,
4440
- });
4441
- const docUrl = new URL('https://docs.cloud.coinbase.com/wallet-sdk/docs/errors');
4442
- docUrl.searchParams.set('version', VERSION);
4443
- docUrl.searchParams.set('code', serialized.code.toString());
4444
- docUrl.searchParams.set('message', serialized.message);
4445
- return Object.assign(Object.assign({}, serialized), { docUrl: docUrl.href });
4446
- }
4447
- /**
4448
- * Converts an error to a serializable object.
4449
- */
4450
- function getErrorObject(error) {
4451
- var _a;
4452
- if (typeof error === 'string') {
4453
- return {
4454
- message: error,
4455
- code: standardErrorCodes.rpc.internal,
4456
- };
4457
- }
4458
- else if (isErrorResponse(error)) {
4459
- const message = error.errorMessage;
4460
- const code = (_a = error.errorCode) !== null && _a !== void 0 ? _a : (message.match(/(denied|rejected)/i)
4461
- ? standardErrorCodes.provider.userRejectedRequest
4462
- : undefined);
4463
- return Object.assign(Object.assign({}, error), { message,
4464
- code, data: { method: error.method } });
4465
- }
4466
- return error;
4467
- }
4468
-
4469
- class ProviderEventEmitter extends index.EventEmitter {
4470
- }
4471
-
4472
- var __rest = (undefined && undefined.__rest) || function (s, e) {
4473
- var t = {};
4474
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
4475
- t[p] = s[p];
4476
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
4477
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
4478
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
4479
- t[p[i]] = s[p[i]];
4480
- }
4481
- return t;
4482
- };
4483
- class CoinbaseWalletProvider extends ProviderEventEmitter {
4484
- constructor(_a) {
4485
- var { metadata } = _a, _b = _a.preference, { keysUrl } = _b, preference = __rest(_b, ["keysUrl"]);
4486
- super();
4487
- this.signer = null;
4488
- this.isCoinbaseWallet = true;
4489
- this.metadata = metadata;
4490
- this.preference = preference;
4491
- this.communicator = new Communicator({
4492
- url: keysUrl,
4493
- metadata,
4494
- preference,
4495
- });
4496
- const signerType = loadSignerType();
4497
- if (signerType) {
4498
- this.signer = this.initSigner(signerType);
4499
- }
4500
- }
4501
- async request(args) {
4502
- try {
4503
- checkErrorForInvalidRequestArgs(args);
4504
- if (!this.signer) {
4505
- switch (args.method) {
4506
- case 'eth_requestAccounts': {
4507
- const signerType = await this.requestSignerSelection(args);
4508
- const signer = this.initSigner(signerType);
4509
- await signer.handshake(args);
4510
- this.signer = signer;
4511
- storeSignerType(signerType);
4512
- break;
4513
- }
4514
- case 'net_version':
4515
- return 1; // default value
4516
- case 'eth_chainId':
4517
- return hexStringFromNumber(1); // default value
4518
- default: {
4519
- throw standardErrors.provider.unauthorized("Must call 'eth_requestAccounts' before other methods");
4520
- }
4521
- }
4522
- }
4523
- return this.signer.request(args);
4524
- }
4525
- catch (error) {
4526
- const { code } = error;
4527
- if (code === standardErrorCodes.provider.unauthorized)
4528
- this.disconnect();
4529
- return Promise.reject(serializeError(error));
4530
- }
4531
- }
4532
- /** @deprecated Use `.request({ method: 'eth_requestAccounts' })` instead. */
4533
- async enable() {
4534
- console.warn(`.enable() has been deprecated. Please use .request({ method: "eth_requestAccounts" }) instead.`);
4535
- return await this.request({
4536
- method: 'eth_requestAccounts',
4537
- });
4538
- }
4539
- async disconnect() {
4540
- var _a;
4541
- await ((_a = this.signer) === null || _a === void 0 ? void 0 : _a.cleanup());
4542
- this.signer = null;
4543
- ScopedLocalStorage.clearAll();
4544
- this.emit('disconnect', standardErrors.provider.disconnected('User initiated disconnection'));
4545
- }
4546
- requestSignerSelection(handshakeRequest) {
4547
- return fetchSignerType({
4548
- communicator: this.communicator,
4549
- preference: this.preference,
4550
- metadata: this.metadata,
4551
- handshakeRequest,
4552
- callback: this.emit.bind(this),
4553
- });
4554
- }
4555
- initSigner(signerType) {
4556
- return createSigner({
4557
- signerType,
4558
- metadata: this.metadata,
4559
- communicator: this.communicator,
4560
- callback: this.emit.bind(this),
4561
- });
4562
- }
4563
- }
4564
-
4565
- /**
4566
- * Validates user supplied preferences. Throws if keys are not valid.
4567
- * @param preference
4568
- */
4569
- function validatePreferences(preference) {
4570
- if (!preference) {
4571
- return;
4572
- }
4573
- if (!['all', 'smartWalletOnly', 'eoaOnly'].includes(preference.options)) {
4574
- throw new Error(`Invalid options: ${preference.options}`);
4575
- }
4576
- if (preference.attribution) {
4577
- if (preference.attribution.auto !== undefined &&
4578
- preference.attribution.dataSuffix !== undefined) {
4579
- throw new Error(`Attribution cannot contain both auto and dataSuffix properties`);
4580
- }
4581
- }
4582
- }
4583
-
4584
- function createCoinbaseWalletProvider(options) {
4585
- var _a;
4586
- const params = {
4587
- metadata: options.metadata,
4588
- preference: options.preference,
4589
- };
4590
- return (_a = getCoinbaseInjectedProvider(params)) !== null && _a !== void 0 ? _a : new CoinbaseWalletProvider(params);
4591
- }
4592
-
4593
- const DEFAULT_PREFERENCE = {
4594
- options: 'all',
4595
- };
4596
- /**
4597
- * Create a Coinbase Wallet SDK instance.
4598
- * @param params - Options to create a Coinbase Wallet SDK instance.
4599
- * @returns A Coinbase Wallet SDK object.
4600
- */
4601
- function createCoinbaseWalletSDK(params) {
4602
- var _a;
4603
- const versionStorage = new ScopedLocalStorage('CBWSDK');
4604
- versionStorage.setItem('VERSION', VERSION);
4605
- void checkCrossOriginOpenerPolicy();
4606
- const options = {
4607
- metadata: {
4608
- appName: params.appName || 'Dapp',
4609
- appLogoUrl: params.appLogoUrl || '',
4610
- appChainIds: params.appChainIds || [],
4611
- },
4612
- preference: Object.assign(DEFAULT_PREFERENCE, (_a = params.preference) !== null && _a !== void 0 ? _a : {}),
4613
- };
4614
- /**
4615
- * Validate user supplied preferences. Throws if key/values are not valid.
4616
- */
4617
- validatePreferences(options.preference);
4618
- let provider = null;
4619
- return {
4620
- getProvider: () => {
4621
- if (!provider) {
4622
- provider = createCoinbaseWalletProvider(options);
4623
- }
4624
- return provider;
4625
- },
4626
- };
4627
- }
4628
-
4629
- exports.createCoinbaseWalletSDK = createCoinbaseWalletSDK;
4630
- //# sourceMappingURL=index-T4Aq984K.js.map