@imtbl/sdk 1.6.1 → 1.7.1

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.cjs CHANGED
@@ -10,10 +10,10 @@ var crypto = require('crypto');
10
10
  var magicSdk = require('magic-sdk');
11
11
  var oidc = require('@magic-ext/oidc');
12
12
  var providers = require('@ethersproject/providers');
13
- var ethers = require('ethers');
14
13
  var BN$2 = require('bn.js');
15
14
  var encUtils = require('enc-utils');
16
15
  var events = require('events');
16
+ var ethers = require('ethers');
17
17
  var abi = require('@0xsequence/abi');
18
18
  var core = require('@0xsequence/core');
19
19
  var FormData$2 = require('form-data');
@@ -174,7 +174,7 @@ const flattenProperties$1 = (properties) => {
174
174
  };
175
175
 
176
176
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
177
- const SDK_VERSION$1 = '1.6.1';
177
+ const SDK_VERSION$1 = '1.7.1';
178
178
  const getReferrer$1 = () => {
179
179
  if (isNode$1()) {
180
180
  return '';
@@ -11297,7 +11297,7 @@ class MultiRollupApiClients {
11297
11297
  }
11298
11298
 
11299
11299
  // eslint-disable-next-line @typescript-eslint/naming-convention
11300
- const defaultHeaders$1 = { 'x-sdk-version': 'ts-immutable-sdk-1.6.1' };
11300
+ const defaultHeaders$1 = { 'x-sdk-version': 'ts-immutable-sdk-1.7.1' };
11301
11301
  const createConfig = ({ basePath, headers, }) => {
11302
11302
  if (!basePath.trim()) {
11303
11303
  throw Error('basePath can not be empty');
@@ -11369,7 +11369,7 @@ class APIError extends Error {
11369
11369
 
11370
11370
  /* eslint-disable implicit-arrow-linebreak */
11371
11371
  const defaultHeaders = {
11372
- sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-1.6.1',
11372
+ sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-1.7.1',
11373
11373
  };
11374
11374
  /**
11375
11375
  * createAPIConfiguration to create a custom Configuration
@@ -11802,7 +11802,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
11802
11802
  chainID,
11803
11803
  coreContractAddress,
11804
11804
  registrationContractAddress,
11805
- sdkVersion: 'ts-immutable-sdk-1.6.1',
11805
+ sdkVersion: 'ts-immutable-sdk-1.7.1',
11806
11806
  });
11807
11807
  /**
11808
11808
  * Sets `sdkVersion` at the time of build
@@ -12305,6 +12305,78 @@ class IMXClient {
12305
12305
  }
12306
12306
  }
12307
12307
 
12308
+ // used to sign message with L1 keys. Used for registration
12309
+ function serializeEthSignature(sig) {
12310
+ // This is because golang appends a recovery param
12311
+ // https://github.com/ethers-io/ethers.js/issues/823
12312
+ return encUtils__namespace.addHexPrefix(encUtils__namespace.padLeft(sig.r.toString(16), 64)
12313
+ + encUtils__namespace.padLeft(sig.s.toString(16), 64)
12314
+ + encUtils__namespace.padLeft(sig.recoveryParam?.toString(16) || '', 2));
12315
+ }
12316
+ function importRecoveryParam(v) {
12317
+ const isValidBigNumber = new BN$2(v, 16).cmp(new BN$2(27)) !== -1
12318
+ ? new BN$2(v, 16).sub(new BN$2(27)).toNumber()
12319
+ : new BN$2(v, 16).toNumber();
12320
+ return v.trim()
12321
+ ? isValidBigNumber
12322
+ : undefined;
12323
+ }
12324
+ // used chained with serializeEthSignature. serializeEthSignature(deserializeSignature(...))
12325
+ function deserializeSignature(sig, size = 64) {
12326
+ const removedHexPrefixSig = encUtils__namespace.removeHexPrefix(sig);
12327
+ return {
12328
+ r: new BN$2(removedHexPrefixSig.substring(0, size), 'hex'),
12329
+ s: new BN$2(removedHexPrefixSig.substring(size, size * 2), 'hex'),
12330
+ recoveryParam: importRecoveryParam(removedHexPrefixSig.substring(size * 2, size * 2 + 2)),
12331
+ };
12332
+ }
12333
+ async function signRaw(payload, signer) {
12334
+ const signature = deserializeSignature(await signer.signMessage(payload));
12335
+ return serializeEthSignature(signature);
12336
+ }
12337
+ async function signMessage$1(message, signer) {
12338
+ const ethAddress = await signer.getAddress();
12339
+ const ethSignature = await signRaw(message, signer);
12340
+ return {
12341
+ message,
12342
+ ethAddress,
12343
+ ethSignature,
12344
+ };
12345
+ }
12346
+
12347
+ /**
12348
+ * Helper method to convert token type to a SignableToken type
12349
+ * @param token - the token type to convert to a SignableToken type
12350
+ * @returns the converted SignableToken
12351
+ */
12352
+ function convertToSignableToken(token) {
12353
+ switch (token.type) {
12354
+ case 'ERC721':
12355
+ return {
12356
+ type: 'ERC721',
12357
+ data: {
12358
+ token_id: token.tokenId,
12359
+ token_address: token.tokenAddress,
12360
+ },
12361
+ };
12362
+ case 'ERC20':
12363
+ return {
12364
+ type: 'ERC20',
12365
+ data: {
12366
+ token_address: token.tokenAddress,
12367
+ },
12368
+ };
12369
+ case 'ETH':
12370
+ default:
12371
+ return {
12372
+ type: 'ETH',
12373
+ data: {
12374
+ decimals: 18,
12375
+ },
12376
+ };
12377
+ }
12378
+ }
12379
+
12308
12380
  function bind$1(fn, thisArg) {
12309
12381
  return function wrap() {
12310
12382
  return fn.apply(thisArg, arguments);
@@ -16220,78 +16292,6 @@ const TransactionApprovalRequestChainTypeEnum = {
16220
16292
  Evm: 'evm'
16221
16293
  };
16222
16294
 
16223
- // used to sign message with L1 keys. Used for registration
16224
- function serializeEthSignature(sig) {
16225
- // This is because golang appends a recovery param
16226
- // https://github.com/ethers-io/ethers.js/issues/823
16227
- return encUtils__namespace.addHexPrefix(encUtils__namespace.padLeft(sig.r.toString(16), 64)
16228
- + encUtils__namespace.padLeft(sig.s.toString(16), 64)
16229
- + encUtils__namespace.padLeft(sig.recoveryParam?.toString(16) || '', 2));
16230
- }
16231
- function importRecoveryParam(v) {
16232
- const isValidBigNumber = new BN$2(v, 16).cmp(new BN$2(27)) !== -1
16233
- ? new BN$2(v, 16).sub(new BN$2(27)).toNumber()
16234
- : new BN$2(v, 16).toNumber();
16235
- return v.trim()
16236
- ? isValidBigNumber
16237
- : undefined;
16238
- }
16239
- // used chained with serializeEthSignature. serializeEthSignature(deserializeSignature(...))
16240
- function deserializeSignature(sig, size = 64) {
16241
- const removedHexPrefixSig = encUtils__namespace.removeHexPrefix(sig);
16242
- return {
16243
- r: new BN$2(removedHexPrefixSig.substring(0, size), 'hex'),
16244
- s: new BN$2(removedHexPrefixSig.substring(size, size * 2), 'hex'),
16245
- recoveryParam: importRecoveryParam(removedHexPrefixSig.substring(size * 2, size * 2 + 2)),
16246
- };
16247
- }
16248
- async function signRaw(payload, signer) {
16249
- const signature = deserializeSignature(await signer.signMessage(payload));
16250
- return serializeEthSignature(signature);
16251
- }
16252
- async function signMessage$1(message, signer) {
16253
- const ethAddress = await signer.getAddress();
16254
- const ethSignature = await signRaw(message, signer);
16255
- return {
16256
- message,
16257
- ethAddress,
16258
- ethSignature,
16259
- };
16260
- }
16261
-
16262
- /**
16263
- * Helper method to convert token type to a SignableToken type
16264
- * @param token - the token type to convert to a SignableToken type
16265
- * @returns the converted SignableToken
16266
- */
16267
- function convertToSignableToken(token) {
16268
- switch (token.type) {
16269
- case 'ERC721':
16270
- return {
16271
- type: 'ERC721',
16272
- data: {
16273
- token_id: token.tokenId,
16274
- token_address: token.tokenAddress,
16275
- },
16276
- };
16277
- case 'ERC20':
16278
- return {
16279
- type: 'ERC20',
16280
- data: {
16281
- token_address: token.tokenAddress,
16282
- },
16283
- };
16284
- case 'ETH':
16285
- default:
16286
- return {
16287
- type: 'ETH',
16288
- data: {
16289
- decimals: 18,
16290
- },
16291
- };
16292
- }
16293
- }
16294
-
16295
16295
  var PassportErrorType;
16296
16296
  (function (PassportErrorType) {
16297
16297
  PassportErrorType["AUTHENTICATION_ERROR"] = "AUTHENTICATION_ERROR";
@@ -16545,6 +16545,17 @@ class AuthManager {
16545
16545
  return AuthManager.mapOidcUserToDomainModel(oidcUser);
16546
16546
  }, PassportErrorType.AUTHENTICATION_ERROR);
16547
16547
  }
16548
+ async getUserOrLogin() {
16549
+ let user = null;
16550
+ try {
16551
+ user = await this.getUser();
16552
+ }
16553
+ catch (err) {
16554
+ // eslint-disable-next-line no-console
16555
+ console.warn('failed to retrieve a cached user session:', err);
16556
+ }
16557
+ return user || this.login();
16558
+ }
16548
16559
  async loginCallback() {
16549
16560
  return withPassportError(async () => this.userManager.signinPopupCallback(), PassportErrorType.AUTHENTICATION_ERROR);
16550
16561
  }
@@ -16792,227 +16803,6 @@ const getStarkSigner = async (signer) => withPassportError(async () => {
16792
16803
  return coreSdk.createStarkSigner(privateKey);
16793
16804
  }, PassportErrorType.WALLET_CONNECTION_ERROR);
16794
16805
 
16795
- const POLL_INTERVAL = 1 * 1000; // every 1 second
16796
- const MAX_RETRIES = 3;
16797
- const wait = (ms) => new Promise((resolve) => {
16798
- setTimeout(() => resolve(), ms);
16799
- });
16800
- const retryWithDelay = async (fn, options) => {
16801
- const { retries = MAX_RETRIES, interval = POLL_INTERVAL, finalErr = Error('Retry failed'), finallyFn = () => { }, } = options || {};
16802
- try {
16803
- return await fn();
16804
- }
16805
- catch (err) {
16806
- if (retries <= 0) {
16807
- return Promise.reject(finalErr);
16808
- }
16809
- await wait(interval);
16810
- return retryWithDelay(fn, { retries: retries - 1, finalErr, finallyFn });
16811
- }
16812
- finally {
16813
- if (retries <= 0) {
16814
- finallyFn();
16815
- }
16816
- }
16817
- };
16818
-
16819
- /**
16820
- * ProviderErrors should take priority over RpcErrorCodes
16821
- * https://eips.ethereum.org/EIPS/eip-1193#provider-errors
16822
- * https://eips.ethereum.org/EIPS/eip-1474#error-codes
16823
- */
16824
- var ProviderErrorCode;
16825
- (function (ProviderErrorCode) {
16826
- ProviderErrorCode[ProviderErrorCode["USER_REJECTED_REQUEST"] = 4001] = "USER_REJECTED_REQUEST";
16827
- ProviderErrorCode[ProviderErrorCode["UNAUTHORIZED"] = 4100] = "UNAUTHORIZED";
16828
- ProviderErrorCode[ProviderErrorCode["UNSUPPORTED_METHOD"] = 4200] = "UNSUPPORTED_METHOD";
16829
- ProviderErrorCode[ProviderErrorCode["DISCONNECTED"] = 4900] = "DISCONNECTED";
16830
- })(ProviderErrorCode || (ProviderErrorCode = {}));
16831
- var RpcErrorCode;
16832
- (function (RpcErrorCode) {
16833
- RpcErrorCode[RpcErrorCode["RPC_SERVER_ERROR"] = -32000] = "RPC_SERVER_ERROR";
16834
- RpcErrorCode[RpcErrorCode["INVALID_REQUEST"] = -32600] = "INVALID_REQUEST";
16835
- RpcErrorCode[RpcErrorCode["METHOD_NOT_FOUND"] = -32601] = "METHOD_NOT_FOUND";
16836
- RpcErrorCode[RpcErrorCode["INVALID_PARAMS"] = -32602] = "INVALID_PARAMS";
16837
- RpcErrorCode[RpcErrorCode["INTERNAL_ERROR"] = -32603] = "INTERNAL_ERROR";
16838
- RpcErrorCode[RpcErrorCode["PARSE_ERROR"] = -32700] = "PARSE_ERROR";
16839
- RpcErrorCode[RpcErrorCode["TRANSACTION_REJECTED"] = -32003] = "TRANSACTION_REJECTED";
16840
- })(RpcErrorCode || (RpcErrorCode = {}));
16841
- class JsonRpcError extends Error {
16842
- message;
16843
- code;
16844
- constructor(code, message) {
16845
- super(message);
16846
- this.message = message;
16847
- this.code = code;
16848
- }
16849
- }
16850
-
16851
- const transactionRejectedCrossSdkBridgeError = 'Transaction requires confirmation but this functionality is not'
16852
- + ' supported in this environment. Please contact Immutable support if you need to enable this feature.';
16853
- const convertBigNumberishToString = (value) => ethers.BigNumber.from(value).toString();
16854
- const transformGuardianTransactions = (txs) => {
16855
- try {
16856
- return txs.map((t) => ({
16857
- delegateCall: t.delegateCall === true,
16858
- revertOnError: t.revertOnError === true,
16859
- gasLimit: t.gasLimit ? convertBigNumberishToString(t.gasLimit) : '0',
16860
- target: t.to ?? ethers.ethers.constants.AddressZero,
16861
- value: t.value ? convertBigNumberishToString(t.value) : '0',
16862
- data: t.data ? t.data.toString() : '0x',
16863
- }));
16864
- }
16865
- catch (error) {
16866
- const errorMessage = error instanceof Error ? error.message : String(error);
16867
- throw new JsonRpcError(RpcErrorCode.INVALID_PARAMS, `Transaction failed to parsing: ${errorMessage}`);
16868
- }
16869
- };
16870
- class GuardianClient {
16871
- transactionAPI;
16872
- messageAPI;
16873
- confirmationScreen;
16874
- crossSdkBridgeEnabled;
16875
- authManager;
16876
- constructor({ confirmationScreen, config, authManager }) {
16877
- const guardianConfiguration = new Configuration({ basePath: config.imxPublicApiDomain });
16878
- this.confirmationScreen = confirmationScreen;
16879
- this.crossSdkBridgeEnabled = config.crossSdkBridgeEnabled;
16880
- this.messageAPI = new MessagesApi(guardianConfiguration);
16881
- this.transactionAPI = new TransactionsApi(guardianConfiguration);
16882
- this.authManager = authManager;
16883
- }
16884
- /**
16885
- * Open confirmation screen and close it automatically if the
16886
- * underlying task fails.
16887
- */
16888
- withConfirmationScreen(popupWindowSize) {
16889
- return (task) => this.withConfirmationScreenTask(popupWindowSize)(task)();
16890
- }
16891
- withConfirmationScreenTask(popupWindowSize) {
16892
- return (task) => async () => {
16893
- this.confirmationScreen.loading(popupWindowSize);
16894
- try {
16895
- return await task();
16896
- }
16897
- catch (err) {
16898
- this.confirmationScreen.closeWindow();
16899
- throw err;
16900
- }
16901
- };
16902
- }
16903
- withDefaultConfirmationScreenTask(task) {
16904
- return this.withConfirmationScreenTask()(task);
16905
- }
16906
- async evaluateImxTransaction({ payloadHash }) {
16907
- const finallyFn = () => {
16908
- this.confirmationScreen.closeWindow();
16909
- };
16910
- const user = await this.authManager.getUser();
16911
- const headers = { Authorization: `Bearer ${user.accessToken}` };
16912
- const transactionRes = await retryWithDelay(async () => this.transactionAPI.getTransactionByID({
16913
- transactionID: payloadHash,
16914
- chainType: 'starkex',
16915
- }, { headers }), { finallyFn });
16916
- if (!transactionRes.data.id) {
16917
- throw new Error("Transaction doesn't exists");
16918
- }
16919
- const evaluateImxRes = await this.transactionAPI.evaluateTransaction({
16920
- id: payloadHash,
16921
- transactionEvaluationRequest: {
16922
- chainType: 'starkex',
16923
- },
16924
- }, { headers });
16925
- const { confirmationRequired } = evaluateImxRes.data;
16926
- if (confirmationRequired) {
16927
- if (this.crossSdkBridgeEnabled) {
16928
- throw new Error(transactionRejectedCrossSdkBridgeError);
16929
- }
16930
- const confirmationResult = await this.confirmationScreen.requestConfirmation(payloadHash, user.imx.ethAddress, TransactionApprovalRequestChainTypeEnum.Starkex);
16931
- if (!confirmationResult.confirmed) {
16932
- throw new Error('Transaction rejected by user');
16933
- }
16934
- }
16935
- else {
16936
- this.confirmationScreen.closeWindow();
16937
- }
16938
- }
16939
- async evaluateEVMTransaction({ chainId, nonce, metaTransactions, }) {
16940
- const user = await this.authManager.getUser();
16941
- const headers = { Authorization: `Bearer ${user.accessToken}` };
16942
- const guardianTransactions = transformGuardianTransactions(metaTransactions);
16943
- try {
16944
- const transactionEvaluationResponseAxiosResponse = await this.transactionAPI.evaluateTransaction({
16945
- id: 'evm',
16946
- transactionEvaluationRequest: {
16947
- chainType: 'evm',
16948
- chainId,
16949
- transactionData: {
16950
- nonce,
16951
- userAddress: user.zkEvm.ethAddress,
16952
- metaTransactions: guardianTransactions,
16953
- },
16954
- },
16955
- }, { headers });
16956
- return transactionEvaluationResponseAxiosResponse.data;
16957
- }
16958
- catch (error) {
16959
- const errorMessage = error instanceof Error ? error.message : String(error);
16960
- throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, `Transaction failed to validate with error: ${errorMessage}`);
16961
- }
16962
- }
16963
- async validateEVMTransaction({ chainId, nonce, metaTransactions, }) {
16964
- const transactionEvaluationResponse = await this.evaluateEVMTransaction({
16965
- chainId,
16966
- nonce,
16967
- metaTransactions,
16968
- });
16969
- const { confirmationRequired, transactionId } = transactionEvaluationResponse;
16970
- if (confirmationRequired && this.crossSdkBridgeEnabled) {
16971
- throw new JsonRpcError(RpcErrorCode.TRANSACTION_REJECTED, transactionRejectedCrossSdkBridgeError);
16972
- }
16973
- if (confirmationRequired && !!transactionId) {
16974
- const user = await this.authManager.getUser();
16975
- const confirmationResult = await this.confirmationScreen.requestConfirmation(transactionId, user.zkEvm.ethAddress, TransactionApprovalRequestChainTypeEnum.Evm, chainId);
16976
- if (!confirmationResult.confirmed) {
16977
- throw new JsonRpcError(RpcErrorCode.TRANSACTION_REJECTED, 'Transaction rejected by user');
16978
- }
16979
- }
16980
- else {
16981
- this.confirmationScreen.closeWindow();
16982
- }
16983
- }
16984
- async evaluateMessage({ chainID, payload }) {
16985
- try {
16986
- const user = await this.authManager.getUser();
16987
- if (user === null) {
16988
- throw new PassportError('evaluateMessage requires a valid ID token or refresh token. Please log in first', PassportErrorType.NOT_LOGGED_IN_ERROR);
16989
- }
16990
- const messageEvalResponse = await this.messageAPI.evaluateMessage({ messageEvaluationRequest: { chainID, payload } }, { headers: { Authorization: `Bearer ${user.accessToken}` } });
16991
- return messageEvalResponse.data;
16992
- }
16993
- catch (error) {
16994
- const errorMessage = error instanceof Error ? error.message : String(error);
16995
- throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, `Message failed to validate with error: ${errorMessage}`);
16996
- }
16997
- }
16998
- async validateMessage({ chainID, payload }) {
16999
- const { messageId, confirmationRequired } = await this.evaluateMessage({ chainID, payload });
17000
- if (confirmationRequired && this.crossSdkBridgeEnabled) {
17001
- throw new JsonRpcError(RpcErrorCode.TRANSACTION_REJECTED, transactionRejectedCrossSdkBridgeError);
17002
- }
17003
- if (confirmationRequired && !!messageId) {
17004
- const user = await this.authManager.getUser();
17005
- const confirmationResult = await this.confirmationScreen.requestMessageConfirmation(messageId, user.zkEvm.ethAddress);
17006
- if (!confirmationResult.confirmed) {
17007
- throw new JsonRpcError(RpcErrorCode.TRANSACTION_REJECTED, 'Signature rejected by user');
17008
- }
17009
- }
17010
- else {
17011
- this.confirmationScreen.closeWindow();
17012
- }
17013
- }
17014
- }
17015
-
17016
16806
  var PassportEvents;
17017
16807
  (function (PassportEvents) {
17018
16808
  PassportEvents["LOGGED_OUT"] = "loggedOut";
@@ -17311,6 +17101,30 @@ async function batchNftTransfer({ user, starkSigner, request, transfersApi, guar
17311
17101
  }), PassportErrorType.TRANSFER_ERROR);
17312
17102
  }
17313
17103
 
17104
+ const POLL_INTERVAL = 1 * 1000; // every 1 second
17105
+ const MAX_RETRIES = 3;
17106
+ const wait = (ms) => new Promise((resolve) => {
17107
+ setTimeout(() => resolve(), ms);
17108
+ });
17109
+ const retryWithDelay = async (fn, options) => {
17110
+ const { retries = MAX_RETRIES, interval = POLL_INTERVAL, finalErr = Error('Retry failed'), finallyFn = () => { }, } = options || {};
17111
+ try {
17112
+ return await fn();
17113
+ }
17114
+ catch (err) {
17115
+ if (retries <= 0) {
17116
+ return Promise.reject(finalErr);
17117
+ }
17118
+ await wait(interval);
17119
+ return retryWithDelay(fn, { retries: retries - 1, finalErr, finallyFn });
17120
+ }
17121
+ finally {
17122
+ if (retries <= 0) {
17123
+ finallyFn();
17124
+ }
17125
+ }
17126
+ };
17127
+
17314
17128
  async function forceUserRefresh(authManager) {
17315
17129
  // User metadata is updated asynchronously. Poll userinfo endpoint until it is updated.
17316
17130
  await retryWithDelay(async () => {
@@ -17356,16 +17170,12 @@ class PassportImxProvider {
17356
17170
  */
17357
17171
  signers;
17358
17172
  signerInitialisationError;
17359
- constructor({ authManager, immutableXClient, confirmationScreen, config, passportEventEmitter, magicAdapter, imxApiClients, }) {
17173
+ constructor({ authManager, immutableXClient, passportEventEmitter, magicAdapter, imxApiClients, guardianClient, }) {
17360
17174
  this.authManager = authManager;
17361
17175
  this.immutableXClient = immutableXClient;
17362
- this.guardianClient = new GuardianClient({
17363
- confirmationScreen,
17364
- config,
17365
- authManager,
17366
- });
17367
17176
  this.magicAdapter = magicAdapter;
17368
17177
  this.imxApiClients = imxApiClients;
17178
+ this.guardianClient = guardianClient;
17369
17179
  this.initialiseSigners();
17370
17180
  passportEventEmitter.on(PassportEvents.LOGGED_OUT, this.handleLogout);
17371
17181
  }
@@ -17528,33 +17338,21 @@ class PassportImxProvider {
17528
17338
 
17529
17339
  class PassportImxProviderFactory {
17530
17340
  authManager;
17531
- config;
17532
- confirmationScreen;
17533
17341
  immutableXClient;
17534
17342
  magicAdapter;
17535
17343
  passportEventEmitter;
17536
17344
  imxApiClients;
17537
- constructor({ authManager, config, confirmationScreen, immutableXClient, magicAdapter, passportEventEmitter, imxApiClients, }) {
17345
+ guardianClient;
17346
+ constructor({ authManager, immutableXClient, magicAdapter, passportEventEmitter, imxApiClients, guardianClient, }) {
17538
17347
  this.authManager = authManager;
17539
- this.config = config;
17540
- this.confirmationScreen = confirmationScreen;
17541
17348
  this.immutableXClient = immutableXClient;
17542
17349
  this.magicAdapter = magicAdapter;
17543
17350
  this.passportEventEmitter = passportEventEmitter;
17544
17351
  this.imxApiClients = imxApiClients;
17352
+ this.guardianClient = guardianClient;
17545
17353
  }
17546
17354
  async getProvider() {
17547
- let user = null;
17548
- try {
17549
- user = await this.authManager.getUser();
17550
- }
17551
- catch (e) {
17552
- // eslint-disable-next-line no-console
17553
- console.warn(e);
17554
- }
17555
- if (!user) {
17556
- user = await this.authManager.login();
17557
- }
17355
+ const user = await this.authManager.getUserOrLogin();
17558
17356
  return this.createProviderInstance(user);
17559
17357
  }
17560
17358
  async getProviderSilent() {
@@ -17569,13 +17367,12 @@ class PassportImxProviderFactory {
17569
17367
  throw new PassportError('Failed to initialise', PassportErrorType.WALLET_CONNECTION_ERROR);
17570
17368
  }
17571
17369
  return new PassportImxProvider({
17572
- config: this.config,
17573
17370
  authManager: this.authManager,
17574
17371
  immutableXClient: this.immutableXClient,
17575
- confirmationScreen: this.confirmationScreen,
17576
17372
  passportEventEmitter: this.passportEventEmitter,
17577
17373
  magicAdapter: this.magicAdapter,
17578
17374
  imxApiClients: this.imxApiClients,
17375
+ guardianClient: this.guardianClient,
17579
17376
  });
17580
17377
  }
17581
17378
  }
@@ -18070,6 +17867,38 @@ class RelayerClient {
18070
17867
  }
18071
17868
  }
18072
17869
 
17870
+ /**
17871
+ * ProviderErrors should take priority over RpcErrorCodes
17872
+ * https://eips.ethereum.org/EIPS/eip-1193#provider-errors
17873
+ * https://eips.ethereum.org/EIPS/eip-1474#error-codes
17874
+ */
17875
+ var ProviderErrorCode;
17876
+ (function (ProviderErrorCode) {
17877
+ ProviderErrorCode[ProviderErrorCode["USER_REJECTED_REQUEST"] = 4001] = "USER_REJECTED_REQUEST";
17878
+ ProviderErrorCode[ProviderErrorCode["UNAUTHORIZED"] = 4100] = "UNAUTHORIZED";
17879
+ ProviderErrorCode[ProviderErrorCode["UNSUPPORTED_METHOD"] = 4200] = "UNSUPPORTED_METHOD";
17880
+ ProviderErrorCode[ProviderErrorCode["DISCONNECTED"] = 4900] = "DISCONNECTED";
17881
+ })(ProviderErrorCode || (ProviderErrorCode = {}));
17882
+ var RpcErrorCode;
17883
+ (function (RpcErrorCode) {
17884
+ RpcErrorCode[RpcErrorCode["RPC_SERVER_ERROR"] = -32000] = "RPC_SERVER_ERROR";
17885
+ RpcErrorCode[RpcErrorCode["INVALID_REQUEST"] = -32600] = "INVALID_REQUEST";
17886
+ RpcErrorCode[RpcErrorCode["METHOD_NOT_FOUND"] = -32601] = "METHOD_NOT_FOUND";
17887
+ RpcErrorCode[RpcErrorCode["INVALID_PARAMS"] = -32602] = "INVALID_PARAMS";
17888
+ RpcErrorCode[RpcErrorCode["INTERNAL_ERROR"] = -32603] = "INTERNAL_ERROR";
17889
+ RpcErrorCode[RpcErrorCode["PARSE_ERROR"] = -32700] = "PARSE_ERROR";
17890
+ RpcErrorCode[RpcErrorCode["TRANSACTION_REJECTED"] = -32003] = "TRANSACTION_REJECTED";
17891
+ })(RpcErrorCode || (RpcErrorCode = {}));
17892
+ class JsonRpcError extends Error {
17893
+ message;
17894
+ code;
17895
+ constructor(code, message) {
17896
+ super(message);
17897
+ this.message = message;
17898
+ this.code = code;
17899
+ }
17900
+ }
17901
+
18073
17902
  const MESSAGE_TO_SIGN = 'Only sign this message from Immutable Passport';
18074
17903
  async function registerZkEvmUser({ authManager, magicProvider, multiRollupApiClients, accessToken, jsonRpcProvider, }) {
18075
17904
  const web3Provider = new providers.Web3Provider(magicProvider);
@@ -18104,17 +17933,7 @@ async function registerZkEvmUser({ authManager, magicProvider, multiRollupApiCli
18104
17933
  }
18105
17934
 
18106
17935
  const loginZkEvmUser = async ({ authManager, magicAdapter, multiRollupApiClients, jsonRpcProvider, }) => {
18107
- let user = null;
18108
- try {
18109
- user = await authManager.getUser();
18110
- }
18111
- catch (err) {
18112
- // eslint-disable-next-line no-console
18113
- console.warn('eth_requestAccounts` failed to retrieve a cached user session:', err);
18114
- }
18115
- if (!user) {
18116
- user = await authManager.login();
18117
- }
17936
+ const user = await authManager.getUserOrLogin();
18118
17937
  if (!user.idToken) {
18119
17938
  throw new Error('User is missing idToken');
18120
17939
  }
@@ -18139,6 +17958,171 @@ const loginZkEvmUser = async ({ authManager, magicAdapter, multiRollupApiClients
18139
17958
  };
18140
17959
  };
18141
17960
 
17961
+ const transactionRejectedCrossSdkBridgeError = 'Transaction requires confirmation but this functionality is not'
17962
+ + ' supported in this environment. Please contact Immutable support if you need to enable this feature.';
17963
+ const convertBigNumberishToString = (value) => ethers.BigNumber.from(value).toString();
17964
+ const transformGuardianTransactions = (txs) => {
17965
+ try {
17966
+ return txs.map((t) => ({
17967
+ delegateCall: t.delegateCall === true,
17968
+ revertOnError: t.revertOnError === true,
17969
+ gasLimit: t.gasLimit ? convertBigNumberishToString(t.gasLimit) : '0',
17970
+ target: t.to ?? ethers.ethers.constants.AddressZero,
17971
+ value: t.value ? convertBigNumberishToString(t.value) : '0',
17972
+ data: t.data ? t.data.toString() : '0x',
17973
+ }));
17974
+ }
17975
+ catch (error) {
17976
+ const errorMessage = error instanceof Error ? error.message : String(error);
17977
+ throw new JsonRpcError(RpcErrorCode.INVALID_PARAMS, `Transaction failed to parsing: ${errorMessage}`);
17978
+ }
17979
+ };
17980
+ class GuardianClient {
17981
+ transactionAPI;
17982
+ messageAPI;
17983
+ confirmationScreen;
17984
+ crossSdkBridgeEnabled;
17985
+ authManager;
17986
+ constructor({ confirmationScreen, config, authManager }) {
17987
+ const guardianConfiguration = new Configuration({ basePath: config.imxPublicApiDomain });
17988
+ this.confirmationScreen = confirmationScreen;
17989
+ this.crossSdkBridgeEnabled = config.crossSdkBridgeEnabled;
17990
+ this.messageAPI = new MessagesApi(guardianConfiguration);
17991
+ this.transactionAPI = new TransactionsApi(guardianConfiguration);
17992
+ this.authManager = authManager;
17993
+ }
17994
+ /**
17995
+ * Open confirmation screen and close it automatically if the
17996
+ * underlying task fails.
17997
+ */
17998
+ withConfirmationScreen(popupWindowSize) {
17999
+ return (task) => this.withConfirmationScreenTask(popupWindowSize)(task)();
18000
+ }
18001
+ withConfirmationScreenTask(popupWindowSize) {
18002
+ return (task) => async () => {
18003
+ this.confirmationScreen.loading(popupWindowSize);
18004
+ try {
18005
+ return await task();
18006
+ }
18007
+ catch (err) {
18008
+ this.confirmationScreen.closeWindow();
18009
+ throw err;
18010
+ }
18011
+ };
18012
+ }
18013
+ withDefaultConfirmationScreenTask(task) {
18014
+ return this.withConfirmationScreenTask()(task);
18015
+ }
18016
+ async evaluateImxTransaction({ payloadHash }) {
18017
+ const finallyFn = () => {
18018
+ this.confirmationScreen.closeWindow();
18019
+ };
18020
+ const user = await this.authManager.getUser();
18021
+ const headers = { Authorization: `Bearer ${user.accessToken}` };
18022
+ const transactionRes = await retryWithDelay(async () => this.transactionAPI.getTransactionByID({
18023
+ transactionID: payloadHash,
18024
+ chainType: 'starkex',
18025
+ }, { headers }), { finallyFn });
18026
+ if (!transactionRes.data.id) {
18027
+ throw new Error("Transaction doesn't exists");
18028
+ }
18029
+ const evaluateImxRes = await this.transactionAPI.evaluateTransaction({
18030
+ id: payloadHash,
18031
+ transactionEvaluationRequest: {
18032
+ chainType: 'starkex',
18033
+ },
18034
+ }, { headers });
18035
+ const { confirmationRequired } = evaluateImxRes.data;
18036
+ if (confirmationRequired) {
18037
+ if (this.crossSdkBridgeEnabled) {
18038
+ throw new Error(transactionRejectedCrossSdkBridgeError);
18039
+ }
18040
+ const confirmationResult = await this.confirmationScreen.requestConfirmation(payloadHash, user.imx.ethAddress, TransactionApprovalRequestChainTypeEnum.Starkex);
18041
+ if (!confirmationResult.confirmed) {
18042
+ throw new Error('Transaction rejected by user');
18043
+ }
18044
+ }
18045
+ else {
18046
+ this.confirmationScreen.closeWindow();
18047
+ }
18048
+ }
18049
+ async evaluateEVMTransaction({ chainId, nonce, metaTransactions, }) {
18050
+ const user = await this.authManager.getUser();
18051
+ const headers = { Authorization: `Bearer ${user.accessToken}` };
18052
+ const guardianTransactions = transformGuardianTransactions(metaTransactions);
18053
+ try {
18054
+ const transactionEvaluationResponseAxiosResponse = await this.transactionAPI.evaluateTransaction({
18055
+ id: 'evm',
18056
+ transactionEvaluationRequest: {
18057
+ chainType: 'evm',
18058
+ chainId,
18059
+ transactionData: {
18060
+ nonce,
18061
+ userAddress: user.zkEvm.ethAddress,
18062
+ metaTransactions: guardianTransactions,
18063
+ },
18064
+ },
18065
+ }, { headers });
18066
+ return transactionEvaluationResponseAxiosResponse.data;
18067
+ }
18068
+ catch (error) {
18069
+ const errorMessage = error instanceof Error ? error.message : String(error);
18070
+ throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, `Transaction failed to validate with error: ${errorMessage}`);
18071
+ }
18072
+ }
18073
+ async validateEVMTransaction({ chainId, nonce, metaTransactions, }) {
18074
+ const transactionEvaluationResponse = await this.evaluateEVMTransaction({
18075
+ chainId,
18076
+ nonce,
18077
+ metaTransactions,
18078
+ });
18079
+ const { confirmationRequired, transactionId } = transactionEvaluationResponse;
18080
+ if (confirmationRequired && this.crossSdkBridgeEnabled) {
18081
+ throw new JsonRpcError(RpcErrorCode.TRANSACTION_REJECTED, transactionRejectedCrossSdkBridgeError);
18082
+ }
18083
+ if (confirmationRequired && !!transactionId) {
18084
+ const user = await this.authManager.getUser();
18085
+ const confirmationResult = await this.confirmationScreen.requestConfirmation(transactionId, user.zkEvm.ethAddress, TransactionApprovalRequestChainTypeEnum.Evm, chainId);
18086
+ if (!confirmationResult.confirmed) {
18087
+ throw new JsonRpcError(RpcErrorCode.TRANSACTION_REJECTED, 'Transaction rejected by user');
18088
+ }
18089
+ }
18090
+ else {
18091
+ this.confirmationScreen.closeWindow();
18092
+ }
18093
+ }
18094
+ async evaluateMessage({ chainID, payload }) {
18095
+ try {
18096
+ const user = await this.authManager.getUser();
18097
+ if (user === null) {
18098
+ throw new PassportError('evaluateMessage requires a valid ID token or refresh token. Please log in first', PassportErrorType.NOT_LOGGED_IN_ERROR);
18099
+ }
18100
+ const messageEvalResponse = await this.messageAPI.evaluateMessage({ messageEvaluationRequest: { chainID, payload } }, { headers: { Authorization: `Bearer ${user.accessToken}` } });
18101
+ return messageEvalResponse.data;
18102
+ }
18103
+ catch (error) {
18104
+ const errorMessage = error instanceof Error ? error.message : String(error);
18105
+ throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, `Message failed to validate with error: ${errorMessage}`);
18106
+ }
18107
+ }
18108
+ async validateMessage({ chainID, payload }) {
18109
+ const { messageId, confirmationRequired } = await this.evaluateMessage({ chainID, payload });
18110
+ if (confirmationRequired && this.crossSdkBridgeEnabled) {
18111
+ throw new JsonRpcError(RpcErrorCode.TRANSACTION_REJECTED, transactionRejectedCrossSdkBridgeError);
18112
+ }
18113
+ if (confirmationRequired && !!messageId) {
18114
+ const user = await this.authManager.getUser();
18115
+ const confirmationResult = await this.confirmationScreen.requestMessageConfirmation(messageId, user.zkEvm.ethAddress);
18116
+ if (!confirmationResult.confirmed) {
18117
+ throw new JsonRpcError(RpcErrorCode.TRANSACTION_REJECTED, 'Signature rejected by user');
18118
+ }
18119
+ }
18120
+ else {
18121
+ this.confirmationScreen.closeWindow();
18122
+ }
18123
+ }
18124
+ }
18125
+
18142
18126
  const MAX_TRANSACTION_HASH_RETRIEVAL_RETRIES = 30;
18143
18127
  const TRANSACTION_HASH_RETRIEVAL_WAIT = 1000;
18144
18128
  const getMetaTransactions = async (metaTransaction, nonce, chainId, walletAddress, signer, relayerClient) => {
@@ -18283,7 +18267,6 @@ const signTypedDataV4 = async ({ params, method, magicProvider, jsonRpcProvider,
18283
18267
  class ZkEvmProvider {
18284
18268
  authManager;
18285
18269
  config;
18286
- confirmationScreen;
18287
18270
  magicAdapter;
18288
18271
  multiRollupApiClients;
18289
18272
  jsonRpcProvider; // Used for read
@@ -18293,11 +18276,11 @@ class ZkEvmProvider {
18293
18276
  magicProvider; // Used for signing
18294
18277
  zkevmAddress;
18295
18278
  isPassport = true;
18296
- constructor({ authManager, magicAdapter, config, confirmationScreen, multiRollupApiClients, passportEventEmitter, }) {
18279
+ constructor({ authManager, magicAdapter, config, multiRollupApiClients, passportEventEmitter, guardianClient, }) {
18297
18280
  this.authManager = authManager;
18298
18281
  this.magicAdapter = magicAdapter;
18299
18282
  this.config = config;
18300
- this.confirmationScreen = confirmationScreen;
18283
+ this.guardianClient = guardianClient;
18301
18284
  if (config.crossSdkBridgeEnabled) {
18302
18285
  // JsonRpcProvider by default sets the referrer as "client".
18303
18286
  // On Unreal 4 this errors as the browser used is expecting a valid URL.
@@ -18317,7 +18300,6 @@ class ZkEvmProvider {
18317
18300
  const shouldEmitAccountsChanged = this.isLoggedIn();
18318
18301
  this.magicProvider = undefined;
18319
18302
  this.relayerClient = undefined;
18320
- this.guardianClient = undefined;
18321
18303
  if (shouldEmitAccountsChanged) {
18322
18304
  this.eventEmitter.emit(ProviderEvent.ACCOUNTS_CHANGED, []);
18323
18305
  }
@@ -18325,8 +18307,7 @@ class ZkEvmProvider {
18325
18307
  isLoggedIn() {
18326
18308
  return this.magicProvider !== undefined
18327
18309
  && this.zkevmAddress !== undefined
18328
- && this.relayerClient !== undefined
18329
- && this.guardianClient !== undefined;
18310
+ && this.relayerClient !== undefined;
18330
18311
  }
18331
18312
  async performRequest(request) {
18332
18313
  switch (request.method) {
@@ -18336,7 +18317,6 @@ class ZkEvmProvider {
18336
18317
  }
18337
18318
  const { magicProvider, user } = await loginZkEvmUser({
18338
18319
  authManager: this.authManager,
18339
- config: this.config,
18340
18320
  magicAdapter: this.magicAdapter,
18341
18321
  multiRollupApiClients: this.multiRollupApiClients,
18342
18322
  jsonRpcProvider: this.jsonRpcProvider,
@@ -18347,11 +18327,6 @@ class ZkEvmProvider {
18347
18327
  jsonRpcProvider: this.jsonRpcProvider,
18348
18328
  authManager: this.authManager,
18349
18329
  });
18350
- this.guardianClient = new GuardianClient({
18351
- confirmationScreen: this.confirmationScreen,
18352
- config: this.config,
18353
- authManager: this.authManager,
18354
- });
18355
18330
  this.zkevmAddress = user.zkEvm.ethAddress;
18356
18331
  this.eventEmitter.emit(ProviderEvent.ACCOUNTS_CHANGED, [user.zkEvm.ethAddress]);
18357
18332
  return [user.zkEvm.ethAddress];
@@ -18530,15 +18505,19 @@ const buildPrivateVars = (passportModuleConfiguration) => {
18530
18505
  const immutableXClient = passportModuleConfiguration.overrides
18531
18506
  ? passportModuleConfiguration.overrides.immutableXClient
18532
18507
  : new IMXClient({ baseConfig: passportModuleConfiguration.baseConfig });
18508
+ const guardianClient = new GuardianClient({
18509
+ confirmationScreen,
18510
+ config,
18511
+ authManager,
18512
+ });
18533
18513
  const imxApiClients = buildImxApiClients(passportModuleConfiguration);
18534
18514
  const passportImxProviderFactory = new PassportImxProviderFactory({
18535
18515
  authManager,
18536
- config,
18537
- confirmationScreen,
18538
18516
  immutableXClient,
18539
18517
  magicAdapter,
18540
18518
  passportEventEmitter,
18541
18519
  imxApiClients,
18520
+ guardianClient,
18542
18521
  });
18543
18522
  return {
18544
18523
  config,
@@ -18549,6 +18528,7 @@ const buildPrivateVars = (passportModuleConfiguration) => {
18549
18528
  multiRollupApiClients,
18550
18529
  passportEventEmitter,
18551
18530
  passportImxProviderFactory,
18531
+ guardianClient,
18552
18532
  };
18553
18533
  };
18554
18534
  class Passport {
@@ -18560,6 +18540,7 @@ class Passport {
18560
18540
  multiRollupApiClients;
18561
18541
  passportImxProviderFactory;
18562
18542
  passportEventEmitter;
18543
+ guardianClient;
18563
18544
  constructor(passportModuleConfiguration) {
18564
18545
  const privateVars = buildPrivateVars(passportModuleConfiguration);
18565
18546
  this.config = privateVars.config;
@@ -18570,6 +18551,7 @@ class Passport {
18570
18551
  this.multiRollupApiClients = privateVars.multiRollupApiClients;
18571
18552
  this.passportEventEmitter = privateVars.passportEventEmitter;
18572
18553
  this.passportImxProviderFactory = privateVars.passportImxProviderFactory;
18554
+ this.guardianClient = privateVars.guardianClient;
18573
18555
  setPassportClientId(passportModuleConfiguration.clientId);
18574
18556
  track('passport', 'initialised');
18575
18557
  }
@@ -18589,8 +18571,8 @@ class Passport {
18589
18571
  authManager: this.authManager,
18590
18572
  magicAdapter: this.magicAdapter,
18591
18573
  config: this.config,
18592
- confirmationScreen: this.confirmationScreen,
18593
18574
  multiRollupApiClients: this.multiRollupApiClients,
18575
+ guardianClient: this.guardianClient,
18594
18576
  });
18595
18577
  }
18596
18578
  /**
@@ -37456,7 +37438,7 @@ const flattenProperties = (properties) => {
37456
37438
  };
37457
37439
 
37458
37440
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
37459
- const SDK_VERSION = '1.6.1';
37441
+ const SDK_VERSION = '1.7.1';
37460
37442
  const getReferrer = () => {
37461
37443
  if (isNode()) {
37462
37444
  return '';
@@ -42623,7 +42605,7 @@ const IMMUTABLE_ZKVEM_GAS_OVERRIDES = {
42623
42605
  maxPriorityFeePerGas: ethers.BigNumber.from(10e9),
42624
42606
  };
42625
42607
 
42626
- const SDK_VERSION_MARKER = '1.6.1';
42608
+ const SDK_VERSION_MARKER = '1.7.1';
42627
42609
  // This SDK version is replaced by the `yarn build` command ran on the root level
42628
42610
  const globalPackageVersion = () => SDK_VERSION_MARKER;
42629
42611
 
@@ -46137,13 +46119,15 @@ class FiatRampService {
46137
46119
  const productsAvailed = 'productsAvailed=buy';
46138
46120
  const exchangeScreenTitle = 'exchangeScreenTitle=Buy';
46139
46121
  const themeColor = 'themeColor=0D0D0D';
46122
+ const defaultFiat = 'defaultFiatAmount=50&defaultFiatCurrency=usd';
46140
46123
  widgetUrl += `${transakPublishableKey}&`
46141
46124
  + `${zkevmNetwork}&`
46142
46125
  + `${defaultPaymentMethod}&`
46143
46126
  + `${disableBankTransfer}&`
46144
46127
  + `${productsAvailed}&`
46145
46128
  + `${exchangeScreenTitle}&`
46146
- + `${themeColor}`;
46129
+ + `${themeColor}&`
46130
+ + `${defaultFiat}`;
46147
46131
  if (params.isPassport && params.email) {
46148
46132
  const encodedEmail = encodeURIComponent(params.email);
46149
46133
  widgetUrl += `&email=${encodedEmail}&isAutoFillUserData=true&disableWalletAddressForm=true`;
@@ -46157,6 +46141,9 @@ class FiatRampService {
46157
46141
  if (params.walletAddress) {
46158
46142
  widgetUrl += `&walletAddress=${params.walletAddress}`;
46159
46143
  }
46144
+ if (params.allowedTokens) {
46145
+ widgetUrl += `&cryptoCurrencyList=${params.allowedTokens?.join(',').toLowerCase()}`;
46146
+ }
46160
46147
  return widgetUrl;
46161
46148
  }
46162
46149
  }
@@ -46603,6 +46590,7 @@ class Checkout {
46603
46590
  tokenAmount = params.tokenAmount;
46604
46591
  tokenSymbol = token.symbol;
46605
46592
  }
46593
+ const allowedTokens = tokenList?.tokens?.filter((t) => t.symbol).map((t) => t.symbol);
46606
46594
  return await this.fiatRampService.createWidgetUrl({
46607
46595
  exchangeType: params.exchangeType,
46608
46596
  isPassport,
@@ -46610,6 +46598,7 @@ class Checkout {
46610
46598
  tokenAmount,
46611
46599
  tokenSymbol,
46612
46600
  email,
46601
+ allowedTokens,
46613
46602
  });
46614
46603
  }
46615
46604
  /**