@pooflabs/web 0.0.75 → 0.0.77

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 (83) hide show
  1. package/README.md +32 -0
  2. package/dist/auth/providers/sol/sol-utils.d.ts +2 -0
  3. package/dist/{index-BcDe_euX.js → index-Bfk81d8_.js} +883 -25
  4. package/dist/index-Bfk81d8_.js.map +1 -0
  5. package/dist/{index-Dho2J3X6.esm.js → index-CFh1x-M0.esm.js} +368 -162
  6. package/dist/index-CFh1x-M0.esm.js.map +1 -0
  7. package/dist/index-CdOv7Nw2.esm.js +6 -0
  8. package/dist/index-CdOv7Nw2.esm.js.map +1 -0
  9. package/dist/{index-_vhjpl1l.esm.js → index-CeQ8hE3s.esm.js} +881 -24
  10. package/dist/index-CeQ8hE3s.esm.js.map +1 -0
  11. package/dist/index-DDXzCx2W.js +8 -0
  12. package/dist/index-DDXzCx2W.js.map +1 -0
  13. package/dist/{index-CMeewi-G.js → index-DQVpAl5t.js} +368 -161
  14. package/dist/index-DQVpAl5t.js.map +1 -0
  15. package/dist/{index-BHYrnHi6.js → index-KUU0aVzP.js} +882 -24
  16. package/dist/index-KUU0aVzP.js.map +1 -0
  17. package/dist/{index-BqDvUK9s.esm.js → index-R7t9pRt_.esm.js} +882 -23
  18. package/dist/index-R7t9pRt_.esm.js.map +1 -0
  19. package/dist/{index.browser-Br0p4bjw.esm.js → index.browser-BE44CEaJ.esm.js} +3 -3
  20. package/dist/{index.browser-Br0p4bjw.esm.js.map → index.browser-BE44CEaJ.esm.js.map} +1 -1
  21. package/dist/{index.browser-DZjyUgtx.esm.js → index.browser-C-_FEr5M.esm.js} +449 -479
  22. package/dist/index.browser-C-_FEr5M.esm.js.map +1 -0
  23. package/dist/index.browser-C9bFQZyQ.esm.js +1373 -0
  24. package/dist/index.browser-C9bFQZyQ.esm.js.map +1 -0
  25. package/dist/index.browser-Dbq5Qf1G.esm.js +242 -0
  26. package/dist/index.browser-Dbq5Qf1G.esm.js.map +1 -0
  27. package/dist/index.browser-Df7yN8D5.js +245 -0
  28. package/dist/index.browser-Df7yN8D5.js.map +1 -0
  29. package/dist/{index.browser-BzHjnrpD.js → index.browser-Di1_YZpi.js} +3 -3
  30. package/dist/{index.browser-BzHjnrpD.js.map → index.browser-Di1_YZpi.js.map} +1 -1
  31. package/dist/{index.browser-BOJRGZWX.js → index.browser-DjEZSiqI.js} +449 -479
  32. package/dist/index.browser-DjEZSiqI.js.map +1 -0
  33. package/dist/index.browser-dszs5oe5.js +1376 -0
  34. package/dist/index.browser-dszs5oe5.js.map +1 -0
  35. package/dist/index.d.ts +1 -0
  36. package/dist/index.esm.js +1 -1
  37. package/dist/index.js +3 -1
  38. package/dist/index.js.map +1 -1
  39. package/dist/{index.native-DcKDTqvq.js → index.native-CKd2b3_F.js} +2767 -188
  40. package/dist/index.native-CKd2b3_F.js.map +1 -0
  41. package/dist/{index.native-BB7er4-z.esm.js → index.native-DAyMVhFq.esm.js} +2766 -190
  42. package/dist/index.native-DAyMVhFq.esm.js.map +1 -0
  43. package/dist/index.native.d.ts +1 -0
  44. package/dist/index.native.esm.js +1 -1
  45. package/dist/index.native.js +3 -1
  46. package/dist/index.native.js.map +1 -1
  47. package/dist/{phantom-wallet-provider-DMxFAUC4.js → phantom-wallet-provider-DJ6qf2VB.js} +4 -4
  48. package/dist/{phantom-wallet-provider-DMxFAUC4.js.map → phantom-wallet-provider-DJ6qf2VB.js.map} +1 -1
  49. package/dist/{phantom-wallet-provider-DHok8ui3.esm.js → phantom-wallet-provider-DQ0uhl2v.esm.js} +4 -4
  50. package/dist/{phantom-wallet-provider-DHok8ui3.esm.js.map → phantom-wallet-provider-DQ0uhl2v.esm.js.map} +1 -1
  51. package/dist/{privy-wallet-provider-CFuoQYuv.esm.js → privy-wallet-provider-BhiHnphv.esm.js} +7 -8
  52. package/dist/privy-wallet-provider-BhiHnphv.esm.js.map +1 -0
  53. package/dist/{privy-wallet-provider-Bhvw0t1d.js → privy-wallet-provider-CMCv5g3O.js} +7 -8
  54. package/dist/privy-wallet-provider-CMCv5g3O.js.map +1 -0
  55. package/dist/{solana-mobile-wallet-provider-BpQghAgC.esm.js → solana-mobile-wallet-provider-DSSk_6CR.esm.js} +4 -4
  56. package/dist/{solana-mobile-wallet-provider-BpQghAgC.esm.js.map → solana-mobile-wallet-provider-DSSk_6CR.esm.js.map} +1 -1
  57. package/dist/{solana-mobile-wallet-provider-D8b5y-By.js → solana-mobile-wallet-provider-DaFNesCe.js} +4 -4
  58. package/dist/{solana-mobile-wallet-provider-D8b5y-By.js.map → solana-mobile-wallet-provider-DaFNesCe.js.map} +1 -1
  59. package/package.json +2 -2
  60. package/dist/index-BHYrnHi6.js.map +0 -1
  61. package/dist/index-BcDe_euX.js.map +0 -1
  62. package/dist/index-Bdcc5821.js +0 -2375
  63. package/dist/index-Bdcc5821.js.map +0 -1
  64. package/dist/index-BqDvUK9s.esm.js.map +0 -1
  65. package/dist/index-CMeewi-G.js.map +0 -1
  66. package/dist/index-CrOVJFX9.esm.js +0 -2373
  67. package/dist/index-CrOVJFX9.esm.js.map +0 -1
  68. package/dist/index-Dho2J3X6.esm.js.map +0 -1
  69. package/dist/index-_vhjpl1l.esm.js.map +0 -1
  70. package/dist/index.browser-BOJRGZWX.js.map +0 -1
  71. package/dist/index.browser-Btm3sRKb.esm.js +0 -307
  72. package/dist/index.browser-Btm3sRKb.esm.js.map +0 -1
  73. package/dist/index.browser-CGfjPfzM.esm.js +0 -1468
  74. package/dist/index.browser-CGfjPfzM.esm.js.map +0 -1
  75. package/dist/index.browser-DZjyUgtx.esm.js.map +0 -1
  76. package/dist/index.browser-Dapjfbl6.js +0 -310
  77. package/dist/index.browser-Dapjfbl6.js.map +0 -1
  78. package/dist/index.browser-JX3F6oPV.js +0 -1471
  79. package/dist/index.browser-JX3F6oPV.js.map +0 -1
  80. package/dist/index.native-BB7er4-z.esm.js.map +0 -1
  81. package/dist/index.native-DcKDTqvq.js.map +0 -1
  82. package/dist/privy-wallet-provider-Bhvw0t1d.js.map +0 -1
  83. package/dist/privy-wallet-provider-CFuoQYuv.esm.js.map +0 -1
