@imtbl/sdk 0.27.8 → 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.8' };
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.8',
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.8',
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,25 +28075,74 @@ 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,
28054
28082
  token,
28055
28083
  });
28056
28084
  const isERC20Amount = (amount) => amount.token.type === 'erc20';
28085
+ const isNativeAmount = (amount) => amount.token.type === 'native';
28057
28086
  const addERC20Amount = (a, b) => {
28058
28087
  // Make sure the ERC20s have the same address
28059
28088
  if (a.token.address !== b.token.address)
28060
28089
  throw new Error('Token mismatch: token addresses must be the same');
28061
28090
  return { value: a.value.add(b.value), token: a.token };
28062
28091
  };
28092
+ const addNativeAmount = (a, b) => ({
28093
+ value: a.value.add(b.value),
28094
+ token: a.token,
28095
+ });
28096
+ const addAmount = (a, b) => {
28097
+ if (isERC20Amount(a) && isERC20Amount(b)) {
28098
+ return addERC20Amount(a, b);
28099
+ }
28100
+ if (isNativeAmount(a) && isNativeAmount(b)) {
28101
+ return addNativeAmount(a, b);
28102
+ }
28103
+ throw new Error('Token mismatch: token types must be the same');
28104
+ };
28063
28105
  const subtractERC20Amount = (a, b) => {
28064
28106
  // Make sure the ERC20s have the same address
28065
28107
  if (a.token.address !== b.token.address)
28066
28108
  throw new Error('Token mismatch: token addresses must be the same');
28067
28109
  return { value: a.value.sub(b.value), token: a.token };
28068
28110
  };
28111
+ const subtractNativeAmount = (a, b) => ({
28112
+ value: a.value.sub(b.value),
28113
+ token: a.token,
28114
+ });
28115
+ const subtractAmount = (a, b) => {
28116
+ if (isERC20Amount(a) && isERC20Amount(b)) {
28117
+ return subtractERC20Amount(a, b);
28118
+ }
28119
+ if (isNativeAmount(a) && isNativeAmount(b)) {
28120
+ return subtractNativeAmount(a, b);
28121
+ }
28122
+ throw new Error('Token mismatch: token types must be the same');
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
+ });
28069
28146
 
28070
28147
  const amountIndex = 0;
28071
28148
  const gasEstimateIndex = 3;
