@imtbl/sdk 1.13.5 → 1.13.6-alpha

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/passport.js CHANGED
@@ -2,7 +2,7 @@ import globalAxios$1, { isAxiosError as isAxiosError$1 } from 'axios';
2
2
  import { ImmutableX, Config, generateLegacyStarkPrivateKey, createStarkSigner } from '@imtbl/core-sdk';
3
3
  import { memorise } from 'lru-memorise';
4
4
  import { getGlobalisedValue as getGlobalisedValue$1 } from 'global-const';
5
- import { UserManager, User, ErrorTimeout, ErrorResponse, InMemoryWebStorage, WebStorageStateStore } from 'oidc-client-ts';
5
+ import { UserManager, ErrorTimeout, ErrorResponse, User, InMemoryWebStorage, WebStorageStateStore } from 'oidc-client-ts';
6
6
  import jwt_decode from 'jwt-decode';
7
7
  import * as crypto from 'crypto';
8
8
  import { Magic } from 'magic-sdk';
@@ -8399,7 +8399,7 @@ class MultiRollupApiClients {
8399
8399
  }
8400
8400
 
8401
8401
  // eslint-disable-next-line @typescript-eslint/naming-convention
8402
- const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.13.5' };
8402
+ const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.13.6-alpha' };
8403
8403
  const createConfig = ({ basePath, headers, }) => {
8404
8404
  if (!basePath.trim()) {
8405
8405
  throw Error('basePath can not be empty');
@@ -8578,7 +8578,7 @@ const flattenProperties = (properties) => {
8578
8578
  };
8579
8579
 
8580
8580
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
8581
- const SDK_VERSION = '1.13.5';
8581
+ const SDK_VERSION = '1.13.6-alpha';
8582
8582
  const getReferrer = () => {
8583
8583
  if (isNode()) {
8584
8584
  return '';
@@ -8797,7 +8797,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
8797
8797
  chainID,
8798
8798
  coreContractAddress,
8799
8799
  registrationContractAddress,
8800
- sdkVersion: 'ts-immutable-sdk-1.13.5',
8800
+ sdkVersion: 'ts-immutable-sdk-1.13.6-alpha',
8801
8801
  });
8802
8802
  /**
8803
8803
  * Sets `sdkVersion` at the time of build
@@ -13278,6 +13278,63 @@ const TransactionApprovalRequestChainTypeEnum = {
13278
13278
  Evm: 'evm'
13279
13279
  };
13280
13280
 
13281
+ /******************************************************************************
13282
+ Copyright (c) Microsoft Corporation.
13283
+
13284
+ Permission to use, copy, modify, and/or distribute this software for any
13285
+ purpose with or without fee is hereby granted.
13286
+
13287
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
13288
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13289
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
13290
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13291
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
13292
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13293
+ PERFORMANCE OF THIS SOFTWARE.
13294
+ ***************************************************************************** */
13295
+ /* global Reflect, Promise, SuppressedError, Symbol */
13296
+
13297
+
13298
+ function __rest(s, e) {
13299
+ var t = {};
13300
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
13301
+ t[p] = s[p];
13302
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
13303
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
13304
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
13305
+ t[p[i]] = s[p[i]];
13306
+ }
13307
+ return t;
13308
+ }
13309
+
13310
+ function __awaiter(thisArg, _arguments, P, generator) {
13311
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
13312
+ return new (P || (P = Promise))(function (resolve, reject) {
13313
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
13314
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
13315
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
13316
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
13317
+ });
13318
+ }
13319
+
13320
+ function __classPrivateFieldGet(receiver, state, kind, f) {
13321
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
13322
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
13323
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
13324
+ }
13325
+
13326
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
13327
+ if (kind === "m") throw new TypeError("Private method is not writable");
13328
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
13329
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
13330
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
13331
+ }
13332
+
13333
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
13334
+ var e = new Error(message);
13335
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
13336
+ };
13337
+
13281
13338
  var PassportErrorType;
