@imtbl/sdk 0.32.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.cjs CHANGED
@@ -62,7 +62,6 @@ class ImmutableConfiguration {
62
62
  }
63
63
  const API_KEY_PREFIX = 'sk_imapik-';
64
64
  const PUBLISHABLE_KEY_PREFIX = 'pk_imapik-';
65
- const PUBLISHABLE_KEY_LENGTH = 30;
66
65
  const addApiKeyToAxiosHeader = (apiKey) => {
67
66
  if (!apiKey.startsWith(API_KEY_PREFIX)) {
68
67
  throw new Error('Invalid API key. Create your api key in Immutable developer hub. https://hub.immutable.com');
@@ -70,7 +69,7 @@ const addApiKeyToAxiosHeader = (apiKey) => {
70
69
  globalAxios$1.defaults.headers.common['x-immutable-api-key'] = apiKey;
71
70
  };
72
71
  const addPublishableKeyToAxiosHeader = (publishableKey) => {
73
- if (!publishableKey.startsWith(PUBLISHABLE_KEY_PREFIX) || publishableKey.length !== PUBLISHABLE_KEY_LENGTH) {
72
+ if (!publishableKey.startsWith(PUBLISHABLE_KEY_PREFIX)) {
74
73
  throw new Error('Invalid Publishable key. Create your Publishable key in Immutable developer hub.'
75
74
  + ' https://hub.immutable.com');
76
75
  }
@@ -3792,7 +3791,7 @@ class MultiRollupApiClients {
3792
3791
  }
3793
3792
 
3794
3793
  // eslint-disable-next-line @typescript-eslint/naming-convention
3795
- const defaultHeaders$1 = { 'x-sdk-version': 'ts-immutable-sdk-0.32.0' };
3794
+ const defaultHeaders$1 = { 'x-sdk-version': 'ts-immutable-sdk-0.34.0' };
3796
3795
  const createConfig = ({ basePath, headers, }) => {
3797
3796
  if (!basePath.trim()) {
3798
3797
  throw Error('basePath can not be empty');
@@ -3852,7 +3851,7 @@ class APIError extends Error {
3852
3851
 
3853
3852
  /* eslint-disable implicit-arrow-linebreak */
3854
3853
  const defaultHeaders = {
3855
- sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-0.32.0',
3854
+ sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-0.34.0',
3856
3855
  };
3857
3856
  /**
3858
3857
  * createAPIConfiguration to create a custom Configuration
@@ -4263,7 +4262,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
4263
4262
  chainID,
4264
4263
  coreContractAddress,
4265
4264
  registrationContractAddress,
4266
- sdkVersion: 'ts-immutable-sdk-0.32.0',
4265
+ sdkVersion: 'ts-immutable-sdk-0.34.0',
4267
4266
  });
4268
4267
  /**
4269
4268
  * Sets `sdkVersion` at the time of build
@@ -8813,26 +8812,10 @@ var ChainName$1;
8813
8812
  ChainName["IMTBL_ZKEVM_MAINNET"] = "Immutable zkEVM";
8814
8813
  })(ChainName$1 || (ChainName$1 = {}));
8815
8814
 
8816
- const keyCrendentials = 'passport_credentials';
8817
8815
  const KEY_PKCE_STATE = 'pkce_state';
8818
8816
  const KEY_PKCE_VERIFIER = 'pkce_verifier';
8819
8817
  const validCredentialsMinTtlSec = 3600; // 1 hour
8820
8818
  class DeviceCredentialsManager {
8821
- saveCredentials(tokenResponse) {
8822
- if (this.areValid(tokenResponse)) {
8823
- localStorage.setItem(keyCrendentials, JSON.stringify(tokenResponse));
8824
- }
8825
- else {
8826
- throw Error('Invalid credentials.');
8827
- }
8828
- }
8829
- getCredentials() {
8830
- const credentialsJson = localStorage.getItem(keyCrendentials);
8831
- if (credentialsJson) {
8832
- return JSON.parse(credentialsJson);
8833
- }
8834
- return null;
8835
- }
8836
8819
  areValid(tokenResponse) {
8837
8820
  if (tokenResponse) {
8838
8821
  const accessTokenValid = this.isTokenValid(tokenResponse.access_token);
@@ -8852,9 +8835,6 @@ class DeviceCredentialsManager {
8852
8835
  return false;
8853
8836
  }
8854
8837
  }
8855
- clearCredentials() {
8856
- localStorage.removeItem(keyCrendentials);
8857
- }
8858
8838
  savePKCEData(data) {
8859
8839
  localStorage.setItem(KEY_PKCE_STATE, data.state);
8860
8840
  localStorage.setItem(KEY_PKCE_VERIFIER, data.verifier);
@@ -8890,9 +8870,14 @@ const formUrlEncodedHeader = {
8890
8870
  'Content-Type': 'application/x-www-form-urlencoded',
8891
8871
  },
8892
8872
  };
8893
- const getAuthConfiguration = ({ oidcConfiguration, authenticationDomain, }) => {
8873
+ const getAuthConfiguration = (config) => {
8874
+ const { authenticationDomain, oidcConfiguration } = config;
8894
8875
  const store = typeof window !== 'undefined' ? window.localStorage : new oidcClientTs.InMemoryWebStorage();
8895
8876
  const userStore = new oidcClientTs.WebStorageStateStore({ store });
8877
+ let endSessionEndpoint = `${authenticationDomain}/v2/logout?client_id=${oidcConfiguration.clientId}`;
8878
+ if (oidcConfiguration.logoutRedirectUri) {
8879
+ endSessionEndpoint += `&returnTo=${encodeURIComponent(oidcConfiguration.logoutRedirectUri)}`;
8880
+ }
8896
8881
  const baseConfiguration = {
8897
8882
  authority: authenticationDomain,
8898
8883
  redirect_uri: oidcConfiguration.redirectUri,
@@ -8902,9 +8887,7 @@ const getAuthConfiguration = ({ oidcConfiguration, authenticationDomain, }) => {
8902
8887
  authorization_endpoint: `${authenticationDomain}/authorize`,
8903
8888
  token_endpoint: `${authenticationDomain}/oauth/token`,
8904
8889
  userinfo_endpoint: `${authenticationDomain}/userinfo`,
8905
- end_session_endpoint: `${authenticationDomain}/v2/logout`
8906
- + `?returnTo=${encodeURIComponent(oidcConfiguration.logoutRedirectUri)}`
8907
- + `&client_id=${oidcConfiguration.clientId}`,
8890
+ end_session_endpoint: endSessionEndpoint,
8908
8891
  },
8909
8892
  mergeClaims: true,
8910
8893
  loadUserInfo: true,
@@ -8923,6 +8906,15 @@ function wait$1(ms) {
8923
8906
  setTimeout(resolve, ms);
8924
8907
  });
8925
8908
  }
8909
+ function base64URLEncode(str) {
8910
+ return str.toString('base64')
8911
+ .replace(/\+/g, '-')
8912
+ .replace(/\//g, '_')
8913
+ .replace(/=/g, '');
8914
+ }
8915
+ function sha256(buffer) {
8916
+ return crypto__namespace.createHash('sha256').update(buffer).digest();
8917
+ }
8926
8918
  class AuthManager {
8927
8919
  userManager;
8928
8920
  config;
@@ -8966,32 +8958,24 @@ class AuthManager {
8966
8958
  }
8967
8959
  return user;
8968
8960
  };
8969
- static mapDeviceTokenResponseToDomainUserModel = (tokenResponse) => {
8961
+ static mapDeviceTokenResponseToOidcUser = (tokenResponse) => {
8970
8962
  const idTokenPayload = jwt_decode(tokenResponse.id_token);
8971
- const user = {
8972
- idToken: tokenResponse.id_token,
8973
- accessToken: tokenResponse.access_token,
8974
- refreshToken: tokenResponse.refresh_token,
8963
+ return new oidcClientTs.User({
8964
+ id_token: tokenResponse.id_token,
8965
+ access_token: tokenResponse.access_token,
8966
+ refresh_token: tokenResponse.refresh_token,
8967
+ token_type: tokenResponse.token_type,
8975
8968
  profile: {
8976
8969
  sub: idTokenPayload.sub,
8970
+ iss: idTokenPayload.iss,
8971
+ aud: idTokenPayload.aud,
8972
+ exp: idTokenPayload.exp,
8973
+ iat: idTokenPayload.iat,
8977
8974
  email: idTokenPayload.email,
8978
8975
  nickname: idTokenPayload.nickname,
8976
+ passport: idTokenPayload.passport,
8979
8977
  },
8980
- };
8981
- if (idTokenPayload?.passport?.imx_eth_address) {
8982
- user.imx = {
8983
- ethAddress: idTokenPayload.passport.imx_eth_address,
8984
- starkAddress: idTokenPayload.passport.imx_stark_address,
8985
- userAdminAddress: idTokenPayload.passport.imx_user_admin_address,
8986
- };
8987
- }
8988
- if (idTokenPayload?.passport?.zkevm_eth_address) {
8989
- user.zkEvm = {
8990
- ethAddress: idTokenPayload?.passport?.zkevm_eth_address,
8991
- userAdminAddress: idTokenPayload?.passport?.zkevm_user_admin_address,
8992
- };
8993
- }
8994
- return user;
8978
+ });
8995
8979
  };
8996
8980
  async login() {
8997
8981
  return withPassportError(async () => {
@@ -9021,7 +9005,7 @@ class AuthManager {
9021
9005
  }, PassportErrorType.AUTHENTICATION_ERROR);
9022
9006
  }
9023
9007
  /* eslint-disable no-await-in-loop */
9024
- async connectImxDeviceFlow(deviceCode, interval, timeoutMs) {
9008
+ async loginWithDeviceFlowCallback(deviceCode, interval, timeoutMs) {
9025
9009
  return withPassportError(async () => {
9026
9010
  const startTime = Date.now();
9027
9011
  const loopCondition = true;
@@ -9032,8 +9016,9 @@ class AuthManager {
9032
9016
  await wait$1(interval * 1000);
9033
9017
  try {
9034
9018
  const tokenResponse = await this.getDeviceFlowToken(deviceCode);
9035
- const user = AuthManager.mapDeviceTokenResponseToDomainUserModel(tokenResponse);
9036
- this.deviceCredentialsManager.saveCredentials(tokenResponse);
9019
+ const oidcUser = AuthManager.mapDeviceTokenResponseToOidcUser(tokenResponse);
9020
+ const user = AuthManager.mapOidcUserToDomainModel(oidcUser);
9021
+ await this.userManager.storeUser(oidcUser);
9037
9022
  return user;
9038
9023
  }
9039
9024
  catch (error) {
@@ -9069,20 +9054,11 @@ class AuthManager {
9069
9054
  }, formUrlEncodedHeader);
9070
9055
  return response.data;
9071
9056
  }
9072
- static base64URLEncode(str) {
9073
- return str.toString('base64')
9074
- .replace(/\+/g, '-')
9075
- .replace(/\//g, '_')
9076
- .replace(/=/g, '');
9077
- }
9078
- static sha256(buffer) {
9079
- return crypto__namespace.createHash('sha256').update(buffer).digest();
9080
- }
9081
9057
  getPKCEAuthorizationUrl() {
9082
- const verifier = AuthManager.base64URLEncode(crypto__namespace.randomBytes(32));
9083
- const challenge = AuthManager.base64URLEncode(AuthManager.sha256(verifier));
9058
+ const verifier = base64URLEncode(crypto__namespace.randomBytes(32));
9059
+ const challenge = base64URLEncode(sha256(verifier));
9084
9060
  // https://auth0.com/docs/secure/attack-protection/state-parameters
9085
- const state = AuthManager.base64URLEncode(crypto__namespace.randomBytes(32));
9061
+ const state = base64URLEncode(crypto__namespace.randomBytes(32));
9086
9062
  this.deviceCredentialsManager.savePKCEData({ state, verifier });
9087
9063
  return `${this.config.authenticationDomain}/authorize?`
9088
9064
  + 'response_type=code'
@@ -9104,8 +9080,9 @@ class AuthManager {
9104
9080
  throw new Error('Provided state does not match stored state');
9105
9081
  }
9106
9082
  const tokenResponse = await this.getPKCEToken(authorizationCode, pkceData.verifier);
9107
- const user = AuthManager.mapDeviceTokenResponseToDomainUserModel(tokenResponse);
9108
- this.deviceCredentialsManager.saveCredentials(tokenResponse);
9083
+ const oidcUser = AuthManager.mapDeviceTokenResponseToOidcUser(tokenResponse);
9084
+ const user = AuthManager.mapOidcUserToDomainModel(oidcUser);
9085
+ await this.userManager.storeUser(oidcUser);
9109
9086
  return user;
9110
9087
  }, PassportErrorType.AUTHENTICATION_ERROR);
9111
9088
  }
@@ -9119,31 +9096,6 @@ class AuthManager {
9119
9096
  }, formUrlEncodedHeader);
9120
9097
  return response.data;
9121
9098
  }
9122
- async connectImxWithCredentials(tokenResponse) {
9123
- return withPassportError(async () => {
9124
- if (this.deviceCredentialsManager.areValid(tokenResponse)) {
9125
- // Credentials exist and are still valid
9126
- return AuthManager.mapDeviceTokenResponseToDomainUserModel(tokenResponse);
9127
- }
9128
- const refreshToken = tokenResponse?.refresh_token ?? null;
9129
- if (refreshToken) {
9130
- // Token is no longer valid, but refresh token can be used to a new one
9131
- const user = await this.refreshToken(refreshToken);
9132
- return user;
9133
- }
9134
- return null;
9135
- }, PassportErrorType.AUTHENTICATION_ERROR);
9136
- }
9137
- async refreshToken(refreshToken) {
9138
- const response = await globalAxios$1.post(`${this.config.authenticationDomain}/oauth/token`, {
9139
- client_id: this.config.oidcConfiguration.clientId,
9140
- grant_type: 'refresh_token',
9141
- refresh_token: refreshToken,
9142
- }, formUrlEncodedHeader);
9143
- const newTokenResponse = response.data;
9144
- this.deviceCredentialsManager.saveCredentials(newTokenResponse);
9145
- return AuthManager.mapDeviceTokenResponseToDomainUserModel(newTokenResponse);
9146
- }
9147
9099
  async logout() {
9148
9100
  return withPassportError(async () => {
9149
9101
  if (this.logoutMode === 'silent') {
@@ -9152,29 +9104,20 @@ class AuthManager {
9152
9104
  return this.userManager.signoutRedirect();
9153
9105
  }, PassportErrorType.LOGOUT_ERROR);
9154
9106
  }
9155
- async logoutSilentCallback(url) {
9156
- return this.userManager.signoutSilentCallback(url);
9157
- }
9158
- async logoutDeviceFlow() {
9159
- return withPassportError(async () => {
9160
- this.deviceCredentialsManager.clearCredentials();
9161
- }, PassportErrorType.LOGOUT_ERROR);
9107
+ async removeUser() {
9108
+ return this.userManager.removeUser();
9162
9109
  }
9163
- /**
9164
- * Get the user from the cache or refresh the token if it's expired.
9165
- * return null if there's no refresh token.
9166
- */
9167
- async getAuthenticatedUser() {
9168
- const oidcUser = await this.userManager.getUser();
9169
- if (!oidcUser)
9170
- return null;
9171
- if (!isTokenExpired(oidcUser)) {
9172
- return AuthManager.mapOidcUserToDomainModel(oidcUser);
9110
+ getDeviceFlowEndSessionEndpoint() {
9111
+ const { authenticationDomain, oidcConfiguration } = this.config;
9112
+ let endSessionEndpoint = `${authenticationDomain}/v2/logout`;
9113
+ if (oidcConfiguration.logoutRedirectUri) {
9114
+ endSessionEndpoint += `?client_id=${oidcConfiguration.clientId}`
9115
+ + `&returnTo=${encodeURIComponent(oidcConfiguration.logoutRedirectUri)}`;
9173
9116
  }
9174
- if (oidcUser.refresh_token) {
9175
- return this.refreshTokenAndUpdatePromise();
9176
- }
9177
- return null;
9117
+ return endSessionEndpoint;
9118
+ }
9119
+ async logoutSilentCallback(url) {
9120
+ return this.userManager.signoutSilentCallback(url);
9178
9121
  }
9179
9122
  async forceUserRefresh() {
9180
9123
  return this.refreshTokenAndUpdatePromise();
@@ -9189,25 +9132,10 @@ class AuthManager {
9189
9132
  // eslint-disable-next-line no-async-promise-executor
9190
9133
  this.refreshingPromise = new Promise(async (resolve, reject) => {
9191
9134
  try {
9192
- if (this.config.crossSdkBridgeEnabled) {
9193
- const tokenResponse = this.checkStoredDeviceFlowCredentials();
9194
- if (tokenResponse) {
9195
- const refreshToken = tokenResponse?.refresh_token ?? null;
9196
- if (refreshToken) {
9197
- const newUser = await this.refreshToken(refreshToken);
9198
- if (newUser) {
9199
- resolve(newUser);
9200
- return;
9201
- }
9202
- }
9203
- }
9204
- }
9205
- else {
9206
- const newOidcUser = await this.userManager.signinSilent();
9207
- if (newOidcUser) {
9208
- resolve(AuthManager.mapOidcUserToDomainModel(newOidcUser));
9209
- return;
9210
- }
9135
+ const newOidcUser = await this.userManager.signinSilent();
9136
+ if (newOidcUser) {
9137
+ resolve(AuthManager.mapOidcUserToDomainModel(newOidcUser));
9138
+ return;
9211
9139
  }
9212
9140
  resolve(null);
9213
9141
  }
@@ -9220,30 +9148,24 @@ class AuthManager {
9220
9148
  });
9221
9149
  return this.refreshingPromise;
9222
9150
  }
9151
+ /**
9152
+ * Get the user from the cache or refresh the token if it's expired.
9153
+ * return null if there's no refresh token.
9154
+ */
9223
9155
  async getUser() {
9224
9156
  return withPassportError(async () => {
9225
- const user = await this.getAuthenticatedUser();
9226
- if (user)
9227
- return user;
9228
- const deviceToken = this.deviceCredentialsManager.getCredentials();
9229
- if (deviceToken) {
9230
- return AuthManager.mapDeviceTokenResponseToDomainUserModel(deviceToken);
9157
+ const oidcUser = await this.userManager.getUser();
9158
+ if (!oidcUser)
9159
+ return null;
9160
+ if (!isTokenExpired(oidcUser)) {
9161
+ return AuthManager.mapOidcUserToDomainModel(oidcUser);
9231
9162
  }
9232
- return null;
9233
- }, PassportErrorType.NOT_LOGGED_IN_ERROR);
9234
- }
9235
- async getUserDeviceFlow() {
9236
- return withPassportError(async () => {
9237
- const deviceToken = this.deviceCredentialsManager.getCredentials();
9238
- if (deviceToken) {
9239
- return AuthManager.mapDeviceTokenResponseToDomainUserModel(deviceToken);
9163
+ if (oidcUser.refresh_token) {
9164
+ return this.refreshTokenAndUpdatePromise();
9240
9165
  }
9241
9166
  return null;
9242
9167
  }, PassportErrorType.NOT_LOGGED_IN_ERROR);
9243
9168
  }
9244
- checkStoredDeviceFlowCredentials() {
9245
- return this.deviceCredentialsManager.getCredentials();
9246
- }
9247
9169
  }
9248
9170
 
9249
9171
  const lazyLoad = (promiseToAwait, initialiseFunction) => promiseToAwait().then(initialiseFunction);
@@ -10078,21 +10000,10 @@ class PassportImxProviderFactory {
10078
10000
  }
10079
10001
  return this.createProviderInstance(user);
10080
10002
  }
10081
- async getProviderWithDeviceFlow(deviceCode, interval, timeoutMs) {
10082
- const user = await this.authManager.connectImxDeviceFlow(deviceCode, interval, timeoutMs);
10083
- return this.createProviderInstance(user);
10084
- }
10085
10003
  async getProviderWithPKCEFlow(authorizationCode, state) {
10086
10004
  const user = await this.authManager.connectImxPKCEFlow(authorizationCode, state);
10087
10005
  return this.createProviderInstance(user);
10088
10006
  }
10089
- async getProviderWithCredentials(tokenResponse) {
10090
- const user = await this.authManager.connectImxWithCredentials(tokenResponse);
10091
- if (!user) {
10092
- return null;
10093
- }
10094
- return this.createProviderInstance(user);
10095
- }
10096
10007
  async createProviderInstance(user) {
10097
10008
  if (!user.idToken) {
10098
10009
  throw new PassportError('Failed to initialise', PassportErrorType.WALLET_CONNECTION_ERROR);
@@ -10136,7 +10047,6 @@ class PassportConfiguration {
10136
10047
  constructor({ baseConfig, overrides, crossSdkBridgeEnabled, ...oidcConfiguration }) {
10137
10048
  validateConfiguration(oidcConfiguration, [
10138
10049
  'clientId',
10139
- 'logoutRedirectUri',
10140
10050
  'redirectUri',
10141
10051
  ]);
10142
10052
  this.oidcConfiguration = oidcConfiguration;
@@ -10611,7 +10521,7 @@ const CHAIN_NAME_MAP = new Map([
10611
10521
  ]);
10612
10522
 
10613
10523
  const MESSAGE_TO_SIGN = 'Only sign this message from Immutable Passport';
10614
- async function registerZkEvmUser({ authManager, config, magicProvider, multiRollupApiClients, accessToken, jsonRpcProvider, }) {
10524
+ async function registerZkEvmUser({ authManager, magicProvider, multiRollupApiClients, accessToken, jsonRpcProvider, }) {
10615
10525
  const web3Provider = new providers.Web3Provider(magicProvider);
10616
10526
  const ethSigner = web3Provider.getSigner();
10617
10527
  const ethereumAddress = await ethSigner.getAddress();
@@ -10634,24 +10544,14 @@ async function registerZkEvmUser({ authManager, config, magicProvider, multiRoll
10634
10544
  catch (error) {
10635
10545
  throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, `Failed to create counterfactual address: ${error}`);
10636
10546
  }
10637
- let user;
10638
- if (config.crossSdkBridgeEnabled) {
10639
- const credentials = authManager.checkStoredDeviceFlowCredentials();
10640
- if (!credentials || !credentials.refresh_token) {
10641
- throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, 'Cross SDK bridge: Failed to refresh user details');
10642
- }
10643
- user = await authManager.refreshToken(credentials.refresh_token);
10644
- }
10645
- else {
10646
- user = await authManager.forceUserRefresh();
10647
- }
10547
+ const user = await authManager.forceUserRefresh();
10648
10548
  if (!user?.zkEvm) {
10649
10549
  throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, 'Failed to refresh user details');
10650
10550
  }
10651
10551
  return user;
10652
10552
  }
10653
10553
 
10654
- const loginZkEvmUser = async ({ authManager, config, magicAdapter, multiRollupApiClients, jsonRpcProvider, }) => {
10554
+ const loginZkEvmUser = async ({ authManager, magicAdapter, multiRollupApiClients, jsonRpcProvider, }) => {
10655
10555
  let user = null;
10656
10556
  try {
10657
10557
  user = await authManager.getUser();
@@ -10661,7 +10561,7 @@ const loginZkEvmUser = async ({ authManager, config, magicAdapter, multiRollupAp
10661
10561
  console.warn('eth_requestAccounts` failed to retrieve a cached user session:', err);
10662
10562
  }
10663
10563
  if (!user) {
10664
- user = await authManager.getUserDeviceFlow() || await authManager.login();
10564
+ user = await authManager.login();
10665
10565
  }
10666
10566
  if (!user.idToken) {
10667
10567
  throw new Error('User is missing idToken');
@@ -10671,7 +10571,6 @@ const loginZkEvmUser = async ({ authManager, config, magicAdapter, multiRollupAp
10671
10571
  // Generate counterfactual address and retrieve updated Auth0 user
10672
10572
  const userZkevm = await registerZkEvmUser({
10673
10573
  authManager,
10674
- config,
10675
10574
  magicProvider,
10676
10575
  multiRollupApiClients,
10677
10576
  accessToken: user.accessToken,
@@ -11095,24 +10994,12 @@ class Passport {
11095
10994
  async connectImx() {
11096
10995
  return this.passportImxProviderFactory.getProvider();
11097
10996
  }
11098
- async connectImxDeviceFlow(deviceCode, interval, timeoutMs) {
11099
- return this.passportImxProviderFactory.getProviderWithDeviceFlow(deviceCode, interval, timeoutMs);
11100
- }
11101
10997
  getPKCEAuthorizationUrl() {
11102
10998
  return this.authManager.getPKCEAuthorizationUrl();
11103
10999
  }
11104
11000
  async connectImxPKCEFlow(authorizationCode, state) {
11105
11001
  return this.passportImxProviderFactory.getProviderWithPKCEFlow(authorizationCode, state);
11106
11002
  }
11107
- /**
11108
- * @returns {boolean} the stored device flow credentials if they exist
11109
- */
11110
- checkStoredDeviceFlowCredentials() {
11111
- return this.authManager.checkStoredDeviceFlowCredentials();
11112
- }
11113
- async connectImxWithCredentials(tokenResponse) {
11114
- return this.passportImxProviderFactory.getProviderWithCredentials(tokenResponse);
11115
- }
11116
11003
  connectEvm() {
11117
11004
  if (this.config.network === Networks.PRODUCTION) {
11118
11005
  throw new Error('EVM is not supported on production network');
@@ -11152,19 +11039,35 @@ class Passport {
11152
11039
  }
11153
11040
  return user ? user.profile : null;
11154
11041
  }
11042
+ async loginCallback() {
11043
+ return this.authManager.loginCallback();
11044
+ }
11155
11045
  async loginWithDeviceFlow() {
11156
11046
  return this.authManager.loginWithDeviceFlow();
11157
11047
  }
11158
- async loginCallback() {
11159
- return this.authManager.loginCallback();
11048
+ async loginWithDeviceFlowCallback(deviceCode, interval, timeoutMs) {
11049
+ const user = await this.authManager.loginWithDeviceFlowCallback(deviceCode, interval, timeoutMs);
11050
+ return user.profile;
11160
11051
  }
11161
11052
  async logout() {
11162
- await this.authManager.logout();
11163
11053
  await this.confirmationScreen.logout();
11054
+ await this.authManager.logout();
11164
11055
  // Code after this point is only executed if the logout mode is silent
11165
11056
  await this.magicAdapter.logout();
11166
11057
  this.passportEventEmitter.emit(PassportEvents.LOGGED_OUT);
11167
11058
  }
11059
+ /**
11060
+ * Logs the user out of Passport when using device flow authentication.
11061
+ *
11062
+ * @returns {Promise<string>} The device flow end session endpoint. Consumers are responsible for
11063
+ * opening this URL in the same browser that was used to log the user in.
11064
+ */
11065
+ async logoutDeviceFlow() {
11066
+ await this.authManager.removeUser();
11067
+ await this.magicAdapter.logout();
11068
+ this.passportEventEmitter.emit(PassportEvents.LOGGED_OUT);
11069
+ return this.authManager.getDeviceFlowEndSessionEndpoint();
11070
+ }
11168
11071
  /**
11169
11072
  * This method should only be called from the logout redirect uri
11170
11073
  * when logout mode is 'silent'.
@@ -11172,17 +11075,10 @@ class Passport {
11172
11075
  async logoutSilentCallback(url) {
11173
11076
  return this.authManager.logoutSilentCallback(url);
11174
11077
  }
11175
- async logoutDeviceFlow() {
11176
- return this.authManager.logoutDeviceFlow();
11177
- }
11178
11078
  async getUserInfo() {
11179
11079
  const user = await this.authManager.getUser();
11180
11080
  return user?.profile;
11181
11081
  }
11182
- async getUserInfoDeviceFlow() {
11183
- const user = await this.authManager.getUserDeviceFlow();
11184
- return user?.profile;
11185
- }
11186
11082
  async getIdToken() {
11187
11083
  const user = await this.authManager.getUser();
11188
11084
  return user?.idToken;
@@ -11636,7 +11532,7 @@ class OrdersService {
11636
11532
  * @returns ListListingsResult OK response.
11637
11533
  * @throws ApiError
11638
11534
  */
11639
- listListings({ chainName, status, sellItemContractAddress, buyItemContractAddress, sellItemTokenId, fromUpdatedAt, pageSize, sortBy, sortDirection, pageCursor, }) {
11535
+ listListings({ chainName, status, sellItemContractAddress, buyItemContractAddress, accountAddress, sellItemMetadataId, sellItemTokenId, fromUpdatedAt, pageSize, sortBy, sortDirection, pageCursor, }) {
11640
11536
  return this.httpRequest.request({
11641
11537
  method: 'GET',
11642
11538
  url: '/v1/chains/{chain_name}/orders/listings',
@@ -11647,6 +11543,8 @@ class OrdersService {
11647
11543
  'status': status,
11648
11544
  'sell_item_contract_address': sellItemContractAddress,
11649
11545
  'buy_item_contract_address': buyItemContractAddress,
11546
+ 'account_address': accountAddress,
11547
+ 'sell_item_metadata_id': sellItemMetadataId,
11650
11548
  'sell_item_token_id': sellItemTokenId,
11651
11549
  'from_updated_at': fromUpdatedAt,
11652
11550
  'page_size': pageSize,
@@ -28573,6 +28471,21 @@ const getCallData = (methodName, contractInterface) => {
28573
28471
  return fragment ? contractInterface?.encodeFunctionData(fragment) : undefined;
28574
28472
  };
28575
28473
 
28474
+ // 0.1% default slippage
28475
+ const DEFAULT_SLIPPAGE = 0.1;
28476
+ // 15 minutes from the time the transaction was prepared
28477
+ const DEFAULT_DEADLINE_SECONDS = 60 * 15;
28478
+ // most swaps will be able to resolve with 2 hops
28479
+ const DEFAULT_MAX_HOPS = 2;
28480
+ // after 10 hops, it is very unlikely a route will be available
28481
+ const MAX_MAX_HOPS = 10;
28482
+ // a max hop of 1 will require a direct swap with no intermediary pools
28483
+ const MIN_MAX_HOPS = 1;
28484
+ // precision used to calculate percentage from basis points
28485
+ const BASIS_POINT_PRECISION = 10000;
28486
+ // 10% maximum secondary fee
28487
+ const MAX_SECONDARY_FEE_BASIS_POINTS = 1000;
28488
+
28576
28489
  const quoteReturnMapping = {
28577
28490
  // eslint-disable-next-line @typescript-eslint/naming-convention
28578
28491
  '0xcdca1753': ['uint256', 'uint160[]', 'uint32[]', 'uint256'],
@@ -28707,6 +28620,7 @@ const toPublicAmount = (amount) => ({
28707
28620
  token: toPublicTokenType(amount.token),
28708
28621
  value: amount.value,
28709
28622
  });
28623
+ const getDefaultDeadlineSeconds = () => Math.floor(Date.now() / 1000) + DEFAULT_DEADLINE_SECONDS;
28710
28624
 
28711
28625
  const amountIndex = 0;
28712
28626
  const gasEstimateIndex = 3;
@@ -29205,21 +29119,6 @@ fees, tradeType, nativeTokenService) {
29205
29119
  return nativeTokenService.maybeWrapAmount(fees.amountLessFees());
29206
29120
  }
29207
29121
 
29208
- // 0.1% default slippage
29209
- const DEFAULT_SLIPPAGE = 0.1;
29210
- // 15 minutes from the current Unix time
29211
- const DEFAULT_DEADLINE = Math.floor(Date.now() / 1000) + 60 * 15;
29212
- // most swaps will be able to resolve with 2 hops
29213
- const DEFAULT_MAX_HOPS = 2;
29214
- // after 10 hops, it is very unlikely a route will be available
29215
- const MAX_MAX_HOPS = 10;
29216
- // a max hop of 1 will require a direct swap with no intermediary pools
29217
- const MIN_MAX_HOPS = 1;
29218
- // precision used to calculate percentage from basis points
29219
- const BASIS_POINT_PRECISION = 10000;
29220
- // 10% maximum secondary fee
29221
- const MAX_SECONDARY_FEE_BASIS_POINTS = 1000;
29222
-
29223
29122
  class Fees {
29224
29123
  secondaryFees;
29225
29124
  amount;
@@ -29764,7 +29663,7 @@ class Exchange {
29764
29663
  * @param {number} deadline (optional) Latest time swap can execute. Default is 15 minutes
29765
29664
  * @return {TransactionResponse} The result containing the unsigned transaction and details of the swap
29766
29665
  */
29767
- async getUnsignedSwapTxFromAmountIn(fromAddress, tokenInAddress, tokenOutAddress, amountIn, slippagePercent = DEFAULT_SLIPPAGE, maxHops = DEFAULT_MAX_HOPS, deadline = DEFAULT_DEADLINE) {
29666
+ async getUnsignedSwapTxFromAmountIn(fromAddress, tokenInAddress, tokenOutAddress, amountIn, slippagePercent = DEFAULT_SLIPPAGE, maxHops = DEFAULT_MAX_HOPS, deadline = getDefaultDeadlineSeconds()) {
29768
29667
  return await this.getUnsignedSwapTx(fromAddress, tokenInAddress, tokenOutAddress, ethers.ethers.BigNumber.from(amountIn), slippagePercent, maxHops, deadline, Uniswap.TradeType.EXACT_INPUT);
29769
29668
  }
29770
29669
  /**
@@ -29780,7 +29679,7 @@ class Exchange {
29780
29679
  * @param {number} deadline (optional) Latest time swap can execute. Default is 15 minutes
29781
29680
  * @return {TransactionResponse} The result containing the unsigned transaction and details of the swap
29782
29681
  */
29783
- async getUnsignedSwapTxFromAmountOut(fromAddress, tokenInAddress, tokenOutAddress, amountOut, slippagePercent = DEFAULT_SLIPPAGE, maxHops = DEFAULT_MAX_HOPS, deadline = DEFAULT_DEADLINE) {
29682
+ async getUnsignedSwapTxFromAmountOut(fromAddress, tokenInAddress, tokenOutAddress, amountOut, slippagePercent = DEFAULT_SLIPPAGE, maxHops = DEFAULT_MAX_HOPS, deadline = getDefaultDeadlineSeconds()) {
29784
29683
  return await this.getUnsignedSwapTx(fromAddress, tokenInAddress, tokenOutAddress, ethers.ethers.BigNumber.from(amountOut), slippagePercent, maxHops, deadline, Uniswap.TradeType.EXACT_OUTPUT);
29785
29684
  }
29786
29685
  }
@@ -30673,7 +30572,7 @@ const GAS_OVERRIDES = {
30673
30572
  maxPriorityFeePerGas: ethers.BigNumber.from(101e9),
30674
30573
  };
30675
30574
 
30676
- const SDK_VERSION_MARKER = '0.32.0';
30575
+ const SDK_VERSION_MARKER = '0.34.0';
30677
30576
  // This SDK version is replaced by the `yarn build` command ran on the root level
30678
30577
  const globalPackageVersion = () => SDK_VERSION_MARKER;
30679
30578
 
@@ -31032,8 +30931,8 @@ const resetBlockscoutClientMap = () => blockscoutClientMap.clear();
31032
30931
  const getIndexerBalance = async (walletAddress, chainId, filterTokens) => {
31033
30932
  // Shuffle the mapping of the tokens configuration so it is a hashmap
31034
30933
  // for faster access to tokens config objects.
31035
- const shouldFilter = filterTokens.length > 0;
31036
- const mapFilterTokens = Object.assign({}, ...(filterTokens.map((t) => ({ [t.address || NATIVE]: t }))));
30934
+ const shouldFilter = filterTokens !== undefined;
30935
+ const mapFilterTokens = Object.assign({}, ...((filterTokens ?? []).map((t) => ({ [t.address || NATIVE]: t }))));
31037
30936
  // Get blockscout client for the given chain
31038
30937
  let blockscoutClient = blockscoutClientMap.get(chainId);
31039
30938
  if (!blockscoutClient) {
@@ -31153,7 +31052,7 @@ const getAllBalances = async (config, web3Provider, walletAddress, chainId) => {
31153
31052
  // Please remove this hack once https://immutable.atlassian.net/browse/WT-1710
31154
31053
  // is done.
31155
31054
  const isL1Chain = getL1ChainId(config) === chainId;
31156
- return await measureAsyncExecution(config, `Time to fetch balances using blockscout for ${chainId}`, getIndexerBalance(walletAddress, chainId, isL1Chain ? tokens : []));
31055
+ return await measureAsyncExecution(config, `Time to fetch balances using blockscout for ${chainId}`, getIndexerBalance(walletAddress, chainId, isL1Chain ? tokens : undefined));
31157
31056
  }
31158
31057
  // This fallback to use ERC20s calls which is a best effort solution
31159
31058
  // Fails in fetching data from the RCP calls might result in some