@imtbl/sdk 0.33.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import globalAxios$1, { isAxiosError as isAxiosError$1, AxiosError as AxiosError$1, HttpStatusCode as HttpStatusCode$2 } from 'axios';
2
2
  import { ImmutableX, Config, IMXError, createStarkSigner, generateLegacyStarkPrivateKey, TransfersApi, OrdersApi as OrdersApi$1, UsersApi, Contracts, TradesApi, ExchangesApi, WithdrawalsApi, MintsApi, DepositsApi, EncodingApi, TokensApi as TokensApi$1 } from '@imtbl/core-sdk';
3
- import { UserManager, InMemoryWebStorage, WebStorageStateStore } from 'oidc-client-ts';
3
+ import { UserManager, User, InMemoryWebStorage, WebStorageStateStore } from 'oidc-client-ts';
4
4
  import jwt_decode from 'jwt-decode';
5
5
  import * as crypto from 'crypto';
6
6
  import { Magic } from 'magic-sdk';
@@ -3769,7 +3769,7 @@ class MultiRollupApiClients {
3769
3769
  }
3770
3770
 
3771
3771
  // eslint-disable-next-line @typescript-eslint/naming-convention
3772
- const defaultHeaders$1 = { 'x-sdk-version': 'ts-immutable-sdk-0.33.0' };
3772
+ const defaultHeaders$1 = { 'x-sdk-version': 'ts-immutable-sdk-0.34.0' };
3773
3773
  const createConfig = ({ basePath, headers, }) => {
3774
3774
  if (!basePath.trim()) {
3775
3775
  throw Error('basePath can not be empty');
@@ -3829,7 +3829,7 @@ class APIError extends Error {
3829
3829
 
3830
3830
  /* eslint-disable implicit-arrow-linebreak */
3831
3831
  const defaultHeaders = {
3832
- sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-0.33.0',
3832
+ sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-0.34.0',
3833
3833
  };
3834
3834
  /**
3835
3835
  * createAPIConfiguration to create a custom Configuration
@@ -4240,7 +4240,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
4240
4240
  chainID,
4241
4241
  coreContractAddress,
4242
4242
  registrationContractAddress,
4243
- sdkVersion: 'ts-immutable-sdk-0.33.0',
4243
+ sdkVersion: 'ts-immutable-sdk-0.34.0',
4244
4244
  });
4245
4245
  /**
4246
4246
  * Sets `sdkVersion` at the time of build
@@ -8790,26 +8790,10 @@ var ChainName$1;
8790
8790
  ChainName["IMTBL_ZKEVM_MAINNET"] = "Immutable zkEVM";
8791
8791
  })(ChainName$1 || (ChainName$1 = {}));
8792
8792
 
8793
- const keyCrendentials = 'passport_credentials';
8794
8793
  const KEY_PKCE_STATE = 'pkce_state';
8795
8794
  const KEY_PKCE_VERIFIER = 'pkce_verifier';
8796
8795
  const validCredentialsMinTtlSec = 3600; // 1 hour
8797
8796
  class DeviceCredentialsManager {
8798
- saveCredentials(tokenResponse) {
8799
- if (this.areValid(tokenResponse)) {
8800
- localStorage.setItem(keyCrendentials, JSON.stringify(tokenResponse));
8801
- }
8802
- else {
8803
- throw Error('Invalid credentials.');
8804
- }
8805
- }
8806
- getCredentials() {
8807
- const credentialsJson = localStorage.getItem(keyCrendentials);
8808
- if (credentialsJson) {
8809
- return JSON.parse(credentialsJson);
8810
- }
8811
- return null;
8812
- }
8813
8797
  areValid(tokenResponse) {
8814
8798
  if (tokenResponse) {
8815
8799
  const accessTokenValid = this.isTokenValid(tokenResponse.access_token);
@@ -8829,9 +8813,6 @@ class DeviceCredentialsManager {
8829
8813
  return false;
8830
8814
  }
8831
8815
  }
8832
- clearCredentials() {
8833
- localStorage.removeItem(keyCrendentials);
8834
- }
8835
8816
  savePKCEData(data) {
8836
8817
  localStorage.setItem(KEY_PKCE_STATE, data.state);
8837
8818
  localStorage.setItem(KEY_PKCE_VERIFIER, data.verifier);
@@ -8867,9 +8848,14 @@ const formUrlEncodedHeader = {
8867
8848
  'Content-Type': 'application/x-www-form-urlencoded',
8868
8849
  },
8869
8850
  };
8870
- const getAuthConfiguration = ({ oidcConfiguration, authenticationDomain, }) => {
8851
+ const getAuthConfiguration = (config) => {
8852
+ const { authenticationDomain, oidcConfiguration } = config;
8871
8853
  const store = typeof window !== 'undefined' ? window.localStorage : new InMemoryWebStorage();
8872
8854
  const userStore = new WebStorageStateStore({ store });
8855
+ let endSessionEndpoint = `${authenticationDomain}/v2/logout?client_id=${oidcConfiguration.clientId}`;
8856
+ if (oidcConfiguration.logoutRedirectUri) {
8857
+ endSessionEndpoint += `&returnTo=${encodeURIComponent(oidcConfiguration.logoutRedirectUri)}`;
8858
+ }
8873
8859
  const baseConfiguration = {
8874
8860
  authority: authenticationDomain,
8875
8861
  redirect_uri: oidcConfiguration.redirectUri,
@@ -8879,9 +8865,7 @@ const getAuthConfiguration = ({ oidcConfiguration, authenticationDomain, }) => {
8879
8865
  authorization_endpoint: `${authenticationDomain}/authorize`,
8880
8866
  token_endpoint: `${authenticationDomain}/oauth/token`,
8881
8867
  userinfo_endpoint: `${authenticationDomain}/userinfo`,
8882
- end_session_endpoint: `${authenticationDomain}/v2/logout`
8883
- + `?returnTo=${encodeURIComponent(oidcConfiguration.logoutRedirectUri)}`
8884
- + `&client_id=${oidcConfiguration.clientId}`,
8868
+ end_session_endpoint: endSessionEndpoint,
8885
8869
  },
8886
8870
  mergeClaims: true,
8887
8871
  loadUserInfo: true,
@@ -8900,6 +8884,15 @@ function wait$1(ms) {
8900
8884
  setTimeout(resolve, ms);
8901
8885
  });
8902
8886
  }
8887
+ function base64URLEncode(str) {
8888
+ return str.toString('base64')
8889
+ .replace(/\+/g, '-')
8890
+ .replace(/\//g, '_')
8891
+ .replace(/=/g, '');
8892
+ }
8893
+ function sha256(buffer) {
8894
+ return crypto.createHash('sha256').update(buffer).digest();
8895
+ }
8903
8896
  class AuthManager {
8904
8897
  userManager;
8905
8898
  config;
@@ -8943,32 +8936,24 @@ class AuthManager {
8943
8936
  }
8944
8937
  return user;
8945
8938
  };
8946
- static mapDeviceTokenResponseToDomainUserModel = (tokenResponse) => {
8939
+ static mapDeviceTokenResponseToOidcUser = (tokenResponse) => {
8947
8940
  const idTokenPayload = jwt_decode(tokenResponse.id_token);
8948
- const user = {
8949
- idToken: tokenResponse.id_token,
8950
- accessToken: tokenResponse.access_token,
8951
- refreshToken: tokenResponse.refresh_token,
8941
+ return new User({
8942
+ id_token: tokenResponse.id_token,
8943
+ access_token: tokenResponse.access_token,
8944
+ refresh_token: tokenResponse.refresh_token,
8945
+ token_type: tokenResponse.token_type,
8952
8946
  profile: {
8953
8947
  sub: idTokenPayload.sub,
8948
+ iss: idTokenPayload.iss,
8949
+ aud: idTokenPayload.aud,
8950
+ exp: idTokenPayload.exp,
8951
+ iat: idTokenPayload.iat,
8954
8952
  email: idTokenPayload.email,
8955
8953
  nickname: idTokenPayload.nickname,
8954
+ passport: idTokenPayload.passport,
8956
8955
  },
8957
- };
8958
- if (idTokenPayload?.passport?.imx_eth_address) {
8959
- user.imx = {
8960
- ethAddress: idTokenPayload.passport.imx_eth_address,
8961
- starkAddress: idTokenPayload.passport.imx_stark_address,
8962
- userAdminAddress: idTokenPayload.passport.imx_user_admin_address,
8963
- };
8964
- }
8965
- if (idTokenPayload?.passport?.zkevm_eth_address) {
8966
- user.zkEvm = {
8967
- ethAddress: idTokenPayload?.passport?.zkevm_eth_address,
8968
- userAdminAddress: idTokenPayload?.passport?.zkevm_user_admin_address,
8969
- };
8970
- }
8971
- return user;
8956
+ });
8972
8957
  };
8973
8958
  async login() {
8974
8959
  return withPassportError(async () => {
@@ -8998,7 +8983,7 @@ class AuthManager {
8998
8983
  }, PassportErrorType.AUTHENTICATION_ERROR);
8999
8984
  }
9000
8985
  /* eslint-disable no-await-in-loop */
9001
- async connectImxDeviceFlow(deviceCode, interval, timeoutMs) {
8986
+ async loginWithDeviceFlowCallback(deviceCode, interval, timeoutMs) {
9002
8987
  return withPassportError(async () => {
9003
8988
  const startTime = Date.now();
9004
8989
  const loopCondition = true;
@@ -9009,8 +8994,9 @@ class AuthManager {
9009
8994
  await wait$1(interval * 1000);
9010
8995
  try {
9011
8996
  const tokenResponse = await this.getDeviceFlowToken(deviceCode);
9012
- const user = AuthManager.mapDeviceTokenResponseToDomainUserModel(tokenResponse);
9013
- this.deviceCredentialsManager.saveCredentials(tokenResponse);
8997
+ const oidcUser = AuthManager.mapDeviceTokenResponseToOidcUser(tokenResponse);
8998
+ const user = AuthManager.mapOidcUserToDomainModel(oidcUser);
8999
+ await this.userManager.storeUser(oidcUser);
9014
9000
  return user;
9015
9001
  }
9016
9002
  catch (error) {
@@ -9046,20 +9032,11 @@ class AuthManager {
9046
9032
  }, formUrlEncodedHeader);
9047
9033
  return response.data;
9048
9034
  }
9049
- static base64URLEncode(str) {
9050
- return str.toString('base64')
9051
- .replace(/\+/g, '-')
9052
- .replace(/\//g, '_')
9053
- .replace(/=/g, '');
9054
- }
9055
- static sha256(buffer) {
9056
- return crypto.createHash('sha256').update(buffer).digest();
9057
- }
9058
9035
  getPKCEAuthorizationUrl() {
9059
- const verifier = AuthManager.base64URLEncode(crypto.randomBytes(32));
9060
- const challenge = AuthManager.base64URLEncode(AuthManager.sha256(verifier));
9036
+ const verifier = base64URLEncode(crypto.randomBytes(32));
9037
+ const challenge = base64URLEncode(sha256(verifier));
9061
9038
  // https://auth0.com/docs/secure/attack-protection/state-parameters
9062
- const state = AuthManager.base64URLEncode(crypto.randomBytes(32));
9039
+ const state = base64URLEncode(crypto.randomBytes(32));
9063
9040
  this.deviceCredentialsManager.savePKCEData({ state, verifier });
9064
9041
  return `${this.config.authenticationDomain}/authorize?`
9065
9042
  + 'response_type=code'
@@ -9081,8 +9058,9 @@ class AuthManager {
9081
9058
  throw new Error('Provided state does not match stored state');
9082
9059
  }
9083
9060
  const tokenResponse = await this.getPKCEToken(authorizationCode, pkceData.verifier);
9084
- const user = AuthManager.mapDeviceTokenResponseToDomainUserModel(tokenResponse);
9085
- this.deviceCredentialsManager.saveCredentials(tokenResponse);
9061
+ const oidcUser = AuthManager.mapDeviceTokenResponseToOidcUser(tokenResponse);
9062
+ const user = AuthManager.mapOidcUserToDomainModel(oidcUser);
9063
+ await this.userManager.storeUser(oidcUser);
9086
9064
  return user;
9087
9065
  }, PassportErrorType.AUTHENTICATION_ERROR);
9088
9066
  }
@@ -9096,31 +9074,6 @@ class AuthManager {
9096
9074
  }, formUrlEncodedHeader);
9097
9075
  return response.data;
9098
9076
  }
9099
- async connectImxWithCredentials(tokenResponse) {
9100
- return withPassportError(async () => {
9101
- if (this.deviceCredentialsManager.areValid(tokenResponse)) {
9102
- // Credentials exist and are still valid
9103
- return AuthManager.mapDeviceTokenResponseToDomainUserModel(tokenResponse);
9104
- }
9105
- const refreshToken = tokenResponse?.refresh_token ?? null;
9106
- if (refreshToken) {
9107
- // Token is no longer valid, but refresh token can be used to a new one
9108
- const user = await this.refreshToken(refreshToken);
9109
- return user;
9110
- }
9111
- return null;
9112
- }, PassportErrorType.AUTHENTICATION_ERROR);
9113
- }
9114
- async refreshToken(refreshToken) {
9115
- const response = await globalAxios$1.post(`${this.config.authenticationDomain}/oauth/token`, {
9116
- client_id: this.config.oidcConfiguration.clientId,
9117
- grant_type: 'refresh_token',
9118
- refresh_token: refreshToken,
9119
- }, formUrlEncodedHeader);
9120
- const newTokenResponse = response.data;
9121
- this.deviceCredentialsManager.saveCredentials(newTokenResponse);
9122
- return AuthManager.mapDeviceTokenResponseToDomainUserModel(newTokenResponse);
9123
- }
9124
9077
  async logout() {
9125
9078
  return withPassportError(async () => {
9126
9079
  if (this.logoutMode === 'silent') {
@@ -9129,29 +9082,20 @@ class AuthManager {
9129
9082
  return this.userManager.signoutRedirect();
9130
9083
  }, PassportErrorType.LOGOUT_ERROR);
9131
9084
  }
9132
- async logoutSilentCallback(url) {
9133
- return this.userManager.signoutSilentCallback(url);
9134
- }
9135
- async logoutDeviceFlow() {
9136
- return withPassportError(async () => {
9137
- this.deviceCredentialsManager.clearCredentials();
9138
- }, PassportErrorType.LOGOUT_ERROR);
9085
+ async removeUser() {
9086
+ return this.userManager.removeUser();
9139
9087
  }
9140
- /**
9141
- * Get the user from the cache or refresh the token if it's expired.
9142
- * return null if there's no refresh token.
9143
- */
9144
- async getAuthenticatedUser() {
9145
- const oidcUser = await this.userManager.getUser();
9146
- if (!oidcUser)
9147
- return null;
9148
- if (!isTokenExpired(oidcUser)) {
9149
- return AuthManager.mapOidcUserToDomainModel(oidcUser);
9088
+ getDeviceFlowEndSessionEndpoint() {
9089
+ const { authenticationDomain, oidcConfiguration } = this.config;
9090
+ let endSessionEndpoint = `${authenticationDomain}/v2/logout`;
9091
+ if (oidcConfiguration.logoutRedirectUri) {
9092
+ endSessionEndpoint += `?client_id=${oidcConfiguration.clientId}`
9093
+ + `&returnTo=${encodeURIComponent(oidcConfiguration.logoutRedirectUri)}`;
9150
9094
  }
9151
- if (oidcUser.refresh_token) {
9152
- return this.refreshTokenAndUpdatePromise();
9153
- }
9154
- return null;
9095
+ return endSessionEndpoint;
9096
+ }
9097
+ async logoutSilentCallback(url) {
9098
+ return this.userManager.signoutSilentCallback(url);
9155
9099
  }
9156
9100
  async forceUserRefresh() {
9157
9101
  return this.refreshTokenAndUpdatePromise();
@@ -9166,25 +9110,10 @@ class AuthManager {
9166
9110
  // eslint-disable-next-line no-async-promise-executor
9167
9111
  this.refreshingPromise = new Promise(async (resolve, reject) => {
9168
9112
  try {
9169
- if (this.config.crossSdkBridgeEnabled) {
9170
- const tokenResponse = this.checkStoredDeviceFlowCredentials();
9171
- if (tokenResponse) {
9172
- const refreshToken = tokenResponse?.refresh_token ?? null;
9173
- if (refreshToken) {
9174
- const newUser = await this.refreshToken(refreshToken);
9175
- if (newUser) {
9176
- resolve(newUser);
9177
- return;
9178
- }
9179
- }
9180
- }
9181
- }
9182
- else {
9183
- const newOidcUser = await this.userManager.signinSilent();
9184
- if (newOidcUser) {
9185
- resolve(AuthManager.mapOidcUserToDomainModel(newOidcUser));
9186
- return;
9187
- }
9113
+ const newOidcUser = await this.userManager.signinSilent();
9114
+ if (newOidcUser) {
9115
+ resolve(AuthManager.mapOidcUserToDomainModel(newOidcUser));
9116
+ return;
9188
9117
  }
9189
9118
  resolve(null);
9190
9119
  }
@@ -9197,30 +9126,24 @@ class AuthManager {
9197
9126
  });
9198
9127
  return this.refreshingPromise;
9199
9128
  }
9129
+ /**
9130
+ * Get the user from the cache or refresh the token if it's expired.
9131
+ * return null if there's no refresh token.
9132
+ */
9200
9133
  async getUser() {
9201
9134
  return withPassportError(async () => {
9202
- const user = await this.getAuthenticatedUser();
9203
- if (user)
9204
- return user;
9205
- const deviceToken = this.deviceCredentialsManager.getCredentials();
9206
- if (deviceToken) {
9207
- return AuthManager.mapDeviceTokenResponseToDomainUserModel(deviceToken);
9135
+ const oidcUser = await this.userManager.getUser();
9136
+ if (!oidcUser)
9137
+ return null;
9138
+ if (!isTokenExpired(oidcUser)) {
9139
+ return AuthManager.mapOidcUserToDomainModel(oidcUser);
9208
9140
  }
9209
- return null;
9210
- }, PassportErrorType.NOT_LOGGED_IN_ERROR);
9211
- }
9212
- async getUserDeviceFlow() {
9213
- return withPassportError(async () => {
9214
- const deviceToken = this.deviceCredentialsManager.getCredentials();
9215
- if (deviceToken) {
9216
- return AuthManager.mapDeviceTokenResponseToDomainUserModel(deviceToken);
9141
+ if (oidcUser.refresh_token) {
9142
+ return this.refreshTokenAndUpdatePromise();
9217
9143
  }
9218
9144
  return null;
9219
9145
  }, PassportErrorType.NOT_LOGGED_IN_ERROR);
9220
9146
  }
9221
- checkStoredDeviceFlowCredentials() {
9222
- return this.deviceCredentialsManager.getCredentials();
9223
- }
9224
9147
  }
9225
9148
 
9226
9149
  const lazyLoad = (promiseToAwait, initialiseFunction) => promiseToAwait().then(initialiseFunction);
@@ -10055,21 +9978,10 @@ class PassportImxProviderFactory {
10055
9978
  }
10056
9979
  return this.createProviderInstance(user);
10057
9980
  }
10058
- async getProviderWithDeviceFlow(deviceCode, interval, timeoutMs) {
10059
- const user = await this.authManager.connectImxDeviceFlow(deviceCode, interval, timeoutMs);
10060
- return this.createProviderInstance(user);
10061
- }
10062
9981
  async getProviderWithPKCEFlow(authorizationCode, state) {
10063
9982
  const user = await this.authManager.connectImxPKCEFlow(authorizationCode, state);
10064
9983
  return this.createProviderInstance(user);
10065
9984
  }
10066
- async getProviderWithCredentials(tokenResponse) {
10067
- const user = await this.authManager.connectImxWithCredentials(tokenResponse);
10068
- if (!user) {
10069
- return null;
10070
- }
10071
- return this.createProviderInstance(user);
10072
- }
10073
9985
  async createProviderInstance(user) {
10074
9986
  if (!user.idToken) {
10075
9987
  throw new PassportError('Failed to initialise', PassportErrorType.WALLET_CONNECTION_ERROR);
@@ -10113,7 +10025,6 @@ class PassportConfiguration {
10113
10025
  constructor({ baseConfig, overrides, crossSdkBridgeEnabled, ...oidcConfiguration }) {
10114
10026
  validateConfiguration(oidcConfiguration, [
10115
10027
  'clientId',
10116
- 'logoutRedirectUri',
10117
10028
  'redirectUri',
10118
10029
  ]);
10119
10030
  this.oidcConfiguration = oidcConfiguration;
@@ -10588,7 +10499,7 @@ const CHAIN_NAME_MAP = new Map([
10588
10499
  ]);
10589
10500
 
10590
10501
  const MESSAGE_TO_SIGN = 'Only sign this message from Immutable Passport';
10591
- async function registerZkEvmUser({ authManager, config, magicProvider, multiRollupApiClients, accessToken, jsonRpcProvider, }) {
10502
+ async function registerZkEvmUser({ authManager, magicProvider, multiRollupApiClients, accessToken, jsonRpcProvider, }) {
10592
10503
  const web3Provider = new Web3Provider(magicProvider);
10593
10504
  const ethSigner = web3Provider.getSigner();
10594
10505
  const ethereumAddress = await ethSigner.getAddress();
@@ -10611,24 +10522,14 @@ async function registerZkEvmUser({ authManager, config, magicProvider, multiRoll
10611
10522
  catch (error) {
10612
10523
  throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, `Failed to create counterfactual address: ${error}`);
10613
10524
  }
10614
- let user;
10615
- if (config.crossSdkBridgeEnabled) {
10616
- const credentials = authManager.checkStoredDeviceFlowCredentials();
10617
- if (!credentials || !credentials.refresh_token) {
10618
- throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, 'Cross SDK bridge: Failed to refresh user details');
10619
- }
10620
- user = await authManager.refreshToken(credentials.refresh_token);
10621
- }
10622
- else {
10623
- user = await authManager.forceUserRefresh();
10624
- }
10525
+ const user = await authManager.forceUserRefresh();
10625
10526
  if (!user?.zkEvm) {
10626
10527
  throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, 'Failed to refresh user details');
10627
10528
  }
10628
10529
  return user;
10629
10530
  }
10630
10531
 
10631
- const loginZkEvmUser = async ({ authManager, config, magicAdapter, multiRollupApiClients, jsonRpcProvider, }) => {
10532
+ const loginZkEvmUser = async ({ authManager, magicAdapter, multiRollupApiClients, jsonRpcProvider, }) => {
10632
10533
  let user = null;
10633
10534
  try {
10634
10535
  user = await authManager.getUser();
@@ -10638,7 +10539,7 @@ const loginZkEvmUser = async ({ authManager, config, magicAdapter, multiRollupAp
10638
10539
  console.warn('eth_requestAccounts` failed to retrieve a cached user session:', err);
10639
10540
  }
10640
10541
  if (!user) {
10641
- user = await authManager.getUserDeviceFlow() || await authManager.login();
10542
+ user = await authManager.login();
10642
10543
  }
10643
10544
  if (!user.idToken) {
10644
10545
  throw new Error('User is missing idToken');
@@ -10648,7 +10549,6 @@ const loginZkEvmUser = async ({ authManager, config, magicAdapter, multiRollupAp
10648
10549
  // Generate counterfactual address and retrieve updated Auth0 user
10649
10550
  const userZkevm = await registerZkEvmUser({
10650
10551
  authManager,
10651
- config,
10652
10552
  magicProvider,
10653
10553
  multiRollupApiClients,
10654
10554
  accessToken: user.accessToken,
@@ -11072,24 +10972,12 @@ class Passport {
11072
10972
  async connectImx() {
11073
10973
  return this.passportImxProviderFactory.getProvider();
11074
10974
  }
11075
- async connectImxDeviceFlow(deviceCode, interval, timeoutMs) {
11076
- return this.passportImxProviderFactory.getProviderWithDeviceFlow(deviceCode, interval, timeoutMs);
11077
- }
11078
10975
  getPKCEAuthorizationUrl() {
11079
10976
  return this.authManager.getPKCEAuthorizationUrl();
11080
10977
  }
11081
10978
  async connectImxPKCEFlow(authorizationCode, state) {
11082
10979
  return this.passportImxProviderFactory.getProviderWithPKCEFlow(authorizationCode, state);
11083
10980
  }
11084
- /**
11085
- * @returns {boolean} the stored device flow credentials if they exist
11086
- */
11087
- checkStoredDeviceFlowCredentials() {
11088
- return this.authManager.checkStoredDeviceFlowCredentials();
11089
- }
11090
- async connectImxWithCredentials(tokenResponse) {
11091
- return this.passportImxProviderFactory.getProviderWithCredentials(tokenResponse);
11092
- }
11093
10981
  connectEvm() {
11094
10982
  if (this.config.network === Networks.PRODUCTION) {
11095
10983
  throw new Error('EVM is not supported on production network');
@@ -11129,19 +11017,35 @@ class Passport {
11129
11017
  }
11130
11018
  return user ? user.profile : null;
11131
11019
  }
11020
+ async loginCallback() {
11021
+ return this.authManager.loginCallback();
11022
+ }
11132
11023
  async loginWithDeviceFlow() {
11133
11024
  return this.authManager.loginWithDeviceFlow();
11134
11025
  }
11135
- async loginCallback() {
11136
- return this.authManager.loginCallback();
11026
+ async loginWithDeviceFlowCallback(deviceCode, interval, timeoutMs) {
11027
+ const user = await this.authManager.loginWithDeviceFlowCallback(deviceCode, interval, timeoutMs);
11028
+ return user.profile;
11137
11029
  }
11138
11030
  async logout() {
11139
- await this.authManager.logout();
11140
11031
  await this.confirmationScreen.logout();
11032
+ await this.authManager.logout();
11141
11033
  // Code after this point is only executed if the logout mode is silent
11142
11034
  await this.magicAdapter.logout();
11143
11035
  this.passportEventEmitter.emit(PassportEvents.LOGGED_OUT);
11144
11036
  }
11037
+ /**
11038
+ * Logs the user out of Passport when using device flow authentication.
11039
+ *
11040
+ * @returns {Promise<string>} The device flow end session endpoint. Consumers are responsible for
11041
+ * opening this URL in the same browser that was used to log the user in.
11042
+ */
11043
+ async logoutDeviceFlow() {
11044
+ await this.authManager.removeUser();
11045
+ await this.magicAdapter.logout();
11046
+ this.passportEventEmitter.emit(PassportEvents.LOGGED_OUT);
11047
+ return this.authManager.getDeviceFlowEndSessionEndpoint();
11048
+ }
11145
11049
  /**
11146
11050
  * This method should only be called from the logout redirect uri
11147
11051
  * when logout mode is 'silent'.
@@ -11149,17 +11053,10 @@ class Passport {
11149
11053
  async logoutSilentCallback(url) {
11150
11054
  return this.authManager.logoutSilentCallback(url);
11151
11055
  }
11152
- async logoutDeviceFlow() {
11153
- return this.authManager.logoutDeviceFlow();
11154
- }
11155
11056
  async getUserInfo() {
11156
11057
  const user = await this.authManager.getUser();
11157
11058
  return user?.profile;
11158
11059
  }
11159
- async getUserInfoDeviceFlow() {
11160
- const user = await this.authManager.getUserDeviceFlow();
11161
- return user?.profile;
11162
- }
11163
11060
  async getIdToken() {
11164
11061
  const user = await this.authManager.getUser();
11165
11062
  return user?.idToken;
@@ -11613,7 +11510,7 @@ class OrdersService {
11613
11510
  * @returns ListListingsResult OK response.
11614
11511
  * @throws ApiError
11615
11512
  */
11616
- listListings({ chainName, status, sellItemContractAddress, buyItemContractAddress, sellItemTokenId, fromUpdatedAt, pageSize, sortBy, sortDirection, pageCursor, }) {
11513
+ listListings({ chainName, status, sellItemContractAddress, buyItemContractAddress, accountAddress, sellItemMetadataId, sellItemTokenId, fromUpdatedAt, pageSize, sortBy, sortDirection, pageCursor, }) {
11617
11514
  return this.httpRequest.request({
11618
11515
  method: 'GET',
11619
11516
  url: '/v1/chains/{chain_name}/orders/listings',
@@ -11624,6 +11521,8 @@ class OrdersService {
11624
11521
  'status': status,
11625
11522
  'sell_item_contract_address': sellItemContractAddress,
11626
11523
  'buy_item_contract_address': buyItemContractAddress,
11524
+ 'account_address': accountAddress,
11525
+ 'sell_item_metadata_id': sellItemMetadataId,
11627
11526
  'sell_item_token_id': sellItemTokenId,
11628
11527
  'from_updated_at': fromUpdatedAt,
11629
11528
  'page_size': pageSize,
@@ -28550,6 +28449,21 @@ const getCallData = (methodName, contractInterface) => {
28550
28449
  return fragment ? contractInterface?.encodeFunctionData(fragment) : undefined;
28551
28450
  };
28552
28451
 
28452
+ // 0.1% default slippage
28453
+ const DEFAULT_SLIPPAGE = 0.1;
28454
+ // 15 minutes from the time the transaction was prepared
28455
+ const DEFAULT_DEADLINE_SECONDS = 60 * 15;
28456
+ // most swaps will be able to resolve with 2 hops
28457
+ const DEFAULT_MAX_HOPS = 2;
28458
+ // after 10 hops, it is very unlikely a route will be available
28459
+ const MAX_MAX_HOPS = 10;
28460
+ // a max hop of 1 will require a direct swap with no intermediary pools
28461
+ const MIN_MAX_HOPS = 1;
28462
+ // precision used to calculate percentage from basis points
28463
+ const BASIS_POINT_PRECISION = 10000;
28464
+ // 10% maximum secondary fee
28465
+ const MAX_SECONDARY_FEE_BASIS_POINTS = 1000;
28466
+
28553
28467
  const quoteReturnMapping = {
28554
28468
  // eslint-disable-next-line @typescript-eslint/naming-convention
28555
28469
  '0xcdca1753': ['uint256', 'uint160[]', 'uint32[]', 'uint256'],
@@ -28684,6 +28598,7 @@ const toPublicAmount = (amount) => ({
28684
28598
  token: toPublicTokenType(amount.token),
28685
28599
  value: amount.value,
28686
28600
  });
28601
+ const getDefaultDeadlineSeconds = () => Math.floor(Date.now() / 1000) + DEFAULT_DEADLINE_SECONDS;
28687
28602
 
28688
28603
  const amountIndex = 0;
28689
28604
  const gasEstimateIndex = 3;
@@ -29182,21 +29097,6 @@ fees, tradeType, nativeTokenService) {
29182
29097
  return nativeTokenService.maybeWrapAmount(fees.amountLessFees());
29183
29098
  }
29184
29099
 
29185
- // 0.1% default slippage
29186
- const DEFAULT_SLIPPAGE = 0.1;
29187
- // 15 minutes from the current Unix time
29188
- const DEFAULT_DEADLINE = Math.floor(Date.now() / 1000) + 60 * 15;
29189
- // most swaps will be able to resolve with 2 hops
29190
- const DEFAULT_MAX_HOPS = 2;
29191
- // after 10 hops, it is very unlikely a route will be available
29192
- const MAX_MAX_HOPS = 10;
29193
- // a max hop of 1 will require a direct swap with no intermediary pools
29194
- const MIN_MAX_HOPS = 1;
29195
- // precision used to calculate percentage from basis points
29196
- const BASIS_POINT_PRECISION = 10000;
29197
- // 10% maximum secondary fee
29198
- const MAX_SECONDARY_FEE_BASIS_POINTS = 1000;
29199
-
29200
29100
  class Fees {
29201
29101
  secondaryFees;
29202
29102
  amount;
@@ -29741,7 +29641,7 @@ class Exchange {
29741
29641
  * @param {number} deadline (optional) Latest time swap can execute. Default is 15 minutes
29742
29642
  * @return {TransactionResponse} The result containing the unsigned transaction and details of the swap
29743
29643
  */
29744
- async getUnsignedSwapTxFromAmountIn(fromAddress, tokenInAddress, tokenOutAddress, amountIn, slippagePercent = DEFAULT_SLIPPAGE, maxHops = DEFAULT_MAX_HOPS, deadline = DEFAULT_DEADLINE) {
29644
+ async getUnsignedSwapTxFromAmountIn(fromAddress, tokenInAddress, tokenOutAddress, amountIn, slippagePercent = DEFAULT_SLIPPAGE, maxHops = DEFAULT_MAX_HOPS, deadline = getDefaultDeadlineSeconds()) {
29745
29645
  return await this.getUnsignedSwapTx(fromAddress, tokenInAddress, tokenOutAddress, ethers.BigNumber.from(amountIn), slippagePercent, maxHops, deadline, TradeType.EXACT_INPUT);
29746
29646
  }
29747
29647
  /**
@@ -29757,7 +29657,7 @@ class Exchange {
29757
29657
  * @param {number} deadline (optional) Latest time swap can execute. Default is 15 minutes
29758
29658
  * @return {TransactionResponse} The result containing the unsigned transaction and details of the swap
29759
29659
  */
29760
- async getUnsignedSwapTxFromAmountOut(fromAddress, tokenInAddress, tokenOutAddress, amountOut, slippagePercent = DEFAULT_SLIPPAGE, maxHops = DEFAULT_MAX_HOPS, deadline = DEFAULT_DEADLINE) {
29660
+ async getUnsignedSwapTxFromAmountOut(fromAddress, tokenInAddress, tokenOutAddress, amountOut, slippagePercent = DEFAULT_SLIPPAGE, maxHops = DEFAULT_MAX_HOPS, deadline = getDefaultDeadlineSeconds()) {
29761
29661
  return await this.getUnsignedSwapTx(fromAddress, tokenInAddress, tokenOutAddress, ethers.BigNumber.from(amountOut), slippagePercent, maxHops, deadline, TradeType.EXACT_OUTPUT);
29762
29662
  }
29763
29663
  }
@@ -30650,7 +30550,7 @@ const GAS_OVERRIDES = {
30650
30550
  maxPriorityFeePerGas: BigNumber$1.from(101e9),
30651
30551
  };
30652
30552
 
30653
- const SDK_VERSION_MARKER = '0.33.0';
30553
+ const SDK_VERSION_MARKER = '0.34.0';
30654
30554
  // This SDK version is replaced by the `yarn build` command ran on the root level
30655
30555
  const globalPackageVersion = () => SDK_VERSION_MARKER;
30656
30556
 
@@ -31009,8 +30909,8 @@ const resetBlockscoutClientMap = () => blockscoutClientMap.clear();
31009
30909
  const getIndexerBalance = async (walletAddress, chainId, filterTokens) => {
31010
30910
  // Shuffle the mapping of the tokens configuration so it is a hashmap
31011
30911
  // for faster access to tokens config objects.
31012
- const shouldFilter = filterTokens.length > 0;
31013
- const mapFilterTokens = Object.assign({}, ...(filterTokens.map((t) => ({ [t.address || NATIVE]: t }))));
30912
+ const shouldFilter = filterTokens !== undefined;
30913
+ const mapFilterTokens = Object.assign({}, ...((filterTokens ?? []).map((t) => ({ [t.address || NATIVE]: t }))));
31014
30914
  // Get blockscout client for the given chain
31015
30915
  let blockscoutClient = blockscoutClientMap.get(chainId);
31016
30916
  if (!blockscoutClient) {
@@ -31130,7 +31030,7 @@ const getAllBalances = async (config, web3Provider, walletAddress, chainId) => {
31130
31030
  // Please remove this hack once https://immutable.atlassian.net/browse/WT-1710
31131
31031
  // is done.
31132
31032
  const isL1Chain = getL1ChainId(config) === chainId;
31133
- return await measureAsyncExecution(config, `Time to fetch balances using blockscout for ${chainId}`, getIndexerBalance(walletAddress, chainId, isL1Chain ? tokens : []));
31033
+ return await measureAsyncExecution(config, `Time to fetch balances using blockscout for ${chainId}`, getIndexerBalance(walletAddress, chainId, isL1Chain ? tokens : undefined));
31134
31034
  }
31135
31035
  // This fallback to use ERC20s calls which is a best effort solution
31136
31036
  // Fails in fetching data from the RCP calls might result in some
@@ -1126,7 +1126,7 @@ declare class OrdersService {
1126
1126
  * @returns ListListingsResult OK response.
1127
1127
  * @throws ApiError
1128
1128
  */
1129
- listListings({ chainName, status, sellItemContractAddress, buyItemContractAddress, sellItemTokenId, fromUpdatedAt, pageSize, sortBy, sortDirection, pageCursor, }: {
1129
+ listListings({ chainName, status, sellItemContractAddress, buyItemContractAddress, accountAddress, sellItemMetadataId, sellItemTokenId, fromUpdatedAt, pageSize, sortBy, sortDirection, pageCursor, }: {
1130
1130
  chainName: ChainName;
1131
1131
  /**
1132
1132
  * Order status to filter by
@@ -1140,6 +1140,14 @@ declare class OrdersService {
1140
1140
  * Buy item contract address to filter by
1141
1141
  */
1142
1142
  buyItemContractAddress?: string;
1143
+ /**
1144
+ * The account address of the user who created the listing
1145
+ */
1146
+ accountAddress?: string;
1147
+ /**
1148
+ * The metadata_id of the sell item
1149
+ */
1150
+ sellItemMetadataId?: string;
1143
1151
  /**
1144
1152
  * Sell item token identifier to filter by
1145
1153
  */