13282
13339
  (function (PassportErrorType) {
13283
13340
  PassportErrorType["AUTHENTICATION_ERROR"] = "AUTHENTICATION_ERROR";
@@ -13300,19 +13357,19 @@ function isAPIError(error) {
13300
13357
  return 'code' in error && 'message' in error;
13301
13358
  }
13302
13359
  class PassportError extends Error {
13303
- type;
13304
13360
  constructor(message, type) {
13305
13361
  super(message);
13306
13362
  this.type = type;
13307
13363
  }
13308
13364
  }
13309
- const withPassportError = async (fn, customErrorType) => {
13365
+ const withPassportError = (fn, customErrorType) => __awaiter(void 0, void 0, void 0, function* () {
13366
+ var _a;
13310
13367
  try {
13311
- return await fn();
13368
+ return yield fn();
13312
13369
  }
13313
13370
  catch (error) {
13314
13371
  let errorMessage;
13315
- if (isAxiosError$1(error) && error.response?.data && isAPIError(error.response.data)) {
13372
+ if (isAxiosError$1(error) && ((_a = error.response) === null || _a === void 0 ? void 0 : _a.data) && isAPIError(error.response.data)) {
13316
13373
  errorMessage = error.response.data.message;
13317
13374
  }
13318
13375
  else {
@@ -13320,7 +13377,7 @@ const withPassportError = async (fn, customErrorType) => {
13320
13377
  }
13321
13378
  throw new PassportError(errorMessage, customErrorType);
13322
13379
  }
13323
- };
13380
+ });
13324
13381
 
13325
13382
  /**
13326
13383
  * Enum representing different chain IDs.
@@ -13370,9 +13427,10 @@ class DeviceCredentialsManager {
13370
13427
  return false;
13371
13428
  }
13372
13429
  isTokenValid(jwt) {
13430
+ var _a;
13373
13431
  try {
13374
13432
  const tokenPayload = jwt_decode(jwt);
13375
- const expiresAt = tokenPayload.exp ?? 0;
13433
+ const expiresAt = (_a = tokenPayload.exp) !== null && _a !== void 0 ? _a : 0;
13376
13434
  const now = (Date.now() / 1000) + validCredentialsMinTtlSec;
13377
13435
  return expiresAt > now;
13378
13436
  }
@@ -13394,7 +13452,8 @@ class DeviceCredentialsManager {
13394
13452
  }
13395
13453
  }
13396
13454
 
13397
- const shouldLog = process?.env?.JEST_WORKER_ID === undefined;
13455
+ var _a;
13456
+ const shouldLog = ((_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a.JEST_WORKER_ID) === undefined;
13398
13457
  const warn = (...args) => {
13399
13458
  if (shouldLog) {
13400
13459
  // eslint-disable-next-line no-console
@@ -13478,171 +13537,127 @@ function sha256(buffer) {
13478
13537
  return crypto.createHash('sha256').update(buffer).digest();
13479
13538
  }
13480
13539
  class AuthManager {
13481
- userManager;
13482
- deviceCredentialsManager;
13483
- config;
13484
- logoutMode;
13485
- /**
13486
- * Promise that is used to prevent multiple concurrent calls to the refresh token endpoint.
13487
- */
13488
- refreshingPromise = null;
13489
13540
  constructor(config) {
13541
+ /**
13542
+ * Promise that is used to prevent multiple concurrent calls to the refresh token endpoint.
13543
+ */
13544
+ this.refreshingPromise = null;
13490
13545
  this.config = config;
13491
13546
  this.userManager = new UserManager(getAuthConfiguration(config));
13492
13547
  this.deviceCredentialsManager = new DeviceCredentialsManager();
13493
13548
  this.logoutMode = config.oidcConfiguration.logoutMode || 'redirect';
13494
13549
  }
13495
- static mapOidcUserToDomainModel = (oidcUser) => {
13496
- let passport;
13497
- if (oidcUser.id_token) {
13498
- passport = jwt_decode(oidcUser.id_token)?.passport;
13499
- }
13500
- const user = {
13501
- expired: oidcUser.expired,
13502
- idToken: oidcUser.id_token,
13503
- accessToken: oidcUser.access_token,
13504
- refreshToken: oidcUser.refresh_token,
13505
- profile: {
13506
- sub: oidcUser.profile.sub,
13507
- email: oidcUser.profile.email,
13508
- nickname: oidcUser.profile.nickname,
13509
- },
13510
- };
13511
- if (passport?.imx_eth_address) {
13512
- user.imx = {
13513
- ethAddress: passport.imx_eth_address,
13514
- starkAddress: passport.imx_stark_address,
13515
- userAdminAddress: passport.imx_user_admin_address,
13516
- };
13517
- }
13518
- if (passport?.zkevm_eth_address) {
13519
- user.zkEvm = {
13520
- ethAddress: passport?.zkevm_eth_address,
13521
- userAdminAddress: passport?.zkevm_user_admin_address,
13522
- };
13523
- }
13524
- return user;
13525
- };
13526
- static mapDeviceTokenResponseToOidcUser = (tokenResponse) => {
13527
- const idTokenPayload = jwt_decode(tokenResponse.id_token);
13528
- return new User({
13529
- id_token: tokenResponse.id_token,
13530
- access_token: tokenResponse.access_token,
13531
- refresh_token: tokenResponse.refresh_token,
13532
- token_type: tokenResponse.token_type,
13533
- profile: {
13534
- sub: idTokenPayload.sub,
13535
- iss: idTokenPayload.iss,
13536
- aud: idTokenPayload.aud,
13537
- exp: idTokenPayload.exp,
13538
- iat: idTokenPayload.iat,
13539
- email: idTokenPayload.email,
13540
- nickname: idTokenPayload.nickname,
13541
- passport: idTokenPayload.passport,
13542
- },
13543
- });
13544
- };
13545
13550
  /**
13546
13551
  * login
13547
13552
  * @param anonymousId Caller can pass an anonymousId if they want to associate their user's identity with immutable's internal instrumentation.
13548
13553
  */
13549
- async login(anonymousId) {
13550
- return withPassportError(async () => {
13551
- const rid = getDetail(Detail.RUNTIME_ID);
13552
- const popupWindowFeatures = { width: 410, height: 450 };
13553
- const oidcUser = await this.userManager.signinPopup({
13554
- extraQueryParams: {
13555
- ...(this.userManager.settings?.extraQueryParams ?? {}),
13556
- rid: rid || '',
13557
- third_party_a_id: anonymousId || '',
13558
- },
13559
- popupWindowFeatures,
13560
- });
13561
- return AuthManager.mapOidcUserToDomainModel(oidcUser);
13562
- }, PassportErrorType.AUTHENTICATION_ERROR);
13554
+ login(anonymousId) {
13555
+ return __awaiter(this, void 0, void 0, function* () {
13556
+ return withPassportError(() => __awaiter(this, void 0, void 0, function* () {
13557
+ var _a, _b;
13558
+ const rid = getDetail(Detail.RUNTIME_ID);
13559
+ const popupWindowFeatures = { width: 410, height: 450 };
13560
+ const oidcUser = yield this.userManager.signinPopup({
13561
+ extraQueryParams: Object.assign(Object.assign({}, ((_b = (_a = this.userManager.settings) === null || _a === void 0 ? void 0 : _a.extraQueryParams) !== null && _b !== void 0 ? _b : {})), { rid: rid || '', third_party_a_id: anonymousId || '' }),
13562
+ popupWindowFeatures,
13563
+ });
13564
+ return AuthManager.mapOidcUserToDomainModel(oidcUser);
13565
+ }), PassportErrorType.AUTHENTICATION_ERROR);
13566
+ });
13563
13567
  }
13564
- async getUserOrLogin() {
13565
- let user = null;
13566
- try {
13567
- user = await this.getUser();
13568
- }
13569
- catch (err) {
13570
- logger.warn('Failed to retrieve a cached user session', err);
13571
- }
13572
- return user || this.login();
13568
+ getUserOrLogin() {
13569
+ return __awaiter(this, void 0, void 0, function* () {
13570
+ let user = null;
13571
+ try {
13572
+ user = yield this.getUser();
13573
+ }
13574
+ catch (err) {
13575
+ logger.warn('Failed to retrieve a cached user session', err);
13576
+ }
13577
+ return user || this.login();
13578
+ });
13573
13579
  }
13574
- async loginCallback() {
13575
- return withPassportError(async () => this.userManager.signinPopupCallback(), PassportErrorType.AUTHENTICATION_ERROR);
13580
+ loginCallback() {
13581
+ return __awaiter(this, void 0, void 0, function* () {
13582
+ return withPassportError(() => __awaiter(this, void 0, void 0, function* () { return this.userManager.signinPopupCallback(); }), PassportErrorType.AUTHENTICATION_ERROR);
13583
+ });
13576
13584
  }
13577
13585
  /**
13578
13586
  * loginWithDeviceFlow
13579
13587
  * @param anonymousId Caller can pass an anonymousId if they want to associate their user's identity with immutable's internal instrumentation.
13580
13588
  */
13581
- async loginWithDeviceFlow(anonymousId) {
13582
- return withPassportError(async () => {
13583
- const response = await globalAxios$1.post(`${this.config.authenticationDomain}/oauth/device/code`, {
13584
- client_id: this.config.oidcConfiguration.clientId,
13585
- scope: this.config.oidcConfiguration.scope,
13586
- audience: this.config.oidcConfiguration.audience,
13587
- }, formUrlEncodedHeader);
13588
- const rid = getDetail(Detail.RUNTIME_ID);
13589
- return {
13590
- code: response.data.user_code,
13591
- deviceCode: response.data.device_code,
13592
- url: `${response.data.verification_uri_complete}${rid ? `&rid=${rid}` : ''}${anonymousId ? `&third_party_a_id=${anonymousId}` : ''}`,
13593
- interval: response.data.interval,
13594
- };
13595
- }, PassportErrorType.AUTHENTICATION_ERROR);
13589
+ loginWithDeviceFlow(anonymousId) {
13590
+ return __awaiter(this, void 0, void 0, function* () {
13591
+ return withPassportError(() => __awaiter(this, void 0, void 0, function* () {
13592
+ const response = yield globalAxios$1.post(`${this.config.authenticationDomain}/oauth/device/code`, {
13593
+ client_id: this.config.oidcConfiguration.clientId,
13594
+ scope: this.config.oidcConfiguration.scope,
13595
+ audience: this.config.oidcConfiguration.audience,
13596
+ }, formUrlEncodedHeader);
13597
+ const rid = getDetail(Detail.RUNTIME_ID);
13598
+ return {
13599
+ code: response.data.user_code,
13600
+ deviceCode: response.data.device_code,
13601
+ url: `${response.data.verification_uri_complete}${rid ? `&rid=${rid}` : ''}${anonymousId ? `&third_party_a_id=${anonymousId}` : ''}`,
13602
+ interval: response.data.interval,
13603
+ };
13604
+ }), PassportErrorType.AUTHENTICATION_ERROR);
13605
+ });
13596
13606
  }
13597
13607
  /* eslint-disable no-await-in-loop */
13598
- async loginWithDeviceFlowCallback(deviceCode, interval, timeoutMs) {
13599
- return withPassportError(async () => {
13600
- const startTime = Date.now();
13601
- const loopCondition = true;
13602
- while (loopCondition) {
13603
- if (timeoutMs != null && Date.now() - startTime > timeoutMs) {
13604
- throw new Error('Timed out');
13605
- }
13606
- await wait$1(interval * 1000);
13607
- try {
13608
- const tokenResponse = await this.getDeviceFlowToken(deviceCode);
13609
- const oidcUser = AuthManager.mapDeviceTokenResponseToOidcUser(tokenResponse);
13610
- const user = AuthManager.mapOidcUserToDomainModel(oidcUser);
13611
- await this.userManager.storeUser(oidcUser);
13612
- return user;
13613
- }
13614
- catch (error) {
13615
- if (globalAxios$1.isAxiosError(error)) {
13616
- const responseError = error.response?.data;
13617
- switch (responseError.error) {
13618
- case 'authorization_pending':
13619
- break;
13620
- case 'slow_down':
13621
- break;
13622
- case 'expired_token':
13623
- throw new Error('Token expired, please log in again');
13624
- case 'access_denied':
13625
- throw new Error('User denied access');
13626
- default:
13627
- throw new Error('Error getting token');
13628
- }
13608
+ loginWithDeviceFlowCallback(deviceCode, interval, timeoutMs) {
13609
+ return __awaiter(this, void 0, void 0, function* () {
13610
+ return withPassportError(() => __awaiter(this, void 0, void 0, function* () {
13611
+ var _a;
13612
+ const startTime = Date.now();
13613
+ const loopCondition = true;
13614
+ while (loopCondition) {
13615
+ if (timeoutMs != null && Date.now() - startTime > timeoutMs) {
13616
+ throw new Error('Timed out');
13617
+ }
13618
+ yield wait$1(interval * 1000);
13619
+ try {
13620
+ const tokenResponse = yield this.getDeviceFlowToken(deviceCode);
13621
+ const oidcUser = AuthManager.mapDeviceTokenResponseToOidcUser(tokenResponse);
13622
+ const user = AuthManager.mapOidcUserToDomainModel(oidcUser);
13623
+ yield this.userManager.storeUser(oidcUser);
13624
+ return user;
13629
13625
  }
13630
- else {
13631
- throw error;
13626
+ catch (error) {
13627
+ if (globalAxios$1.isAxiosError(error)) {
13628
+ const responseError = (_a = error.response) === null || _a === void 0 ? void 0 : _a.data;
13629
+ switch (responseError.error) {
13630
+ case 'authorization_pending':
13631
+ break;
13632
+ case 'slow_down':
13633
+ break;
13634
+ case 'expired_token':
13635
+ throw new Error('Token expired, please log in again');
13636
+ case 'access_denied':
13637
+ throw new Error('User denied access');
13638
+ default:
13639
+ throw new Error('Error getting token');
13640
+ }
13641
+ }
13642
+ else {
13643
+ throw error;
13644
+ }
13632
13645
  }
13633
13646
  }
13634
- }
13635
- throw new Error('Failed to get credentials');
13636
- }, PassportErrorType.AUTHENTICATION_ERROR);
13647
+ throw new Error('Failed to get credentials');
13648
+ }), PassportErrorType.AUTHENTICATION_ERROR);
13649
+ });
13637
13650
  }
13638
13651
  /* eslint-enable no-await-in-loop */
13639
- async getDeviceFlowToken(deviceCode) {
13640
- const response = await globalAxios$1.post(`${this.config.authenticationDomain}/oauth/token`, {
13641
- client_id: this.config.oidcConfiguration.clientId,
13642
- grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
13643
- device_code: deviceCode,
13644
- }, formUrlEncodedHeader);
13645
- return response.data;
13652
+ getDeviceFlowToken(deviceCode) {
13653
+ return __awaiter(this, void 0, void 0, function* () {
13654
+ const response = yield globalAxios$1.post(`${this.config.authenticationDomain}/oauth/token`, {
13655
+ client_id: this.config.oidcConfiguration.clientId,
13656
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
13657
+ device_code: deviceCode,
13658
+ }, formUrlEncodedHeader);
13659
+ return response.data;
13660
+ });
13646
13661
  }
13647
13662
  getPKCEAuthorizationUrl() {
13648
13663
  const verifier = base64URLEncode(crypto.randomBytes(32));
@@ -13660,42 +13675,50 @@ class AuthManager {
13660
13675
  + `&state=${state}`
13661
13676
  + `&audience=${this.config.oidcConfiguration.audience}`;
13662
13677
  }
13663
- async loginWithPKCEFlowCallback(authorizationCode, state) {
13664
- return withPassportError(async () => {
13665
- const pkceData = this.deviceCredentialsManager.getPKCEData();
13666
- if (!pkceData) {
13667
- throw new Error('No code verifier or state for PKCE');
13668
- }
13669
- if (state !== pkceData.state) {
13670
- throw new Error('Provided state does not match stored state');
13671
- }
13672
- const tokenResponse = await this.getPKCEToken(authorizationCode, pkceData.verifier);
13673
- const oidcUser = AuthManager.mapDeviceTokenResponseToOidcUser(tokenResponse);
13674
- const user = AuthManager.mapOidcUserToDomainModel(oidcUser);
13675
- await this.userManager.storeUser(oidcUser);
13676
- return user;
13677
- }, PassportErrorType.AUTHENTICATION_ERROR);
13678
- }
13679
- async getPKCEToken(authorizationCode, codeVerifier) {
13680
- const response = await globalAxios$1.post(`${this.config.authenticationDomain}/oauth/token`, {
13681
- client_id: this.config.oidcConfiguration.clientId,
13682
- grant_type: 'authorization_code',
13683
- code_verifier: codeVerifier,
13684
- code: authorizationCode,
13685
- redirect_uri: this.config.oidcConfiguration.redirectUri,
13686
- }, formUrlEncodedHeader);
13687
- return response.data;
13678
+ loginWithPKCEFlowCallback(authorizationCode, state) {
13679
+ return __awaiter(this, void 0, void 0, function* () {
13680
+ return withPassportError(() => __awaiter(this, void 0, void 0, function* () {
13681
+ const pkceData = this.deviceCredentialsManager.getPKCEData();
13682
+ if (!pkceData) {
13683
+ throw new Error('No code verifier or state for PKCE');
13684
+ }
13685
+ if (state !== pkceData.state) {
13686
+ throw new Error('Provided state does not match stored state');
13687
+ }
13688
+ const tokenResponse = yield this.getPKCEToken(authorizationCode, pkceData.verifier);
13689
+ const oidcUser = AuthManager.mapDeviceTokenResponseToOidcUser(tokenResponse);
13690
+ const user = AuthManager.mapOidcUserToDomainModel(oidcUser);
13691
+ yield this.userManager.storeUser(oidcUser);
13692
+ return user;
13693
+ }), PassportErrorType.AUTHENTICATION_ERROR);
13694
+ });
13688
13695
  }
13689
- async logout() {
13690
- return withPassportError(async () => {
13691
- if (this.logoutMode === 'silent') {
13692
- return this.userManager.signoutSilent();
13693
- }
13694
- return this.userManager.signoutRedirect();
13695
- }, PassportErrorType.LOGOUT_ERROR);
13696
+ getPKCEToken(authorizationCode, codeVerifier) {
13697
+ return __awaiter(this, void 0, void 0, function* () {
13698
+ const response = yield globalAxios$1.post(`${this.config.authenticationDomain}/oauth/token`, {
13699
+ client_id: this.config.oidcConfiguration.clientId,
13700
+ grant_type: 'authorization_code',
13701
+ code_verifier: codeVerifier,
13702
+ code: authorizationCode,
13703
+ redirect_uri: this.config.oidcConfiguration.redirectUri,
13704
+ }, formUrlEncodedHeader);
13705
+ return response.data;
13706
+ });
13707
+ }
13708
+ logout() {
13709
+ return __awaiter(this, void 0, void 0, function* () {
13710
+ return withPassportError(() => __awaiter(this, void 0, void 0, function* () {
13711
+ if (this.logoutMode === 'silent') {
13712
+ return this.userManager.signoutSilent();
13713
+ }
13714
+ return this.userManager.signoutRedirect();
13715
+ }), PassportErrorType.LOGOUT_ERROR);
13716
+ });
13696
13717
  }
13697
- async removeUser() {
13698
- return this.userManager.removeUser();
13718
+ removeUser() {
13719
+ return __awaiter(this, void 0, void 0, function* () {
13720
+ return this.userManager.removeUser();
13721
+ });
13699
13722
  }
13700
13723
  getDeviceFlowEndSessionEndpoint() {
13701
13724
  const { authenticationDomain, oidcConfiguration } = this.config;
@@ -13706,54 +13729,60 @@ class AuthManager {
13706
13729
  }
13707
13730
  return endSessionEndpoint;
13708
13731
  }
13709
- async logoutSilentCallback(url) {
13710
- return this.userManager.signoutSilentCallback(url);
13732
+ logoutSilentCallback(url) {
13733
+ return __awaiter(this, void 0, void 0, function* () {
13734
+ return this.userManager.signoutSilentCallback(url);
13735
+ });
13711
13736
  }
13712
13737
  forceUserRefreshInBackground() {
13713
13738
  this.refreshTokenAndUpdatePromise().catch((error) => {
13714
13739
  logger.warn('Failed to refresh user token', error);
13715
13740
  });
13716
13741
  }
13717
- async forceUserRefresh() {
13718
- return this.refreshTokenAndUpdatePromise();
13742
+ forceUserRefresh() {
13743
+ return __awaiter(this, void 0, void 0, function* () {
13744
+ return this.refreshTokenAndUpdatePromise();
13745
+ });
13719
13746
  }
13720
13747
  /**
13721
13748
  * Refreshes the token and returns the user.
13722
13749
  * If the token is already being refreshed, returns the existing promise.
13723
13750
  */
13724
- async refreshTokenAndUpdatePromise() {
13725
- if (this.refreshingPromise)
13726
- return this.refreshingPromise;
13727
- // eslint-disable-next-line no-async-promise-executor
13728
- this.refreshingPromise = new Promise(async (resolve, reject) => {
13729
- try {
13730
- const newOidcUser = await this.userManager.signinSilent();
13731
- if (newOidcUser) {
13732
- resolve(AuthManager.mapOidcUserToDomainModel(newOidcUser));
13733
- return;
13734
- }
13735
- resolve(null);
13736
- }
13737
- catch (err) {
13738
- let passportErrorType = PassportErrorType.AUTHENTICATION_ERROR;
13739
- let errorMessage = 'Failed to refresh token';
13740
- if (err instanceof ErrorTimeout) {
13741
- passportErrorType = PassportErrorType.SILENT_LOGIN_ERROR;
13751
+ refreshTokenAndUpdatePromise() {
13752
+ return __awaiter(this, void 0, void 0, function* () {
13753
+ if (this.refreshingPromise)
13754
+ return this.refreshingPromise;
13755
+ // eslint-disable-next-line no-async-promise-executor
13756
+ this.refreshingPromise = new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
13757
+ try {
13758
+ const newOidcUser = yield this.userManager.signinSilent();
13759
+ if (newOidcUser) {
13760
+ resolve(AuthManager.mapOidcUserToDomainModel(newOidcUser));
13761
+ return;
13762
+ }
13763
+ resolve(null);
13742
13764
  }
13743
- else if (err instanceof ErrorResponse) {
13744
- passportErrorType = PassportErrorType.NOT_LOGGED_IN_ERROR;
13745
- errorMessage = `${err.message}: ${err.error_description}`;
13765
+ catch (err) {
13766
+ let passportErrorType = PassportErrorType.AUTHENTICATION_ERROR;
13767
+ let errorMessage = 'Failed to refresh token';
13768
+ if (err instanceof ErrorTimeout) {
13769
+ passportErrorType = PassportErrorType.SILENT_LOGIN_ERROR;
13770
+ }
13771
+ else if (err instanceof ErrorResponse) {
13772
+ passportErrorType = PassportErrorType.NOT_LOGGED_IN_ERROR;
13773
+ errorMessage = `${err.message}: ${err.error_description}`;
13774
+ }
13775
+ else if (err instanceof Error) {
13776
+ errorMessage = err.message;
13777
+ }
13778
+ reject(new PassportError(errorMessage, passportErrorType));
13746
13779
  }
13747
- else if (err instanceof Error) {
13748
- errorMessage = err.message;
13780
+ finally {
13781
+ this.refreshingPromise = null; // Reset the promise after completion
13749
13782
  }
13750
- reject(new PassportError(errorMessage, passportErrorType));
13751
- }
13752
- finally {
13753
- this.refreshingPromise = null; // Reset the promise after completion
13754
- }
13783
+ }));
13784
+ return this.refreshingPromise;
13755
13785
  });
13756
- return this.refreshingPromise;
13757
13786
  }
13758
13787
  /**
13759
13788
  *
@@ -13768,46 +13797,103 @@ class AuthManager {
13768
13797
  * 3. Attempt to refresh the User if a refresh token is present.
13769
13798
  * 4. Return null if no valid User can be obtained.
13770
13799
  */
13771
- async getUser(typeAssertion = (user) => true) {
13772
- if (this.refreshingPromise) {
13773
- const user = await this.refreshingPromise;
13774
- if (user && typeAssertion(user)) {
13775
- return user;
13800
+ getUser(typeAssertion = (user) => true) {
13801
+ return __awaiter(this, void 0, void 0, function* () {
13802
+ if (this.refreshingPromise) {
13803
+ const user = yield this.refreshingPromise;
13804
+ if (user && typeAssertion(user)) {
13805
+ return user;
13806
+ }
13807
+ return null;
13808
+ }
13809
+ const oidcUser = yield this.userManager.getUser();
13810
+ if (!oidcUser)
13811
+ return null;
13812
+ if (!isTokenExpired(oidcUser)) {
13813
+ const user = AuthManager.mapOidcUserToDomainModel(oidcUser);
13814
+ if (user && typeAssertion(user)) {
13815
+ return user;
13816
+ }
13817
+ }
13818
+ if (oidcUser.refresh_token) {
13819
+ const user = yield this.refreshTokenAndUpdatePromise();
13820
+ if (user && typeAssertion(user)) {
13821
+ return user;
13822
+ }
13776
13823
  }
13777
13824
  return null;
13778
- }
13779
- const oidcUser = await this.userManager.getUser();
13780
- if (!oidcUser)
13781
- return null;
13782
- if (!isTokenExpired(oidcUser)) {
13783
- const user = AuthManager.mapOidcUserToDomainModel(oidcUser);
13784
- if (user && typeAssertion(user)) {
13785
- return user;
13825
+ });
13826
+ }
13827
+ getUserZkEvm() {
13828
+ return __awaiter(this, void 0, void 0, function* () {
13829
+ const user = yield this.getUser(isUserZkEvm);
13830
+ if (!user) {
13831
+ throw new Error('Failed to obtain a User with the required ZkEvm attributes');
13786
13832
  }
13787
- }
13788
- if (oidcUser.refresh_token) {
13789
- const user = await this.refreshTokenAndUpdatePromise();
13790
- if (user && typeAssertion(user)) {
13791
- return user;
13833
+ return user;
13834
+ });
13835
+ }
13836
+ getUserImx() {
13837
+ return __awaiter(this, void 0, void 0, function* () {
13838
+ const user = yield this.getUser(isUserImx);
13839
+ if (!user) {
13840
+ throw new Error('Failed to obtain a User with the required IMX attributes');
13792
13841
  }
13793
- }
13794
- return null;
13842
+ return user;
13843
+ });
13795
13844
  }
13796
- async getUserZkEvm() {
13797
- const user = await this.getUser(isUserZkEvm);
13798
- if (!user) {
13799
- throw new Error('Failed to obtain a User with the required ZkEvm attributes');
13800
- }
13801
- return user;
13845
+ }
13846
+ AuthManager.mapOidcUserToDomainModel = (oidcUser) => {
13847
+ var _a;
13848
+ let passport;
13849
+ if (oidcUser.id_token) {
13850
+ passport = (_a = jwt_decode(oidcUser.id_token)) === null || _a === void 0 ? void 0 : _a.passport;
13851
+ }
13852
+ const user = {
13853
+ expired: oidcUser.expired,
13854
+ idToken: oidcUser.id_token,
13855
+ accessToken: oidcUser.access_token,
13856
+ refreshToken: oidcUser.refresh_token,
13857
+ profile: {
13858
+ sub: oidcUser.profile.sub,
13859
+ email: oidcUser.profile.email,
13860
+ nickname: oidcUser.profile.nickname,
13861
+ },
13862
+ };
13863
+ if (passport === null || passport === void 0 ? void 0 : passport.imx_eth_address) {
13864
+ user.imx = {
13865
+ ethAddress: passport.imx_eth_address,
13866
+ starkAddress: passport.imx_stark_address,
13867
+ userAdminAddress: passport.imx_user_admin_address,
13868
+ };
13802
13869
  }
13803
- async getUserImx() {
13804
- const user = await this.getUser(isUserImx);
13805
- if (!user) {
13806
- throw new Error('Failed to obtain a User with the required IMX attributes');
13807
- }
13808
- return user;
13870
+ if (passport === null || passport === void 0 ? void 0 : passport.zkevm_eth_address) {
13871
+ user.zkEvm = {
13872
+ ethAddress: passport === null || passport === void 0 ? void 0 : passport.zkevm_eth_address,
13873
+ userAdminAddress: passport === null || passport === void 0 ? void 0 : passport.zkevm_user_admin_address,
13874
+ };
13809
13875
  }
13810
- }
13876
+ return user;
13877
+ };
13878
+ AuthManager.mapDeviceTokenResponseToOidcUser = (tokenResponse) => {
13879
+ const idTokenPayload = jwt_decode(tokenResponse.id_token);
13880
+ return new User({
13881
+ id_token: tokenResponse.id_token,
13882
+ access_token: tokenResponse.access_token,
13883
+ refresh_token: tokenResponse.refresh_token,
13884
+ token_type: tokenResponse.token_type,
13885
+ profile: {
13886
+ sub: idTokenPayload.sub,
13887
+ iss: idTokenPayload.iss,
13888
+ aud: idTokenPayload.aud,
13889
+ exp: idTokenPayload.exp,
13890
+ iat: idTokenPayload.iat,
13891
+ email: idTokenPayload.email,
13892
+ nickname: idTokenPayload.nickname,
13893
+ passport: idTokenPayload.passport,
13894
+ },
13895
+ });
13896
+ };
13811
13897
 
13812
13898
  const lazyLoad = (promiseToAwait, initialiseFunction) => promiseToAwait().then(initialiseFunction);
13813
13899
  const lazyDocumentReady = (initialiseFunction) => {
@@ -13830,8 +13916,6 @@ const lazyDocumentReady = (initialiseFunction) => {
13830
13916
 
13831
13917
  const MAINNET = 'mainnet';
13832
13918
  class MagicAdapter {
13833
- config;
13834
- lazyMagicClient;
13835
13919
  constructor(config) {
13836
13920
  this.config = config;
13837
13921
  if (typeof window !== 'undefined') {
@@ -13851,320 +13935,341 @@ class MagicAdapter {
13851
13935
  }
13852
13936
  return this.lazyMagicClient;
13853
13937
  }
13854
- async login(idToken) {
13855
- return withPassportError(async () => {
13856
- const magicClient = await this.magicClient;
13857
- await magicClient.openid.loginWithOIDC({
13858
- jwt: idToken,
13859
- providerId: this.config.magicProviderId,
13860
- });
13861
- return magicClient.rpcProvider;
13862
- }, PassportErrorType.WALLET_CONNECTION_ERROR);
13938
+ login(idToken) {
13939
+ return __awaiter(this, void 0, void 0, function* () {
13940
+ return withPassportError(() => __awaiter(this, void 0, void 0, function* () {
13941
+ const magicClient = yield this.magicClient;
13942
+ yield magicClient.openid.loginWithOIDC({
13943
+ jwt: idToken,
13944
+ providerId: this.config.magicProviderId,
13945
+ });
13946
+ return magicClient.rpcProvider;
13947
+ }), PassportErrorType.WALLET_CONNECTION_ERROR);
13948
+ });
13863
13949
  }
13864
- async logout() {
13865
- const magicClient = await this.magicClient;
13866
- if (magicClient.user) {
13867
- await magicClient.user.logout();
13868
- }
13950
+ logout() {
13951
+ return __awaiter(this, void 0, void 0, function* () {
13952
+ const magicClient = yield this.magicClient;
13953
+ if (magicClient.user) {
13954
+ yield magicClient.user.logout();
13955
+ }
13956
+ });
13869
13957
  }
13870
13958
  }
13871
13959
 
13872
- const getStarkSigner = async (signer) => withPassportError(async () => {
13873
- const privateKey = await generateLegacyStarkPrivateKey(signer);
13874
- return createStarkSigner(privateKey);
13875
- }, PassportErrorType.WALLET_CONNECTION_ERROR);
13876
-
13877
- async function exchangeTransfer({ user, starkSigner, request, exchangesApi, }) {
13878
- return withPassportError(async () => {
13879
- const { ethAddress } = user.imx;
13880
- const transferAmount = request.amount;
13881
- const signableResult = await exchangesApi.getExchangeSignableTransfer({
13882
- id: request.transactionID,
13883
- getSignableTransferRequest: {
13884
- sender: ethAddress,
13885
- token: convertToSignableToken(request),
13886
- amount: transferAmount,
13887
- receiver: request.receiver,
13888
- },
13889
- });
13890
- const starkAddress = await starkSigner.getAddress();
13891
- const { payload_hash: payloadHash } = signableResult.data;
13892
- const starkSignature = await starkSigner.signMessage(payloadHash);
13893
- const transferSigningParams = {
13894
- sender_stark_key: signableResult.data.sender_stark_key || starkAddress,
13895
- sender_vault_id: signableResult.data.sender_vault_id,
13896
- receiver_stark_key: signableResult.data.receiver_stark_key,
13897
- receiver_vault_id: signableResult.data.receiver_vault_id,
13898
- asset_id: signableResult.data.asset_id,
13899
- amount: signableResult.data.amount,
13900
- nonce: signableResult.data.nonce,
13901
- expiration_timestamp: signableResult.data.expiration_timestamp,
13902
- stark_signature: starkSignature,
13903
- };
13904
- const headers = {
13905
- // eslint-disable-next-line @typescript-eslint/naming-convention
13906
- Authorization: `Bearer ${user.accessToken}`,
13907
- };
13908
- const response = await exchangesApi.createExchangeTransfer({
13909
- id: request.transactionID,
13910
- createTransferRequest: transferSigningParams,
13911
- }, { headers });
13912
- return {
13913
- sent_signature: response?.data.sent_signature,
13914
- status: response?.data.status?.toString(),
13915
- time: response?.data.time,
13916
- transfer_id: response?.data.transfer_id,
13917
- };
13918
- }, PassportErrorType.EXCHANGE_TRANSFER_ERROR);
13960
+ const getStarkSigner = (signer) => __awaiter(void 0, void 0, void 0, function* () {
13961
+ return withPassportError(() => __awaiter(void 0, void 0, void 0, function* () {
13962
+ const privateKey = yield generateLegacyStarkPrivateKey(signer);
13963
+ return createStarkSigner(privateKey);
13964
+ }), PassportErrorType.WALLET_CONNECTION_ERROR);
13965
+ });
13966
+
13967
+ function exchangeTransfer({ user, starkSigner, request, exchangesApi, }) {
13968
+ return __awaiter(this, void 0, void 0, function* () {
13969
+ return withPassportError(() => __awaiter(this, void 0, void 0, function* () {
13970
+ var _a;
13971
+ const { ethAddress } = user.imx;
13972
+ const transferAmount = request.amount;
13973
+ const signableResult = yield exchangesApi.getExchangeSignableTransfer({
13974
+ id: request.transactionID,
13975
+ getSignableTransferRequest: {
13976
+ sender: ethAddress,
13977
+ token: convertToSignableToken(request),
13978
+ amount: transferAmount,
13979
+ receiver: request.receiver,
13980
+ },
13981
+ });
13982
+ const starkAddress = yield starkSigner.getAddress();
13983
+ const { payload_hash: payloadHash } = signableResult.data;
13984
+ const starkSignature = yield starkSigner.signMessage(payloadHash);
13985
+ const transferSigningParams = {
13986
+ sender_stark_key: signableResult.data.sender_stark_key || starkAddress,
13987
+ sender_vault_id: signableResult.data.sender_vault_id,
13988
+ receiver_stark_key: signableResult.data.receiver_stark_key,
13989
+ receiver_vault_id: signableResult.data.receiver_vault_id,
13990
+ asset_id: signableResult.data.asset_id,
13991
+ amount: signableResult.data.amount,
13992
+ nonce: signableResult.data.nonce,
13993
+ expiration_timestamp: signableResult.data.expiration_timestamp,
13994
+ stark_signature: starkSignature,
13995
+ };
13996
+ const headers = {
13997
+ // eslint-disable-next-line @typescript-eslint/naming-convention
13998
+ Authorization: `Bearer ${user.accessToken}`,
13999
+ };
14000
+ const response = yield exchangesApi.createExchangeTransfer({
14001
+ id: request.transactionID,
14002
+ createTransferRequest: transferSigningParams,
14003
+ }, { headers });
14004
+ return {
14005
+ sent_signature: response === null || response === void 0 ? void 0 : response.data.sent_signature,
14006
+ status: (_a = response === null || response === void 0 ? void 0 : response.data.status) === null || _a === void 0 ? void 0 : _a.toString(),
14007
+ time: response === null || response === void 0 ? void 0 : response.data.time,
14008
+ transfer_id: response === null || response === void 0 ? void 0 : response.data.transfer_id,
14009
+ };
14010
+ }), PassportErrorType.EXCHANGE_TRANSFER_ERROR);
14011
+ });
13919
14012
  }
13920
14013
 
13921
14014
  const ERC721$1 = 'ERC721';
13922
- async function createOrder({ starkSigner, user, request, ordersApi, guardianClient, }) {
13923
- return withPassportError(guardianClient.withDefaultConfirmationScreenTask(async () => {
13924
- const { ethAddress } = user.imx;
13925
- const amountSell = request.sell.type === ERC721$1 ? '1' : request.sell.amount;
13926
- const amountBuy = request.buy.type === ERC721$1 ? '1' : request.buy.amount;
13927
- const headers = { Authorization: `Bearer ${user.accessToken}` };
13928
- const getSignableOrderRequestV3 = {
13929
- user: ethAddress,
13930
- amount_buy: amountBuy,
13931
- token_buy: convertToSignableToken(request.buy),
13932
- amount_sell: amountSell,
13933
- token_sell: convertToSignableToken(request.sell),
13934
- fees: request.fees,
13935
- split_fees: true,
13936
- expiration_timestamp: request.expiration_timestamp,
13937
- };
13938
- const getSignableOrderResponse = await ordersApi.getSignableOrder({
13939
- getSignableOrderRequestV3,
13940
- }, { headers });
13941
- await guardianClient.evaluateImxTransaction({
13942
- payloadHash: getSignableOrderResponse.data.payload_hash,
13943
- });
13944
- const { payload_hash: payloadHash } = getSignableOrderResponse.data;
13945
- const starkSignature = await starkSigner.signMessage(payloadHash);
13946
- const signableResultData = getSignableOrderResponse.data;
13947
- const orderParams = {
13948
- createOrderRequest: {
13949
- include_fees: true,
14015
+ function createOrder({ starkSigner, user, request, ordersApi, guardianClient, }) {
14016
+ return __awaiter(this, void 0, void 0, function* () {
14017
+ return withPassportError(guardianClient.withDefaultConfirmationScreenTask(() => __awaiter(this, void 0, void 0, function* () {
14018
+ const { ethAddress } = user.imx;
14019
+ const amountSell = request.sell.type === ERC721$1 ? '1' : request.sell.amount;
14020
+ const amountBuy = request.buy.type === ERC721$1 ? '1' : request.buy.amount;
14021
+ const headers = { Authorization: `Bearer ${user.accessToken}` };
14022
+ const getSignableOrderRequestV3 = {
14023
+ user: ethAddress,
14024
+ amount_buy: amountBuy,
14025
+ token_buy: convertToSignableToken(request.buy),
14026
+ amount_sell: amountSell,
14027
+ token_sell: convertToSignableToken(request.sell),
13950
14028
  fees: request.fees,
13951
- stark_signature: starkSignature,
13952
- amount_buy: signableResultData.amount_buy,
13953
- amount_sell: signableResultData.amount_sell,
13954
- asset_id_buy: signableResultData.asset_id_buy,
13955
- asset_id_sell: signableResultData.asset_id_sell,
13956
- expiration_timestamp: signableResultData.expiration_timestamp,
13957
- nonce: signableResultData.nonce,
13958
- stark_key: signableResultData.stark_key,
13959
- vault_id_buy: signableResultData.vault_id_buy,
13960
- vault_id_sell: signableResultData.vault_id_sell,
13961
- },
13962
- };
13963
- const createOrderResponse = await ordersApi.createOrderV3(orderParams, {
13964
- headers,
13965
- });
13966
- return {
13967
- ...createOrderResponse.data,
13968
- };
13969
- }), PassportErrorType.CREATE_ORDER_ERROR);
14029
+ split_fees: true,
14030
+ expiration_timestamp: request.expiration_timestamp,
14031
+ };
14032
+ const getSignableOrderResponse = yield ordersApi.getSignableOrder({
14033
+ getSignableOrderRequestV3,
14034
+ }, { headers });
14035
+ yield guardianClient.evaluateImxTransaction({
14036
+ payloadHash: getSignableOrderResponse.data.payload_hash,
14037
+ });
14038
+ const { payload_hash: payloadHash } = getSignableOrderResponse.data;
14039
+ const starkSignature = yield starkSigner.signMessage(payloadHash);
14040
+ const signableResultData = getSignableOrderResponse.data;
14041
+ const orderParams = {
14042
+ createOrderRequest: {
14043
+ include_fees: true,
14044
+ fees: request.fees,
14045
+ stark_signature: starkSignature,
14046
+ amount_buy: signableResultData.amount_buy,
14047
+ amount_sell: signableResultData.amount_sell,
14048
+ asset_id_buy: signableResultData.asset_id_buy,
14049
+ asset_id_sell: signableResultData.asset_id_sell,
14050
+ expiration_timestamp: signableResultData.expiration_timestamp,
14051
+ nonce: signableResultData.nonce,
14052
+ stark_key: signableResultData.stark_key,
14053
+ vault_id_buy: signableResultData.vault_id_buy,
14054
+ vault_id_sell: signableResultData.vault_id_sell,
14055
+ },
14056
+ };
14057
+ const createOrderResponse = yield ordersApi.createOrderV3(orderParams, {
14058
+ headers,
14059
+ });
14060
+ return Object.assign({}, createOrderResponse.data);
14061
+ })), PassportErrorType.CREATE_ORDER_ERROR);
14062
+ });
13970
14063
  }
13971
- async function cancelOrder({ user, starkSigner, request, ordersApi, guardianClient, }) {
13972
- return withPassportError(guardianClient.withDefaultConfirmationScreenTask(async () => {
13973
- const getSignableCancelOrderRequest = {
13974
- order_id: request.order_id,
13975
- };
13976
- const headers = {
13977
- // eslint-disable-next-line @typescript-eslint/naming-convention
13978
- Authorization: `Bearer ${user.accessToken}`,
13979
- };
13980
- const getSignableCancelOrderResponse = await ordersApi.getSignableCancelOrderV3({
13981
- getSignableCancelOrderRequest,
13982
- }, { headers });
13983
- await guardianClient.evaluateImxTransaction({
13984
- payloadHash: getSignableCancelOrderResponse.data.payload_hash,
13985
- });
13986
- const { payload_hash: payloadHash } = getSignableCancelOrderResponse.data;
13987
- const starkSignature = await starkSigner.signMessage(payloadHash);
13988
- const cancelOrderResponse = await ordersApi.cancelOrderV3({
13989
- id: request.order_id.toString(),
13990
- cancelOrderRequest: {
14064
+ function cancelOrder({ user, starkSigner, request, ordersApi, guardianClient, }) {
14065
+ return __awaiter(this, void 0, void 0, function* () {
14066
+ return withPassportError(guardianClient.withDefaultConfirmationScreenTask(() => __awaiter(this, void 0, void 0, function* () {
14067
+ const getSignableCancelOrderRequest = {
13991
14068
  order_id: request.order_id,
13992
- stark_signature: starkSignature,
13993
- },
13994
- }, { headers });
13995
- return {
13996
- order_id: cancelOrderResponse.data.order_id,
13997
- status: cancelOrderResponse.data.status,
13998
- };
13999
- }), PassportErrorType.CANCEL_ORDER_ERROR);
14000
- }
14001
-
14002
- async function registerPassport({ ethSigner, starkSigner, imxApiClients }, authorization) {
14003
- const [userAddress, starkPublicKey] = await Promise.all([
14004
- ethSigner.getAddress(),
14005
- starkSigner.getAddress(),
14006
- ]);
14007
- const signableResult = await imxApiClients.usersApi.getSignableRegistrationOffchain({
14008
- getSignableRegistrationRequest: {
14009
- ether_key: userAddress,
14010
- stark_key: starkPublicKey,
14011
- },
14012
- });
14013
- const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
14014
- const [ethSignature, starkSignature] = await Promise.all([
14015
- signRaw(signableMessage, ethSigner),
14016
- starkSigner.signMessage(payloadHash),
14017
- ]);
14018
- const response = await imxApiClients.usersApi.registerPassportUserV2({
14019
- authorization: `Bearer ${authorization}`,
14020
- registerPassportUserRequest: {
14021
- eth_signature: ethSignature,
14022
- ether_key: userAddress,
14023
- stark_signature: starkSignature,
14024
- stark_key: starkPublicKey,
14025
- },
14069
+ };
14070
+ const headers = {
14071
+ // eslint-disable-next-line @typescript-eslint/naming-convention
14072
+ Authorization: `Bearer ${user.accessToken}`,
14073
+ };
14074
+ const getSignableCancelOrderResponse = yield ordersApi.getSignableCancelOrderV3({
14075
+ getSignableCancelOrderRequest,
14076
+ }, { headers });
14077
+ yield guardianClient.evaluateImxTransaction({
14078
+ payloadHash: getSignableCancelOrderResponse.data.payload_hash,
14079
+ });
14080
+ const { payload_hash: payloadHash } = getSignableCancelOrderResponse.data;
14081
+ const starkSignature = yield starkSigner.signMessage(payloadHash);
14082
+ const cancelOrderResponse = yield ordersApi.cancelOrderV3({
14083
+ id: request.order_id.toString(),
14084
+ cancelOrderRequest: {
14085
+ order_id: request.order_id,
14086
+ stark_signature: starkSignature,
14087
+ },
14088
+ }, { headers });
14089
+ return {
14090
+ order_id: cancelOrderResponse.data.order_id,
14091
+ status: cancelOrderResponse.data.status,
14092
+ };
14093
+ })), PassportErrorType.CANCEL_ORDER_ERROR);
14026
14094
  });
14027
- return response.data;
14028
14095
  }
14029
14096
 
14030
- async function createTrade({ request, tradesApi, user, starkSigner, guardianClient, }) {
14031
- return withPassportError(guardianClient.withDefaultConfirmationScreenTask(async () => {
14032
- const { ethAddress } = user.imx;
14033
- const getSignableTradeRequest = {
14034
- expiration_timestamp: request.expiration_timestamp,
14035
- fees: request.fees,
14036
- order_id: request.order_id,
14037
- user: ethAddress,
14038
- };
14039
- // eslint-disable-next-line @typescript-eslint/naming-convention
14040
- const headers = { Authorization: `Bearer ${user.accessToken}` };
14041
- const getSignableTradeResponse = await tradesApi.getSignableTrade({
14042
- getSignableTradeRequest,
14043
- }, { headers });
14044
- await guardianClient.evaluateImxTransaction({
14045
- payloadHash: getSignableTradeResponse.data.payload_hash,
14097
+ function registerPassport({ ethSigner, starkSigner, imxApiClients }, authorization) {
14098
+ return __awaiter(this, void 0, void 0, function* () {
14099
+ const [userAddress, starkPublicKey] = yield Promise.all([
14100
+ ethSigner.getAddress(),
14101
+ starkSigner.getAddress(),
14102
+ ]);
14103
+ const signableResult = yield imxApiClients.usersApi.getSignableRegistrationOffchain({
14104
+ getSignableRegistrationRequest: {
14105
+ ether_key: userAddress,
14106
+ stark_key: starkPublicKey,
14107
+ },
14046
14108
  });
14047
- const { payload_hash: payloadHash } = getSignableTradeResponse.data;
14048
- const starkSignature = await starkSigner.signMessage(payloadHash);
14049
- const { data: signableResultData } = getSignableTradeResponse;
14050
- const tradeParams = {
14051
- createTradeRequest: {
14052
- include_fees: true,
14053
- fees: request?.fees,
14109
+ const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
14110
+ const [ethSignature, starkSignature] = yield Promise.all([
14111
+ signRaw(signableMessage, ethSigner),
14112
+ starkSigner.signMessage(payloadHash),
14113
+ ]);
14114
+ const response = yield imxApiClients.usersApi.registerPassportUserV2({
14115
+ authorization: `Bearer ${authorization}`,
14116
+ registerPassportUserRequest: {
14117
+ eth_signature: ethSignature,
14118
+ ether_key: userAddress,
14054
14119
  stark_signature: starkSignature,
14055
- order_id: request?.order_id,
14056
- fee_info: signableResultData.fee_info,
14057
- amount_buy: signableResultData.amount_buy,
14058
- amount_sell: signableResultData.amount_sell,
14059
- asset_id_buy: signableResultData.asset_id_buy,
14060
- asset_id_sell: signableResultData.asset_id_sell,
14061
- expiration_timestamp: signableResultData.expiration_timestamp,
14062
- nonce: signableResultData.nonce,
14063
- stark_key: signableResultData.stark_key,
14064
- vault_id_buy: signableResultData.vault_id_buy,
14065
- vault_id_sell: signableResultData.vault_id_sell,
14120
+ stark_key: starkPublicKey,
14066
14121
  },
14067
- };
14068
- const { data: createTradeResponse } = await tradesApi.createTradeV3(tradeParams, {
14069
- headers,
14070
14122
  });
14071
- return createTradeResponse;
14072
- }), PassportErrorType.CREATE_TRADE_ERROR);
14123
+ return response.data;
14124
+ });
14125
+ }
14126
+
14127
+ function createTrade({ request, tradesApi, user, starkSigner, guardianClient, }) {
14128
+ return __awaiter(this, void 0, void 0, function* () {
14129
+ return withPassportError(guardianClient.withDefaultConfirmationScreenTask(() => __awaiter(this, void 0, void 0, function* () {
14130
+ const { ethAddress } = user.imx;
14131
+ const getSignableTradeRequest = {
14132
+ expiration_timestamp: request.expiration_timestamp,
14133
+ fees: request.fees,
14134
+ order_id: request.order_id,
14135
+ user: ethAddress,
14136
+ };
14137
+ // eslint-disable-next-line @typescript-eslint/naming-convention
14138
+ const headers = { Authorization: `Bearer ${user.accessToken}` };
14139
+ const getSignableTradeResponse = yield tradesApi.getSignableTrade({
14140
+ getSignableTradeRequest,
14141
+ }, { headers });
14142
+ yield guardianClient.evaluateImxTransaction({
14143
+ payloadHash: getSignableTradeResponse.data.payload_hash,
14144
+ });
14145
+ const { payload_hash: payloadHash } = getSignableTradeResponse.data;
14146
+ const starkSignature = yield starkSigner.signMessage(payloadHash);
14147
+ const { data: signableResultData } = getSignableTradeResponse;
14148
+ const tradeParams = {
14149
+ createTradeRequest: {
14150
+ include_fees: true,
14151
+ fees: request === null || request === void 0 ? void 0 : request.fees,
14152
+ stark_signature: starkSignature,
14153
+ order_id: request === null || request === void 0 ? void 0 : request.order_id,
14154
+ fee_info: signableResultData.fee_info,
14155
+ amount_buy: signableResultData.amount_buy,
14156
+ amount_sell: signableResultData.amount_sell,
14157
+ asset_id_buy: signableResultData.asset_id_buy,
14158
+ asset_id_sell: signableResultData.asset_id_sell,
14159
+ expiration_timestamp: signableResultData.expiration_timestamp,
14160
+ nonce: signableResultData.nonce,
14161
+ stark_key: signableResultData.stark_key,
14162
+ vault_id_buy: signableResultData.vault_id_buy,
14163
+ vault_id_sell: signableResultData.vault_id_sell,
14164
+ },
14165
+ };
14166
+ const { data: createTradeResponse } = yield tradesApi.createTradeV3(tradeParams, {
14167
+ headers,
14168
+ });
14169
+ return createTradeResponse;
14170
+ })), PassportErrorType.CREATE_TRADE_ERROR);
14171
+ });
14073
14172
  }
14074
14173
 
14075
14174
  const ERC721 = 'ERC721';
14076
- async function transfer({ request, transfersApi, starkSigner, user, guardianClient, }) {
14077
- return withPassportError(guardianClient.withDefaultConfirmationScreenTask(async () => {
14078
- const transferAmount = request.type === ERC721 ? '1' : request.amount;
14079
- const getSignableTransferRequest = {
14080
- sender: user.imx.ethAddress,
14081
- token: convertToSignableToken(request),
14082
- amount: transferAmount,
14083
- receiver: request.receiver,
14084
- };
14085
- const headers = {
14086
- Authorization: `Bearer ${user.accessToken}`,
14087
- };
14088
- const signableResult = await transfersApi.getSignableTransferV1({
14089
- getSignableTransferRequest,
14090
- }, { headers });
14091
- await guardianClient.evaluateImxTransaction({
14092
- payloadHash: signableResult.data.payload_hash,
14093
- });
14094
- const signableResultData = signableResult.data;
14095
- const { payload_hash: payloadHash } = signableResultData;
14096
- const starkSignature = await starkSigner.signMessage(payloadHash);
14097
- const senderStarkKey = await starkSigner.getAddress();
14098
- const transferSigningParams = {
14099
- sender_stark_key: signableResultData.sender_stark_key || senderStarkKey,
14100
- sender_vault_id: signableResultData.sender_vault_id,
14101
- receiver_stark_key: signableResultData.receiver_stark_key,
14102
- receiver_vault_id: signableResultData.receiver_vault_id,
14103
- asset_id: signableResultData.asset_id,
14104
- amount: signableResultData.amount,
14105
- nonce: signableResultData.nonce,
14106
- expiration_timestamp: signableResultData.expiration_timestamp,
14107
- stark_signature: starkSignature,
14108
- };
14109
- const createTransferRequest = {
14110
- createTransferRequest: transferSigningParams,
14111
- };
14112
- const { data: responseData } = await transfersApi.createTransferV1(createTransferRequest, { headers });
14113
- return {
14114
- sent_signature: responseData.sent_signature,
14115
- status: responseData.status?.toString(),
14116
- time: responseData.time,
14117
- transfer_id: responseData.transfer_id,
14118
- };
14119
- }), PassportErrorType.TRANSFER_ERROR);
14175
+ function transfer({ request, transfersApi, starkSigner, user, guardianClient, }) {
14176
+ return __awaiter(this, void 0, void 0, function* () {
14177
+ return withPassportError(guardianClient.withDefaultConfirmationScreenTask(() => __awaiter(this, void 0, void 0, function* () {
14178
+ var _a;
14179
+ const transferAmount = request.type === ERC721 ? '1' : request.amount;
14180
+ const getSignableTransferRequest = {
14181
+ sender: user.imx.ethAddress,
14182
+ token: convertToSignableToken(request),
14183
+ amount: transferAmount,
14184
+ receiver: request.receiver,
14185
+ };
14186
+ const headers = {
14187
+ Authorization: `Bearer ${user.accessToken}`,
14188
+ };
14189
+ const signableResult = yield transfersApi.getSignableTransferV1({
14190
+ getSignableTransferRequest,
14191
+ }, { headers });
14192
+ yield guardianClient.evaluateImxTransaction({
14193
+ payloadHash: signableResult.data.payload_hash,
14194
+ });
14195
+ const signableResultData = signableResult.data;
14196
+ const { payload_hash: payloadHash } = signableResultData;
14197
+ const starkSignature = yield starkSigner.signMessage(payloadHash);
14198
+ const senderStarkKey = yield starkSigner.getAddress();
14199
+ const transferSigningParams = {
14200
+ sender_stark_key: signableResultData.sender_stark_key || senderStarkKey,
14201
+ sender_vault_id: signableResultData.sender_vault_id,
14202
+ receiver_stark_key: signableResultData.receiver_stark_key,
14203
+ receiver_vault_id: signableResultData.receiver_vault_id,
14204
+ asset_id: signableResultData.asset_id,
14205
+ amount: signableResultData.amount,
14206
+ nonce: signableResultData.nonce,
14207
+ expiration_timestamp: signableResultData.expiration_timestamp,
14208
+ stark_signature: starkSignature,
14209
+ };
14210
+ const createTransferRequest = {
14211
+ createTransferRequest: transferSigningParams,
14212
+ };
14213
+ const { data: responseData } = yield transfersApi.createTransferV1(createTransferRequest, { headers });
14214
+ return {
14215
+ sent_signature: responseData.sent_signature,
14216
+ status: (_a = responseData.status) === null || _a === void 0 ? void 0 : _a.toString(),
14217
+ time: responseData.time,
14218
+ transfer_id: responseData.transfer_id,
14219
+ };
14220
+ })), PassportErrorType.TRANSFER_ERROR);
14221
+ });
14120
14222
  }
14121
- async function batchNftTransfer({ user, starkSigner, request, transfersApi, guardianClient, }) {
14122
- // eslint-disable-next-line function-paren-newline
14123
- return withPassportError(guardianClient.withConfirmationScreenTask({ width: 480, height: 784 })(async () => {
14124
- const { ethAddress } = user.imx;
14125
- const signableRequests = request.map((nftTransfer) => ({
14126
- amount: '1',
14127
- token: convertToSignableToken({
14128
- type: ERC721,
14129
- tokenId: nftTransfer.tokenId,
14130
- tokenAddress: nftTransfer.tokenAddress,
14131
- }),
14132
- receiver: nftTransfer.receiver,
14133
- }));
14134
- const headers = { Authorization: `Bearer ${user.accessToken}` };
14135
- const signableResult = await transfersApi.getSignableTransfer({
14136
- getSignableTransferRequestV2: {
14137
- sender_ether_key: ethAddress,
14138
- signable_requests: signableRequests,
14139
- },
14140
- }, { headers });
14141
- await guardianClient.evaluateImxTransaction({
14142
- payloadHash: signableResult.data.signable_responses[0]?.payload_hash,
14143
- });
14144
- const requests = await Promise.all(signableResult.data.signable_responses.map(async (resp) => {
14145
- const starkSignature = await starkSigner.signMessage(resp.payload_hash);
14223
+ function batchNftTransfer({ user, starkSigner, request, transfersApi, guardianClient, }) {
14224
+ return __awaiter(this, void 0, void 0, function* () {
14225
+ // eslint-disable-next-line function-paren-newline
14226
+ return withPassportError(guardianClient.withConfirmationScreenTask({ width: 480, height: 784 })(() => __awaiter(this, void 0, void 0, function* () {
14227
+ var _a;
14228
+ const { ethAddress } = user.imx;
14229
+ const signableRequests = request.map((nftTransfer) => ({
14230
+ amount: '1',
14231
+ token: convertToSignableToken({
14232
+ type: ERC721,
14233
+ tokenId: nftTransfer.tokenId,
14234
+ tokenAddress: nftTransfer.tokenAddress,
14235
+ }),
14236
+ receiver: nftTransfer.receiver,
14237
+ }));
14238
+ const headers = { Authorization: `Bearer ${user.accessToken}` };
14239
+ const signableResult = yield transfersApi.getSignableTransfer({
14240
+ getSignableTransferRequestV2: {
14241
+ sender_ether_key: ethAddress,
14242
+ signable_requests: signableRequests,
14243
+ },
14244
+ }, { headers });
14245
+ yield guardianClient.evaluateImxTransaction({
14246
+ payloadHash: (_a = signableResult.data.signable_responses[0]) === null || _a === void 0 ? void 0 : _a.payload_hash,
14247
+ });
14248
+ const requests = yield Promise.all(signableResult.data.signable_responses.map((resp) => __awaiter(this, void 0, void 0, function* () {
14249
+ const starkSignature = yield starkSigner.signMessage(resp.payload_hash);
14250
+ return {
14251
+ sender_vault_id: resp.sender_vault_id,
14252
+ receiver_stark_key: resp.receiver_stark_key,
14253
+ receiver_vault_id: resp.receiver_vault_id,
14254
+ asset_id: resp.asset_id,
14255
+ amount: resp.amount,
14256
+ nonce: resp.nonce,
14257
+ expiration_timestamp: resp.expiration_timestamp,
14258
+ stark_signature: starkSignature,
14259
+ };
14260
+ })));
14261
+ const transferSigningParams = {
14262
+ sender_stark_key: signableResult.data.sender_stark_key,
14263
+ requests,
14264
+ };
14265
+ const response = yield transfersApi.createTransfer({
14266
+ createTransferRequestV2: transferSigningParams,
14267
+ }, { headers });
14146
14268
  return {
14147
- sender_vault_id: resp.sender_vault_id,
14148
- receiver_stark_key: resp.receiver_stark_key,
14149
- receiver_vault_id: resp.receiver_vault_id,
14150
- asset_id: resp.asset_id,
14151
- amount: resp.amount,
14152
- nonce: resp.nonce,
14153
- expiration_timestamp: resp.expiration_timestamp,
14154
- stark_signature: starkSignature,
14269
+ transfer_ids: response === null || response === void 0 ? void 0 : response.data.transfer_ids,
14155
14270
  };
14156
- }));
14157
- const transferSigningParams = {
14158
- sender_stark_key: signableResult.data.sender_stark_key,
14159
- requests,
14160
- };
14161
- const response = await transfersApi.createTransfer({
14162
- createTransferRequestV2: transferSigningParams,
14163
- }, { headers });
14164
- return {
14165
- transfer_ids: response?.data.transfer_ids,
14166
- };
14167
- }), PassportErrorType.TRANSFER_ERROR);
14271
+ })), PassportErrorType.TRANSFER_ERROR);
14272
+ });
14168
14273
  }
14169
14274
 
14170
14275
  const POLL_INTERVAL = 1 * 1000; // every 1 second
@@ -14172,16 +14277,16 @@ const MAX_RETRIES = 3;
14172
14277
  const wait = (ms) => new Promise((resolve) => {
14173
14278
  setTimeout(() => resolve(), ms);
14174
14279
  });
14175
- const retryWithDelay = async (fn, options) => {
14280
+ const retryWithDelay = (fn, options) => __awaiter(void 0, void 0, void 0, function* () {
14176
14281
  const { retries = MAX_RETRIES, interval = POLL_INTERVAL, finalErr = Error('Retry failed'), finallyFn = () => { }, } = options || {};
14177
14282
  try {
14178
- return await fn();
14283
+ return yield fn();
14179
14284
  }
14180
14285
  catch (err) {
14181
14286
  if (retries <= 0) {
14182
14287
  return Promise.reject(finalErr);
14183
14288
  }
14184
- await wait(interval);
14289
+ yield wait(interval);
14185
14290
  return retryWithDelay(fn, { retries: retries - 1, finalErr, finallyFn });
14186
14291
  }
14187
14292
  finally {
@@ -14189,203 +14294,147 @@ const retryWithDelay = async (fn, options) => {
14189
14294
  finallyFn();
14190
14295
  }
14191
14296
  }
14192
- };
14297
+ });
14193
14298
 
14194
- async function forceUserRefresh(authManager) {
14195
- // User metadata is updated asynchronously. Poll userinfo endpoint until it is updated.
14196
- await retryWithDelay(async () => {
14197
- const user = await authManager.forceUserRefresh(); // force refresh to get updated user info
14198
- if (user?.imx)
14199
- return user;
14200
- return Promise.reject(new Error('user wallet addresses not exist'));
14299
+ function forceUserRefresh(authManager) {
14300
+ return __awaiter(this, void 0, void 0, function* () {
14301
+ // User metadata is updated asynchronously. Poll userinfo endpoint until it is updated.
14302
+ yield retryWithDelay(() => __awaiter(this, void 0, void 0, function* () {
14303
+ const user = yield authManager.forceUserRefresh(); // force refresh to get updated user info
14304
+ if (user === null || user === void 0 ? void 0 : user.imx)
14305
+ return user;
14306
+ return Promise.reject(new Error('user wallet addresses not exist'));
14307
+ }));
14201
14308
  });
14202
14309
  }
14203
- async function registerOffchain(userAdminKeySigner, starkSigner, unregisteredUser, authManager, imxApiClients) {
14204
- return withPassportError(async () => {
14205
- try {
14206
- const response = await registerPassport({
14207
- ethSigner: userAdminKeySigner,
14208
- starkSigner,
14209
- imxApiClients,
14210
- }, unregisteredUser.accessToken);
14211
- await forceUserRefresh(authManager);
14212
- return response;
14213
- }
14214
- catch (err) {
14215
- if (globalAxios$1.isAxiosError(err) && err.response?.status === 409) {
14216
- // The user already registered, but the user token is not updated yet.
14217
- await forceUserRefresh(authManager);
14218
- return { tx_hash: '' };
14310
+ function registerOffchain(userAdminKeySigner, starkSigner, unregisteredUser, authManager, imxApiClients) {
14311
+ return __awaiter(this, void 0, void 0, function* () {
14312
+ return withPassportError(() => __awaiter(this, void 0, void 0, function* () {
14313
+ var _a;
14314
+ try {
14315
+ const response = yield registerPassport({
14316
+ ethSigner: userAdminKeySigner,
14317
+ starkSigner,
14318
+ imxApiClients,
14319
+ }, unregisteredUser.accessToken);
14320
+ yield forceUserRefresh(authManager);
14321
+ return response;
14219
14322
  }
14220
- throw err;
14221
- }
14222
- }, PassportErrorType.USER_REGISTRATION_ERROR);
14323
+ catch (err) {
14324
+ if (globalAxios$1.isAxiosError(err) && ((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 409) {
14325
+ // The user already registered, but the user token is not updated yet.
14326
+ yield forceUserRefresh(authManager);
14327
+ return { tx_hash: '' };
14328
+ }
14329
+ throw err;
14330
+ }
14331
+ }), PassportErrorType.USER_REGISTRATION_ERROR);
14332
+ });
14223
14333
  }
14224
14334
 
14335
+ var _PassportImxProvider_instances, _PassportImxProvider_initialiseSigners, _PassportImxProvider_getAuthenticatedUser, _PassportImxProvider_getSigners, _PassportImxProvider_getRegisteredImxUserAndSigners;
14225
14336
  class PassportImxProvider {
14226
- authManager;
14227
- immutableXClient;
14228
- guardianClient;
14229
- imxApiClients;
14230
- magicAdapter;
14231
- /**
14232
- * This property is set during initialisation and stores the signers in a promise.
14233
- * This property is not meant to be accessed directly, but through the
14234
- * `#getSigners` method.
14235
- * @see #getSigners
14236
- */
14237
- signers;
14238
- signerInitialisationError;
14239
14337
  constructor({ authManager, immutableXClient, passportEventEmitter, magicAdapter, imxApiClients, guardianClient, }) {
14338
+ _PassportImxProvider_instances.add(this);
14339
+ this.handleLogout = () => {
14340
+ this.signers = undefined;
14341
+ };
14240
14342
  this.authManager = authManager;
14241
14343
  this.immutableXClient = immutableXClient;
14242
14344
  this.magicAdapter = magicAdapter;
14243
14345
  this.imxApiClients = imxApiClients;
14244
14346
  this.guardianClient = guardianClient;
14245
- this.#initialiseSigners();
14347
+ __classPrivateFieldGet(this, _PassportImxProvider_instances, "m", _PassportImxProvider_initialiseSigners).call(this);
14246
14348
  passportEventEmitter.on(PassportEvents.LOGGED_OUT, this.handleLogout);
14247
14349
  }
14248
- handleLogout = () => {
14249
- this.signers = undefined;
14250
- };
14251
- /**
14252
- * This method is called by the constructor and asynchronously initialises the signers.
14253
- * The signers are stored in a promise so that they can be retrieved by the provider
14254
- * when needed.
14255
- *
14256
- * If an error is thrown during initialisation, it is stored in the `signerInitialisationError`,
14257
- * so that it doesn't result in an unhandled promise rejection.
14258
- *
14259
- * This error is thrown when the signers are requested through:
14260
- * @see #getSigners
14261
- *
14262
- */
14263
- #initialiseSigners() {
14264
- const generateSigners = async () => {
14265
- const user = await this.authManager.getUser();
14266
- // The user will be present because the factory validates it
14267
- const magicRpcProvider = await this.magicAdapter.login(user.idToken);
14268
- const web3Provider = new Web3Provider(magicRpcProvider);
14269
- const ethSigner = web3Provider.getSigner();
14270
- const starkSigner = await getStarkSigner(ethSigner);
14271
- return { ethSigner, starkSigner };
14272
- };
14273
- // eslint-disable-next-line no-async-promise-executor
14274
- this.signers = new Promise(async (resolve) => {
14275
- try {
14276
- resolve(await generateSigners());
14277
- }
14278
- catch (err) {
14279
- // Capture and store the initialization error
14280
- this.signerInitialisationError = err;
14281
- resolve(undefined);
14282
- }
14350
+ transfer(request) {
14351
+ return __awaiter(this, void 0, void 0, function* () {
14352
+ const { user, starkSigner } = yield __classPrivateFieldGet(this, _PassportImxProvider_instances, "m", _PassportImxProvider_getRegisteredImxUserAndSigners).call(this);
14353
+ return transfer({
14354
+ request,
14355
+ user,
14356
+ starkSigner,
14357
+ transfersApi: this.immutableXClient.transfersApi,
14358
+ guardianClient: this.guardianClient,
14359
+ });
14283
14360
  });
14284
14361
  }
14285
- async #getAuthenticatedUser() {
14286
- const user = await this.authManager.getUser();
14287
- if (!user || !this.signers) {
14288
- throw new PassportError('User has been logged out', PassportErrorType.NOT_LOGGED_IN_ERROR);
14289
- }
14290
- return user;
14291
- }
14292
- async #getSigners() {
14293
- const signers = await this.signers;
14294
- // Throw the stored error if the signers failed to initialise
14295
- if (typeof signers === 'undefined') {
14296
- if (typeof this.signerInitialisationError !== 'undefined') {
14297
- throw this.signerInitialisationError;
14298
- }
14299
- throw new Error('Signers failed to initialise');
14300
- }
14301
- return signers;
14302
- }
14303
- async #getRegisteredImxUserAndSigners() {
14304
- const [user, signers] = await Promise.all([
14305
- this.#getAuthenticatedUser(),
14306
- this.#getSigners(),
14307
- ]);
14308
- if (!isUserImx(user)) {
14309
- throw new PassportError('User has not been registered with StarkEx', PassportErrorType.USER_NOT_REGISTERED_ERROR);
14310
- }
14311
- return {
14312
- user,
14313
- starkSigner: signers.starkSigner,
14314
- ethSigner: signers.ethSigner,
14315
- };
14316
- }
14317
- async transfer(request) {
14318
- const { user, starkSigner } = await this.#getRegisteredImxUserAndSigners();
14319
- return transfer({
14320
- request,
14321
- user,
14322
- starkSigner,
14323
- transfersApi: this.immutableXClient.transfersApi,
14324
- guardianClient: this.guardianClient,
14362
+ registerOffchain() {
14363
+ return __awaiter(this, void 0, void 0, function* () {
14364
+ const [user, signers] = yield Promise.all([
14365
+ __classPrivateFieldGet(this, _PassportImxProvider_instances, "m", _PassportImxProvider_getAuthenticatedUser).call(this),
14366
+ __classPrivateFieldGet(this, _PassportImxProvider_instances, "m", _PassportImxProvider_getSigners).call(this),
14367
+ ]);
14368
+ return yield registerOffchain(signers.ethSigner, signers.starkSigner, user, this.authManager, this.imxApiClients);
14325
14369
  });
14326
14370
  }
14327
- async registerOffchain() {
14328
- const [user, signers] = await Promise.all([
14329
- this.#getAuthenticatedUser(),
14330
- this.#getSigners(),
14331
- ]);
14332
- return await registerOffchain(signers.ethSigner, signers.starkSigner, user, this.authManager, this.imxApiClients);
14333
- }
14334
- async isRegisteredOffchain() {
14335
- const user = await this.#getAuthenticatedUser();
14336
- return !!user.imx;
14371
+ isRegisteredOffchain() {
14372
+ return __awaiter(this, void 0, void 0, function* () {
14373
+ const user = yield __classPrivateFieldGet(this, _PassportImxProvider_instances, "m", _PassportImxProvider_getAuthenticatedUser).call(this);
14374
+ return !!user.imx;
14375
+ });
14337
14376
  }
14338
14377
  // eslint-disable-next-line class-methods-use-this, @typescript-eslint/no-unused-vars
14339
14378
  isRegisteredOnchain() {
14340
14379
  throw new PassportError('Operation not supported', PassportErrorType.OPERATION_NOT_SUPPORTED_ERROR);
14341
14380
  }
14342
- async createOrder(request) {
14343
- const { user, starkSigner } = await this.#getRegisteredImxUserAndSigners();
14344
- return createOrder({
14345
- request,
14346
- user,
14347
- starkSigner,
14348
- ordersApi: this.immutableXClient.ordersApi,
14349
- guardianClient: this.guardianClient,
14381
+ createOrder(request) {
14382
+ return __awaiter(this, void 0, void 0, function* () {
14383
+ const { user, starkSigner } = yield __classPrivateFieldGet(this, _PassportImxProvider_instances, "m", _PassportImxProvider_getRegisteredImxUserAndSigners).call(this);
14384
+ return createOrder({
14385
+ request,
14386
+ user,
14387
+ starkSigner,
14388
+ ordersApi: this.immutableXClient.ordersApi,
14389
+ guardianClient: this.guardianClient,
14390
+ });
14350
14391
  });
14351
14392
  }
14352
- async cancelOrder(request) {
14353
- const { user, starkSigner } = await this.#getRegisteredImxUserAndSigners();
14354
- return cancelOrder({
14355
- request,
14356
- user,
14357
- starkSigner,
14358
- ordersApi: this.immutableXClient.ordersApi,
14359
- guardianClient: this.guardianClient,
14393
+ cancelOrder(request) {
14394
+ return __awaiter(this, void 0, void 0, function* () {
14395
+ const { user, starkSigner } = yield __classPrivateFieldGet(this, _PassportImxProvider_instances, "m", _PassportImxProvider_getRegisteredImxUserAndSigners).call(this);
14396
+ return cancelOrder({
14397
+ request,
14398
+ user,
14399
+ starkSigner,
14400
+ ordersApi: this.immutableXClient.ordersApi,
14401
+ guardianClient: this.guardianClient,
14402
+ });
14360
14403
  });
14361
14404
  }
14362
- async createTrade(request) {
14363
- const { user, starkSigner } = await this.#getRegisteredImxUserAndSigners();
14364
- return createTrade({
14365
- request,
14366
- user,
14367
- starkSigner,
14368
- tradesApi: this.immutableXClient.tradesApi,
14369
- guardianClient: this.guardianClient,
14405
+ createTrade(request) {
14406
+ return __awaiter(this, void 0, void 0, function* () {
14407
+ const { user, starkSigner } = yield __classPrivateFieldGet(this, _PassportImxProvider_instances, "m", _PassportImxProvider_getRegisteredImxUserAndSigners).call(this);
14408
+ return createTrade({
14409
+ request,
14410
+ user,
14411
+ starkSigner,
14412
+ tradesApi: this.immutableXClient.tradesApi,
14413
+ guardianClient: this.guardianClient,
14414
+ });
14370
14415
  });
14371
14416
  }
14372
- async batchNftTransfer(request) {
14373
- const { user, starkSigner } = await this.#getRegisteredImxUserAndSigners();
14374
- return batchNftTransfer({
14375
- request,
14376
- user,
14377
- starkSigner,
14378
- transfersApi: this.immutableXClient.transfersApi,
14379
- guardianClient: this.guardianClient,
14417
+ batchNftTransfer(request) {
14418
+ return __awaiter(this, void 0, void 0, function* () {
14419
+ const { user, starkSigner } = yield __classPrivateFieldGet(this, _PassportImxProvider_instances, "m", _PassportImxProvider_getRegisteredImxUserAndSigners).call(this);
14420
+ return batchNftTransfer({
14421
+ request,
14422
+ user,
14423
+ starkSigner,
14424
+ transfersApi: this.immutableXClient.transfersApi,
14425
+ guardianClient: this.guardianClient,
14426
+ });
14380
14427
  });
14381
14428
  }
14382
- async exchangeTransfer(request) {
14383
- const { user, starkSigner } = await this.#getRegisteredImxUserAndSigners();
14384
- return exchangeTransfer({
14385
- request,
14386
- user,
14387
- starkSigner,
14388
- exchangesApi: this.immutableXClient.exchangeApi,
14429
+ exchangeTransfer(request) {
14430
+ return __awaiter(this, void 0, void 0, function* () {
14431
+ const { user, starkSigner } = yield __classPrivateFieldGet(this, _PassportImxProvider_instances, "m", _PassportImxProvider_getRegisteredImxUserAndSigners).call(this);
14432
+ return exchangeTransfer({
14433
+ request,
14434
+ user,
14435
+ starkSigner,
14436
+ exchangesApi: this.immutableXClient.exchangeApi,
14437
+ });
14389
14438
  });
14390
14439
  }
14391
14440
  // eslint-disable-next-line class-methods-use-this, @typescript-eslint/no-unused-vars
@@ -14404,22 +14453,75 @@ class PassportImxProvider {
14404
14453
  token) {
14405
14454
  throw new PassportError('Operation not supported', PassportErrorType.OPERATION_NOT_SUPPORTED_ERROR);
14406
14455
  }
14407
- async getAddress() {
14408
- const user = await this.#getAuthenticatedUser();
14456
+ getAddress() {
14457
+ return __awaiter(this, void 0, void 0, function* () {
14458
+ const user = yield __classPrivateFieldGet(this, _PassportImxProvider_instances, "m", _PassportImxProvider_getAuthenticatedUser).call(this);
14459
+ if (!isUserImx(user)) {
14460
+ throw new PassportError('User has not been registered with StarkEx', PassportErrorType.USER_NOT_REGISTERED_ERROR);
14461
+ }
14462
+ return Promise.resolve(user.imx.ethAddress);
14463
+ });
14464
+ }
14465
+ }
14466
+ _PassportImxProvider_instances = new WeakSet(), _PassportImxProvider_initialiseSigners = function _PassportImxProvider_initialiseSigners() {
14467
+ const generateSigners = () => __awaiter(this, void 0, void 0, function* () {
14468
+ const user = yield this.authManager.getUser();
14469
+ // The user will be present because the factory validates it
14470
+ const magicRpcProvider = yield this.magicAdapter.login(user.idToken);
14471
+ const web3Provider = new Web3Provider(magicRpcProvider);
14472
+ const ethSigner = web3Provider.getSigner();
14473
+ const starkSigner = yield getStarkSigner(ethSigner);
14474
+ return { ethSigner, starkSigner };
14475
+ });
14476
+ // eslint-disable-next-line no-async-promise-executor
14477
+ this.signers = new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
14478
+ try {
14479
+ resolve(yield generateSigners());
14480
+ }
14481
+ catch (err) {
14482
+ // Capture and store the initialization error
14483
+ this.signerInitialisationError = err;
14484
+ resolve(undefined);
14485
+ }
14486
+ }));
14487
+ }, _PassportImxProvider_getAuthenticatedUser = function _PassportImxProvider_getAuthenticatedUser() {
14488
+ return __awaiter(this, void 0, void 0, function* () {
14489
+ const user = yield this.authManager.getUser();
14490
+ if (!user || !this.signers) {
14491
+ throw new PassportError('User has been logged out', PassportErrorType.NOT_LOGGED_IN_ERROR);
14492
+ }
14493
+ return user;
14494
+ });
14495
+ }, _PassportImxProvider_getSigners = function _PassportImxProvider_getSigners() {
14496
+ return __awaiter(this, void 0, void 0, function* () {
14497
+ const signers = yield this.signers;
14498
+ // Throw the stored error if the signers failed to initialise
14499
+ if (typeof signers === 'undefined') {
14500
+ if (typeof this.signerInitialisationError !== 'undefined') {
14501
+ throw this.signerInitialisationError;
14502
+ }
14503
+ throw new Error('Signers failed to initialise');
14504
+ }
14505
+ return signers;
14506
+ });
14507
+ }, _PassportImxProvider_getRegisteredImxUserAndSigners = function _PassportImxProvider_getRegisteredImxUserAndSigners() {
14508
+ return __awaiter(this, void 0, void 0, function* () {
14509
+ const [user, signers] = yield Promise.all([
14510
+ __classPrivateFieldGet(this, _PassportImxProvider_instances, "m", _PassportImxProvider_getAuthenticatedUser).call(this),
14511
+ __classPrivateFieldGet(this, _PassportImxProvider_instances, "m", _PassportImxProvider_getSigners).call(this),
14512
+ ]);
14409
14513
  if (!isUserImx(user)) {
14410
14514
  throw new PassportError('User has not been registered with StarkEx', PassportErrorType.USER_NOT_REGISTERED_ERROR);
14411
14515
  }
14412
- return Promise.resolve(user.imx.ethAddress);
14413
- }
14414
- }
14516
+ return {
14517
+ user,
14518
+ starkSigner: signers.starkSigner,
14519
+ ethSigner: signers.ethSigner,
14520
+ };
14521
+ });
14522
+ };
14415
14523
 
14416
14524
  class PassportImxProviderFactory {
14417
- authManager;
14418
- immutableXClient;
14419
- magicAdapter;
14420
- passportEventEmitter;
14421
- imxApiClients;
14422
- guardianClient;
14423
14525
  constructor({ authManager, immutableXClient, magicAdapter, passportEventEmitter, imxApiClients, guardianClient, }) {
14424
14526
  this.authManager = authManager;
14425
14527
  this.immutableXClient = immutableXClient;
@@ -14428,28 +14530,34 @@ class PassportImxProviderFactory {
14428
14530
  this.imxApiClients = imxApiClients;
14429
14531
  this.guardianClient = guardianClient;
14430
14532
  }
14431
- async getProvider() {
14432
- const user = await this.authManager.getUserOrLogin();
14433
- return this.createProviderInstance(user);
14533
+ getProvider() {
14534
+ return __awaiter(this, void 0, void 0, function* () {
14535
+ const user = yield this.authManager.getUserOrLogin();
14536
+ return this.createProviderInstance(user);
14537
+ });
14434
14538
  }
14435
- async getProviderSilent() {
14436
- const user = await this.authManager.getUser();
14437
- if (!user) {
14438
- return null;
14439
- }
14440
- return this.createProviderInstance(user);
14539
+ getProviderSilent() {
14540
+ return __awaiter(this, void 0, void 0, function* () {
14541
+ const user = yield this.authManager.getUser();
14542
+ if (!user) {
14543
+ return null;
14544
+ }
14545
+ return this.createProviderInstance(user);
14546
+ });
14441
14547
  }
14442
- async createProviderInstance(user) {
14443
- if (!user.idToken) {
14444
- throw new PassportError('Failed to initialise', PassportErrorType.WALLET_CONNECTION_ERROR);
14445
- }
14446
- return new PassportImxProvider({
14447
- authManager: this.authManager,
14448
- immutableXClient: this.immutableXClient,
14449
- passportEventEmitter: this.passportEventEmitter,
14450
- magicAdapter: this.magicAdapter,
14451
- imxApiClients: this.imxApiClients,
14452
- guardianClient: this.guardianClient,
14548
+ createProviderInstance(user) {
14549
+ return __awaiter(this, void 0, void 0, function* () {
14550
+ if (!user.idToken) {
14551
+ throw new PassportError('Failed to initialise', PassportErrorType.WALLET_CONNECTION_ERROR);
14552
+ }
14553
+ return new PassportImxProvider({
14554
+ authManager: this.authManager,
14555
+ immutableXClient: this.immutableXClient,
14556
+ passportEventEmitter: this.passportEventEmitter,
14557
+ magicAdapter: this.magicAdapter,
14558
+ imxApiClients: this.imxApiClients,
14559
+ guardianClient: this.guardianClient,
14560
+ });
14453
14561
  });
14454
14562
  }
14455
14563
  }
@@ -14467,18 +14575,8 @@ const validateConfiguration = (configuration, requiredKeys, prefix) => {
14467
14575
  }
14468
14576
  };
14469
14577
  class PassportConfiguration {
14470
- authenticationDomain;
14471
- passportDomain;
14472
- imxPublicApiDomain;
14473
- magicPublishableApiKey;
14474
- magicProviderId;
14475
- oidcConfiguration;
14476
- baseConfig;
14477
- zkEvmRpcUrl;
14478
- relayerUrl;
14479
- multiRollupConfig;
14480
- crossSdkBridgeEnabled;
14481
- constructor({ baseConfig, overrides, crossSdkBridgeEnabled, ...oidcConfiguration }) {
14578
+ constructor(_a) {
14579
+ var { baseConfig, overrides, crossSdkBridgeEnabled } = _a, oidcConfiguration = __rest(_a, ["baseConfig", "overrides", "crossSdkBridgeEnabled"]);
14482
14580
  validateConfiguration(oidcConfiguration, [
14483
14581
  'clientId',
14484
14582
  'redirectUri',
@@ -14583,8 +14681,6 @@ const CONFIRMATION_WINDOW_CLOSED_POLLING_DURATION = 1000;
14583
14681
  const CONFIRMATION_IFRAME_ID = 'passport-confirm';
14584
14682
  const CONFIRMATION_IFRAME_STYLE = 'display: none; position: absolute;width:0px;height:0px;border:0;';
14585
14683
  class ConfirmationScreen {
14586
- config;
14587
- confirmationWindow;
14588
14684
  constructor(config) {
14589
14685
  this.config = config;
14590
14686
  }
@@ -14680,12 +14776,13 @@ class ConfirmationScreen {
14680
14776
  this.confirmationWindow = openPopupCenter({
14681
14777
  url: this.getHref('loading'),
14682
14778
  title: CONFIRMATION_WINDOW_TITLE,
14683
- width: popupOptions?.width || CONFIRMATION_WINDOW_WIDTH,
14684
- height: popupOptions?.height || CONFIRMATION_WINDOW_HEIGHT,
14779
+ width: (popupOptions === null || popupOptions === void 0 ? void 0 : popupOptions.width) || CONFIRMATION_WINDOW_WIDTH,
14780
+ height: (popupOptions === null || popupOptions === void 0 ? void 0 : popupOptions.height) || CONFIRMATION_WINDOW_HEIGHT,
14685
14781
  });
14686
14782
  }
14687
14783
  closeWindow() {
14688
- this.confirmationWindow?.close();
14784
+ var _a;
14785
+ (_a = this.confirmationWindow) === null || _a === void 0 ? void 0 : _a.close();
14689
14786
  }
14690
14787
  logout() {
14691
14788
  return new Promise((resolve, rejects) => {
@@ -14713,7 +14810,8 @@ class ConfirmationScreen {
14713
14810
  this.confirmationWindow.location.href = href;
14714
14811
  // https://stackoverflow.com/questions/9388380/capture-the-close-event-of-popup-window-in-javascript/48240128#48240128
14715
14812
  const timer = setInterval(() => {
14716
- if (this.confirmationWindow?.closed) {
14813
+ var _a;
14814
+ if ((_a = this.confirmationWindow) === null || _a === void 0 ? void 0 : _a.closed) {
14717
14815
  clearInterval(timer);
14718
14816
  window.removeEventListener('message', messageHandler);
14719
14817
  resolve({ confirmed: false });
@@ -14736,7 +14834,9 @@ var ProviderEvent;
14736
14834
  })(ProviderEvent || (ProviderEvent = {}));
14737
14835
 
14738
14836
  class TypedEventEmitter {
14739
- emitter = new EventEmitter();
14837
+ constructor() {
14838
+ this.emitter = new EventEmitter();
14839
+ }
14740
14840
  emit(eventName, ...eventArg) {
14741
14841
  this.emitter.emit(eventName, ...eventArg);
14742
14842
  }
@@ -14762,23 +14862,26 @@ const META_TRANSACTIONS_TYPE = `tuple(
14762
14862
  bytes data
14763
14863
  )[]`;
14764
14864
  function getNormalisedTransactions(txs) {
14765
- return txs.map((t) => ({
14766
- delegateCall: t.delegateCall === true,
14767
- revertOnError: t.revertOnError === true,
14768
- gasLimit: t.gasLimit ?? constants.Zero,
14769
- target: t.to ?? constants.AddressZero,
14770
- value: t.value ?? constants.Zero,
14771
- data: t.data ?? [],
14772
- }));
14865
+ return txs.map((t) => {
14866
+ var _a, _b, _c, _d;
14867
+ return ({
14868
+ delegateCall: t.delegateCall === true,
14869
+ revertOnError: t.revertOnError === true,
14870
+ gasLimit: (_a = t.gasLimit) !== null && _a !== void 0 ? _a : constants.Zero,
14871
+ target: (_b = t.to) !== null && _b !== void 0 ? _b : constants.AddressZero,
14872
+ value: (_c = t.value) !== null && _c !== void 0 ? _c : constants.Zero,
14873
+ data: (_d = t.data) !== null && _d !== void 0 ? _d : [],
14874
+ });
14875
+ });
14773
14876
  }
14774
14877
  function digestOfTransactionsAndNonce(nonce, normalisedTransactions) {
14775
14878
  const packMetaTransactionsNonceData = utils$2.defaultAbiCoder.encode(['uint256', META_TRANSACTIONS_TYPE], [nonce, normalisedTransactions]);
14776
14879
  return utils$2.keccak256(packMetaTransactionsNonceData);
14777
14880
  }
14778
- const getNonce = async (jsonRpcProvider, smartContractWalletAddress) => {
14881
+ const getNonce = (jsonRpcProvider, smartContractWalletAddress) => __awaiter(void 0, void 0, void 0, function* () {
14779
14882
  try {
14780
14883
  const contract = new Contract(smartContractWalletAddress, walletContracts.mainModule.abi, jsonRpcProvider);
14781
- const result = await contract.nonce();
14884
+ const result = yield contract.nonce();
14782
14885
  if (result instanceof BigNumber) {
14783
14886
  return result;
14784
14887
  }
@@ -14794,9 +14897,9 @@ const getNonce = async (jsonRpcProvider, smartContractWalletAddress) => {
14794
14897
  throw error;
14795
14898
  }
14796
14899
  throw new Error('Unexpected result from contract.nonce() call.');
14797
- };
14900
+ });
14798
14901
  const encodeMessageSubDigest = (chainId, walletAddress, digest) => (utils$2.solidityPack(['string', 'uint256', 'address', 'bytes32'], [ETH_SIGN_PREFIX, chainId, walletAddress, digest]));
14799
- const getSignedMetaTransactions = async (metaTransactions, nonce, chainId, walletAddress, signer) => {
14902
+ const getSignedMetaTransactions = (metaTransactions, nonce, chainId, walletAddress, signer) => __awaiter(void 0, void 0, void 0, function* () {
14800
14903
  const normalisedMetaTransactions = getNormalisedTransactions(metaTransactions);
14801
14904
  // Get the hash
14802
14905
  const digest = digestOfTransactionsAndNonce(nonce, normalisedMetaTransactions);
@@ -14804,7 +14907,7 @@ const getSignedMetaTransactions = async (metaTransactions, nonce, chainId, walle
14804
14907
  const hash = utils$2.keccak256(completePayload);
14805
14908
  // Sign the digest
14806
14909
  const hashArray = utils$2.arrayify(hash);
14807
- const ethsigNoType = await signer.signMessage(hashArray);
14910
+ const ethsigNoType = yield signer.signMessage(hashArray);
14808
14911
  const signedDigest = `${ethsigNoType}${ETH_SIGN_FLAG}`;
14809
14912
  // Add metadata
14810
14913
  const encodedSignature = v1.signature.encodeSignature({
@@ -14826,14 +14929,14 @@ const getSignedMetaTransactions = async (metaTransactions, nonce, chainId, walle
14826
14929
  nonce,
14827
14930
  encodedSignature,
14828
14931
  ]);
14829
- };
14932
+ });
14830
14933
  const decodeRelayerTypedDataSignature = (relayerSignature) => {
14831
14934
  const signatureWithThreshold = `0x0000${relayerSignature}`;
14832
14935
  return v1.signature.decodeSignature(signatureWithThreshold);
14833
14936
  };
14834
- const getSignedTypedData = async (typedData, relayerSignature, chainId, walletAddress, signer) => {
14937
+ const getSignedTypedData = (typedData, relayerSignature, chainId, walletAddress, signer) => __awaiter(void 0, void 0, void 0, function* () {
14835
14938
  // Ethers auto-generates the EIP712Domain type in the TypedDataEncoder, and so it needs to be removed
14836
- const types = { ...typedData.types };
14939
+ const types = Object.assign({}, typedData.types);
14837
14940
  // @ts-ignore
14838
14941
  delete types.EIP712Domain;
14839
14942
  // Hash the EIP712 payload and generate the complete payload
@@ -14844,7 +14947,7 @@ const getSignedTypedData = async (typedData, relayerSignature, chainId, walletAd
14844
14947
  // Sign the sub digest
14845
14948
  // https://github.com/immutable/wallet-contracts/blob/7824b5f24b2e0eb2dc465ecb5cd71f3984556b73/src/contracts/modules/commons/ModuleAuth.sol#L155
14846
14949
  const hashArray = utils$2.arrayify(hash);
14847
- const ethsigNoType = await signer.signMessage(hashArray);
14950
+ const ethsigNoType = yield signer.signMessage(hashArray);
14848
14951
  const signedDigest = `${ethsigNoType}${ETH_SIGN_FLAG}`;
14849
14952
  // Combine the relayer and user signatures; sort by address to match the imageHash order
14850
14953
  const { signers: relayerSigners } = decodeRelayerTypedDataSignature(relayerSignature);
@@ -14855,7 +14958,7 @@ const getSignedTypedData = async (typedData, relayerSignature, chainId, walletAd
14855
14958
  unrecovered: true,
14856
14959
  weight: SIGNATURE_WEIGHT,
14857
14960
  signature: signedDigest,
14858
- address: await signer.getAddress(),
14961
+ address: yield signer.getAddress(),
14859
14962
  },
14860
14963
  ];
14861
14964
  const sortedSigners = combinedSigners.sort((a, b) => {
@@ -14874,85 +14977,88 @@ const getSignedTypedData = async (typedData, relayerSignature, chainId, walletAd
14874
14977
  threshold: EIP712_SIGNATURE_THRESHOLD,
14875
14978
  signers: sortedSigners,
14876
14979
  });
14877
- };
14980
+ });
14878
14981
  const getEip155ChainId = (chainId) => `eip155:${chainId}`;
14879
14982
 
14880
14983
  class RelayerClient {
14881
- config;
14882
- jsonRpcProvider;
14883
- authManager;
14884
14984
  constructor({ config, jsonRpcProvider, authManager }) {
14885
14985
  this.config = config;
14886
14986
  this.jsonRpcProvider = jsonRpcProvider;
14887
14987
  this.authManager = authManager;
14888
14988
  }
14889
- async postToRelayer(request) {
14890
- const body = {
14891
- id: 1,
14892
- jsonrpc: '2.0',
14893
- ...request,
14894
- };
14895
- const user = await this.authManager.getUserZkEvm();
14896
- const response = await fetch(`${this.config.relayerUrl}/v1/transactions`, {
14897
- method: 'POST',
14898
- headers: {
14899
- Authorization: `Bearer ${user.accessToken}`,
14900
- 'Content-Type': 'application/json',
14901
- },
14902
- body: JSON.stringify(body),
14989
+ postToRelayer(request) {
14990
+ return __awaiter(this, void 0, void 0, function* () {
14991
+ const body = Object.assign({ id: 1, jsonrpc: '2.0' }, request);
14992
+ const user = yield this.authManager.getUserZkEvm();
14993
+ const response = yield fetch(`${this.config.relayerUrl}/v1/transactions`, {
14994
+ method: 'POST',
14995
+ headers: {
14996
+ Authorization: `Bearer ${user.accessToken}`,
14997
+ 'Content-Type': 'application/json',
14998
+ },
14999
+ body: JSON.stringify(body),
15000
+ });
15001
+ const jsonResponse = yield response.json();
15002
+ if (jsonResponse.error) {
15003
+ throw jsonResponse.error;
15004
+ }
15005
+ return jsonResponse;
14903
15006
  });
14904
- const jsonResponse = await response.json();
14905
- if (jsonResponse.error) {
14906
- throw jsonResponse.error;
14907
- }
14908
- return jsonResponse;
14909
- }
14910
- async ethSendTransaction(to, data) {
14911
- const { chainId } = await this.jsonRpcProvider.ready;
14912
- const payload = {
14913
- method: 'eth_sendTransaction',
14914
- params: [{
14915
- to,
14916
- data,
14917
- chainId: getEip155ChainId(chainId),
14918
- }],
14919
- };
14920
- const { result } = await this.postToRelayer(payload);
14921
- return result;
14922
15007
  }
14923
- async imGetTransactionByHash(hash) {
14924
- const payload = {
14925
- method: 'im_getTransactionByHash',
14926
- params: [hash],
14927
- };
14928
- const { result } = await this.postToRelayer(payload);
14929
- return result;
14930
- }
14931
- async imGetFeeOptions(userAddress, data) {
14932
- const { chainId } = await this.jsonRpcProvider.ready;
14933
- const payload = {
14934
- method: 'im_getFeeOptions',
14935
- params: [{
14936
- userAddress,
14937
- data,
14938
- chainId: getEip155ChainId(chainId),
14939
- }],
14940
- };
14941
- const { result } = await this.postToRelayer(payload);
14942
- return result;
14943
- }
14944
- async imSignTypedData(address, eip712Payload) {
14945
- const { chainId } = await this.jsonRpcProvider.ready;
14946
- const payload = {
14947
- method: 'im_signTypedData',
14948
- params: [{
14949
- address,
14950
- eip712Payload,
14951
- chainId: getEip155ChainId(chainId),
14952
- }],
14953
- };
14954
- const { result } = await this.postToRelayer(payload);
14955
- return result;
15008
+ ethSendTransaction(to, data) {
15009
+ return __awaiter(this, void 0, void 0, function* () {
15010
+ const { chainId } = yield this.jsonRpcProvider.ready;
15011
+ const payload = {
15012
+ method: 'eth_sendTransaction',
15013
+ params: [{
15014
+ to,
15015
+ data,
15016
+ chainId: getEip155ChainId(chainId),
15017
+ }],
15018
+ };
15019
+ const { result } = yield this.postToRelayer(payload);
15020
+ return result;
15021
+ });
15022
+ }
15023
+ imGetTransactionByHash(hash) {
15024
+ return __awaiter(this, void 0, void 0, function* () {
15025
+ const payload = {
15026
+ method: 'im_getTransactionByHash',
15027
+ params: [hash],
15028
+ };
15029
+ const { result } = yield this.postToRelayer(payload);
15030
+ return result;
15031
+ });
15032
+ }
15033
+ imGetFeeOptions(userAddress, data) {
15034
+ return __awaiter(this, void 0, void 0, function* () {
15035
+ const { chainId } = yield this.jsonRpcProvider.ready;
15036
+ const payload = {
15037
+ method: 'im_getFeeOptions',
15038
+ params: [{
15039
+ userAddress,
15040
+ data,
15041
+ chainId: getEip155ChainId(chainId),
15042
+ }],
15043
+ };
15044
+ const { result } = yield this.postToRelayer(payload);
15045
+ return result;
15046
+ });
15047
+ }
15048
+ imSignTypedData(address, eip712Payload) {
15049
+ return __awaiter(this, void 0, void 0, function* () {
15050
+ const { chainId } = yield this.jsonRpcProvider.ready;
15051
+ const payload = {
15052
+ method: 'im_signTypedData',
15053
+ params: [{
15054
+ address,
15055
+ eip712Payload,
15056
+ chainId: getEip155ChainId(chainId),
15057
+ }],
15058
+ };
15059
+ const { result } = yield this.postToRelayer(payload);
15060
+ return result;
15061
+ });
14956
15062
  }
14957
15063
  }
14958
15064
 
@@ -14979,8 +15085,6 @@ var RpcErrorCode;
14979
15085
  RpcErrorCode[RpcErrorCode["TRANSACTION_REJECTED"] = -32003] = "TRANSACTION_REJECTED";
14980
15086
  })(RpcErrorCode || (RpcErrorCode = {}));
14981
15087
  class JsonRpcError extends Error {
14982
- message;
14983
- code;
14984
15088
  constructor(code, message) {
14985
15089
  super(message);
14986
15090
  this.message = message;
@@ -14989,34 +15093,37 @@ class JsonRpcError extends Error {
14989
15093
  }
14990
15094
 
14991
15095
  const MESSAGE_TO_SIGN = 'Only sign this message from Immutable Passport';
14992
- async function registerZkEvmUser({ authManager, ethSigner, multiRollupApiClients, accessToken, jsonRpcProvider, }) {
14993
- const [ethereumAddress, ethereumSignature, network, chainListResponse] = await Promise.all([
14994
- ethSigner.getAddress(),
14995
- signRaw(MESSAGE_TO_SIGN, ethSigner),
14996
- jsonRpcProvider.ready,
14997
- multiRollupApiClients.chainsApi.listChains(),
14998
- ]);
14999
- const eipChainId = getEip155ChainId(network.chainId);
15000
- const chainName = chainListResponse.data?.result?.find((chain) => chain.id === eipChainId)?.name;
15001
- if (!chainName) {
15002
- throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, `Chain name does not exist on for chain id ${network.chainId}`);
15003
- }
15004
- try {
15005
- const registrationResponse = await multiRollupApiClients.passportApi.createCounterfactualAddressV2({
15006
- chainName,
15007
- createCounterfactualAddressRequest: {
15008
- ethereum_address: ethereumAddress,
15009
- ethereum_signature: ethereumSignature,
15010
- },
15011
- }, {
15012
- headers: { Authorization: `Bearer ${accessToken}` },
15013
- });
15014
- authManager.forceUserRefreshInBackground();
15015
- return registrationResponse.data.counterfactual_address;
15016
- }
15017
- catch (error) {
15018
- throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, `Failed to create counterfactual address: ${error}`);
15019
- }
15096
+ function registerZkEvmUser({ authManager, ethSigner, multiRollupApiClients, accessToken, jsonRpcProvider, }) {
15097
+ var _a, _b, _c;
15098
+ return __awaiter(this, void 0, void 0, function* () {
15099
+ const [ethereumAddress, ethereumSignature, network, chainListResponse] = yield Promise.all([
15100
+ ethSigner.getAddress(),
15101
+ signRaw(MESSAGE_TO_SIGN, ethSigner),
15102
+ jsonRpcProvider.ready,
15103
+ multiRollupApiClients.chainsApi.listChains(),
15104
+ ]);
15105
+ const eipChainId = getEip155ChainId(network.chainId);
15106
+ const chainName = (_c = (_b = (_a = chainListResponse.data) === null || _a === void 0 ? void 0 : _a.result) === null || _b === void 0 ? void 0 : _b.find((chain) => chain.id === eipChainId)) === null || _c === void 0 ? void 0 : _c.name;
15107
+ if (!chainName) {
15108
+ throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, `Chain name does not exist on for chain id ${network.chainId}`);
15109
+ }
15110
+ try {
15111
+ const registrationResponse = yield multiRollupApiClients.passportApi.createCounterfactualAddressV2({
15112
+ chainName,
15113
+ createCounterfactualAddressRequest: {
15114
+ ethereum_address: ethereumAddress,
15115
+ ethereum_signature: ethereumSignature,
15116
+ },
15117
+ }, {
15118
+ headers: { Authorization: `Bearer ${accessToken}` },
15119
+ });
15120
+ authManager.forceUserRefreshInBackground();
15121
+ return registrationResponse.data.counterfactual_address;
15122
+ }
15123
+ catch (error) {
15124
+ throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, `Failed to create counterfactual address: ${error}`);
15125
+ }
15126
+ });
15020
15127
  }
15021
15128
 
15022
15129
  const transactionRejectedCrossSdkBridgeError = 'Transaction requires confirmation but this functionality is not'
@@ -15024,14 +15131,17 @@ const transactionRejectedCrossSdkBridgeError = 'Transaction requires confirmatio
15024
15131
  const convertBigNumberishToString = (value) => BigNumber.from(value).toString();
15025
15132
  const transformGuardianTransactions = (txs) => {
15026
15133
  try {
15027
- return txs.map((t) => ({
15028
- delegateCall: t.delegateCall === true,
15029
- revertOnError: t.revertOnError === true,
15030
- gasLimit: t.gasLimit ? convertBigNumberishToString(t.gasLimit) : '0',
15031
- target: t.to ?? ethers.constants.AddressZero,
15032
- value: t.value ? convertBigNumberishToString(t.value) : '0',
15033
- data: t.data ? t.data.toString() : '0x',
15034
- }));
15134
+ return txs.map((t) => {
15135
+ var _a;
15136
+ return ({
15137
+ delegateCall: t.delegateCall === true,
15138
+ revertOnError: t.revertOnError === true,
15139
+ gasLimit: t.gasLimit ? convertBigNumberishToString(t.gasLimit) : '0',
15140
+ target: (_a = t.to) !== null && _a !== void 0 ? _a : ethers.constants.AddressZero,
15141
+ value: t.value ? convertBigNumberishToString(t.value) : '0',
15142
+ data: t.data ? t.data.toString() : '0x',
15143
+ });
15144
+ });
15035
15145
  }
15036
15146
  catch (error) {
15037
15147
  const errorMessage = error instanceof Error ? error.message : String(error);
@@ -15039,11 +15149,6 @@ const transformGuardianTransactions = (txs) => {
15039
15149
  }
15040
15150
  };
15041
15151
  class GuardianClient {
15042
- transactionAPI;
15043
- messageAPI;
15044
- confirmationScreen;
15045
- crossSdkBridgeEnabled;
15046
- authManager;
15047
15152
  constructor({ confirmationScreen, config, authManager }) {
15048
15153
  const guardianConfiguration = new Configuration({ basePath: config.imxPublicApiDomain });
15049
15154
  this.confirmationScreen = confirmationScreen;
@@ -15060,145 +15165,157 @@ class GuardianClient {
15060
15165
  return (task) => this.withConfirmationScreenTask(popupWindowSize)(task)();
15061
15166
  }
15062
15167
  withConfirmationScreenTask(popupWindowSize) {
15063
- return (task) => async () => {
15168
+ return (task) => () => __awaiter(this, void 0, void 0, function* () {
15064
15169
  this.confirmationScreen.loading(popupWindowSize);
15065
15170
  try {
15066
- return await task();
15171
+ return yield task();
15067
15172
  }
15068
15173
  catch (err) {
15069
15174
  this.confirmationScreen.closeWindow();
15070
15175
  throw err;
15071
15176
  }
15072
- };
15177
+ });
15073
15178
  }
15074
15179
  withDefaultConfirmationScreenTask(task) {
15075
15180
  return this.withConfirmationScreenTask()(task);
15076
15181
  }
15077
- async evaluateImxTransaction({ payloadHash }) {
15078
- const finallyFn = () => {
15079
- this.confirmationScreen.closeWindow();
15080
- };
15081
- const user = await this.authManager.getUserImx();
15082
- const headers = { Authorization: `Bearer ${user.accessToken}` };
15083
- const transactionRes = await retryWithDelay(async () => this.transactionAPI.getTransactionByID({
15084
- transactionID: payloadHash,
15085
- chainType: 'starkex',
15086
- }, { headers }), { finallyFn });
15087
- if (!transactionRes.data.id) {
15088
- throw new Error("Transaction doesn't exists");
15089
- }
15090
- const evaluateImxRes = await this.transactionAPI.evaluateTransaction({
15091
- id: payloadHash,
15092
- transactionEvaluationRequest: {
15093
- chainType: 'starkex',
15094
- },
15095
- }, { headers });
15096
- const { confirmationRequired } = evaluateImxRes.data;
15097
- if (confirmationRequired) {
15098
- if (this.crossSdkBridgeEnabled) {
15099
- throw new Error(transactionRejectedCrossSdkBridgeError);
15100
- }
15101
- const confirmationResult = await this.confirmationScreen.requestConfirmation(payloadHash, user.imx.ethAddress, TransactionApprovalRequestChainTypeEnum.Starkex);
15102
- if (!confirmationResult.confirmed) {
15103
- throw new Error('Transaction rejected by user');
15104
- }
15105
- }
15106
- else {
15107
- this.confirmationScreen.closeWindow();
15108
- }
15109
- }
15110
- async evaluateEVMTransaction({ chainId, nonce, metaTransactions, }) {
15111
- const user = await this.authManager.getUserZkEvm();
15112
- const headers = { Authorization: `Bearer ${user.accessToken}` };
15113
- const guardianTransactions = transformGuardianTransactions(metaTransactions);
15114
- try {
15115
- const transactionEvaluationResponseAxiosResponse = await this.transactionAPI.evaluateTransaction({
15116
- id: 'evm',
15182
+ evaluateImxTransaction({ payloadHash }) {
15183
+ return __awaiter(this, void 0, void 0, function* () {
15184
+ const finallyFn = () => {
15185
+ this.confirmationScreen.closeWindow();
15186
+ };
15187
+ const user = yield this.authManager.getUserImx();
15188
+ const headers = { Authorization: `Bearer ${user.accessToken}` };
15189
+ const transactionRes = yield retryWithDelay(() => __awaiter(this, void 0, void 0, function* () {
15190
+ return this.transactionAPI.getTransactionByID({
15191
+ transactionID: payloadHash,
15192
+ chainType: 'starkex',
15193
+ }, { headers });
15194
+ }), { finallyFn });
15195
+ if (!transactionRes.data.id) {
15196
+ throw new Error("Transaction doesn't exists");
15197
+ }
15198
+ const evaluateImxRes = yield this.transactionAPI.evaluateTransaction({
15199
+ id: payloadHash,
15117
15200
  transactionEvaluationRequest: {
15118
- chainType: 'evm',
15119
- chainId,
15120
- transactionData: {
15121
- nonce,
15122
- userAddress: user.zkEvm.ethAddress,
15123
- metaTransactions: guardianTransactions,
15124
- },
15201
+ chainType: 'starkex',
15125
15202
  },
15126
15203
  }, { headers });
15127
- return transactionEvaluationResponseAxiosResponse.data;
15128
- }
15129
- catch (error) {
15130
- const errorMessage = error instanceof Error ? error.message : String(error);
15131
- throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, `Transaction failed to validate with error: ${errorMessage}`);
15132
- }
15204
+ const { confirmationRequired } = evaluateImxRes.data;
15205
+ if (confirmationRequired) {
15206
+ if (this.crossSdkBridgeEnabled) {
15207
+ throw new Error(transactionRejectedCrossSdkBridgeError);
15208
+ }
15209
+ const confirmationResult = yield this.confirmationScreen.requestConfirmation(payloadHash, user.imx.ethAddress, TransactionApprovalRequestChainTypeEnum.Starkex);
15210
+ if (!confirmationResult.confirmed) {
15211
+ throw new Error('Transaction rejected by user');
15212
+ }
15213
+ }
15214
+ else {
15215
+ this.confirmationScreen.closeWindow();
15216
+ }
15217
+ });
15133
15218
  }
15134
- async validateEVMTransaction({ chainId, nonce, metaTransactions, }) {
15135
- const transactionEvaluationResponse = await this.evaluateEVMTransaction({
15136
- chainId,
15137
- nonce,
15138
- metaTransactions,
15219
+ evaluateEVMTransaction({ chainId, nonce, metaTransactions, }) {
15220
+ return __awaiter(this, void 0, void 0, function* () {
15221
+ const user = yield this.authManager.getUserZkEvm();
15222
+ const headers = { Authorization: `Bearer ${user.accessToken}` };
15223
+ const guardianTransactions = transformGuardianTransactions(metaTransactions);
15224
+ try {
15225
+ const transactionEvaluationResponseAxiosResponse = yield this.transactionAPI.evaluateTransaction({
15226
+ id: 'evm',
15227
+ transactionEvaluationRequest: {
15228
+ chainType: 'evm',
15229
+ chainId,
15230
+ transactionData: {
15231
+ nonce,
15232
+ userAddress: user.zkEvm.ethAddress,
15233
+ metaTransactions: guardianTransactions,
15234
+ },
15235
+ },
15236
+ }, { headers });
15237
+ return transactionEvaluationResponseAxiosResponse.data;
15238
+ }
15239
+ catch (error) {
15240
+ const errorMessage = error instanceof Error ? error.message : String(error);
15241
+ throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, `Transaction failed to validate with error: ${errorMessage}`);
15242
+ }
15139
15243
  });
15140
- const { confirmationRequired, transactionId } = transactionEvaluationResponse;
15141
- if (confirmationRequired && this.crossSdkBridgeEnabled) {
15142
- throw new JsonRpcError(RpcErrorCode.TRANSACTION_REJECTED, transactionRejectedCrossSdkBridgeError);
15143
- }
15144
- if (confirmationRequired && !!transactionId) {
15145
- const user = await this.authManager.getUserZkEvm();
15146
- const confirmationResult = await this.confirmationScreen.requestConfirmation(transactionId, user.zkEvm.ethAddress, TransactionApprovalRequestChainTypeEnum.Evm, chainId);
15147
- if (!confirmationResult.confirmed) {
15148
- throw new JsonRpcError(RpcErrorCode.TRANSACTION_REJECTED, 'Transaction rejected by user');
15244
+ }
15245
+ validateEVMTransaction({ chainId, nonce, metaTransactions, }) {
15246
+ return __awaiter(this, void 0, void 0, function* () {
15247
+ const transactionEvaluationResponse = yield this.evaluateEVMTransaction({
15248
+ chainId,
15249
+ nonce,
15250
+ metaTransactions,
15251
+ });
15252
+ const { confirmationRequired, transactionId } = transactionEvaluationResponse;
15253
+ if (confirmationRequired && this.crossSdkBridgeEnabled) {
15254
+ throw new JsonRpcError(RpcErrorCode.TRANSACTION_REJECTED, transactionRejectedCrossSdkBridgeError);
15255
+ }
15256
+ if (confirmationRequired && !!transactionId) {
15257
+ const user = yield this.authManager.getUserZkEvm();
15258
+ const confirmationResult = yield this.confirmationScreen.requestConfirmation(transactionId, user.zkEvm.ethAddress, TransactionApprovalRequestChainTypeEnum.Evm, chainId);
15259
+ if (!confirmationResult.confirmed) {
15260
+ throw new JsonRpcError(RpcErrorCode.TRANSACTION_REJECTED, 'Transaction rejected by user');
15261
+ }
15149
15262
  }
15150
- }
15151
- else {
15152
- this.confirmationScreen.closeWindow();
15153
- }
15263
+ else {
15264
+ this.confirmationScreen.closeWindow();
15265
+ }
15266
+ });
15154
15267
  }
15155
- async evaluateMessage({ chainID, payload }) {
15156
- try {
15157
- const user = await this.authManager.getUserZkEvm();
15158
- if (user === null) {
15159
- throw new PassportError('evaluateMessage requires a valid ID token or refresh token. Please log in first', PassportErrorType.NOT_LOGGED_IN_ERROR);
15268
+ evaluateMessage({ chainID, payload }) {
15269
+ return __awaiter(this, void 0, void 0, function* () {
15270
+ try {
15271
+ const user = yield this.authManager.getUserZkEvm();
15272
+ if (user === null) {
15273
+ throw new PassportError('evaluateMessage requires a valid ID token or refresh token. Please log in first', PassportErrorType.NOT_LOGGED_IN_ERROR);
15274
+ }
15275
+ const messageEvalResponse = yield this.messageAPI.evaluateMessage({ messageEvaluationRequest: { chainID, payload } }, { headers: { Authorization: `Bearer ${user.accessToken}` } });
15276
+ return messageEvalResponse.data;
15160
15277
  }
15161
- const messageEvalResponse = await this.messageAPI.evaluateMessage({ messageEvaluationRequest: { chainID, payload } }, { headers: { Authorization: `Bearer ${user.accessToken}` } });
15162
- return messageEvalResponse.data;
15163
- }
15164
- catch (error) {
15165
- const errorMessage = error instanceof Error ? error.message : String(error);
15166
- throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, `Message failed to validate with error: ${errorMessage}`);
15167
- }
15278
+ catch (error) {
15279
+ const errorMessage = error instanceof Error ? error.message : String(error);
15280
+ throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, `Message failed to validate with error: ${errorMessage}`);
15281
+ }
15282
+ });
15168
15283
  }
15169
- async validateMessage({ chainID, payload }) {
15170
- const { messageId, confirmationRequired } = await this.evaluateMessage({ chainID, payload });
15171
- if (confirmationRequired && this.crossSdkBridgeEnabled) {
15172
- throw new JsonRpcError(RpcErrorCode.TRANSACTION_REJECTED, transactionRejectedCrossSdkBridgeError);
15173
- }
15174
- if (confirmationRequired && !!messageId) {
15175
- const user = await this.authManager.getUserZkEvm();
15176
- const confirmationResult = await this.confirmationScreen.requestMessageConfirmation(messageId, user.zkEvm.ethAddress);
15177
- if (!confirmationResult.confirmed) {
15178
- throw new JsonRpcError(RpcErrorCode.TRANSACTION_REJECTED, 'Signature rejected by user');
15284
+ validateMessage({ chainID, payload }) {
15285
+ return __awaiter(this, void 0, void 0, function* () {
15286
+ const { messageId, confirmationRequired } = yield this.evaluateMessage({ chainID, payload });
15287
+ if (confirmationRequired && this.crossSdkBridgeEnabled) {
15288
+ throw new JsonRpcError(RpcErrorCode.TRANSACTION_REJECTED, transactionRejectedCrossSdkBridgeError);
15289
+ }
15290
+ if (confirmationRequired && !!messageId) {
15291
+ const user = yield this.authManager.getUserZkEvm();
15292
+ const confirmationResult = yield this.confirmationScreen.requestMessageConfirmation(messageId, user.zkEvm.ethAddress);
15293
+ if (!confirmationResult.confirmed) {
15294
+ throw new JsonRpcError(RpcErrorCode.TRANSACTION_REJECTED, 'Signature rejected by user');
15295
+ }
15179
15296
  }
15180
- }
15181
- else {
15182
- this.confirmationScreen.closeWindow();
15183
- }
15297
+ else {
15298
+ this.confirmationScreen.closeWindow();
15299
+ }
15300
+ });
15184
15301
  }
15185
15302
  }
15186
15303
 
15187
15304
  const MAX_TRANSACTION_HASH_RETRIEVAL_RETRIES = 30;
15188
15305
  const TRANSACTION_HASH_RETRIEVAL_WAIT = 1000;
15189
- const getMetaTransactions = async (metaTransaction, nonce, chainId, walletAddress, signer, relayerClient) => {
15306
+ const getMetaTransactions = (metaTransaction, nonce, chainId, walletAddress, signer, relayerClient) => __awaiter(void 0, void 0, void 0, function* () {
15190
15307
  // NOTE: We sign the transaction before getting the fee options because
15191
15308
  // accurate estimation of a transaction gas cost is only possible if the smart
15192
15309
  // wallet contract can actually execute it (in a simulated environment) - and
15193
15310
  // it can only execute signed transactions.
15194
- const signedTransaction = await getSignedMetaTransactions([metaTransaction], nonce, chainId, walletAddress, signer);
15311
+ const signedTransaction = yield getSignedMetaTransactions([metaTransaction], nonce, chainId, walletAddress, signer);
15195
15312
  // TODO: ID-698 Add support for non-native gas payments (e.g ERC20, feeTransaction initialisation must change)
15196
15313
  // NOTE: "Fee Options" represent the multiple ways we could pay for the gas
15197
15314
  // used in this transaction. Each fee option has a "recipientAddress" we
15198
15315
  // should transfer the payment to, an amount and a currency. We choose one
15199
15316
  // option and build a transaction that sends the expected currency amount for
15200
15317
  // that option to the specified address.
15201
- const feeOptions = await relayerClient.imGetFeeOptions(walletAddress, signedTransaction);
15318
+ const feeOptions = yield relayerClient.imGetFeeOptions(walletAddress, signedTransaction);
15202
15319
  const imxFeeOption = feeOptions.find((feeOption) => feeOption.tokenSymbol === 'IMX');
15203
15320
  if (!imxFeeOption) {
15204
15321
  throw new Error('Failed to retrieve fees for IMX token');
@@ -15213,16 +15330,16 @@ const getMetaTransactions = async (metaTransaction, nonce, chainId, walletAddres
15213
15330
  return [metaTransaction];
15214
15331
  }
15215
15332
  return [metaTransaction, feeMetaTransaction];
15216
- };
15333
+ });
15217
15334
  const sendTransaction = ({ params, ethSigner, jsonRpcProvider, relayerClient, guardianClient, zkevmAddress, }) => guardianClient
15218
- .withConfirmationScreen({ width: 480, height: 720 })(async () => {
15335
+ .withConfirmationScreen({ width: 480, height: 720 })(() => __awaiter(void 0, void 0, void 0, function* () {
15219
15336
  const transactionRequest = params[0];
15220
15337
  if (!transactionRequest.to) {
15221
15338
  throw new JsonRpcError(RpcErrorCode.INVALID_PARAMS, 'eth_sendTransaction requires a "to" field');
15222
15339
  }
15223
- const { chainId } = await jsonRpcProvider.ready;
15340
+ const { chainId } = yield jsonRpcProvider.ready;
15224
15341
  const chainIdBigNumber = BigNumber.from(chainId);
15225
- const nonce = await getNonce(jsonRpcProvider, zkevmAddress);
15342
+ const nonce = yield getNonce(jsonRpcProvider, zkevmAddress);
15226
15343
  const metaTransaction = {
15227
15344
  to: transactionRequest.to,
15228
15345
  data: transactionRequest.data,
@@ -15230,9 +15347,9 @@ const sendTransaction = ({ params, ethSigner, jsonRpcProvider, relayerClient, gu
15230
15347
  value: transactionRequest.value,
15231
15348
  revertOnError: true,
15232
15349
  };
15233
- const metaTransactions = await getMetaTransactions(metaTransaction, nonce, chainIdBigNumber, zkevmAddress, ethSigner, relayerClient);
15350
+ const metaTransactions = yield getMetaTransactions(metaTransaction, nonce, chainIdBigNumber, zkevmAddress, ethSigner, relayerClient);
15234
15351
  // Parallelize the validation and signing of the transaction
15235
- const [, signedTransactions] = await Promise.all([
15352
+ const [, signedTransactions] = yield Promise.all([
15236
15353
  guardianClient.validateEVMTransaction({
15237
15354
  chainId: getEip155ChainId(chainId),
15238
15355
  nonce: convertBigNumberishToString(nonce),
@@ -15242,9 +15359,9 @@ const sendTransaction = ({ params, ethSigner, jsonRpcProvider, relayerClient, gu
15242
15359
  // whole payload is different and needs a new signature.
15243
15360
  getSignedMetaTransactions(metaTransactions, nonce, chainIdBigNumber, zkevmAddress, ethSigner),
15244
15361
  ]);
15245
- const relayerId = await relayerClient.ethSendTransaction(zkevmAddress, signedTransactions);
15246
- const retrieveRelayerTransaction = async () => {
15247
- const tx = await relayerClient.imGetTransactionByHash(relayerId);
15362
+ const relayerId = yield relayerClient.ethSendTransaction(zkevmAddress, signedTransactions);
15363
+ const retrieveRelayerTransaction = () => __awaiter(void 0, void 0, void 0, function* () {
15364
+ const tx = yield relayerClient.imGetTransactionByHash(relayerId);
15248
15365
  // NOTE: The transaction hash is only available from the Relayer once the
15249
15366
  // transaction is actually submitted onchain. Hence we need to poll the
15250
15367
  // Relayer get transaction endpoint until the status transitions to one that
@@ -15253,8 +15370,8 @@ const sendTransaction = ({ params, ethSigner, jsonRpcProvider, relayerClient, gu
15253
15370
  throw new Error();
15254
15371
  }
15255
15372
  return tx;
15256
- };
15257
- const relayerTransaction = await retryWithDelay(retrieveRelayerTransaction, {
15373
+ });
15374
+ const relayerTransaction = yield retryWithDelay(retrieveRelayerTransaction, {
15258
15375
  retries: MAX_TRANSACTION_HASH_RETRIEVAL_RETRIES,
15259
15376
  interval: TRANSACTION_HASH_RETRIEVAL_WAIT,
15260
15377
  finalErr: new JsonRpcError(RpcErrorCode.RPC_SERVER_ERROR, 'transaction hash not generated in time'),
@@ -15270,11 +15387,12 @@ const sendTransaction = ({ params, ethSigner, jsonRpcProvider, relayerClient, gu
15270
15387
  throw new JsonRpcError(RpcErrorCode.RPC_SERVER_ERROR, errorMessage);
15271
15388
  }
15272
15389
  return relayerTransaction.hash;
15273
- });
15390
+ }));
15274
15391
 
15275
15392
  const REQUIRED_TYPED_DATA_PROPERTIES = ['types', 'domain', 'primaryType', 'message'];
15276
15393
  const isValidTypedDataPayload = (typedData) => (REQUIRED_TYPED_DATA_PROPERTIES.every((key) => key in typedData));
15277
15394
  const transformTypedData = (typedData, chainId) => {
15395
+ var _a;
15278
15396
  let transformedTypedData;
15279
15397
  if (typeof typedData === 'string') {
15280
15398
  try {
@@ -15293,7 +15411,7 @@ const transformTypedData = (typedData, chainId) => {
15293
15411
  if (!isValidTypedDataPayload(transformedTypedData)) {
15294
15412
  throw new JsonRpcError(RpcErrorCode.INVALID_PARAMS, `Invalid typed data argument. The following properties are required: ${REQUIRED_TYPED_DATA_PROPERTIES.join(', ')}`);
15295
15413
  }
15296
- const providedChainId = transformedTypedData.domain?.chainId;
15414
+ const providedChainId = (_a = transformedTypedData.domain) === null || _a === void 0 ? void 0 : _a.chainId;
15297
15415
  if (providedChainId) {
15298
15416
  // domain.chainId (if defined) can be a number, string, or hex value, but the relayer & guardian only accept a number.
15299
15417
  if (typeof providedChainId === 'string') {
@@ -15310,168 +15428,234 @@ const transformTypedData = (typedData, chainId) => {
15310
15428
  }
15311
15429
  return transformedTypedData;
15312
15430
  };
15313
- const signTypedDataV4 = async ({ params, method, ethSigner, jsonRpcProvider, relayerClient, guardianClient, }) => guardianClient
15314
- .withConfirmationScreen({ width: 480, height: 720 })(async () => {
15315
- const fromAddress = params[0];
15316
- const typedDataParam = params[1];
15317
- if (!fromAddress || !typedDataParam) {
15318
- throw new JsonRpcError(RpcErrorCode.INVALID_PARAMS, `${method} requires an address and a typed data JSON`);
15319
- }
15320
- const { chainId } = await jsonRpcProvider.ready;
15321
- const typedData = transformTypedData(typedDataParam, chainId);
15322
- await guardianClient.validateMessage({ chainID: String(chainId), payload: typedData });
15323
- const relayerSignature = await relayerClient.imSignTypedData(fromAddress, typedData);
15324
- return getSignedTypedData(typedData, relayerSignature, BigNumber.from(chainId), fromAddress, ethSigner);
15431
+ const signTypedDataV4 = ({ params, method, ethSigner, jsonRpcProvider, relayerClient, guardianClient, }) => __awaiter(void 0, void 0, void 0, function* () {
15432
+ return guardianClient
15433
+ .withConfirmationScreen({ width: 480, height: 720 })(() => __awaiter(void 0, void 0, void 0, function* () {
15434
+ const fromAddress = params[0];
15435
+ const typedDataParam = params[1];
15436
+ if (!fromAddress || !typedDataParam) {
15437
+ throw new JsonRpcError(RpcErrorCode.INVALID_PARAMS, `${method} requires an address and a typed data JSON`);
15438
+ }
15439
+ const { chainId } = yield jsonRpcProvider.ready;
15440
+ const typedData = transformTypedData(typedDataParam, chainId);
15441
+ yield guardianClient.validateMessage({ chainID: String(chainId), payload: typedData });
15442
+ const relayerSignature = yield relayerClient.imSignTypedData(fromAddress, typedData);
15443
+ return getSignedTypedData(typedData, relayerSignature, BigNumber.from(chainId), fromAddress, ethSigner);
15444
+ }));
15325
15445
  });
15326
15446
 
15447
+ var _ZkEvmProvider_instances, _ZkEvmProvider_authManager, _ZkEvmProvider_config, _ZkEvmProvider_eventEmitter, _ZkEvmProvider_guardianClient, _ZkEvmProvider_jsonRpcProvider, _ZkEvmProvider_magicAdapter, _ZkEvmProvider_multiRollupApiClients, _ZkEvmProvider_relayerClient, _ZkEvmProvider_ethSigner, _ZkEvmProvider_signerInitialisationError, _ZkEvmProvider_zkEvmAddress, _ZkEvmProvider_handleLogout, _ZkEvmProvider_initialiseEthSigner, _ZkEvmProvider_getSigner, _ZkEvmProvider_performRequest, _ZkEvmProvider_performJsonRpcRequest;
15327
15448
  const isZkEvmUser = (user) => 'zkEvm' in user;
15328
15449
  class ZkEvmProvider {
15329
- #authManager;
15330
- #config;
15331
- #eventEmitter;
15332
- #guardianClient;
15333
- #jsonRpcProvider; // Used for read
15334
- #magicAdapter;
15335
- #multiRollupApiClients;
15336
- #relayerClient;
15337
- /**
15338
- * This property is set during `#initialiseEthSigner` and stores the signer in a promise.
15339
- * This property is not meant to be accessed directly, but through the
15340
- * `#getSigner` method.
15341
- * @see getSigner
15342
- */
15343
- #ethSigner;
15344
- #signerInitialisationError;
15345
- #zkEvmAddress;
15346
- isPassport = true;
15347
15450
  constructor({ authManager, magicAdapter, config, multiRollupApiClients, passportEventEmitter, guardianClient, }) {
15348
- this.#authManager = authManager;
15349
- this.#magicAdapter = magicAdapter;
15350
- this.#config = config;
15351
- this.#guardianClient = guardianClient;
15451
+ _ZkEvmProvider_instances.add(this);
15452
+ _ZkEvmProvider_authManager.set(this, void 0);
15453
+ _ZkEvmProvider_config.set(this, void 0);
15454
+ _ZkEvmProvider_eventEmitter.set(this, void 0);
15455
+ _ZkEvmProvider_guardianClient.set(this, void 0);
15456
+ _ZkEvmProvider_jsonRpcProvider.set(this, void 0); // Used for read
15457
+ _ZkEvmProvider_magicAdapter.set(this, void 0);
15458
+ _ZkEvmProvider_multiRollupApiClients.set(this, void 0);
15459
+ _ZkEvmProvider_relayerClient.set(this, void 0);
15460
+ /**
15461
+ * This property is set during `#initialiseEthSigner` and stores the signer in a promise.
15462
+ * This property is not meant to be accessed directly, but through the
15463
+ * `#getSigner` method.
15464
+ * @see getSigner
15465
+ */
15466
+ _ZkEvmProvider_ethSigner.set(this, void 0);
15467
+ _ZkEvmProvider_signerInitialisationError.set(this, void 0);
15468
+ _ZkEvmProvider_zkEvmAddress.set(this, void 0);
15469
+ this.isPassport = true;
15470
+ _ZkEvmProvider_handleLogout.set(this, () => {
15471
+ const shouldEmitAccountsChanged = !!__classPrivateFieldGet(this, _ZkEvmProvider_zkEvmAddress, "f");
15472
+ __classPrivateFieldSet(this, _ZkEvmProvider_ethSigner, undefined, "f");
15473
+ __classPrivateFieldSet(this, _ZkEvmProvider_zkEvmAddress, undefined, "f");
15474
+ if (shouldEmitAccountsChanged) {
15475
+ __classPrivateFieldGet(this, _ZkEvmProvider_eventEmitter, "f").emit(ProviderEvent.ACCOUNTS_CHANGED, []);
15476
+ }
15477
+ });
15478
+ __classPrivateFieldSet(this, _ZkEvmProvider_authManager, authManager, "f");
15479
+ __classPrivateFieldSet(this, _ZkEvmProvider_magicAdapter, magicAdapter, "f");
15480
+ __classPrivateFieldSet(this, _ZkEvmProvider_config, config, "f");
15481
+ __classPrivateFieldSet(this, _ZkEvmProvider_guardianClient, guardianClient, "f");
15352
15482
  if (config.crossSdkBridgeEnabled) {
15353
15483
  // JsonRpcProvider by default sets the referrer as "client".
15354
15484
  // On Unreal 4 this errors as the browser used is expecting a valid URL.
15355
- this.#jsonRpcProvider = new JsonRpcProvider({
15356
- url: this.#config.zkEvmRpcUrl,
15485
+ __classPrivateFieldSet(this, _ZkEvmProvider_jsonRpcProvider, new JsonRpcProvider({
15486
+ url: __classPrivateFieldGet(this, _ZkEvmProvider_config, "f").zkEvmRpcUrl,
15357
15487
  fetchOptions: { referrer: 'http://imtblgamesdk.local' },
15358
- });
15488
+ }), "f");
15359
15489
  }
15360
15490
  else {
15361
- this.#jsonRpcProvider = new JsonRpcProvider(this.#config.zkEvmRpcUrl);
15491
+ __classPrivateFieldSet(this, _ZkEvmProvider_jsonRpcProvider, new JsonRpcProvider(__classPrivateFieldGet(this, _ZkEvmProvider_config, "f").zkEvmRpcUrl), "f");
15362
15492
  }
15363
- this.#relayerClient = new RelayerClient({
15364
- config: this.#config,
15365
- jsonRpcProvider: this.#jsonRpcProvider,
15366
- authManager: this.#authManager,
15493
+ __classPrivateFieldSet(this, _ZkEvmProvider_relayerClient, new RelayerClient({
15494
+ config: __classPrivateFieldGet(this, _ZkEvmProvider_config, "f"),
15495
+ jsonRpcProvider: __classPrivateFieldGet(this, _ZkEvmProvider_jsonRpcProvider, "f"),
15496
+ authManager: __classPrivateFieldGet(this, _ZkEvmProvider_authManager, "f"),
15497
+ }), "f");
15498
+ __classPrivateFieldSet(this, _ZkEvmProvider_multiRollupApiClients, multiRollupApiClients, "f");
15499
+ __classPrivateFieldSet(this, _ZkEvmProvider_eventEmitter, new TypedEventEmitter(), "f");
15500
+ passportEventEmitter.on(PassportEvents.LOGGED_OUT, __classPrivateFieldGet(this, _ZkEvmProvider_handleLogout, "f"));
15501
+ }
15502
+ request(request) {
15503
+ return __awaiter(this, void 0, void 0, function* () {
15504
+ try {
15505
+ return __classPrivateFieldGet(this, _ZkEvmProvider_instances, "m", _ZkEvmProvider_performRequest).call(this, request);
15506
+ }
15507
+ catch (error) {
15508
+ if (error instanceof JsonRpcError) {
15509
+ throw error;
15510
+ }
15511
+ if (error instanceof Error) {
15512
+ throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, error.message);
15513
+ }
15514
+ throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, 'Internal error');
15515
+ }
15367
15516
  });
15368
- this.#multiRollupApiClients = multiRollupApiClients;
15369
- this.#eventEmitter = new TypedEventEmitter();
15370
- passportEventEmitter.on(PassportEvents.LOGGED_OUT, this.#handleLogout);
15371
- }
15372
- #handleLogout = () => {
15373
- const shouldEmitAccountsChanged = !!this.#zkEvmAddress;
15374
- this.#ethSigner = undefined;
15375
- this.#zkEvmAddress = undefined;
15376
- if (shouldEmitAccountsChanged) {
15377
- this.#eventEmitter.emit(ProviderEvent.ACCOUNTS_CHANGED, []);
15517
+ }
15518
+ sendAsync(request, callback) {
15519
+ if (!callback) {
15520
+ throw new Error('No callback provided');
15378
15521
  }
15379
- };
15380
- /**
15381
- * This method is called by `eth_requestAccounts` and asynchronously initialises the signer.
15382
- * The signer is stored in a promise so that it can be retrieved by the provider
15383
- * when needed.
15384
- *
15385
- * If an error is thrown during initialisation, it is stored in the `signerInitialisationError`,
15386
- * so that it doesn't result in an unhandled promise rejection.
15387
- *
15388
- * This error is thrown when the signer is requested through:
15389
- * @see #getSigner
15390
- *
15391
- */
15392
- #initialiseEthSigner(user) {
15393
- const generateSigner = async () => {
15394
- const magicRpcProvider = await this.#magicAdapter.login(user.idToken);
15395
- const web3Provider = new Web3Provider(magicRpcProvider);
15396
- return web3Provider.getSigner();
15397
- };
15398
- // eslint-disable-next-line no-async-promise-executor
15399
- this.#ethSigner = new Promise(async (resolve) => {
15400
- try {
15401
- resolve(await generateSigner());
15522
+ if (Array.isArray(request)) {
15523
+ Promise.all(request.map(__classPrivateFieldGet(this, _ZkEvmProvider_instances, "m", _ZkEvmProvider_performJsonRpcRequest))).then((result) => {
15524
+ callback(null, result);
15525
+ }).catch((error) => {
15526
+ callback(error, []);
15527
+ });
15528
+ }
15529
+ else {
15530
+ __classPrivateFieldGet(this, _ZkEvmProvider_instances, "m", _ZkEvmProvider_performJsonRpcRequest).call(this, request).then((result) => {
15531
+ callback(null, result);
15532
+ }).catch((error) => {
15533
+ callback(error, null);
15534
+ });
15535
+ }
15536
+ }
15537
+ send(request, callbackOrParams, callback) {
15538
+ return __awaiter(this, void 0, void 0, function* () {
15539
+ // Web3 >= 1.0.0-beta.38 calls `send` with method and parameters.
15540
+ if (typeof request === 'string') {
15541
+ if (typeof callbackOrParams === 'function') {
15542
+ return this.sendAsync({
15543
+ method: request,
15544
+ params: [],
15545
+ }, callbackOrParams);
15546
+ }
15547
+ if (callback) {
15548
+ return this.sendAsync({
15549
+ method: request,
15550
+ params: Array.isArray(callbackOrParams) ? callbackOrParams : [],
15551
+ }, callback);
15552
+ }
15553
+ return this.request({
15554
+ method: request,
15555
+ params: Array.isArray(callbackOrParams) ? callbackOrParams : [],
15556
+ });
15402
15557
  }
15403
- catch (err) {
15404
- // Capture and store the initialization error
15405
- this.#signerInitialisationError = err;
15406
- resolve(undefined);
15558
+ // Web3 <= 1.0.0-beta.37 uses `send` with a callback for async queries.
15559
+ if (typeof callbackOrParams === 'function') {
15560
+ return this.sendAsync(request, callbackOrParams);
15407
15561
  }
15562
+ if (!Array.isArray(request) && typeof request === 'object') {
15563
+ return __classPrivateFieldGet(this, _ZkEvmProvider_instances, "m", _ZkEvmProvider_performJsonRpcRequest).call(this, request);
15564
+ }
15565
+ throw new JsonRpcError(RpcErrorCode.INVALID_REQUEST, 'Invalid request');
15408
15566
  });
15409
15567
  }
15410
- async #getSigner() {
15411
- const ethSigner = await this.#ethSigner;
15568
+ on(event, listener) {
15569
+ __classPrivateFieldGet(this, _ZkEvmProvider_eventEmitter, "f").on(event, listener);
15570
+ }
15571
+ removeListener(event, listener) {
15572
+ __classPrivateFieldGet(this, _ZkEvmProvider_eventEmitter, "f").removeListener(event, listener);
15573
+ }
15574
+ }
15575
+ _ZkEvmProvider_authManager = new WeakMap(), _ZkEvmProvider_config = new WeakMap(), _ZkEvmProvider_eventEmitter = new WeakMap(), _ZkEvmProvider_guardianClient = new WeakMap(), _ZkEvmProvider_jsonRpcProvider = new WeakMap(), _ZkEvmProvider_magicAdapter = new WeakMap(), _ZkEvmProvider_multiRollupApiClients = new WeakMap(), _ZkEvmProvider_relayerClient = new WeakMap(), _ZkEvmProvider_ethSigner = new WeakMap(), _ZkEvmProvider_signerInitialisationError = new WeakMap(), _ZkEvmProvider_zkEvmAddress = new WeakMap(), _ZkEvmProvider_handleLogout = new WeakMap(), _ZkEvmProvider_instances = new WeakSet(), _ZkEvmProvider_initialiseEthSigner = function _ZkEvmProvider_initialiseEthSigner(user) {
15576
+ const generateSigner = () => __awaiter(this, void 0, void 0, function* () {
15577
+ const magicRpcProvider = yield __classPrivateFieldGet(this, _ZkEvmProvider_magicAdapter, "f").login(user.idToken);
15578
+ const web3Provider = new Web3Provider(magicRpcProvider);
15579
+ return web3Provider.getSigner();
15580
+ });
15581
+ // eslint-disable-next-line no-async-promise-executor
15582
+ __classPrivateFieldSet(this, _ZkEvmProvider_ethSigner, new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
15583
+ try {
15584
+ resolve(yield generateSigner());
15585
+ }
15586
+ catch (err) {
15587
+ // Capture and store the initialization error
15588
+ __classPrivateFieldSet(this, _ZkEvmProvider_signerInitialisationError, err, "f");
15589
+ resolve(undefined);
15590
+ }
15591
+ })), "f");
15592
+ }, _ZkEvmProvider_getSigner = function _ZkEvmProvider_getSigner() {
15593
+ return __awaiter(this, void 0, void 0, function* () {
15594
+ const ethSigner = yield __classPrivateFieldGet(this, _ZkEvmProvider_ethSigner, "f");
15412
15595
  // Throw the stored error if the signers failed to initialise
15413
15596
  if (typeof ethSigner === 'undefined') {
15414
- if (typeof this.#signerInitialisationError !== 'undefined') {
15415
- throw this.#signerInitialisationError;
15597
+ if (typeof __classPrivateFieldGet(this, _ZkEvmProvider_signerInitialisationError, "f") !== 'undefined') {
15598
+ throw __classPrivateFieldGet(this, _ZkEvmProvider_signerInitialisationError, "f");
15416
15599
  }
15417
15600
  throw new Error('Signer failed to initialise');
15418
15601
  }
15419
15602
  return ethSigner;
15420
- }
15421
- async #performRequest(request) {
15603
+ });
15604
+ }, _ZkEvmProvider_performRequest = function _ZkEvmProvider_performRequest(request) {
15605
+ return __awaiter(this, void 0, void 0, function* () {
15422
15606
  switch (request.method) {
15423
15607
  case 'eth_requestAccounts': {
15424
- if (this.#zkEvmAddress) {
15425
- return [this.#zkEvmAddress];
15608
+ if (__classPrivateFieldGet(this, _ZkEvmProvider_zkEvmAddress, "f")) {
15609
+ return [__classPrivateFieldGet(this, _ZkEvmProvider_zkEvmAddress, "f")];
15426
15610
  }
15427
- const user = await this.#authManager.getUserOrLogin();
15428
- this.#initialiseEthSigner(user);
15611
+ const user = yield __classPrivateFieldGet(this, _ZkEvmProvider_authManager, "f").getUserOrLogin();
15612
+ __classPrivateFieldGet(this, _ZkEvmProvider_instances, "m", _ZkEvmProvider_initialiseEthSigner).call(this, user);
15429
15613
  if (!isZkEvmUser(user)) {
15430
- const ethSigner = await this.#getSigner();
15431
- this.#zkEvmAddress = await registerZkEvmUser({
15614
+ const ethSigner = yield __classPrivateFieldGet(this, _ZkEvmProvider_instances, "m", _ZkEvmProvider_getSigner).call(this);
15615
+ __classPrivateFieldSet(this, _ZkEvmProvider_zkEvmAddress, yield registerZkEvmUser({
15432
15616
  ethSigner,
15433
- authManager: this.#authManager,
15434
- multiRollupApiClients: this.#multiRollupApiClients,
15617
+ authManager: __classPrivateFieldGet(this, _ZkEvmProvider_authManager, "f"),
15618
+ multiRollupApiClients: __classPrivateFieldGet(this, _ZkEvmProvider_multiRollupApiClients, "f"),
15435
15619
  accessToken: user.accessToken,
15436
- jsonRpcProvider: this.#jsonRpcProvider,
15437
- });
15620
+ jsonRpcProvider: __classPrivateFieldGet(this, _ZkEvmProvider_jsonRpcProvider, "f"),
15621
+ }), "f");
15438
15622
  }
15439
15623
  else {
15440
- this.#zkEvmAddress = user.zkEvm.ethAddress;
15624
+ __classPrivateFieldSet(this, _ZkEvmProvider_zkEvmAddress, user.zkEvm.ethAddress, "f");
15441
15625
  }
15442
- this.#eventEmitter.emit(ProviderEvent.ACCOUNTS_CHANGED, [this.#zkEvmAddress]);
15443
- return [this.#zkEvmAddress];
15626
+ __classPrivateFieldGet(this, _ZkEvmProvider_eventEmitter, "f").emit(ProviderEvent.ACCOUNTS_CHANGED, [__classPrivateFieldGet(this, _ZkEvmProvider_zkEvmAddress, "f")]);
15627
+ return [__classPrivateFieldGet(this, _ZkEvmProvider_zkEvmAddress, "f")];
15444
15628
  }
15445
15629
  case 'eth_sendTransaction': {
15446
- if (!this.#zkEvmAddress) {
15630
+ if (!__classPrivateFieldGet(this, _ZkEvmProvider_zkEvmAddress, "f")) {
15447
15631
  throw new JsonRpcError(ProviderErrorCode.UNAUTHORIZED, 'Unauthorised - call eth_requestAccounts first');
15448
15632
  }
15449
- const ethSigner = await this.#getSigner();
15633
+ const ethSigner = yield __classPrivateFieldGet(this, _ZkEvmProvider_instances, "m", _ZkEvmProvider_getSigner).call(this);
15450
15634
  return sendTransaction({
15451
15635
  params: request.params || [],
15452
15636
  ethSigner,
15453
- guardianClient: this.#guardianClient,
15454
- jsonRpcProvider: this.#jsonRpcProvider,
15455
- relayerClient: this.#relayerClient,
15456
- zkevmAddress: this.#zkEvmAddress,
15637
+ guardianClient: __classPrivateFieldGet(this, _ZkEvmProvider_guardianClient, "f"),
15638
+ jsonRpcProvider: __classPrivateFieldGet(this, _ZkEvmProvider_jsonRpcProvider, "f"),
15639
+ relayerClient: __classPrivateFieldGet(this, _ZkEvmProvider_relayerClient, "f"),
15640
+ zkevmAddress: __classPrivateFieldGet(this, _ZkEvmProvider_zkEvmAddress, "f"),
15457
15641
  });
15458
15642
  }
15459
15643
  case 'eth_accounts': {
15460
- return this.#zkEvmAddress ? [this.#zkEvmAddress] : [];
15644
+ return __classPrivateFieldGet(this, _ZkEvmProvider_zkEvmAddress, "f") ? [__classPrivateFieldGet(this, _ZkEvmProvider_zkEvmAddress, "f")] : [];
15461
15645
  }
15462
15646
  case 'eth_signTypedData':
15463
15647
  case 'eth_signTypedData_v4': {
15464
- if (!this.#zkEvmAddress) {
15648
+ if (!__classPrivateFieldGet(this, _ZkEvmProvider_zkEvmAddress, "f")) {
15465
15649
  throw new JsonRpcError(ProviderErrorCode.UNAUTHORIZED, 'Unauthorised - call eth_requestAccounts first');
15466
15650
  }
15467
- const ethSigner = await this.#getSigner();
15651
+ const ethSigner = yield __classPrivateFieldGet(this, _ZkEvmProvider_instances, "m", _ZkEvmProvider_getSigner).call(this);
15468
15652
  return signTypedDataV4({
15469
15653
  method: request.method,
15470
15654
  params: request.params || [],
15471
15655
  ethSigner,
15472
- jsonRpcProvider: this.#jsonRpcProvider,
15473
- relayerClient: this.#relayerClient,
15474
- guardianClient: this.#guardianClient,
15656
+ jsonRpcProvider: __classPrivateFieldGet(this, _ZkEvmProvider_jsonRpcProvider, "f"),
15657
+ relayerClient: __classPrivateFieldGet(this, _ZkEvmProvider_relayerClient, "f"),
15658
+ guardianClient: __classPrivateFieldGet(this, _ZkEvmProvider_guardianClient, "f"),
15475
15659
  });
15476
15660
  }
15477
15661
  // Pass through methods
@@ -15488,17 +15672,18 @@ class ZkEvmProvider {
15488
15672
  case 'eth_getTransactionByHash':
15489
15673
  case 'eth_getTransactionReceipt':
15490
15674
  case 'eth_getTransactionCount': {
15491
- return this.#jsonRpcProvider.send(request.method, request.params || []);
15675
+ return __classPrivateFieldGet(this, _ZkEvmProvider_jsonRpcProvider, "f").send(request.method, request.params || []);
15492
15676
  }
15493
15677
  default: {
15494
15678
  throw new JsonRpcError(ProviderErrorCode.UNSUPPORTED_METHOD, 'Method not supported');
15495
15679
  }
15496
15680
  }
15497
- }
15498
- async #performJsonRpcRequest(request) {
15681
+ });
15682
+ }, _ZkEvmProvider_performJsonRpcRequest = function _ZkEvmProvider_performJsonRpcRequest(request) {
15683
+ return __awaiter(this, void 0, void 0, function* () {
15499
15684
  const { id, jsonrpc } = request;
15500
15685
  try {
15501
- const result = await this.#performRequest(request);
15686
+ const result = yield __classPrivateFieldGet(this, _ZkEvmProvider_instances, "m", _ZkEvmProvider_performRequest).call(this, request);
15502
15687
  return {
15503
15688
  id,
15504
15689
  jsonrpc,
@@ -15522,76 +15707,8 @@ class ZkEvmProvider {
15522
15707
  error: jsonRpcError,
15523
15708
  };
15524
15709
  }
15525
- }
15526
- async request(request) {
15527
- try {
15528
- return this.#performRequest(request);
15529
- }
15530
- catch (error) {
15531
- if (error instanceof JsonRpcError) {
15532
- throw error;
15533
- }
15534
- if (error instanceof Error) {
15535
- throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, error.message);
15536
- }
15537
- throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, 'Internal error');
15538
- }
15539
- }
15540
- sendAsync(request, callback) {
15541
- if (!callback) {
15542
- throw new Error('No callback provided');
15543
- }
15544
- if (Array.isArray(request)) {
15545
- Promise.all(request.map(this.#performJsonRpcRequest)).then((result) => {
15546
- callback(null, result);
15547
- }).catch((error) => {
15548
- callback(error, []);
15549
- });
15550
- }
15551
- else {
15552
- this.#performJsonRpcRequest(request).then((result) => {
15553
- callback(null, result);
15554
- }).catch((error) => {
15555
- callback(error, null);
15556
- });
15557
- }
15558
- }
15559
- async send(request, callbackOrParams, callback) {
15560
- // Web3 >= 1.0.0-beta.38 calls `send` with method and parameters.
15561
- if (typeof request === 'string') {
15562
- if (typeof callbackOrParams === 'function') {
15563
- return this.sendAsync({
15564
- method: request,
15565
- params: [],
15566
- }, callbackOrParams);
15567
- }
15568
- if (callback) {
15569
- return this.sendAsync({
15570
- method: request,
15571
- params: Array.isArray(callbackOrParams) ? callbackOrParams : [],
15572
- }, callback);
15573
- }
15574
- return this.request({
15575
- method: request,
15576
- params: Array.isArray(callbackOrParams) ? callbackOrParams : [],
15577
- });
15578
- }
15579
- // Web3 <= 1.0.0-beta.37 uses `send` with a callback for async queries.
15580
- if (typeof callbackOrParams === 'function') {
15581
- return this.sendAsync(request, callbackOrParams);
15582
- }
15583
- if (!Array.isArray(request) && typeof request === 'object') {
15584
- return this.#performJsonRpcRequest(request);
15585
- }
15586
- throw new JsonRpcError(RpcErrorCode.INVALID_REQUEST, 'Invalid request');
15587
- }
15588
- on(event, listener) {
15589
- this.#eventEmitter.on(event, listener);
15590
- }
15591
- removeListener(event, listener) {
15592
- this.#eventEmitter.removeListener(event, listener);
15593
- }
15594
- }
15710
+ });
15711
+ };
15595
15712
 
15596
15713
  const buildImxClientConfig = (passportModuleConfiguration) => {
15597
15714
  if (passportModuleConfiguration.overrides) {
@@ -15603,7 +15720,8 @@ const buildImxClientConfig = (passportModuleConfiguration) => {
15603
15720
  return imxApiConfig.getProduction();
15604
15721
  };
15605
15722
  const buildImxApiClients = (passportModuleConfiguration) => {
15606
- if (passportModuleConfiguration.overrides?.imxApiClients)
15723
+ var _a;
15724
+ if ((_a = passportModuleConfiguration.overrides) === null || _a === void 0 ? void 0 : _a.imxApiClients)
15607
15725
  return passportModuleConfiguration.overrides.imxApiClients;
15608
15726
  const config = buildImxClientConfig(passportModuleConfiguration);
15609
15727
  return new ImxApiClients(config);
@@ -15645,15 +15763,6 @@ const buildPrivateVars = (passportModuleConfiguration) => {
15645
15763
  };
15646
15764
  };
15647
15765
  class Passport {
15648
- authManager;
15649
- config;
15650
- confirmationScreen;
15651
- immutableXClient;
15652
- magicAdapter;
15653
- multiRollupApiClients;
15654
- passportImxProviderFactory;
15655
- passportEventEmitter;
15656
- guardianClient;
15657
15766
  constructor(passportModuleConfiguration) {
15658
15767
  const privateVars = buildPrivateVars(passportModuleConfiguration);
15659
15768
  this.config = privateVars.config;
@@ -15672,11 +15781,15 @@ class Passport {
15672
15781
  * @deprecated The method `login` with an argument of `{ useCachedSession: true }` should be used in conjunction with
15673
15782
  * `connectImx` instead.
15674
15783
  */
15675
- async connectImxSilent() {
15676
- return this.passportImxProviderFactory.getProviderSilent();
15784
+ connectImxSilent() {
15785
+ return __awaiter(this, void 0, void 0, function* () {
15786
+ return this.passportImxProviderFactory.getProviderSilent();
15787
+ });
15677
15788
  }
15678
- async connectImx() {
15679
- return this.passportImxProviderFactory.getProvider();
15789
+ connectImx() {
15790
+ return __awaiter(this, void 0, void 0, function* () {
15791
+ return this.passportImxProviderFactory.getProvider();
15792
+ });
15680
15793
  }
15681
15794
  connectEvm() {
15682
15795
  return new ZkEvmProvider({
@@ -15697,57 +15810,69 @@ class Passport {
15697
15810
  * @param options.anonymousId - If provided, Passport internal metrics will be enriched with this value.
15698
15811
  * @returns {Promise<UserProfile | null>} the user profile if the user is logged in, otherwise null
15699
15812
  */
15700
- async login(options) {
15701
- const { useCachedSession = false } = options || {};
15702
- let user = null;
15703
- try {
15704
- user = await this.authManager.getUser();
15705
- }
15706
- catch (error) {
15707
- if (useCachedSession) {
15708
- throw error;
15813
+ login(options) {
15814
+ return __awaiter(this, void 0, void 0, function* () {
15815
+ const { useCachedSession = false } = options || {};
15816
+ let user = null;
15817
+ try {
15818
+ user = yield this.authManager.getUser();
15709
15819
  }
15710
- logger.warn('Failed to retrieve a cached user session', error);
15711
- }
15712
- if (!user && !useCachedSession) {
15713
- user = await this.authManager.login(options?.anonymousId);
15714
- }
15715
- if (user) {
15716
- identify({
15717
- passportId: user.profile.sub,
15718
- });
15719
- }
15720
- return user ? user.profile : null;
15820
+ catch (error) {
15821
+ if (useCachedSession) {
15822
+ throw error;
15823
+ }
15824
+ logger.warn('Failed to retrieve a cached user session', error);
15825
+ }
15826
+ if (!user && !useCachedSession) {
15827
+ user = yield this.authManager.login(options === null || options === void 0 ? void 0 : options.anonymousId);
15828
+ }
15829
+ if (user) {
15830
+ identify({
15831
+ passportId: user.profile.sub,
15832
+ });
15833
+ }
15834
+ return user ? user.profile : null;
15835
+ });
15721
15836
  }
15722
- async loginCallback() {
15723
- return this.authManager.loginCallback();
15837
+ loginCallback() {
15838
+ return __awaiter(this, void 0, void 0, function* () {
15839
+ return this.authManager.loginCallback();
15840
+ });
15724
15841
  }
15725
- async loginWithDeviceFlow(options) {
15726
- return this.authManager.loginWithDeviceFlow(options?.anonymousId);
15842
+ loginWithDeviceFlow(options) {
15843
+ return __awaiter(this, void 0, void 0, function* () {
15844
+ return this.authManager.loginWithDeviceFlow(options === null || options === void 0 ? void 0 : options.anonymousId);
15845
+ });
15727
15846
  }
15728
- async loginWithDeviceFlowCallback(deviceCode, interval, timeoutMs) {
15729
- const user = await this.authManager.loginWithDeviceFlowCallback(deviceCode, interval, timeoutMs);
15730
- return user.profile;
15847
+ loginWithDeviceFlowCallback(deviceCode, interval, timeoutMs) {
15848
+ return __awaiter(this, void 0, void 0, function* () {
15849
+ const user = yield this.authManager.loginWithDeviceFlowCallback(deviceCode, interval, timeoutMs);
15850
+ return user.profile;
15851
+ });
15731
15852
  }
15732
15853
  loginWithPKCEFlow() {
15733
15854
  return this.authManager.getPKCEAuthorizationUrl();
15734
15855
  }
15735
- async loginWithPKCEFlowCallback(authorizationCode, state) {
15736
- const user = await this.authManager.loginWithPKCEFlowCallback(authorizationCode, state);
15737
- return user.profile;
15856
+ loginWithPKCEFlowCallback(authorizationCode, state) {
15857
+ return __awaiter(this, void 0, void 0, function* () {
15858
+ const user = yield this.authManager.loginWithPKCEFlowCallback(authorizationCode, state);
15859
+ return user.profile;
15860
+ });
15738
15861
  }
15739
- async logout() {
15740
- try {
15741
- await this.confirmationScreen.logout();
15742
- }
15743
- catch (err) {
15744
- logger.warn('Failed to logout from confirmation screen', err);
15745
- }
15746
- await Promise.allSettled([
15747
- this.authManager.logout(),
15748
- this.magicAdapter.logout(),
15749
- ]);
15750
- this.passportEventEmitter.emit(PassportEvents.LOGGED_OUT);
15862
+ logout() {
15863
+ return __awaiter(this, void 0, void 0, function* () {
15864
+ try {
15865
+ yield this.confirmationScreen.logout();
15866
+ }
15867
+ catch (err) {
15868
+ logger.warn('Failed to logout from confirmation screen', err);
15869
+ }
15870
+ yield Promise.allSettled([
15871
+ this.authManager.logout(),
15872
+ this.magicAdapter.logout(),
15873
+ ]);
15874
+ this.passportEventEmitter.emit(PassportEvents.LOGGED_OUT);
15875
+ });
15751
15876
  }
15752
15877
  /**
15753
15878
  * Logs the user out of Passport when using device flow authentication.
@@ -15755,42 +15880,54 @@ class Passport {
15755
15880
  * @returns {Promise<string>} The device flow end session endpoint. Consumers are responsible for
15756
15881
  * opening this URL in the same browser that was used to log the user in.
15757
15882
  */
15758
- async logoutDeviceFlow() {
15759
- await this.authManager.removeUser();
15760
- await this.magicAdapter.logout();
15761
- this.passportEventEmitter.emit(PassportEvents.LOGGED_OUT);
15762
- return this.authManager.getDeviceFlowEndSessionEndpoint();
15883
+ logoutDeviceFlow() {
15884
+ return __awaiter(this, void 0, void 0, function* () {
15885
+ yield this.authManager.removeUser();
15886
+ yield this.magicAdapter.logout();
15887
+ this.passportEventEmitter.emit(PassportEvents.LOGGED_OUT);
15888
+ return this.authManager.getDeviceFlowEndSessionEndpoint();
15889
+ });
15763
15890
  }
15764
15891
  /**
15765
15892
  * This method should only be called from the logout redirect uri
15766
15893
  * when logout mode is 'silent'.
15767
15894
  */
15768
- async logoutSilentCallback(url) {
15769
- return this.authManager.logoutSilentCallback(url);
15895
+ logoutSilentCallback(url) {
15896
+ return __awaiter(this, void 0, void 0, function* () {
15897
+ return this.authManager.logoutSilentCallback(url);
15898
+ });
15770
15899
  }
15771
- async getUserInfo() {
15772
- const user = await this.authManager.getUser();
15773
- return user?.profile;
15900
+ getUserInfo() {
15901
+ return __awaiter(this, void 0, void 0, function* () {
15902
+ const user = yield this.authManager.getUser();
15903
+ return user === null || user === void 0 ? void 0 : user.profile;
15904
+ });
15774
15905
  }
15775
- async getIdToken() {
15776
- const user = await this.authManager.getUser();
15777
- return user?.idToken;
15906
+ getIdToken() {
15907
+ return __awaiter(this, void 0, void 0, function* () {
15908
+ const user = yield this.authManager.getUser();
15909
+ return user === null || user === void 0 ? void 0 : user.idToken;
15910
+ });
15778
15911
  }
15779
- async getAccessToken() {
15780
- const user = await this.authManager.getUser();
15781
- return user?.accessToken;
15912
+ getAccessToken() {
15913
+ return __awaiter(this, void 0, void 0, function* () {
15914
+ const user = yield this.authManager.getUser();
15915
+ return user === null || user === void 0 ? void 0 : user.accessToken;
15916
+ });
15782
15917
  }
15783
- async getLinkedAddresses() {
15784
- const user = await this.authManager.getUser();
15785
- if (!user?.profile.sub) {
15786
- return [];
15787
- }
15788
- const headers = { Authorization: `Bearer ${user.accessToken}` };
15789
- const linkedAddressesResult = await this.multiRollupApiClients.passportApi.getLinkedAddresses({
15790
- chainName: ChainName.ETHEREUM,
15791
- userId: user?.profile.sub,
15792
- }, { headers });
15793
- return linkedAddressesResult.data.linked_addresses;
15918
+ getLinkedAddresses() {
15919
+ return __awaiter(this, void 0, void 0, function* () {
15920
+ const user = yield this.authManager.getUser();
15921
+ if (!(user === null || user === void 0 ? void 0 : user.profile.sub)) {
15922
+ return [];
15923
+ }
15924
+ const headers = { Authorization: `Bearer ${user.accessToken}` };
15925
+ const linkedAddressesResult = yield this.multiRollupApiClients.passportApi.getLinkedAddresses({
15926
+ chainName: ChainName.ETHEREUM,
15927
+ userId: user === null || user === void 0 ? void 0 : user.profile.sub,
15928
+ }, { headers });
15929
+ return linkedAddressesResult.data.linked_addresses;
15930
+ });
15794
15931
  }
15795
15932
  }
15796
15933