@imtbl/sdk 0.27.9 → 0.27.10

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
@@ -19,7 +19,7 @@ var seaportJs = require('@opensea/seaport-js');
19
19
  var units = require('@ethersproject/units');
20
20
  var bignumber = require('@ethersproject/bignumber');
21
21
  var detectEthereumProvider = require('@metamask/detect-provider');
22
- var sdkCore = require('@uniswap/sdk-core');
22
+ var Uniswap = require('@uniswap/sdk-core');
23
23
  var assert = require('assert');
24
24
  var v3Sdk = require('@uniswap/v3-sdk');
25
25
  var solidity = require('@ethersproject/solidity');
@@ -46,6 +46,7 @@ function _interopNamespaceDefault(e) {
46
46
 
47
47
  var crypto__namespace = /*#__PURE__*/_interopNamespaceDefault(crypto);
48
48
  var encUtils__namespace = /*#__PURE__*/_interopNamespaceDefault(encUtils);
49
+ var Uniswap__namespace = /*#__PURE__*/_interopNamespaceDefault(Uniswap);
49
50
 
50
51
  var Environment$1;
51
52
  (function (Environment) {
@@ -3631,7 +3632,7 @@ class MultiRollupApiClients {
3631
3632
  }
3632
3633
 
3633
3634
  // eslint-disable-next-line @typescript-eslint/naming-convention
3634
- const defaultHeaders$1 = { 'x-sdk-version': 'ts-immutable-sdk-0.27.9' };
3635
+ const defaultHeaders$1 = { 'x-sdk-version': 'ts-immutable-sdk-0.27.10' };
3635
3636
  const createConfig = ({ basePath, headers, }) => {
3636
3637
  if (!basePath.trim()) {
3637
3638
  throw Error('basePath can not be empty');
@@ -3691,7 +3692,7 @@ class APIError extends Error {
3691
3692
 
3692
3693
  /* eslint-disable implicit-arrow-linebreak */
3693
3694
  const defaultHeaders = {
3694
- sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-0.27.9',
3695
+ sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-0.27.10',
3695
3696
  };
3696
3697
  /**
3697
3698
  * createAPIConfiguration to create a custom Configuration
@@ -4102,7 +4103,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
4102
4103
  chainID,
4103
4104
  coreContractAddress,
4104
4105
  registrationContractAddress,
4105
- sdkVersion: 'ts-immutable-sdk-0.27.9',
4106
+ sdkVersion: 'ts-immutable-sdk-0.27.10',
4106
4107
  });
4107
4108
  /**
4108
4109
  * Sets `sdkVersion` at the time of build
@@ -8582,6 +8583,7 @@ var PassportErrorType;
8582
8583
  PassportErrorType["SILENT_LOGIN_ERROR"] = "SILENT_LOGIN_ERROR";
8583
8584
  PassportErrorType["REFRESH_TOKEN_ERROR"] = "REFRESH_TOKEN_ERROR";
8584
8585
  PassportErrorType["USER_REGISTRATION_ERROR"] = "USER_REGISTRATION_ERROR";
8586
+ PassportErrorType["USER_NOT_REGISTERED_ERROR"] = "USER_NOT_REGISTERED_ERROR";
8585
8587
  PassportErrorType["LOGOUT_ERROR"] = "LOGOUT_ERROR";
8586
8588
  PassportErrorType["TRANSFER_ERROR"] = "TRANSFER_ERROR";
8587
8589
  PassportErrorType["CREATE_ORDER_ERROR"] = "CREATE_ORDER_ERROR";
@@ -8731,6 +8733,10 @@ class AuthManager {
8731
8733
  config;
8732
8734
  deviceCredentialsManager;
8733
8735
  logoutMode;
8736
+ /**
8737
+ * Promise that is used to prevent multiple concurrent calls to the refresh token endpoint.
8738
+ */
8739
+ refreshingPromise = null;
8734
8740
  constructor(config) {
8735
8741
  this.config = config;
8736
8742
  this.userManager = new oidcClientTs.UserManager(getAuthConfiguration(config));
@@ -8975,32 +8981,52 @@ class AuthManager {
8975
8981
  * @param forceRefresh If set to true, force an HTTP call to the OIDC server's authorization endpoint. This call will
8976
8982
  * throw an error if there's no refresh token.
8977
8983
  */
8978
- async getWebUser({ forceRefresh = false }) {
8984
+ async getAuthenticatedUser({ forceRefresh = false }) {
8979
8985
  if (forceRefresh) {
8980
- const newOidcUser = await this.userManager.signinSilent();
8981
- return newOidcUser ? AuthManager.mapOidcUserToDomainModel(newOidcUser) : null;
8986
+ return this.refreshTokenAndUpdatePromise();
8982
8987
  }
8983
8988
  const oidcUser = await this.userManager.getUser();
8984
8989
  if (!oidcUser)
8985
8990
  return null;
8986
- const tokenExpired = isTokenExpired(oidcUser);
8987
- if (!tokenExpired) {
8991
+ if (!isTokenExpired(oidcUser)) {
8988
8992
  return AuthManager.mapOidcUserToDomainModel(oidcUser);
8989
8993
  }
8990
8994
  if (oidcUser.refresh_token) {
8991
- const newOidcUser = await this.userManager.signinSilent();
8992
- if (newOidcUser) {
8993
- return AuthManager.mapOidcUserToDomainModel(newOidcUser);
8994
- }
8995
+ return this.refreshTokenAndUpdatePromise();
8995
8996
  }
8996
8997
  return null;
8997
8998
  }
8999
+ /**
9000
+ * Refreshes the token and returns the user.
9001
+ * If the token is already being refreshed, returns the existing promise.
9002
+ */
9003
+ async refreshTokenAndUpdatePromise() {
9004
+ if (this.refreshingPromise)
9005
+ return this.refreshingPromise;
9006
+ // eslint-disable-next-line no-async-promise-executor
9007
+ this.refreshingPromise = new Promise(async (resolve, reject) => {
9008
+ try {
9009
+ const newOidcUser = await this.userManager.signinSilent();
9010
+ if (newOidcUser) {
9011
+ resolve(AuthManager.mapOidcUserToDomainModel(newOidcUser));
9012
+ return;
9013
+ }
9014
+ resolve(null);
9015
+ }
9016
+ catch (err) {
9017
+ reject(err);
9018
+ }
9019
+ finally {
9020
+ this.refreshingPromise = null; // Reset the promise after completion
9021
+ }
9022
+ });
9023
+ return this.refreshingPromise;
9024
+ }
8998
9025
  async getUser({ forceRefresh } = { forceRefresh: false }) {
8999
9026
  return withPassportError(async () => {
9000
- const user = await this.getWebUser({ forceRefresh });
9001
- if (user) {
9027
+ const user = await this.getAuthenticatedUser({ forceRefresh });
9028
+ if (user)
9002
9029
  return user;
9003
- }
9004
9030
  const deviceToken = this.deviceCredentialsManager.getCredentials();
9005
9031
  if (deviceToken) {
9006
9032
  return AuthManager.mapDeviceTokenResponseToDomainUserModel(deviceToken);
@@ -9027,14 +9053,16 @@ class MagicAdapter {
9027
9053
  magicClient;
9028
9054
  constructor(config) {
9029
9055
  this.config = config;
9030
- this.magicClient = new magicSdk.Magic(this.config.magicPublishableApiKey, {
9031
- extensions: [new oidc.OpenIdExtension()],
9032
- network: config.network,
9033
- });
9034
- this.magicClient.preload();
9056
+ if (window) {
9057
+ this.magicClient = this.initMagicClient();
9058
+ this.magicClient.preload();
9059
+ }
9035
9060
  }
9036
9061
  async login(idToken) {
9037
9062
  return withPassportError(async () => {
9063
+ if (!this.magicClient) {
9064
+ this.magicClient = this.initMagicClient();
9065
+ }
9038
9066
  await this.magicClient.openid.loginWithOIDC({
9039
9067
  jwt: idToken,
9040
9068
  providerId: this.config.magicProviderId,
@@ -9043,10 +9071,16 @@ class MagicAdapter {
9043
9071
  }, PassportErrorType.WALLET_CONNECTION_ERROR);
9044
9072
  }
9045
9073
  async logout() {
9046
- if (this.magicClient.user) {
9074
+ if (this.magicClient?.user) {
9047
9075
  await this.magicClient.user.logout();
9048
9076
  }
9049
9077
  }
9078
+ initMagicClient() {
9079
+ return new magicSdk.Magic(this.config.magicPublishableApiKey, {
9080
+ extensions: [new oidc.OpenIdExtension()],
9081
+ network: this.config.network,
9082
+ });
9083
+ }
9050
9084
  }
9051
9085
 
9052
9086
  const getStarkSigner = async (signer) => withPassportError(async () => {
@@ -9133,16 +9167,13 @@ class GuardianClient {
9133
9167
  transactionAPI;
9134
9168
  messageAPI;
9135
9169
  confirmationScreen;
9136
- // TODO: ID-977, make this rollup agnostic
9137
- imxEtherAddress;
9138
9170
  crossSdkBridgeEnabled;
9139
- constructor({ accessToken, confirmationScreen, imxEtherAddress, config, }) {
9140
- const guardianConfiguration = new Configuration({ accessToken, basePath: config.imxPublicApiDomain });
9171
+ constructor({ confirmationScreen, config }) {
9172
+ const guardianConfiguration = new Configuration({ basePath: config.imxPublicApiDomain });
9141
9173
  this.confirmationScreen = confirmationScreen;
9142
- this.transactionAPI = new TransactionsApi(new Configuration(guardianConfiguration));
9143
- this.imxEtherAddress = imxEtherAddress;
9144
9174
  this.crossSdkBridgeEnabled = config.crossSdkBridgeEnabled;
9145
9175
  this.messageAPI = new MessagesApi(guardianConfiguration);
9176
+ this.transactionAPI = new TransactionsApi(guardianConfiguration);
9146
9177
  }
9147
9178
  /**
9148
9179
  * Open confirmation screen and close it automatically if the
@@ -9166,29 +9197,30 @@ class GuardianClient {
9166
9197
  withDefaultConfirmationScreenTask(task) {
9167
9198
  return this.withConfirmationScreenTask()(task);
9168
9199
  }
9169
- async validate({ payloadHash }) {
9200
+ async evaluateImxTransaction({ payloadHash, user }) {
9170
9201
  const finallyFn = () => {
9171
9202
  this.confirmationScreen.closeWindow();
9172
9203
  };
9204
+ const headers = { Authorization: `Bearer ${user.accessToken}` };
9173
9205
  const transactionRes = await retryWithDelay(async () => this.transactionAPI.getTransactionByID({
9174
9206
  transactionID: payloadHash,
9175
9207
  chainType: 'starkex',
9176
- }), { finallyFn });
9208
+ }, { headers }), { finallyFn });
9177
9209
  if (!transactionRes.data.id) {
9178
9210
  throw new Error("Transaction doesn't exists");
9179
9211
  }
9180
- const evaluateStarkexRes = await this.transactionAPI.evaluateTransaction({
9212
+ const evaluateImxRes = await this.transactionAPI.evaluateTransaction({
9181
9213
  id: payloadHash,
9182
9214
  transactionEvaluationRequest: {
9183
9215
  chainType: 'starkex',
9184
9216
  },
9185
- });
9186
- const { confirmationRequired } = evaluateStarkexRes.data;
9217
+ }, { headers });
9218
+ const { confirmationRequired } = evaluateImxRes.data;
9187
9219
  if (confirmationRequired) {
9188
9220
  if (this.crossSdkBridgeEnabled) {
9189
9221
  throw new Error(transactionRejectedCrossSdkBridgeError);
9190
9222
  }
9191
- const confirmationResult = await this.confirmationScreen.requestConfirmation(payloadHash, this.imxEtherAddress, TransactionApprovalRequestChainTypeEnum.Starkex);
9223
+ const confirmationResult = await this.confirmationScreen.requestConfirmation(payloadHash, user.imx.ethAddress, TransactionApprovalRequestChainTypeEnum.Starkex);
9192
9224
  if (!confirmationResult.confirmed) {
9193
9225
  throw new Error('Transaction rejected by user');
9194
9226
  }
@@ -9232,7 +9264,7 @@ class GuardianClient {
9232
9264
  throw new JsonRpcError(RpcErrorCode.TRANSACTION_REJECTED, transactionRejectedCrossSdkBridgeError);
9233
9265
  }
9234
9266
  if (confirmationRequired && !!transactionId) {
9235
- const confirmationResult = await this.confirmationScreen.requestConfirmation(transactionId, this.imxEtherAddress, TransactionApprovalRequestChainTypeEnum.Evm, chainId);
9267
+ const confirmationResult = await this.confirmationScreen.requestConfirmation(transactionId, user.zkEvm.ethAddress, TransactionApprovalRequestChainTypeEnum.Evm, chainId);
9236
9268
  if (!confirmationResult.confirmed) {
9237
9269
  throw new JsonRpcError(RpcErrorCode.TRANSACTION_REJECTED, 'Transaction rejected by user');
9238
9270
  }
@@ -9328,10 +9360,7 @@ async function createOrder$1({ starkSigner, user, request, ordersApi, guardianCl
9328
9360
  const { ethAddress } = user.imx;
9329
9361
  const amountSell = request.sell.type === ERC721$1 ? '1' : request.sell.amount;
9330
9362
  const amountBuy = request.buy.type === ERC721$1 ? '1' : request.buy.amount;
9331
- const headers = {
9332
- // eslint-disable-next-line @typescript-eslint/naming-convention
9333
- Authorization: `Bearer ${user.accessToken}`,
9334
- };
9363
+ const headers = { Authorization: `Bearer ${user.accessToken}` };
9335
9364
  const getSignableOrderRequestV3 = {
9336
9365
  user: ethAddress,
9337
9366
  amount_buy: amountBuy,
@@ -9345,7 +9374,8 @@ async function createOrder$1({ starkSigner, user, request, ordersApi, guardianCl
9345
9374
  const getSignableOrderResponse = await ordersApi.getSignableOrder({
9346
9375
  getSignableOrderRequestV3,
9347
9376
  }, { headers });
9348
- await guardianClient.validate({
9377
+ await guardianClient.evaluateImxTransaction({
9378
+ user,
9349
9379
  payloadHash: getSignableOrderResponse.data.payload_hash,
9350
9380
  });
9351
9381
  const { payload_hash: payloadHash } = getSignableOrderResponse.data;
@@ -9387,7 +9417,8 @@ async function cancelOrder$1({ user, starkSigner, request, ordersApi, guardianCl
9387
9417
  const getSignableCancelOrderResponse = await ordersApi.getSignableCancelOrderV3({
9388
9418
  getSignableCancelOrderRequest,
9389
9419
  }, { headers });
9390
- await guardianClient.validate({
9420
+ await guardianClient.evaluateImxTransaction({
9421
+ user,
9391
9422
  payloadHash: getSignableCancelOrderResponse.data.payload_hash,
9392
9423
  });
9393
9424
  const { payload_hash: payloadHash } = getSignableCancelOrderResponse.data;
@@ -9450,7 +9481,8 @@ async function createTrade$1({ request, tradesApi, user, starkSigner, guardianCl
9450
9481
  const getSignableTradeResponse = await tradesApi.getSignableTrade({
9451
9482
  getSignableTradeRequest,
9452
9483
  }, { headers });
9453
- await guardianClient.validate({
9484
+ await guardianClient.evaluateImxTransaction({
9485
+ user,
9454
9486
  payloadHash: getSignableTradeResponse.data.payload_hash,
9455
9487
  });
9456
9488
  const { payload_hash: payloadHash } = getSignableTradeResponse.data;
@@ -9497,7 +9529,8 @@ async function transfer$1({ request, transfersApi, starkSigner, user, guardianCl
9497
9529
  const signableResult = await transfersApi.getSignableTransferV1({
9498
9530
  getSignableTransferRequest,
9499
9531
  }, { headers });
9500
- await guardianClient.validate({
9532
+ await guardianClient.evaluateImxTransaction({
9533
+ user,
9501
9534
  payloadHash: signableResult.data.payload_hash,
9502
9535
  });
9503
9536
  const signableResultData = signableResult.data;
@@ -9544,14 +9577,12 @@ async function batchNftTransfer({ user, starkSigner, request, transfersApi, guar
9544
9577
  sender_ether_key: ethAddress,
9545
9578
  signable_requests: signableRequests,
9546
9579
  };
9547
- const headers = {
9548
- // eslint-disable-next-line @typescript-eslint/naming-convention
9549
- Authorization: `Bearer ${user.accessToken}`,
9550
- };
9580
+ const headers = { Authorization: `Bearer ${user.accessToken}` };
9551
9581
  const signableResult = await transfersApi.getSignableTransfer({
9552
9582
  getSignableTransferRequestV2,
9553
9583
  }, { headers });
9554
- await guardianClient.validate({
9584
+ await guardianClient.evaluateImxTransaction({
9585
+ user,
9555
9586
  payloadHash: signableResult.data.signable_responses[0]?.payload_hash,
9556
9587
  });
9557
9588
  const requests = await Promise.all(signableResult.data.signable_responses.map(async (resp) => {
@@ -9581,39 +9612,40 @@ async function batchNftTransfer({ user, starkSigner, request, transfersApi, guar
9581
9612
  }
9582
9613
 
9583
9614
  class PassportImxProvider {
9584
- user;
9615
+ authManager;
9585
9616
  starkSigner;
9586
9617
  immutableXClient;
9587
- confirmationScreen;
9588
9618
  guardianClient;
9589
- constructor({ user, starkSigner, immutableXClient, confirmationScreen, config, passportEventEmitter, }) {
9590
- this.user = user;
9619
+ constructor({ authManager, starkSigner, immutableXClient, confirmationScreen, config, passportEventEmitter, }) {
9620
+ this.authManager = authManager;
9591
9621
  this.starkSigner = starkSigner;
9592
9622
  this.immutableXClient = immutableXClient;
9593
- this.confirmationScreen = confirmationScreen;
9594
9623
  this.guardianClient = new GuardianClient({
9595
- accessToken: user.accessToken,
9596
9624
  confirmationScreen,
9597
- imxEtherAddress: user.imx.ethAddress,
9598
9625
  config,
9599
9626
  });
9600
9627
  passportEventEmitter.on(PassportEvents.LOGGED_OUT, this.handleLogout);
9601
9628
  }
9602
9629
  handleLogout = () => {
9603
- this.user = undefined;
9604
9630
  this.starkSigner = undefined;
9605
9631
  };
9606
- checkIsLoggedIn() {
9607
- if (this.user === undefined || this.starkSigner === undefined) {
9632
+ async getAuthenticatedUserSigner() {
9633
+ const user = await this.authManager.getUser();
9634
+ if (!user || this.starkSigner === undefined) {
9608
9635
  throw new PassportError('User has been logged out', PassportErrorType.NOT_LOGGED_IN_ERROR);
9609
9636
  }
9637
+ const isUserImx = (oidcUser) => oidcUser?.imx !== undefined;
9638
+ if (!isUserImx(user)) {
9639
+ throw new PassportError('User has not been registered with StarkEx', PassportErrorType.USER_NOT_REGISTERED_ERROR);
9640
+ }
9641
+ return { user, starkSigner: this.starkSigner };
9610
9642
  }
9611
9643
  async transfer(request) {
9612
- this.checkIsLoggedIn();
9644
+ const { user, starkSigner } = await this.getAuthenticatedUserSigner();
9613
9645
  return transfer$1({
9614
9646
  request,
9615
- user: this.user,
9616
- starkSigner: this.starkSigner,
9647
+ user,
9648
+ starkSigner,
9617
9649
  transfersApi: this.immutableXClient.transfersApi,
9618
9650
  guardianClient: this.guardianClient,
9619
9651
  });
@@ -9628,52 +9660,52 @@ class PassportImxProvider {
9628
9660
  isRegisteredOnchain() {
9629
9661
  throw new PassportError('Operation not supported', PassportErrorType.OPERATION_NOT_SUPPORTED_ERROR);
9630
9662
  }
9631
- createOrder(request) {
9632
- this.checkIsLoggedIn();
9663
+ async createOrder(request) {
9664
+ const { user, starkSigner } = await this.getAuthenticatedUserSigner();
9633
9665
  return createOrder$1({
9634
9666
  request,
9635
- user: this.user,
9636
- starkSigner: this.starkSigner,
9667
+ user,
9668
+ starkSigner,
9637
9669
  ordersApi: this.immutableXClient.ordersApi,
9638
9670
  guardianClient: this.guardianClient,
9639
9671
  });
9640
9672
  }
9641
- cancelOrder(request) {
9642
- this.checkIsLoggedIn();
9673
+ async cancelOrder(request) {
9674
+ const { user, starkSigner } = await this.getAuthenticatedUserSigner();
9643
9675
  return cancelOrder$1({
9644
9676
  request,
9645
- user: this.user,
9646
- starkSigner: this.starkSigner,
9677
+ user,
9678
+ starkSigner,
9647
9679
  ordersApi: this.immutableXClient.ordersApi,
9648
9680
  guardianClient: this.guardianClient,
9649
9681
  });
9650
9682
  }
9651
- createTrade(request) {
9652
- this.checkIsLoggedIn();
9683
+ async createTrade(request) {
9684
+ const { user, starkSigner } = await this.getAuthenticatedUserSigner();
9653
9685
  return createTrade$1({
9654
9686
  request,
9655
- user: this.user,
9656
- starkSigner: this.starkSigner,
9687
+ user,
9688
+ starkSigner,
9657
9689
  tradesApi: this.immutableXClient.tradesApi,
9658
9690
  guardianClient: this.guardianClient,
9659
9691
  });
9660
9692
  }
9661
- batchNftTransfer(request) {
9662
- this.checkIsLoggedIn();
9693
+ async batchNftTransfer(request) {
9694
+ const { user, starkSigner } = await this.getAuthenticatedUserSigner();
9663
9695
  return batchNftTransfer({
9664
9696
  request,
9665
- user: this.user,
9666
- starkSigner: this.starkSigner,
9697
+ user,
9698
+ starkSigner,
9667
9699
  transfersApi: this.immutableXClient.transfersApi,
9668
9700
  guardianClient: this.guardianClient,
9669
9701
  });
9670
9702
  }
9671
- exchangeTransfer(request) {
9672
- this.checkIsLoggedIn();
9703
+ async exchangeTransfer(request) {
9704
+ const { user, starkSigner } = await this.getAuthenticatedUserSigner();
9673
9705
  return exchangeTransfer$1({
9674
9706
  request,
9675
- user: this.user,
9676
- starkSigner: this.starkSigner,
9707
+ user,
9708
+ starkSigner,
9677
9709
  exchangesApi: this.immutableXClient.exchangeApi,
9678
9710
  });
9679
9711
  }
@@ -9696,9 +9728,9 @@ class PassportImxProvider {
9696
9728
  token) {
9697
9729
  throw new PassportError('Operation not supported', PassportErrorType.OPERATION_NOT_SUPPORTED_ERROR);
9698
9730
  }
9699
- getAddress() {
9700
- this.checkIsLoggedIn();
9701
- return Promise.resolve(this.user.imx.ethAddress);
9731
+ async getAddress() {
9732
+ const { user } = await this.getAuthenticatedUserSigner();
9733
+ return Promise.resolve(user.imx.ethAddress);
9702
9734
  }
9703
9735
  }
9704
9736
 
@@ -9752,9 +9784,9 @@ class PassportImxProviderFactory {
9752
9784
  const ethSigner = web3Provider.getSigner();
9753
9785
  const starkSigner = await getStarkSigner(ethSigner);
9754
9786
  if (!user.imx?.ethAddress) {
9755
- const userImx = await this.registerStarkEx(ethSigner, starkSigner, user.accessToken);
9787
+ await this.registerStarkEx(ethSigner, starkSigner, user.accessToken);
9756
9788
  return new PassportImxProvider({
9757
- user: userImx,
9789
+ authManager: this.authManager,
9758
9790
  starkSigner,
9759
9791
  immutableXClient: this.immutableXClient,
9760
9792
  confirmationScreen: this.confirmationScreen,
@@ -9763,7 +9795,7 @@ class PassportImxProviderFactory {
9763
9795
  });
9764
9796
  }
9765
9797
  return new PassportImxProvider({
9766
- user: user,
9798
+ authManager: this.authManager,
9767
9799
  starkSigner,
9768
9800
  immutableXClient: this.immutableXClient,
9769
9801
  confirmationScreen: this.confirmationScreen,
@@ -10508,9 +10540,7 @@ class ZkEvmProvider {
10508
10540
  user: this.user,
10509
10541
  });
10510
10542
  this.guardianClient = new GuardianClient({
10511
- accessToken: this.user.accessToken,
10512
10543
  confirmationScreen: this.confirmationScreen,
10513
- imxEtherAddress: this.user.zkEvm.ethAddress,
10514
10544
  config: this.config,
10515
10545
  });
10516
10546
  this.eventEmitter.emit(ProviderEvent.ACCOUNTS_CHANGED, [this.user.zkEvm.ethAddress]);
@@ -28000,10 +28030,8 @@ const quoteReturnMapping = {
28000
28030
  * @param poolB the other pool
28001
28031
  */
28002
28032
  function poolEquals(poolA, poolB) {
28003
- return (poolA === poolB
28004
- || (poolA.token0.equals(poolB.token0)
28005
- && poolA.token1.equals(poolB.token1)
28006
- && poolA.fee === poolB.fee));
28033
+ return (poolA === poolB ||
28034
+ (poolA.token0.equals(poolB.token0) && poolA.token1.equals(poolB.token1) && poolA.fee === poolB.fee));
28007
28035
  }
28008
28036
  async function getERC20Decimals(tokenAddress, provider) {
28009
28037
  const decimalsFunctionSig = ethers.ethers.utils.id('decimals()').substring(0, 10);
@@ -28036,7 +28064,7 @@ function isValidNonZeroAddress(address) {
28036
28064
  }
28037
28065
  const erc20ToUniswapToken = (token) =>
28038
28066
  // eslint-disable-next-line implicit-arrow-linebreak
28039
- new sdkCore.Token(token.chainId, token.address, token.decimals, token.symbol, token.name);
28067
+ new Uniswap__namespace.Token(token.chainId, token.address, token.decimals, token.symbol, token.name);
28040
28068
  const uniswapTokenToERC20 = (token) => ({
28041
28069
  chainId: token.chainId,
28042
28070
  address: token.address,
@@ -28047,7 +28075,7 @@ const uniswapTokenToERC20 = (token) => ({
28047
28075
  });
28048
28076
  const toCurrencyAmount = (amount) => {
28049
28077
  const token = erc20ToUniswapToken(amount.token);
28050
- return sdkCore.CurrencyAmount.fromRawAmount(token, amount.value.toString());
28078
+ return Uniswap__namespace.CurrencyAmount.fromRawAmount(token, amount.value.toString());
28051
28079
  };
28052
28080
  const newAmount = (amount, token) => ({
28053
28081
  value: amount,
@@ -28093,6 +28121,28 @@ const subtractAmount = (a, b) => {
28093
28121
  }
28094
28122
  throw new Error('Token mismatch: token types must be the same');
28095
28123
  };
28124
+ /**
28125
+ * Converts our internal token type which could be ERC20 or Native
28126
+ * into a format consumable by Checkout. They require an address to be
28127
+ * present. We populate the address with empty string if it's Native.
28128
+ * If it's ERC20, we don't need to change it.
28129
+ */
28130
+ const toPublicTokenType = (token) => {
28131
+ if (token.type === 'native') {
28132
+ return {
28133
+ address: '',
28134
+ chainId: token.chainId,
28135
+ decimals: token.decimals,
28136
+ symbol: token.symbol,
28137
+ name: token.name,
28138
+ };
28139
+ }
28140
+ return token;
28141
+ };
28142
+ const toPublicAmount = (amount) => ({
28143
+ token: toPublicTokenType(amount.token),
28144
+ value: amount.value,
28145
+ });
28096
28146
 
28097
28147
  const amountIndex = 0;
28098
28148
  const gasEstimateIndex = 3;
@@ -28134,8 +28184,8 @@ async function getQuotesForRoutes(multicallContract, quoterContractAddress, rout
28134
28184
  const output = uniswapTokenToERC20(routes[i].output);
28135
28185
  decodedQuoteResults.push({
28136
28186
  route: routes[i],
28137
- amountIn: tradeType === sdkCore.TradeType.EXACT_INPUT ? amountSpecified : newAmount(quoteAmount, input),
28138
- amountOut: tradeType === sdkCore.TradeType.EXACT_INPUT ? newAmount(quoteAmount, output) : amountSpecified,
28187
+ amountIn: tradeType === Uniswap.TradeType.EXACT_INPUT ? amountSpecified : newAmount(quoteAmount, input),
28188
+ amountOut: tradeType === Uniswap.TradeType.EXACT_INPUT ? newAmount(quoteAmount, output) : amountSpecified,
28139
28189
  gasEstimate: ethers.ethers.BigNumber.from(decodedQuoteResult[gasEstimateIndex]),
28140
28190
  tradeType,
28141
28191
  });
@@ -28308,11 +28358,11 @@ class Router {
28308
28358
  throw new NoRoutesAvailableError();
28309
28359
  }
28310
28360
  // We want to maximise the amountOut for the EXACT_INPUT type
28311
- if (tradeType === sdkCore.TradeType.EXACT_INPUT) {
28361
+ if (tradeType === Uniswap.TradeType.EXACT_INPUT) {
28312
28362
  return this.bestQuoteForAmountIn(quotes);
28313
28363
  }
28314
28364
  // We want to minimise the amountIn for the EXACT_OUTPUT type
28315
- if (tradeType === sdkCore.TradeType.EXACT_OUTPUT) {
28365
+ if (tradeType === Uniswap.TradeType.EXACT_OUTPUT) {
28316
28366
  return this.bestQuoteForAmountOut(quotes);
28317
28367
  }
28318
28368
  throw new Error('Invalid trade type');
@@ -28340,7 +28390,7 @@ class Router {
28340
28390
  // eslint-disable-next-line class-methods-use-this
28341
28391
  determineERC20InAndERC20Out(tradeType, amountSpecified, otherToken) {
28342
28392
  // If the trade type is EXACT INPUT then we have specified the amount for the tokenIn
28343
- return tradeType === sdkCore.TradeType.EXACT_INPUT
28393
+ return tradeType === Uniswap.TradeType.EXACT_INPUT
28344
28394
  ? [amountSpecified.token, otherToken]
28345
28395
  : [otherToken, amountSpecified.token];
28346
28396
  }
@@ -28467,7 +28517,7 @@ const getUnsignedERC20ApproveTransaction = (ownerAddress, tokenAmount, spenderAd
28467
28517
  };
28468
28518
  };
28469
28519
  const prepareApproval = (tradeType, amountSpecified, amountWithSlippage, contracts, secondaryFees) => {
28470
- const amountOfTokenIn = tradeType === sdkCore.TradeType.EXACT_INPUT ? amountSpecified : amountWithSlippage;
28520
+ const amountOfTokenIn = tradeType === Uniswap.TradeType.EXACT_INPUT ? amountSpecified : amountWithSlippage;
28471
28521
  const spender = secondaryFees.length === 0
28472
28522
  ? contracts.routerAddress
28473
28523
  : contracts.secondaryFeeAddress;
@@ -28503,7 +28553,7 @@ async function getApproveGasEstimate(provider, ownerAddress, spenderAddress, tok
28503
28553
  from: ownerAddress,
28504
28554
  });
28505
28555
  }
28506
- const getApproval = async (provider, ownerAddress, preparedApproval, gasPrice, nativeTokenService) => {
28556
+ const getApproval = async (provider, ownerAddress, preparedApproval, gasPrice) => {
28507
28557
  const approveTransaction = await getApproveTransaction(provider, ownerAddress, preparedApproval.amount, preparedApproval.spender);
28508
28558
  if (!approveTransaction) {
28509
28559
  return null;
@@ -28512,8 +28562,7 @@ const getApproval = async (provider, ownerAddress, preparedApproval, gasPrice, n
28512
28562
  const gasFeeEstimate = gasPrice ? calculateGasFee(gasPrice, gasEstimate) : null;
28513
28563
  return {
28514
28564
  transaction: approveTransaction,
28515
- // TODO: TP-1649: Remove the wrapping here
28516
- gasFeeEstimate: gasFeeEstimate ? nativeTokenService.maybeWrapAmount(gasFeeEstimate) : null,
28565
+ gasFeeEstimate: gasFeeEstimate ? toPublicAmount(gasFeeEstimate) : null,
28517
28566
  };
28518
28567
  };
28519
28568
 
@@ -28523,7 +28572,7 @@ const slippageToFraction = (slippage) => {
28523
28572
  // If we receive a whole number, we can return slippage/100
28524
28573
  const noDecimals = slippage.toString().split('.').length === 1;
28525
28574
  if (noDecimals) {
28526
- return new sdkCore.Percent(slippage, 100);
28575
+ return new Uniswap.Percent(slippage, 100);
28527
28576
  }
28528
28577
  // Divide the slippage number by 100 to get the decimal
28529
28578
  const slippageDecimal = slippage / 100;
@@ -28533,11 +28582,11 @@ const slippageToFraction = (slippage) => {
28533
28582
  const numerator = parts[0] + parts[1];
28534
28583
  // Get the denominator by multiplying decimals^10
28535
28584
  const denominator = 10 ** parts[1].length;
28536
- return new sdkCore.Percent(numerator, denominator);
28585
+ return new Uniswap.Percent(numerator, denominator);
28537
28586
  };
28538
28587
 
28539
28588
  function getQuoteAmountFromTradeType(tradeInfo) {
28540
- if (tradeInfo.tradeType === sdkCore.TradeType.EXACT_INPUT) {
28589
+ if (tradeInfo.tradeType === Uniswap.TradeType.EXACT_INPUT) {
28541
28590
  return tradeInfo.amountOut;
28542
28591
  }
28543
28592
  return tradeInfo.amountIn;
@@ -28545,29 +28594,13 @@ function getQuoteAmountFromTradeType(tradeInfo) {
28545
28594
  function applySlippage(tradeType, amount, slippage) {
28546
28595
  const slippageTolerance = slippageToFraction(slippage);
28547
28596
  const slippagePlusOne = slippageTolerance.add(1);
28548
- const maybeInverted = tradeType === sdkCore.TradeType.EXACT_INPUT ? slippagePlusOne.invert() : slippagePlusOne;
28597
+ const maybeInverted = tradeType === Uniswap.TradeType.EXACT_INPUT ? slippagePlusOne.invert() : slippagePlusOne;
28549
28598
  const amountWithSlippage = maybeInverted.multiply(amount.toString()).quotient;
28550
28599
  return ethers.ethers.BigNumber.from(amountWithSlippage.toString());
28551
28600
  }
28552
- function prepareUserQuote(otherToken, tradeInfo, slippage, fees, nativeTokenService) {
28553
- const quote = getQuoteAmountFromTradeType(tradeInfo);
28554
- const amountWithSlippage = applySlippage(tradeInfo.tradeType, quote.value, slippage);
28555
- return {
28556
- amount: quote,
28557
- amountWithMaxSlippage: {
28558
- token: otherToken,
28559
- value: amountWithSlippage,
28560
- },
28561
- slippage,
28562
- fees: fees.withAmounts().map((fee) => ({
28563
- ...fee,
28564
- amount: nativeTokenService.maybeWrapAmount(fee.amount),
28565
- })),
28566
- };
28567
- }
28568
28601
  function getOurQuoteReqAmount(amountSpecified, // the amount specified by the user, either exactIn or exactOut
28569
28602
  fees, tradeType, nativeTokenService) {
28570
- if (tradeType === sdkCore.TradeType.EXACT_OUTPUT) {
28603
+ if (tradeType === Uniswap.TradeType.EXACT_OUTPUT) {
28571
28604
  // For an exact output swap, we do not need to subtract fees from the given amount
28572
28605
  return nativeTokenService.maybeWrapAmount(amountSpecified);
28573
28606
  }
@@ -28640,11 +28673,14 @@ class NativeTokenService {
28640
28673
  this.wrappedToken = wrappedToken;
28641
28674
  }
28642
28675
  wrapAmount(amount) {
28676
+ if (!this.isNativeToken(amount.token)) {
28677
+ throw new Error(`cannot wrap non-native token: ${amount.token.address}`);
28678
+ }
28643
28679
  return newAmount(amount.value, this.wrappedToken);
28644
28680
  }
28645
28681
  unwrapAmount(amount) {
28646
28682
  if (amount.token !== this.wrappedToken) {
28647
- throw new Error(`token ${amount.token.address} is not wrapped`);
28683
+ throw new Error(`cannot unwrap non-wrapped token ${amount.token.address}`);
28648
28684
  }
28649
28685
  return newAmount(amount.value, this.nativeToken);
28650
28686
  }
@@ -28664,14 +28700,6 @@ class NativeTokenService {
28664
28700
 
28665
28701
  const IMMUTABLE_TESTNET_RPC_URL = 'https://rpc.testnet.immutable.com';
28666
28702
  const IMMUTABLE_TESTNET_CHAIN_ID = 13472;
28667
-
28668
- const NATIVE_IMX_IMMUTABLE_TESTNET = {
28669
- chainId: IMMUTABLE_TESTNET_CHAIN_ID,
28670
- decimals: 18,
28671
- symbol: 'tIMX',
28672
- name: 'Immutable Testnet Token',
28673
- type: 'native',
28674
- };
28675
28703
  const TIMX_IMMUTABLE_TESTNET = {
28676
28704
  chainId: IMMUTABLE_TESTNET_CHAIN_ID,
28677
28705
  address: '0x0000000000000000000000000000000000001010',
@@ -28700,7 +28728,7 @@ function buildSwapParametersForSinglePoolSwap(fromAddress, trade, route, amountI
28700
28728
  feeBasisPoints: fee.basisPoints,
28701
28729
  recipient: fee.recipient,
28702
28730
  }));
28703
- if (trade.tradeType === sdkCore.TradeType.EXACT_INPUT) {
28731
+ if (trade.tradeType === Uniswap.TradeType.EXACT_INPUT) {
28704
28732
  return secondaryFeeContract.encodeFunctionData('exactInputSingleWithSecondaryFee', [secondaryFeeValues, {
28705
28733
  tokenIn: route.tokenPath[0].address,
28706
28734
  tokenOut: route.tokenPath[1].address,
@@ -28722,12 +28750,12 @@ function buildSwapParametersForSinglePoolSwap(fromAddress, trade, route, amountI
28722
28750
  }]);
28723
28751
  }
28724
28752
  function buildSwapParametersForMultiPoolSwap(fromAddress, trade, route, amountIn, amountOut, secondaryFees, secondaryFeeContract) {
28725
- const path = v3Sdk.encodeRouteToPath(route, trade.tradeType === sdkCore.TradeType.EXACT_OUTPUT);
28753
+ const path = v3Sdk.encodeRouteToPath(route, trade.tradeType === Uniswap.TradeType.EXACT_OUTPUT);
28726
28754
  const secondaryFeeValues = secondaryFees.map((fee) => ({
28727
28755
  feeBasisPoints: fee.basisPoints,
28728
28756
  recipient: fee.recipient,
28729
28757
  }));
28730
- if (trade.tradeType === sdkCore.TradeType.EXACT_INPUT) {
28758
+ if (trade.tradeType === Uniswap.TradeType.EXACT_INPUT) {
28731
28759
  return secondaryFeeContract.encodeFunctionData('exactInputWithSecondaryFee', [secondaryFeeValues, {
28732
28760
  path,
28733
28761
  recipient: fromAddress,
@@ -28803,7 +28831,7 @@ function getSwap(adjustedQuote, fromAddress, slippage, deadline, peripheryRouter
28803
28831
  };
28804
28832
  }
28805
28833
  const adjustAmountIn = (ourQuote, amountSpecified, fees, nativeTokenService) => {
28806
- if (ourQuote.tradeType === sdkCore.TradeType.EXACT_OUTPUT) {
28834
+ if (ourQuote.tradeType === Uniswap.TradeType.EXACT_OUTPUT) {
28807
28835
  // when doing exact output, calculate the fees based on the amountIn
28808
28836
  const amountToAdd = nativeTokenService.isNativeToken(fees.token)
28809
28837
  ? nativeTokenService.unwrapAmount(ourQuote.amountIn)
@@ -28849,7 +28877,7 @@ const SUPPORTED_SANDBOX_CHAINS = {
28849
28877
  rpcUrl: IMMUTABLE_TESTNET_RPC_URL,
28850
28878
  contracts: CONTRACTS_FOR_CHAIN_ID[IMMUTABLE_TESTNET_CHAIN_ID],
28851
28879
  commonRoutingTokens: IMMUTABLE_TESTNET_COMMON_ROUTING_TOKENS,
28852
- nativeToken: NATIVE_IMX_IMMUTABLE_TESTNET,
28880
+ nativeToken: TIMX_IMMUTABLE_TESTNET,
28853
28881
  wrappedNativeToken: TIMX_IMMUTABLE_TESTNET, // TODO: TP-1649: Change to WIMX when ready.
28854
28882
  },
28855
28883
  };
@@ -28921,6 +28949,15 @@ class ExchangeConfiguration {
28921
28949
  }
28922
28950
  }
28923
28951
 
28952
+ const toPublicQuote = (amount, amountWithMaxSlippage, slippage, fees) => ({
28953
+ amount,
28954
+ amountWithMaxSlippage,
28955
+ slippage,
28956
+ fees: fees.withAmounts().map((fee) => ({
28957
+ ...fee,
28958
+ amount: toPublicAmount(fee.amount),
28959
+ })),
28960
+ });
28924
28961
  class Exchange {
28925
28962
  provider;
28926
28963
  router;
@@ -28989,7 +29026,7 @@ class Exchange {
28989
29026
  decimals: tokenOutDecimals,
28990
29027
  };
28991
29028
  // determine which amount was specified for the swap from the TradeType
28992
- const [tokenSpecified, otherToken] = tradeType === sdkCore.TradeType.EXACT_INPUT ? [tokenIn, tokenOut] : [tokenOut, tokenIn];
29029
+ const [tokenSpecified, otherToken] = tradeType === Uniswap.TradeType.EXACT_INPUT ? [tokenIn, tokenOut] : [tokenOut, tokenIn];
28993
29030
  const amountSpecified = newAmount(amount, tokenSpecified);
28994
29031
  const fees = new Fees(secondaryFees, tokenIn);
28995
29032
  const ourQuoteReqAmount = getOurQuoteReqAmount(amountSpecified, fees, tradeType, this.nativeTokenService);
@@ -29000,18 +29037,16 @@ class Exchange {
29000
29037
  ]);
29001
29038
  const adjustedQuote = adjustQuoteWithFees(ourQuote, amountSpecified, fees, this.nativeTokenService);
29002
29039
  const swap = getSwap(adjustedQuote, fromAddress, slippagePercent, deadline, this.routerContractAddress, this.secondaryFeeContractAddress, gasPrice, secondaryFees, this.nativeTokenService);
29003
- const userQuote = prepareUserQuote(otherToken, adjustedQuote, slippagePercent, fees, this.nativeTokenService);
29004
- const preparedApproval = prepareApproval(tradeType, amountSpecified, userQuote.amountWithMaxSlippage, {
29040
+ const quotedAmount = getQuoteAmountFromTradeType(adjustedQuote);
29041
+ const amountWithMaxSlippage = newAmount(applySlippage(adjustedQuote.tradeType, quotedAmount.value, slippagePercent), otherToken);
29042
+ const preparedApproval = prepareApproval(tradeType, amountSpecified, amountWithMaxSlippage, {
29005
29043
  routerAddress: this.routerContractAddress,
29006
29044
  secondaryFeeAddress: this.secondaryFeeContractAddress,
29007
29045
  }, secondaryFees);
29008
29046
  // preparedApproval always uses the tokenIn address because we are always selling the tokenIn
29009
- const approval = await getApproval(this.provider, fromAddress, preparedApproval, gasPrice, this.nativeTokenService);
29010
- return {
29011
- approval,
29012
- swap,
29013
- quote: userQuote,
29014
- };
29047
+ const approval = await getApproval(this.provider, fromAddress, preparedApproval, gasPrice);
29048
+ const quote = toPublicQuote(quotedAmount, amountWithMaxSlippage, slippagePercent, fees);
29049
+ return { quote, approval, swap };
29015
29050
  }
29016
29051
  /**
29017
29052
  * Get the unsigned swap transaction given the amount to sell.
@@ -29027,7 +29062,7 @@ class Exchange {
29027
29062
  * @return {TransactionResponse} The result containing the unsigned transaction and details of the swap.
29028
29063
  */
29029
29064
  async getUnsignedSwapTxFromAmountIn(fromAddress, tokenInAddress, tokenOutAddress, amountIn, slippagePercent = DEFAULT_SLIPPAGE, maxHops = DEFAULT_MAX_HOPS, deadline = DEFAULT_DEADLINE) {
29030
- return await this.getUnsignedSwapTx(fromAddress, tokenInAddress, tokenOutAddress, ethers.ethers.BigNumber.from(amountIn), slippagePercent, maxHops, deadline, sdkCore.TradeType.EXACT_INPUT);
29065
+ return await this.getUnsignedSwapTx(fromAddress, tokenInAddress, tokenOutAddress, ethers.ethers.BigNumber.from(amountIn), slippagePercent, maxHops, deadline, Uniswap.TradeType.EXACT_INPUT);
29031
29066
  }
29032
29067
  /**
29033
29068
  * Get the unsigned swap transaction given the amount to buy.
@@ -29043,7 +29078,7 @@ class Exchange {
29043
29078
  * @return {TransactionResponse} The result containing the unsigned transaction and details of the swap.
29044
29079
  */
29045
29080
  async getUnsignedSwapTxFromAmountOut(fromAddress, tokenInAddress, tokenOutAddress, amountOut, slippagePercent = DEFAULT_SLIPPAGE, maxHops = DEFAULT_MAX_HOPS, deadline = DEFAULT_DEADLINE) {
29046
- return await this.getUnsignedSwapTx(fromAddress, tokenInAddress, tokenOutAddress, ethers.ethers.BigNumber.from(amountOut), slippagePercent, maxHops, deadline, sdkCore.TradeType.EXACT_OUTPUT);
29081
+ return await this.getUnsignedSwapTx(fromAddress, tokenInAddress, tokenOutAddress, ethers.ethers.BigNumber.from(amountOut), slippagePercent, maxHops, deadline, Uniswap.TradeType.EXACT_OUTPUT);
29047
29082
  }
29048
29083
  }
29049
29084
 
@@ -33203,7 +33238,7 @@ var $045213b18e9f1f94$export$75be0f6af9650f2c;
33203
33238
  })($045213b18e9f1f94$export$75be0f6af9650f2c || ($045213b18e9f1f94$export$75be0f6af9650f2c = {}));
33204
33239
 
33205
33240
 
33206
- const $d663162fd5a0853f$export$38a083d9fb5551ca = "0.27.9";
33241
+ const $d663162fd5a0853f$export$38a083d9fb5551ca = "0.27.10";
33207
33242
  const $d663162fd5a0853f$export$83bf90b30cdfd29f = ()=>false;
33208
33243
  const $d663162fd5a0853f$export$1169f5475725171b = ()=>$d663162fd5a0853f$export$38a083d9fb5551ca;
33209
33244