@imtbl/sdk 0.0.1-alpha.2 → 0.1.0-alpha

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.
package/dist/index.js CHANGED
@@ -1,45 +1,529 @@
1
- import { Config as Config$1, ImmutableX, TransfersApi, OrdersApi, UsersApi, Contracts, TradesApi, ExchangesApi, WithdrawalsApi, MintsApi, DepositsApi, EncodingApi, TokensApi, Configuration as Configuration$1, generateLegacyStarkPrivateKey, createStarkSigner } from '@imtbl/core-sdk';
1
+ import { ImmutableX, Config, Configuration, UsersApi, TransfersApi, OrdersApi, ExchangesApi, TradesApi, generateLegacyStarkPrivateKey, createStarkSigner, Contracts, WithdrawalsApi, MintsApi, DepositsApi, EncodingApi, TokensApi } from '@imtbl/core-sdk';
2
+ export { createStarkSigner as imxClientCreateStarkSigner, generateLegacyStarkPrivateKey as imxClientGenerateLegacyStarkPrivateKey } from '@imtbl/core-sdk';
3
+ import { UserManager } from 'oidc-client-ts';
4
+ import { ethers, utils, Contract } from 'ethers';
5
+ import { Magic } from 'magic-sdk';
6
+ import { OpenIdExtension } from '@magic-ext/oidc';
2
7
  import BN from 'bn.js';
3
8
  import * as encUtils from 'enc-utils';
4
9
  import { parseUnits } from '@ethersproject/units';
5
10
  import { BigNumber } from '@ethersproject/bignumber';
6
- import { ethers, utils, Contract } from 'ethers';
7
11
  import detectEthereumProvider from '@metamask/detect-provider';
8
- import { UserManager } from 'oidc-client-ts';
9
- import { Magic } from 'magic-sdk';
10
- import { OpenIdExtension } from '@magic-ext/oidc';
11
12
  import { Web3Provider } from '@ethersproject/providers';
12
13
 
13
14
  var Environment;
14
15
  (function (Environment) {
15
- Environment["DEVELOPMENT"] = "development";
16
- Environment["SANDBOX"] = "sandbox";
17
16
  Environment["PRODUCTION"] = "production";
17
+ Environment["SANDBOX"] = "sandbox";
18
18
  })(Environment || (Environment = {}));