@@ -28107,8 +28184,8 @@ async function getQuotesForRoutes(multicallContract, quoterContractAddress, rout
28107
28184
  const output = uniswapTokenToERC20(routes[i].output);
28108
28185
  decodedQuoteResults.push({
28109
28186
  route: routes[i],
28110
- amountIn: tradeType === sdkCore.TradeType.EXACT_INPUT ? amountSpecified : newAmount(quoteAmount, input),
28111
- 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,
28112
28189
  gasEstimate: ethers.ethers.BigNumber.from(decodedQuoteResult[gasEstimateIndex]),
28113
28190
  tradeType,
28114
28191
  });
@@ -28281,11 +28358,11 @@ class Router {
28281
28358
  throw new NoRoutesAvailableError();
28282
28359
  }
28283
28360
  // We want to maximise the amountOut for the EXACT_INPUT type
28284
- if (tradeType === sdkCore.TradeType.EXACT_INPUT) {
28361
+ if (tradeType === Uniswap.TradeType.EXACT_INPUT) {
28285
28362
  return this.bestQuoteForAmountIn(quotes);
28286
28363
  }
28287
28364
  // We want to minimise the amountIn for the EXACT_OUTPUT type
28288
- if (tradeType === sdkCore.TradeType.EXACT_OUTPUT) {
28365
+ if (tradeType === Uniswap.TradeType.EXACT_OUTPUT) {
28289
28366
  return this.bestQuoteForAmountOut(quotes);
28290
28367
  }
28291
28368
  throw new Error('Invalid trade type');
@@ -28313,7 +28390,7 @@ class Router {
28313
28390
  // eslint-disable-next-line class-methods-use-this
28314
28391
  determineERC20InAndERC20Out(tradeType, amountSpecified, otherToken) {
28315
28392
  // If the trade type is EXACT INPUT then we have specified the amount for the tokenIn
28316
- return tradeType === sdkCore.TradeType.EXACT_INPUT
28393
+ return tradeType === Uniswap.TradeType.EXACT_INPUT
28317
28394
  ? [amountSpecified.token, otherToken]
28318
28395
  : [otherToken, amountSpecified.token];
28319
28396
  }
@@ -28439,11 +28516,11 @@ const getUnsignedERC20ApproveTransaction = (ownerAddress, tokenAmount, spenderAd
28439
28516
  from: ownerAddress,
28440
28517
  };
28441
28518
  };
28442
- const prepareApproval = (tradeType, amountSpecified, amountWithSlippage, routingContracts, secondaryFees) => {
28443
- const amountOfTokenIn = tradeType === sdkCore.TradeType.EXACT_INPUT ? amountSpecified : amountWithSlippage;
28519
+ const prepareApproval = (tradeType, amountSpecified, amountWithSlippage, contracts, secondaryFees) => {
28520
+ const amountOfTokenIn = tradeType === Uniswap.TradeType.EXACT_INPUT ? amountSpecified : amountWithSlippage;
28444
28521
  const spender = secondaryFees.length === 0
28445
- ? routingContracts.peripheryRouterAddress
28446
- : routingContracts.secondaryFeeAddress;
28522
+ ? contracts.routerAddress
28523
+ : contracts.secondaryFeeAddress;
28447
28524
  return { spender, amount: amountOfTokenIn };
28448
28525
  };
28449
28526
  /**
@@ -28476,7 +28553,7 @@ async function getApproveGasEstimate(provider, ownerAddress, spenderAddress, tok
28476
28553
  from: ownerAddress,
28477
28554
  });
28478
28555
  }
28479
- const getApproval = async (provider, ownerAddress, preparedApproval, gasPrice, nativeTokenService) => {
28556
+ const getApproval = async (provider, ownerAddress, preparedApproval, gasPrice) => {
28480
28557
  const approveTransaction = await getApproveTransaction(provider, ownerAddress, preparedApproval.amount, preparedApproval.spender);
28481
28558
  if (!approveTransaction) {
28482
28559
  return null;
@@ -28485,8 +28562,7 @@ const getApproval = async (provider, ownerAddress, preparedApproval, gasPrice, n
28485
28562
  const gasFeeEstimate = gasPrice ? calculateGasFee(gasPrice, gasEstimate) : null;
28486
28563
  return {
28487
28564
  transaction: approveTransaction,
28488
- // TODO: TP-1649: Remove the wrapping here
28489
- gasFeeEstimate: gasFeeEstimate ? nativeTokenService.maybeWrapAmount(gasFeeEstimate) : null,
28565
+ gasFeeEstimate: gasFeeEstimate ? toPublicAmount(gasFeeEstimate) : null,
28490
28566
  };
28491
28567
  };
28492
28568
 
@@ -28496,7 +28572,7 @@ const slippageToFraction = (slippage) => {
28496
28572
  // If we receive a whole number, we can return slippage/100
28497
28573
  const noDecimals = slippage.toString().split('.').length === 1;
28498
28574
  if (noDecimals) {
28499
- return new sdkCore.Percent(slippage, 100);
28575
+ return new Uniswap.Percent(slippage, 100);
28500
28576
  }
28501
28577
  // Divide the slippage number by 100 to get the decimal
28502
28578
  const slippageDecimal = slippage / 100;
@@ -28506,11 +28582,11 @@ const slippageToFraction = (slippage) => {
28506
28582
  const numerator = parts[0] + parts[1];
28507
28583
  // Get the denominator by multiplying decimals^10
28508
28584
  const denominator = 10 ** parts[1].length;
28509
- return new sdkCore.Percent(numerator, denominator);
28585
+ return new Uniswap.Percent(numerator, denominator);
28510
28586
  };
28511
28587
 
28512
28588
  function getQuoteAmountFromTradeType(tradeInfo) {
28513
- if (tradeInfo.tradeType === sdkCore.TradeType.EXACT_INPUT) {
28589
+ if (tradeInfo.tradeType === Uniswap.TradeType.EXACT_INPUT) {
28514
28590
  return tradeInfo.amountOut;
28515
28591
  }
28516
28592
  return tradeInfo.amountIn;
@@ -28518,30 +28594,13 @@ function getQuoteAmountFromTradeType(tradeInfo) {
28518
28594
  function applySlippage(tradeType, amount, slippage) {
28519
28595
  const slippageTolerance = slippageToFraction(slippage);
28520
28596
  const slippagePlusOne = slippageTolerance.add(1);
28521
- const maybeInverted = tradeType === sdkCore.TradeType.EXACT_INPUT ? slippagePlusOne.invert() : slippagePlusOne;
28597
+ const maybeInverted = tradeType === Uniswap.TradeType.EXACT_INPUT ? slippagePlusOne.invert() : slippagePlusOne;
28522
28598
  const amountWithSlippage = maybeInverted.multiply(amount.toString()).quotient;
28523
28599
  return ethers.ethers.BigNumber.from(amountWithSlippage.toString());
28524
28600
  }
28525
- function prepareUserQuote(otherToken, tradeInfo, slippage, fees) {
28526
- const quote = getQuoteAmountFromTradeType(tradeInfo);
28527
- const amountWithSlippage = applySlippage(tradeInfo.tradeType, quote.value, slippage);
28528
- return {
28529
- amount: quote,
28530
- amountWithMaxSlippage: {
28531
- token: otherToken,
28532
- value: amountWithSlippage,
28533
- },
28534
- slippage,
28535
- fees: fees.withAmounts(),
28536
- };
28537
- }
28538
28601
  function getOurQuoteReqAmount(amountSpecified, // the amount specified by the user, either exactIn or exactOut
28539
28602
  fees, tradeType, nativeTokenService) {
28540
- // TODO: TP-1649: Remove this when we support Native
28541
- if (!isERC20Amount(amountSpecified)) {
28542
- throw new Error('Not implemented yet!');
28543
- }
28544
- if (tradeType === sdkCore.TradeType.EXACT_OUTPUT) {
28603
+ if (tradeType === Uniswap.TradeType.EXACT_OUTPUT) {
28545
28604
  // For an exact output swap, we do not need to subtract fees from the given amount
28546
28605
  return nativeTokenService.maybeWrapAmount(amountSpecified);
28547
28606
  }
@@ -28571,14 +28630,17 @@ class Fees {
28571
28630
  this.secondaryFees = secondaryFees;
28572
28631
  this.amount = newAmount(ethers.BigNumber.from(0), token);
28573
28632
  }
28633
+ get token() {
28634
+ return this.amount.token;
28635
+ }
28574
28636
  addAmount(amount) {
28575
- this.amount = addERC20Amount(this.amount, amount);
28637
+ this.amount = addAmount(this.amount, amount);
28576
28638
  }
28577
28639
  amountWithFeesApplied() {
28578
- return addERC20Amount(this.amount, this.total());
28640
+ return addAmount(this.amount, this.total());
28579
28641
  }
28580
28642
  amountLessFees() {
28581
- return subtractERC20Amount(this.amount, this.total());
28643
+ return subtractAmount(this.amount, this.total());
28582
28644
  }
28583
28645
  withAmounts() {
28584
28646
  return this.secondaryFees.map((fee) => {
@@ -28597,7 +28659,7 @@ class Fees {
28597
28659
  const feeAmount = this.amount.value
28598
28660
  .mul(fee.basisPoints)
28599
28661
  .div(BASIS_POINT_PRECISION);
28600
- totalFees = addERC20Amount(totalFees, newAmount(feeAmount, this.amount.token));
28662
+ totalFees = addAmount(totalFees, newAmount(feeAmount, this.amount.token));
28601
28663
  }
28602
28664
  return totalFees;
28603
28665
  }
@@ -28611,11 +28673,14 @@ class NativeTokenService {
28611
28673
  this.wrappedToken = wrappedToken;
28612
28674
  }
28613
28675
  wrapAmount(amount) {
28676
+ if (!this.isNativeToken(amount.token)) {
28677
+ throw new Error(`cannot wrap non-native token: ${amount.token.address}`);
28678
+ }
28614
28679
  return newAmount(amount.value, this.wrappedToken);
28615
28680
  }
28616
28681
  unwrapAmount(amount) {
28617
28682
  if (amount.token !== this.wrappedToken) {
28618
- throw new Error(`token ${amount.token.address} is not wrapped`);
28683
+ throw new Error(`cannot unwrap non-wrapped token ${amount.token.address}`);
28619
28684
  }
28620
28685
  return newAmount(amount.value, this.nativeToken);
28621
28686
  }
@@ -28635,14 +28700,6 @@ class NativeTokenService {
28635
28700
 
28636
28701
  const IMMUTABLE_TESTNET_RPC_URL = 'https://rpc.testnet.immutable.com';
28637
28702
  const IMMUTABLE_TESTNET_CHAIN_ID = 13472;
28638
-
28639
- const NATIVE_IMX_IMMUTABLE_TESTNET = {
28640
- chainId: IMMUTABLE_TESTNET_CHAIN_ID,
28641
- decimals: 18,
28642
- symbol: 'tIMX',
28643
- name: 'Immutable Testnet Token',
28644
- type: 'native',
28645
- };
28646
28703
  const TIMX_IMMUTABLE_TESTNET = {
28647
28704
  chainId: IMMUTABLE_TESTNET_CHAIN_ID,
28648
28705
  address: '0x0000000000000000000000000000000000001010',
@@ -28671,7 +28728,7 @@ function buildSwapParametersForSinglePoolSwap(fromAddress, trade, route, amountI
28671
28728
  feeBasisPoints: fee.basisPoints,
28672
28729
  recipient: fee.recipient,
28673
28730
  }));
28674
- if (trade.tradeType === sdkCore.TradeType.EXACT_INPUT) {
28731
+ if (trade.tradeType === Uniswap.TradeType.EXACT_INPUT) {
28675
28732
  return secondaryFeeContract.encodeFunctionData('exactInputSingleWithSecondaryFee', [secondaryFeeValues, {
28676
28733
  tokenIn: route.tokenPath[0].address,
28677
28734
  tokenOut: route.tokenPath[1].address,
@@ -28693,12 +28750,12 @@ function buildSwapParametersForSinglePoolSwap(fromAddress, trade, route, amountI
28693
28750
  }]);
28694
28751
  }
28695
28752
  function buildSwapParametersForMultiPoolSwap(fromAddress, trade, route, amountIn, amountOut, secondaryFees, secondaryFeeContract) {
28696
- const path = v3Sdk.encodeRouteToPath(route, trade.tradeType === sdkCore.TradeType.EXACT_OUTPUT);
28753
+ const path = v3Sdk.encodeRouteToPath(route, trade.tradeType === Uniswap.TradeType.EXACT_OUTPUT);
28697
28754
  const secondaryFeeValues = secondaryFees.map((fee) => ({
28698
28755
  feeBasisPoints: fee.basisPoints,
28699
28756
  recipient: fee.recipient,
28700
28757
  }));
28701
- if (trade.tradeType === sdkCore.TradeType.EXACT_INPUT) {
28758
+ if (trade.tradeType === Uniswap.TradeType.EXACT_INPUT) {
28702
28759
  return secondaryFeeContract.encodeFunctionData('exactInputWithSecondaryFee', [secondaryFeeValues, {
28703
28760
  path,
28704
28761
  recipient: fromAddress,
@@ -28773,21 +28830,33 @@ function getSwap(adjustedQuote, fromAddress, slippage, deadline, peripheryRouter
28773
28830
  gasFeeEstimate: gasFeeEstimate ? nativeTokenService.maybeWrapAmount(gasFeeEstimate) : null,
28774
28831
  };
28775
28832
  }
28776
- function prepareSwap(ourQuote, amountSpecified, fees) {
28777
- if (ourQuote.tradeType === sdkCore.TradeType.EXACT_OUTPUT) {
28778
- fees.addAmount(ourQuote.amountIn);
28779
- return {
28780
- gasEstimate: ourQuote.gasEstimate,
28781
- route: ourQuote.route,
28782
- amountIn: fees.amountWithFeesApplied(),
28783
- amountOut: amountSpecified,
28784
- tradeType: ourQuote.tradeType,
28785
- };
28833
+ const adjustAmountIn = (ourQuote, amountSpecified, fees, nativeTokenService) => {
28834
+ if (ourQuote.tradeType === Uniswap.TradeType.EXACT_OUTPUT) {
28835
+ // when doing exact output, calculate the fees based on the amountIn
28836
+ const amountToAdd = nativeTokenService.isNativeToken(fees.token)
28837
+ ? nativeTokenService.unwrapAmount(ourQuote.amountIn)
28838
+ : ourQuote.amountIn;
28839
+ fees.addAmount(amountToAdd);
28840
+ return nativeTokenService.maybeWrapAmount(fees.amountWithFeesApplied());
28786
28841
  }
28842
+ return nativeTokenService.maybeWrapAmount(amountSpecified);
28843
+ };
28844
+ /**
28845
+ * adjustQuoteWithFees adjusts the amountIn of the quote to account for fees
28846
+ * EXACT_OUTPUT swaps will have the fees added to the amountIn if there are fees specified
28847
+ * EXACT_INPUT swaps will have amountIn set to the user-specified amount
28848
+ * @param ourQuote The quote from calling the Quoter contract
28849
+ * @param amountSpecified The user-specified amount for the swap (EXACT...)
28850
+ * @param fees The fees applied to the swap
28851
+ * @param tokenWrapper Helper class for the native token and associated ERC20
28852
+ * @returns {QuoteResult} The adjusted quote
28853
+ */
28854
+ function adjustQuoteWithFees(ourQuote, amountSpecified, fees, nativeTokenService) {
28855
+ const adjustedAmountIn = adjustAmountIn(ourQuote, amountSpecified, fees, nativeTokenService);
28787
28856
  return {
28788
28857
  gasEstimate: ourQuote.gasEstimate,
28789
28858
  route: ourQuote.route,
28790
- amountIn: amountSpecified,
28859
+ amountIn: adjustedAmountIn,
28791
28860
  amountOut: ourQuote.amountOut,
28792
28861
  tradeType: ourQuote.tradeType,
28793
28862
  };
@@ -28808,7 +28877,7 @@ const SUPPORTED_SANDBOX_CHAINS = {
28808
28877
  rpcUrl: IMMUTABLE_TESTNET_RPC_URL,
28809
28878
  contracts: CONTRACTS_FOR_CHAIN_ID[IMMUTABLE_TESTNET_CHAIN_ID],
28810
28879
  commonRoutingTokens: IMMUTABLE_TESTNET_COMMON_ROUTING_TOKENS,
28811
- nativeToken: NATIVE_IMX_IMMUTABLE_TESTNET,
28880
+ nativeToken: TIMX_IMMUTABLE_TESTNET,
28812
28881
  wrappedNativeToken: TIMX_IMMUTABLE_TESTNET, // TODO: TP-1649: Change to WIMX when ready.
28813
28882
  },
28814
28883
  };
@@ -28880,6 +28949,15 @@ class ExchangeConfiguration {
28880
28949
  }
28881
28950
  }
28882
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
+ });
28883
28961
  class Exchange {
28884
28962
  provider;
28885
28963
  router;
@@ -28888,6 +28966,8 @@ class Exchange {
28888
28966
  wrappedNativeToken;
28889
28967
  secondaryFees;
28890
28968
  nativeTokenService;
28969
+ secondaryFeeContractAddress;
28970
+ routerContractAddress;
28891
28971
  constructor(configuration) {
28892
28972
  const config = new ExchangeConfiguration(configuration);
28893
28973
  this.chainId = config.chain.chainId;
@@ -28895,13 +28975,13 @@ class Exchange {
28895
28975
  this.wrappedNativeToken = config.chain.wrappedNativeToken;
28896
28976
  this.nativeTokenService = new NativeTokenService(this.nativeToken, this.wrappedNativeToken);
28897
28977
  this.secondaryFees = config.secondaryFees;
28978
+ this.routerContractAddress = config.chain.contracts.peripheryRouter;
28979
+ this.secondaryFeeContractAddress = config.chain.contracts.secondaryFee;
28898
28980
  this.provider = new ethers.ethers.providers.JsonRpcProvider(config.chain.rpcUrl);
28899
28981
  this.router = new Router(this.provider, config.chain.commonRoutingTokens, {
28900
28982
  multicallAddress: config.chain.contracts.multicall,
28901
28983
  factoryAddress: config.chain.contracts.coreFactory,
28902
28984
  quoterAddress: config.chain.contracts.quoterV2,
28903
- peripheryRouterAddress: config.chain.contracts.peripheryRouter,
28904
- secondaryFeeAddress: config.chain.contracts.secondaryFee,
28905
28985
  });
28906
28986
  }
28907
28987
  static validate(tokenInAddress, tokenOutAddress, maxHops, slippagePercent, fromAddress) {
@@ -28918,7 +28998,7 @@ class Exchange {
28918
28998
  if (this.secondaryFees.length === 0) {
28919
28999
  return [];
28920
29000
  }
28921
- const secondaryFeeContract = SecondaryFee__factory.connect(this.router.routingContracts.secondaryFeeAddress, this.provider);
29001
+ const secondaryFeeContract = SecondaryFee__factory.connect(this.secondaryFeeContractAddress, this.provider);
28922
29002
  if (await secondaryFeeContract.paused()) {
28923
29003
  // Do not use secondary fees if the contract is paused
28924
29004
  return [];
@@ -28946,8 +29026,7 @@ class Exchange {
28946
29026
  decimals: tokenOutDecimals,
28947
29027
  };
28948
29028
  // determine which amount was specified for the swap from the TradeType
28949
- const [tokenSpecified, otherToken] = tradeType === sdkCore.TradeType.EXACT_INPUT
28950
- ? [tokenIn, tokenOut] : [tokenOut, tokenIn];
29029
+ const [tokenSpecified, otherToken] = tradeType === Uniswap.TradeType.EXACT_INPUT ? [tokenIn, tokenOut] : [tokenOut, tokenIn];
28951
29030
  const amountSpecified = newAmount(amount, tokenSpecified);
28952
29031
  const fees = new Fees(secondaryFees, tokenIn);
28953
29032
  const ourQuoteReqAmount = getOurQuoteReqAmount(amountSpecified, fees, tradeType, this.nativeTokenService);
@@ -28956,17 +29035,18 @@ class Exchange {
28956
29035
  this.router.findOptimalRoute(ourQuoteReqAmount, otherToken, tradeType, maxHops),
28957
29036
  fetchGasPrice(this.provider, this.nativeToken),
28958
29037
  ]);
28959
- const adjustedQuote = prepareSwap(ourQuote, amountSpecified, fees);
28960
- const swap = getSwap(adjustedQuote, fromAddress, slippagePercent, deadline, this.router.routingContracts.peripheryRouterAddress, this.router.routingContracts.secondaryFeeAddress, gasPrice, secondaryFees, this.nativeTokenService);
28961
- const userQuote = prepareUserQuote(otherToken, adjustedQuote, slippagePercent, fees);
28962
- const preparedApproval = prepareApproval(tradeType, amountSpecified, userQuote.amountWithMaxSlippage, this.router.routingContracts, secondaryFees);
29038
+ const adjustedQuote = adjustQuoteWithFees(ourQuote, amountSpecified, fees, this.nativeTokenService);
29039
+ const swap = getSwap(adjustedQuote, fromAddress, slippagePercent, deadline, this.routerContractAddress, this.secondaryFeeContractAddress, gasPrice, secondaryFees, this.nativeTokenService);
29040
+ const quotedAmount = getQuoteAmountFromTradeType(adjustedQuote);
29041
+ const amountWithMaxSlippage = newAmount(applySlippage(adjustedQuote.tradeType, quotedAmount.value, slippagePercent), otherToken);
29042
+ const preparedApproval = prepareApproval(tradeType, amountSpecified, amountWithMaxSlippage, {
29043
+ routerAddress: this.routerContractAddress,
29044
+ secondaryFeeAddress: this.secondaryFeeContractAddress,
29045
+ }, secondaryFees);
28963
29046
  // preparedApproval always uses the tokenIn address because we are always selling the tokenIn
28964
- const approval = await getApproval(this.provider, fromAddress, preparedApproval, gasPrice, this.nativeTokenService);
28965
- return {
28966
- approval,
28967
- swap,
28968
- quote: userQuote,
28969
- };
29047
+ const approval = await getApproval(this.provider, fromAddress, preparedApproval, gasPrice);
29048
+ const quote = toPublicQuote(quotedAmount, amountWithMaxSlippage, slippagePercent, fees);
29049
+ return { quote, approval, swap };
28970
29050
  }
28971
29051
  /**
28972
29052
  * Get the unsigned swap transaction given the amount to sell.
@@ -28982,7 +29062,7 @@ class Exchange {
28982
29062
  * @return {TransactionResponse} The result containing the unsigned transaction and details of the swap.
28983
29063
  */
28984
29064
  async getUnsignedSwapTxFromAmountIn(fromAddress, tokenInAddress, tokenOutAddress, amountIn, slippagePercent = DEFAULT_SLIPPAGE, maxHops = DEFAULT_MAX_HOPS, deadline = DEFAULT_DEADLINE) {
28985
- 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);
28986
29066
  }
28987
29067
  /**
28988
29068
  * Get the unsigned swap transaction given the amount to buy.
@@ -28998,7 +29078,7 @@ class Exchange {
28998
29078
  * @return {TransactionResponse} The result containing the unsigned transaction and details of the swap.
28999
29079
  */
29000
29080
  async getUnsignedSwapTxFromAmountOut(fromAddress, tokenInAddress, tokenOutAddress, amountOut, slippagePercent = DEFAULT_SLIPPAGE, maxHops = DEFAULT_MAX_HOPS, deadline = DEFAULT_DEADLINE) {
29001
- 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);
29002
29082
  }
29003
29083
  }
29004
29084
 
@@ -33158,7 +33238,7 @@ var $045213b18e9f1f94$export$75be0f6af9650f2c;
33158
33238
  })($045213b18e9f1f94$export$75be0f6af9650f2c || ($045213b18e9f1f94$export$75be0f6af9650f2c = {}));
33159
33239
 
33160
33240
 
33161
- const $d663162fd5a0853f$export$38a083d9fb5551ca = "0.27.8";
33241
+ const $d663162fd5a0853f$export$38a083d9fb5551ca = "0.27.10";
33162
33242
  const $d663162fd5a0853f$export$83bf90b30cdfd29f = ()=>false;
33163
33243
  const $d663162fd5a0853f$export$1169f5475725171b = ()=>$d663162fd5a0853f$export$38a083d9fb5551ca;
33164
33244