@@ -1,1471 +0,0 @@
1
- 'use strict';
2
-
3
- var web3_js = require('@solana/web3.js');
4
- var index_native = require('./index.native-DcKDTqvq.js');
5
- require('axios');
6
- require('@coral-xyz/anchor');
7
- require('react');
8
-
9
- /**
10
- * TODO: docs
11
- */
12
- function createSignInMessageText(input) {
13
- // ${domain} wants you to sign in with your Solana account:
14
- // ${address}
15
- //
16
- // ${statement}
17
- //
18
- // URI: ${uri}
19
- // Version: ${version}
20
- // Chain ID: ${chain}
21
- // Nonce: ${nonce}
22
- // Issued At: ${issued-at}
23
- // Expiration Time: ${expiration-time}
24
- // Not Before: ${not-before}
25
- // Request ID: ${request-id}
26
- // Resources:
27
- // - ${resources[0]}
28
- // - ${resources[1]}
29
- // ...
30
- // - ${resources[n]}
31
- let message = `${input.domain} wants you to sign in with your Solana account:\n`;
32
- message += `${input.address}`;
33
- if (input.statement) {
34
- message += `\n\n${input.statement}`;
35
- }
36
- const fields = [];
37
- if (input.uri) {
38
- fields.push(`URI: ${input.uri}`);
39
- }
40
- if (input.version) {
41
- fields.push(`Version: ${input.version}`);
42
- }
43
- if (input.chainId) {
44
- fields.push(`Chain ID: ${input.chainId}`);
45
- }
46
- if (input.nonce) {
47
- fields.push(`Nonce: ${input.nonce}`);
48
- }
49
- if (input.issuedAt) {
50
- fields.push(`Issued At: ${input.issuedAt}`);
51
- }
52
- if (input.expirationTime) {
53
- fields.push(`Expiration Time: ${input.expirationTime}`);
54
- }
55
- if (input.notBefore) {
56
- fields.push(`Not Before: ${input.notBefore}`);
57
- }
58
- if (input.requestId) {
59
- fields.push(`Request ID: ${input.requestId}`);
60
- }
61
- if (input.resources) {
62
- fields.push(`Resources:`);
63
- for (const resource of input.resources) {
64
- fields.push(`- ${resource}`);
65
- }
66
- }
67
- if (fields.length) {
68
- message += `\n\n${fields.join('\n')}`;
69
- }
70
- return message;
71
- }
72
-
73
- function createDecoder(decoder) {
74
- return Object.freeze({
75
- ...decoder,
76
- decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0]
77
- });
78
- }
79
-
80
- var getBaseXDecoder = (alphabet4) => {
81
- return createDecoder({
82
- read(rawBytes, offset) {
83
- const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);
84
- if (bytes.length === 0) return ["", 0];
85
- let trailIndex = bytes.findIndex((n) => n !== 0);
86
- trailIndex = trailIndex === -1 ? bytes.length : trailIndex;
87
- const leadingZeroes = alphabet4[0].repeat(trailIndex);
88
- if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length];
89
- const base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);
90
- const tailChars = getBaseXFromBigInt(base10Number, alphabet4);
91
- return [leadingZeroes + tailChars, rawBytes.length];
92
- }
93
- });
94
- };
95
- function getBaseXFromBigInt(value, alphabet4) {
96
- const base = BigInt(alphabet4.length);
97
- const tailChars = [];
98
- while (value > 0n) {
99
- tailChars.unshift(alphabet4[Number(value % base)]);
100
- value /= base;
101
- }
102
- return tailChars.join("");
103
- }
104
-
105
- // src/base58.ts
106
- var alphabet2 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
107
- var getBase58Decoder = () => getBaseXDecoder(alphabet2);
108
-
109
- // Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/
110
- const SolanaMobileWalletAdapterErrorCode = {
111
- ERROR_ASSOCIATION_PORT_OUT_OF_RANGE: 'ERROR_ASSOCIATION_PORT_OUT_OF_RANGE',
112
- ERROR_FORBIDDEN_WALLET_BASE_URL: 'ERROR_FORBIDDEN_WALLET_BASE_URL',
113
- ERROR_SECURE_CONTEXT_REQUIRED: 'ERROR_SECURE_CONTEXT_REQUIRED',
114
- ERROR_SESSION_CLOSED: 'ERROR_SESSION_CLOSED',
115
- ERROR_SESSION_TIMEOUT: 'ERROR_SESSION_TIMEOUT',
116
- ERROR_WALLET_NOT_FOUND: 'ERROR_WALLET_NOT_FOUND',
117
- ERROR_INVALID_PROTOCOL_VERSION: 'ERROR_INVALID_PROTOCOL_VERSION'};
118
- class SolanaMobileWalletAdapterError extends Error {
119
- constructor(...args) {
120
- const [code, message, data] = args;
121
- super(message);
122
- this.code = code;
123
- this.data = data;
124
- this.name = 'SolanaMobileWalletAdapterError';
125
- }
126
- }
127
- class SolanaMobileWalletAdapterProtocolError extends Error {
128
- constructor(...args) {
129
- const [jsonRpcMessageId, code, message, data] = args;
130
- super(message);
131
- this.code = code;
132
- this.data = data;
133
- this.jsonRpcMessageId = jsonRpcMessageId;
134
- this.name = 'SolanaMobileWalletAdapterProtocolError';
135
- }
136
- }
137
-
138
- /******************************************************************************
139
- Copyright (c) Microsoft Corporation.
140
-
141
- Permission to use, copy, modify, and/or distribute this software for any
142
- purpose with or without fee is hereby granted.
143
-
144
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
145
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
146
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
147
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
148
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
149
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
150
- PERFORMANCE OF THIS SOFTWARE.
151
- ***************************************************************************** */
152
-
153
- function __awaiter$1(thisArg, _arguments, P, generator) {
154
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
155
- return new (P || (P = Promise))(function (resolve, reject) {
156
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
157
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
158
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
159
- step((generator = generator.apply(thisArg, [])).next());
160
- });
161
- }
162
-
163
- function encode(input) {
164
- return window.btoa(input);
165
- }
166
- function fromUint8Array$1(byteArray, urlsafe) {
167
- const base64 = window.btoa(String.fromCharCode.call(null, ...byteArray));
168
- if (urlsafe) {
169
- return base64
170
- .replace(/\+/g, '-')
171
- .replace(/\//g, '_')
172
- .replace(/=+$/, '');
173
- }
174
- else
175
- return base64;
176
- }
177
- function toUint8Array$1(base64EncodedByteArray) {
178
- return new Uint8Array(window
179
- .atob(base64EncodedByteArray)
180
- .split('')
181
- .map((c) => c.charCodeAt(0)));
182
- }
183
-
184
- function createHelloReq(ecdhPublicKey, associationKeypairPrivateKey) {
185
- return __awaiter$1(this, void 0, void 0, function* () {
186
- const publicKeyBuffer = yield crypto.subtle.exportKey('raw', ecdhPublicKey);
187
- const signatureBuffer = yield crypto.subtle.sign({ hash: 'SHA-256', name: 'ECDSA' }, associationKeypairPrivateKey, publicKeyBuffer);
188
- const response = new Uint8Array(publicKeyBuffer.byteLength + signatureBuffer.byteLength);
189
- response.set(new Uint8Array(publicKeyBuffer), 0);
190
- response.set(new Uint8Array(signatureBuffer), publicKeyBuffer.byteLength);
191
- return response;
192
- });
193
- }
194
-
195
- function createSIWSMessage(payload) {
196
- return createSignInMessageText(payload);
197
- }
198
- function createSIWSMessageBase64Url(payload) {
199
- return encode(createSIWSMessage(payload))
200
- .replace(/\+/g, '-')
201
- .replace(/\//g, '_')
202
- .replace(/=+$/, ''); // convert to base64url encoding;
203
- }
204
-
205
- // optional features
206
- const SolanaSignTransactions = 'solana:signTransactions';
207
- const SolanaCloneAuthorization = 'solana:cloneAuthorization';
208
-
209
- function fromUint8Array$2(byteArray) {
210
- return getBase58Decoder().decode(byteArray);
211
- }
212
- function base64ToBase58(base64EncodedString) {
213
- return fromUint8Array$2(toUint8Array$1(base64EncodedString));
214
- }
215
-
216
- /**
217
- * Creates a {@link MobileWallet} proxy that handles backwards compatibility and API to RPC conversion.
218
- *
219
- * @param protocolVersion the protocol version in use for this session/request
220
- * @param protocolRequestHandler callback function that handles sending the RPC request to the wallet endpoint.
221
- * @returns a {@link MobileWallet} proxy
222
- */
223
- function createMobileWalletProxy(protocolVersion, protocolRequestHandler) {
224
- return new Proxy({}, {
225
- get(target, p) {
226
- // Wrapping a Proxy in a promise results in the Proxy being asked for a 'then' property so must
227
- // return null if 'then' is called on this proxy to let the 'resolve()' call know this is not a promise.
228
- // see: https://stackoverflow.com/a/53890904
229
- //@ts-ignore
230
- if (p === 'then') {
231
- return null;
232
- }
233
- if (target[p] == null) {
234
- target[p] = function (inputParams) {
235
- return __awaiter$1(this, void 0, void 0, function* () {
236
- const { method, params } = handleMobileWalletRequest(p, inputParams, protocolVersion);
237
- const result = yield protocolRequestHandler(method, params);
238
- // if the request tried to sign in but the wallet did not return a sign in result, fallback on message signing
239
- if (method === 'authorize' && params.sign_in_payload && !result.sign_in_result) {
240
- result['sign_in_result'] = yield signInFallback(params.sign_in_payload, result, protocolRequestHandler);
241
- }
242
- return handleMobileWalletResponse(p, result, protocolVersion);
243
- });
244
- };
245
- }
246
- return target[p];
247
- },
248
- defineProperty() {
249
- return false;
250
- },
251
- deleteProperty() {
252
- return false;
253
- },
254
- });
255
- }
256
- /**
257
- * Handles all {@link MobileWallet} API requests and determines the correct MWA RPC method and params to call.
258
- * This handles backwards compatibility, based on the provided @protocolVersion.
259
- *
260
- * @param methodName the name of {@link MobileWallet} method that was called
261
- * @param methodParams the parameters that were passed to the method
262
- * @param protocolVersion the protocol version in use for this session/request
263
- * @returns the RPC request method and params that should be sent to the wallet endpoint
264
- */
265
- function handleMobileWalletRequest(methodName, methodParams, protocolVersion) {
266
- let params = methodParams;
267
- let method = methodName
268
- .toString()
269
- .replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)
270
- .toLowerCase();
271
- switch (methodName) {
272
- case 'authorize': {
273
- let { chain } = params;
274
- if (protocolVersion === 'legacy') {
275
- switch (chain) {
276
- case 'solana:testnet': {
277
- chain = 'testnet';
278
- break;
279
- }
280
- case 'solana:devnet': {
281
- chain = 'devnet';
282
- break;
283
- }
284
- case 'solana:mainnet': {
285
- chain = 'mainnet-beta';
286
- break;
287
- }
288
- default: {
289
- chain = params.cluster;
290
- }
291
- }
292
- params.cluster = chain;
293
- }
294
- else {
295
- switch (chain) {
296
- case 'testnet':
297
- case 'devnet': {
298
- chain = `solana:${chain}`;
299
- break;
300
- }
301
- case 'mainnet-beta': {
302
- chain = 'solana:mainnet';
303
- break;
304
- }
305
- }
306
- params.chain = chain;
307
- }
308
- }
309
- case 'reauthorize': {
310
- const { auth_token, identity } = params;
311
- if (auth_token) {
312
- switch (protocolVersion) {
313
- case 'legacy': {
314
- method = 'reauthorize';
315
- params = { auth_token: auth_token, identity: identity };
316
- break;
317
- }
318
- default: {
319
- method = 'authorize';
320
- break;
321
- }
322
- }
323
- }
324
- break;
325
- }
326
- }
327
- return { method, params };
328
- }
329
- /**
330
- * Handles all {@link MobileWallet} API responses and modifies the response for backwards compatibility, if needed
331
- *
332
- * @param method the {@link MobileWallet} method that was called
333
- * @param response the original response that was returned by the method call
334
- * @param protocolVersion the protocol version in use for this session/request
335
- * @returns the possibly modified response
336
- */
337
- function handleMobileWalletResponse(method, response, protocolVersion) {
338
- switch (method) {
339
- case 'getCapabilities': {
340
- const capabilities = response;
341
- switch (protocolVersion) {
342
- case 'legacy': {
343
- const features = [SolanaSignTransactions];
344
- if (capabilities.supports_clone_authorization === true) {
345
- features.push(SolanaCloneAuthorization);
346
- }
347
- return Object.assign(Object.assign({}, capabilities), { features: features });
348
- }
349
- case 'v1': {
350
- return Object.assign(Object.assign({}, capabilities), { supports_sign_and_send_transactions: true, supports_clone_authorization: capabilities.features.includes(SolanaCloneAuthorization) });
351
- }
352
- }
353
- }
354
- }
355
- return response;
356
- }
357
- function signInFallback(signInPayload, authorizationResult, protocolRequestHandler) {
358
- var _a;
359
- return __awaiter$1(this, void 0, void 0, function* () {
360
- const domain = (_a = signInPayload.domain) !== null && _a !== void 0 ? _a : window.location.host;
361
- const address = authorizationResult.accounts[0].address;
362
- const siwsMessage = createSIWSMessageBase64Url(Object.assign(Object.assign({}, signInPayload), { domain, address: base64ToBase58(address) }));
363
- const signMessageResult = yield protocolRequestHandler('sign_messages', {
364
- addresses: [address],
365
- payloads: [siwsMessage]
366
- });
367
- const signedPayload = toUint8Array$1(signMessageResult.signed_payloads[0]);
368
- const signedMessage = fromUint8Array$1(signedPayload.slice(0, signedPayload.length - 64));
369
- const signature = fromUint8Array$1(signedPayload.slice(signedPayload.length - 64));
370
- const signInResult = {
371
- address: address,
372
- // Workaround: some wallets have been observed to only reply with the message signature.
373
- // This is non-compliant with the spec, but in the interest of maximizing compatibility,
374
- // detect this case and reuse the original message.
375
- signed_message: signedMessage.length == 0 ? siwsMessage : signedMessage,
376
- signature
377
- };
378
- return signInResult;
379
- });
380
- }
381
-
382
- const SEQUENCE_NUMBER_BYTES = 4;
383
- function createSequenceNumberVector(sequenceNumber) {
384
- if (sequenceNumber >= 4294967296) {
385
- throw new Error('Outbound sequence number overflow. The maximum sequence number is 32-bytes.');
386
- }
387
- const byteArray = new ArrayBuffer(SEQUENCE_NUMBER_BYTES);
388
- const view = new DataView(byteArray);
389
- view.setUint32(0, sequenceNumber, /* littleEndian */ false);
390
- return new Uint8Array(byteArray);
391
- }
392
-
393
- const INITIALIZATION_VECTOR_BYTES = 12;
394
- const ENCODED_PUBLIC_KEY_LENGTH_BYTES = 65;
395
- function encryptMessage(plaintext, sequenceNumber, sharedSecret) {
396
- return __awaiter$1(this, void 0, void 0, function* () {
397
- const sequenceNumberVector = createSequenceNumberVector(sequenceNumber);
398
- const initializationVector = new Uint8Array(INITIALIZATION_VECTOR_BYTES);
399
- crypto.getRandomValues(initializationVector);
400
- const ciphertext = yield crypto.subtle.encrypt(getAlgorithmParams(sequenceNumberVector, initializationVector), sharedSecret, new TextEncoder().encode(plaintext));
401
- const response = new Uint8Array(sequenceNumberVector.byteLength + initializationVector.byteLength + ciphertext.byteLength);
402
- response.set(new Uint8Array(sequenceNumberVector), 0);
403
- response.set(new Uint8Array(initializationVector), sequenceNumberVector.byteLength);
404
- response.set(new Uint8Array(ciphertext), sequenceNumberVector.byteLength + initializationVector.byteLength);
405
- return response;
406
- });
407
- }
408
- function decryptMessage(message, sharedSecret) {
409
- return __awaiter$1(this, void 0, void 0, function* () {
410
- const sequenceNumberVector = message.slice(0, SEQUENCE_NUMBER_BYTES);
411
- const initializationVector = message.slice(SEQUENCE_NUMBER_BYTES, SEQUENCE_NUMBER_BYTES + INITIALIZATION_VECTOR_BYTES);
412
- const ciphertext = message.slice(SEQUENCE_NUMBER_BYTES + INITIALIZATION_VECTOR_BYTES);
413
- const plaintextBuffer = yield crypto.subtle.decrypt(getAlgorithmParams(sequenceNumberVector, initializationVector), sharedSecret, ciphertext);
414
- const plaintext = getUtf8Decoder().decode(plaintextBuffer);
415
- return plaintext;
416
- });
417
- }
418
- function getAlgorithmParams(sequenceNumber, initializationVector) {
419
- return {
420
- additionalData: sequenceNumber,
421
- iv: initializationVector,
422
- name: 'AES-GCM',
423
- tagLength: 128, // 16 byte tag => 128 bits
424
- };
425
- }
426
- let _utf8Decoder;
427
- function getUtf8Decoder() {
428
- if (_utf8Decoder === undefined) {
429
- _utf8Decoder = new TextDecoder('utf-8');
430
- }
431
- return _utf8Decoder;
432
- }
433
-
434
- function generateAssociationKeypair() {
435
- return __awaiter$1(this, void 0, void 0, function* () {
436
- return yield crypto.subtle.generateKey({
437
- name: 'ECDSA',
438
- namedCurve: 'P-256',
439
- }, false /* extractable */, ['sign'] /* keyUsages */);
440
- });
441
- }
442
-
443
- function generateECDHKeypair() {
444
- return __awaiter$1(this, void 0, void 0, function* () {
445
- return yield crypto.subtle.generateKey({
446
- name: 'ECDH',
447
- namedCurve: 'P-256',
448
- }, false /* extractable */, ['deriveKey', 'deriveBits'] /* keyUsages */);
449
- });
450
- }
451
-
452
- // https://stackoverflow.com/a/9458996/802047
453
- function arrayBufferToBase64String(buffer) {
454
- let binary = '';
455
- const bytes = new Uint8Array(buffer);
456
- const len = bytes.byteLength;
457
- for (let ii = 0; ii < len; ii++) {
458
- binary += String.fromCharCode(bytes[ii]);
459
- }
460
- return window.btoa(binary);
461
- }
462
-
463
- function getRandomAssociationPort() {
464
- return assertAssociationPort(49152 + Math.floor(Math.random() * (65535 - 49152 + 1)));
465
- }
466
- function assertAssociationPort(port) {
467
- if (port < 49152 || port > 65535) {
468
- throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_PORT_OUT_OF_RANGE, `Association port number must be between 49152 and 65535. ${port} given.`, { port });
469
- }
470
- return port;
471
- }
472
-
473
- function getStringWithURLUnsafeCharactersReplaced(unsafeBase64EncodedString) {
474
- return unsafeBase64EncodedString.replace(/[/+=]/g, (m) => ({
475
- '/': '_',
476
- '+': '-',
477
- '=': '.',
478
- }[m]));
479
- }
480
-
481
- const INTENT_NAME = 'solana-wallet';
482
- function getPathParts(pathString) {
483
- return (pathString
484
- // Strip leading and trailing slashes
485
- .replace(/(^\/+|\/+$)/g, '')
486
- // Return an array of directories
487
- .split('/'));
488
- }
489
- function getIntentURL(methodPathname, intentUrlBase) {
490
- let baseUrl = null;
491
- if (intentUrlBase) {
492
- try {
493
- baseUrl = new URL(intentUrlBase);
494
- }
495
- catch (_a) { } // eslint-disable-line no-empty
496
- if ((baseUrl === null || baseUrl === void 0 ? void 0 : baseUrl.protocol) !== 'https:') {
497
- throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL, 'Base URLs supplied by wallets must be valid `https` URLs');
498
- }
499
- }
500
- baseUrl || (baseUrl = new URL(`${INTENT_NAME}:/`));
501
- const pathname = methodPathname.startsWith('/')
502
- ? // Method is an absolute path. Replace it wholesale.
503
- methodPathname
504
- : // Method is a relative path. Merge it with the existing one.
505
- [...getPathParts(baseUrl.pathname), ...getPathParts(methodPathname)].join('/');
506
- return new URL(pathname, baseUrl);
507
- }
508
- function getAssociateAndroidIntentURL(associationPublicKey, putativePort, associationURLBase, protocolVersions = ['v1']) {
509
- return __awaiter$1(this, void 0, void 0, function* () {
510
- const associationPort = assertAssociationPort(putativePort);
511
- const exportedKey = yield crypto.subtle.exportKey('raw', associationPublicKey);
512
- const encodedKey = arrayBufferToBase64String(exportedKey);
513
- const url = getIntentURL('v1/associate/local', associationURLBase);
514
- url.searchParams.set('association', getStringWithURLUnsafeCharactersReplaced(encodedKey));
515
- url.searchParams.set('port', `${associationPort}`);
516
- protocolVersions.forEach((version) => {
517
- url.searchParams.set('v', version);
518
- });
519
- return url;
520
- });
521
- }
522
- function getRemoteAssociateAndroidIntentURL(associationPublicKey, hostAuthority, reflectorId, associationURLBase, protocolVersions = ['v1']) {
523
- return __awaiter$1(this, void 0, void 0, function* () {
524
- const exportedKey = yield crypto.subtle.exportKey('raw', associationPublicKey);
525
- const encodedKey = arrayBufferToBase64String(exportedKey);
526
- const url = getIntentURL('v1/associate/remote', associationURLBase);
527
- url.searchParams.set('association', getStringWithURLUnsafeCharactersReplaced(encodedKey));
528
- url.searchParams.set('reflector', `${hostAuthority}`);
529
- url.searchParams.set('id', `${fromUint8Array$1(reflectorId, true)}`);
530
- protocolVersions.forEach((version) => {
531
- url.searchParams.set('v', version);
532
- });
533
- return url;
534
- });
535
- }
536
-
537
- function encryptJsonRpcMessage(jsonRpcMessage, sharedSecret) {
538
- return __awaiter$1(this, void 0, void 0, function* () {
539
- const plaintext = JSON.stringify(jsonRpcMessage);
540
- const sequenceNumber = jsonRpcMessage.id;
541
- return encryptMessage(plaintext, sequenceNumber, sharedSecret);
542
- });
543
- }
544
- function decryptJsonRpcMessage(message, sharedSecret) {
545
- return __awaiter$1(this, void 0, void 0, function* () {
546
- const plaintext = yield decryptMessage(message, sharedSecret);
547
- const jsonRpcMessage = JSON.parse(plaintext);
548
- if (Object.hasOwnProperty.call(jsonRpcMessage, 'error')) {
549
- throw new SolanaMobileWalletAdapterProtocolError(jsonRpcMessage.id, jsonRpcMessage.error.code, jsonRpcMessage.error.message);
550
- }
551
- return jsonRpcMessage;
552
- });
553
- }
554
-
555
- function parseHelloRsp(payloadBuffer, // The X9.62-encoded wallet endpoint ephemeral ECDH public keypoint.
556
- associationPublicKey, ecdhPrivateKey) {
557
- return __awaiter$1(this, void 0, void 0, function* () {
558
- const [associationPublicKeyBuffer, walletPublicKey] = yield Promise.all([
559
- crypto.subtle.exportKey('raw', associationPublicKey),
560
- crypto.subtle.importKey('raw', payloadBuffer.slice(0, ENCODED_PUBLIC_KEY_LENGTH_BYTES), { name: 'ECDH', namedCurve: 'P-256' }, false /* extractable */, [] /* keyUsages */),
561
- ]);
562
- const sharedSecret = yield crypto.subtle.deriveBits({ name: 'ECDH', public: walletPublicKey }, ecdhPrivateKey, 256);
563
- const ecdhSecretKey = yield crypto.subtle.importKey('raw', sharedSecret, 'HKDF', false /* extractable */, ['deriveKey'] /* keyUsages */);
564
- const aesKeyMaterialVal = yield crypto.subtle.deriveKey({
565
- name: 'HKDF',
566
- hash: 'SHA-256',
567
- salt: new Uint8Array(associationPublicKeyBuffer),
568
- info: new Uint8Array(),
569
- }, ecdhSecretKey, { name: 'AES-GCM', length: 128 }, false /* extractable */, ['encrypt', 'decrypt']);
570
- return aesKeyMaterialVal;
571
- });
572
- }
573
-
574
- function parseSessionProps(message, sharedSecret) {
575
- return __awaiter$1(this, void 0, void 0, function* () {
576
- const plaintext = yield decryptMessage(message, sharedSecret);
577
- const jsonProperties = JSON.parse(plaintext);
578
- let protocolVersion = 'legacy';
579
- if (Object.hasOwnProperty.call(jsonProperties, 'v')) {
580
- switch (jsonProperties.v) {
581
- case 1:
582
- case '1':
583
- case 'v1':
584
- protocolVersion = 'v1';
585
- break;
586
- case 'legacy':
587
- protocolVersion = 'legacy';
588
- break;
589
- default:
590
- throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_INVALID_PROTOCOL_VERSION, `Unknown/unsupported protocol version: ${jsonProperties.v}`);
591
- }
592
- }
593
- return ({
594
- protocol_version: protocolVersion
595
- });
596
- });
597
- }
598
-
599
- // Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/
600
- const Browser = {
601
- Firefox: 0,
602
- Other: 1,
603
- };
604
- function assertUnreachable(x) {
605
- return x;
606
- }
607
- function getBrowser() {
608
- return navigator.userAgent.indexOf('Firefox/') !== -1 ? Browser.Firefox : Browser.Other;
609
- }
610
- function getDetectionPromise() {
611
- // Chrome and others silently fail if a custom protocol is not supported.
612
- // For these, we wait to see if the browser is navigated away from in
613
- // a reasonable amount of time (ie. the native wallet opened).
614
- return new Promise((resolve, reject) => {
615
- function cleanup() {
616
- clearTimeout(timeoutId);
617
- window.removeEventListener('blur', handleBlur);
618
- }
619
- function handleBlur() {
620
- cleanup();
621
- resolve();
622
- }
623
- window.addEventListener('blur', handleBlur);
624
- const timeoutId = setTimeout(() => {
625
- cleanup();
626
- reject();
627
- }, 3000);
628
- });
629
- }
630
- let _frame = null;
631
- function launchUrlThroughHiddenFrame(url) {
632
- if (_frame == null) {
633
- _frame = document.createElement('iframe');
634
- _frame.style.display = 'none';
635
- document.body.appendChild(_frame);
636
- }
637
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
638
- _frame.contentWindow.location.href = url.toString();
639
- }
640
- function launchAssociation(associationUrl) {
641
- return __awaiter$1(this, void 0, void 0, function* () {
642
- if (associationUrl.protocol === 'https:') {
643
- // The association URL is an Android 'App Link' or iOS 'Universal Link'.
644
- // These are regular web URLs that are designed to launch an app if it
645
- // is installed or load the actual target webpage if not.
646
- window.location.assign(associationUrl);
647
- }
648
- else {
649
- // The association URL has a custom protocol (eg. `solana-wallet:`)
650
- try {
651
- const browser = getBrowser();
652
- switch (browser) {
653
- case Browser.Firefox:
654
- // If a custom protocol is not supported in Firefox, it throws.
655
- launchUrlThroughHiddenFrame(associationUrl);
656
- // If we reached this line, it's supported.
657
- break;
658
- case Browser.Other: {
659
- const detectionPromise = getDetectionPromise();
660
- window.location.assign(associationUrl);
661
- yield detectionPromise;
662
- break;
663
- }
664
- default:
665
- assertUnreachable(browser);
666
- }
667
- }
668
- catch (e) {
669
- throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_WALLET_NOT_FOUND, 'Found no installed wallet that supports the mobile wallet protocol.');
670
- }
671
- }
672
- });
673
- }
674
- function startSession(associationPublicKey, associationURLBase) {
675
- return __awaiter$1(this, void 0, void 0, function* () {
676
- const randomAssociationPort = getRandomAssociationPort();
677
- const associationUrl = yield getAssociateAndroidIntentURL(associationPublicKey, randomAssociationPort, associationURLBase);
678
- yield launchAssociation(associationUrl);
679
- return randomAssociationPort;
680
- });
681
- }
682
-
683
- const WEBSOCKET_CONNECTION_CONFIG = {
684
- /**
685
- * 300 milliseconds is a generally accepted threshold for what someone
686
- * would consider an acceptable response time for a user interface
687
- * after having performed a low-attention tapping task. We set the initial
688
- * interval at which we wait for the wallet to set up the websocket at
689
- * half this, as per the Nyquist frequency, with a progressive backoff
690
- * sequence from there. The total wait time is 30s, which allows for the
691
- * user to be presented with a disambiguation dialog, select a wallet, and
692
- * for the wallet app to subsequently start.
693
- */
694
- retryDelayScheduleMs: [150, 150, 200, 500, 500, 750, 750, 1000],
695
- timeoutMs: 30000,
696
- };
697
- const WEBSOCKET_PROTOCOL_BINARY = 'com.solana.mobilewalletadapter.v1';
698
- const WEBSOCKET_PROTOCOL_BASE64 = 'com.solana.mobilewalletadapter.v1.base64';
699
- function assertSecureContext() {
700
- if (typeof window === 'undefined' || window.isSecureContext !== true) {
701
- throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SECURE_CONTEXT_REQUIRED, 'The mobile wallet adapter protocol must be used in a secure context (`https`).');
702
- }
703
- }
704
- function assertSecureEndpointSpecificURI(walletUriBase) {
705
- let url;
706
- try {
707
- url = new URL(walletUriBase);
708
- }
709
- catch (_a) {
710
- throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL, 'Invalid base URL supplied by wallet');
711
- }
712
- if (url.protocol !== 'https:') {
713
- throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL, 'Base URLs supplied by wallets must be valid `https` URLs');
714
- }
715
- }
716
- function getSequenceNumberFromByteArray(byteArray) {
717
- const view = new DataView(byteArray);
718
- return view.getUint32(0, /* littleEndian */ false);
719
- }
720
- function decodeVarLong(byteArray) {
721
- var bytes = new Uint8Array(byteArray), l = byteArray.byteLength, limit = 10, value = 0, offset = 0, b;
722
- do {
723
- if (offset >= l || offset > limit)
724
- throw new RangeError('Failed to decode varint');
725
- b = bytes[offset++];
726
- value |= (b & 0x7F) << (7 * offset);
727
- } while (b >= 0x80);
728
- return { value, offset };
729
- }
730
- function getReflectorIdFromByteArray(byteArray) {
731
- let { value: length, offset } = decodeVarLong(byteArray);
732
- return new Uint8Array(byteArray.slice(offset, offset + length));
733
- }
734
- function transact$1(callback, config) {
735
- return __awaiter$1(this, void 0, void 0, function* () {
736
- assertSecureContext();
737
- const associationKeypair = yield generateAssociationKeypair();
738
- const sessionPort = yield startSession(associationKeypair.publicKey, config === null || config === void 0 ? void 0 : config.baseUri);
739
- const websocketURL = `ws://localhost:${sessionPort}/solana-wallet`;
740
- let connectionStartTime;
741
- const getNextRetryDelayMs = (() => {
742
- const schedule = [...WEBSOCKET_CONNECTION_CONFIG.retryDelayScheduleMs];
743
- return () => (schedule.length > 1 ? schedule.shift() : schedule[0]);
744
- })();
745
- let nextJsonRpcMessageId = 1;
746
- let lastKnownInboundSequenceNumber = 0;
747
- let state = { __type: 'disconnected' };
748
- return new Promise((resolve, reject) => {
749
- let socket;
750
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
751
- const jsonRpcResponsePromises = {};
752
- const handleOpen = () => __awaiter$1(this, void 0, void 0, function* () {
753
- if (state.__type !== 'connecting') {
754
- console.warn('Expected adapter state to be `connecting` at the moment the websocket opens. ' +
755
- `Got \`${state.__type}\`.`);
756
- return;
757
- }
758
- socket.removeEventListener('open', handleOpen);
759
- // previous versions of this library and walletlib incorrectly implemented the MWA session
760
- // establishment protocol for local connections. The dapp is supposed to wait for the
761
- // APP_PING message before sending the HELLO_REQ. Instead, the dapp was sending the HELLO_REQ
762
- // immediately upon connection to the websocket server regardless of wether or not an
763
- // APP_PING was sent by the wallet/websocket server. We must continue to support this behavior
764
- // in case the user is using a wallet that has not updated their walletlib implementation.
765
- const { associationKeypair } = state;
766
- const ecdhKeypair = yield generateECDHKeypair();
767
- socket.send(yield createHelloReq(ecdhKeypair.publicKey, associationKeypair.privateKey));
768
- state = {
769
- __type: 'hello_req_sent',
770
- associationPublicKey: associationKeypair.publicKey,
771
- ecdhPrivateKey: ecdhKeypair.privateKey,
772
- };
773
- });
774
- const handleClose = (evt) => {
775
- if (evt.wasClean) {
776
- state = { __type: 'disconnected' };
777
- }
778
- else {
779
- reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_CLOSED, `The wallet session dropped unexpectedly (${evt.code}: ${evt.reason}).`, { closeEvent: evt }));
780
- }
781
- disposeSocket();
782
- };
783
- const handleError = (_evt) => __awaiter$1(this, void 0, void 0, function* () {
784
- disposeSocket();
785
- if (Date.now() - connectionStartTime >= WEBSOCKET_CONNECTION_CONFIG.timeoutMs) {
786
- reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_TIMEOUT, `Failed to connect to the wallet websocket at ${websocketURL}.`));
787
- }
788
- else {
789
- yield new Promise((resolve) => {
790
- const retryDelayMs = getNextRetryDelayMs();
791
- retryWaitTimeoutId = window.setTimeout(resolve, retryDelayMs);
792
- });
793
- attemptSocketConnection();
794
- }
795
- });
796
- const handleMessage = (evt) => __awaiter$1(this, void 0, void 0, function* () {
797
- const responseBuffer = yield evt.data.arrayBuffer();
798
- switch (state.__type) {
799
- case 'connecting':
800
- if (responseBuffer.byteLength !== 0) {
801
- throw new Error('Encountered unexpected message while connecting');
802
- }
803
- const ecdhKeypair = yield generateECDHKeypair();
804
- socket.send(yield createHelloReq(ecdhKeypair.publicKey, associationKeypair.privateKey));
805
- state = {
806
- __type: 'hello_req_sent',
807
- associationPublicKey: associationKeypair.publicKey,
808
- ecdhPrivateKey: ecdhKeypair.privateKey,
809
- };
810
- break;
811
- case 'connected':
812
- try {
813
- const sequenceNumberVector = responseBuffer.slice(0, SEQUENCE_NUMBER_BYTES);
814
- const sequenceNumber = getSequenceNumberFromByteArray(sequenceNumberVector);
815
- if (sequenceNumber !== (lastKnownInboundSequenceNumber + 1)) {
816
- throw new Error('Encrypted message has invalid sequence number');
817
- }
818
- lastKnownInboundSequenceNumber = sequenceNumber;
819
- const jsonRpcMessage = yield decryptJsonRpcMessage(responseBuffer, state.sharedSecret);
820
- const responsePromise = jsonRpcResponsePromises[jsonRpcMessage.id];
821
- delete jsonRpcResponsePromises[jsonRpcMessage.id];
822
- responsePromise.resolve(jsonRpcMessage.result);
823
- }
824
- catch (e) {
825
- if (e instanceof SolanaMobileWalletAdapterProtocolError) {
826
- const responsePromise = jsonRpcResponsePromises[e.jsonRpcMessageId];
827
- delete jsonRpcResponsePromises[e.jsonRpcMessageId];
828
- responsePromise.reject(e);
829
- }
830
- else {
831
- throw e;
832
- }
833
- }
834
- break;
835
- case 'hello_req_sent': {
836
- // if we receive an APP_PING message (empty message), resend the HELLO_REQ (see above)
837
- if (responseBuffer.byteLength === 0) {
838
- const ecdhKeypair = yield generateECDHKeypair();
839
- socket.send(yield createHelloReq(ecdhKeypair.publicKey, associationKeypair.privateKey));
840
- state = {
841
- __type: 'hello_req_sent',
842
- associationPublicKey: associationKeypair.publicKey,
843
- ecdhPrivateKey: ecdhKeypair.privateKey,
844
- };
845
- break;
846
- }
847
- const sharedSecret = yield parseHelloRsp(responseBuffer, state.associationPublicKey, state.ecdhPrivateKey);
848
- const sessionPropertiesBuffer = responseBuffer.slice(ENCODED_PUBLIC_KEY_LENGTH_BYTES);
849
- const sessionProperties = sessionPropertiesBuffer.byteLength !== 0
850
- ? yield (() => __awaiter$1(this, void 0, void 0, function* () {
851
- const sequenceNumberVector = sessionPropertiesBuffer.slice(0, SEQUENCE_NUMBER_BYTES);
852
- const sequenceNumber = getSequenceNumberFromByteArray(sequenceNumberVector);
853
- if (sequenceNumber !== (lastKnownInboundSequenceNumber + 1)) {
854
- throw new Error('Encrypted message has invalid sequence number');
855
- }
856
- lastKnownInboundSequenceNumber = sequenceNumber;
857
- return parseSessionProps(sessionPropertiesBuffer, sharedSecret);
858
- }))() : { protocol_version: 'legacy' };
859
- state = { __type: 'connected', sharedSecret, sessionProperties };
860
- const wallet = createMobileWalletProxy(sessionProperties.protocol_version, (method, params) => __awaiter$1(this, void 0, void 0, function* () {
861
- const id = nextJsonRpcMessageId++;
862
- socket.send(yield encryptJsonRpcMessage({
863
- id,
864
- jsonrpc: '2.0',
865
- method,
866
- params: params !== null && params !== void 0 ? params : {},
867
- }, sharedSecret));
868
- return new Promise((resolve, reject) => {
869
- jsonRpcResponsePromises[id] = {
870
- resolve(result) {
871
- switch (method) {
872
- case 'authorize':
873
- case 'reauthorize': {
874
- const { wallet_uri_base } = result;
875
- if (wallet_uri_base != null) {
876
- try {
877
- assertSecureEndpointSpecificURI(wallet_uri_base);
878
- }
879
- catch (e) {
880
- reject(e);
881
- return;
882
- }
883
- }
884
- break;
885
- }
886
- }
887
- resolve(result);
888
- },
889
- reject,
890
- };
891
- });
892
- }));
893
- try {
894
- resolve(yield callback(wallet));
895
- }
896
- catch (e) {
897
- reject(e);
898
- }
899
- finally {
900
- disposeSocket();
901
- socket.close();
902
- }
903
- break;
904
- }
905
- }
906
- });
907
- let disposeSocket;
908
- let retryWaitTimeoutId;
909
- const attemptSocketConnection = () => {
910
- if (disposeSocket) {
911
- disposeSocket();
912
- }
913
- state = { __type: 'connecting', associationKeypair };
914
- if (connectionStartTime === undefined) {
915
- connectionStartTime = Date.now();
916
- }
917
- socket = new WebSocket(websocketURL, [WEBSOCKET_PROTOCOL_BINARY]);
918
- socket.addEventListener('open', handleOpen);
919
- socket.addEventListener('close', handleClose);
920
- socket.addEventListener('error', handleError);
921
- socket.addEventListener('message', handleMessage);
922
- disposeSocket = () => {
923
- window.clearTimeout(retryWaitTimeoutId);
924
- socket.removeEventListener('open', handleOpen);
925
- socket.removeEventListener('close', handleClose);
926
- socket.removeEventListener('error', handleError);
927
- socket.removeEventListener('message', handleMessage);
928
- };
929
- };
930
- attemptSocketConnection();
931
- });
932
- });
933
- }
934
- function startRemoteScenario$1(config) {
935
- return __awaiter$1(this, void 0, void 0, function* () {
936
- assertSecureContext();
937
- const associationKeypair = yield generateAssociationKeypair();
938
- const websocketURL = `wss://${config === null || config === void 0 ? void 0 : config.remoteHostAuthority}/reflect`;
939
- let connectionStartTime;
940
- const getNextRetryDelayMs = (() => {
941
- const schedule = [...WEBSOCKET_CONNECTION_CONFIG.retryDelayScheduleMs];
942
- return () => (schedule.length > 1 ? schedule.shift() : schedule[0]);
943
- })();
944
- let nextJsonRpcMessageId = 1;
945
- let lastKnownInboundSequenceNumber = 0;
946
- let encoding;
947
- let state = { __type: 'disconnected' };
948
- let socket;
949
- let disposeSocket;
950
- let decodeBytes = (evt) => __awaiter$1(this, void 0, void 0, function* () {
951
- if (encoding == 'base64') { // base64 encoding
952
- const message = yield evt.data;
953
- return toUint8Array$1(message).buffer;
954
- }
955
- else {
956
- return yield evt.data.arrayBuffer();
957
- }
958
- });
959
- // Reflector Connection Phase
960
- // here we connect to the reflector and wait for the REFLECTOR_ID message
961
- // so we build the association URL and return that back to the caller
962
- const associationUrl = yield new Promise((resolve, reject) => {
963
- const handleOpen = () => __awaiter$1(this, void 0, void 0, function* () {
964
- if (state.__type !== 'connecting') {
965
- console.warn('Expected adapter state to be `connecting` at the moment the websocket opens. ' +
966
- `Got \`${state.__type}\`.`);
967
- return;
968
- }
969
- if (socket.protocol.includes(WEBSOCKET_PROTOCOL_BASE64)) {
970
- encoding = 'base64';
971
- }
972
- else {
973
- encoding = 'binary';
974
- }
975
- socket.removeEventListener('open', handleOpen);
976
- });
977
- const handleClose = (evt) => {
978
- if (evt.wasClean) {
979
- state = { __type: 'disconnected' };
980
- }
981
- else {
982
- reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_CLOSED, `The wallet session dropped unexpectedly (${evt.code}: ${evt.reason}).`, { closeEvent: evt }));
983
- }
984
- disposeSocket();
985
- };
986
- const handleError = (_evt) => __awaiter$1(this, void 0, void 0, function* () {
987
- disposeSocket();
988
- if (Date.now() - connectionStartTime >= WEBSOCKET_CONNECTION_CONFIG.timeoutMs) {
989
- reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_TIMEOUT, `Failed to connect to the wallet websocket at ${websocketURL}.`));
990
- }
991
- else {
992
- yield new Promise((resolve) => {
993
- const retryDelayMs = getNextRetryDelayMs();
994
- retryWaitTimeoutId = window.setTimeout(resolve, retryDelayMs);
995
- });
996
- attemptSocketConnection();
997
- }
998
- });
999
- const handleReflectorIdMessage = (evt) => __awaiter$1(this, void 0, void 0, function* () {
1000
- const responseBuffer = yield decodeBytes(evt);
1001
- if (state.__type === 'connecting') {
1002
- if (responseBuffer.byteLength == 0) {
1003
- throw new Error('Encountered unexpected message while connecting');
1004
- }
1005
- const reflectorId = getReflectorIdFromByteArray(responseBuffer);
1006
- state = {
1007
- __type: 'reflector_id_received',
1008
- reflectorId: reflectorId
1009
- };
1010
- const associationUrl = yield getRemoteAssociateAndroidIntentURL(associationKeypair.publicKey, config.remoteHostAuthority, reflectorId, config === null || config === void 0 ? void 0 : config.baseUri);
1011
- socket.removeEventListener('message', handleReflectorIdMessage);
1012
- resolve(associationUrl);
1013
- }
1014
- });
1015
- let retryWaitTimeoutId;
1016
- const attemptSocketConnection = () => {
1017
- if (disposeSocket) {
1018
- disposeSocket();
1019
- }
1020
- state = { __type: 'connecting', associationKeypair };
1021
- if (connectionStartTime === undefined) {
1022
- connectionStartTime = Date.now();
1023
- }
1024
- socket = new WebSocket(websocketURL, [WEBSOCKET_PROTOCOL_BINARY, WEBSOCKET_PROTOCOL_BASE64]);
1025
- socket.addEventListener('open', handleOpen);
1026
- socket.addEventListener('close', handleClose);
1027
- socket.addEventListener('error', handleError);
1028
- socket.addEventListener('message', handleReflectorIdMessage);
1029
- disposeSocket = () => {
1030
- window.clearTimeout(retryWaitTimeoutId);
1031
- socket.removeEventListener('open', handleOpen);
1032
- socket.removeEventListener('close', handleClose);
1033
- socket.removeEventListener('error', handleError);
1034
- socket.removeEventListener('message', handleReflectorIdMessage);
1035
- };
1036
- };
1037
- attemptSocketConnection();
1038
- });
1039
- // Wallet Connection Phase
1040
- // here we return the association URL (containing the reflector ID) to the caller +
1041
- // a promise that will resolve the MobileWallet object once the wallet connects.
1042
- let sessionEstablished = false;
1043
- let handleClose;
1044
- return { associationUrl, close: () => {
1045
- socket.close();
1046
- handleClose();
1047
- }, wallet: new Promise((resolve, reject) => {
1048
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1049
- const jsonRpcResponsePromises = {};
1050
- const handleMessage = (evt) => __awaiter$1(this, void 0, void 0, function* () {
1051
- const responseBuffer = yield decodeBytes(evt);
1052
- switch (state.__type) {
1053
- case 'reflector_id_received':
1054
- if (responseBuffer.byteLength !== 0) {
1055
- throw new Error('Encountered unexpected message while awaiting reflection');
1056
- }
1057
- const ecdhKeypair = yield generateECDHKeypair();
1058
- const binaryMsg = yield createHelloReq(ecdhKeypair.publicKey, associationKeypair.privateKey);
1059
- if (encoding == 'base64') {
1060
- socket.send(fromUint8Array$1(binaryMsg));
1061
- }
1062
- else {
1063
- socket.send(binaryMsg);
1064
- }
1065
- state = {
1066
- __type: 'hello_req_sent',
1067
- associationPublicKey: associationKeypair.publicKey,
1068
- ecdhPrivateKey: ecdhKeypair.privateKey,
1069
- };
1070
- break;
1071
- case 'connected':
1072
- try {
1073
- const sequenceNumberVector = responseBuffer.slice(0, SEQUENCE_NUMBER_BYTES);
1074
- const sequenceNumber = getSequenceNumberFromByteArray(sequenceNumberVector);
1075
- if (sequenceNumber !== (lastKnownInboundSequenceNumber + 1)) {
1076
- throw new Error('Encrypted message has invalid sequence number');
1077
- }
1078
- lastKnownInboundSequenceNumber = sequenceNumber;
1079
- const jsonRpcMessage = yield decryptJsonRpcMessage(responseBuffer, state.sharedSecret);
1080
- const responsePromise = jsonRpcResponsePromises[jsonRpcMessage.id];
1081
- delete jsonRpcResponsePromises[jsonRpcMessage.id];
1082
- responsePromise.resolve(jsonRpcMessage.result);
1083
- }
1084
- catch (e) {
1085
- if (e instanceof SolanaMobileWalletAdapterProtocolError) {
1086
- const responsePromise = jsonRpcResponsePromises[e.jsonRpcMessageId];
1087
- delete jsonRpcResponsePromises[e.jsonRpcMessageId];
1088
- responsePromise.reject(e);
1089
- }
1090
- else {
1091
- throw e;
1092
- }
1093
- }
1094
- break;
1095
- case 'hello_req_sent': {
1096
- const sharedSecret = yield parseHelloRsp(responseBuffer, state.associationPublicKey, state.ecdhPrivateKey);
1097
- const sessionPropertiesBuffer = responseBuffer.slice(ENCODED_PUBLIC_KEY_LENGTH_BYTES);
1098
- const sessionProperties = sessionPropertiesBuffer.byteLength !== 0
1099
- ? yield (() => __awaiter$1(this, void 0, void 0, function* () {
1100
- const sequenceNumberVector = sessionPropertiesBuffer.slice(0, SEQUENCE_NUMBER_BYTES);
1101
- const sequenceNumber = getSequenceNumberFromByteArray(sequenceNumberVector);
1102
- if (sequenceNumber !== (lastKnownInboundSequenceNumber + 1)) {
1103
- throw new Error('Encrypted message has invalid sequence number');
1104
- }
1105
- lastKnownInboundSequenceNumber = sequenceNumber;
1106
- return parseSessionProps(sessionPropertiesBuffer, sharedSecret);
1107
- }))() : { protocol_version: 'legacy' };
1108
- state = { __type: 'connected', sharedSecret, sessionProperties };
1109
- const wallet = createMobileWalletProxy(sessionProperties.protocol_version, (method, params) => __awaiter$1(this, void 0, void 0, function* () {
1110
- const id = nextJsonRpcMessageId++;
1111
- const binaryMsg = yield encryptJsonRpcMessage({
1112
- id,
1113
- jsonrpc: '2.0',
1114
- method,
1115
- params: params !== null && params !== void 0 ? params : {},
1116
- }, sharedSecret);
1117
- if (encoding == 'base64') {
1118
- socket.send(fromUint8Array$1(binaryMsg));
1119
- }
1120
- else {
1121
- socket.send(binaryMsg);
1122
- }
1123
- return new Promise((resolve, reject) => {
1124
- jsonRpcResponsePromises[id] = {
1125
- resolve(result) {
1126
- switch (method) {
1127
- case 'authorize':
1128
- case 'reauthorize': {
1129
- const { wallet_uri_base } = result;
1130
- if (wallet_uri_base != null) {
1131
- try {
1132
- assertSecureEndpointSpecificURI(wallet_uri_base);
1133
- }
1134
- catch (e) {
1135
- reject(e);
1136
- return;
1137
- }
1138
- }
1139
- break;
1140
- }
1141
- }
1142
- resolve(result);
1143
- },
1144
- reject,
1145
- };
1146
- });
1147
- }));
1148
- sessionEstablished = true;
1149
- try {
1150
- resolve(wallet);
1151
- }
1152
- catch (e) {
1153
- reject(e);
1154
- }
1155
- break;
1156
- }
1157
- }
1158
- });
1159
- socket.addEventListener('message', handleMessage);
1160
- handleClose = () => {
1161
- socket.removeEventListener('message', handleMessage);
1162
- disposeSocket();
1163
- if (!sessionEstablished) {
1164
- reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_CLOSED, `The wallet session was closed before connection.`, { closeEvent: new CloseEvent('socket was closed before connection') }));
1165
- }
1166
- };
1167
- }) };
1168
- });
1169
- }
1170
-
1171
- var src;
1172
- var hasRequiredSrc;
1173
-
1174
- function requireSrc () {
1175
- if (hasRequiredSrc) return src;
1176
- hasRequiredSrc = 1;
1177
- // base-x encoding / decoding
1178
- // Copyright (c) 2018 base-x contributors
1179
- // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
1180
- // Distributed under the MIT software license, see the accompanying
1181
- // file LICENSE or http://www.opensource.org/licenses/mit-license.php.
1182
- function base (ALPHABET) {
1183
- if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }
1184
- var BASE_MAP = new Uint8Array(256);
1185
- for (var j = 0; j < BASE_MAP.length; j++) {
1186
- BASE_MAP[j] = 255;
1187
- }
1188
- for (var i = 0; i < ALPHABET.length; i++) {
1189
- var x = ALPHABET.charAt(i);
1190
- var xc = x.charCodeAt(0);
1191
- if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }
1192
- BASE_MAP[xc] = i;
1193
- }
1194
- var BASE = ALPHABET.length;
1195
- var LEADER = ALPHABET.charAt(0);
1196
- var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
1197
- var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
1198
- function encode (source) {
1199
- if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {
1200
- source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
1201
- } else if (Array.isArray(source)) {
1202
- source = Uint8Array.from(source);
1203
- }
1204
- if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }
1205
- if (source.length === 0) { return '' }
1206
- // Skip & count leading zeroes.
1207
- var zeroes = 0;
1208
- var length = 0;
1209
- var pbegin = 0;
1210
- var pend = source.length;
1211
- while (pbegin !== pend && source[pbegin] === 0) {
1212
- pbegin++;
1213
- zeroes++;
1214
- }
1215
- // Allocate enough space in big-endian base58 representation.
1216
- var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
1217
- var b58 = new Uint8Array(size);
1218
- // Process the bytes.
1219
- while (pbegin !== pend) {
1220
- var carry = source[pbegin];
1221
- // Apply "b58 = b58 * 256 + ch".
1222
- var i = 0;
1223
- for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
1224
- carry += (256 * b58[it1]) >>> 0;
1225
- b58[it1] = (carry % BASE) >>> 0;
1226
- carry = (carry / BASE) >>> 0;
1227
- }
1228
- if (carry !== 0) { throw new Error('Non-zero carry') }
1229
- length = i;
1230
- pbegin++;
1231
- }
1232
- // Skip leading zeroes in base58 result.
1233
- var it2 = size - length;
1234
- while (it2 !== size && b58[it2] === 0) {
1235
- it2++;
1236
- }
1237
- // Translate the result into a string.
1238
- var str = LEADER.repeat(zeroes);
1239
- for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }
1240
- return str
1241
- }
1242
- function decodeUnsafe (source) {
1243
- if (typeof source !== 'string') { throw new TypeError('Expected String') }
1244
- if (source.length === 0) { return new Uint8Array() }
1245
- var psz = 0;
1246
- // Skip and count leading '1's.
1247
- var zeroes = 0;
1248
- var length = 0;
1249
- while (source[psz] === LEADER) {
1250
- zeroes++;
1251
- psz++;
1252
- }
1253
- // Allocate enough space in big-endian base256 representation.
1254
- var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
1255
- var b256 = new Uint8Array(size);
1256
- // Process the characters.
1257
- while (source[psz]) {
1258
- // Find code of next character
1259
- var charCode = source.charCodeAt(psz);
1260
- // Base map can not be indexed using char code
1261
- if (charCode > 255) { return }
1262
- // Decode character
1263
- var carry = BASE_MAP[charCode];
1264
- // Invalid character
1265
- if (carry === 255) { return }
1266
- var i = 0;
1267
- for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
1268
- carry += (BASE * b256[it3]) >>> 0;
1269
- b256[it3] = (carry % 256) >>> 0;
1270
- carry = (carry / 256) >>> 0;
1271
- }
1272
- if (carry !== 0) { throw new Error('Non-zero carry') }
1273
- length = i;
1274
- psz++;
1275
- }
1276
- // Skip leading zeroes in b256.
1277
- var it4 = size - length;
1278
- while (it4 !== size && b256[it4] === 0) {
1279
- it4++;
1280
- }
1281
- var vch = new Uint8Array(zeroes + (size - it4));
1282
- var j = zeroes;
1283
- while (it4 !== size) {
1284
- vch[j++] = b256[it4++];
1285
- }
1286
- return vch
1287
- }
1288
- function decode (string) {
1289
- var buffer = decodeUnsafe(string);
1290
- if (buffer) { return buffer }
1291
- throw new Error('Non-base' + BASE + ' character')
1292
- }
1293
- return {
1294
- encode: encode,
1295
- decodeUnsafe: decodeUnsafe,
1296
- decode: decode
1297
- }
1298
- }
1299
- src = base;
1300
- return src;
1301
- }
1302
-
1303
- var bs58$1;
1304
- var hasRequiredBs58;
1305
-
1306
- function requireBs58 () {
1307
- if (hasRequiredBs58) return bs58$1;
1308
- hasRequiredBs58 = 1;
1309
- const basex = requireSrc();
1310
- const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
1311
-
1312
- bs58$1 = basex(ALPHABET);
1313
- return bs58$1;
1314
- }
1315
-
1316
- var bs58Exports = requireBs58();
1317
- var bs58 = /*@__PURE__*/index_native.getDefaultExportFromCjs(bs58Exports);
1318
-
1319
- /******************************************************************************
1320
- Copyright (c) Microsoft Corporation.
1321
-
1322
- Permission to use, copy, modify, and/or distribute this software for any
1323
- purpose with or without fee is hereby granted.
1324
-
1325
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
1326
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
1327
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
1328
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
1329
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
1330
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
1331
- PERFORMANCE OF THIS SOFTWARE.
1332
- ***************************************************************************** */
1333
-
1334
- function __rest(s, e) {
1335
- var t = {};
1336
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
1337
- t[p] = s[p];
1338
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
1339
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
1340
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
1341
- t[p[i]] = s[p[i]];
1342
- }
1343
- return t;
1344
- }
1345
-
1346
- function __awaiter(thisArg, _arguments, P, generator) {
1347
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1348
- return new (P || (P = Promise))(function (resolve, reject) {
1349
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1350
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1351
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1352
- step((generator = generator.apply(thisArg, [])).next());
1353
- });
1354
- }
1355
-
1356
- function fromUint8Array(byteArray) {
1357
- return window.btoa(String.fromCharCode.call(null, ...byteArray));
1358
- }
1359
- function toUint8Array(base64EncodedByteArray) {
1360
- return new Uint8Array(window
1361
- .atob(base64EncodedByteArray)
1362
- .split('')
1363
- .map((c) => c.charCodeAt(0)));
1364
- }
1365
-
1366
- function getPayloadFromTransaction(transaction) {
1367
- const serializedTransaction = 'version' in transaction
1368
- ? transaction.serialize()
1369
- : transaction.serialize({
1370
- requireAllSignatures: false,
1371
- verifySignatures: false,
1372
- });
1373
- const payload = fromUint8Array(serializedTransaction);
1374
- return payload;
1375
- }
1376
- function getTransactionFromWireMessage(byteArray) {
1377
- const numSignatures = byteArray[0];
1378
- const messageOffset = numSignatures * web3_js.SIGNATURE_LENGTH_IN_BYTES + 1;
1379
- const version = web3_js.VersionedMessage.deserializeMessageVersion(byteArray.slice(messageOffset, byteArray.length));
1380
- if (version === 'legacy') {
1381
- return web3_js.Transaction.from(byteArray);
1382
- }
1383
- else {
1384
- return web3_js.VersionedTransaction.deserialize(byteArray);
1385
- }
1386
- }
1387
- function transact(callback, config) {
1388
- return __awaiter(this, void 0, void 0, function* () {
1389
- const augmentedCallback = (wallet) => {
1390
- return callback(augmentWalletAPI(wallet));
1391
- };
1392
- return yield transact$1(augmentedCallback, config);
1393
- });
1394
- }
1395
- function startRemoteScenario(config) {
1396
- return __awaiter(this, void 0, void 0, function* () {
1397
- const { wallet, close, associationUrl } = yield startRemoteScenario$1(config);
1398
- const augmentedPromise = wallet.then((wallet) => {
1399
- return augmentWalletAPI(wallet);
1400
- });
1401
- return { wallet: augmentedPromise, close, associationUrl };
1402
- });
1403
- }
1404
- function augmentWalletAPI(wallet) {
1405
- return new Proxy({}, {
1406
- get(target, p) {
1407
- if (target[p] == null) {
1408
- switch (p) {
1409
- case 'signAndSendTransactions':
1410
- target[p] = function (_a) {
1411
- var { minContextSlot, commitment, skipPreflight, maxRetries, waitForCommitmentToSendNextTransaction, transactions } = _a, rest = __rest(_a, ["minContextSlot", "commitment", "skipPreflight", "maxRetries", "waitForCommitmentToSendNextTransaction", "transactions"]);
1412
- return __awaiter(this, void 0, void 0, function* () {
1413
- const payloads = transactions.map(getPayloadFromTransaction);
1414
- const options = {
1415
- min_context_slot: minContextSlot,
1416
- commitment: commitment,
1417
- skip_preflight: skipPreflight,
1418
- max_retries: maxRetries,
1419
- wait_for_commitment_to_send_next_transaction: waitForCommitmentToSendNextTransaction
1420
- };
1421
- const { signatures: base64EncodedSignatures } = yield wallet.signAndSendTransactions(Object.assign(Object.assign(Object.assign({}, rest), (Object.values(options).some(element => element != null)
1422
- ? { options: options }
1423
- : null)), { payloads }));
1424
- const signatures = base64EncodedSignatures.map(toUint8Array).map(bs58.encode);
1425
- return signatures;
1426
- });
1427
- };
1428
- break;
1429
- case 'signMessages':
1430
- target[p] = function (_a) {
1431
- var { payloads } = _a, rest = __rest(_a, ["payloads"]);
1432
- return __awaiter(this, void 0, void 0, function* () {
1433
- const base64EncodedPayloads = payloads.map(fromUint8Array);
1434
- const { signed_payloads: base64EncodedSignedMessages } = yield wallet.signMessages(Object.assign(Object.assign({}, rest), { payloads: base64EncodedPayloads }));
1435
- const signedMessages = base64EncodedSignedMessages.map(toUint8Array);
1436
- return signedMessages;
1437
- });
1438
- };
1439
- break;
1440
- case 'signTransactions':
1441
- target[p] = function (_a) {
1442
- var { transactions } = _a, rest = __rest(_a, ["transactions"]);
1443
- return __awaiter(this, void 0, void 0, function* () {
1444
- const payloads = transactions.map(getPayloadFromTransaction);
1445
- const { signed_payloads: base64EncodedCompiledTransactions } = yield wallet.signTransactions(Object.assign(Object.assign({}, rest), { payloads }));
1446
- const compiledTransactions = base64EncodedCompiledTransactions.map(toUint8Array);
1447
- const signedTransactions = compiledTransactions.map(getTransactionFromWireMessage);
1448
- return signedTransactions;
1449
- });
1450
- };
1451
- break;
1452
- default: {
1453
- target[p] = wallet[p];
1454
- break;
1455
- }
1456
- }
1457
- }
1458
- return target[p];
1459
- },
1460
- defineProperty() {
1461
- return false;
1462
- },
1463
- deleteProperty() {
1464
- return false;
1465
- },
1466
- });
1467
- }
1468
-
1469
- exports.startRemoteScenario = startRemoteScenario;
1470
- exports.transact = transact;
1471
- //# sourceMappingURL=index.browser-JX3F6oPV.js.map