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