19
- class Configuration {
20
- starkExConfig;
21
- constructor(config) {
22
- this.starkExConfig = config;
23
- }
24
- getStarkExConfig() {
25
- return this.starkExConfig;
26
- }
27
- }
28
- const PRODUCTION = {
29
- ...Config$1.PRODUCTION,
30
- env: Environment.PRODUCTION,
19
+ class ImmutableConfiguration {
20
+ environment;
21
+ apiKey;
22
+ constructor(options) {
23
+ this.environment = options.environment;
24
+ this.apiKey = options.apiKey;
25
+ }
26
+ }
27
+
28
+ // Set `sdkVersion` on config
29
+ const PRODUCTION = () => {
30
+ return Config.createConfig({
31
+ basePath: 'https://api.x.immutable.com',
32
+ chainID: 1,
33
+ coreContractAddress: '0x5FDCCA53617f4d2b9134B29090C87D01058e27e9',
34
+ registrationContractAddress: '0x72a06bf2a1CE5e39cBA06c0CAb824960B587d64c',
35
+ sdkVersion: 'ts-immutable-sdk-0.1.0-alpha',
36
+ });
31
37
  };
32
- const SANDBOX = {
33
- ...Config$1.SANDBOX,
34
- env: Environment.SANDBOX,
38
+ // Set `sdkVersion` on config
39
+ const SANDBOX = () => {
40
+ return Config.createConfig({
41
+ basePath: 'https://api.sandbox.x.immutable.com',
42
+ chainID: 5,
43
+ coreContractAddress: '0x7917eDb51ecD6CdB3F9854c3cc593F33de10c623',
44
+ registrationContractAddress: '0x1C97Ada273C9A52253f463042f29117090Cd7D83',
45
+ sdkVersion: 'ts-immutable-sdk-0.1.0-alpha',
46
+ });
35
47
  };
48
+ class ImxConfiguration {
49
+ immutableXConfig;
50
+ baseConfig;
51
+ constructor({ baseConfig, overrides }) {
52
+ this.baseConfig = baseConfig;
53
+ if (overrides) {
54
+ this.immutableXConfig = overrides.immutableXConfig;
55
+ }
56
+ else {
57
+ switch (baseConfig.environment) {
58
+ case Environment.SANDBOX: {
59
+ this.immutableXConfig = SANDBOX();
60
+ break;
61
+ }
62
+ case Environment.PRODUCTION: {
63
+ this.immutableXConfig = PRODUCTION();
64
+ break;
65
+ }
66
+ }
67
+ }
68
+ }
69
+ }
36
70
 
37
- /* eslint-disable @typescript-eslint/no-unused-vars */
38
- const StarkExAPIFactory = (config) => {
39
- const imtblClient = new ImmutableX(config.getStarkExConfig());
40
- const { deposit, registerOffchain, isRegisteredOnchain, prepareWithdrawal, completeWithdrawal, createOrder, cancelOrder, createTrade, transfer, batchNftTransfer, ...StarkEx } = imtblClient;
41
- return { ...StarkEx };
42
- };
71
+ class ImmutableXClient {
72
+ immutableX;
73
+ depositsApi;
74
+ mintsApi;
75
+ ordersApi;
76
+ tokensApi;
77
+ tradesApi;
78
+ transfersApi;
79
+ exchangeApi;
80
+ nftCheckoutPrimaryApi;
81
+ usersApi;
82
+ withdrawalsApi;
83
+ balanceApi;
84
+ assetApi;
85
+ collectionApi;
86
+ metadataApi;
87
+ metadataRefreshesApi;
88
+ projectsApi;
89
+ constructor(config) {
90
+ const imxConfig = new ImxConfiguration(config);
91
+ this.immutableX = new ImmutableX(imxConfig.immutableXConfig);
92
+ this.depositsApi = this.immutableX.depositsApi;
93
+ this.mintsApi = this.immutableX.mintsApi;
94
+ this.ordersApi = this.immutableX.ordersApi;
95
+ this.tokensApi = this.immutableX.tokensApi;
96
+ this.tradesApi = this.immutableX.tradesApi;
97
+ this.transfersApi = this.immutableX.transfersApi;
98
+ this.exchangeApi = this.immutableX.exchangeApi;
99
+ this.usersApi = this.immutableX.usersApi;
100
+ this.withdrawalsApi = this.immutableX.withdrawalsApi;
101
+ this.balanceApi = this.immutableX.balanceApi;
102
+ this.assetApi = this.immutableX.assetApi;
103
+ this.collectionApi = this.immutableX.collectionApi;
104
+ this.metadataApi = this.immutableX.metadataApi;
105
+ this.metadataRefreshesApi = this.immutableX.metadataRefreshesApi;
106
+ this.nftCheckoutPrimaryApi = this.immutableX.nftCheckoutPrimaryApi;
107
+ this.projectsApi = this.immutableX.projectsApi;
108
+ }
109
+ /**
110
+ * Get details of a Deposit with the given ID
111
+ * @param request - the request object containing the parameters to be provided in the API request
112
+ * @returns a promise that resolves with the requested Deposit
113
+ * @throws {@link index.IMXError}
114
+ */
115
+ getDeposit(request) {
116
+ return this.immutableX.getDeposit(request);
117
+ }
118
+ /**
119
+ * Get a list of Deposits
120
+ * @param request - optional request object containing the parameters to be provided in the API request
121
+ * @returns a promise that resolves with the requested list of Deposits
122
+ * @throws {@link index.IMXError}
123
+ */
124
+ listDeposits(request) {
125
+ return this.immutableX.listDeposits(request);
126
+ }
127
+ /**
128
+ * Get Stark keys for a registered User
129
+ * @param ethAddress - the eth address of the User
130
+ * @returns a promise that resolves with the requested User
131
+ * @throws {@link index.IMXError}
132
+ */
133
+ getUser(ethAddress) {
134
+ return this.immutableX.getUser(ethAddress);
135
+ }
136
+ /**
137
+ * Get details of an Asset
138
+ * @param request - the request object containing the parameters to be provided in the API request
139
+ * @returns a promise that resolves with the requested Asset
140
+ * @throws {@link index.IMXError}
141
+ */
142
+ getAsset(request) {
143
+ return this.immutableX.getAsset(request);
144
+ }
145
+ /**
146
+ * Get a list of Assets
147
+ * @param request - optional request object containing the parameters to be provided in the API request
148
+ * @returns a promise that resolves with the requested list of Assets
149
+ * @throws {@link index.IMXError}
150
+ */
151
+ listAssets(request) {
152
+ return this.immutableX.listAssets(request);
153
+ }
154
+ /**
155
+ * Create a Collection
156
+ * @param ethSigner - the L1 signer
157
+ * @param request - the request object to be provided in the API request
158
+ * @returns a promise that resolves with the created Collection
159
+ * @throws {@link index.IMXError}
160
+ */
161
+ createCollection(ethSigner, request) {
162
+ return this.immutableX.createCollection(ethSigner, request);
163
+ }
164
+ /**
165
+ * Get details of a Collection at the given address
166
+ * @param request - the request object containing the parameters to be provided in the API request
167
+ * @returns a promise that resolves with the requested Collection
168
+ * @throws {@link index.IMXError}
169
+ */
170
+ getCollection(request) {
171
+ return this.immutableX.getCollection(request);
172
+ }
173
+ /**
174
+ * Get a list of Collection filters
175
+ * @param request - the request object containing the parameters to be provided in the API request
176
+ * @returns a promise that resolves with the requested list of Collection Filters
177
+ * @throws {@link index.IMXError}
178
+ */
179
+ listCollectionFilters(request) {
180
+ return this.immutableX.listCollectionFilters(request);
181
+ }
182
+ /**
183
+ * Get a list of Collections
184
+ * @param request - optional request object containing the parameters to be provided in the API request
185
+ * @returns a promise that resolves with the requested list of Collections
186
+ * @throws {@link index.IMXError}
187
+ */
188
+ listCollections(request) {
189
+ return this.collectionApi.listCollections(request).then((res) => res.data);
190
+ }
191
+ /**
192
+ * Update a Collection
193
+ * @param ethSigner - the L1 signer
194
+ * @param collectionAddress - the Collection contract address
195
+ * @param request - the request object containing the parameters to be provided in the API request
196
+ * @returns a promise that resolves with the updated Collection
197
+ * @throws {@link index.IMXError}
198
+ */
199
+ updateCollection(ethSigner, collectionAddress, request) {
200
+ return this.immutableX.updateCollection(ethSigner, collectionAddress, request);
201
+ }
202
+ /**
203
+ * Add metadata schema to Collection
204
+ * @param ethSigner - the L1 signer
205
+ * @param collectionAddress - the Collection contract address
206
+ * @param request - the request object containing the parameters to be provided in the API request
207
+ * @returns a promise that resolves with the SuccessResponse if successful
208
+ * @throws {@link index.IMXError}
209
+ */
210
+ addMetadataSchemaToCollection(ethSigner, collectionAddress, request) {
211
+ return this.immutableX.addMetadataSchemaToCollection(ethSigner, collectionAddress, request);
212
+ }
213
+ /**
214
+ * Get Metadata schema
215
+ * @param request - the request object containing the parameters to be provided in the API request
216
+ * @returns a promise that resolves with the requested Metadata schema
217
+ * @throws {@link index.IMXError}
218
+ */
219
+ getMetadataSchema(request) {
220
+ return this.immutableX.getMetadataSchema(request);
221
+ }
222
+ /**
223
+ * Update metadata schema by name
224
+ * @param ethSigner - the L1 signer
225
+ * @param collectionAddress - the Collection contract address
226
+ * @param name - the Metadata schema name
227
+ * @param request - the request object containing the parameters to be provided in the API request
228
+ * @returns a promise that resolves with the SuccessResponse if successful
229
+ * @throws {@link index.IMXError}
230
+ */
231
+ updateMetadataSchemaByName(ethSigner, collectionAddress, name, request) {
232
+ return this.immutableX.updateMetadataSchemaByName(ethSigner, collectionAddress, name, request);
233
+ }
234
+ /**
235
+ * Get a list of metadata refreshes
236
+ * @param ethSigner - the L1 signer
237
+ * @param collectionAddress - the Collection contract address
238
+ * @param pageSize - the page size of the result
239
+ * @param cursor - the cursor
240
+ * @returns a promise that resolves with the requested metadata refreshes
241
+ * @throws {@link index.IMXError}
242
+ */
243
+ listMetadataRefreshes(ethSigner, collectionAddress, pageSize, cursor) {
244
+ return this.immutableX.listMetadataRefreshes(ethSigner, collectionAddress, pageSize, cursor);
245
+ }
246
+ /**
247
+ * Get a list of metadata refresh errors
248
+ * @param ethSigner - the L1 signer
249
+ * @param refreshId - the metadata refresh ID
250
+ * @param pageSize - the page size of the result
251
+ * @param cursor - the cursor
252
+ * @returns a promise that resolves with the requested metadata refresh errors
253
+ * @throws {@link index.IMXError}
254
+ */
255
+ getMetadataRefreshErrors(ethSigner, refreshId, pageSize, cursor) {
256
+ return this.immutableX.getMetadataRefreshErrors(ethSigner, refreshId, pageSize, cursor);
257
+ }
258
+ /**
259
+ * Get a list of metadata refresh results
260
+ * @param ethSigner - the L1 signer
261
+ * @param refreshId - the metadata refresh ID
262
+ * @returns a promise that resolves with the requested metadata refresh results
263
+ * @throws {@link index.IMXError}
264
+ */
265
+ getMetadataRefreshResults(ethSigner, refreshId) {
266
+ return this.immutableX.getMetadataRefreshResults(ethSigner, refreshId);
267
+ }
268
+ /**
269
+ * Request a metadata refresh
270
+ * @param ethSigner - the L1 signer
271
+ * @param request the request object containing the parameters to be provided in the API request
272
+ * @returns a promise that resolves with the requested metadata refresh
273
+ * @throws {@link index.IMXError}
274
+ */
275
+ createMetadataRefresh(ethSigner, request) {
276
+ return this.immutableX.createMetadataRefresh(ethSigner, request);
277
+ }
278
+ /**
279
+ * Create a Project
280
+ * @param ethSigner - the L1 signer
281
+ * @param request - the request object containing the parameters to be provided in the API request
282
+ * @returns a promise that resolves with the created Project
283
+ * @throws {@link index.IMXError}
284
+ */
285
+ async createProject(ethSigner, request) {
286
+ return this.immutableX.createProject(ethSigner, request);
287
+ }
288
+ /**
289
+ * Get a Project
290
+ * @param ethSigner - the L1 signer
291
+ * @param id - the Project ID
292
+ * @returns a promise that resolves with the requested Project
293
+ * @throws {@link index.IMXError}
294
+ */
295
+ async getProject(ethSigner, id) {
296
+ return this.immutableX.getProject(ethSigner, id);
297
+ }
298
+ /**
299
+ * Get Projects owned by the given User
300
+ * @param ethSigner - the L1 signer
301
+ * @param pageSize - the page size of the result
302
+ * @param cursor - the cursor
303
+ * @param orderBy - the property to sort by
304
+ * @param direction - direction to sort (asc/desc)
305
+ * @returns a promise that resolves with the requested Projects
306
+ * @throws {@link index.IMXError}
307
+ */
308
+ async getProjects(ethSigner, pageSize, cursor, orderBy, direction) {
309
+ return this.immutableX.getProjects(ethSigner, pageSize, cursor, orderBy, direction);
310
+ }
311
+ /**
312
+ * Get the token Balances of the User
313
+ * @param request - the request object containing the parameters to be provided in the API request
314
+ * @returns a promise that resolves with the requested Balance
315
+ * @throws {@link index.IMXError}
316
+ */
317
+ getBalance(request) {
318
+ return this.immutableX.getBalance(request);
319
+ }
320
+ /**
321
+ * Get a list of Balances for given User
322
+ * @param request the request object containing the parameters to be provided in the API request
323
+ * @returns a promise that resolves with the requested list of Balances
324
+ * @throws {@link index.IMXError}
325
+ */
326
+ listBalances(request) {
327
+ return this.immutableX.listBalances(request);
328
+ }
329
+ /**
330
+ * Get details of a Mint with the given ID
331
+ * @param request the request object containing the parameters to be provided in the API request
332
+ * @returns a promise that resolves with the requested Mint
333
+ * @throws {@link index.IMXError}
334
+ */
335
+ getMint(request) {
336
+ return this.immutableX.getMint(request);
337
+ }
338
+ /**
339
+ * Get a list of Mints
340
+ * @param request optional request object containing the parameters to be provided in the API request
341
+ * @returns a promise that resolves with the requested list of Mints
342
+ * @throws {@link index.IMXError}
343
+ */
344
+ listMints(request) {
345
+ return this.immutableX.listMints(request);
346
+ }
347
+ /**
348
+ * Mint tokens in a batch with fees
349
+ * @param ethSigner - the L1 signer
350
+ * @param request - the request object to be provided in the API request
351
+ * @returns a promise that resolves with the minted tokens
352
+ * @throws {@link index.IMXError}
353
+ */
354
+ mint(ethSigner, request) {
355
+ return this.immutableX.mint(ethSigner, request);
356
+ }
357
+ /**
358
+ * Get a list of Withdrawals
359
+ * @param request - optional request object containing the parameters to be provided in the API request
360
+ * @returns a promise that resolves with the requested list of Withdrawals
361
+ * @throws {@link index.IMXError}
362
+ */
363
+ listWithdrawals(request) {
364
+ return this.immutableX.listWithdrawals(request);
365
+ }
366
+ /**
367
+ * Get details of Withdrawal with the given ID
368
+ * @param request - the request object containing the parameters to be provided in the API request
369
+ * @returns a promise that resolves with the requested Withdrawal
370
+ * @throws {@link index.IMXError}
371
+ */
372
+ getWithdrawal(request) {
373
+ return this.immutableX.getWithdrawal(request);
374
+ }
375
+ /**
376
+ * Get details of an Order with the given ID
377
+ * @param request - the request object containing the parameters to be provided in the API request
378
+ * @returns a promise that resolves with the requested Order
379
+ * @throws {@link index.IMXError}
380
+ */
381
+ getOrder(request) {
382
+ return this.immutableX.getOrder(request);
383
+ }
384
+ /**
385
+ * Get a list of Orders
386
+ * @param request - optional request object containing the parameters to be provided in the API request
387
+ * @returns a promise that resolves with the requested list of Orders
388
+ * @throws {@link index.IMXError}
389
+ */
390
+ listOrders(request) {
391
+ return this.immutableX.listOrders(request);
392
+ }
393
+ /**
394
+ * Get details of a Trade with the given ID
395
+ * @param request - the request object containing the parameters to be provided in the API request
396
+ * @returns a promise that resolves with the requested Trade
397
+ * @throws {@link index.IMXError}
398
+ */
399
+ getTrade(request) {
400
+ return this.immutableX.getTrade(request);
401
+ }
402
+ /**
403
+ * Get a list of Trades
404
+ * @param request - optional request object containing the parameters to be provided in the API request
405
+ * @returns a promise that resolves with the requested list of Trades
406
+ * @throws {@link index.IMXError}
407
+ */
408
+ listTrades(request) {
409
+ return this.immutableX.listTrades(request);
410
+ }
411
+ /**
412
+ * Get details of a Token
413
+ * @param request - the request object containing the parameters to be provided in the API request
414
+ * @returns a promise that resolves with the requested Token
415
+ * @throws {@link index.IMXError}
416
+ */
417
+ getToken(request) {
418
+ return this.immutableX.getToken(request);
419
+ }
420
+ /**
421
+ * Get a list of Tokens
422
+ * @param request - optional request object containing the parameters to be provided in the API request
423
+ * @returns a promise that resolves with the requested list of Tokens
424
+ * @throws {@link index.IMXError}
425
+ */
426
+ listTokens(request) {
427
+ return this.immutableX.listTokens(request);
428
+ }
429
+ /**
430
+ * Get details of a Transfer with the given ID
431
+ * @param request - the request object containing the parameters to be provided in the API request
432
+ * @returns a promise that resolves with the requested Transfer
433
+ * @throws {@link index.IMXError}
434
+ */
435
+ getTransfer(request) {
436
+ return this.immutableX.getTransfer(request);
437
+ }
438
+ /**
439
+ * Get a list of Transfers
440
+ * @param request - optional request object containing the parameters to be provided in the API request
441
+ * @returns a promise that resolves with the requested list of Transfers
442
+ * @throws {@link index.IMXError}
443
+ */
444
+ listTransfers(request) {
445
+ return this.immutableX.listTransfers(request);
446
+ }
447
+ /**
448
+ * Create a new Exchange transaction
449
+ * @param request - the request object to be provided in the API request
450
+ * @returns a promise that resolves with the created Exchange Transaction
451
+ * @throws {@link index.IMXError}
452
+ */
453
+ createExchange(request) {
454
+ return this.immutableX.createExchange(request).then((res) => res.data);
455
+ }
456
+ /**
457
+ * Get an Exchange transaction
458
+ * @param request - the request object to be provided in the API request
459
+ * @returns a promise that resolves with the Exchange Transaction
460
+ * @throws {@link index.IMXError}
461
+ */
462
+ getExchange(request) {
463
+ return this.immutableX.getExchange(request).then((res) => res.data);
464
+ }
465
+ /**
466
+ * Get Exchange transactions
467
+ * @param request - the request object to be provided in the API request
468
+ * @returns a promise that resolves with Exchange Transactions
469
+ * @throws {@link index.IMXError}
470
+ */
471
+ getExchanges(request) {
472
+ return this.immutableX.getExchanges(request).then((res) => res.data);
473
+ }
474
+ /**
475
+ * Create a new Transfer request
476
+ * @param walletConnection - the pair of Eth/Stark signers
477
+ * @param request - the request object to be provided in the API request
478
+ * @returns a promise that resolves with the created Exchange Transfer
479
+ * @throws {@link index.IMXError}
480
+ */
481
+ exchangeTransfer(walletConnection, request) {
482
+ return this.immutableX.exchangeTransfer(walletConnection, request);
483
+ }
484
+ /**
485
+ * Create a new nft primary transaction
486
+ * @param request - the request object to be provided in the API request
487
+ * @returns a promise that resolves with the created nft primary Transaction
488
+ * @throws {@link index.IMXError}
489
+ */
490
+ createNftPrimary(request) {
491
+ return this.immutableX.createNftPrimary(request).then((res) => res.data);
492
+ }
493
+ /**
494
+ * Get nft primary supported currencies and their limits
495
+ * @param request - the request object to be provided in the API request
496
+ * @returns a promise that resolves with nft primary Currencies
497
+ * @throws {@link index.IMXError}
498
+ */
499
+ getCurrenciesNFTCheckoutPrimary(request) {
500
+ return this.immutableX
501
+ .getCurrenciesNFTCheckoutPrimary(request)
502
+ .then((res) => res.data);
503
+ }
504
+ /**
505
+ * Get nft primary transaction by transaction id
506
+ * @param request - the request object to be provided in the API request
507
+ * @returns a promise that resolves with nft primary transaction
508
+ * @throws {@link index.IMXError}
509
+ */
510
+ getNftPrimaryTransaction(request) {
511
+ return this.immutableX
512
+ .getNftPrimaryTransaction(request)
513
+ .then((res) => res.data);
514
+ }
515
+ /**
516
+ * Get list of nft primary transactions
517
+ * @param request - the request object to be provided in the API request
518
+ * @returns a promise that resolves with nft primary transaction
519
+ * @throws {@link index.IMXError}
520
+ */
521
+ getNftPrimaryTransactions(request) {
522
+ return this.immutableX
523
+ .getNftPrimaryTransactions(request)
524
+ .then((res) => res.data);
525
+ }
526
+ }
43
527
 
44
528
  // used to sign message with L1 keys. Used for registration
45
529
  function serializeEthSignature(sig) {
@@ -111,1876 +595,1923 @@ function convertToSignableToken(token) {
111
595
  }
112
596
  }
113
597
 
114
- function isChainValid(chainID, config) {
115
- return chainID === config.ethConfiguration.chainID;
116
- }
117
- async function validateChain(signer, config) {
118
- const chainID = await signer.getChainId();
119
- if (!isChainValid(chainID, config))
120
- throw new Error('The wallet used for this operation is not connected to the correct network.');
598
+ var PassportErrorType;
599
+ (function (PassportErrorType) {
600
+ PassportErrorType["AUTHENTICATION_ERROR"] = "AUTHENTICATION_ERROR";
601
+ PassportErrorType["INVALID_CONFIGURATION"] = "INVALID_CONFIGURATION";
602
+ PassportErrorType["WALLET_CONNECTION_ERROR"] = "WALLET_CONNECTION_ERROR";
603
+ PassportErrorType["NOT_LOGGED_IN_ERROR"] = "NOT_LOGGED_IN_ERROR";
604
+ PassportErrorType["SILENT_LOGIN_ERROR"] = "SILENT_LOGIN_ERROR";
605
+ PassportErrorType["REFRESH_TOKEN_ERROR"] = "REFRESH_TOKEN_ERROR";
606
+ PassportErrorType["USER_REGISTRATION_ERROR"] = "USER_REGISTRATION_ERROR";
607
+ PassportErrorType["LOGOUT_ERROR"] = "LOGOUT_ERROR";
608
+ PassportErrorType["TRANSFER_ERROR"] = "TRANSFER_ERROR";
609
+ PassportErrorType["CREATE_ORDER_ERROR"] = "CREATE_ORDER_ERROR";
610
+ PassportErrorType["CANCEL_ORDER_ERROR"] = "CANCEL_ORDER_ERROR";
611
+ PassportErrorType["EXCHANGE_TRANSFER_ERROR"] = "EXCHANGE_TRANSFER_ERROR";
612
+ PassportErrorType["CREATE_TRADE_ERROR"] = "CREATE_TRADE_ERROR";
613
+ PassportErrorType["OPERATION_NOT_SUPPORTED_ERROR"] = "OPERATION_NOT_SUPPORTED_ERROR";
614
+ })(PassportErrorType || (PassportErrorType = {}));
615
+ class PassportError extends Error {
616
+ type;
617
+ constructor(message, type) {
618
+ super(message);
619
+ this.type = type;
620
+ }
121
621
  }
622
+ const withPassportError = async (fn, customErrorType) => {
623
+ try {
624
+ return await fn();
625
+ }
626
+ catch (error) {
627
+ const errorMessage = `${customErrorType}: ${error.message}` || 'UnknownError';
628
+ throw new PassportError(errorMessage, customErrorType);
629
+ }
630
+ };
122
631
 
123
- async function transfer$1({ signers: { ethSigner, starkExSigner }, request, config, }) {
124
- await validateChain(ethSigner, config.getStarkExConfig());
125
- const ethAddress = await ethSigner.getAddress();
126
- const transfersApi = new TransfersApi(config.getStarkExConfig().apiConfiguration);
127
- const transferAmount = request.type === 'ERC721' ? '1' : request.amount;
128
- const signableResult = await transfersApi.getSignableTransferV1({
129
- getSignableTransferRequest: {
130
- sender: ethAddress,
131
- token: convertToSignableToken(request),
132
- amount: transferAmount,
133
- receiver: request.receiver,
632
+ const POLL_INTERVAL = 1 * 1000; // every 1 second
633
+ const MAX_RETRIES = 3;
634
+ const wait = (ms) => new Promise((resolve) => {
635
+ setTimeout(() => resolve(), ms);
636
+ });
637
+ const retryWithDelay = async (fn, options) => {
638
+ const { retries = MAX_RETRIES, interval = POLL_INTERVAL, finalErr = Error('Retry failed'), } = options || {};
639
+ try {
640
+ return await fn();
641
+ }
642
+ catch (err) {
643
+ if (retries <= 0) {
644
+ return Promise.reject(finalErr);
645
+ }
646
+ await wait(interval);
647
+ return retryWithDelay(fn, { retries: retries - 1, finalErr });
648
+ }
649
+ };
650
+
651
+ const getAuthConfiguration = ({ oidcConfiguration, authenticationDomain, }) => {
652
+ const baseConfiguration = {
653
+ authority: authenticationDomain,
654
+ redirect_uri: oidcConfiguration.redirectUri,
655
+ popup_redirect_uri: oidcConfiguration.redirectUri,
656
+ client_id: oidcConfiguration.clientId,
657
+ metadata: {
658
+ authorization_endpoint: `${authenticationDomain}/authorize`,
659
+ token_endpoint: `${authenticationDomain}/oauth/token`,
660
+ userinfo_endpoint: `${authenticationDomain}/userinfo`,
661
+ end_session_endpoint: `${authenticationDomain}/v2/logout` +
662
+ `?returnTo=${encodeURIComponent(oidcConfiguration.logoutRedirectUri)}` +
663
+ `&client_id=${oidcConfiguration.clientId}`,
134
664
  },
135
- });
136
- const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
137
- const ethSignature = await signRaw(signableMessage, ethSigner);
138
- const starkSignature = await starkExSigner.signMessage(payloadHash);
139
- const transferSigningParams = {
140
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
141
- sender_stark_key: signableResult.data.sender_stark_key,
142
- sender_vault_id: signableResult.data.sender_vault_id,
143
- receiver_stark_key: signableResult.data.receiver_stark_key,
144
- receiver_vault_id: signableResult.data.receiver_vault_id,
145
- asset_id: signableResult.data.asset_id,
146
- amount: signableResult.data.amount,
147
- nonce: signableResult.data.nonce,
148
- expiration_timestamp: signableResult.data.expiration_timestamp,
149
- stark_signature: starkSignature,
150
- };
151
- const response = await transfersApi.createTransferV1({
152
- createTransferRequest: transferSigningParams,
153
- xImxEthAddress: ethAddress,
154
- xImxEthSignature: ethSignature,
155
- });
156
- return {
157
- sent_signature: response?.data.sent_signature,
158
- status: response?.data.status?.toString(),
159
- time: response?.data.time,
160
- transfer_id: response?.data.transfer_id,
665
+ mergeClaims: true,
666
+ loadUserInfo: true,
667
+ scope: oidcConfiguration.scope,
161
668
  };
162
- }
163
- async function batchTransfer({ signers: { ethSigner, starkExSigner }, request, config, }) {
164
- await validateChain(ethSigner, config.getStarkExConfig());
165
- const ethAddress = await ethSigner.getAddress();
166
- const transfersApi = new TransfersApi(config.getStarkExConfig().apiConfiguration);
167
- const signableRequests = request.map((nftTransfer) => {
168
- return {
169
- amount: '1',
170
- token: convertToSignableToken({
171
- type: 'ERC721',
172
- tokenId: nftTransfer.tokenId,
173
- tokenAddress: nftTransfer.tokenAddress,
174
- }),
175
- receiver: nftTransfer.receiver,
669
+ if (oidcConfiguration.audience) {
670
+ baseConfiguration.extraQueryParams = {
671
+ audience: oidcConfiguration.audience,
176
672
  };
177
- });
178
- const signableResult = await transfersApi.getSignableTransfer({
179
- getSignableTransferRequestV2: {
180
- sender_ether_key: ethAddress,
181
- signable_requests: signableRequests,
182
- },
183
- });
184
- const signableMessage = signableResult.data.signable_message;
185
- if (signableMessage === undefined) {
186
- throw new Error('Invalid response from Signable registration offchain');
187
673
  }
188
- const ethSignature = await signRaw(signableMessage, ethSigner);
189
- const requests = [];
190
- for (const resp of signableResult.data.signable_responses) {
191
- const starkSignature = await starkExSigner.signMessage(resp.payload_hash);
192
- const req = {
193
- sender_vault_id: resp.sender_vault_id,
194
- receiver_stark_key: resp.receiver_stark_key,
195
- receiver_vault_id: resp.receiver_vault_id,
196
- asset_id: resp.asset_id,
197
- amount: resp.amount,
198
- nonce: resp.nonce,
199
- expiration_timestamp: resp.expiration_timestamp,
200
- stark_signature: starkSignature,
201
- };
202
- requests.push(req);
674
+ return baseConfiguration;
675
+ };
676
+ class AuthManager {
677
+ userManager;
678
+ config;
679
+ constructor(config) {
680
+ this.config = config;
681
+ this.userManager = new UserManager(getAuthConfiguration(config));
203
682
  }
204
- // TODO: throw error on missing payload hash?
205
- const transferSigningParams = {
206
- sender_stark_key: signableResult.data.sender_stark_key,
207
- requests,
208
- };
209
- const response = await transfersApi.createTransfer({
210
- createTransferRequestV2: transferSigningParams,
211
- xImxEthAddress: ethAddress,
212
- xImxEthSignature: ethSignature,
213
- });
214
- return {
215
- transfer_ids: response?.data.transfer_ids,
683
+ mapOidcUserToDomainModel = (oidcUser) => {
684
+ const passport = oidcUser.profile?.passport;
685
+ return {
686
+ expired: oidcUser.expired,
687
+ idToken: oidcUser.id_token,
688
+ accessToken: oidcUser.access_token,
689
+ refreshToken: oidcUser.refresh_token,
690
+ profile: {
691
+ sub: oidcUser.profile.sub,
692
+ email: oidcUser.profile.email,
693
+ nickname: oidcUser.profile.nickname,
694
+ },
695
+ etherKey: passport?.ether_key || '',
696
+ };
216
697
  };
698
+ async login() {
699
+ return withPassportError(async () => {
700
+ const popupWindowFeatures = { width: 410, height: 450 };
701
+ const oidcUser = await this.userManager.signinPopup({
702
+ popupWindowFeatures,
703
+ });
704
+ return this.mapOidcUserToDomainModel(oidcUser);
705
+ }, PassportErrorType.AUTHENTICATION_ERROR);
706
+ }
707
+ async loginCallback() {
708
+ return withPassportError(async () => this.userManager.signinPopupCallback(), PassportErrorType.AUTHENTICATION_ERROR);
709
+ }
710
+ async logout() {
711
+ return withPassportError(async () => this.userManager.signoutRedirect(), PassportErrorType.LOGOUT_ERROR);
712
+ }
713
+ async loginSilent() {
714
+ return withPassportError(async () => {
715
+ const existedUser = await this.getUser();
716
+ if (!existedUser) {
717
+ return null;
718
+ }
719
+ const oidcUser = await this.userManager.signinSilent();
720
+ if (!oidcUser) {
721
+ return null;
722
+ }
723
+ return this.mapOidcUserToDomainModel(oidcUser);
724
+ }, PassportErrorType.SILENT_LOGIN_ERROR);
725
+ }
726
+ async getUser() {
727
+ return withPassportError(async () => {
728
+ const oidcUser = await this.userManager.getUser();
729
+ if (!oidcUser) {
730
+ return null;
731
+ }
732
+ return this.mapOidcUserToDomainModel(oidcUser);
733
+ }, PassportErrorType.NOT_LOGGED_IN_ERROR);
734
+ }
735
+ async requestRefreshTokenAfterRegistration() {
736
+ return withPassportError(async () => {
737
+ const updatedUser = await retryWithDelay(async () => {
738
+ const user = await this.userManager.signinSilent();
739
+ const passportMetadata = user?.profile?.passport;
740
+ const metadataExists = !!passportMetadata?.ether_key &&
741
+ !!passportMetadata?.stark_key &&
742
+ !!passportMetadata?.user_admin_key;
743
+ if (metadataExists) {
744
+ return user;
745
+ }
746
+ return Promise.reject('user wallet addresses not exist');
747
+ });
748
+ if (!updatedUser) {
749
+ return null;
750
+ }
751
+ return this.mapOidcUserToDomainModel(updatedUser);
752
+ }, PassportErrorType.REFRESH_TOKEN_ERROR);
753
+ }
217
754
  }
218
755
 
219
- async function createOrder$1({ signers, request, config, }) {
220
- await validateChain(signers.ethSigner, config.getStarkExConfig());
221
- const ethAddress = await signers.ethSigner.getAddress();
222
- const ordersApi = new OrdersApi(config.getStarkExConfig().apiConfiguration);
223
- const amountSell = request.sell.type === 'ERC721' ? '1' : request.sell.amount;
224
- const amountBuy = request.buy.type === 'ERC721' ? '1' : request.buy.amount;
225
- const getSignableOrderRequest = {
226
- user: ethAddress,
227
- amount_buy: amountBuy,
228
- token_buy: convertToSignableToken(request.buy),
229
- amount_sell: amountSell,
230
- token_sell: convertToSignableToken(request.sell),
231
- fees: request.fees,
232
- expiration_timestamp: request.expiration_timestamp,
233
- };
234
- const getSignableOrderResponse = await ordersApi.getSignableOrder({
235
- getSignableOrderRequestV3: getSignableOrderRequest,
236
- });
237
- const { signable_message: signableMessage, payload_hash: payloadHash } = getSignableOrderResponse.data;
238
- const ethSignature = await signRaw(signableMessage, signers.ethSigner);
239
- const starkSignature = await signers.starkExSigner.signMessage(payloadHash);
240
- const resp = getSignableOrderResponse.data;
241
- const orderParams = {
242
- createOrderRequest: {
243
- amount_buy: resp.amount_buy,
244
- amount_sell: resp.amount_sell,
245
- asset_id_buy: resp.asset_id_buy,
246
- asset_id_sell: resp.asset_id_sell,
247
- expiration_timestamp: resp.expiration_timestamp,
248
- include_fees: true,
249
- fees: request.fees,
250
- nonce: resp.nonce,
251
- stark_key: resp.stark_key,
252
- stark_signature: starkSignature,
253
- vault_id_buy: resp.vault_id_buy,
254
- vault_id_sell: resp.vault_id_sell,
255
- },
256
- xImxEthAddress: ethAddress,
257
- xImxEthSignature: ethSignature,
258
- };
259
- const createOrderResponse = await ordersApi.createOrder(orderParams);
260
- return {
261
- ...createOrderResponse.data,
262
- };
263
- }
264
- async function cancelOrder$1({ signers, request, config, }) {
265
- const ordersApi = new OrdersApi(config.getStarkExConfig().apiConfiguration);
266
- const getSignableCancelOrderResponse = await ordersApi.getSignableCancelOrder({
267
- getSignableCancelOrderRequest: {
268
- order_id: request.order_id,
269
- },
270
- });
271
- const { signable_message: signableMessage, payload_hash: payloadHash } = getSignableCancelOrderResponse.data;
272
- const ethSignature = await signRaw(signableMessage, signers.ethSigner);
273
- const starkSignature = await signers.starkExSigner.signMessage(payloadHash);
274
- const ethAddress = await signers.ethSigner.getAddress();
275
- const cancelOrderResponse = await ordersApi.cancelOrder({
276
- id: request.order_id.toString(),
277
- cancelOrderRequest: {
278
- order_id: request.order_id,
279
- stark_signature: starkSignature,
280
- },
281
- xImxEthAddress: ethAddress,
282
- xImxEthSignature: ethSignature,
283
- });
284
- return {
285
- order_id: cancelOrderResponse.data.order_id,
286
- status: cancelOrderResponse.data.status,
287
- };
288
- }
289
-
290
- async function registerOffchain(signers, config) {
291
- await validateChain(signers.ethSigner, config.getStarkExConfig());
292
- const usersApi = new UsersApi(config.getStarkExConfig().apiConfiguration);
293
- const userAddress = await signers.ethSigner.getAddress();
294
- const starkPublicKey = await signers.starkExSigner.getAddress();
295
- const signableResult = await usersApi.getSignableRegistrationOffchain({
296
- getSignableRegistrationRequest: {
297
- ether_key: userAddress,
298
- stark_key: starkPublicKey,
299
- },
300
- });
301
- const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
302
- const ethSignature = await signRaw(signableMessage, signers.ethSigner);
303
- const starkSignature = await signers.starkExSigner.signMessage(payloadHash);
304
- const registeredUser = await usersApi.registerUser({
305
- registerUserRequest: {
306
- eth_signature: ethSignature,
307
- ether_key: userAddress,
308
- stark_signature: starkSignature,
309
- stark_key: starkPublicKey,
310
- },
311
- });
312
- return registeredUser.data;
313
- }
314
- async function isRegisteredOnChain(starkPublicKey, ethSigner, config) {
315
- await validateChain(ethSigner, config.getStarkExConfig());
316
- const registrationContract = Contracts.Registration.connect(config.getStarkExConfig().ethConfiguration.registrationContractAddress, ethSigner);
317
- try {
318
- return await registrationContract.isRegistered(starkPublicKey);
756
+ class MagicAdapter {
757
+ magicClient;
758
+ config;
759
+ constructor(config) {
760
+ this.config = config;
761
+ this.magicClient = new Magic(config.magicPublishableApiKey, {
762
+ network: config.network,
763
+ extensions: [new OpenIdExtension()],
764
+ });
319
765
  }
320
- catch (ex) {
321
- if (ex.reason === 'USER_UNREGISTERED') {
322
- return false;
323
- }
324
- throw ex;
766
+ async login(idToken) {
767
+ return withPassportError(async () => {
768
+ await this.magicClient.openid.loginWithOIDC({
769
+ jwt: idToken,
770
+ providerId: this.config.magicProviderId,
771
+ });
772
+ return new ethers.providers.Web3Provider(this.magicClient
773
+ .rpcProvider);
774
+ }, PassportErrorType.WALLET_CONNECTION_ERROR);
325
775
  }
326
776
  }
327
- async function getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi) {
328
- const response = await usersApi.getSignableRegistration({
329
- getSignableRegistrationRequest: {
330
- ether_key: etherKey,
331
- stark_key: starkPublicKey,
332
- },
333
- });
334
- return {
335
- operator_signature: response.data.operator_signature,
336
- payload_hash: response.data.payload_hash,
337
- };
338
- }
339
-
340
- const assertIsDefined = (value) => {
341
- if (value !== undefined)
342
- return value;
343
- throw new Error('undefined field exception');
344
- };
345
- async function prepareWithdrawalAction(params) {
346
- const { signers: { ethSigner, starkExSigner }, type, config, } = params;
347
- await validateChain(ethSigner, params.config);
348
- const withdrawalsApi = new WithdrawalsApi(config.apiConfiguration);
349
- const withdrawalAmount = type === 'ERC721' ? '1' : params.amount;
350
- const signableWithdrawalResult = await withdrawalsApi.getSignableWithdrawal({
351
- getSignableWithdrawalRequest: {
352
- user: await ethSigner.getAddress(),
353
- token: convertToSignableToken(params),
354
- amount: withdrawalAmount,
355
- },
356
- });
357
- const { signable_message: signableMessage, payload_hash: payloadHash } = signableWithdrawalResult.data;
358
- const starkSignature = await starkExSigner.signMessage(payloadHash);
359
- const { ethAddress, ethSignature } = await signMessage(signableMessage, ethSigner);
360
- const prepareWithdrawalResponse = await withdrawalsApi.createWithdrawal({
361
- createWithdrawalRequest: {
362
- stark_key: assertIsDefined(signableWithdrawalResult.data.stark_key),
363
- amount: withdrawalAmount,
364
- asset_id: assertIsDefined(signableWithdrawalResult.data.asset_id),
365
- vault_id: assertIsDefined(signableWithdrawalResult.data.vault_id),
366
- nonce: assertIsDefined(signableWithdrawalResult.data.nonce),
367
- stark_signature: starkSignature,
368
- },
369
- xImxEthAddress: ethAddress,
370
- xImxEthSignature: ethSignature,
371
- });
372
- return prepareWithdrawalResponse.data;
373
- }
374
777
 
375
- async function getEncodeAssetInfo(assetType, tokenType, config, tokenData) {
376
- const encodingApi = new EncodingApi(config.apiConfiguration);
377
- const result = await encodingApi.encodeAsset({
378
- assetType,
379
- encodeAssetRequest: {
380
- token: {
381
- type: tokenType,
382
- ...(tokenData && { data: tokenData }),
383
- },
384
- },
385
- });
386
- return result.data;
387
- }
778
+ var ReceiveMessage;
779
+ (function (ReceiveMessage) {
780
+ ReceiveMessage["CONFIRMATION_WINDOW_READY"] = "confirmation_window_ready";
781
+ ReceiveMessage["TRANSACTION_CONFIRMED"] = "transaction_confirmed";
782
+ ReceiveMessage["TRANSACTION_ERROR"] = "transaction_error";
783
+ })(ReceiveMessage || (ReceiveMessage = {}));
784
+ var SendMessage;
785
+ (function (SendMessage) {
786
+ SendMessage["TRANSACTION_START"] = "transaction_start";
787
+ })(SendMessage || (SendMessage = {}));
788
+ var TransactionTypes;
789
+ (function (TransactionTypes) {
790
+ TransactionTypes["CancelOrder"] = "delete:v1/orders";
791
+ TransactionTypes["CreateOrder"] = "post:v1/orders";
792
+ TransactionTypes["CreateTrade"] = "post:v1/trades";
793
+ TransactionTypes["CreateTransfer"] = "post:v1/transfers";
794
+ TransactionTypes["CreateBatchTransfer"] = "post:v2/transfers";
795
+ })(TransactionTypes || (TransactionTypes = {}));
796
+ const PassportEventType = 'imx_passport_confirmation';
388
797
 
389
- async function executeRegisterAndWithdrawERC20({ ethSigner, assetType, starkPublicKey, config, }) {
390
- const etherKey = await ethSigner.getAddress();
391
- const starkExConfig = config.getStarkExConfig();
392
- const usersApi = new UsersApi(starkExConfig.apiConfiguration);
393
- const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
394
- const contract = Contracts.Registration.connect(config.getStarkExConfig().ethConfiguration.registrationContractAddress, ethSigner);
395
- const populatedTransaction = await contract.populateTransaction.registerAndWithdraw(etherKey, starkPublicKey, signableResult.operator_signature, assetType);
396
- return ethSigner.sendTransaction(populatedTransaction);
397
- }
398
- async function executeWithdrawERC20(ethSigner, assetType, starkPublicKey, config) {
399
- const contract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
400
- const populatedTransaction = await contract.populateTransaction.withdraw(starkPublicKey, assetType);
401
- return ethSigner.sendTransaction(populatedTransaction);
402
- }
403
- async function completeERC20WithdrawalAction({ ethSigner, starkPublicKey, token, config, }) {
404
- await validateChain(ethSigner, config.getStarkExConfig());
405
- const starkExConfig = config.getStarkExConfig();
406
- const assetType = await getEncodeAssetInfo('asset', 'ERC20', starkExConfig, {
407
- token_address: token.tokenAddress,
408
- });
409
- const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
410
- if (!isRegistered) {
411
- return executeRegisterAndWithdrawERC20({
412
- ethSigner,
413
- assetType: assetType.asset_type,
414
- starkPublicKey,
415
- config,
416
- });
417
- }
418
- else {
419
- return executeWithdrawERC20(ethSigner, assetType.asset_type, starkPublicKey, starkExConfig);
798
+ const openPopupCenter = ({ url, title, width, height, }) => {
799
+ const left = Math.max(0, Math.round(window.screenX + (window.outerWidth - width) / 2));
800
+ const top = Math.max(0, Math.round(window.screenY + (window.outerHeight - height) / 2));
801
+ const newWindow = window.open(url, title, `
802
+ scrollbars=yes,
803
+ width=${width},
804
+ height=${height},
805
+ top=${top},
806
+ left=${left}
807
+ `);
808
+ if (!newWindow) {
809
+ throw new Error('Failed to open confirmation screen');
420
810
  }
421
- }
811
+ newWindow.focus();
812
+ return newWindow;
813
+ };
422
814
 
423
- async function executeWithdrawMintableERC721(ethSigner, assetType, starkPublicKey, mintingBlob, config) {
424
- const contract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
425
- const populatedTransaction = await contract.populateTransaction.withdrawAndMint(starkPublicKey, assetType, mintingBlob);
426
- return ethSigner.sendTransaction(populatedTransaction);
427
- }
428
- async function executeRegisterAndWithdrawMintableERC721(ethSigner, assetType, starkPublicKey, mintingBlob, config) {
429
- const etherKey = await ethSigner.getAddress();
430
- const usersApi = new UsersApi(config.apiConfiguration);
431
- const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
432
- const contract = Contracts.Registration.connect(config.ethConfiguration.registrationContractAddress, ethSigner);
433
- const populatedTransaction = await contract.populateTransaction.regsiterAndWithdrawAndMint(etherKey, starkPublicKey, signableResult.operator_signature, assetType, mintingBlob);
434
- return ethSigner.sendTransaction(populatedTransaction);
435
- }
436
- function getMintingBlob(token) {
437
- const id = token.data.id;
438
- const blueprint = token.data.blueprint || '';
439
- return encUtils.sanitizeHex(encUtils.utf8ToHex(`{${id}}:{${blueprint}}`));
440
- }
441
- async function completeMintableERC721Withdrawal(ethSigner, starkPublicKey, token, config) {
442
- const starkExConfig = config.getStarkExConfig();
443
- const assetType = await getEncodeAssetInfo('mintable-asset', 'ERC721', starkExConfig, {
444
- id: token.data.id,
445
- token_address: token.data.tokenAddress,
446
- ...(token.data.blueprint && { blueprint: token.data.blueprint }),
447
- });
448
- const mintingBlob = getMintingBlob(token);
449
- const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
450
- if (!isRegistered) {
451
- return executeRegisterAndWithdrawMintableERC721(ethSigner, assetType.asset_type, starkPublicKey, mintingBlob, starkExConfig);
815
+ const ConfirmationWindowTitle = 'Confirm this transaction';
816
+ const ConfirmationWindowHeight = 380;
817
+ const ConfirmationWindowWidth = 480;
818
+ const ConfirmationWindowClosedPollingDuration = 1000;
819
+ class ConfirmationScreen {
820
+ config;
821
+ constructor(config) {
822
+ this.config = config;
452
823
  }
453
- else {
454
- return executeWithdrawMintableERC721(ethSigner, assetType.asset_type, starkPublicKey, mintingBlob, starkExConfig);
824
+ postMessage(destinationWindow, accessToken, message) {
825
+ destinationWindow.postMessage({
826
+ eventType: PassportEventType,
827
+ accessToken,
828
+ ...message,
829
+ }, this.config.passportDomain);
455
830
  }
456
- }
457
- async function executeRegisterAndWithdrawERC721(ethSigner, assetType, starkPublicKey, tokenId, config) {
458
- const etherKey = await ethSigner.getAddress();
459
- const usersApi = new UsersApi(config.apiConfiguration);
460
- const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
461
- const contract = Contracts.Registration.connect(config.ethConfiguration.registrationContractAddress, ethSigner);
462
- const populatedTransaction = await contract.populateTransaction.registerAndWithdrawNft(etherKey, starkPublicKey, signableResult.operator_signature, assetType, tokenId);
463
- return ethSigner.sendTransaction(populatedTransaction);
464
- }
465
- async function executeWithdrawERC721(ethSigner, assetType, starkPublicKey, tokenId, config) {
466
- const contract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
467
- const populatedTransaction = await contract.populateTransaction.withdrawNft(starkPublicKey, assetType, tokenId);
468
- return ethSigner.sendTransaction(populatedTransaction);
469
- }
470
- async function completeERC721Withdrawal(ethSigner, starkPublicKey, token, config) {
471
- const starkExConfig = config.getStarkExConfig();
472
- const assetType = await getEncodeAssetInfo('asset', 'ERC721', starkExConfig, {
473
- token_id: token.tokenId,
474
- token_address: token.tokenAddress,
475
- });
476
- const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
477
- if (!isRegistered) {
478
- return executeRegisterAndWithdrawERC721(ethSigner, assetType.asset_type, starkPublicKey, token.tokenId, starkExConfig);
479
- }
480
- else {
481
- return executeWithdrawERC721(ethSigner, assetType.asset_type, starkPublicKey, token.tokenId, starkExConfig);
482
- }
483
- }
484
- async function completeERC721WithdrawalAction({ ethSigner, starkPublicKey, token, config, }) {
485
- await validateChain(ethSigner, config.getStarkExConfig());
486
- const tokenAddress = token.tokenAddress;
487
- const tokenId = token.tokenId;
488
- const starkExConfig = config.getStarkExConfig();
489
- const mintsApi = new MintsApi(starkExConfig.apiConfiguration);
490
- return await mintsApi
491
- .getMintableTokenDetailsByClientTokenId({
492
- tokenAddress,
493
- tokenId,
494
- })
495
- .then((mintableToken) => completeMintableERC721Withdrawal(ethSigner, starkPublicKey, {
496
- type: 'ERC721',
497
- data: {
498
- id: tokenId,
499
- tokenAddress: tokenAddress,
500
- blueprint: mintableToken.data.blueprint,
501
- },
502
- }, config))
503
- .catch((error) => {
504
- if (error.response?.status === 404) {
505
- // token is already minted on L1
506
- return completeERC721Withdrawal(ethSigner, starkPublicKey, token, config);
507
- }
508
- throw error; // unable to recover from any other kind of error
509
- });
510
- }
511
-
512
- async function executeRegisterAndWithdrawEth(ethSigner, assetType, starkPublicKey, config) {
513
- const etherKey = await ethSigner.getAddress();
514
- const usersApi = new UsersApi(config.apiConfiguration);
515
- const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
516
- const contract = Contracts.Registration.connect(config.ethConfiguration.registrationContractAddress, ethSigner);
517
- const populatedTransaction = await contract.populateTransaction.registerAndWithdraw(etherKey, starkPublicKey, signableResult.operator_signature, assetType);
518
- return ethSigner.sendTransaction(populatedTransaction);
519
- }
520
- async function executeWithdrawEth(ethSigner, assetType, starkPublicKey, config) {
521
- const contract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
522
- const populatedTransaction = await contract.populateTransaction.withdraw(starkPublicKey, assetType);
523
- return ethSigner.sendTransaction(populatedTransaction);
524
- }
525
- async function completeEthWithdrawalAction({ ethSigner, starkPublicKey, config, }) {
526
- await validateChain(ethSigner, config.getStarkExConfig());
527
- const starkExConfig = config.getStarkExConfig();
528
- const assetType = await getEncodeAssetInfo('asset', 'ETH', starkExConfig);
529
- const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
530
- if (!isRegistered) {
531
- return executeRegisterAndWithdrawEth(ethSigner, assetType.asset_type, starkPublicKey, starkExConfig);
532
- }
533
- else {
534
- return executeWithdrawEth(ethSigner, assetType.asset_type, starkPublicKey, starkExConfig);
831
+ startTransaction(accessToken, transaction, popupOptions) {
832
+ return new Promise((resolve, reject) => {
833
+ const messageHandler = ({ data, origin }) => {
834
+ if (origin != this.config.passportDomain ||
835
+ data.eventType != PassportEventType) {
836
+ return;
837
+ }
838
+ switch (data.messageType) {
839
+ case ReceiveMessage.CONFIRMATION_WINDOW_READY: {
840
+ this.postMessage(confirmationWindow, accessToken, {
841
+ messageType: SendMessage.TRANSACTION_START,
842
+ messageData: transaction,
843
+ });
844
+ break;
845
+ }
846
+ case ReceiveMessage.TRANSACTION_CONFIRMED: {
847
+ resolve({ confirmed: true });
848
+ break;
849
+ }
850
+ case ReceiveMessage.TRANSACTION_ERROR: {
851
+ reject(new Error('Transaction error'));
852
+ break;
853
+ }
854
+ default:
855
+ reject(new Error('Unsupported message type'));
856
+ }
857
+ };
858
+ window.addEventListener('message', messageHandler);
859
+ const confirmationWindow = openPopupCenter({
860
+ url: `${this.config.passportDomain}/transaction-confirmation`,
861
+ title: ConfirmationWindowTitle,
862
+ width: popupOptions?.width || ConfirmationWindowWidth,
863
+ height: popupOptions?.height || ConfirmationWindowHeight,
864
+ });
865
+ // https://stackoverflow.com/questions/9388380/capture-the-close-event-of-popup-window-in-javascript/48240128#48240128
866
+ const timer = setInterval(function () {
867
+ if (confirmationWindow.closed) {
868
+ clearInterval(timer);
869
+ window.removeEventListener('message', messageHandler);
870
+ resolve({ confirmed: false });
871
+ }
872
+ }, ConfirmationWindowClosedPollingDuration);
873
+ });
535
874
  }
536
875
  }
537
876
 
538
- async function prepareWithdrawal({ signers, withdrawal, config, }) {
539
- const starkExConfig = config.getStarkExConfig();
540
- return prepareWithdrawalAction({
541
- signers,
542
- config: starkExConfig,
543
- ...withdrawal,
544
- });
545
- }
546
- async function completeWithdrawal({ signers: { ethSigner }, starkPublicKey, token, config, }) {
547
- switch (token.type) {
548
- case 'ETH':
549
- return completeEthWithdrawalAction({ ethSigner, starkPublicKey, config });
550
- case 'ERC20':
551
- return completeERC20WithdrawalAction({
552
- ethSigner,
553
- starkPublicKey,
554
- token,
555
- config,
556
- });
557
- case 'ERC721':
558
- return completeERC721WithdrawalAction({
559
- ethSigner,
560
- starkPublicKey,
561
- token,
562
- config,
563
- });
564
- }
877
+ const ERC721$1 = 'ERC721';
878
+ const transfer$1 = ({ request, transfersApi, starkSigner, user, passportConfig, }) => {
879
+ return withPassportError(async () => {
880
+ const transferAmount = request.type === ERC721$1 ? '1' : request.amount;
881
+ const getSignableTransferRequest = {
882
+ sender: user.etherKey,
883
+ token: convertToSignableToken(request),
884
+ amount: transferAmount,
885
+ receiver: request.receiver,
886
+ };
887
+ const signableResult = await transfersApi.getSignableTransferV1({
888
+ getSignableTransferRequest,
889
+ });
890
+ const confirmationScreen = new ConfirmationScreen(passportConfig);
891
+ const confirmationResult = await confirmationScreen.startTransaction(user.accessToken, {
892
+ transactionType: TransactionTypes.CreateTransfer,
893
+ transactionData: getSignableTransferRequest,
894
+ });
895
+ if (!confirmationResult.confirmed) {
896
+ throw new Error('Transaction rejected by user');
897
+ }
898
+ const signableResultData = signableResult.data;
899
+ const { payload_hash: payloadHash } = signableResultData;
900
+ const starkSignature = await starkSigner.signMessage(payloadHash);
901
+ const senderStarkKey = await starkSigner.getAddress();
902
+ const transferSigningParams = {
903
+ sender_stark_key: signableResultData.sender_stark_key || senderStarkKey,
904
+ sender_vault_id: signableResultData.sender_vault_id,
905
+ receiver_stark_key: signableResultData.receiver_stark_key,
906
+ receiver_vault_id: signableResultData.receiver_vault_id,
907
+ asset_id: signableResultData.asset_id,
908
+ amount: signableResultData.amount,
909
+ nonce: signableResultData.nonce,
910
+ expiration_timestamp: signableResultData.expiration_timestamp,
911
+ stark_signature: starkSignature,
912
+ };
913
+ const createTransferRequest = {
914
+ createTransferRequest: transferSigningParams,
915
+ };
916
+ const headers = {
917
+ Authorization: 'Bearer ' + user.accessToken,
918
+ };
919
+ const { data: responseData } = await transfersApi.createTransferV1(createTransferRequest, { headers });
920
+ return {
921
+ sent_signature: responseData.sent_signature,
922
+ status: responseData.status?.toString(),
923
+ time: responseData.time,
924
+ transfer_id: responseData.transfer_id,
925
+ };
926
+ }, PassportErrorType.TRANSFER_ERROR);
927
+ };
928
+ async function batchNftTransfer({ user, starkSigner, request, transfersApi, passportConfig, }) {
929
+ return withPassportError(async () => {
930
+ const ethAddress = user.etherKey;
931
+ const signableRequests = request.map((nftTransfer) => {
932
+ return {
933
+ amount: '1',
934
+ token: convertToSignableToken({
935
+ type: ERC721$1,
936
+ tokenId: nftTransfer.tokenId,
937
+ tokenAddress: nftTransfer.tokenAddress,
938
+ }),
939
+ receiver: nftTransfer.receiver,
940
+ };
941
+ });
942
+ const getSignableTransferRequestV2 = {
943
+ sender_ether_key: ethAddress,
944
+ signable_requests: signableRequests,
945
+ };
946
+ const signableResult = await transfersApi.getSignableTransfer({
947
+ getSignableTransferRequestV2,
948
+ });
949
+ const confirmationScreen = new ConfirmationScreen(passportConfig);
950
+ const popupWindowSize = { width: 480, height: 784 };
951
+ const confirmationResult = await confirmationScreen.startTransaction(user.accessToken, {
952
+ transactionType: TransactionTypes.CreateBatchTransfer,
953
+ transactionData: getSignableTransferRequestV2,
954
+ }, popupWindowSize);
955
+ if (!confirmationResult.confirmed) {
956
+ throw new Error('Transaction rejected by user');
957
+ }
958
+ const requests = await Promise.all(signableResult.data.signable_responses.map(async (resp) => {
959
+ const starkSignature = await starkSigner.signMessage(resp.payload_hash);
960
+ return {
961
+ sender_vault_id: resp.sender_vault_id,
962
+ receiver_stark_key: resp.receiver_stark_key,
963
+ receiver_vault_id: resp.receiver_vault_id,
964
+ asset_id: resp.asset_id,
965
+ amount: resp.amount,
966
+ nonce: resp.nonce,
967
+ expiration_timestamp: resp.expiration_timestamp,
968
+ stark_signature: starkSignature,
969
+ };
970
+ }));
971
+ const transferSigningParams = {
972
+ sender_stark_key: signableResult.data.sender_stark_key,
973
+ requests,
974
+ };
975
+ const headers = {
976
+ Authorization: 'Bearer ' + user.accessToken,
977
+ };
978
+ const response = await transfersApi.createTransfer({
979
+ createTransferRequestV2: transferSigningParams,
980
+ }, { headers });
981
+ return {
982
+ transfer_ids: response?.data.transfer_ids,
983
+ };
984
+ }, PassportErrorType.TRANSFER_ERROR);
565
985
  }
566
986
 
567
- async function createTrade$1({ signers: { ethSigner, starkExSigner }, request, config, }) {
568
- await validateChain(ethSigner, config.getStarkExConfig());
569
- const ethAddress = await ethSigner.getAddress();
570
- const tradesApi = new TradesApi(config.getStarkExConfig().apiConfiguration);
571
- const signableResult = await tradesApi.getSignableTrade({
572
- getSignableTradeRequest: {
987
+ const ERC721 = 'ERC721';
988
+ async function createOrder$1({ starkSigner, user, request, ordersApi, passportConfig, }) {
989
+ return withPassportError(async () => {
990
+ const ethAddress = user.etherKey;
991
+ const amountSell = request.sell.type === ERC721 ? '1' : request.sell.amount;
992
+ const amountBuy = request.buy.type === ERC721 ? '1' : request.buy.amount;
993
+ const getSignableOrderRequestV3 = {
573
994
  user: ethAddress,
574
- order_id: request.order_id,
995
+ amount_buy: amountBuy,
996
+ token_buy: convertToSignableToken(request.buy),
997
+ amount_sell: amountSell,
998
+ token_sell: convertToSignableToken(request.sell),
575
999
  fees: request.fees,
576
- },
577
- });
578
- const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
579
- const ethSignature = await signRaw(signableMessage, ethSigner);
580
- const starkSignature = await starkExSigner.signMessage(payloadHash);
581
- const createTradeResponse = await tradesApi.createTrade({
582
- createTradeRequest: {
583
- amount_buy: signableResult.data.amount_buy,
584
- amount_sell: signableResult.data.amount_sell,
585
- asset_id_buy: signableResult.data.asset_id_buy,
586
- asset_id_sell: signableResult.data.asset_id_sell,
587
- expiration_timestamp: signableResult.data.expiration_timestamp,
588
- fee_info: signableResult.data.fee_info,
589
- fees: request.fees,
590
- include_fees: true,
591
- nonce: signableResult.data.nonce,
592
- order_id: request.order_id,
593
- stark_key: signableResult.data.stark_key,
594
- vault_id_buy: signableResult.data.vault_id_buy,
595
- vault_id_sell: signableResult.data.vault_id_sell,
596
- stark_signature: starkSignature,
597
- },
598
- xImxEthAddress: ethAddress,
599
- xImxEthSignature: ethSignature,
600
- });
601
- return createTradeResponse.data;
602
- }
603
-
604
- async function depositEth({ signers: { ethSigner }, deposit, config, }) {
605
- await validateChain(ethSigner, config.getStarkExConfig());
606
- const user = await ethSigner.getAddress();
607
- const data = {
608
- decimals: 18,
609
- };
610
- const amount = parseUnits(deposit.amount, 'wei');
611
- const starkExConfig = config.getStarkExConfig();
612
- const depositsApi = new DepositsApi(starkExConfig.apiConfiguration);
613
- const encodingApi = new EncodingApi(starkExConfig.apiConfiguration);
614
- const usersApi = new UsersApi(starkExConfig.apiConfiguration);
615
- const getSignableDepositRequest = {
616
- user,
617
- token: {
618
- type: deposit.type,
619
- data,
620
- },
621
- amount: amount.toString(),
622
- };
623
- const signableDepositResult = await depositsApi.getSignableDeposit({
624
- getSignableDepositRequest,
625
- });
626
- const encodingResult = await encodingApi.encodeAsset({
627
- assetType: 'asset',
628
- encodeAssetRequest: {
629
- token: {
630
- type: deposit.type,
1000
+ expiration_timestamp: request.expiration_timestamp,
1001
+ };
1002
+ const getSignableOrderResponse = await ordersApi.getSignableOrder({
1003
+ getSignableOrderRequestV3,
1004
+ });
1005
+ const confirmationScreen = new ConfirmationScreen(passportConfig);
1006
+ const confirmationResult = await confirmationScreen.startTransaction(user.accessToken, {
1007
+ transactionType: TransactionTypes.CreateOrder,
1008
+ transactionData: getSignableOrderRequestV3,
1009
+ });
1010
+ if (!confirmationResult.confirmed) {
1011
+ throw new Error('Transaction rejected by user');
1012
+ }
1013
+ const { payload_hash: payloadHash } = getSignableOrderResponse.data;
1014
+ const starkSignature = await starkSigner.signMessage(payloadHash);
1015
+ const signableResultData = getSignableOrderResponse.data;
1016
+ const orderParams = {
1017
+ createOrderRequest: {
1018
+ include_fees: true,
1019
+ fees: request.fees,
1020
+ stark_signature: starkSignature,
1021
+ amount_buy: signableResultData.amount_buy,
1022
+ amount_sell: signableResultData.amount_sell,
1023
+ asset_id_buy: signableResultData.asset_id_buy,
1024
+ asset_id_sell: signableResultData.asset_id_sell,
1025
+ expiration_timestamp: signableResultData.expiration_timestamp,
1026
+ nonce: signableResultData.nonce,
1027
+ stark_key: signableResultData.stark_key,
1028
+ vault_id_buy: signableResultData.vault_id_buy,
1029
+ vault_id_sell: signableResultData.vault_id_sell,
631
1030
  },
632
- },
633
- });
634
- const assetType = encodingResult.data.asset_type;
635
- const starkPublicKey = signableDepositResult.data.stark_key;
636
- const vaultId = signableDepositResult.data.vault_id;
637
- const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
638
- if (!isRegistered) {
639
- return executeRegisterAndDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, starkExConfig, usersApi);
640
- }
641
- else {
642
- return executeDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, starkExConfig);
643
- }
644
- }
645
- async function executeRegisterAndDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, config, usersApi) {
646
- const etherKey = await ethSigner.getAddress();
647
- const coreContract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
648
- const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
649
- const populatedTransaction = await coreContract.populateTransaction.registerAndDepositEth(etherKey, starkPublicKey, signableResult.operator_signature, assetType, vaultId);
650
- return ethSigner.sendTransaction({ ...populatedTransaction, value: amount });
1031
+ };
1032
+ const headers = {
1033
+ Authorization: 'Bearer ' + user.accessToken,
1034
+ };
1035
+ const createOrderResponse = await ordersApi.createOrder(orderParams, {
1036
+ headers,
1037
+ });
1038
+ return {
1039
+ ...createOrderResponse.data,
1040
+ };
1041
+ }, PassportErrorType.CREATE_ORDER_ERROR);
651
1042
  }
652
- async function executeDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, config) {
653
- const coreContract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
654
- const populatedTransaction = await coreContract.populateTransaction['deposit(uint256,uint256,uint256)'](starkPublicKey, assetType, vaultId);
655
- return ethSigner.sendTransaction({ ...populatedTransaction, value: amount });
1043
+ async function cancelOrder$1({ user, starkSigner, request, ordersApi, passportConfig, }) {
1044
+ return withPassportError(async () => {
1045
+ const getSignableCancelOrderRequest = {
1046
+ order_id: request.order_id,
1047
+ };
1048
+ const getSignableCancelOrderResponse = await ordersApi.getSignableCancelOrder({
1049
+ getSignableCancelOrderRequest,
1050
+ });
1051
+ const confirmationScreen = new ConfirmationScreen(passportConfig);
1052
+ const confirmationResult = await confirmationScreen.startTransaction(user.accessToken, {
1053
+ transactionType: TransactionTypes.CancelOrder,
1054
+ transactionData: getSignableCancelOrderRequest,
1055
+ });
1056
+ if (!confirmationResult.confirmed) {
1057
+ throw new Error('Transaction rejected by user');
1058
+ }
1059
+ const { payload_hash: payloadHash } = getSignableCancelOrderResponse.data;
1060
+ const starkSignature = await starkSigner.signMessage(payloadHash);
1061
+ const headers = {
1062
+ Authorization: 'Bearer ' + user.accessToken,
1063
+ };
1064
+ const cancelOrderResponse = await ordersApi.cancelOrder({
1065
+ id: request.order_id.toString(),
1066
+ cancelOrderRequest: {
1067
+ order_id: request.order_id,
1068
+ stark_signature: starkSignature,
1069
+ },
1070
+ }, { headers });
1071
+ return {
1072
+ order_id: cancelOrderResponse.data.order_id,
1073
+ status: cancelOrderResponse.data.status,
1074
+ };
1075
+ }, PassportErrorType.CANCEL_ORDER_ERROR);
656
1076
  }
657
1077
 
658
- async function depositERC20({ signers: { ethSigner }, deposit, config, }) {
659
- await validateChain(ethSigner, config.getStarkExConfig());
660
- const { apiConfiguration, ethConfiguration } = config.getStarkExConfig();
661
- const user = await ethSigner.getAddress();
662
- const tokensApi = new TokensApi(apiConfiguration);
663
- const depositsApi = new DepositsApi(apiConfiguration);
664
- const encodingApi = new EncodingApi(apiConfiguration);
665
- const usersApi = new UsersApi(apiConfiguration);
666
- // Get decimals for this specific ERC20
667
- const token = await tokensApi.getToken({ address: deposit.tokenAddress });
668
- const decimals = parseInt(token.data.decimals);
669
- const data = {
670
- decimals,
671
- token_address: deposit.tokenAddress,
672
- };
673
- const amount = parseUnits(deposit.amount, 0); // 0 to always use undecimalized value
674
- // Approve whether an amount of token from an account can be spent by a third-party account
675
- const tokenContract = Contracts.IERC20.connect(deposit.tokenAddress, ethSigner);
676
- const approveTransaction = await tokenContract.populateTransaction.approve(ethConfiguration.coreContractAddress, amount);
677
- await ethSigner.sendTransaction(approveTransaction);
678
- const getSignableDepositRequest = {
679
- user,
680
- token: {
681
- type: deposit.type,
682
- data,
683
- },
684
- amount: amount.toString(),
685
- };
686
- const signableDepositResult = await depositsApi.getSignableDeposit({
687
- getSignableDepositRequest,
688
- });
689
- // Perform encoding on asset details to get an assetType (required for stark contract request)
690
- const encodingResult = await encodingApi.encodeAsset({
691
- assetType: 'asset',
692
- encodeAssetRequest: {
693
- token: {
694
- type: deposit.type,
695
- data: {
696
- token_address: deposit.tokenAddress,
697
- },
1078
+ async function exchangeTransfer$1({ user, starkSigner, request, exchangesApi, }) {
1079
+ return withPassportError(async () => {
1080
+ const ethAddress = user.etherKey;
1081
+ const transferAmount = request.amount;
1082
+ const signableResult = await exchangesApi.getExchangeSignableTransfer({
1083
+ id: request.transactionID,
1084
+ getSignableTransferRequest: {
1085
+ sender: ethAddress,
1086
+ token: convertToSignableToken(request),
1087
+ amount: transferAmount,
1088
+ receiver: request.receiver,
698
1089
  },
699
- },
700
- });
701
- const assetType = encodingResult.data.asset_type;
702
- const starkPublicKey = signableDepositResult.data.stark_key;
703
- const vaultId = signableDepositResult.data.vault_id;
704
- const quantizedAmount = BigNumber.from(signableDepositResult.data.amount);
705
- const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
706
- if (!isRegistered) {
707
- return executeRegisterAndDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, ethConfiguration, usersApi);
708
- }
709
- else {
710
- return executeDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, ethConfiguration);
711
- }
712
- }
713
- async function executeDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, config) {
714
- const coreContract = Contracts.Core.connect(config.coreContractAddress, ethSigner);
715
- const populatedTransaction = await coreContract.populateTransaction.depositERC20(starkPublicKey, assetType, vaultId, quantizedAmount);
716
- return ethSigner.sendTransaction(populatedTransaction);
717
- }
718
- async function executeRegisterAndDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, config, usersApi) {
719
- const etherKey = await ethSigner.getAddress();
720
- const coreContract = Contracts.Core.connect(config.coreContractAddress, ethSigner);
721
- const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
722
- const populatedTransaction = await coreContract.populateTransaction.registerAndDepositERC20(etherKey, starkPublicKey, signableResult.operator_signature, assetType, vaultId, quantizedAmount);
723
- return ethSigner.sendTransaction(populatedTransaction);
1090
+ });
1091
+ const starkAddress = await starkSigner.getAddress();
1092
+ const { payload_hash: payloadHash } = signableResult.data;
1093
+ const starkSignature = await starkSigner.signMessage(payloadHash);
1094
+ const transferSigningParams = {
1095
+ sender_stark_key: signableResult.data.sender_stark_key || starkAddress,
1096
+ sender_vault_id: signableResult.data.sender_vault_id,
1097
+ receiver_stark_key: signableResult.data.receiver_stark_key,
1098
+ receiver_vault_id: signableResult.data.receiver_vault_id,
1099
+ asset_id: signableResult.data.asset_id,
1100
+ amount: signableResult.data.amount,
1101
+ nonce: signableResult.data.nonce,
1102
+ expiration_timestamp: signableResult.data.expiration_timestamp,
1103
+ stark_signature: starkSignature,
1104
+ };
1105
+ const headers = {
1106
+ Authorization: 'Bearer ' + user.accessToken,
1107
+ };
1108
+ const response = await exchangesApi.createExchangeTransfer({
1109
+ id: request.transactionID,
1110
+ createTransferRequest: transferSigningParams,
1111
+ }, { headers });
1112
+ return {
1113
+ sent_signature: response?.data.sent_signature,
1114
+ status: response?.data.status?.toString(),
1115
+ time: response?.data.time,
1116
+ transfer_id: response?.data.transfer_id,
1117
+ };
1118
+ }, PassportErrorType.EXCHANGE_TRANSFER_ERROR);
724
1119
  }
725
1120
 
726
- async function depositERC721({ signers: { ethSigner }, deposit, config, }) {
727
- await validateChain(ethSigner, config.getStarkExConfig());
728
- const user = await ethSigner.getAddress();
729
- const starkExConfig = config.getStarkExConfig();
730
- const depositsApi = new DepositsApi(starkExConfig.apiConfiguration);
731
- const encodingApi = new EncodingApi(starkExConfig.apiConfiguration);
732
- const usersApi = new UsersApi(starkExConfig.apiConfiguration);
733
- const data = {
734
- token_address: deposit.tokenAddress,
735
- token_id: deposit.tokenId,
736
- };
737
- const amount = '1';
738
- const getSignableDepositRequest = {
739
- user,
740
- token: {
741
- type: deposit.type,
742
- data,
743
- },
744
- amount: amount.toString(),
745
- };
746
- const signableDepositResult = await depositsApi.getSignableDeposit({
747
- getSignableDepositRequest,
748
- });
749
- // Perform encoding on asset details to get an assetType (required for stark contract request)
750
- const encodingResult = await encodingApi.encodeAsset({
751
- assetType: 'asset',
752
- encodeAssetRequest: {
753
- token: {
754
- type: deposit.type,
755
- data: {
756
- token_address: deposit.tokenAddress,
757
- token_id: deposit.tokenId,
758
- },
1121
+ async function createTrade$1({ request, tradesApi, user, starkSigner, passportConfig, }) {
1122
+ return withPassportError(async () => {
1123
+ const ethAddress = user.etherKey;
1124
+ const getSignableTradeRequest = {
1125
+ expiration_timestamp: request.expiration_timestamp,
1126
+ fees: request.fees,
1127
+ order_id: request.order_id,
1128
+ user: ethAddress,
1129
+ };
1130
+ const getSignableTradeResponse = await tradesApi.getSignableTrade({
1131
+ getSignableTradeRequest,
1132
+ });
1133
+ const confirmationScreen = new ConfirmationScreen(passportConfig);
1134
+ const confirmationResult = await confirmationScreen.startTransaction(user.accessToken, {
1135
+ transactionType: TransactionTypes.CreateTrade,
1136
+ transactionData: getSignableTradeRequest,
1137
+ });
1138
+ if (!confirmationResult.confirmed) {
1139
+ throw new Error('Transaction rejected by user');
1140
+ }
1141
+ const { payload_hash: payloadHash } = getSignableTradeResponse.data;
1142
+ const starkSignature = await starkSigner.signMessage(payloadHash);
1143
+ const { data: signableResultData } = getSignableTradeResponse;
1144
+ const tradeParams = {
1145
+ createTradeRequest: {
1146
+ include_fees: true,
1147
+ fees: request?.fees,
1148
+ stark_signature: starkSignature,
1149
+ order_id: request?.order_id,
1150
+ fee_info: signableResultData.fee_info,
1151
+ amount_buy: signableResultData.amount_buy,
1152
+ amount_sell: signableResultData.amount_sell,
1153
+ asset_id_buy: signableResultData.asset_id_buy,
1154
+ asset_id_sell: signableResultData.asset_id_sell,
1155
+ expiration_timestamp: signableResultData.expiration_timestamp,
1156
+ nonce: signableResultData.nonce,
1157
+ stark_key: signableResultData.stark_key,
1158
+ vault_id_buy: signableResultData.vault_id_buy,
1159
+ vault_id_sell: signableResultData.vault_id_sell,
759
1160
  },
760
- },
761
- });
762
- const assetType = encodingResult.data.asset_type;
763
- const starkPublicKey = signableDepositResult.data.stark_key;
764
- const vaultId = signableDepositResult.data.vault_id;
765
- const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
766
- // Approve whether an amount of token from an account can be spent by a third-party account
767
- const tokenContract = Contracts.IERC721.connect(deposit.tokenAddress, ethSigner);
768
- const operator = starkExConfig.ethConfiguration.coreContractAddress;
769
- const isApprovedForAll = await tokenContract.isApprovedForAll(user, operator);
770
- if (!isApprovedForAll) {
771
- await tokenContract.setApprovalForAll(operator, true);
772
- }
773
- if (!isRegistered) {
774
- const signableResult = await getSignableRegistrationOnchain(user, starkPublicKey, usersApi);
775
- const coreContract = Contracts.Core.connect(starkExConfig.ethConfiguration.coreContractAddress, ethSigner);
776
- // Note: proxy registration contract registerAndDepositNft method is not used as it currently fails erc721 transfer ownership check
777
- await coreContract.registerUser(user, starkPublicKey, signableResult.operator_signature);
778
- }
779
- return executeDepositERC721(ethSigner, deposit.tokenId, assetType, starkPublicKey, vaultId, starkExConfig);
780
- }
781
- async function executeDepositERC721(ethSigner, tokenId, assetType, starkPublicKey, vaultId, config) {
782
- const coreContract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
783
- const populatedTransaction = await coreContract.populateTransaction.depositNft(starkPublicKey, assetType, vaultId, tokenId);
784
- return ethSigner.sendTransaction(populatedTransaction);
785
- }
786
-
787
- async function deposit({ signers, deposit, config }) {
788
- switch (deposit.type) {
789
- case 'ETH':
790
- return depositEth({ signers, deposit, config });
791
- case 'ERC20':
792
- return depositERC20({ signers, deposit, config });
793
- case 'ERC721':
794
- return depositERC721({ signers, deposit, config });
795
- }
796
- }
797
-
798
- async function exchangeTransfer$1({ signers, request, config, }) {
799
- await validateChain(signers.ethSigner, config.getStarkExConfig());
800
- const exchangeApi = new ExchangesApi(config.getStarkExConfig().apiConfiguration);
801
- const ethAddress = await signers.ethSigner.getAddress();
802
- const transferAmount = request.amount;
803
- const signableResult = await exchangeApi.getExchangeSignableTransfer({
804
- id: request.transactionID,
805
- getSignableTransferRequest: {
806
- sender: ethAddress,
807
- token: convertToSignableToken(request),
808
- amount: transferAmount,
809
- receiver: request.receiver,
810
- },
811
- });
812
- const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
813
- const ethSignature = await signRaw(signableMessage, signers.ethSigner);
814
- const starkSignature = await signers.starkExSigner.signMessage(payloadHash);
815
- const transferSigningParams = {
816
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
817
- sender_stark_key: signableResult.data.sender_stark_key,
818
- sender_vault_id: signableResult.data.sender_vault_id,
819
- receiver_stark_key: signableResult.data.receiver_stark_key,
820
- receiver_vault_id: signableResult.data.receiver_vault_id,
821
- asset_id: signableResult.data.asset_id,
822
- amount: signableResult.data.amount,
823
- nonce: signableResult.data.nonce,
824
- expiration_timestamp: signableResult.data.expiration_timestamp,
825
- stark_signature: starkSignature,
826
- };
827
- const response = await exchangeApi.createExchangeTransfer({
828
- id: request.transactionID,
829
- createTransferRequest: transferSigningParams,
830
- xImxEthAddress: ethAddress,
831
- xImxEthSignature: ethSignature,
832
- });
833
- return {
834
- sent_signature: response?.data.sent_signature,
835
- status: response?.data.status?.toString(),
836
- time: response?.data.time,
837
- transfer_id: response?.data.transfer_id,
838
- };
1161
+ };
1162
+ const headers = { Authorization: 'Bearer ' + user.accessToken };
1163
+ const { data: createTradeResponse } = await tradesApi.createTradeV3(tradeParams, {
1164
+ headers,
1165
+ });
1166
+ return createTradeResponse;
1167
+ }, PassportErrorType.CREATE_TRADE_ERROR);
839
1168
  }
840
1169
 
841
- class GenericIMXProvider {
842
- config;
843
- signers;
844
- constructor(config, ethSigner, starkExSigner) {
845
- this.config = config;
846
- this.signers = { ethSigner, starkExSigner };
1170
+ class PassportImxProvider {
1171
+ user;
1172
+ starkSigner;
1173
+ transfersApi;
1174
+ ordersApi;
1175
+ passportConfig;
1176
+ exchangesApi;
1177
+ tradesApi;
1178
+ constructor({ user, starkSigner, passportConfig }) {
1179
+ this.user = user;
1180
+ this.starkSigner = starkSigner;
1181
+ this.passportConfig = passportConfig;
1182
+ const apiConfig = new Configuration({
1183
+ basePath: passportConfig.imxApiBasePath,
1184
+ });
1185
+ this.transfersApi = new TransfersApi(apiConfig);
1186
+ this.ordersApi = new OrdersApi(apiConfig);
1187
+ this.exchangesApi = new ExchangesApi(apiConfig);
1188
+ this.tradesApi = new TradesApi(apiConfig);
847
1189
  }
848
- async getAddress() {
849
- return await this.signers.ethSigner.getAddress();
1190
+ async transfer(request) {
1191
+ return transfer$1({
1192
+ request,
1193
+ user: this.user,
1194
+ starkSigner: this.starkSigner,
1195
+ transfersApi: this.transfersApi,
1196
+ passportConfig: this.passportConfig,
1197
+ });
850
1198
  }
851
1199
  registerOffchain() {
852
- return registerOffchain(this.signers, this.config);
1200
+ throw new PassportError('Operation not supported', PassportErrorType.OPERATION_NOT_SUPPORTED_ERROR);
853
1201
  }
854
- batchNftTransfer(request) {
855
- return batchTransfer({
856
- signers: this.signers,
1202
+ isRegisteredOnchain() {
1203
+ throw new PassportError('Operation not supported', PassportErrorType.OPERATION_NOT_SUPPORTED_ERROR);
1204
+ }
1205
+ createOrder(request) {
1206
+ return createOrder$1({
857
1207
  request,
858
- config: this.config,
1208
+ user: this.user,
1209
+ starkSigner: this.starkSigner,
1210
+ ordersApi: this.ordersApi,
1211
+ passportConfig: this.passportConfig,
859
1212
  });
860
1213
  }
861
1214
  cancelOrder(request) {
862
1215
  return cancelOrder$1({
863
- signers: this.signers,
864
- request,
865
- config: this.config,
866
- });
867
- }
868
- completeWithdrawal(starkPublicKey, token) {
869
- return completeWithdrawal({
870
- config: this.config,
871
- signers: this.signers,
872
- token,
873
- starkPublicKey,
874
- });
875
- }
876
- createOrder(request) {
877
- return createOrder$1({
878
- signers: this.signers,
879
1216
  request,
880
- config: this.config,
1217
+ user: this.user,
1218
+ starkSigner: this.starkSigner,
1219
+ ordersApi: this.ordersApi,
1220
+ passportConfig: this.passportConfig,
881
1221
  });
882
1222
  }
883
1223
  createTrade(request) {
884
1224
  return createTrade$1({
885
- signers: this.signers,
886
1225
  request,
887
- config: this.config,
1226
+ user: this.user,
1227
+ starkSigner: this.starkSigner,
1228
+ tradesApi: this.tradesApi,
1229
+ passportConfig: this.passportConfig,
888
1230
  });
889
1231
  }
890
- deposit(tokenAmount) {
891
- return deposit({
892
- signers: this.signers,
893
- deposit: tokenAmount,
894
- config: this.config,
1232
+ batchNftTransfer(request) {
1233
+ return batchNftTransfer({
1234
+ request,
1235
+ user: this.user,
1236
+ starkSigner: this.starkSigner,
1237
+ transfersApi: this.transfersApi,
1238
+ passportConfig: this.passportConfig,
895
1239
  });
896
1240
  }
897
1241
  exchangeTransfer(request) {
898
1242
  return exchangeTransfer$1({
899
- signers: this.signers,
900
1243
  request,
901
- config: this.config,
1244
+ user: this.user,
1245
+ starkSigner: this.starkSigner,
1246
+ exchangesApi: this.exchangesApi,
902
1247
  });
903
1248
  }
904
- async isRegisteredOnchain() {
905
- const starkPublicKey = await this.signers.starkExSigner.getAddress();
906
- return isRegisteredOnChain(starkPublicKey, this.signers.ethSigner, this.config);
1249
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1250
+ deposit(deposit) {
1251
+ throw new PassportError('Operation not supported', PassportErrorType.OPERATION_NOT_SUPPORTED_ERROR);
907
1252
  }
1253
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
908
1254
  prepareWithdrawal(request) {
909
- return prepareWithdrawal({
910
- signers: this.signers,
911
- withdrawal: request,
912
- config: this.config,
913
- });
1255
+ throw new PassportError('Operation not supported', PassportErrorType.OPERATION_NOT_SUPPORTED_ERROR);
914
1256
  }
915
- transfer(request) {
916
- return transfer$1({
917
- signers: this.signers,
918
- request,
919
- config: this.config,
920
- });
1257
+ completeWithdrawal(
1258
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1259
+ starkPublicKey,
1260
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1261
+ token) {
1262
+ throw new PassportError('Operation not supported', PassportErrorType.OPERATION_NOT_SUPPORTED_ERROR);
1263
+ }
1264
+ getAddress() {
1265
+ return Promise.resolve(this.starkSigner.getAddress());
921
1266
  }
922
1267
  }
923
1268
 
924
- const WALLET_ACTION = {
925
- SWITCH_CHAIN: 'wallet_switchEthereumChain',
926
- CONNECT: 'eth_requestAccounts',
927
- };
928
- function isRequestableProvider(provider) {
929
- return !!provider?.request;
930
- }
931
- async function connectProvider(provider, chainID) {
932
- await provider.request({ method: WALLET_ACTION.CONNECT });
933
- if (chainID) {
934
- await provider.request({
935
- method: WALLET_ACTION.SWITCH_CHAIN,
936
- params: [{ chainId: `0x${chainID.toString(16)}` }],
937
- });
938
- }
939
- }
1269
+ var Networks;
1270
+ (function (Networks) {
1271
+ Networks["PRODUCTION"] = "mainnet";
1272
+ Networks["SANDBOX"] = "goerli";
1273
+ })(Networks || (Networks = {}));
940
1274
 
941
- const ERRORS = {
942
- PROVIDER_NOT_FOUND: 'The Metamask provider was not found',
1275
+ const validateConfiguration = (configuration, requiredKeys, prefix) => {
1276
+ const missingKeys = requiredKeys
1277
+ .map((key) => !configuration[key] && key)
1278
+ .filter((n) => n)
1279
+ .join(', ');
1280
+ if (missingKeys !== '') {
1281
+ const errorMessage = prefix
1282
+ ? `${prefix} - ${missingKeys} cannot be null`
1283
+ : `${missingKeys} cannot be null`;
1284
+ throw new PassportError(errorMessage, PassportErrorType.INVALID_CONFIGURATION);
1285
+ }
943
1286
  };
944
- async function connect$1({ chainID, }) {
945
- const provider = (await detectEthereumProvider());
946
- if (!isRequestableProvider(provider)) {
947
- throw new Error(ERRORS.PROVIDER_NOT_FOUND);
1287
+ class PassportConfiguration {
1288
+ network;
1289
+ authenticationDomain;
1290
+ passportDomain;
1291
+ magicPublishableApiKey;
1292
+ magicProviderId;
1293
+ imxApiBasePath;
1294
+ oidcConfiguration;
1295
+ baseConfig;
1296
+ constructor({ baseConfig, overrides, ...oidcConfiguration }) {
1297
+ validateConfiguration(oidcConfiguration, [
1298
+ 'clientId',
1299
+ 'logoutRedirectUri',
1300
+ 'redirectUri',
1301
+ ]);
1302
+ this.oidcConfiguration = oidcConfiguration;
1303
+ this.baseConfig = baseConfig;
1304
+ if (overrides) {
1305
+ validateConfiguration(overrides, [
1306
+ 'network',
1307
+ 'authenticationDomain',
1308
+ 'magicPublishableApiKey',
1309
+ 'magicProviderId',
1310
+ 'passportDomain',
1311
+ 'imxApiBasePath',
1312
+ ], 'overrides');
1313
+ this.network = overrides.network;
1314
+ this.authenticationDomain = overrides.authenticationDomain;
1315
+ this.passportDomain = overrides.passportDomain;
1316
+ this.magicPublishableApiKey = overrides.magicPublishableApiKey;
1317
+ this.magicProviderId = overrides.magicProviderId;
1318
+ this.imxApiBasePath = overrides.imxApiBasePath;
1319
+ }
1320
+ else {
1321
+ switch (baseConfig.environment) {
1322
+ case Environment.SANDBOX: {
1323
+ this.network = Networks.SANDBOX;
1324
+ this.authenticationDomain = 'https://auth.immutable.com';
1325
+ this.magicPublishableApiKey = 'pk_live_10F423798A540ED7';
1326
+ this.magicProviderId = 'fSMzaRQ4O7p4fttl7pCyGVtJS_G70P8SNsLXtPPGHo0=';
1327
+ this.passportDomain = 'https://passport.sandbox.immutable.com';
1328
+ this.imxApiBasePath = 'https://api.sandbox.x.immutable.com';
1329
+ break;
1330
+ }
1331
+ case Environment.PRODUCTION: {
1332
+ this.network = Networks.PRODUCTION;
1333
+ this.authenticationDomain = 'https://auth.immutable.com';
1334
+ this.magicPublishableApiKey = 'pk_live_10F423798A540ED7';
1335
+ this.magicProviderId = 'fSMzaRQ4O7p4fttl7pCyGVtJS_G70P8SNsLXtPPGHo0=';
1336
+ this.passportDomain = 'https://passport.immutable.com';
1337
+ this.imxApiBasePath = 'https://api.x.immutable.com';
1338
+ break;
1339
+ }
1340
+ }
1341
+ }
948
1342
  }
949
- await connectProvider(provider, chainID);
950
- // NOTE: if we want to listen to Metamask events in the future, we can add a
951
- // listener here.
952
- return new ethers.providers.Web3Provider(provider);
953
1343
  }
954
1344
 
955
- const COMMUNICATION_TYPE = 'message';
956
- var RequestEventType;
957
- (function (RequestEventType) {
958
- RequestEventType["GET_CONNECTION_REQUEST"] = "GET_CONNECTION_REQUEST";
959
- RequestEventType["CONNECT_WALLET_REQUEST"] = "CONNECT_WALLET_REQUEST";
960
- RequestEventType["SIGN_MESSAGE_REQUEST"] = "SIGN_MESSAGE_REQUEST";
961
- RequestEventType["DISCONNECT_WALLET_REQUEST"] = "DISCONNECT_WALLET_REQUEST";
962
- })(RequestEventType || (RequestEventType = {}));
963
- var ResponseEventType;
964
- (function (ResponseEventType) {
965
- ResponseEventType["CONNECT_WALLET_RESPONSE"] = "CONNECT_WALLET_RESPONSE";
966
- ResponseEventType["SIGN_MESSAGE_RESPONSE"] = "SIGN_MESSAGE_RESPONSE";
967
- ResponseEventType["GET_CONNECTION_RESPONSE"] = "GET_CONNECTION_RESPONSE";
968
- ResponseEventType["DISCONNECT_WALLET_RESPONSE"] = "DISCONNECT_WALLET_RESPONSE";
969
- })(ResponseEventType || (ResponseEventType = {}));
1345
+ const getStarkSigner = async (signer) => {
1346
+ return withPassportError(async () => {
1347
+ const privateKey = await generateLegacyStarkPrivateKey(signer);
1348
+ return createStarkSigner(privateKey);
1349
+ }, PassportErrorType.WALLET_CONNECTION_ERROR);
1350
+ };
970
1351
 
971
- function postRequestMessage(iframe, payload) {
972
- if (iframe && iframe.contentWindow) {
973
- iframe.contentWindow.postMessage(payload, new URL(iframe.src).origin);
974
- }
1352
+ async function registerPassport({ ethSigner, starkSigner, usersApi }, authorization) {
1353
+ return withPassportError(async () => {
1354
+ const userAddress = await ethSigner.getAddress();
1355
+ const starkPublicKey = await starkSigner.getAddress();
1356
+ const signableResult = await usersApi.getSignableRegistrationOffchain({
1357
+ getSignableRegistrationRequest: {
1358
+ ether_key: userAddress,
1359
+ stark_key: starkPublicKey,
1360
+ },
1361
+ });
1362
+ const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
1363
+ const ethSignature = await signRaw(signableMessage, ethSigner);
1364
+ const starkSignature = await starkSigner.signMessage(payloadHash);
1365
+ const response = await usersApi.registerPassportUser({
1366
+ authorization: `Bearer ` + authorization,
1367
+ registerPassportUserRequest: {
1368
+ eth_signature: ethSignature,
1369
+ ether_key: userAddress,
1370
+ stark_signature: starkSignature,
1371
+ stark_key: starkPublicKey,
1372
+ },
1373
+ });
1374
+ return response.statusText;
1375
+ }, PassportErrorType.USER_REGISTRATION_ERROR);
975
1376
  }
976
1377
 
977
- function messageResponseListener(iframe, event, eventType, callback) {
978
- if (iframe && event.source !== iframe.contentWindow) {
979
- return;
1378
+ class Passport {
1379
+ authManager;
1380
+ magicAdapter;
1381
+ config;
1382
+ constructor(passportModuleConfiguration) {
1383
+ const passportConfiguration = new PassportConfiguration(passportModuleConfiguration);
1384
+ this.config = passportConfiguration;
1385
+ this.authManager = new AuthManager(this.config);
1386
+ this.magicAdapter = new MagicAdapter(this.config);
980
1387
  }
981
- const l2WalletMessage = event.data;
982
- if (l2WalletMessage.type !== eventType) {
983
- return;
1388
+ async getImxProvider(user) {
1389
+ if (!user || !user.idToken) {
1390
+ throw new PassportError('Failed to initialise', PassportErrorType.WALLET_CONNECTION_ERROR);
1391
+ }
1392
+ const provider = await this.magicAdapter.login(user.idToken);
1393
+ const ethSigner = provider.getSigner();
1394
+ const starkSigner = await getStarkSigner(ethSigner);
1395
+ if (!user.etherKey) {
1396
+ const updatedUser = await this.registerUser(ethSigner, starkSigner, user.accessToken);
1397
+ return new PassportImxProvider({
1398
+ user: updatedUser,
1399
+ starkSigner,
1400
+ passportConfig: this.config,
1401
+ });
1402
+ }
1403
+ const userWithEtherKey = user;
1404
+ return new PassportImxProvider({
1405
+ user: userWithEtherKey,
1406
+ starkSigner,
1407
+ passportConfig: this.config,
1408
+ });
984
1409
  }
985
- callback(l2WalletMessage.details);
986
- }
987
-
988
- class ImxSigner {
989
- publicAddress;
990
- iframe;
991
- constructor(publicAddress, iframe) {
992
- this.publicAddress = publicAddress;
993
- this.iframe = iframe;
1410
+ async connectImxSilent() {
1411
+ const user = await this.authManager.loginSilent();
1412
+ if (!user) {
1413
+ return null;
1414
+ }
1415
+ return this.getImxProvider(user);
994
1416
  }
995
- getAddress() {
996
- return this.publicAddress;
1417
+ async connectImx() {
1418
+ const user = await this.authManager.login();
1419
+ return this.getImxProvider(user);
997
1420
  }
998
- signMessage(rawMessage) {
999
- return new Promise((resolve, reject) => {
1000
- const listener = (event) => {
1001
- messageResponseListener(this.iframe, event, ResponseEventType.SIGN_MESSAGE_RESPONSE, (messageDetails) => {
1002
- window.removeEventListener(COMMUNICATION_TYPE, listener);
1003
- if (!messageDetails.success) {
1004
- reject(new Error(messageDetails.error?.message));
1005
- }
1006
- resolve(messageDetails.data.signedMessage);
1007
- });
1008
- };
1009
- window.addEventListener(COMMUNICATION_TYPE, listener);
1010
- postRequestMessage(this.iframe, {
1011
- type: RequestEventType.SIGN_MESSAGE_REQUEST,
1012
- details: { starkPublicKey: this.publicAddress, message: rawMessage },
1013
- });
1014
- });
1421
+ async loginCallback() {
1422
+ return this.authManager.loginCallback();
1015
1423
  }
1016
- getIFrame() {
1017
- return this.iframe;
1424
+ async logout() {
1425
+ return this.authManager.logout();
1426
+ }
1427
+ async getUserInfo() {
1428
+ const user = await this.authManager.getUser();
1429
+ return user?.profile;
1430
+ }
1431
+ async getIdToken() {
1432
+ const user = await this.authManager.getUser();
1433
+ return user?.idToken;
1434
+ }
1435
+ async getAccessToken() {
1436
+ const user = await this.authManager.getUser();
1437
+ return user?.accessToken;
1438
+ }
1439
+ async registerUser(userAdminKeySigner, starkSigner, jwt) {
1440
+ const configuration = new Configuration({
1441
+ basePath: this.config.imxApiBasePath,
1442
+ });
1443
+ const usersApi = new UsersApi(configuration);
1444
+ await registerPassport({
1445
+ ethSigner: userAdminKeySigner,
1446
+ starkSigner,
1447
+ usersApi,
1448
+ }, jwt);
1449
+ const updatedUser = await this.authManager.requestRefreshTokenAfterRegistration();
1450
+ if (!updatedUser) {
1451
+ throw new PassportError('Failed to get refresh token', PassportErrorType.REFRESH_TOKEN_ERROR);
1452
+ }
1453
+ return updatedUser;
1018
1454
  }
1019
1455
  }
1020
1456
 
1021
- const IMX_WALLET_IFRAME_ID = 'imx-wallet-app';
1022
- const IMX_WALLET_IFRAME_HOSTS = {
1023
- [Environment.DEVELOPMENT]: 'http://localhost:8080',
1024
- [Environment.SANDBOX]: 'https://wallets.sandbox.immutable.com',
1025
- [Environment.PRODUCTION]: 'https://wallets.immutable.com',
1026
- };
1027
- const IMX_WALLET_IFRAME_STYLE = 'display: none;';
1028
- function getIFrame() {
1029
- return document.querySelector(`iframe#${IMX_WALLET_IFRAME_ID}`);
1030
- }
1031
- async function setupIFrame(env) {
1032
- return new Promise((resolve) => {
1033
- const iframe = document.createElement('iframe');
1034
- iframe.setAttribute('id', IMX_WALLET_IFRAME_ID);
1035
- iframe.setAttribute('src', IMX_WALLET_IFRAME_HOSTS[env]);
1036
- iframe.setAttribute('style', IMX_WALLET_IFRAME_STYLE);
1037
- document.body.appendChild(iframe);
1038
- iframe.onload = () => resolve(iframe);
1039
- });
1457
+ function isChainValid(chainID, config) {
1458
+ return chainID === config.ethConfiguration.chainID;
1040
1459
  }
1041
- async function getOrSetupIFrame(env) {
1042
- const iframe = getIFrame();
1043
- if (iframe)
1044
- return iframe;
1045
- return await setupIFrame(env);
1460
+ async function validateChain(signer, config) {
1461
+ const chainID = await signer.getChainId();
1462
+ if (!isChainValid(chainID, config))
1463
+ throw new Error('The wallet used for this operation is not connected to the correct network.');
1046
1464
  }
1047
1465
 
1048
- const DEFAULT_CONNECTION_MESSAGE = 'Only sign this request if you’ve initiated an action with Immutable X.';
1049
- const CONNECTION_FAILED_ERROR = 'The L2 IMX Wallet connection has failed';
1050
- async function connect(l1Provider, env) {
1051
- const l1Signer = l1Provider.getSigner();
1052
- const address = await l1Signer.getAddress();
1053
- const signature = await l1Signer.signMessage(DEFAULT_CONNECTION_MESSAGE);
1054
- const iframe = await getOrSetupIFrame(env);
1055
- return new Promise((resolve, reject) => {
1056
- const listener = (event) => {
1057
- messageResponseListener(iframe, event, ResponseEventType.CONNECT_WALLET_RESPONSE, (messageDetails) => {
1058
- window.removeEventListener(COMMUNICATION_TYPE, listener);
1059
- if (!messageDetails.success) {
1060
- reject(new Error(CONNECTION_FAILED_ERROR));
1061
- }
1062
- resolve(new ImxSigner(messageDetails.data.starkPublicKey, iframe));
1063
- });
1064
- };
1065
- window.addEventListener(COMMUNICATION_TYPE, listener);
1066
- postRequestMessage(iframe, {
1067
- type: RequestEventType.CONNECT_WALLET_REQUEST,
1068
- details: { ethAddress: address, signature },
1069
- });
1466
+ async function transfer({ signers: { ethSigner, starkSigner }, request, config, }) {
1467
+ await validateChain(ethSigner, config.immutableXConfig);
1468
+ const ethAddress = await ethSigner.getAddress();
1469
+ const transfersApi = new TransfersApi(config.immutableXConfig.apiConfiguration);
1470
+ const transferAmount = request.type === 'ERC721' ? '1' : request.amount;
1471
+ const signableResult = await transfersApi.getSignableTransferV1({
1472
+ getSignableTransferRequest: {
1473
+ sender: ethAddress,
1474
+ token: convertToSignableToken(request),
1475
+ amount: transferAmount,
1476
+ receiver: request.receiver,
1477
+ },
1478
+ });
1479
+ const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
1480
+ const ethSignature = await signRaw(signableMessage, ethSigner);
1481
+ const starkSignature = await starkSigner.signMessage(payloadHash);
1482
+ const transferSigningParams = {
1483
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1484
+ sender_stark_key: signableResult.data.sender_stark_key,
1485
+ sender_vault_id: signableResult.data.sender_vault_id,
1486
+ receiver_stark_key: signableResult.data.receiver_stark_key,
1487
+ receiver_vault_id: signableResult.data.receiver_vault_id,
1488
+ asset_id: signableResult.data.asset_id,
1489
+ amount: signableResult.data.amount,
1490
+ nonce: signableResult.data.nonce,
1491
+ expiration_timestamp: signableResult.data.expiration_timestamp,
1492
+ stark_signature: starkSignature,
1493
+ };
1494
+ const response = await transfersApi.createTransferV1({
1495
+ createTransferRequest: transferSigningParams,
1496
+ xImxEthAddress: ethAddress,
1497
+ xImxEthSignature: ethSignature,
1070
1498
  });
1499
+ return {
1500
+ sent_signature: response?.data.sent_signature,
1501
+ status: response?.data.status?.toString(),
1502
+ time: response?.data.time,
1503
+ transfer_id: response?.data.transfer_id,
1504
+ };
1071
1505
  }
1072
- async function disconnect(imxSigner) {
1073
- const iframe = imxSigner.getIFrame();
1074
- return new Promise((resolve, reject) => {
1075
- const listener = (event) => {
1076
- messageResponseListener(iframe, event, ResponseEventType.DISCONNECT_WALLET_RESPONSE, (messageDetails) => {
1077
- window.removeEventListener(COMMUNICATION_TYPE, listener);
1078
- if (!messageDetails.success && messageDetails.error) {
1079
- reject(messageDetails.error);
1080
- }
1081
- iframe.remove();
1082
- resolve();
1083
- });
1506
+ async function batchTransfer({ signers: { ethSigner, starkSigner }, request, config, }) {
1507
+ await validateChain(ethSigner, config.immutableXConfig);
1508
+ const ethAddress = await ethSigner.getAddress();
1509
+ const transfersApi = new TransfersApi(config.immutableXConfig.apiConfiguration);
1510
+ const signableRequests = request.map((nftTransfer) => {
1511
+ return {
1512
+ amount: '1',
1513
+ token: convertToSignableToken({
1514
+ type: 'ERC721',
1515
+ tokenId: nftTransfer.tokenId,
1516
+ tokenAddress: nftTransfer.tokenAddress,
1517
+ }),
1518
+ receiver: nftTransfer.receiver,
1084
1519
  };
1085
- window.addEventListener(COMMUNICATION_TYPE, listener);
1086
- postRequestMessage(iframe, {
1087
- type: RequestEventType.DISCONNECT_WALLET_REQUEST,
1088
- details: { starkPublicKey: imxSigner.getAddress() },
1089
- });
1090
1520
  });
1091
- }
1092
-
1093
- var ProviderErrorType;
1094
- (function (ProviderErrorType) {
1095
- ProviderErrorType["PROVIDER_CONNECTION_ERROR"] = "PROVIDER_CONNECTION_ERROR";
1096
- ProviderErrorType["WALLET_CONNECTION_ERROR"] = "WALLET_CONNECTION_ERROR";
1097
- })(ProviderErrorType || (ProviderErrorType = {}));
1098
- class ProviderError extends Error {
1099
- type;
1100
- constructor(message, type) {
1101
- super(message);
1102
- this.type = type;
1103
- }
1104
- }
1105
- const withProviderError = async (fn, customError) => {
1106
- try {
1107
- return await fn();
1108
- }
1109
- catch (error) {
1110
- const errorMessage = customError.message || `${error.message}` || 'UnknownError';
1111
- throw new ProviderError(errorMessage, customError.type);
1112
- }
1113
- };
1114
-
1115
- class MetaMaskIMXProvider extends GenericIMXProvider {
1116
- static imxSigner;
1117
- constructor(config, ethSigner, starkExSigner) {
1118
- super(config, ethSigner, starkExSigner);
1119
- }
1120
- static async connect(config) {
1121
- const starkExConfig = config.getStarkExConfig();
1122
- return await withProviderError(async () => {
1123
- const metaMaskProvider = await connect$1({
1124
- chainID: starkExConfig.ethConfiguration.chainID,
1125
- });
1126
- this.imxSigner = await connect(metaMaskProvider, starkExConfig.env);
1127
- return new MetaMaskIMXProvider(config, metaMaskProvider.getSigner(), this.imxSigner);
1128
- }, { type: ProviderErrorType.WALLET_CONNECTION_ERROR });
1129
- }
1130
- static async disconnect() {
1131
- if (!this.imxSigner) {
1132
- throw new ProviderError('Attempted to disconnect from the MetaMask IMX provider without an established connection', ProviderErrorType.PROVIDER_CONNECTION_ERROR);
1133
- }
1134
- return withProviderError(async () => {
1135
- await disconnect(this.imxSigner);
1136
- }, { type: ProviderErrorType.PROVIDER_CONNECTION_ERROR });
1521
+ const signableResult = await transfersApi.getSignableTransfer({
1522
+ getSignableTransferRequestV2: {
1523
+ sender_ether_key: ethAddress,
1524
+ signable_requests: signableRequests,
1525
+ },
1526
+ });
1527
+ const signableMessage = signableResult.data.signable_message;
1528
+ if (signableMessage === undefined) {
1529
+ throw new Error('Invalid response from Signable registration offchain');
1137
1530
  }
1138
- static async signMessage(message) {
1139
- if (!this.imxSigner) {
1140
- throw new ProviderError('Attempted to sign a message with the MetaMask IMX provider without an established connection', ProviderErrorType.PROVIDER_CONNECTION_ERROR);
1141
- }
1142
- return withProviderError(async () => {
1143
- return await this.imxSigner.signMessage(message);
1144
- }, { type: ProviderErrorType.PROVIDER_CONNECTION_ERROR });
1531
+ const ethSignature = await signRaw(signableMessage, ethSigner);
1532
+ const requests = [];
1533
+ for (const resp of signableResult.data.signable_responses) {
1534
+ const starkSignature = await starkSigner.signMessage(resp.payload_hash);
1535
+ const req = {
1536
+ sender_vault_id: resp.sender_vault_id,
1537
+ receiver_stark_key: resp.receiver_stark_key,
1538
+ receiver_vault_id: resp.receiver_vault_id,
1539
+ asset_id: resp.asset_id,
1540
+ amount: resp.amount,
1541
+ nonce: resp.nonce,
1542
+ expiration_timestamp: resp.expiration_timestamp,
1543
+ stark_signature: starkSignature,
1544
+ };
1545
+ requests.push(req);
1145
1546
  }
1547
+ // TODO: throw error on missing payload hash?
1548
+ const transferSigningParams = {
1549
+ sender_stark_key: signableResult.data.sender_stark_key,
1550
+ requests,
1551
+ };
1552
+ const response = await transfersApi.createTransfer({
1553
+ createTransferRequestV2: transferSigningParams,
1554
+ xImxEthAddress: ethAddress,
1555
+ xImxEthSignature: ethSignature,
1556
+ });
1557
+ return {
1558
+ transfer_ids: response?.data.transfer_ids,
1559
+ };
1146
1560
  }
1147
1561
 
1148
- var PassportErrorType;
1149
- (function (PassportErrorType) {
1150
- PassportErrorType["AUTHENTICATION_ERROR"] = "AUTHENTICATION_ERROR";
1151
- PassportErrorType["INVALID_CONFIGURATION"] = "INVALID_CONFIGURATION";
1152
- PassportErrorType["WALLET_CONNECTION_ERROR"] = "WALLET_CONNECTION_ERROR";
1153
- PassportErrorType["NOT_LOGGED_IN_ERROR"] = "NOT_LOGGED_IN_ERROR";
1154
- PassportErrorType["REFRESH_TOKEN_ERROR"] = "REFRESH_TOKEN_ERROR";
1155
- PassportErrorType["USER_REGISTRATION_ERROR"] = "USER_REGISTRATION_ERROR";
1156
- PassportErrorType["LOGOUT_ERROR"] = "LOGOUT_ERROR";
1157
- PassportErrorType["TRANSFER_ERROR"] = "TRANSFER_ERROR";
1158
- PassportErrorType["CREATE_ORDER_ERROR"] = "CREATE_ORDER_ERROR";
1159
- PassportErrorType["CANCEL_ORDER_ERROR"] = "CANCEL_ORDER_ERROR";
1160
- PassportErrorType["EXCHANGE_TRANSFER_ERROR"] = "EXCHANGE_TRANSFER_ERROR";
1161
- PassportErrorType["CREATE_TRADE_ERROR"] = "CREATE_TRADE_ERROR";
1162
- PassportErrorType["OPERATION_NOT_SUPPORTED_ERROR"] = "OPERATION_NOT_SUPPORTED_ERROR";
1163
- })(PassportErrorType || (PassportErrorType = {}));
1164
- class PassportError extends Error {
1165
- type;
1166
- constructor(message, type) {
1167
- super(message);
1168
- this.type = type;
1169
- }
1562
+ async function createOrder({ signers, request, config, }) {
1563
+ await validateChain(signers.ethSigner, config.immutableXConfig);
1564
+ const ethAddress = await signers.ethSigner.getAddress();
1565
+ const ordersApi = new OrdersApi(config.immutableXConfig.apiConfiguration);
1566
+ const amountSell = request.sell.type === 'ERC721' ? '1' : request.sell.amount;
1567
+ const amountBuy = request.buy.type === 'ERC721' ? '1' : request.buy.amount;
1568
+ const getSignableOrderRequest = {
1569
+ user: ethAddress,
1570
+ amount_buy: amountBuy,
1571
+ token_buy: convertToSignableToken(request.buy),
1572
+ amount_sell: amountSell,
1573
+ token_sell: convertToSignableToken(request.sell),
1574
+ fees: request.fees,
1575
+ expiration_timestamp: request.expiration_timestamp,
1576
+ };
1577
+ const getSignableOrderResponse = await ordersApi.getSignableOrder({
1578
+ getSignableOrderRequestV3: getSignableOrderRequest,
1579
+ });
1580
+ const { signable_message: signableMessage, payload_hash: payloadHash } = getSignableOrderResponse.data;
1581
+ const ethSignature = await signRaw(signableMessage, signers.ethSigner);
1582
+ const starkSignature = await signers.starkSigner.signMessage(payloadHash);
1583
+ const resp = getSignableOrderResponse.data;
1584
+ const orderParams = {
1585
+ createOrderRequest: {
1586
+ amount_buy: resp.amount_buy,
1587
+ amount_sell: resp.amount_sell,
1588
+ asset_id_buy: resp.asset_id_buy,
1589
+ asset_id_sell: resp.asset_id_sell,
1590
+ expiration_timestamp: resp.expiration_timestamp,
1591
+ include_fees: true,
1592
+ fees: request.fees,
1593
+ nonce: resp.nonce,
1594
+ stark_key: resp.stark_key,
1595
+ stark_signature: starkSignature,
1596
+ vault_id_buy: resp.vault_id_buy,
1597
+ vault_id_sell: resp.vault_id_sell,
1598
+ },
1599
+ xImxEthAddress: ethAddress,
1600
+ xImxEthSignature: ethSignature,
1601
+ };
1602
+ const createOrderResponse = await ordersApi.createOrder(orderParams);
1603
+ return {
1604
+ ...createOrderResponse.data,
1605
+ };
1606
+ }
1607
+ async function cancelOrder({ signers, request, config, }) {
1608
+ const ordersApi = new OrdersApi(config.immutableXConfig.apiConfiguration);
1609
+ const getSignableCancelOrderResponse = await ordersApi.getSignableCancelOrder({
1610
+ getSignableCancelOrderRequest: {
1611
+ order_id: request.order_id,
1612
+ },
1613
+ });
1614
+ const { signable_message: signableMessage, payload_hash: payloadHash } = getSignableCancelOrderResponse.data;
1615
+ const ethSignature = await signRaw(signableMessage, signers.ethSigner);
1616
+ const starkSignature = await signers.starkSigner.signMessage(payloadHash);
1617
+ const ethAddress = await signers.ethSigner.getAddress();
1618
+ const cancelOrderResponse = await ordersApi.cancelOrder({
1619
+ id: request.order_id.toString(),
1620
+ cancelOrderRequest: {
1621
+ order_id: request.order_id,
1622
+ stark_signature: starkSignature,
1623
+ },
1624
+ xImxEthAddress: ethAddress,
1625
+ xImxEthSignature: ethSignature,
1626
+ });
1627
+ return {
1628
+ order_id: cancelOrderResponse.data.order_id,
1629
+ status: cancelOrderResponse.data.status,
1630
+ };
1170
1631
  }
1171
- const withPassportError = async (fn, customErrorType) => {
1172
- try {
1173
- return await fn();
1174
- }
1175
- catch (error) {
1176
- const errorMessage = `${customErrorType}: ${error.message}` || 'UnknownError';
1177
- throw new PassportError(errorMessage, customErrorType);
1178
- }
1179
- };
1180
1632
 
1181
- const POLL_INTERVAL = 1 * 1000; // every 1 second
1182
- const MAX_RETRIES = 3;
1183
- const wait = (ms) => new Promise((resolve) => {
1184
- setTimeout(() => resolve(), ms);
1185
- });
1186
- const retryWithDelay = async (fn, options) => {
1187
- const { retries = MAX_RETRIES, interval = POLL_INTERVAL, finalErr = Error('Retry failed'), } = options || {};
1633
+ async function registerOffchain(signers, config) {
1634
+ await validateChain(signers.ethSigner, config.immutableXConfig);
1635
+ const usersApi = new UsersApi(config.immutableXConfig.apiConfiguration);
1636
+ const userAddress = await signers.ethSigner.getAddress();
1637
+ const starkPublicKey = await signers.starkSigner.getAddress();
1638
+ const signableResult = await usersApi.getSignableRegistrationOffchain({
1639
+ getSignableRegistrationRequest: {
1640
+ ether_key: userAddress,
1641
+ stark_key: starkPublicKey,
1642
+ },
1643
+ });
1644
+ const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
1645
+ const ethSignature = await signRaw(signableMessage, signers.ethSigner);
1646
+ const starkSignature = await signers.starkSigner.signMessage(payloadHash);
1647
+ const registeredUser = await usersApi.registerUser({
1648
+ registerUserRequest: {
1649
+ eth_signature: ethSignature,
1650
+ ether_key: userAddress,
1651
+ stark_signature: starkSignature,
1652
+ stark_key: starkPublicKey,
1653
+ },
1654
+ });
1655
+ return registeredUser.data;
1656
+ }
1657
+ async function isRegisteredOnChain(starkPublicKey, ethSigner, config) {
1658
+ await validateChain(ethSigner, config.immutableXConfig);
1659
+ const registrationContract = Contracts.Registration.connect(config.immutableXConfig.ethConfiguration.registrationContractAddress, ethSigner);
1188
1660
  try {
1189
- return await fn();
1661
+ return await registrationContract.isRegistered(starkPublicKey);
1190
1662
  }
1191
- catch (err) {
1192
- if (retries <= 0) {
1193
- return Promise.reject(finalErr);
1663
+ catch (ex) {
1664
+ if (ex.reason === 'USER_UNREGISTERED') {
1665
+ return false;
1194
1666
  }
1195
- await wait(interval);
1196
- return retryWithDelay(fn, { retries: retries - 1, finalErr });
1667
+ throw ex;
1197
1668
  }
1198
- };
1199
-
1200
- const getAuthConfiguration = ({ oidcConfiguration, }) => {
1201
- const baseConfiguration = {
1202
- authority: oidcConfiguration.authenticationDomain,
1203
- redirect_uri: oidcConfiguration.redirectUri,
1204
- popup_redirect_uri: oidcConfiguration.redirectUri,
1205
- client_id: oidcConfiguration.clientId,
1206
- metadata: {
1207
- authorization_endpoint: `${oidcConfiguration.authenticationDomain}/authorize`,
1208
- token_endpoint: `${oidcConfiguration.authenticationDomain}/oauth/token`,
1209
- userinfo_endpoint: `${oidcConfiguration.authenticationDomain}/userinfo`,
1210
- end_session_endpoint: `${oidcConfiguration.authenticationDomain}/v2/logout` +
1211
- `?returnTo=${encodeURIComponent(oidcConfiguration.logoutRedirectUri)}` +
1212
- `&client_id=${oidcConfiguration.clientId}`,
1213
- },
1214
- mergeClaims: true,
1215
- loadUserInfo: true,
1216
- scope: oidcConfiguration.scope,
1669
+ }
1670
+ async function getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi) {
1671
+ const response = await usersApi.getSignableRegistration({
1672
+ getSignableRegistrationRequest: {
1673
+ ether_key: etherKey,
1674
+ stark_key: starkPublicKey,
1675
+ },
1676
+ });
1677
+ return {
1678
+ operator_signature: response.data.operator_signature,
1679
+ payload_hash: response.data.payload_hash,
1217
1680
  };
1218
- if (oidcConfiguration.audience) {
1219
- baseConfiguration.extraQueryParams = {
1220
- audience: oidcConfiguration.audience,
1221
- };
1222
- }
1223
- return baseConfiguration;
1681
+ }
1682
+
1683
+ const assertIsDefined = (value) => {
1684
+ if (value !== undefined)
1685
+ return value;
1686
+ throw new Error('undefined field exception');
1224
1687
  };
1225
- class AuthManager {
1226
- userManager;
1227
- config;
1228
- constructor(config) {
1229
- this.config = config;
1230
- this.userManager = new UserManager(getAuthConfiguration(config));
1231
- }
1232
- mapOidcUserToDomainModel = (oidcUser) => {
1233
- const passport = oidcUser.profile?.passport;
1234
- return {
1235
- idToken: oidcUser.id_token,
1236
- accessToken: oidcUser.access_token,
1237
- refreshToken: oidcUser.refresh_token,
1238
- profile: {
1239
- sub: oidcUser.profile.sub,
1240
- email: oidcUser.profile.email,
1241
- nickname: oidcUser.profile.nickname,
1688
+ async function prepareWithdrawalAction(params) {
1689
+ const { signers: { ethSigner, starkSigner }, type, config, } = params;
1690
+ await validateChain(ethSigner, params.config);
1691
+ const withdrawalsApi = new WithdrawalsApi(config.apiConfiguration);
1692
+ const withdrawalAmount = type === 'ERC721' ? '1' : params.amount;
1693
+ const signableWithdrawalResult = await withdrawalsApi.getSignableWithdrawal({
1694
+ getSignableWithdrawalRequest: {
1695
+ user: await ethSigner.getAddress(),
1696
+ token: convertToSignableToken(params),
1697
+ amount: withdrawalAmount,
1698
+ },
1699
+ });
1700
+ const { signable_message: signableMessage, payload_hash: payloadHash } = signableWithdrawalResult.data;
1701
+ const starkSignature = await starkSigner.signMessage(payloadHash);
1702
+ const { ethAddress, ethSignature } = await signMessage(signableMessage, ethSigner);
1703
+ const prepareWithdrawalResponse = await withdrawalsApi.createWithdrawal({
1704
+ createWithdrawalRequest: {
1705
+ stark_key: assertIsDefined(signableWithdrawalResult.data.stark_key),
1706
+ amount: withdrawalAmount,
1707
+ asset_id: assertIsDefined(signableWithdrawalResult.data.asset_id),
1708
+ vault_id: assertIsDefined(signableWithdrawalResult.data.vault_id),
1709
+ nonce: assertIsDefined(signableWithdrawalResult.data.nonce),
1710
+ stark_signature: starkSignature,
1711
+ },
1712
+ xImxEthAddress: ethAddress,
1713
+ xImxEthSignature: ethSignature,
1714
+ });
1715
+ return prepareWithdrawalResponse.data;
1716
+ }
1717
+
1718
+ async function getEncodeAssetInfo(assetType, tokenType, config, tokenData) {
1719
+ const encodingApi = new EncodingApi(config.apiConfiguration);
1720
+ const result = await encodingApi.encodeAsset({
1721
+ assetType,
1722
+ encodeAssetRequest: {
1723
+ token: {
1724
+ type: tokenType,
1725
+ ...(tokenData && { data: tokenData }),
1242
1726
  },
1243
- etherKey: passport?.ether_key || '',
1244
- };
1245
- };
1246
- async login() {
1247
- return withPassportError(async () => {
1248
- const oidcUser = await this.userManager.signinPopup();
1249
- return this.mapOidcUserToDomainModel(oidcUser);
1250
- }, PassportErrorType.AUTHENTICATION_ERROR);
1727
+ },
1728
+ });
1729
+ return result.data;
1730
+ }
1731
+
1732
+ async function executeRegisterAndWithdrawERC20({ ethSigner, assetType, starkPublicKey, config, }) {
1733
+ const etherKey = await ethSigner.getAddress();
1734
+ const imxConfig = config.immutableXConfig;
1735
+ const usersApi = new UsersApi(imxConfig.apiConfiguration);
1736
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
1737
+ const contract = Contracts.Registration.connect(config.immutableXConfig.ethConfiguration.registrationContractAddress, ethSigner);
1738
+ const populatedTransaction = await contract.populateTransaction.registerAndWithdraw(etherKey, starkPublicKey, signableResult.operator_signature, assetType);
1739
+ return ethSigner.sendTransaction(populatedTransaction);
1740
+ }
1741
+ async function executeWithdrawERC20(ethSigner, assetType, starkPublicKey, config) {
1742
+ const contract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
1743
+ const populatedTransaction = await contract.populateTransaction.withdraw(starkPublicKey, assetType);
1744
+ return ethSigner.sendTransaction(populatedTransaction);
1745
+ }
1746
+ async function completeERC20WithdrawalAction({ ethSigner, starkPublicKey, token, config, }) {
1747
+ await validateChain(ethSigner, config.immutableXConfig);
1748
+ const imxConfig = config.immutableXConfig;
1749
+ const assetType = await getEncodeAssetInfo('asset', 'ERC20', imxConfig, {
1750
+ token_address: token.tokenAddress,
1751
+ });
1752
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
1753
+ if (!isRegistered) {
1754
+ return executeRegisterAndWithdrawERC20({
1755
+ ethSigner,
1756
+ assetType: assetType.asset_type,
1757
+ starkPublicKey,
1758
+ config,
1759
+ });
1251
1760
  }
1252
- async loginCallback() {
1253
- return withPassportError(async () => this.userManager.signinPopupCallback(), PassportErrorType.AUTHENTICATION_ERROR);
1761
+ else {
1762
+ return executeWithdrawERC20(ethSigner, assetType.asset_type, starkPublicKey, imxConfig);
1254
1763
  }
1255
- async logout() {
1256
- return withPassportError(async () => this.userManager.signoutRedirect(), PassportErrorType.LOGOUT_ERROR);
1764
+ }
1765
+
1766
+ async function executeWithdrawMintableERC721(ethSigner, assetType, starkPublicKey, mintingBlob, config) {
1767
+ const contract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
1768
+ const populatedTransaction = await contract.populateTransaction.withdrawAndMint(starkPublicKey, assetType, mintingBlob);
1769
+ return ethSigner.sendTransaction(populatedTransaction);
1770
+ }
1771
+ async function executeRegisterAndWithdrawMintableERC721(ethSigner, assetType, starkPublicKey, mintingBlob, config) {
1772
+ const etherKey = await ethSigner.getAddress();
1773
+ const usersApi = new UsersApi(config.apiConfiguration);
1774
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
1775
+ const contract = Contracts.Registration.connect(config.ethConfiguration.registrationContractAddress, ethSigner);
1776
+ const populatedTransaction = await contract.populateTransaction.regsiterAndWithdrawAndMint(etherKey, starkPublicKey, signableResult.operator_signature, assetType, mintingBlob);
1777
+ return ethSigner.sendTransaction(populatedTransaction);
1778
+ }
1779
+ function getMintingBlob(token) {
1780
+ const id = token.data.id;
1781
+ const blueprint = token.data.blueprint || '';
1782
+ return encUtils.sanitizeHex(encUtils.utf8ToHex(`{${id}}:{${blueprint}}`));
1783
+ }
1784
+ async function completeMintableERC721Withdrawal(ethSigner, starkPublicKey, token, config) {
1785
+ const imxConfig = config.immutableXConfig;
1786
+ const assetType = await getEncodeAssetInfo('mintable-asset', 'ERC721', imxConfig, {
1787
+ id: token.data.id,
1788
+ token_address: token.data.tokenAddress,
1789
+ ...(token.data.blueprint && { blueprint: token.data.blueprint }),
1790
+ });
1791
+ const mintingBlob = getMintingBlob(token);
1792
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
1793
+ if (!isRegistered) {
1794
+ return executeRegisterAndWithdrawMintableERC721(ethSigner, assetType.asset_type, starkPublicKey, mintingBlob, imxConfig);
1257
1795
  }
1258
- async getUser() {
1259
- return withPassportError(async () => {
1260
- const oidcUser = await this.userManager.getUser();
1261
- if (!oidcUser) {
1262
- throw new Error('Failed to retrieve user');
1263
- }
1264
- return this.mapOidcUserToDomainModel(oidcUser);
1265
- }, PassportErrorType.NOT_LOGGED_IN_ERROR);
1796
+ else {
1797
+ return executeWithdrawMintableERC721(ethSigner, assetType.asset_type, starkPublicKey, mintingBlob, imxConfig);
1266
1798
  }
1267
- async requestRefreshTokenAfterRegistration() {
1268
- return withPassportError(async () => {
1269
- const updatedUser = await retryWithDelay(async () => {
1270
- const user = await this.userManager.signinSilent();
1271
- const passportMetadata = user?.profile?.passport;
1272
- const metadataExists = !!passportMetadata?.ether_key &&
1273
- !!passportMetadata?.stark_key &&
1274
- !!passportMetadata?.user_admin_key;
1275
- if (metadataExists) {
1276
- return user;
1277
- }
1278
- return Promise.reject('user wallet addresses not exist');
1279
- });
1280
- if (!updatedUser) {
1281
- return null;
1282
- }
1283
- return this.mapOidcUserToDomainModel(updatedUser);
1284
- }, PassportErrorType.REFRESH_TOKEN_ERROR);
1799
+ }
1800
+ async function executeRegisterAndWithdrawERC721(ethSigner, assetType, starkPublicKey, tokenId, config) {
1801
+ const etherKey = await ethSigner.getAddress();
1802
+ const usersApi = new UsersApi(config.apiConfiguration);
1803
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
1804
+ const contract = Contracts.Registration.connect(config.ethConfiguration.registrationContractAddress, ethSigner);
1805
+ const populatedTransaction = await contract.populateTransaction.registerAndWithdrawNft(etherKey, starkPublicKey, signableResult.operator_signature, assetType, tokenId);
1806
+ return ethSigner.sendTransaction(populatedTransaction);
1807
+ }
1808
+ async function executeWithdrawERC721(ethSigner, assetType, starkPublicKey, tokenId, config) {
1809
+ const contract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
1810
+ const populatedTransaction = await contract.populateTransaction.withdrawNft(starkPublicKey, assetType, tokenId);
1811
+ return ethSigner.sendTransaction(populatedTransaction);
1812
+ }
1813
+ async function completeERC721Withdrawal(ethSigner, starkPublicKey, token, config) {
1814
+ const imxConfig = config.immutableXConfig;
1815
+ const assetType = await getEncodeAssetInfo('asset', 'ERC721', imxConfig, {
1816
+ token_id: token.tokenId,
1817
+ token_address: token.tokenAddress,
1818
+ });
1819
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
1820
+ if (!isRegistered) {
1821
+ return executeRegisterAndWithdrawERC721(ethSigner, assetType.asset_type, starkPublicKey, token.tokenId, imxConfig);
1822
+ }
1823
+ else {
1824
+ return executeWithdrawERC721(ethSigner, assetType.asset_type, starkPublicKey, token.tokenId, imxConfig);
1285
1825
  }
1286
1826
  }
1827
+ async function completeERC721WithdrawalAction({ ethSigner, starkPublicKey, token, config, }) {
1828
+ await validateChain(ethSigner, config.immutableXConfig);
1829
+ const tokenAddress = token.tokenAddress;
1830
+ const tokenId = token.tokenId;
1831
+ const imxConfig = config.immutableXConfig;
1832
+ const mintsApi = new MintsApi(imxConfig.apiConfiguration);
1833
+ return await mintsApi
1834
+ .getMintableTokenDetailsByClientTokenId({
1835
+ tokenAddress,
1836
+ tokenId,
1837
+ })
1838
+ .then((mintableToken) => completeMintableERC721Withdrawal(ethSigner, starkPublicKey, {
1839
+ type: 'ERC721',
1840
+ data: {
1841
+ id: tokenId,
1842
+ tokenAddress: tokenAddress,
1843
+ blueprint: mintableToken.data.blueprint,
1844
+ },
1845
+ }, config))
1846
+ .catch((error) => {
1847
+ if (error.response?.status === 404) {
1848
+ // token is already minted on L1
1849
+ return completeERC721Withdrawal(ethSigner, starkPublicKey, token, config);
1850
+ }
1851
+ throw error; // unable to recover from any other kind of error
1852
+ });
1853
+ }
1287
1854
 
1288
- class MagicAdapter {
1289
- magicClient;
1290
- config;
1291
- constructor(config) {
1292
- this.config = config;
1293
- this.magicClient = new Magic(config.magicPublishableApiKey, {
1294
- network: config.network,
1295
- extensions: [new OpenIdExtension()],
1296
- });
1855
+ async function executeRegisterAndWithdrawEth(ethSigner, assetType, starkPublicKey, config) {
1856
+ const etherKey = await ethSigner.getAddress();
1857
+ const usersApi = new UsersApi(config.apiConfiguration);
1858
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
1859
+ const contract = Contracts.Registration.connect(config.ethConfiguration.registrationContractAddress, ethSigner);
1860
+ const populatedTransaction = await contract.populateTransaction.registerAndWithdraw(etherKey, starkPublicKey, signableResult.operator_signature, assetType);
1861
+ return ethSigner.sendTransaction(populatedTransaction);
1862
+ }
1863
+ async function executeWithdrawEth(ethSigner, assetType, starkPublicKey, config) {
1864
+ const contract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
1865
+ const populatedTransaction = await contract.populateTransaction.withdraw(starkPublicKey, assetType);
1866
+ return ethSigner.sendTransaction(populatedTransaction);
1867
+ }
1868
+ async function completeEthWithdrawalAction({ ethSigner, starkPublicKey, config, }) {
1869
+ await validateChain(ethSigner, config.immutableXConfig);
1870
+ const imxConfig = config.immutableXConfig;
1871
+ const assetType = await getEncodeAssetInfo('asset', 'ETH', imxConfig);
1872
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
1873
+ if (!isRegistered) {
1874
+ return executeRegisterAndWithdrawEth(ethSigner, assetType.asset_type, starkPublicKey, imxConfig);
1297
1875
  }
1298
- async login(idToken) {
1299
- return withPassportError(async () => {
1300
- await this.magicClient.openid.loginWithOIDC({
1301
- jwt: idToken,
1302
- providerId: this.config.magicProviderId,
1303
- });
1304
- return new ethers.providers.Web3Provider(this.magicClient
1305
- .rpcProvider);
1306
- }, PassportErrorType.WALLET_CONNECTION_ERROR);
1876
+ else {
1877
+ return executeWithdrawEth(ethSigner, assetType.asset_type, starkPublicKey, imxConfig);
1307
1878
  }
1308
1879
  }
1309
1880
 
1310
- var ReceiveMessage;
1311
- (function (ReceiveMessage) {
1312
- ReceiveMessage["CONFIRMATION_WINDOW_READY"] = "confirmation_window_ready";
1313
- ReceiveMessage["TRANSACTION_CONFIRMED"] = "transaction_confirmed";
1314
- ReceiveMessage["TRANSACTION_ERROR"] = "transaction_error";
1315
- })(ReceiveMessage || (ReceiveMessage = {}));
1316
- var SendMessage;
1317
- (function (SendMessage) {
1318
- SendMessage["TRANSACTION_START"] = "transaction_start";
1319
- })(SendMessage || (SendMessage = {}));
1320
- var TransactionTypes;
1321
- (function (TransactionTypes) {
1322
- TransactionTypes["CancelOrder"] = "delete:v1/orders";
1323
- TransactionTypes["CreateOrder"] = "post:v1/orders";
1324
- TransactionTypes["CreateTrade"] = "post:v1/trades";
1325
- TransactionTypes["CreateTransfer"] = "post:v1/transfers";
1326
- TransactionTypes["CreateBatchTransfer"] = "post:v2/transfers";
1327
- })(TransactionTypes || (TransactionTypes = {}));
1328
- const PassportEventType = 'imx_passport_confirmation';
1329
-
1330
- const openPopupCenter = ({ url, title, width, height, }) => {
1331
- // Fixes dual-screen position Most browsers Firefox
1332
- const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : window.screenX;
1333
- const dualScreenTop = window.screenTop !== undefined ? window.screenTop : window.screenY;
1334
- const windowWidth = window.innerWidth
1335
- ? window.innerWidth
1336
- : document.documentElement.clientWidth
1337
- ? document.documentElement.clientWidth
1338
- : screen.width;
1339
- const windowHeight = window.innerHeight
1340
- ? window.innerHeight
1341
- : document.documentElement.clientHeight
1342
- ? document.documentElement.clientHeight
1343
- : screen.height;
1344
- const systemZoom = windowWidth / window.screen.availWidth;
1345
- const left = (windowWidth - width) / 2 / systemZoom + dualScreenLeft;
1346
- const top = (windowHeight - height) / 2 / systemZoom + dualScreenTop;
1347
- const newWindow = window.open(url, title, `
1348
- scrollbars=yes,
1349
- width=${width / systemZoom},
1350
- height=${height / systemZoom},
1351
- top=${top},
1352
- left=${left}
1353
- `);
1354
- if (!newWindow) {
1355
- throw new Error('Failed to open confirmation screen');
1881
+ async function prepareWithdrawal({ signers, withdrawal, config, }) {
1882
+ return prepareWithdrawalAction({
1883
+ signers,
1884
+ config: config.immutableXConfig,
1885
+ ...withdrawal,
1886
+ });
1887
+ }
1888
+ async function completeWithdrawal({ signers: { ethSigner }, starkPublicKey, token, config, }) {
1889
+ switch (token.type) {
1890
+ case 'ETH':
1891
+ return completeEthWithdrawalAction({ ethSigner, starkPublicKey, config });
1892
+ case 'ERC20':
1893
+ return completeERC20WithdrawalAction({
1894
+ ethSigner,
1895
+ starkPublicKey,
1896
+ token,
1897
+ config,
1898
+ });
1899
+ case 'ERC721':
1900
+ return completeERC721WithdrawalAction({
1901
+ ethSigner,
1902
+ starkPublicKey,
1903
+ token,
1904
+ config,
1905
+ });
1356
1906
  }
1357
- newWindow.focus();
1358
- return newWindow;
1359
- };
1907
+ }
1360
1908
 
1361
- const ConfirmationWindowTitle = 'Confirm this transaction';
1362
- const ConfirmationWindowHeight = 600;
1363
- const ConfirmationWindowWidth = 600;
1364
- const ConfirmationWindowClosedPollingDuration = 1000;
1365
- class ConfirmationScreen {
1366
- config;
1367
- constructor(config) {
1368
- this.config = config;
1369
- }
1370
- postMessage(destinationWindow, accessToken, message) {
1371
- destinationWindow.postMessage({
1372
- eventType: PassportEventType,
1373
- accessToken,
1374
- ...message,
1375
- }, this.config.passportDomain);
1909
+ async function createTrade({ signers: { ethSigner, starkSigner }, request, config, }) {
1910
+ await validateChain(ethSigner, config.immutableXConfig);
1911
+ const ethAddress = await ethSigner.getAddress();
1912
+ const tradesApi = new TradesApi(config.immutableXConfig.apiConfiguration);
1913
+ const signableResult = await tradesApi.getSignableTrade({
1914
+ getSignableTradeRequest: {
1915
+ user: ethAddress,
1916
+ order_id: request.order_id,
1917
+ fees: request.fees,
1918
+ },
1919
+ });
1920
+ const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
1921
+ const ethSignature = await signRaw(signableMessage, ethSigner);
1922
+ const starkSignature = await starkSigner.signMessage(payloadHash);
1923
+ const createTradeResponse = await tradesApi.createTrade({
1924
+ createTradeRequest: {
1925
+ amount_buy: signableResult.data.amount_buy,
1926
+ amount_sell: signableResult.data.amount_sell,
1927
+ asset_id_buy: signableResult.data.asset_id_buy,
1928
+ asset_id_sell: signableResult.data.asset_id_sell,
1929
+ expiration_timestamp: signableResult.data.expiration_timestamp,
1930
+ fee_info: signableResult.data.fee_info,
1931
+ fees: request.fees,
1932
+ include_fees: true,
1933
+ nonce: signableResult.data.nonce,
1934
+ order_id: request.order_id,
1935
+ stark_key: signableResult.data.stark_key,
1936
+ vault_id_buy: signableResult.data.vault_id_buy,
1937
+ vault_id_sell: signableResult.data.vault_id_sell,
1938
+ stark_signature: starkSignature,
1939
+ },
1940
+ xImxEthAddress: ethAddress,
1941
+ xImxEthSignature: ethSignature,
1942
+ });
1943
+ return createTradeResponse.data;
1944
+ }
1945
+
1946
+ async function depositEth({ signers: { ethSigner }, deposit, config, }) {
1947
+ await validateChain(ethSigner, config.immutableXConfig);
1948
+ const user = await ethSigner.getAddress();
1949
+ const data = {
1950
+ decimals: 18,
1951
+ };
1952
+ const amount = parseUnits(deposit.amount, 'wei');
1953
+ const imxConfig = config.immutableXConfig;
1954
+ const depositsApi = new DepositsApi(imxConfig.apiConfiguration);
1955
+ const encodingApi = new EncodingApi(imxConfig.apiConfiguration);
1956
+ const usersApi = new UsersApi(imxConfig.apiConfiguration);
1957
+ const getSignableDepositRequest = {
1958
+ user,
1959
+ token: {
1960
+ type: deposit.type,
1961
+ data,
1962
+ },
1963
+ amount: amount.toString(),
1964
+ };
1965
+ const signableDepositResult = await depositsApi.getSignableDeposit({
1966
+ getSignableDepositRequest,
1967
+ });
1968
+ const encodingResult = await encodingApi.encodeAsset({
1969
+ assetType: 'asset',
1970
+ encodeAssetRequest: {
1971
+ token: {
1972
+ type: deposit.type,
1973
+ },
1974
+ },
1975
+ });
1976
+ const assetType = encodingResult.data.asset_type;
1977
+ const starkPublicKey = signableDepositResult.data.stark_key;
1978
+ const vaultId = signableDepositResult.data.vault_id;
1979
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
1980
+ if (!isRegistered) {
1981
+ return executeRegisterAndDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, imxConfig, usersApi);
1376
1982
  }
1377
- startTransaction(accessToken, transaction) {
1378
- return new Promise((resolve, reject) => {
1379
- const messageHandler = ({ data, origin }) => {
1380
- if (origin != this.config.passportDomain ||
1381
- data.eventType != PassportEventType) {
1382
- return;
1383
- }
1384
- switch (data.messageType) {
1385
- case ReceiveMessage.CONFIRMATION_WINDOW_READY: {
1386
- this.postMessage(confirmationWindow, accessToken, {
1387
- messageType: SendMessage.TRANSACTION_START,
1388
- messageData: transaction,
1389
- });
1390
- break;
1391
- }
1392
- case ReceiveMessage.TRANSACTION_CONFIRMED: {
1393
- resolve({ confirmed: true });
1394
- break;
1395
- }
1396
- case ReceiveMessage.TRANSACTION_ERROR: {
1397
- reject(new Error('Transaction error'));
1398
- break;
1399
- }
1400
- default:
1401
- reject(new Error('Unsupported message type'));
1402
- }
1403
- };
1404
- window.addEventListener('message', messageHandler);
1405
- const confirmationWindow = openPopupCenter({
1406
- url: `${this.config.passportDomain}/transaction-confirmation`,
1407
- title: ConfirmationWindowTitle,
1408
- width: ConfirmationWindowWidth,
1409
- height: ConfirmationWindowHeight,
1410
- });
1411
- // https://stackoverflow.com/questions/9388380/capture-the-close-event-of-popup-window-in-javascript/48240128#48240128
1412
- const timer = setInterval(function () {
1413
- if (confirmationWindow.closed) {
1414
- clearInterval(timer);
1415
- window.removeEventListener('message', messageHandler);
1416
- resolve({ confirmed: false });
1417
- }
1418
- }, ConfirmationWindowClosedPollingDuration);
1419
- });
1983
+ else {
1984
+ return executeDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, imxConfig);
1420
1985
  }
1421
1986
  }
1987
+ async function executeRegisterAndDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, config, usersApi) {
1988
+ const etherKey = await ethSigner.getAddress();
1989
+ const coreContract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
1990
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
1991
+ const populatedTransaction = await coreContract.populateTransaction.registerAndDepositEth(etherKey, starkPublicKey, signableResult.operator_signature, assetType, vaultId);
1992
+ return ethSigner.sendTransaction({ ...populatedTransaction, value: amount });
1993
+ }
1994
+ async function executeDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, config) {
1995
+ const coreContract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
1996
+ const populatedTransaction = await coreContract.populateTransaction['deposit(uint256,uint256,uint256)'](starkPublicKey, assetType, vaultId);
1997
+ return ethSigner.sendTransaction({ ...populatedTransaction, value: amount });
1998
+ }
1422
1999
 
1423
- const ERC721$1 = 'ERC721';
1424
- const transfer = ({ request, transfersApi, starkSigner, user, passportConfig, }) => {
1425
- return withPassportError(async () => {
1426
- const transferAmount = request.type === ERC721$1 ? '1' : request.amount;
1427
- const getSignableTransferRequest = {
1428
- sender: user.etherKey,
1429
- token: convertToSignableToken(request),
1430
- amount: transferAmount,
1431
- receiver: request.receiver,
1432
- };
1433
- const signableResult = await transfersApi.getSignableTransferV1({
1434
- getSignableTransferRequest,
1435
- });
1436
- const confirmationScreen = new ConfirmationScreen(passportConfig);
1437
- const confirmationResult = await confirmationScreen.startTransaction(user.accessToken, {
1438
- transactionType: TransactionTypes.CreateTransfer,
1439
- transactionData: getSignableTransferRequest,
1440
- });
1441
- if (!confirmationResult.confirmed) {
1442
- throw new Error('Transaction rejected by user');
1443
- }
1444
- const signableResultData = signableResult.data;
1445
- const { payload_hash: payloadHash } = signableResultData;
1446
- const starkSignature = await starkSigner.signMessage(payloadHash);
1447
- const senderStarkKey = await starkSigner.getAddress();
1448
- const transferSigningParams = {
1449
- sender_stark_key: signableResultData.sender_stark_key || senderStarkKey,
1450
- sender_vault_id: signableResultData.sender_vault_id,
1451
- receiver_stark_key: signableResultData.receiver_stark_key,
1452
- receiver_vault_id: signableResultData.receiver_vault_id,
1453
- asset_id: signableResultData.asset_id,
1454
- amount: signableResultData.amount,
1455
- nonce: signableResultData.nonce,
1456
- expiration_timestamp: signableResultData.expiration_timestamp,
1457
- stark_signature: starkSignature,
1458
- };
1459
- const createTransferRequest = {
1460
- createTransferRequest: transferSigningParams,
1461
- };
1462
- const headers = {
1463
- Authorization: 'Bearer ' + user.accessToken,
1464
- };
1465
- const { data: responseData } = await transfersApi.createTransferV1(createTransferRequest, { headers });
1466
- return {
1467
- sent_signature: responseData.sent_signature,
1468
- status: responseData.status?.toString(),
1469
- time: responseData.time,
1470
- transfer_id: responseData.transfer_id,
1471
- };
1472
- }, PassportErrorType.TRANSFER_ERROR);
1473
- };
1474
- async function batchNftTransfer({ user, starkSigner, request, transfersApi, passportConfig, }) {
1475
- return withPassportError(async () => {
1476
- const ethAddress = user.etherKey;
1477
- const signableRequests = request.map((nftTransfer) => {
1478
- return {
1479
- amount: '1',
1480
- token: convertToSignableToken({
1481
- type: ERC721$1,
1482
- tokenId: nftTransfer.tokenId,
1483
- tokenAddress: nftTransfer.tokenAddress,
1484
- }),
1485
- receiver: nftTransfer.receiver,
1486
- };
1487
- });
1488
- const getSignableTransferRequestV2 = {
1489
- sender_ether_key: ethAddress,
1490
- signable_requests: signableRequests,
1491
- };
1492
- const signableResult = await transfersApi.getSignableTransfer({
1493
- getSignableTransferRequestV2,
1494
- });
1495
- const confirmationScreen = new ConfirmationScreen(passportConfig);
1496
- const confirmationResult = await confirmationScreen.startTransaction(user.accessToken, {
1497
- transactionType: TransactionTypes.CreateBatchTransfer,
1498
- transactionData: getSignableTransferRequestV2,
1499
- });
1500
- if (!confirmationResult.confirmed) {
1501
- throw new Error('Transaction rejected by user');
1502
- }
1503
- const requests = await Promise.all(signableResult.data.signable_responses.map(async (resp) => {
1504
- const starkSignature = await starkSigner.signMessage(resp.payload_hash);
1505
- return {
1506
- sender_vault_id: resp.sender_vault_id,
1507
- receiver_stark_key: resp.receiver_stark_key,
1508
- receiver_vault_id: resp.receiver_vault_id,
1509
- asset_id: resp.asset_id,
1510
- amount: resp.amount,
1511
- nonce: resp.nonce,
1512
- expiration_timestamp: resp.expiration_timestamp,
1513
- stark_signature: starkSignature,
1514
- };
1515
- }));
1516
- const transferSigningParams = {
1517
- sender_stark_key: signableResult.data.sender_stark_key,
1518
- requests,
1519
- };
1520
- const headers = {
1521
- Authorization: 'Bearer ' + user.accessToken,
1522
- };
1523
- const response = await transfersApi.createTransfer({
1524
- createTransferRequestV2: transferSigningParams,
1525
- }, { headers });
1526
- return {
1527
- transfer_ids: response?.data.transfer_ids,
1528
- };
1529
- }, PassportErrorType.TRANSFER_ERROR);
2000
+ async function depositERC20({ signers: { ethSigner }, deposit, config, }) {
2001
+ await validateChain(ethSigner, config.immutableXConfig);
2002
+ const { apiConfiguration, ethConfiguration } = config.immutableXConfig;
2003
+ const user = await ethSigner.getAddress();
2004
+ const tokensApi = new TokensApi(apiConfiguration);
2005
+ const depositsApi = new DepositsApi(apiConfiguration);
2006
+ const encodingApi = new EncodingApi(apiConfiguration);
2007
+ const usersApi = new UsersApi(apiConfiguration);
2008
+ // Get decimals for this specific ERC20
2009
+ const token = await tokensApi.getToken({ address: deposit.tokenAddress });
2010
+ const decimals = parseInt(token.data.decimals);
2011
+ const data = {
2012
+ decimals,
2013
+ token_address: deposit.tokenAddress,
2014
+ };
2015
+ const amount = parseUnits(deposit.amount, 0); // 0 to always use undecimalized value
2016
+ // Approve whether an amount of token from an account can be spent by a third-party account
2017
+ const tokenContract = Contracts.IERC20.connect(deposit.tokenAddress, ethSigner);
2018
+ const approveTransaction = await tokenContract.populateTransaction.approve(ethConfiguration.coreContractAddress, amount);
2019
+ await ethSigner.sendTransaction(approveTransaction);
2020
+ const getSignableDepositRequest = {
2021
+ user,
2022
+ token: {
2023
+ type: deposit.type,
2024
+ data,
2025
+ },
2026
+ amount: amount.toString(),
2027
+ };
2028
+ const signableDepositResult = await depositsApi.getSignableDeposit({
2029
+ getSignableDepositRequest,
2030
+ });
2031
+ // Perform encoding on asset details to get an assetType (required for stark contract request)
2032
+ const encodingResult = await encodingApi.encodeAsset({
2033
+ assetType: 'asset',
2034
+ encodeAssetRequest: {
2035
+ token: {
2036
+ type: deposit.type,
2037
+ data: {
2038
+ token_address: deposit.tokenAddress,
2039
+ },
2040
+ },
2041
+ },
2042
+ });
2043
+ const assetType = encodingResult.data.asset_type;
2044
+ const starkPublicKey = signableDepositResult.data.stark_key;
2045
+ const vaultId = signableDepositResult.data.vault_id;
2046
+ const quantizedAmount = BigNumber.from(signableDepositResult.data.amount);
2047
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
2048
+ if (!isRegistered) {
2049
+ return executeRegisterAndDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, ethConfiguration, usersApi);
2050
+ }
2051
+ else {
2052
+ return executeDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, ethConfiguration);
2053
+ }
2054
+ }
2055
+ async function executeDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, config) {
2056
+ const coreContract = Contracts.Core.connect(config.coreContractAddress, ethSigner);
2057
+ const populatedTransaction = await coreContract.populateTransaction.depositERC20(starkPublicKey, assetType, vaultId, quantizedAmount);
2058
+ return ethSigner.sendTransaction(populatedTransaction);
2059
+ }
2060
+ async function executeRegisterAndDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, config, usersApi) {
2061
+ const etherKey = await ethSigner.getAddress();
2062
+ const coreContract = Contracts.Core.connect(config.coreContractAddress, ethSigner);
2063
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
2064
+ const populatedTransaction = await coreContract.populateTransaction.registerAndDepositERC20(etherKey, starkPublicKey, signableResult.operator_signature, assetType, vaultId, quantizedAmount);
2065
+ return ethSigner.sendTransaction(populatedTransaction);
1530
2066
  }
1531
2067
 
1532
- const ERC721 = 'ERC721';
1533
- async function createOrder({ starkSigner, user, request, ordersApi, passportConfig, }) {
1534
- return withPassportError(async () => {
1535
- const ethAddress = user.etherKey;
1536
- const amountSell = request.sell.type === ERC721 ? '1' : request.sell.amount;
1537
- const amountBuy = request.buy.type === ERC721 ? '1' : request.buy.amount;
1538
- const getSignableOrderRequestV3 = {
1539
- user: ethAddress,
1540
- amount_buy: amountBuy,
1541
- token_buy: convertToSignableToken(request.buy),
1542
- amount_sell: amountSell,
1543
- token_sell: convertToSignableToken(request.sell),
1544
- fees: request.fees,
1545
- expiration_timestamp: request.expiration_timestamp,
1546
- };
1547
- const getSignableOrderResponse = await ordersApi.getSignableOrder({
1548
- getSignableOrderRequestV3,
1549
- });
1550
- const confirmationScreen = new ConfirmationScreen(passportConfig);
1551
- const confirmationResult = await confirmationScreen.startTransaction(user.accessToken, {
1552
- transactionType: TransactionTypes.CreateOrder,
1553
- transactionData: getSignableOrderRequestV3,
1554
- });
1555
- if (!confirmationResult.confirmed) {
1556
- throw new Error('Transaction rejected by user');
1557
- }
1558
- const { payload_hash: payloadHash } = getSignableOrderResponse.data;
1559
- const starkSignature = await starkSigner.signMessage(payloadHash);
1560
- const signableResultData = getSignableOrderResponse.data;
1561
- const orderParams = {
1562
- createOrderRequest: {
1563
- include_fees: true,
1564
- fees: request.fees,
1565
- stark_signature: starkSignature,
1566
- amount_buy: signableResultData.amount_buy,
1567
- amount_sell: signableResultData.amount_sell,
1568
- asset_id_buy: signableResultData.asset_id_buy,
1569
- asset_id_sell: signableResultData.asset_id_sell,
1570
- expiration_timestamp: signableResultData.expiration_timestamp,
1571
- nonce: signableResultData.nonce,
1572
- stark_key: signableResultData.stark_key,
1573
- vault_id_buy: signableResultData.vault_id_buy,
1574
- vault_id_sell: signableResultData.vault_id_sell,
2068
+ async function depositERC721({ signers: { ethSigner }, deposit, config, }) {
2069
+ await validateChain(ethSigner, config.immutableXConfig);
2070
+ const user = await ethSigner.getAddress();
2071
+ const { immutableXConfig } = config;
2072
+ const depositsApi = new DepositsApi(immutableXConfig.apiConfiguration);
2073
+ const encodingApi = new EncodingApi(immutableXConfig.apiConfiguration);
2074
+ const usersApi = new UsersApi(immutableXConfig.apiConfiguration);
2075
+ const data = {
2076
+ token_address: deposit.tokenAddress,
2077
+ token_id: deposit.tokenId,
2078
+ };
2079
+ const amount = '1';
2080
+ const getSignableDepositRequest = {
2081
+ user,
2082
+ token: {
2083
+ type: deposit.type,
2084
+ data,
2085
+ },
2086
+ amount: amount.toString(),
2087
+ };
2088
+ const signableDepositResult = await depositsApi.getSignableDeposit({
2089
+ getSignableDepositRequest,
2090
+ });
2091
+ // Perform encoding on asset details to get an assetType (required for stark contract request)
2092
+ const encodingResult = await encodingApi.encodeAsset({
2093
+ assetType: 'asset',
2094
+ encodeAssetRequest: {
2095
+ token: {
2096
+ type: deposit.type,
2097
+ data: {
2098
+ token_address: deposit.tokenAddress,
2099
+ token_id: deposit.tokenId,
2100
+ },
1575
2101
  },
1576
- };
1577
- const headers = {
1578
- Authorization: 'Bearer ' + user.accessToken,
1579
- };
1580
- const createOrderResponse = await ordersApi.createOrder(orderParams, {
1581
- headers,
1582
- });
1583
- return {
1584
- ...createOrderResponse.data,
1585
- };
1586
- }, PassportErrorType.CREATE_ORDER_ERROR);
2102
+ },
2103
+ });
2104
+ const assetType = encodingResult.data.asset_type;
2105
+ const starkPublicKey = signableDepositResult.data.stark_key;
2106
+ const vaultId = signableDepositResult.data.vault_id;
2107
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
2108
+ // Approve whether an amount of token from an account can be spent by a third-party account
2109
+ const tokenContract = Contracts.IERC721.connect(deposit.tokenAddress, ethSigner);
2110
+ const operator = immutableXConfig.ethConfiguration.coreContractAddress;
2111
+ const isApprovedForAll = await tokenContract.isApprovedForAll(user, operator);
2112
+ if (!isApprovedForAll) {
2113
+ await tokenContract.setApprovalForAll(operator, true);
2114
+ }
2115
+ if (!isRegistered) {
2116
+ const signableResult = await getSignableRegistrationOnchain(user, starkPublicKey, usersApi);
2117
+ const coreContract = Contracts.Core.connect(immutableXConfig.ethConfiguration.coreContractAddress, ethSigner);
2118
+ // Note: proxy registration contract registerAndDepositNft method is not used as it currently fails erc721 transfer ownership check
2119
+ await coreContract.registerUser(user, starkPublicKey, signableResult.operator_signature);
2120
+ }
2121
+ return executeDepositERC721(ethSigner, deposit.tokenId, assetType, starkPublicKey, vaultId, immutableXConfig);
1587
2122
  }
1588
- async function cancelOrder({ user, starkSigner, request, ordersApi, passportConfig, }) {
1589
- return withPassportError(async () => {
1590
- const getSignableCancelOrderRequest = {
1591
- order_id: request.order_id,
1592
- };
1593
- const getSignableCancelOrderResponse = await ordersApi.getSignableCancelOrder({
1594
- getSignableCancelOrderRequest,
1595
- });
1596
- const confirmationScreen = new ConfirmationScreen(passportConfig);
1597
- const confirmationResult = await confirmationScreen.startTransaction(user.accessToken, {
1598
- transactionType: TransactionTypes.CancelOrder,
1599
- transactionData: getSignableCancelOrderRequest,
1600
- });
1601
- if (!confirmationResult.confirmed) {
1602
- throw new Error('Transaction rejected by user');
1603
- }
1604
- const { payload_hash: payloadHash } = getSignableCancelOrderResponse.data;
1605
- const starkSignature = await starkSigner.signMessage(payloadHash);
1606
- const headers = {
1607
- Authorization: 'Bearer ' + user.accessToken,
1608
- };
1609
- const cancelOrderResponse = await ordersApi.cancelOrder({
1610
- id: request.order_id.toString(),
1611
- cancelOrderRequest: {
1612
- order_id: request.order_id,
1613
- stark_signature: starkSignature,
1614
- },
1615
- }, { headers });
1616
- return {
1617
- order_id: cancelOrderResponse.data.order_id,
1618
- status: cancelOrderResponse.data.status,
1619
- };
1620
- }, PassportErrorType.CANCEL_ORDER_ERROR);
2123
+ async function executeDepositERC721(ethSigner, tokenId, assetType, starkPublicKey, vaultId, config) {
2124
+ const coreContract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
2125
+ const populatedTransaction = await coreContract.populateTransaction.depositNft(starkPublicKey, assetType, vaultId, tokenId);
2126
+ return ethSigner.sendTransaction(populatedTransaction);
1621
2127
  }
1622
2128
 
1623
- async function exchangeTransfer({ user, starkSigner, request, exchangesApi, }) {
1624
- return withPassportError(async () => {
1625
- const ethAddress = user.etherKey;
1626
- const transferAmount = request.amount;
1627
- const signableResult = await exchangesApi.getExchangeSignableTransfer({
1628
- id: request.transactionID,
1629
- getSignableTransferRequest: {
1630
- sender: ethAddress,
1631
- token: convertToSignableToken(request),
1632
- amount: transferAmount,
1633
- receiver: request.receiver,
1634
- },
1635
- });
1636
- const starkAddress = await starkSigner.getAddress();
1637
- const { payload_hash: payloadHash } = signableResult.data;
1638
- const starkSignature = await starkSigner.signMessage(payloadHash);
1639
- const transferSigningParams = {
1640
- sender_stark_key: signableResult.data.sender_stark_key || starkAddress,
1641
- sender_vault_id: signableResult.data.sender_vault_id,
1642
- receiver_stark_key: signableResult.data.receiver_stark_key,
1643
- receiver_vault_id: signableResult.data.receiver_vault_id,
1644
- asset_id: signableResult.data.asset_id,
1645
- amount: signableResult.data.amount,
1646
- nonce: signableResult.data.nonce,
1647
- expiration_timestamp: signableResult.data.expiration_timestamp,
1648
- stark_signature: starkSignature,
1649
- };
1650
- const headers = {
1651
- Authorization: 'Bearer ' + user.accessToken,
1652
- };
1653
- const response = await exchangesApi.createExchangeTransfer({
1654
- id: request.transactionID,
1655
- createTransferRequest: transferSigningParams,
1656
- }, { headers });
1657
- return {
1658
- sent_signature: response?.data.sent_signature,
1659
- status: response?.data.status?.toString(),
1660
- time: response?.data.time,
1661
- transfer_id: response?.data.transfer_id,
1662
- };
1663
- }, PassportErrorType.EXCHANGE_TRANSFER_ERROR);
2129
+ async function deposit({ signers, deposit, config }) {
2130
+ switch (deposit.type) {
2131
+ case 'ETH':
2132
+ return depositEth({ signers, deposit, config });
2133
+ case 'ERC20':
2134
+ return depositERC20({ signers, deposit, config });
2135
+ case 'ERC721':
2136
+ return depositERC721({ signers, deposit, config });
2137
+ }
1664
2138
  }
1665
2139
 
1666
- async function createTrade({ request, tradesApi, user, starkSigner, passportConfig, }) {
1667
- return withPassportError(async () => {
1668
- const ethAddress = user.etherKey;
1669
- const getSignableTradeRequest = {
1670
- expiration_timestamp: request.expiration_timestamp,
1671
- fees: request.fees,
1672
- order_id: request.order_id,
1673
- user: ethAddress,
1674
- };
1675
- const getSignableTradeResponse = await tradesApi.getSignableTrade({
1676
- getSignableTradeRequest,
1677
- });
1678
- const confirmationScreen = new ConfirmationScreen(passportConfig);
1679
- const confirmationResult = await confirmationScreen.startTransaction(user.accessToken, {
1680
- transactionType: TransactionTypes.CreateTrade,
1681
- transactionData: getSignableTradeRequest,
1682
- });
1683
- if (!confirmationResult.confirmed) {
1684
- throw new Error('Transaction rejected by user');
1685
- }
1686
- const { payload_hash: payloadHash } = getSignableTradeResponse.data;
1687
- const starkSignature = await starkSigner.signMessage(payloadHash);
1688
- const { data: signableResultData } = getSignableTradeResponse;
1689
- const tradeParams = {
1690
- createTradeRequest: {
1691
- include_fees: true,
1692
- fees: request?.fees,
1693
- stark_signature: starkSignature,
1694
- order_id: request?.order_id,
1695
- fee_info: signableResultData.fee_info,
1696
- amount_buy: signableResultData.amount_buy,
1697
- amount_sell: signableResultData.amount_sell,
1698
- asset_id_buy: signableResultData.asset_id_buy,
1699
- asset_id_sell: signableResultData.asset_id_sell,
1700
- expiration_timestamp: signableResultData.expiration_timestamp,
1701
- nonce: signableResultData.nonce,
1702
- stark_key: signableResultData.stark_key,
1703
- vault_id_buy: signableResultData.vault_id_buy,
1704
- vault_id_sell: signableResultData.vault_id_sell,
1705
- },
1706
- };
1707
- const headers = { Authorization: 'Bearer ' + user.accessToken };
1708
- const { data: createTradeResponse } = await tradesApi.createTrade(tradeParams, {
1709
- headers,
1710
- });
1711
- return createTradeResponse;
1712
- }, PassportErrorType.CREATE_TRADE_ERROR);
2140
+ async function exchangeTransfer({ signers, request, config, }) {
2141
+ await validateChain(signers.ethSigner, config.immutableXConfig);
2142
+ const exchangeApi = new ExchangesApi(config.immutableXConfig.apiConfiguration);
2143
+ const ethAddress = await signers.ethSigner.getAddress();
2144
+ const transferAmount = request.amount;
2145
+ const signableResult = await exchangeApi.getExchangeSignableTransfer({
2146
+ id: request.transactionID,
2147
+ getSignableTransferRequest: {
2148
+ sender: ethAddress,
2149
+ token: convertToSignableToken(request),
2150
+ amount: transferAmount,
2151
+ receiver: request.receiver,
2152
+ },
2153
+ });
2154
+ const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
2155
+ const ethSignature = await signRaw(signableMessage, signers.ethSigner);
2156
+ const starkSignature = await signers.starkSigner.signMessage(payloadHash);
2157
+ const transferSigningParams = {
2158
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2159
+ sender_stark_key: signableResult.data.sender_stark_key,
2160
+ sender_vault_id: signableResult.data.sender_vault_id,
2161
+ receiver_stark_key: signableResult.data.receiver_stark_key,
2162
+ receiver_vault_id: signableResult.data.receiver_vault_id,
2163
+ asset_id: signableResult.data.asset_id,
2164
+ amount: signableResult.data.amount,
2165
+ nonce: signableResult.data.nonce,
2166
+ expiration_timestamp: signableResult.data.expiration_timestamp,
2167
+ stark_signature: starkSignature,
2168
+ };
2169
+ const response = await exchangeApi.createExchangeTransfer({
2170
+ id: request.transactionID,
2171
+ createTransferRequest: transferSigningParams,
2172
+ xImxEthAddress: ethAddress,
2173
+ xImxEthSignature: ethSignature,
2174
+ });
2175
+ return {
2176
+ sent_signature: response?.data.sent_signature,
2177
+ status: response?.data.status?.toString(),
2178
+ time: response?.data.time,
2179
+ transfer_id: response?.data.transfer_id,
2180
+ };
1713
2181
  }
1714
2182
 
1715
- class PassportImxProvider {
1716
- user;
1717
- starkSigner;
1718
- transfersApi;
1719
- ordersApi;
1720
- passportConfig;
1721
- exchangesApi;
1722
- tradesApi;
1723
- constructor({ user, starkSigner, passportConfig }) {
1724
- this.user = user;
1725
- this.starkSigner = starkSigner;
1726
- this.passportConfig = passportConfig;
1727
- const apiConfig = new Configuration$1({
1728
- basePath: passportConfig.imxAPIConfiguration.basePath,
1729
- });
1730
- this.transfersApi = new TransfersApi(apiConfig);
1731
- this.ordersApi = new OrdersApi(apiConfig);
1732
- this.exchangesApi = new ExchangesApi(apiConfig);
1733
- this.tradesApi = new TradesApi(apiConfig);
2183
+ class GenericIMXProvider {
2184
+ config;
2185
+ signers;
2186
+ constructor(config, ethSigner, starkSigner) {
2187
+ this.config = config;
2188
+ this.signers = { ethSigner, starkSigner };
1734
2189
  }
1735
- async transfer(request) {
1736
- return transfer({
1737
- request,
1738
- user: this.user,
1739
- starkSigner: this.starkSigner,
1740
- transfersApi: this.transfersApi,
1741
- passportConfig: this.passportConfig,
1742
- });
2190
+ async getAddress() {
2191
+ return await this.signers.ethSigner.getAddress();
1743
2192
  }
1744
2193
  registerOffchain() {
1745
- throw new PassportError('Operation not supported', PassportErrorType.OPERATION_NOT_SUPPORTED_ERROR);
2194
+ return registerOffchain(this.signers, this.config);
1746
2195
  }
1747
- isRegisteredOnchain() {
1748
- throw new PassportError('Operation not supported', PassportErrorType.OPERATION_NOT_SUPPORTED_ERROR);
2196
+ batchNftTransfer(request) {
2197
+ return batchTransfer({
2198
+ signers: this.signers,
2199
+ request,
2200
+ config: this.config,
2201
+ });
1749
2202
  }
1750
- createOrder(request) {
1751
- return createOrder({
2203
+ cancelOrder(request) {
2204
+ return cancelOrder({
2205
+ signers: this.signers,
1752
2206
  request,
1753
- user: this.user,
1754
- starkSigner: this.starkSigner,
1755
- ordersApi: this.ordersApi,
1756
- passportConfig: this.passportConfig,
2207
+ config: this.config,
2208
+ });
2209
+ }
2210
+ completeWithdrawal(starkPublicKey, token) {
2211
+ return completeWithdrawal({
2212
+ config: this.config,
2213
+ signers: this.signers,
2214
+ token,
2215
+ starkPublicKey,
1757
2216
  });
1758
2217
  }
1759
- cancelOrder(request) {
1760
- return cancelOrder({
2218
+ createOrder(request) {
2219
+ return createOrder({
2220
+ signers: this.signers,
1761
2221
  request,
1762
- user: this.user,
1763
- starkSigner: this.starkSigner,
1764
- ordersApi: this.ordersApi,
1765
- passportConfig: this.passportConfig,
2222
+ config: this.config,
1766
2223
  });
1767
2224
  }
1768
2225
  createTrade(request) {
1769
2226
  return createTrade({
2227
+ signers: this.signers,
1770
2228
  request,
1771
- user: this.user,
1772
- starkSigner: this.starkSigner,
1773
- tradesApi: this.tradesApi,
1774
- passportConfig: this.passportConfig,
2229
+ config: this.config,
1775
2230
  });
1776
2231
  }
1777
- batchNftTransfer(request) {
1778
- return batchNftTransfer({
1779
- request,
1780
- user: this.user,
1781
- starkSigner: this.starkSigner,
1782
- transfersApi: this.transfersApi,
1783
- passportConfig: this.passportConfig,
2232
+ deposit(tokenAmount) {
2233
+ return deposit({
2234
+ signers: this.signers,
2235
+ deposit: tokenAmount,
2236
+ config: this.config,
1784
2237
  });
1785
2238
  }
1786
2239
  exchangeTransfer(request) {
1787
2240
  return exchangeTransfer({
2241
+ signers: this.signers,
1788
2242
  request,
1789
- user: this.user,
1790
- starkSigner: this.starkSigner,
1791
- exchangesApi: this.exchangesApi,
2243
+ config: this.config,
1792
2244
  });
1793
2245
  }
1794
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
1795
- deposit(deposit) {
1796
- throw new PassportError('Operation not supported', PassportErrorType.OPERATION_NOT_SUPPORTED_ERROR);
2246
+ async isRegisteredOnchain() {
2247
+ const starkPublicKey = await this.signers.starkSigner.getAddress();
2248
+ return isRegisteredOnChain(starkPublicKey, this.signers.ethSigner, this.config);
1797
2249
  }
1798
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
1799
2250
  prepareWithdrawal(request) {
1800
- throw new PassportError('Operation not supported', PassportErrorType.OPERATION_NOT_SUPPORTED_ERROR);
1801
- }
1802
- completeWithdrawal(
1803
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
1804
- starkPublicKey,
1805
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
1806
- token) {
1807
- throw new PassportError('Operation not supported', PassportErrorType.OPERATION_NOT_SUPPORTED_ERROR);
2251
+ return prepareWithdrawal({
2252
+ signers: this.signers,
2253
+ withdrawal: request,
2254
+ config: this.config,
2255
+ });
1808
2256
  }
1809
- getAddress() {
1810
- return Promise.resolve(this.starkSigner.getAddress());
2257
+ transfer(request) {
2258
+ return transfer({
2259
+ signers: this.signers,
2260
+ request,
2261
+ config: this.config,
2262
+ });
1811
2263
  }
1812
2264
  }
1813
2265
 
1814
- var Networks;
1815
- (function (Networks) {
1816
- Networks["PRODUCTION"] = "mainnet";
1817
- Networks["SANDBOX"] = "goerli";
1818
- })(Networks || (Networks = {}));
2266
+ const WALLET_ACTION = {
2267
+ SWITCH_CHAIN: 'wallet_switchEthereumChain',
2268
+ CONNECT: 'eth_requestAccounts',
2269
+ };
2270
+ function isRequestableProvider(provider) {
2271
+ return !!provider?.request;
2272
+ }
2273
+ async function connectProvider(provider, chainID) {
2274
+ await provider.request({ method: WALLET_ACTION.CONNECT });
2275
+ if (chainID) {
2276
+ await provider.request({
2277
+ method: WALLET_ACTION.SWITCH_CHAIN,
2278
+ params: [{ chainId: `0x${chainID.toString(16)}` }],
2279
+ });
2280
+ }
2281
+ }
1819
2282
 
1820
- const Config = {
1821
- PRODUCTION: {
1822
- network: Networks.PRODUCTION,
1823
- authenticationDomain: 'https://auth.immutable.com',
1824
- magicPublishableApiKey: 'pk_live_10F423798A540ED7',
1825
- magicProviderId: 'fSMzaRQ4O7p4fttl7pCyGVtJS_G70P8SNsLXtPPGHo0=',
1826
- baseIMXApiPath: 'https://api.x.immutable.com',
1827
- passportDomain: 'https://passport.immutable.com',
1828
- },
1829
- SANDBOX: {
1830
- network: Networks.SANDBOX,
1831
- authenticationDomain: 'https://auth.immutable.com',
1832
- magicPublishableApiKey: 'pk_live_10F423798A540ED7',
1833
- magicProviderId: 'fSMzaRQ4O7p4fttl7pCyGVtJS_G70P8SNsLXtPPGHo0=',
1834
- baseIMXApiPath: 'https://api.sandbox.x.immutable.com',
1835
- passportDomain: 'https://passport.sandbox.immutable.com',
1836
- },
2283
+ const ERRORS = {
2284
+ PROVIDER_NOT_FOUND: 'The Metamask provider was not found',
1837
2285
  };
1838
- const validateConfiguration = (configurationName, configuration, requiredKeys) => {
1839
- if (!configuration) {
1840
- throw new PassportError(`${configurationName} cannot be null`, PassportErrorType.INVALID_CONFIGURATION);
2286
+ async function connect$1({ chainID, }) {
2287
+ const provider = (await detectEthereumProvider());
2288
+ if (!isRequestableProvider(provider)) {
2289
+ throw new Error(ERRORS.PROVIDER_NOT_FOUND);
1841
2290
  }
1842
- const missingKeys = requiredKeys
1843
- .map((key) => !configuration[key] && key)
1844
- .filter((n) => n)
1845
- .join(', ');
1846
- if (missingKeys !== '') {
1847
- throw new PassportError(`${configurationName} - ${missingKeys} cannot be null`, PassportErrorType.INVALID_CONFIGURATION);
2291
+ await connectProvider(provider, chainID);
2292
+ // NOTE: if we want to listen to Metamask events in the future, we can add a
2293
+ // listener here.
2294
+ return new ethers.providers.Web3Provider(provider);
2295
+ }
2296
+
2297
+ const COMMUNICATION_TYPE = 'message';
2298
+ var RequestEventType;
2299
+ (function (RequestEventType) {
2300
+ RequestEventType["GET_CONNECTION_REQUEST"] = "GET_CONNECTION_REQUEST";
2301
+ RequestEventType["CONNECT_WALLET_REQUEST"] = "CONNECT_WALLET_REQUEST";
2302
+ RequestEventType["SIGN_MESSAGE_REQUEST"] = "SIGN_MESSAGE_REQUEST";
2303
+ RequestEventType["DISCONNECT_WALLET_REQUEST"] = "DISCONNECT_WALLET_REQUEST";
2304
+ })(RequestEventType || (RequestEventType = {}));
2305
+ var ResponseEventType;
2306
+ (function (ResponseEventType) {
2307
+ ResponseEventType["CONNECT_WALLET_RESPONSE"] = "CONNECT_WALLET_RESPONSE";
2308
+ ResponseEventType["SIGN_MESSAGE_RESPONSE"] = "SIGN_MESSAGE_RESPONSE";
2309
+ ResponseEventType["GET_CONNECTION_RESPONSE"] = "GET_CONNECTION_RESPONSE";
2310
+ ResponseEventType["DISCONNECT_WALLET_RESPONSE"] = "DISCONNECT_WALLET_RESPONSE";
2311
+ })(ResponseEventType || (ResponseEventType = {}));
2312
+
2313
+ function postRequestMessage(iframe, payload) {
2314
+ if (iframe && iframe.contentWindow) {
2315
+ iframe.contentWindow.postMessage(payload, new URL(iframe.src).origin);
1848
2316
  }
1849
- };
1850
- const getPassportConfiguration = (environmentConfiguration, oidcConfiguration) => {
1851
- validateConfiguration('EnvironmentConfiguration', environmentConfiguration, [
1852
- 'network',
1853
- 'authenticationDomain',
1854
- 'magicPublishableApiKey',
1855
- 'magicProviderId',
1856
- 'passportDomain',
1857
- ]);
1858
- validateConfiguration('OidcConfiguration', oidcConfiguration, [
1859
- 'clientId',
1860
- 'logoutRedirectUri',
1861
- 'redirectUri',
1862
- ]);
1863
- return {
1864
- network: environmentConfiguration.network,
1865
- oidcConfiguration: {
1866
- authenticationDomain: environmentConfiguration.authenticationDomain,
1867
- clientId: oidcConfiguration.clientId,
1868
- logoutRedirectUri: oidcConfiguration.logoutRedirectUri,
1869
- redirectUri: oidcConfiguration.redirectUri,
1870
- scope: oidcConfiguration.scope,
1871
- audience: oidcConfiguration.audience,
1872
- },
1873
- imxAPIConfiguration: {
1874
- basePath: environmentConfiguration.baseIMXApiPath,
1875
- },
1876
- passportDomain: environmentConfiguration.passportDomain,
1877
- magicPublishableApiKey: environmentConfiguration.magicPublishableApiKey,
1878
- magicProviderId: environmentConfiguration.magicProviderId,
1879
- };
1880
- };
2317
+ }
1881
2318
 
1882
- const getStarkSigner = async (signer) => {
1883
- return withPassportError(async () => {
1884
- const privateKey = await generateLegacyStarkPrivateKey(signer);
1885
- return createStarkSigner(privateKey);
1886
- }, PassportErrorType.WALLET_CONNECTION_ERROR);
2319
+ function messageResponseListener(iframe, event, eventType, callback) {
2320
+ if (iframe && event.source !== iframe.contentWindow) {
2321
+ return;
2322
+ }
2323
+ const l2WalletMessage = event.data;
2324
+ if (l2WalletMessage.type !== eventType) {
2325
+ return;
2326
+ }
2327
+ callback(l2WalletMessage.details);
2328
+ }
2329
+
2330
+ class ImxSigner {
2331
+ publicAddress;
2332
+ iframe;
2333
+ constructor(publicAddress, iframe) {
2334
+ this.publicAddress = publicAddress;
2335
+ this.iframe = iframe;
2336
+ }
2337
+ getAddress() {
2338
+ return this.publicAddress;
2339
+ }
2340
+ signMessage(rawMessage) {
2341
+ return new Promise((resolve, reject) => {
2342
+ const listener = (event) => {
2343
+ messageResponseListener(this.iframe, event, ResponseEventType.SIGN_MESSAGE_RESPONSE, (messageDetails) => {
2344
+ window.removeEventListener(COMMUNICATION_TYPE, listener);
2345
+ if (!messageDetails.success) {
2346
+ reject(new Error(messageDetails.error?.message));
2347
+ }
2348
+ resolve(messageDetails.data.signedMessage);
2349
+ });
2350
+ };
2351
+ window.addEventListener(COMMUNICATION_TYPE, listener);
2352
+ postRequestMessage(this.iframe, {
2353
+ type: RequestEventType.SIGN_MESSAGE_REQUEST,
2354
+ details: { starkPublicKey: this.publicAddress, message: rawMessage },
2355
+ });
2356
+ });
2357
+ }
2358
+ getIFrame() {
2359
+ return this.iframe;
2360
+ }
2361
+ }
2362
+
2363
+ const IMX_WALLET_IFRAME_ID = 'imx-wallet-app';
2364
+ const IMX_WALLET_IFRAME_HOSTS = {
2365
+ [Environment.SANDBOX]: 'https://wallets.sandbox.immutable.com',
2366
+ [Environment.PRODUCTION]: 'https://wallets.immutable.com',
1887
2367
  };
2368
+ const IMX_WALLET_IFRAME_STYLE = 'display: none;';
2369
+ function getIFrame() {
2370
+ return document.querySelector(`iframe#${IMX_WALLET_IFRAME_ID}`);
2371
+ }
2372
+ async function setupIFrame(env) {
2373
+ return new Promise((resolve) => {
2374
+ const iframe = document.createElement('iframe');
2375
+ iframe.setAttribute('id', IMX_WALLET_IFRAME_ID);
2376
+ iframe.setAttribute('src', IMX_WALLET_IFRAME_HOSTS[env]);
2377
+ iframe.setAttribute('style', IMX_WALLET_IFRAME_STYLE);
2378
+ document.body.appendChild(iframe);
2379
+ iframe.onload = () => resolve(iframe);
2380
+ });
2381
+ }
2382
+ async function getOrSetupIFrame(env) {
2383
+ const iframe = getIFrame();
2384
+ if (iframe)
2385
+ return iframe;
2386
+ return await setupIFrame(env);
2387
+ }
1888
2388
 
1889
- async function registerPassport({ ethSigner, starkSigner, usersApi }, authorization) {
1890
- return withPassportError(async () => {
1891
- const userAddress = await ethSigner.getAddress();
1892
- const starkPublicKey = await starkSigner.getAddress();
1893
- const signableResult = await usersApi.getSignableRegistrationOffchain({
1894
- getSignableRegistrationRequest: {
1895
- ether_key: userAddress,
1896
- stark_key: starkPublicKey,
1897
- },
2389
+ const DEFAULT_CONNECTION_MESSAGE = 'Only sign this request if you’ve initiated an action with Immutable X.';
2390
+ const CONNECTION_FAILED_ERROR = 'The L2 IMX Wallet connection has failed';
2391
+ async function connect(l1Provider, env) {
2392
+ const l1Signer = l1Provider.getSigner();
2393
+ const address = await l1Signer.getAddress();
2394
+ const signature = await l1Signer.signMessage(DEFAULT_CONNECTION_MESSAGE);
2395
+ const iframe = await getOrSetupIFrame(env);
2396
+ return new Promise((resolve, reject) => {
2397
+ const listener = (event) => {
2398
+ messageResponseListener(iframe, event, ResponseEventType.CONNECT_WALLET_RESPONSE, (messageDetails) => {
2399
+ window.removeEventListener(COMMUNICATION_TYPE, listener);
2400
+ if (!messageDetails.success) {
2401
+ reject(new Error(CONNECTION_FAILED_ERROR));
2402
+ }
2403
+ resolve(new ImxSigner(messageDetails.data.starkPublicKey, iframe));
2404
+ });
2405
+ };
2406
+ window.addEventListener(COMMUNICATION_TYPE, listener);
2407
+ postRequestMessage(iframe, {
2408
+ type: RequestEventType.CONNECT_WALLET_REQUEST,
2409
+ details: { ethAddress: address, signature },
1898
2410
  });
1899
- const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
1900
- const ethSignature = await signRaw(signableMessage, ethSigner);
1901
- const starkSignature = await starkSigner.signMessage(payloadHash);
1902
- const response = await usersApi.registerPassportUser({
1903
- authorization: `Bearer ` + authorization,
1904
- registerPassportUserRequest: {
1905
- eth_signature: ethSignature,
1906
- ether_key: userAddress,
1907
- stark_signature: starkSignature,
1908
- stark_key: starkPublicKey,
1909
- },
2411
+ });
2412
+ }
2413
+ async function disconnect(imxSigner) {
2414
+ const iframe = imxSigner.getIFrame();
2415
+ return new Promise((resolve, reject) => {
2416
+ const listener = (event) => {
2417
+ messageResponseListener(iframe, event, ResponseEventType.DISCONNECT_WALLET_RESPONSE, (messageDetails) => {
2418
+ window.removeEventListener(COMMUNICATION_TYPE, listener);
2419
+ if (!messageDetails.success && messageDetails.error) {
2420
+ reject(messageDetails.error);
2421
+ }
2422
+ iframe.remove();
2423
+ resolve();
2424
+ });
2425
+ };
2426
+ window.addEventListener(COMMUNICATION_TYPE, listener);
2427
+ postRequestMessage(iframe, {
2428
+ type: RequestEventType.DISCONNECT_WALLET_REQUEST,
2429
+ details: { starkPublicKey: imxSigner.getAddress() },
1910
2430
  });
1911
- return response.statusText;
1912
- }, PassportErrorType.USER_REGISTRATION_ERROR);
2431
+ });
1913
2432
  }
1914
2433
 
1915
- class Passport {
1916
- authManager;
1917
- magicAdapter;
1918
- config;
1919
- constructor(environmentConfiguration, oidcConfiguration) {
1920
- const passportConfiguration = getPassportConfiguration(environmentConfiguration, oidcConfiguration);
1921
- this.config = passportConfiguration;
1922
- this.authManager = new AuthManager(this.config);
1923
- this.magicAdapter = new MagicAdapter(this.config);
2434
+ var ProviderErrorType;
2435
+ (function (ProviderErrorType) {
2436
+ ProviderErrorType["PROVIDER_CONNECTION_ERROR"] = "PROVIDER_CONNECTION_ERROR";
2437
+ ProviderErrorType["WALLET_CONNECTION_ERROR"] = "WALLET_CONNECTION_ERROR";
2438
+ })(ProviderErrorType || (ProviderErrorType = {}));
2439
+ class ProviderError extends Error {
2440
+ type;
2441
+ constructor(message, type) {
2442
+ super(message);
2443
+ this.type = type;
1924
2444
  }
1925
- async connectImx() {
1926
- const user = await this.authManager.login();
1927
- if (!user.idToken) {
1928
- throw new PassportError('Failed to initialise', PassportErrorType.WALLET_CONNECTION_ERROR);
1929
- }
1930
- const provider = await this.magicAdapter.login(user.idToken);
1931
- const ethSigner = provider.getSigner();
1932
- const starkSigner = await getStarkSigner(ethSigner);
1933
- if (!user.etherKey) {
1934
- const updatedUser = await this.registerUser(ethSigner, starkSigner, user.accessToken);
1935
- return new PassportImxProvider({
1936
- user: updatedUser,
1937
- starkSigner,
1938
- passportConfig: this.config,
1939
- });
1940
- }
1941
- const userWithEtherKey = user;
1942
- return new PassportImxProvider({
1943
- user: userWithEtherKey,
1944
- starkSigner,
1945
- passportConfig: this.config,
1946
- });
2445
+ }
2446
+ const withProviderError = async (fn, customError) => {
2447
+ try {
2448
+ return await fn();
1947
2449
  }
1948
- async loginCallback() {
1949
- return this.authManager.loginCallback();
2450
+ catch (error) {
2451
+ const errorMessage = customError.message || `${error.message}` || 'UnknownError';
2452
+ throw new ProviderError(errorMessage, customError.type);
1950
2453
  }
1951
- async logout() {
1952
- return this.authManager.logout();
2454
+ };
2455
+
2456
+ class MetaMaskIMXProvider extends GenericIMXProvider {
2457
+ static imxSigner;
2458
+ constructor(config, ethSigner, starkSigner) {
2459
+ super(config, ethSigner, starkSigner);
1953
2460
  }
1954
- async getUserInfo() {
1955
- const user = await this.authManager.getUser();
1956
- return user.profile;
2461
+ static async connect(config) {
2462
+ return await withProviderError(async () => {
2463
+ const metaMaskProvider = await connect$1({
2464
+ chainID: config.immutableXConfig.ethConfiguration.chainID,
2465
+ });
2466
+ this.imxSigner = await connect(metaMaskProvider, config.baseConfig.environment);
2467
+ return new MetaMaskIMXProvider(config, metaMaskProvider.getSigner(), this.imxSigner);
2468
+ }, { type: ProviderErrorType.WALLET_CONNECTION_ERROR });
1957
2469
  }
1958
- async getIdToken() {
1959
- const user = await this.authManager.getUser();
1960
- return user.idToken;
2470
+ static async disconnect() {
2471
+ if (!this.imxSigner) {
2472
+ throw new ProviderError('Attempted to disconnect from the MetaMask IMX provider without an established connection', ProviderErrorType.PROVIDER_CONNECTION_ERROR);
2473
+ }
2474
+ return withProviderError(async () => {
2475
+ await disconnect(this.imxSigner);
2476
+ }, { type: ProviderErrorType.PROVIDER_CONNECTION_ERROR });
1961
2477
  }
1962
- async getAccessToken() {
1963
- const user = await this.authManager.getUser();
1964
- return user.accessToken;
2478
+ static async signMessage(message) {
2479
+ if (!this.imxSigner) {
2480
+ throw new ProviderError('Attempted to sign a message with the MetaMask IMX provider without an established connection', ProviderErrorType.PROVIDER_CONNECTION_ERROR);
2481
+ }
2482
+ return withProviderError(async () => {
2483
+ return await this.imxSigner.signMessage(message);
2484
+ }, { type: ProviderErrorType.PROVIDER_CONNECTION_ERROR });
1965
2485
  }
1966
- async registerUser(userAdminKeySigner, starkSigner, jwt) {
1967
- const configuration = new Configuration$1({
1968
- basePath: this.config.imxAPIConfiguration.basePath,
1969
- });
1970
- const usersApi = new UsersApi(configuration);
1971
- await registerPassport({
1972
- ethSigner: userAdminKeySigner,
1973
- starkSigner,
1974
- usersApi,
1975
- }, jwt);
1976
- const updatedUser = await this.authManager.requestRefreshTokenAfterRegistration();
1977
- if (!updatedUser) {
1978
- throw new PassportError('Failed to get refresh token', PassportErrorType.REFRESH_TOKEN_ERROR);
2486
+ }
2487
+
2488
+ class ProviderConfiguration {
2489
+ immutableXConfig;
2490
+ baseConfig;
2491
+ constructor({ baseConfig, overrides }) {
2492
+ this.baseConfig = baseConfig;
2493
+ if (overrides) {
2494
+ this.immutableXConfig = overrides.immutableXConfig;
2495
+ }
2496
+ else {
2497
+ switch (baseConfig.environment) {
2498
+ case Environment.SANDBOX: {
2499
+ this.immutableXConfig = Config.SANDBOX;
2500
+ break;
2501
+ }
2502
+ case Environment.PRODUCTION: {
2503
+ this.immutableXConfig = Config.PRODUCTION;
2504
+ break;
2505
+ }
2506
+ }
1979
2507
  }
1980
- return updatedUser;
1981
2508
  }
1982
2509
  }
1983
2510
 
2511
+ function $parcel$interopDefault(a) {
2512
+ return a && a.__esModule ? a.default : a;
2513
+ }
2514
+
1984
2515
  const $762782b6c862d954$export$db5daa1b5156ccfe = [
1985
2516
  {
1986
2517
  constant: true,
@@ -2101,8 +2632,18 @@ const $a47e48dd2c04791b$export$f61f4aaec62f6be9 = {
2101
2632
  ]
2102
2633
  }
2103
2634
  };
2635
+ let $a47e48dd2c04791b$export$1f05a55fe0680cc7;
2636
+ (function(NetworkFilterTypes) {
2637
+ NetworkFilterTypes["ALL"] = "all";
2638
+ })($a47e48dd2c04791b$export$1f05a55fe0680cc7 || ($a47e48dd2c04791b$export$1f05a55fe0680cc7 = {}));
2104
2639
 
2105
2640
 
2641
+ let $08d5ddc39acd6833$export$fd9b17d87f4121d2;
2642
+ (function(TokenFilterTypes) {
2643
+ TokenFilterTypes["SWAP"] = "swap";
2644
+ TokenFilterTypes["BRIDGE"] = "bridge";
2645
+ TokenFilterTypes["ALL"] = "all";
2646
+ })($08d5ddc39acd6833$export$fd9b17d87f4121d2 || ($08d5ddc39acd6833$export$fd9b17d87f4121d2 = {}));
2106
2647
 
2107
2648
 
2108
2649
 
@@ -2113,70 +2654,177 @@ const $4f91c5f280efe242$export$a130407f3423b97d = {
2113
2654
  ADD_NETWORK: "wallet_addEthereumChain",
2114
2655
  SWITCH_NETWORK: "wallet_switchEthereumChain"
2115
2656
  };
2657
+ let $4f91c5f280efe242$export$a75605c67ea83a5a;
2658
+ (function(WalletFilterTypes) {
2659
+ WalletFilterTypes["ALL"] = "all";
2660
+ WalletFilterTypes["DESKTOP"] = "desktop";
2661
+ WalletFilterTypes["MOBILE"] = "mobile";
2662
+ })($4f91c5f280efe242$export$a75605c67ea83a5a || ($4f91c5f280efe242$export$a75605c67ea83a5a = {}));
2116
2663
 
2117
2664
 
2118
2665
 
2119
2666
 
2120
- let $a8bc256d81a5e2c1$export$e3dc0620abde7f5a;
2667
+ /**
2668
+ * The different types of errors that can be returned by the checkout process.
2669
+ */ let $a8bc256d81a5e2c1$export$e3dc0620abde7f5a;
2121
2670
  (function(CheckoutErrorType) {
2671
+ CheckoutErrorType["PROVIDER_PREFERENCE_ERROR"] = "PROVIDER_PREFERENCE_ERROR";
2122
2672
  CheckoutErrorType["CONNECT_PROVIDER_ERROR"] = "CONNECT_PROVIDER_ERROR";
2123
2673
  CheckoutErrorType["GET_BALANCE_ERROR"] = "GET_BALANCE_ERROR";
2124
2674
  CheckoutErrorType["GET_ERC20_BALANCE_ERROR"] = "GET_ERC20_BALANCE_ERROR";
2675
+ CheckoutErrorType["GET_NETWORK_INFO_ERROR"] = "GET_NETWORK_INFO_ERROR";
2125
2676
  CheckoutErrorType["METAMASK_PROVIDER_ERROR"] = "METAMASK_PROVIDER_ERROR";
2126
2677
  CheckoutErrorType["CHAIN_NOT_SUPPORTED_ERROR"] = "CHAIN_NOT_SUPPORTED_ERROR";
2127
2678
  CheckoutErrorType["PROVIDER_REQUEST_MISSING_ERROR"] = "PROVIDER_REQUEST_MISSING_ERROR";
2679
+ CheckoutErrorType["PROVIDER_REQUEST_FAILED_ERROR"] = "PROVIDER_REQUEST_FAILED_ERROR";
2128
2680
  CheckoutErrorType["USER_REJECTED_REQUEST_ERROR"] = "USER_REJECTED_REQUEST_ERROR";
2129
2681
  CheckoutErrorType["TRANSACTION_ERROR"] = "TRANSACTION_ERROR";
2130
2682
  })($a8bc256d81a5e2c1$export$e3dc0620abde7f5a || ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a = {}));
2131
2683
  class $a8bc256d81a5e2c1$export$b722478a3cbfa3bc extends Error {
2132
- constructor(message, type){
2684
+ constructor(message, type, data){
2133
2685
  super(message);
2686
+ this.message = message;
2134
2687
  this.type = type;
2688
+ this.data = data;
2135
2689
  }
2136
2690
  }
2691
+ let $a8bc256d81a5e2c1$export$a22d4e0719ee6def;
2692
+ (function(CheckoutInternalErrorType) {
2693
+ CheckoutInternalErrorType["REJECTED_SWITCH_AFTER_ADDING_NETWORK"] = "REJECTED_SWITCH_AFTER_ADDING_NETWORK";
2694
+ })($a8bc256d81a5e2c1$export$a22d4e0719ee6def || ($a8bc256d81a5e2c1$export$a22d4e0719ee6def = {}));
2137
2695
  const $a8bc256d81a5e2c1$export$bacc563de539c6c3 = async (fn, customError)=>{
2138
2696
  try {
2139
2697
  return await fn();
2140
2698
  } catch (error) {
2141
- const errorMessage = customError.message || `${error.message}` || "UnknownError";
2142
- throw new $a8bc256d81a5e2c1$export$b722478a3cbfa3bc(errorMessage, customError.type);
2699
+ const cause = `${error.message}` || "UnknownError";
2700
+ const errorMessage = customError.message ? `[${customError.type}]:${customError.message}. Cause:${cause}` : `[${customError.type}] Cause:${cause}`;
2701
+ if (error instanceof $a8bc256d81a5e2c1$export$b722478a3cbfa3bc) throw new $a8bc256d81a5e2c1$export$b722478a3cbfa3bc(errorMessage, customError.type, {
2702
+ ...customError.data,
2703
+ innerErrorType: error.type,
2704
+ ...error.data
2705
+ });
2706
+ throw new $a8bc256d81a5e2c1$export$b722478a3cbfa3bc(errorMessage, customError.type, {
2707
+ ...customError.data
2708
+ });
2143
2709
  }
2144
2710
  };
2145
2711
 
2146
2712
 
2147
2713
 
2148
2714
 
2715
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2149
2716
 
2717
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2150
2718
 
2151
2719
 
2152
- async function $de192de6ef100f9f$export$79f13b4cfaaf0d09(provider) {
2153
- const network = await provider.getNetwork();
2154
- if (!Object.values(($a47e48dd2c04791b$export$c06e1e7429de6283)).includes(network.chainId)) // return empty details
2155
- return {};
2156
- const chainIdNetworkInfo = ($a47e48dd2c04791b$export$f61f4aaec62f6be9)[network.chainId];
2157
- const networkInfo = {
2158
- name: chainIdNetworkInfo.chainName,
2159
- chainId: parseInt(chainIdNetworkInfo.chainIdHex, 16),
2160
- nativeCurrency: chainIdNetworkInfo.nativeCurrency
2720
+
2721
+ async function $c99672cf2294e839$export$2d040992269b4717(providerPreference) {
2722
+ const provider = await $c99672cf2294e839$var$getWalletProviderForPreference(providerPreference);
2723
+ if (!provider.provider?.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Incompatible provider", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).PROVIDER_REQUEST_MISSING_ERROR, {
2724
+ details: `Unsupported provider for ${providerPreference}`
2725
+ });
2726
+ let accounts = [];
2727
+ try {
2728
+ accounts = await provider.provider.request({
2729
+ method: (0, $4f91c5f280efe242$export$a130407f3423b97d).CHECK_CONNECTION,
2730
+ params: []
2731
+ });
2732
+ } catch (err) {
2733
+ throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)(`Check wallet connection request failed`, ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).PROVIDER_REQUEST_FAILED_ERROR, {
2734
+ rpcMethod: ($4f91c5f280efe242$export$a130407f3423b97d).CHECK_CONNECTION
2735
+ });
2736
+ }
2737
+ // accounts[0] will have the active account if connected.
2738
+ return {
2739
+ isConnected: accounts && accounts.length > 0,
2740
+ walletAddress: accounts[0] ?? ""
2161
2741
  };
2162
- return networkInfo;
2163
2742
  }
2164
- async function $de192de6ef100f9f$export$b827d9418aeb5dbd(provider, chainId) {
2165
- if (!Object.values(($a47e48dd2c04791b$export$c06e1e7429de6283)).includes(chainId)) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)(`${chainId} is not a supported chain`, ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).CHAIN_NOT_SUPPORTED_ERROR);
2166
- if (!provider.provider?.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("provider object is missing request function", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).PROVIDER_REQUEST_MISSING_ERROR);
2743
+ async function $c99672cf2294e839$export$fba2f6c3656e07c1(params) {
2744
+ const web3Provider = await $c99672cf2294e839$var$getWalletProviderForPreference(params.providerPreference);
2745
+ await ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
2746
+ if (!web3Provider || !web3Provider?.provider?.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Incompatible provider", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).PROVIDER_REQUEST_MISSING_ERROR, {
2747
+ details: `Unsupported provider for ${params.providerPreference}`
2748
+ });
2749
+ // this makes the request to the wallet to connect i.e request eth accounts ('eth_requestAccounts')
2750
+ await web3Provider.provider.request({
2751
+ method: ($4f91c5f280efe242$export$a130407f3423b97d).CONNECT,
2752
+ params: []
2753
+ });
2754
+ }, {
2755
+ type: ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).USER_REJECTED_REQUEST_ERROR
2756
+ });
2757
+ return web3Provider;
2758
+ }
2759
+ async function $c99672cf2294e839$var$getWalletProviderForPreference(providerPreference) {
2760
+ let web3Provider = null;
2761
+ switch(providerPreference){
2762
+ case ($d176a05e966364ba$export$3bfad4d03ada24c4).METAMASK:
2763
+ web3Provider = await $c99672cf2294e839$var$getMetaMaskProvider();
2764
+ break;
2765
+ default:
2766
+ throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Provider preference is not supported", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).PROVIDER_PREFERENCE_ERROR);
2767
+ }
2768
+ return web3Provider;
2769
+ }
2770
+ async function $c99672cf2294e839$var$getMetaMaskProvider() {
2771
+ const provider = await ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
2772
+ return await (detectEthereumProvider)();
2773
+ }, {
2774
+ type: ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).METAMASK_PROVIDER_ERROR
2775
+ });
2776
+ if (!provider || !provider.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("No MetaMask provider installed.", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).METAMASK_PROVIDER_ERROR);
2777
+ return new (Web3Provider)(provider);
2778
+ }
2779
+
2780
+
2781
+ var $497c134ecbc8a50f$exports = {};
2782
+ $497c134ecbc8a50f$exports = JSON.parse('[{"chainId":1},{"chainId":5},{"chainId":137}]');
2783
+
2784
+
2785
+ const $de192de6ef100f9f$var$UNRECOGNISED_CHAIN_ERROR_CODE = 4902; // error code (MetaMask)
2786
+ async function $de192de6ef100f9f$export$79f13b4cfaaf0d09(provider) {
2787
+ return ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
2788
+ const network = await provider.getNetwork();
2789
+ if (!Object.values(($a47e48dd2c04791b$export$c06e1e7429de6283)).includes(network.chainId)) // return empty details
2790
+ return {
2791
+ chainId: network.chainId,
2792
+ name: network.name,
2793
+ isSupported: false
2794
+ };
2795
+ const chainIdNetworkInfo = ($a47e48dd2c04791b$export$f61f4aaec62f6be9)[network.chainId];
2796
+ return {
2797
+ name: chainIdNetworkInfo.chainName,
2798
+ chainId: parseInt(chainIdNetworkInfo.chainIdHex, 16),
2799
+ nativeCurrency: chainIdNetworkInfo.nativeCurrency,
2800
+ isSupported: true
2801
+ };
2802
+ }, {
2803
+ type: ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).GET_NETWORK_INFO_ERROR
2804
+ });
2805
+ }
2806
+ async function $de192de6ef100f9f$export$b827d9418aeb5dbd(providerPreference, provider, chainId) {
2807
+ let currentProvider = provider;
2808
+ if (!Object.values(($a47e48dd2c04791b$export$c06e1e7429de6283)).includes(chainId)) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)(`Chain:${chainId} is not a supported chain`, ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).CHAIN_NOT_SUPPORTED_ERROR);
2809
+ if (!currentProvider || !currentProvider.provider?.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Incompatible provider", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).PROVIDER_REQUEST_MISSING_ERROR, {
2810
+ details: `Unsupported provider`
2811
+ });
2167
2812
  // WT-1146 - Refer to the README in this folder for explantion on the switch network flow
2168
2813
  try {
2169
- await $de192de6ef100f9f$var$switchNetworkInWallet(provider, chainId);
2170
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2814
+ await $de192de6ef100f9f$var$switchNetworkInWallet(currentProvider, chainId);
2171
2815
  } catch (err) {
2172
- if (err.message.includes("Unrecognized chain ID")) try {
2173
- await $de192de6ef100f9f$var$addNetworkToWallet(provider, chainId);
2174
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2816
+ if (err.code === $de192de6ef100f9f$var$UNRECOGNISED_CHAIN_ERROR_CODE) try {
2817
+ await $de192de6ef100f9f$var$addNetworkToWallet(currentProvider, chainId);
2175
2818
  } catch (err) {
2176
- throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("user cancelled the add network request", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).USER_REJECTED_REQUEST_ERROR);
2819
+ throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("User cancelled add network request", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).USER_REJECTED_REQUEST_ERROR);
2177
2820
  }
2178
- else throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("user cancelled the switch network request", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).USER_REJECTED_REQUEST_ERROR);
2821
+ else throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("User cancelled switch network request", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).USER_REJECTED_REQUEST_ERROR);
2179
2822
  }
2823
+ currentProvider = await ($c99672cf2294e839$export$fba2f6c3656e07c1)({
2824
+ providerPreference: providerPreference
2825
+ });
2826
+ if ((await currentProvider.getNetwork()).chainId !== chainId) // user didn't actually switch
2827
+ throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("User cancelled switch network request", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).USER_REJECTED_REQUEST_ERROR);
2180
2828
  // we can assume that if the above succeeds then user has successfully
2181
2829
  // switched to the network specified
2182
2830
  const newNetwork = ($a47e48dd2c04791b$export$f61f4aaec62f6be9)[chainId];
@@ -2185,7 +2833,28 @@ async function $de192de6ef100f9f$export$b827d9418aeb5dbd(provider, chainId) {
2185
2833
  name: newNetwork.chainName,
2186
2834
  chainId: parseInt(newNetwork.chainIdHex, 16),
2187
2835
  nativeCurrency: newNetwork.nativeCurrency
2188
- }
2836
+ },
2837
+ provider: currentProvider
2838
+ };
2839
+ }
2840
+ async function $de192de6ef100f9f$export$3043f6442a9ef563({ type: type = ($a47e48dd2c04791b$export$1f05a55fe0680cc7).ALL , exclude: exclude }) {
2841
+ const list = ((/*@__PURE__*/$parcel$interopDefault($497c134ecbc8a50f$exports))).filter((network)=>{
2842
+ const allowAllTokens = type === ($a47e48dd2c04791b$export$1f05a55fe0680cc7).ALL;
2843
+ const networkNotExcluded = !(exclude || []).map((exc)=>exc.chainId).includes(network.chainId);
2844
+ return allowAllTokens && networkNotExcluded;
2845
+ });
2846
+ const allowedNetworks = [];
2847
+ list.forEach((element)=>{
2848
+ const newNetwork = ($a47e48dd2c04791b$export$f61f4aaec62f6be9)[element.chainId];
2849
+ allowedNetworks.push({
2850
+ name: newNetwork.chainName,
2851
+ chainId: parseInt(newNetwork.chainIdHex, 16),
2852
+ nativeCurrency: newNetwork.nativeCurrency,
2853
+ isSupported: true
2854
+ });
2855
+ });
2856
+ return {
2857
+ networks: allowedNetworks
2189
2858
  };
2190
2859
  }
2191
2860
  // these functions should not be exported. These functions should be used as part of an exported function e.g switchWalletNetwork() above.
@@ -2222,67 +2891,24 @@ async function $de192de6ef100f9f$var$addNetworkToWallet(provider, chainId) {
2222
2891
 
2223
2892
 
2224
2893
 
2225
- let $efe60cea83bfc4e8$export$f04a61298a47a40f;
2226
- (function(Icon) {
2227
- Icon["ETH"] = "data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='100%25' height='100%25' version='1.1' shape-rendering='geometricPrecision' text-rendering='geometricPrecision' image-rendering='optimizeQuality' fill-rule='evenodd' clip-rule='evenodd'%0AviewBox='0 0 784.37 1277.39' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xodm='http://www.corel.com/coreldraw/odm/2003'%3E%3Cg id='Layer_x0020_1'%3E%3Cmetadata id='CorelCorpID_0Corel-Layer'/%3E%3Cg id='_1421394342400'%3E%3Cg%3E%3Cpolygon fill='%23343434' fill-rule='nonzero' points='392.07,0 383.5,29.11 383.5,873.74 392.07,882.29 784.13,650.54 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,0 -0,650.54 392.07,882.29 392.07,472.33 '/%3E%3Cpolygon fill='%233C3C3B' fill-rule='nonzero' points='392.07,956.52 387.24,962.41 387.24,1263.28 392.07,1277.38 784.37,724.89 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,1277.38 392.07,956.52 -0,724.89 '/%3E%3Cpolygon fill='%23141414' fill-rule='nonzero' points='392.07,882.29 784.13,650.54 392.07,472.33 '/%3E%3Cpolygon fill='%23393939' fill-rule='nonzero' points='0,650.54 392.07,882.29 392.07,472.33 '/%3E%3C/g%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A";
2228
- Icon["MATIC"] = "data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3Csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 38.4 33.5' style='enable-background:new 0 0 38.4 33.5;' xml:space='preserve'%3E%3Cstyle type='text/css'%3E .st0%7Bfill:%238247E5;%7D%0A%3C/style%3E%3Cg%3E%3Cpath class='st0' d='M29,10.2c-0.7-0.4-1.6-0.4-2.4,0L21,13.5l-3.8,2.1l-5.5,3.3c-0.7,0.4-1.6,0.4-2.4,0L5,16.3 c-0.7-0.4-1.2-1.2-1.2-2.1v-5c0-0.8,0.4-1.6,1.2-2.1l4.3-2.5c0.7-0.4,1.6-0.4,2.4,0L16,7.2c0.7,0.4,1.2,1.2,1.2,2.1v3.3l3.8-2.2V7 c0-0.8-0.4-1.6-1.2-2.1l-8-4.7c-0.7-0.4-1.6-0.4-2.4,0L1.2,5C0.4,5.4,0,6.2,0,7v9.4c0,0.8,0.4,1.6,1.2,2.1l8.1,4.7 c0.7,0.4,1.6,0.4,2.4,0l5.5-3.2l3.8-2.2l5.5-3.2c0.7-0.4,1.6-0.4,2.4,0l4.3,2.5c0.7,0.4,1.2,1.2,1.2,2.1v5c0,0.8-0.4,1.6-1.2,2.1 L29,28.8c-0.7,0.4-1.6,0.4-2.4,0l-4.3-2.5c-0.7-0.4-1.2-1.2-1.2-2.1V21l-3.8,2.2v3.3c0,0.8,0.4,1.6,1.2,2.1l8.1,4.7 c0.7,0.4,1.6,0.4,2.4,0l8.1-4.7c0.7-0.4,1.2-1.2,1.2-2.1V17c0-0.8-0.4-1.6-1.2-2.1L29,10.2z'/%3E%3C/g%3E%3C/svg%3E%0A";
2229
- Icon["IMX"] = "data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3Csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 139 113' style='enable-background:new 0 0 139 113;' xml:space='preserve'%3E%3Cstyle type='text/css'%3E .st0%7Bclip-path:url(%23SVGID_00000053504646934646330740000009134454895836103350_);%7D .st1%7Bfill:%2317B5CB;%7D%0A%3C/style%3E%3Cg%3E%3Cdefs%3E%3Crect id='SVGID_1_' width='139' height='113'/%3E%3C/defs%3E%3CclipPath id='SVGID_00000035518931339590433170000002358037249938198420_'%3E%3Cuse xlink:href='%23SVGID_1_' style='overflow:visible;'/%3E%3C/clipPath%3E%3Cg style='clip-path:url(%23SVGID_00000035518931339590433170000002358037249938198420_);'%3E%3Cpath class='st1' d='M124.1,0h14.6L79.5,67.6c-1.5,1.7-1.6,4.3-0.1,6.1l34.1,39.7H98.3L66.8,76.6l-1.6-2c-1.5-1.7-1.4-4.4,0.1-6.1 L124.1,0z'/%3E%3Cpath class='st1' d='M91.2,73.7c-1-1.1-1.3-2.7-1-4.1c0.3-0.8,0.8-1.6,1.4-2.2l3.9-4.3l43.5,50.3h-13.8 C125.2,113.4,99.7,83.6,91.2,73.7z'/%3E%3Cpath class='st1' d='M15.2,113.4H0l46.6-53.9c1.5-1.7,1.5-4.3,0-6L0.4,0H15l46.5,53.9c1.2,1.6,1.4,3.9,0.1,5.4 C49.4,73.4,15.2,113.4,15.2,113.4z'/%3E%3Cpath class='st1' d='M40.6,0h-14l43.1,49.9c0,0,0.1-0.1,4.9-5.8c1.3-1.5,1.6-3.4,0.1-4.9C65.7,30,40.6,0,40.6,0z'/%3E%3Cpath class='st1' d='M82.6,34.8L112.5,0H98.3L82.7,18.2l-4.5,5.3c-1.5,1.7-1.6,4.3-0.1,6.1C79.2,30.9,82.6,34.8,82.6,34.8z'/%3E%3Cpath class='st1' d='M56.6,78.6l-29.9,34.8h14.1l15.6-18.2l4.5-5.3c1.5-1.7,1.6-4.3,0.1-6.1C59.9,82.5,56.6,78.6,56.6,78.6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A";
2230
- })($efe60cea83bfc4e8$export$f04a61298a47a40f || ($efe60cea83bfc4e8$export$f04a61298a47a40f = {}));
2231
- const $efe60cea83bfc4e8$export$3dbcce43073f40c7 = [
2232
- {
2233
- name: "Ethereum",
2234
- symbol: "ETH",
2235
- decimals: 18,
2236
- icon: "data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='100%25' height='100%25' version='1.1' shape-rendering='geometricPrecision' text-rendering='geometricPrecision' image-rendering='optimizeQuality' fill-rule='evenodd' clip-rule='evenodd'%0AviewBox='0 0 784.37 1277.39' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xodm='http://www.corel.com/coreldraw/odm/2003'%3E%3Cg id='Layer_x0020_1'%3E%3Cmetadata id='CorelCorpID_0Corel-Layer'/%3E%3Cg id='_1421394342400'%3E%3Cg%3E%3Cpolygon fill='%23343434' fill-rule='nonzero' points='392.07,0 383.5,29.11 383.5,873.74 392.07,882.29 784.13,650.54 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,0 -0,650.54 392.07,882.29 392.07,472.33 '/%3E%3Cpolygon fill='%233C3C3B' fill-rule='nonzero' points='392.07,956.52 387.24,962.41 387.24,1263.28 392.07,1277.38 784.37,724.89 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,1277.38 392.07,956.52 -0,724.89 '/%3E%3Cpolygon fill='%23141414' fill-rule='nonzero' points='392.07,882.29 784.13,650.54 392.07,472.33 '/%3E%3Cpolygon fill='%23393939' fill-rule='nonzero' points='0,650.54 392.07,882.29 392.07,472.33 '/%3E%3C/g%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A"
2237
- },
2238
- {
2239
- name: "Matic",
2240
- symbol: "MATIC",
2241
- address: "0x7D1AfA7B718fb893dB30A3aBc0Cfc608AaCfeBB0",
2242
- decimals: 18,
2243
- icon: "data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3Csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 38.4 33.5' style='enable-background:new 0 0 38.4 33.5;' xml:space='preserve'%3E%3Cstyle type='text/css'%3E .st0%7Bfill:%238247E5;%7D%0A%3C/style%3E%3Cg%3E%3Cpath class='st0' d='M29,10.2c-0.7-0.4-1.6-0.4-2.4,0L21,13.5l-3.8,2.1l-5.5,3.3c-0.7,0.4-1.6,0.4-2.4,0L5,16.3 c-0.7-0.4-1.2-1.2-1.2-2.1v-5c0-0.8,0.4-1.6,1.2-2.1l4.3-2.5c0.7-0.4,1.6-0.4,2.4,0L16,7.2c0.7,0.4,1.2,1.2,1.2,2.1v3.3l3.8-2.2V7 c0-0.8-0.4-1.6-1.2-2.1l-8-4.7c-0.7-0.4-1.6-0.4-2.4,0L1.2,5C0.4,5.4,0,6.2,0,7v9.4c0,0.8,0.4,1.6,1.2,2.1l8.1,4.7 c0.7,0.4,1.6,0.4,2.4,0l5.5-3.2l3.8-2.2l5.5-3.2c0.7-0.4,1.6-0.4,2.4,0l4.3,2.5c0.7,0.4,1.2,1.2,1.2,2.1v5c0,0.8-0.4,1.6-1.2,2.1 L29,28.8c-0.7,0.4-1.6,0.4-2.4,0l-4.3-2.5c-0.7-0.4-1.2-1.2-1.2-2.1V21l-3.8,2.2v3.3c0,0.8,0.4,1.6,1.2,2.1l8.1,4.7 c0.7,0.4,1.6,0.4,2.4,0l8.1-4.7c0.7-0.4,1.2-1.2,1.2-2.1V17c0-0.8-0.4-1.6-1.2-2.1L29,10.2z'/%3E%3C/g%3E%3C/svg%3E%0A"
2244
- },
2245
- {
2246
- name: "Immutable X",
2247
- symbol: "IMX",
2248
- address: "0xF57e7e7C23978C3cAEC3C3548E3D615c346e79fF",
2249
- decimals: 18,
2250
- icon: "data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3Csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 139 113' style='enable-background:new 0 0 139 113;' xml:space='preserve'%3E%3Cstyle type='text/css'%3E .st0%7Bclip-path:url(%23SVGID_00000053504646934646330740000009134454895836103350_);%7D .st1%7Bfill:%2317B5CB;%7D%0A%3C/style%3E%3Cg%3E%3Cdefs%3E%3Crect id='SVGID_1_' width='139' height='113'/%3E%3C/defs%3E%3CclipPath id='SVGID_00000035518931339590433170000002358037249938198420_'%3E%3Cuse xlink:href='%23SVGID_1_' style='overflow:visible;'/%3E%3C/clipPath%3E%3Cg style='clip-path:url(%23SVGID_00000035518931339590433170000002358037249938198420_);'%3E%3Cpath class='st1' d='M124.1,0h14.6L79.5,67.6c-1.5,1.7-1.6,4.3-0.1,6.1l34.1,39.7H98.3L66.8,76.6l-1.6-2c-1.5-1.7-1.4-4.4,0.1-6.1 L124.1,0z'/%3E%3Cpath class='st1' d='M91.2,73.7c-1-1.1-1.3-2.7-1-4.1c0.3-0.8,0.8-1.6,1.4-2.2l3.9-4.3l43.5,50.3h-13.8 C125.2,113.4,99.7,83.6,91.2,73.7z'/%3E%3Cpath class='st1' d='M15.2,113.4H0l46.6-53.9c1.5-1.7,1.5-4.3,0-6L0.4,0H15l46.5,53.9c1.2,1.6,1.4,3.9,0.1,5.4 C49.4,73.4,15.2,113.4,15.2,113.4z'/%3E%3Cpath class='st1' d='M40.6,0h-14l43.1,49.9c0,0,0.1-0.1,4.9-5.8c1.3-1.5,1.6-3.4,0.1-4.9C65.7,30,40.6,0,40.6,0z'/%3E%3Cpath class='st1' d='M82.6,34.8L112.5,0H98.3L82.7,18.2l-4.5,5.3c-1.5,1.7-1.6,4.3-0.1,6.1C79.2,30.9,82.6,34.8,82.6,34.8z'/%3E%3Cpath class='st1' d='M56.6,78.6l-29.9,34.8h14.1l15.6-18.2l4.5-5.3c1.5-1.7,1.6-4.3,0.1-6.1C59.9,82.5,56.6,78.6,56.6,78.6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A"
2251
- }
2252
- ];
2253
- const $efe60cea83bfc4e8$var$goerliTokensList = [
2254
- {
2255
- name: "Ethereum",
2256
- symbol: "ETH",
2257
- decimals: 18,
2258
- icon: "data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='100%25' height='100%25' version='1.1' shape-rendering='geometricPrecision' text-rendering='geometricPrecision' image-rendering='optimizeQuality' fill-rule='evenodd' clip-rule='evenodd'%0AviewBox='0 0 784.37 1277.39' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xodm='http://www.corel.com/coreldraw/odm/2003'%3E%3Cg id='Layer_x0020_1'%3E%3Cmetadata id='CorelCorpID_0Corel-Layer'/%3E%3Cg id='_1421394342400'%3E%3Cg%3E%3Cpolygon fill='%23343434' fill-rule='nonzero' points='392.07,0 383.5,29.11 383.5,873.74 392.07,882.29 784.13,650.54 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,0 -0,650.54 392.07,882.29 392.07,472.33 '/%3E%3Cpolygon fill='%233C3C3B' fill-rule='nonzero' points='392.07,956.52 387.24,962.41 387.24,1263.28 392.07,1277.38 784.37,724.89 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,1277.38 392.07,956.52 -0,724.89 '/%3E%3Cpolygon fill='%23141414' fill-rule='nonzero' points='392.07,882.29 784.13,650.54 392.07,472.33 '/%3E%3Cpolygon fill='%23393939' fill-rule='nonzero' points='0,650.54 392.07,882.29 392.07,472.33 '/%3E%3C/g%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A"
2259
- },
2260
- {
2261
- name: "Immutable X",
2262
- symbol: "IMX",
2263
- address: "0x1facdd0165489f373255a90304650e15481b2c85",
2264
- decimals: 18,
2265
- icon: "data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3Csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 139 113' style='enable-background:new 0 0 139 113;' xml:space='preserve'%3E%3Cstyle type='text/css'%3E .st0%7Bclip-path:url(%23SVGID_00000053504646934646330740000009134454895836103350_);%7D .st1%7Bfill:%2317B5CB;%7D%0A%3C/style%3E%3Cg%3E%3Cdefs%3E%3Crect id='SVGID_1_' width='139' height='113'/%3E%3C/defs%3E%3CclipPath id='SVGID_00000035518931339590433170000002358037249938198420_'%3E%3Cuse xlink:href='%23SVGID_1_' style='overflow:visible;'/%3E%3C/clipPath%3E%3Cg style='clip-path:url(%23SVGID_00000035518931339590433170000002358037249938198420_);'%3E%3Cpath class='st1' d='M124.1,0h14.6L79.5,67.6c-1.5,1.7-1.6,4.3-0.1,6.1l34.1,39.7H98.3L66.8,76.6l-1.6-2c-1.5-1.7-1.4-4.4,0.1-6.1 L124.1,0z'/%3E%3Cpath class='st1' d='M91.2,73.7c-1-1.1-1.3-2.7-1-4.1c0.3-0.8,0.8-1.6,1.4-2.2l3.9-4.3l43.5,50.3h-13.8 C125.2,113.4,99.7,83.6,91.2,73.7z'/%3E%3Cpath class='st1' d='M15.2,113.4H0l46.6-53.9c1.5-1.7,1.5-4.3,0-6L0.4,0H15l46.5,53.9c1.2,1.6,1.4,3.9,0.1,5.4 C49.4,73.4,15.2,113.4,15.2,113.4z'/%3E%3Cpath class='st1' d='M40.6,0h-14l43.1,49.9c0,0,0.1-0.1,4.9-5.8c1.3-1.5,1.6-3.4,0.1-4.9C65.7,30,40.6,0,40.6,0z'/%3E%3Cpath class='st1' d='M82.6,34.8L112.5,0H98.3L82.7,18.2l-4.5,5.3c-1.5,1.7-1.6,4.3-0.1,6.1C79.2,30.9,82.6,34.8,82.6,34.8z'/%3E%3Cpath class='st1' d='M56.6,78.6l-29.9,34.8h14.1l15.6-18.2l4.5-5.3c1.5-1.7,1.6-4.3,0.1-6.1C59.9,82.5,56.6,78.6,56.6,78.6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A"
2266
- }
2267
- ];
2268
- const $efe60cea83bfc4e8$var$polygonTokensList = [];
2269
- const $efe60cea83bfc4e8$export$473cec51305fdae8 = (chainId)=>{
2270
- let tokenList = [];
2271
- switch(chainId){
2272
- case ($a47e48dd2c04791b$export$c06e1e7429de6283).ETHEREUM:
2273
- tokenList = $efe60cea83bfc4e8$export$3dbcce43073f40c7;
2274
- break;
2275
- case ($a47e48dd2c04791b$export$c06e1e7429de6283).GOERLI:
2276
- tokenList = $efe60cea83bfc4e8$var$goerliTokensList;
2277
- break;
2278
- case ($a47e48dd2c04791b$export$c06e1e7429de6283).POLYGON:
2279
- tokenList = $efe60cea83bfc4e8$var$polygonTokensList;
2280
- break;
2281
- default:
2282
- tokenList = $efe60cea83bfc4e8$export$3dbcce43073f40c7;
2283
- }
2894
+ var $cda6003506e4182e$exports = {};
2895
+ $cda6003506e4182e$exports = JSON.parse("[{\"address\":\"0x7D1AfA7B718fb893dB30A3aBc0Cfc608AaCfeBB0\",\"chainId\":137,\"name\":\"Matic\",\"symbol\":\"MATIC\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3Csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 38.4 33.5' style='enable-background:new 0 0 38.4 33.5;' xml:space='preserve'%3E%3Cstyle type='text/css'%3E .st0%7Bfill:%238247E5;%7D%0A%3C/style%3E%3Cg%3E%3Cpath class='st0' d='M29,10.2c-0.7-0.4-1.6-0.4-2.4,0L21,13.5l-3.8,2.1l-5.5,3.3c-0.7,0.4-1.6,0.4-2.4,0L5,16.3 c-0.7-0.4-1.2-1.2-1.2-2.1v-5c0-0.8,0.4-1.6,1.2-2.1l4.3-2.5c0.7-0.4,1.6-0.4,2.4,0L16,7.2c0.7,0.4,1.2,1.2,1.2,2.1v3.3l3.8-2.2V7 c0-0.8-0.4-1.6-1.2-2.1l-8-4.7c-0.7-0.4-1.6-0.4-2.4,0L1.2,5C0.4,5.4,0,6.2,0,7v9.4c0,0.8,0.4,1.6,1.2,2.1l8.1,4.7 c0.7,0.4,1.6,0.4,2.4,0l5.5-3.2l3.8-2.2l5.5-3.2c0.7-0.4,1.6-0.4,2.4,0l4.3,2.5c0.7,0.4,1.2,1.2,1.2,2.1v5c0,0.8-0.4,1.6-1.2,2.1 L29,28.8c-0.7,0.4-1.6,0.4-2.4,0l-4.3-2.5c-0.7-0.4-1.2-1.2-1.2-2.1V21l-3.8,2.2v3.3c0,0.8,0.4,1.6,1.2,2.1l8.1,4.7 c0.7,0.4,1.6,0.4,2.4,0l8.1-4.7c0.7-0.4,1.2-1.2,1.2-2.1V17c0-0.8-0.4-1.6-1.2-2.1L29,10.2z'/%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"name\":\"Ethereum\",\"symbol\":\"ETH\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='100%25' height='100%25' version='1.1' shape-rendering='geometricPrecision' text-rendering='geometricPrecision' image-rendering='optimizeQuality' fill-rule='evenodd' clip-rule='evenodd'%0AviewBox='0 0 784.37 1277.39' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xodm='http://www.corel.com/coreldraw/odm/2003'%3E%3Cg id='Layer_x0020_1'%3E%3Cmetadata id='CorelCorpID_0Corel-Layer'/%3E%3Cg id='_1421394342400'%3E%3Cg%3E%3Cpolygon fill='%23343434' fill-rule='nonzero' points='392.07,0 383.5,29.11 383.5,873.74 392.07,882.29 784.13,650.54 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,0 -0,650.54 392.07,882.29 392.07,472.33 '/%3E%3Cpolygon fill='%233C3C3B' fill-rule='nonzero' points='392.07,956.52 387.24,962.41 387.24,1263.28 392.07,1277.38 784.37,724.89 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,1277.38 392.07,956.52 -0,724.89 '/%3E%3Cpolygon fill='%23141414' fill-rule='nonzero' points='392.07,882.29 784.13,650.54 392.07,472.33 '/%3E%3Cpolygon fill='%23393939' fill-rule='nonzero' points='0,650.54 392.07,882.29 392.07,472.33 '/%3E%3C/g%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"chainId\":1,\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"address\":\"0xF57e7e7C23978C3cAEC3C3548E3D615c346e79fF\",\"chainId\":1,\"name\":\"Immutable X\",\"symbol\":\"IMX\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3Csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 139 113' style='enable-background:new 0 0 139 113;' xml:space='preserve'%3E%3Cstyle type='text/css'%3E .st0%7Bclip-path:url(%23SVGID_00000053504646934646330740000009134454895836103350_);%7D .st1%7Bfill:%2317B5CB;%7D%0A%3C/style%3E%3Cg%3E%3Cdefs%3E%3Crect id='SVGID_1_' width='139' height='113'/%3E%3C/defs%3E%3CclipPath id='SVGID_00000035518931339590433170000002358037249938198420_'%3E%3Cuse xlink:href='%23SVGID_1_' style='overflow:visible;'/%3E%3C/clipPath%3E%3Cg style='clip-path:url(%23SVGID_00000035518931339590433170000002358037249938198420_);'%3E%3Cpath class='st1' d='M124.1,0h14.6L79.5,67.6c-1.5,1.7-1.6,4.3-0.1,6.1l34.1,39.7H98.3L66.8,76.6l-1.6-2c-1.5-1.7-1.4-4.4,0.1-6.1 L124.1,0z'/%3E%3Cpath class='st1' d='M91.2,73.7c-1-1.1-1.3-2.7-1-4.1c0.3-0.8,0.8-1.6,1.4-2.2l3.9-4.3l43.5,50.3h-13.8 C125.2,113.4,99.7,83.6,91.2,73.7z'/%3E%3Cpath class='st1' d='M15.2,113.4H0l46.6-53.9c1.5-1.7,1.5-4.3,0-6L0.4,0H15l46.5,53.9c1.2,1.6,1.4,3.9,0.1,5.4 C49.4,73.4,15.2,113.4,15.2,113.4z'/%3E%3Cpath class='st1' d='M40.6,0h-14l43.1,49.9c0,0,0.1-0.1,4.9-5.8c1.3-1.5,1.6-3.4,0.1-4.9C65.7,30,40.6,0,40.6,0z'/%3E%3Cpath class='st1' d='M82.6,34.8L112.5,0H98.3L82.7,18.2l-4.5,5.3c-1.5,1.7-1.6,4.3-0.1,6.1C79.2,30.9,82.6,34.8,82.6,34.8z'/%3E%3Cpath class='st1' d='M56.6,78.6l-29.9,34.8h14.1l15.6-18.2l4.5-5.3c1.5-1.7,1.6-4.3,0.1-6.1C59.9,82.5,56.6,78.6,56.6,78.6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"address\":\"0x7D1AfA7B718fb893dB30A3aBc0Cfc608AaCfeBB0\",\"chainId\":1,\"name\":\"Matic\",\"symbol\":\"MATIC\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3Csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 38.4 33.5' style='enable-background:new 0 0 38.4 33.5;' xml:space='preserve'%3E%3Cstyle type='text/css'%3E .st0%7Bfill:%238247E5;%7D%0A%3C/style%3E%3Cg%3E%3Cpath class='st0' d='M29,10.2c-0.7-0.4-1.6-0.4-2.4,0L21,13.5l-3.8,2.1l-5.5,3.3c-0.7,0.4-1.6,0.4-2.4,0L5,16.3 c-0.7-0.4-1.2-1.2-1.2-2.1v-5c0-0.8,0.4-1.6,1.2-2.1l4.3-2.5c0.7-0.4,1.6-0.4,2.4,0L16,7.2c0.7,0.4,1.2,1.2,1.2,2.1v3.3l3.8-2.2V7 c0-0.8-0.4-1.6-1.2-2.1l-8-4.7c-0.7-0.4-1.6-0.4-2.4,0L1.2,5C0.4,5.4,0,6.2,0,7v9.4c0,0.8,0.4,1.6,1.2,2.1l8.1,4.7 c0.7,0.4,1.6,0.4,2.4,0l5.5-3.2l3.8-2.2l5.5-3.2c0.7-0.4,1.6-0.4,2.4,0l4.3,2.5c0.7,0.4,1.2,1.2,1.2,2.1v5c0,0.8-0.4,1.6-1.2,2.1 L29,28.8c-0.7,0.4-1.6,0.4-2.4,0l-4.3-2.5c-0.7-0.4-1.2-1.2-1.2-2.1V21l-3.8,2.2v3.3c0,0.8,0.4,1.6,1.2,2.1l8.1,4.7 c0.7,0.4,1.6,0.4,2.4,0l8.1-4.7c0.7-0.4,1.2-1.2,1.2-2.1V17c0-0.8-0.4-1.6-1.2-2.1L29,10.2z'/%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"name\":\"Ethereum\",\"symbol\":\"ETH\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='100%25' height='100%25' version='1.1' shape-rendering='geometricPrecision' text-rendering='geometricPrecision' image-rendering='optimizeQuality' fill-rule='evenodd' clip-rule='evenodd'%0AviewBox='0 0 784.37 1277.39' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xodm='http://www.corel.com/coreldraw/odm/2003'%3E%3Cg id='Layer_x0020_1'%3E%3Cmetadata id='CorelCorpID_0Corel-Layer'/%3E%3Cg id='_1421394342400'%3E%3Cg%3E%3Cpolygon fill='%23343434' fill-rule='nonzero' points='392.07,0 383.5,29.11 383.5,873.74 392.07,882.29 784.13,650.54 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,0 -0,650.54 392.07,882.29 392.07,472.33 '/%3E%3Cpolygon fill='%233C3C3B' fill-rule='nonzero' points='392.07,956.52 387.24,962.41 387.24,1263.28 392.07,1277.38 784.37,724.89 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,1277.38 392.07,956.52 -0,724.89 '/%3E%3Cpolygon fill='%23141414' fill-rule='nonzero' points='392.07,882.29 784.13,650.54 392.07,472.33 '/%3E%3Cpolygon fill='%23393939' fill-rule='nonzero' points='0,650.54 392.07,882.29 392.07,472.33 '/%3E%3C/g%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"chainId\":5,\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"address\":\"0x1facdd0165489f373255a90304650e15481b2c85\",\"chainId\":5,\"name\":\"Immutable X\",\"symbol\":\"IMX\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3Csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 139 113' style='enable-background:new 0 0 139 113;' xml:space='preserve'%3E%3Cstyle type='text/css'%3E .st0%7Bclip-path:url(%23SVGID_00000053504646934646330740000009134454895836103350_);%7D .st1%7Bfill:%2317B5CB;%7D%0A%3C/style%3E%3Cg%3E%3Cdefs%3E%3Crect id='SVGID_1_' width='139' height='113'/%3E%3C/defs%3E%3CclipPath id='SVGID_00000035518931339590433170000002358037249938198420_'%3E%3Cuse xlink:href='%23SVGID_1_' style='overflow:visible;'/%3E%3C/clipPath%3E%3Cg style='clip-path:url(%23SVGID_00000035518931339590433170000002358037249938198420_);'%3E%3Cpath class='st1' d='M124.1,0h14.6L79.5,67.6c-1.5,1.7-1.6,4.3-0.1,6.1l34.1,39.7H98.3L66.8,76.6l-1.6-2c-1.5-1.7-1.4-4.4,0.1-6.1 L124.1,0z'/%3E%3Cpath class='st1' d='M91.2,73.7c-1-1.1-1.3-2.7-1-4.1c0.3-0.8,0.8-1.6,1.4-2.2l3.9-4.3l43.5,50.3h-13.8 C125.2,113.4,99.7,83.6,91.2,73.7z'/%3E%3Cpath class='st1' d='M15.2,113.4H0l46.6-53.9c1.5-1.7,1.5-4.3,0-6L0.4,0H15l46.5,53.9c1.2,1.6,1.4,3.9,0.1,5.4 C49.4,73.4,15.2,113.4,15.2,113.4z'/%3E%3Cpath class='st1' d='M40.6,0h-14l43.1,49.9c0,0,0.1-0.1,4.9-5.8c1.3-1.5,1.6-3.4,0.1-4.9C65.7,30,40.6,0,40.6,0z'/%3E%3Cpath class='st1' d='M82.6,34.8L112.5,0H98.3L82.7,18.2l-4.5,5.3c-1.5,1.7-1.6,4.3-0.1,6.1C79.2,30.9,82.6,34.8,82.6,34.8z'/%3E%3Cpath class='st1' d='M56.6,78.6l-29.9,34.8h14.1l15.6-18.2l4.5-5.3c1.5-1.7,1.6-4.3,0.1-6.1C59.9,82.5,56.6,78.6,56.6,78.6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"address\":\"0x123456789\",\"chainId\":5,\"name\":\"Swap Coin\",\"symbol\":\"SWC\",\"decimals\":18,\"tokenFeatures\":[\"swap\",\"fakeFeature\"]},{\"address\":\"0x123456789\",\"chainId\":5,\"name\":\"Bridge Coin\",\"symbol\":\"BDC\",\"decimals\":18,\"tokenFeatures\":[\"bridge\",\"fakeFeature\"]}]");
2896
+
2897
+
2898
+ const $efe60cea83bfc4e8$export$473cec51305fdae8 = async function({ type: type = ($08d5ddc39acd6833$export$fd9b17d87f4121d2).ALL , chainId: chainId , exclude: exclude }) {
2899
+ // todo:For API call, use the CheckoutError with errorType:API_CALL_ERROR?? or any other
2900
+ const filteredTokenList = ((/*@__PURE__*/$parcel$interopDefault($cda6003506e4182e$exports))).filter((token)=>{
2901
+ const chainIdMatches = token.chainId == chainId;
2902
+ const tokenNotExcluded = !exclude?.map((excludeToken)=>excludeToken.address).includes(token.address || "");
2903
+ const allowAllTokens = type === ($08d5ddc39acd6833$export$fd9b17d87f4121d2).ALL;
2904
+ const tokenAllowedForType = token.tokenFeatures.includes(type);
2905
+ return chainIdMatches && tokenNotExcluded && (allowAllTokens || tokenAllowedForType);
2906
+ }).map((token)=>{
2907
+ const { chainId: chainId , tokenFeatures: tokenFeatures , ...tokenInfo } = token;
2908
+ return tokenInfo;
2909
+ });
2284
2910
  return {
2285
- tokens: tokenList
2911
+ tokens: filteredTokenList
2286
2912
  };
2287
2913
  };
2288
2914
 
@@ -2292,6 +2918,9 @@ const $efe60cea83bfc4e8$export$473cec51305fdae8 = (chainId)=>{
2292
2918
  const $1564e43dde50bb61$export$df96cd8d56be0ab1 = async (provider, walletAddress)=>{
2293
2919
  return await ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
2294
2920
  const networkInfo = await ($de192de6ef100f9f$export$79f13b4cfaaf0d09)(provider);
2921
+ if (!networkInfo.isSupported) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)(`Chain:${networkInfo.chainId} is not a supported chain`, ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).CHAIN_NOT_SUPPORTED_ERROR, {
2922
+ chainName: networkInfo.name
2923
+ });
2295
2924
  const balance = await provider.getBalance(walletAddress);
2296
2925
  return {
2297
2926
  balance: balance,
@@ -2327,7 +2956,10 @@ async function $1564e43dde50bb61$export$60e0fe116a0e6ed0(provider, walletAddress
2327
2956
  const $1564e43dde50bb61$export$fee49741664a4d7e = async (provider, walletAddress, chainId)=>{
2328
2957
  if (!Object.values(($a47e48dd2c04791b$export$c06e1e7429de6283)).includes(chainId)) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)(`ChainId ${chainId} is not supported`, ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).CHAIN_NOT_SUPPORTED_ERROR);
2329
2958
  if (!provider.provider?.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("provider object is missing request function", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).PROVIDER_REQUEST_MISSING_ERROR);
2330
- const tokenList = ($efe60cea83bfc4e8$export$473cec51305fdae8)(chainId);
2959
+ const tokenList = await ($efe60cea83bfc4e8$export$473cec51305fdae8)({
2960
+ type: ($08d5ddc39acd6833$export$fd9b17d87f4121d2).ALL,
2961
+ chainId: chainId
2962
+ });
2331
2963
  const allBalancePromises = [];
2332
2964
  allBalancePromises.push($1564e43dde50bb61$export$df96cd8d56be0ab1(provider, walletAddress));
2333
2965
  tokenList.tokens.filter((token)=>token.address).forEach((token)=>allBalancePromises.push($1564e43dde50bb61$export$60e0fe116a0e6ed0(provider, walletAddress, token.address ?? "")));
@@ -2342,57 +2974,29 @@ const $1564e43dde50bb61$export$fee49741664a4d7e = async (provider, walletAddress
2342
2974
 
2343
2975
 
2344
2976
 
2345
- /* eslint-disable @typescript-eslint/no-explicit-any */
2346
2977
 
2347
2978
 
2348
2979
 
2349
- async function $c99672cf2294e839$export$2d040992269b4717(providerPreference) {
2350
- const provider = await $c99672cf2294e839$var$getWalletProviderForPreference(providerPreference);
2351
- if (!provider.provider?.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Incompatible provider", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).PROVIDER_REQUEST_MISSING_ERROR);
2352
- const accounts = await provider.provider.request({
2353
- method: ($4f91c5f280efe242$export$a130407f3423b97d).CHECK_CONNECTION,
2354
- params: []
2980
+
2981
+ var $6f3c55a615003cbf$exports = {};
2982
+ $6f3c55a615003cbf$exports = JSON.parse('[{"connectionProvider":"metamask","icon":"some-icon-url","name":"MetaMask","description":"complete web3 wallet solution","platform":["desktop"]},{"connectionProvider":"passport","icon":"pp-icon","name":"Passport","description":"Web3 with your email!","platform":["mobile","desktop"]},{"connectionProvider":"gamestop","icon":"gme-icon","name":"GameStop","description":"Never stopping the game!","platform":["mobile"]}]');
2983
+
2984
+
2985
+ async function $5cdde2ffe6360fec$export$a822caa90d7eef09({ type: type = ($4f91c5f280efe242$export$a75605c67ea83a5a).ALL , exclude: exclude }) {
2986
+ // todo:For async API call, use the CheckoutError with errorType:API_CALL_ERROR?? or any other
2987
+ const filteredWalletsList = ((/*@__PURE__*/$parcel$interopDefault($6f3c55a615003cbf$exports))).filter((wallet)=>{
2988
+ const walletNotExcluded = !exclude?.map((excludeWallet)=>excludeWallet.connectionProvider).includes(wallet.connectionProvider);
2989
+ const allowAllWallets = type === ($4f91c5f280efe242$export$a75605c67ea83a5a).ALL;
2990
+ const walletsAllowedForType = wallet.platform.includes(type);
2991
+ return walletNotExcluded && (allowAllWallets || walletsAllowedForType);
2992
+ }).map((wallet)=>{
2993
+ const { platform: platform , ...walletInfo } = wallet;
2994
+ return walletInfo;
2355
2995
  });
2356
- // accounts[0] will have the active account if connected.
2357
2996
  return {
2358
- isConnected: accounts && accounts.length > 0,
2359
- walletAddress: accounts[0] ?? ""
2997
+ wallets: filteredWalletsList
2360
2998
  };
2361
2999
  }
2362
- async function $c99672cf2294e839$export$fba2f6c3656e07c1(params) {
2363
- const web3Provider = await $c99672cf2294e839$var$getWalletProviderForPreference(params.providerPreference);
2364
- await ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
2365
- if (!web3Provider || !web3Provider?.provider?.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("No MetaMask provider installed.", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).METAMASK_PROVIDER_ERROR);
2366
- // this makes the request to the wallet to connect i.e request eth accounts ('eth_requestAccounts')
2367
- await web3Provider.provider.request({
2368
- method: ($4f91c5f280efe242$export$a130407f3423b97d).CONNECT,
2369
- params: []
2370
- });
2371
- }, {
2372
- type: ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).USER_REJECTED_REQUEST_ERROR
2373
- });
2374
- return web3Provider;
2375
- }
2376
- async function $c99672cf2294e839$var$getWalletProviderForPreference(providerPreference) {
2377
- let web3Provider = null;
2378
- switch(providerPreference){
2379
- case ($d176a05e966364ba$export$3bfad4d03ada24c4).METAMASK:
2380
- web3Provider = await $c99672cf2294e839$var$getMetaMaskProvider();
2381
- break;
2382
- default:
2383
- throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Provider preference was not detected", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).CONNECT_PROVIDER_ERROR);
2384
- }
2385
- return web3Provider;
2386
- }
2387
- async function $c99672cf2294e839$var$getMetaMaskProvider() {
2388
- const provider = await ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
2389
- return await (detectEthereumProvider)();
2390
- }, {
2391
- type: ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).METAMASK_PROVIDER_ERROR
2392
- });
2393
- if (!provider || !provider.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("No MetaMask provider installed.", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).METAMASK_PROVIDER_ERROR);
2394
- return new (Web3Provider)(provider);
2395
- }
2396
3000
 
2397
3001
 
2398
3002
 
@@ -2414,34 +3018,98 @@ const $dbe95599a4661140$export$8e0e7ffc78696d30 = async (params)=>{
2414
3018
 
2415
3019
 
2416
3020
 
3021
+
2417
3022
  class $a8cb37a3fc8eb863$export$1f60ba4ec72508a0 {
2418
- async checkIsWalletConnected(params) {
3023
+ /**
3024
+ * Check if a wallet is connected to the current application without requesting permission from the wallet and hence triggering a connect popup.
3025
+ * @param {CheckConnectionParams} params - The necessary data required to verify a wallet connection status.
3026
+ * @returns Wallet connection status details.
3027
+ * @throws {@link ErrorType}
3028
+ */ async checkIsWalletConnected(params) {
2419
3029
  return $c99672cf2294e839$export$2d040992269b4717(params.providerPreference);
2420
3030
  }
2421
- async connect(params) {
3031
+ /**
3032
+ * Establish a connection with a wallet provider such as MetaMask and returns the provider object and the current network details.
3033
+ * @param {ConnectParams} params - The necessary data required to establish a connection with a wallet provider.
3034
+ * @returns Wallet provider and current network information.
3035
+ * @throws {@link ErrorType}
3036
+ */ async connect(params) {
3037
+ this.providerPreference = params.providerPreference;
2422
3038
  const provider = await $c99672cf2294e839$export$fba2f6c3656e07c1(params);
2423
- const network = await ($de192de6ef100f9f$export$79f13b4cfaaf0d09)(provider);
3039
+ const networkInfo = await $de192de6ef100f9f$export$79f13b4cfaaf0d09(provider);
2424
3040
  return {
2425
3041
  provider: provider,
2426
- network: network
3042
+ network: networkInfo
2427
3043
  };
2428
3044
  }
2429
- async switchNetwork(params) {
2430
- return await ($de192de6ef100f9f$export$b827d9418aeb5dbd)(params.provider, params.chainId);
2431
- }
2432
- async getBalance(params) {
3045
+ /**
3046
+ * Switch the currently connected wallet to a new network.
3047
+ * @param {SwitchNetworkParams} params - The necessary data required to switch network.
3048
+ * @returns The new network information.
3049
+ * @throws {@link ErrorType}
3050
+ */ async switchNetwork(params) {
3051
+ if (!this.providerPreference) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)(`connect should be called before switchNetwork to set the provider preference`, ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).PROVIDER_PREFERENCE_ERROR);
3052
+ return await $de192de6ef100f9f$export$b827d9418aeb5dbd(this.providerPreference, params.provider, params.chainId);
3053
+ }
3054
+ /**
3055
+ * Fetch the balance of the native token of the current connected network or, if a contract address is provided, it will return the balance of that ERC20 token. For example, if the wallet is connected to the Ethereum Mainnet then the function gets the wallet ETH L1 balance.
3056
+ * @param {GetBalanceParams} params - The necessary data required to fetch the wallet balance.
3057
+ * @returns Native token balance for the given wallet.
3058
+ * @throws {@link ErrorType}
3059
+ */ async getBalance(params) {
2433
3060
  if (!params.contractAddress || params.contractAddress === "") return await $1564e43dde50bb61$export$df96cd8d56be0ab1(params.provider, params.walletAddress);
2434
3061
  return await $1564e43dde50bb61$export$60e0fe116a0e6ed0(params.provider, params.walletAddress, params.contractAddress);
2435
3062
  }
2436
- async getAllBalances(params) {
3063
+ /**
3064
+ * Fetch all available balances (ERC20 & Native) of the current connected network of the given wallet. It will loop through the list of allowed tokens and check for balance on each one.
3065
+ * @param {GetAllBalancesParams} params - The necessary data required to fetch all the wallet balances.
3066
+ * @returns List of tokens balance for the given wallet.
3067
+ * @throws {@link ErrorType}
3068
+ */ async getAllBalances(params) {
2437
3069
  return $1564e43dde50bb61$export$fee49741664a4d7e(params.provider, params.walletAddress, params.chainId);
2438
3070
  }
2439
- getTokenAllowList(params) {
2440
- return $efe60cea83bfc4e8$export$473cec51305fdae8(params.chainId);
2441
- }
2442
- async sendTransaction(params) {
3071
+ /**
3072
+ * Fetch the list of available networks that a wallet can add or/and switch to.
3073
+ * @param {GetNetworkAllowListParams} params - The necessary data required to fetch the list of available networks.
3074
+ * @returns List of networks.
3075
+ * @throws {@link ErrorType}
3076
+ */ async getNetworkAllowList(params) {
3077
+ return await $de192de6ef100f9f$export$3043f6442a9ef563(params);
3078
+ }
3079
+ /**
3080
+ * Get the list of tokens which are allowed to be used with the product.
3081
+ * @param {GetTokenAllowListParams} params - The necessary data required to fetch the list of allowed tokens.
3082
+ * @returns List of allowed tokens.
3083
+ * @throws {@link ErrorType}
3084
+ */ async getTokenAllowList(params) {
3085
+ return await $efe60cea83bfc4e8$export$473cec51305fdae8(params);
3086
+ }
3087
+ /**
3088
+ * Fetch the list of wallets which are available to connect with.
3089
+ * @param {GetWalletAllowListParams} params - The necessary data required to fetch the list of allowed wallets.
3090
+ * @returns List of allowed wallets.
3091
+ * @throws {@link ErrorType}
3092
+ */ async getWalletAllowList(params) {
3093
+ return await $5cdde2ffe6360fec$export$a822caa90d7eef09(params);
3094
+ }
3095
+ /**
3096
+ * Send a generic transaction to the provider.
3097
+ * @param {SendTransactionParams} params - The necessary data required to send a transaction.
3098
+ * @returns Transaction response.
3099
+ * @throws {@link ErrorType}
3100
+ * @remarks
3101
+ * Further documenation can be found at [MetaMask | Sending Transactions](https://docs.metamask.io/guide/sending-transactions.html).
3102
+ */ async sendTransaction(params) {
2443
3103
  return await $dbe95599a4661140$export$8e0e7ffc78696d30(params);
2444
3104
  }
3105
+ /**
3106
+ * Get network information about the currently selected network.
3107
+ * @param {GetNetworkParams} params - The necessary data required to get the current network information.
3108
+ * @returns Network details.
3109
+ * @throws {@link ErrorType}
3110
+ */ async getNetworkInfo(params) {
3111
+ return await $de192de6ef100f9f$export$79f13b4cfaaf0d09(params.provider);
3112
+ }
2445
3113
  }
2446
3114
 
2447
3115
  function $parcel$export(e, n, v, s) {
@@ -2467,6 +3135,7 @@ let $d71a87afc3136184$export$e72e7f9969a47dd3;
2467
3135
  (function(ConnectEventType) {
2468
3136
  ConnectEventType["SUCCESS"] = "success";
2469
3137
  ConnectEventType["FAILURE"] = "failure";
3138
+ ConnectEventType["CLOSE_WIDGET"] = "close-widget";
2470
3139
  })($d71a87afc3136184$export$e72e7f9969a47dd3 || ($d71a87afc3136184$export$e72e7f9969a47dd3 = {}));
2471
3140
 
2472
3141
 
@@ -2533,4 +3202,4 @@ let $9234b4c577442a97$export$c88931fdc51854eb;
2533
3202
  WidgetTheme["CUSTOM"] = "custom";
2534
3203
  })($9234b4c577442a97$export$c88931fdc51854eb || ($9234b4c577442a97$export$c88931fdc51854eb = {}));
2535
3204
 
2536
- export { $28a5fdc2f5e6c742$export$d1bfa21f7c76447a as BridgeEventType, $ede253beebe0de4a$export$90db5fe1be5993c1 as BuyEventType, $a47e48dd2c04791b$export$c06e1e7429de6283 as ChainId, $a8cb37a3fc8eb863$export$1f60ba4ec72508a0 as Checkout, Config, Configuration, $d71a87afc3136184$export$e72e7f9969a47dd3 as ConnectEventType, $d176a05e966364ba$export$3bfad4d03ada24c4 as ConnectionProviders, Environment, GenericIMXProvider, $88e4c575901cd68c$export$5a0ace85cae72d45 as IMTBLWidgetEvents, MetaMaskIMXProvider, $9234b4c577442a97$export$95be4ae94445245a as Network, PRODUCTION, Passport, PassportError, SANDBOX, StarkExAPIFactory, $5d497088f13bb116$export$140a49745ab55563 as SwapEventType, $9d0f1783d4d36e8a$export$d9be06b70b28c742 as WalletEventType, $9234b4c577442a97$export$c88931fdc51854eb as WidgetTheme };
3205
+ export { $28a5fdc2f5e6c742$export$d1bfa21f7c76447a as BridgeEventType, $ede253beebe0de4a$export$90db5fe1be5993c1 as BuyEventType, $a47e48dd2c04791b$export$c06e1e7429de6283 as ChainId, $a8cb37a3fc8eb863$export$1f60ba4ec72508a0 as Checkout, $a8bc256d81a5e2c1$export$e3dc0620abde7f5a as CheckoutErrorType, $d71a87afc3136184$export$e72e7f9969a47dd3 as ConnectEventType, $d176a05e966364ba$export$3bfad4d03ada24c4 as ConnectionProviders, Environment, GenericIMXProvider, $88e4c575901cd68c$export$5a0ace85cae72d45 as IMTBLWidgetEvents, ImmutableConfiguration, ImmutableXClient, MetaMaskIMXProvider, $9234b4c577442a97$export$95be4ae94445245a as Network, $a47e48dd2c04791b$export$1f05a55fe0680cc7 as NetworkFilterTypes, Passport, PassportConfiguration, PassportError, ProviderConfiguration, $5d497088f13bb116$export$140a49745ab55563 as SwapEventType, $08d5ddc39acd6833$export$fd9b17d87f4121d2 as TokenFilterTypes, $9d0f1783d4d36e8a$export$d9be06b70b28c742 as WalletEventType, $4f91c5f280efe242$export$a75605c67ea83a5a as WalletFilterTypes, $9234b4c577442a97$export$c88931fdc51854eb as WidgetTheme };