@imtbl/sdk 0.4.0-alpha.1 → 0.4.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -9,8 +9,11 @@ var oidc = require('@magic-ext/oidc');
9
9
  var BN$2 = require('bn.js');
10
10
  var encUtils = require('enc-utils');
11
11
  var providers = require('@ethersproject/providers');
12
- var FormData$2 = require('form-data');
12
+ var events = require('events');
13
13
  var ethers = require('ethers');
14
+ var abi = require('@0xsequence/abi');
15
+ var config = require('@0xsequence/config');
16
+ var FormData$2 = require('form-data');
14
17
  var seaportJs = require('@opensea/seaport-js');
15
18
  var units = require('@ethersproject/units');
16
19
  var bignumber = require('@ethersproject/bignumber');
@@ -3265,6 +3268,94 @@ axios$1.default = axios$1;
3265
3268
  // this module should only have a default export
3266
3269
  var globalAxios$1 = axios$1;
3267
3270
 
3271
+ /* tslint:disable */
3272
+ /* eslint-disable */
3273
+ /**
3274
+ * Immutable X API
3275
+ * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
3276
+ *
3277
+ * The version of the OpenAPI document: 3.0
3278
+ * Contact: support@immutable.com
3279
+ *
3280
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
3281
+ * https://openapi-generator.tech
3282
+ * Do not edit the class manually.
3283
+ */
3284
+ let Configuration$1 = class Configuration {
3285
+ /**
3286
+ * parameter for apiKey security
3287
+ * @param name security name
3288
+ * @memberof Configuration
3289
+ */
3290
+ apiKey;
3291
+ /**
3292
+ * parameter for basic security
3293
+ *
3294
+ * @type {string}
3295
+ * @memberof Configuration
3296
+ */
3297
+ username;
3298
+ /**
3299
+ * parameter for basic security
3300
+ *
3301
+ * @type {string}
3302
+ * @memberof Configuration
3303
+ */
3304
+ password;
3305
+ /**
3306
+ * parameter for oauth2 security
3307
+ * @param name security name
3308
+ * @param scopes oauth2 scope
3309
+ * @memberof Configuration
3310
+ */
3311
+ accessToken;
3312
+ /**
3313
+ * override base path
3314
+ *
3315
+ * @type {string}
3316
+ * @memberof Configuration
3317
+ */
3318
+ basePath;
3319
+ /**
3320
+ * base options for axios calls
3321
+ *
3322
+ * @type {any}
3323
+ * @memberof Configuration
3324
+ */
3325
+ baseOptions;
3326
+ /**
3327
+ * The FormData constructor that will be used to create multipart form data
3328
+ * requests. You can inject this here so that execution environments that
3329
+ * do not support the FormData class can still run the generated client.
3330
+ *
3331
+ * @type {new () => FormData}
3332
+ */
3333
+ formDataCtor;
3334
+ constructor(param = {}) {
3335
+ this.apiKey = param.apiKey;
3336
+ this.username = param.username;
3337
+ this.password = param.password;
3338
+ this.accessToken = param.accessToken;
3339
+ this.basePath = param.basePath;
3340
+ this.baseOptions = param.baseOptions;
3341
+ this.formDataCtor = param.formDataCtor;
3342
+ }
3343
+ /**
3344
+ * Check if the given MIME is a JSON MIME.
3345
+ * JSON MIME examples:
3346
+ * application/json
3347
+ * application/json; charset=UTF8
3348
+ * APPLICATION/JSON
3349
+ * application/vnd.company+json
3350
+ * @param mime - MIME (Multipurpose Internet Mail Extensions)
3351
+ * @return True if the given MIME is JSON, false otherwise.
3352
+ */
3353
+ isJsonMime(mime) {
3354
+ const jsonMime = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i');
3355
+ return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json');
3356
+ }
3357
+ };
3358
+
3268
3359
  /* tslint:disable */
3269
3360
  /* eslint-disable */
3270
3361
  /**
@@ -4973,7 +5064,7 @@ class TokensApi extends BaseAPI$1 {
4973
5064
  * https://openapi-generator.tech
4974
5065
  * Do not edit the class manually.
4975
5066
  */
4976
- let Configuration$1 = class Configuration {
5067
+ let Configuration$2 = class Configuration {
4977
5068
  /**
4978
5069
  * parameter for apiKey security
4979
5070
  * @param name security name
@@ -5406,7 +5497,7 @@ var index = /*#__PURE__*/Object.freeze({
5406
5497
  CollectionsApiAxiosParamCreator: CollectionsApiAxiosParamCreator,
5407
5498
  CollectionsApiFactory: CollectionsApiFactory,
5408
5499
  CollectionsApiFp: CollectionsApiFp,
5409
- Configuration: Configuration$1,
5500
+ Configuration: Configuration$2,
5410
5501
  CreateOrderProtocolDataOrderTypeEnum: CreateOrderProtocolDataOrderTypeEnum,
5411
5502
  ERC20ItemItemTypeEnum: ERC20ItemItemTypeEnum,
5412
5503
  ERC721ItemItemTypeEnum: ERC721ItemItemTypeEnum,
@@ -5438,6 +5529,69 @@ var index = /*#__PURE__*/Object.freeze({
5438
5529
  TokensApiFp: TokensApiFp
5439
5530
  });
5440
5531
 
5532
+ class MultiRollupApiClients {
5533
+ config;
5534
+ activitiesApi;
5535
+ chainsApi;
5536
+ collectionApi;
5537
+ nftOwnersApi;
5538
+ nftsApi;
5539
+ ordersApi;
5540
+ passportApi;
5541
+ constructor(config) {
5542
+ this.config = config;
5543
+ this.activitiesApi = new ActivitiesApi(config.indexer);
5544
+ this.chainsApi = new ChainsApi(config.indexer);
5545
+ this.collectionApi = new CollectionsApi(config.indexer);
5546
+ this.nftOwnersApi = new NftOwnersApi(config.indexer);
5547
+ this.nftsApi = new NftsApi(config.indexer);
5548
+ this.ordersApi = new OrdersApi(config.orderBook);
5549
+ this.passportApi = new PassportApi(config.passport);
5550
+ }
5551
+ }
5552
+
5553
+ // eslint-disable-next-line @typescript-eslint/naming-convention
5554
+ const defaultHeaders$1 = { 'x-sdk-version': 'ts-immutable-sdk-0.4.0-alpha.3' };
5555
+ const createConfig = ({ basePath, headers, }) => {
5556
+ if (!basePath.trim()) {
5557
+ throw Error('basePath can not be empty');
5558
+ }
5559
+ const composedHeaders = { ...defaultHeaders$1, ...(headers || {}) };
5560
+ const apiConfigOptions = {
5561
+ basePath,
5562
+ baseOptions: { headers: composedHeaders },
5563
+ };
5564
+ return new Configuration$1(apiConfigOptions);
5565
+ };
5566
+ /**
5567
+ * Creates a Configuration for the specified environment
5568
+ * @returns an MultiRollupAPIConfiguration
5569
+ */
5570
+ const multiRollupConfig = {
5571
+ getProduction: () => ({
5572
+ indexer: createConfig({
5573
+ basePath: 'https://indexer-mr.imtbl.com',
5574
+ }),
5575
+ orderBook: createConfig({
5576
+ basePath: 'https://order-book-mr.imtbl.com',
5577
+ }),
5578
+ passport: createConfig({
5579
+ basePath: 'https://api.immutable.com',
5580
+ }),
5581
+ }),
5582
+ getSandbox: () => ({
5583
+ indexer: createConfig({
5584
+ basePath: 'https://indexer-mr.sandbox.imtbl.com',
5585
+ }),
5586
+ orderBook: createConfig({
5587
+ basePath: 'https://order-book-mr.sandbox.imtbl.com',
5588
+ }),
5589
+ passport: createConfig({
5590
+ basePath: 'https://api.sandbox.immutable.com',
5591
+ }),
5592
+ }),
5593
+ };
5594
+
5441
5595
  /**
5442
5596
  * Custom Error class that is returned from the API when a request fails
5443
5597
  */
@@ -5457,7 +5611,7 @@ class APIError extends Error {
5457
5611
 
5458
5612
  /* eslint-disable implicit-arrow-linebreak */
5459
5613
  const defaultHeaders = {
5460
- sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-0.4.0-alpha.1',
5614
+ sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-0.4.0-alpha.3',
5461
5615
  };
5462
5616
  /**
5463
5617
  * createAPIConfiguration to create a custom Configuration
@@ -5723,7 +5877,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
5723
5877
  chainID,
5724
5878
  coreContractAddress,
5725
5879
  registrationContractAddress,
5726
- sdkVersion: 'ts-immutable-sdk-0.4.0-alpha.1',
5880
+ sdkVersion: 'ts-immutable-sdk-0.4.0-alpha.3',
5727
5881
  });
5728
5882
  /**
5729
5883
  * Sets `sdkVersion` at the time of build
@@ -9447,6 +9601,8 @@ var globalAxios = axios;
9447
9601
  * https://openapi-generator.tech
9448
9602
  * Do not edit the class manually.
9449
9603
  */
9604
+ // Some imports not used depending on template conditions
9605
+ // @ts-ignore
9450
9606
  const BASE_PATH = "https://guardian.sandbox.imtbl.com".replace(/\/+$/, "");
9451
9607
  /**
9452
9608
  *
@@ -9474,10 +9630,10 @@ class BaseAPI {
9474
9630
  */
9475
9631
  class RequiredError extends Error {
9476
9632
  field;
9633
+ name = "RequiredError";
9477
9634
  constructor(field, msg) {
9478
9635
  super(msg);
9479
9636
  this.field = field;
9480
- this.name = "RequiredError";
9481
9637
  }
9482
9638
  }
9483
9639
 
@@ -9522,8 +9678,6 @@ const setBearerAuthToObject = async function (object, configuration) {
9522
9678
  }
9523
9679
  };
9524
9680
  function setFlattenedQueryParams(urlSearchParams, parameter, key = "") {
9525
- if (parameter == null)
9526
- return;
9527
9681
  if (typeof parameter === "object") {
9528
9682
  if (Array.isArray(parameter)) {
9529
9683
  parameter.forEach(item => setFlattenedQueryParams(urlSearchParams, item, key));
@@ -9679,7 +9833,7 @@ const TransactionsApiAxiosParamCreator = function (configuration) {
9679
9833
  * @summary Info for a specific transaction
9680
9834
  * @param {string} transactionID The id of the starkex transaction to retrieve
9681
9835
  * @param {'starkex' | 'evm'} chainType roll up type
9682
- * @param {number} [chainID] ID of evm chain
9836
+ * @param {string} [chainID] ID of evm chain
9683
9837
  * @param {*} [options] Override http request option.
9684
9838
  * @throws {RequiredError}
9685
9839
  */
@@ -9754,7 +9908,7 @@ const TransactionsApiFp = function (configuration) {
9754
9908
  * @summary Info for a specific transaction
9755
9909
  * @param {string} transactionID The id of the starkex transaction to retrieve
9756
9910
  * @param {'starkex' | 'evm'} chainType roll up type
9757
- * @param {number} [chainID] ID of evm chain
9911
+ * @param {string} [chainID] ID of evm chain
9758
9912
  * @param {*} [options] Override http request option.
9759
9913
  * @throws {RequiredError}
9760
9914
  */
@@ -10071,10 +10225,12 @@ class AuthManager {
10071
10225
  userManager;
10072
10226
  config;
10073
10227
  deviceCredentialsManager;
10228
+ logoutMode;
10074
10229
  constructor(config) {
10075
10230
  this.config = config;
10076
10231
  this.userManager = new oidcClientTs.UserManager(getAuthConfiguration(config));
10077
10232
  this.deviceCredentialsManager = new DeviceCredentialsManager();
10233
+ this.logoutMode = config.oidcConfiguration.logoutMode || 'redirect';
10078
10234
  }
10079
10235
  static mapOidcUserToDomainModel = (oidcUser) => {
10080
10236
  const passport = oidcUser.profile?.passport;
@@ -10228,7 +10384,15 @@ class AuthManager {
10228
10384
  return response.data;
10229
10385
  }
10230
10386
  async logout() {
10231
- return withPassportError(async () => this.userManager.signoutRedirect(), PassportErrorType.LOGOUT_ERROR);
10387
+ return withPassportError(async () => {
10388
+ if (this.logoutMode === 'silent') {
10389
+ return this.userManager.signoutSilent();
10390
+ }
10391
+ return this.userManager.signoutRedirect();
10392
+ }, PassportErrorType.LOGOUT_ERROR);
10393
+ }
10394
+ async logoutSilentCallback(url) {
10395
+ return this.userManager.signoutSilentCallback(url);
10232
10396
  }
10233
10397
  async logoutDeviceFlow() {
10234
10398
  return withPassportError(async () => {
@@ -10431,6 +10595,7 @@ async function createOrder$1({ starkSigner, user, request, ordersApi, guardianCl
10431
10595
  amount_sell: amountSell,
10432
10596
  token_sell: convertToSignableToken(request.sell),
10433
10597
  fees: request.fees,
10598
+ split_fees: true,
10434
10599
  expiration_timestamp: request.expiration_timestamp,
10435
10600
  };
10436
10601
  const getSignableOrderResponse = await ordersApi.getSignableOrder({
@@ -10885,6 +11050,10 @@ class PassportConfiguration {
10885
11050
  magicProviderId;
10886
11051
  oidcConfiguration;
10887
11052
  baseConfig;
11053
+ zkEvmChainId;
11054
+ zkEvmRpcUrl;
11055
+ relayerUrl;
11056
+ multiRollupConfig;
10888
11057
  constructor({ baseConfig, overrides, ...oidcConfiguration }) {
10889
11058
  validateConfiguration(oidcConfiguration, [
10890
11059
  'clientId',
@@ -10897,10 +11066,16 @@ class PassportConfiguration {
10897
11066
  validateConfiguration(overrides, [
10898
11067
  'network',
10899
11068
  'authenticationDomain',
11069
+ 'passportDomain',
10900
11070
  'magicPublishableApiKey',
10901
11071
  'magicProviderId',
10902
- 'passportDomain',
11072
+ 'zkEvmRpcUrl',
11073
+ 'zkEvmChainId',
11074
+ 'relayerUrl',
10903
11075
  'imxPublicApiDomain',
11076
+ 'indexerMrBasePath',
11077
+ 'orderBookMrBasePath',
11078
+ 'passportMrBasePath',
10904
11079
  ], 'overrides');
10905
11080
  this.network = overrides.network;
10906
11081
  this.authenticationDomain = overrides.authenticationDomain;
@@ -10908,6 +11083,20 @@ class PassportConfiguration {
10908
11083
  this.imxPublicApiDomain = overrides.imxPublicApiDomain;
10909
11084
  this.magicPublishableApiKey = overrides.magicPublishableApiKey;
10910
11085
  this.magicProviderId = overrides.magicProviderId;
11086
+ this.zkEvmRpcUrl = overrides.zkEvmRpcUrl;
11087
+ this.zkEvmChainId = overrides.zkEvmChainId;
11088
+ this.relayerUrl = overrides.relayerUrl;
11089
+ this.multiRollupConfig = {
11090
+ indexer: createConfig({
11091
+ basePath: overrides.indexerMrBasePath,
11092
+ }),
11093
+ orderBook: createConfig({
11094
+ basePath: overrides.orderBookMrBasePath,
11095
+ }),
11096
+ passport: createConfig({
11097
+ basePath: overrides.passportMrBasePath,
11098
+ }),
11099
+ };
10911
11100
  }
10912
11101
  else {
10913
11102
  switch (baseConfig.environment) {
@@ -10918,6 +11107,10 @@ class PassportConfiguration {
10918
11107
  this.magicProviderId = 'fSMzaRQ4O7p4fttl7pCyGVtJS_G70P8SNsLXtPPGHo0=';
10919
11108
  this.passportDomain = 'https://passport.immutable.com';
10920
11109
  this.imxPublicApiDomain = 'https://api.immutable.com';
11110
+ this.zkEvmRpcUrl = ''; // TODO: ID-785 Update once mainnet has been deployed
11111
+ this.zkEvmChainId = ''; // TODO: ID-785 Update once mainnet has been deployed
11112
+ this.relayerUrl = 'https://api.immutable.com/relayer-mr';
11113
+ this.multiRollupConfig = multiRollupConfig.getProduction();
10921
11114
  break;
10922
11115
  }
10923
11116
  case exports.Environment.SANDBOX:
@@ -10928,6 +11121,10 @@ class PassportConfiguration {
10928
11121
  this.magicProviderId = 'fSMzaRQ4O7p4fttl7pCyGVtJS_G70P8SNsLXtPPGHo0=';
10929
11122
  this.passportDomain = 'https://passport.sandbox.immutable.com';
10930
11123
  this.imxPublicApiDomain = 'https://api.sandbox.immutable.com';
11124
+ this.zkEvmRpcUrl = 'https://zkevm-rpc.sandbox.x.immutable.com';
11125
+ this.zkEvmChainId = 'eip155:13392';
11126
+ this.relayerUrl = 'https://api.sandbox.immutable.com/relayer-mr';
11127
+ this.multiRollupConfig = multiRollupConfig.getSandbox();
10931
11128
  break;
10932
11129
  }
10933
11130
  }
@@ -11088,6 +11285,537 @@ class ConfirmationScreen {
11088
11285
  }
11089
11286
  }
11090
11287
 
11288
+ var RelayerTransactionStatus;
11289
+ (function (RelayerTransactionStatus) {
11290
+ RelayerTransactionStatus["PENDING"] = "PENDING";
11291
+ RelayerTransactionStatus["SUBMITTED"] = "SUBMITTED";
11292
+ RelayerTransactionStatus["SUCCESSFUL"] = "SUCCESSFUL";
11293
+ RelayerTransactionStatus["REVERTED"] = "REVERTED";
11294
+ RelayerTransactionStatus["FAILED"] = "FAILED";
11295
+ })(RelayerTransactionStatus || (RelayerTransactionStatus = {}));
11296
+ exports.ProviderEvent = void 0;
11297
+ (function (ProviderEvent) {
11298
+ ProviderEvent["ACCOUNTS_CHANGED"] = "accountsChanged";
11299
+ })(exports.ProviderEvent || (exports.ProviderEvent = {}));
11300
+
11301
+ class TypedEventEmitter {
11302
+ emitter = new events.EventEmitter();
11303
+ emit(eventName, ...eventArg) {
11304
+ this.emitter.emit(eventName, ...eventArg);
11305
+ }
11306
+ on(eventName, handler) {
11307
+ this.emitter.on(eventName, handler);
11308
+ }
11309
+ removeListener(eventName, handler) {
11310
+ this.emitter.removeListener(eventName, handler);
11311
+ }
11312
+ }
11313
+
11314
+ class RelayerClient {
11315
+ config;
11316
+ constructor({ config }) {
11317
+ this.config = config;
11318
+ }
11319
+ async postToRelayer(request) {
11320
+ const body = {
11321
+ id: 1,
11322
+ jsonrpc: '2.0',
11323
+ ...request,
11324
+ };
11325
+ const response = await fetch(`${this.config.relayerUrl}/v1/transactions`, {
11326
+ method: 'POST',
11327
+ headers: {
11328
+ 'Content-Type': 'application/json',
11329
+ },
11330
+ body: JSON.stringify(body),
11331
+ });
11332
+ const jsonResponse = await response.json();
11333
+ if (jsonResponse.error) {
11334
+ throw jsonResponse.error;
11335
+ }
11336
+ return jsonResponse;
11337
+ }
11338
+ async ethSendTransaction(to, data) {
11339
+ const payload = {
11340
+ method: 'eth_sendTransaction',
11341
+ params: [{
11342
+ to,
11343
+ data,
11344
+ chainId: this.config.zkEvmChainId.toString(),
11345
+ }],
11346
+ };
11347
+ const { result } = await this.postToRelayer(payload);
11348
+ return result;
11349
+ }
11350
+ async imGetTransactionByHash(hash) {
11351
+ const payload = {
11352
+ method: 'im_getTransactionByHash',
11353
+ params: [hash],
11354
+ };
11355
+ const { result } = await this.postToRelayer(payload);
11356
+ return result;
11357
+ }
11358
+ async imGetFeeOptions(userAddress, data) {
11359
+ const payload = {
11360
+ method: 'im_getFeeOptions',
11361
+ params: [{
11362
+ userAddress,
11363
+ data,
11364
+ chainId: this.config.zkEvmChainId.toString(),
11365
+ }],
11366
+ };
11367
+ const { result } = await this.postToRelayer(payload);
11368
+ return result;
11369
+ }
11370
+ }
11371
+
11372
+ /**
11373
+ * ProviderErrors should take priority over RpcErrorCodes
11374
+ */
11375
+ exports.ProviderErrorCode = void 0;
11376
+ (function (ProviderErrorCode) {
11377
+ ProviderErrorCode[ProviderErrorCode["USER_REJECTED_REQUEST"] = 4001] = "USER_REJECTED_REQUEST";
11378
+ ProviderErrorCode[ProviderErrorCode["UNAUTHORIZED"] = 4100] = "UNAUTHORIZED";
11379
+ ProviderErrorCode[ProviderErrorCode["UNSUPPORTED_METHOD"] = 4200] = "UNSUPPORTED_METHOD";
11380
+ ProviderErrorCode[ProviderErrorCode["DISCONNECTED"] = 4900] = "DISCONNECTED";
11381
+ })(exports.ProviderErrorCode || (exports.ProviderErrorCode = {}));
11382
+ exports.RpcErrorCode = void 0;
11383
+ (function (RpcErrorCode) {
11384
+ RpcErrorCode[RpcErrorCode["RPC_SERVER_ERROR"] = -32000] = "RPC_SERVER_ERROR";
11385
+ RpcErrorCode[RpcErrorCode["INVALID_REQUEST"] = -32600] = "INVALID_REQUEST";
11386
+ RpcErrorCode[RpcErrorCode["METHOD_NOT_FOUND"] = -32601] = "METHOD_NOT_FOUND";
11387
+ RpcErrorCode[RpcErrorCode["INVALID_PARAMS"] = -32602] = "INVALID_PARAMS";
11388
+ RpcErrorCode[RpcErrorCode["INTERNAL_ERROR"] = -32603] = "INTERNAL_ERROR";
11389
+ RpcErrorCode[RpcErrorCode["PARSE_ERROR"] = -32700] = "PARSE_ERROR";
11390
+ })(exports.RpcErrorCode || (exports.RpcErrorCode = {}));
11391
+ class JsonRpcError extends Error {
11392
+ message;
11393
+ code;
11394
+ constructor(code, message) {
11395
+ super(message);
11396
+ this.message = message;
11397
+ this.code = code;
11398
+ }
11399
+ }
11400
+
11401
+ const MESSAGE_TO_SIGN = 'Only sign this message from Immutable Passport';
11402
+ async function registerZkEvmUser({ authManager, magicProvider, multiRollupApiClients, accessToken, }) {
11403
+ const web3Provider = new providers.Web3Provider(magicProvider);
11404
+ const ethSigner = web3Provider.getSigner();
11405
+ const ethereumAddress = await ethSigner.getAddress();
11406
+ const ethereumSignature = await signRaw(MESSAGE_TO_SIGN, ethSigner);
11407
+ const headers = { Authorization: `Bearer ${accessToken}` };
11408
+ try {
11409
+ await multiRollupApiClients.passportApi.createCounterfactualAddress({
11410
+ createCounterfactualAddressRequest: {
11411
+ ethereumAddress,
11412
+ ethereumSignature,
11413
+ },
11414
+ }, { headers });
11415
+ }
11416
+ catch (error) {
11417
+ throw new JsonRpcError(exports.RpcErrorCode.INTERNAL_ERROR, `Failed to create counterfactual address: ${error}`);
11418
+ }
11419
+ const user = await authManager.loginSilent();
11420
+ if (!user?.zkEvm) {
11421
+ throw new JsonRpcError(exports.RpcErrorCode.INTERNAL_ERROR, 'Failed to refresh user details');
11422
+ }
11423
+ return user;
11424
+ }
11425
+
11426
+ const loginZkEvmUser = async ({ authManager, config, magicAdapter, multiRollupApiClients, }) => {
11427
+ const user = await authManager.getUser() || await authManager.login();
11428
+ if (!user.idToken) {
11429
+ throw new Error('User is missing idToken');
11430
+ }
11431
+ const magicProvider = await magicAdapter.login(user.idToken, config.network);
11432
+ if (!user.zkEvm) {
11433
+ // Generate counterfactual address and retrieve updated Auth0 user
11434
+ const userZkevm = await registerZkEvmUser({
11435
+ authManager,
11436
+ magicProvider,
11437
+ multiRollupApiClients,
11438
+ accessToken: user.accessToken,
11439
+ });
11440
+ return {
11441
+ user: userZkevm,
11442
+ magicProvider,
11443
+ };
11444
+ }
11445
+ return {
11446
+ user: user,
11447
+ magicProvider,
11448
+ };
11449
+ };
11450
+
11451
+ // These are ignored by the Relayer but for consistency we set them to the
11452
+ // appropriate values for a 1/1 wallet.
11453
+ //
11454
+ // Weight of a single signature in the multisig
11455
+ const SIGNATURE_WEIGHT = 1;
11456
+ // Total required weight in the multisig
11457
+ const SIGNATURE_THRESHOLD = 1;
11458
+ const ETH_SIGN_FLAG = '02';
11459
+ const ETH_SIGN_PREFIX = '\x19\x01';
11460
+ const META_TRANSACTIONS_TYPE = `tuple(
11461
+ bool delegateCall,
11462
+ bool revertOnError,
11463
+ uint256 gasLimit,
11464
+ address target,
11465
+ uint256 value,
11466
+ bytes data
11467
+ )[]`;
11468
+ function getNormalisedTransactions(txs) {
11469
+ return txs.map((t) => ({
11470
+ delegateCall: t.delegateCall === true,
11471
+ revertOnError: t.revertOnError === true,
11472
+ gasLimit: t.gasLimit ?? ethers.ethers.constants.Zero,
11473
+ target: t.to ?? ethers.ethers.constants.AddressZero,
11474
+ value: t.value ?? ethers.ethers.constants.Zero,
11475
+ data: t.data ?? [],
11476
+ }));
11477
+ }
11478
+ function digestOfTransactionsAndNonce(nonce, normalisedTransactions) {
11479
+ const packMetaTransactionsNonceData = ethers.ethers.utils.defaultAbiCoder.encode(['uint256', META_TRANSACTIONS_TYPE], [nonce, normalisedTransactions]);
11480
+ return ethers.ethers.utils.keccak256(packMetaTransactionsNonceData);
11481
+ }
11482
+ const getNonce = async (jsonRpcProvider, smartContractWalletAddress) => {
11483
+ const code = await jsonRpcProvider.send('eth_getCode', [smartContractWalletAddress, 'latest']);
11484
+ if (code && code !== '0x') {
11485
+ const contract = new ethers.ethers.Contract(smartContractWalletAddress, abi.walletContracts.mainModule.abi, jsonRpcProvider);
11486
+ return contract.nonce();
11487
+ }
11488
+ return 0;
11489
+ };
11490
+ const getSignedMetaTransactions = async (metaTransactions, nonce, chainId, walletAddress, signer) => {
11491
+ const normalisedMetaTransactions = getNormalisedTransactions(metaTransactions);
11492
+ // Get the hash
11493
+ const digest = digestOfTransactionsAndNonce(nonce, normalisedMetaTransactions);
11494
+ const completePayload = ethers.ethers.utils.solidityPack(['string', 'uint256', 'address', 'bytes32'], [ETH_SIGN_PREFIX, chainId, walletAddress, digest]);
11495
+ const hash = ethers.ethers.utils.keccak256(completePayload);
11496
+ // Sign the digest
11497
+ const hashArray = ethers.ethers.utils.arrayify(hash);
11498
+ const ethsigNoType = await signer.signMessage(hashArray);
11499
+ const signedDigest = `${ethsigNoType}${ETH_SIGN_FLAG}`;
11500
+ // Add metadata
11501
+ const encodedSignature = config.encodeSignature({
11502
+ threshold: SIGNATURE_THRESHOLD,
11503
+ signers: [
11504
+ {
11505
+ weight: SIGNATURE_WEIGHT,
11506
+ signature: signedDigest,
11507
+ },
11508
+ ],
11509
+ });
11510
+ // Encode the transaction;
11511
+ const walletInterface = new ethers.ethers.utils.Interface(abi.walletContracts.mainModule.abi);
11512
+ return walletInterface.encodeFunctionData(walletInterface.getFunction('execute'), [
11513
+ normalisedMetaTransactions,
11514
+ nonce,
11515
+ encodedSignature,
11516
+ ]);
11517
+ };
11518
+ const chainIdNumber = (chainId) => {
11519
+ const caip2Components = chainId.split(':');
11520
+ if (caip2Components.length !== 2) {
11521
+ throw new Error('Invalid configuration, chain ID is not in CAIP-2 format');
11522
+ }
11523
+ return ethers.BigNumber.from(caip2Components[1]);
11524
+ };
11525
+
11526
+ const MAX_TRANSACTION_HASH_RETRIEVAL_RETRIES = 30;
11527
+ const TRANSACTION_HASH_RETRIEVAL_WAIT = 1000;
11528
+ const converBigNumberishToNumber = (value) => ethers.BigNumber.from(value).toNumber();
11529
+ const transformGardianTransactions = (txs) => {
11530
+ try {
11531
+ return txs.map((t) => ({
11532
+ delegateCall: t.delegateCall === true,
11533
+ revertOnError: t.revertOnError === true,
11534
+ gasLimit: t.gasLimit ? converBigNumberishToNumber(t.gasLimit).toString() : '0',
11535
+ target: t.to ?? ethers.ethers.constants.AddressZero,
11536
+ value: t.value ? converBigNumberishToNumber(t.value).toString() : '0',
11537
+ data: t.data ? t.data.toString() : '0x00',
11538
+ }));
11539
+ }
11540
+ catch (error) {
11541
+ const errorMessage = (error instanceof Error) ? error.message : String(error);
11542
+ throw new JsonRpcError(exports.RpcErrorCode.INVALID_PARAMS, `Transaction failed to parsing: ${errorMessage}`);
11543
+ }
11544
+ };
11545
+ const guardianValidation = async ({ transactionAPI, chainId, nonce, user, metaTransactions, }) => {
11546
+ const headers = { Authorization: `Bearer ${user.accessToken}` };
11547
+ const guardianTransactions = transformGardianTransactions(metaTransactions);
11548
+ try {
11549
+ await transactionAPI.evaluateTransaction({
11550
+ id: 'evm',
11551
+ transactionEvaluationRequest: {
11552
+ chainType: 'evm',
11553
+ chainId,
11554
+ transactionData: {
11555
+ nonce,
11556
+ userAddress: user.zkEvm.ethAddress,
11557
+ metaTransactions: guardianTransactions,
11558
+ },
11559
+ },
11560
+ }, { headers });
11561
+ }
11562
+ catch (error) {
11563
+ const errorMessage = (error instanceof Error) ? error.message : String(error);
11564
+ throw new JsonRpcError(exports.RpcErrorCode.INTERNAL_ERROR, `Transaction failed to validate with error: ${errorMessage}`);
11565
+ }
11566
+ };
11567
+ const sendTransaction = async ({ params, magicProvider, jsonRpcProvider, relayerClient, transactionAPI, config, user, }) => {
11568
+ const transactionRequest = params[0];
11569
+ if (!transactionRequest.to) {
11570
+ throw new JsonRpcError(exports.RpcErrorCode.INVALID_PARAMS, 'eth_sendTransaction requires a "to" field');
11571
+ }
11572
+ const chainId = chainIdNumber(config.zkEvmChainId);
11573
+ const magicWeb3Provider = new providers.Web3Provider(magicProvider);
11574
+ const signer = magicWeb3Provider.getSigner();
11575
+ const nonce = await getNonce(jsonRpcProvider, user.zkEvm.ethAddress);
11576
+ const metaTransaction = {
11577
+ to: transactionRequest.to,
11578
+ data: transactionRequest.data,
11579
+ nonce,
11580
+ value: transactionRequest.value,
11581
+ revertOnError: true,
11582
+ };
11583
+ // NOTE: We sign the transaction before getting the fee options because
11584
+ // accurate estimation of a transaction gas cost is only possible if the smart
11585
+ // wallet contract can actually execute it (in a simulated environment) - and
11586
+ // it can only execute signed transactions.
11587
+ const signedTransaction = await getSignedMetaTransactions([metaTransaction], nonce, chainId, user.zkEvm.ethAddress, signer);
11588
+ // TODO: ID-698 Add support for non-native gas payments (e.g ERC20, feeTransaction initialisation must change)
11589
+ // NOTE: "Fee Options" represent the multiple ways we could pay for the gas
11590
+ // used in this transaction. Each fee option has a "recipientAddress" we
11591
+ // should transfer the payment to, an amount and a currency. We choose one
11592
+ // option and build a transaction that sends the expected currency amount for
11593
+ // that option to the specified address.
11594
+ const feeOptions = await relayerClient.imGetFeeOptions(user.zkEvm.ethAddress, signedTransaction);
11595
+ const imxFeeOption = feeOptions.find((feeOption) => feeOption.tokenSymbol === 'IMX');
11596
+ if (!imxFeeOption) {
11597
+ throw new Error('Failed to retrieve fees for IMX token');
11598
+ }
11599
+ const feeMetaTransaction = {
11600
+ nonce,
11601
+ to: imxFeeOption.recipientAddress,
11602
+ value: imxFeeOption.tokenPrice,
11603
+ revertOnError: true,
11604
+ };
11605
+ await guardianValidation({
11606
+ transactionAPI,
11607
+ chainId: config.zkEvmChainId,
11608
+ nonce: converBigNumberishToNumber(nonce),
11609
+ user,
11610
+ metaTransactions: [metaTransaction, feeMetaTransaction],
11611
+ });
11612
+ // NOTE: We sign again because we now are adding the fee transaction, so the
11613
+ // whole payload is different and needs a new signature.
11614
+ const signedTransactions = await getSignedMetaTransactions([metaTransaction, feeMetaTransaction], nonce, chainId, user.zkEvm.ethAddress, signer);
11615
+ // TODO: ID-697 Evaluate transactions through Guardian
11616
+ const relayerId = await relayerClient.ethSendTransaction(user.zkEvm.ethAddress, signedTransactions);
11617
+ const retrieveRelayerTransaction = async () => {
11618
+ const tx = await relayerClient.imGetTransactionByHash(relayerId);
11619
+ // NOTE: The transaction hash is only available from the Relayer once the
11620
+ // transaction is actually submitted onchain. Hence we need to poll the
11621
+ // Relayer get transaction endpoint until the status transitions to one that
11622
+ // has the hash available.
11623
+ if (tx.status === RelayerTransactionStatus.PENDING) {
11624
+ throw new Error();
11625
+ }
11626
+ return tx;
11627
+ };
11628
+ const relayerTransaction = await retryWithDelay(retrieveRelayerTransaction, {
11629
+ retries: MAX_TRANSACTION_HASH_RETRIEVAL_RETRIES,
11630
+ interval: TRANSACTION_HASH_RETRIEVAL_WAIT,
11631
+ finalErr: new JsonRpcError(exports.RpcErrorCode.RPC_SERVER_ERROR, 'transaction hash not generated in time'),
11632
+ });
11633
+ if (![RelayerTransactionStatus.SUBMITTED, RelayerTransactionStatus.SUCCESSFUL].includes(relayerTransaction.status)) {
11634
+ throw new JsonRpcError(exports.RpcErrorCode.RPC_SERVER_ERROR, `Transaction failed to submit with status ${relayerTransaction.status}`);
11635
+ }
11636
+ return relayerTransaction.hash;
11637
+ };
11638
+
11639
+ class ZkEvmProvider {
11640
+ authManager;
11641
+ config;
11642
+ confirmationScreen;
11643
+ magicAdapter;
11644
+ relayerClient;
11645
+ transactionAPI;
11646
+ multiRollupApiClients;
11647
+ jsonRpcProvider; // Used for read
11648
+ eventEmitter;
11649
+ magicProvider; // Used for signing
11650
+ user;
11651
+ constructor({ authManager, magicAdapter, config, confirmationScreen, multiRollupApiClients, }) {
11652
+ this.authManager = authManager;
11653
+ this.magicAdapter = magicAdapter;
11654
+ this.config = config;
11655
+ this.confirmationScreen = confirmationScreen;
11656
+ this.relayerClient = new RelayerClient({ config });
11657
+ this.transactionAPI = new TransactionsApi(new Configuration({
11658
+ basePath: this.config.imxPublicApiDomain,
11659
+ }));
11660
+ this.jsonRpcProvider = new providers.JsonRpcProvider(this.config.zkEvmRpcUrl);
11661
+ this.multiRollupApiClients = multiRollupApiClients;
11662
+ this.eventEmitter = new TypedEventEmitter();
11663
+ }
11664
+ isLoggedIn() {
11665
+ return this.magicProvider !== undefined && this.user !== undefined;
11666
+ }
11667
+ async performRequest(request) {
11668
+ switch (request.method) {
11669
+ case 'eth_requestAccounts': {
11670
+ if (this.isLoggedIn()) {
11671
+ return [this.user.zkEvm.ethAddress];
11672
+ }
11673
+ const { magicProvider, user } = await loginZkEvmUser({
11674
+ authManager: this.authManager,
11675
+ config: this.config,
11676
+ magicAdapter: this.magicAdapter,
11677
+ multiRollupApiClients: this.multiRollupApiClients,
11678
+ });
11679
+ this.user = user;
11680
+ this.magicProvider = magicProvider;
11681
+ this.eventEmitter.emit(exports.ProviderEvent.ACCOUNTS_CHANGED, [this.user.zkEvm.ethAddress]);
11682
+ return [this.user.zkEvm.ethAddress];
11683
+ }
11684
+ case 'eth_sendTransaction': {
11685
+ if (!this.isLoggedIn()) {
11686
+ throw new JsonRpcError(exports.ProviderErrorCode.UNAUTHORIZED, 'Unauthorised - call eth_requestAccounts first');
11687
+ }
11688
+ return sendTransaction({
11689
+ params: request.params || [],
11690
+ magicProvider: this.magicProvider,
11691
+ transactionAPI: this.transactionAPI,
11692
+ jsonRpcProvider: this.jsonRpcProvider,
11693
+ config: this.config,
11694
+ relayerClient: this.relayerClient,
11695
+ user: this.user,
11696
+ });
11697
+ }
11698
+ case 'eth_accounts': {
11699
+ return this.isLoggedIn() ? [this.user.zkEvm.ethAddress] : [];
11700
+ }
11701
+ // Pass through methods
11702
+ case 'eth_gasPrice':
11703
+ case 'eth_getBalance':
11704
+ case 'eth_getStorageAt':
11705
+ case 'eth_estimateGas':
11706
+ case 'eth_call':
11707
+ case 'eth_blockNumber':
11708
+ case 'eth_chainId':
11709
+ case 'eth_getBlockByHash':
11710
+ case 'eth_getBlockByNumber':
11711
+ case 'eth_getTransactionByHash':
11712
+ case 'eth_getTransactionReceipt':
11713
+ case 'eth_getTransactionCount': {
11714
+ return this.jsonRpcProvider.send(request.method, request.params || []);
11715
+ }
11716
+ default: {
11717
+ throw new JsonRpcError(exports.ProviderErrorCode.UNSUPPORTED_METHOD, 'Method not supported');
11718
+ }
11719
+ }
11720
+ }
11721
+ async performJsonRpcRequest(request) {
11722
+ const { id, jsonrpc } = request;
11723
+ try {
11724
+ const result = await this.performRequest(request);
11725
+ return {
11726
+ id,
11727
+ jsonrpc,
11728
+ result,
11729
+ };
11730
+ }
11731
+ catch (error) {
11732
+ let jsonRpcError;
11733
+ if (error instanceof JsonRpcError) {
11734
+ jsonRpcError = error;
11735
+ }
11736
+ else if (error instanceof Error) {
11737
+ jsonRpcError = new JsonRpcError(exports.RpcErrorCode.INTERNAL_ERROR, error.message);
11738
+ }
11739
+ else {
11740
+ jsonRpcError = new JsonRpcError(exports.RpcErrorCode.INTERNAL_ERROR, 'Internal error');
11741
+ }
11742
+ return {
11743
+ id,
11744
+ jsonrpc,
11745
+ error: jsonRpcError,
11746
+ };
11747
+ }
11748
+ }
11749
+ async request(request) {
11750
+ try {
11751
+ return this.performRequest(request);
11752
+ }
11753
+ catch (error) {
11754
+ if (error instanceof JsonRpcError) {
11755
+ throw error;
11756
+ }
11757
+ if (error instanceof Error) {
11758
+ throw new JsonRpcError(exports.RpcErrorCode.INTERNAL_ERROR, error.message);
11759
+ }
11760
+ throw new JsonRpcError(exports.RpcErrorCode.INTERNAL_ERROR, 'Internal error');
11761
+ }
11762
+ }
11763
+ sendAsync(request, callback) {
11764
+ if (!callback) {
11765
+ throw new Error('No callback provided');
11766
+ }
11767
+ if (Array.isArray(request)) {
11768
+ Promise.all(request.map(this.performJsonRpcRequest)).then((result) => {
11769
+ callback(null, result);
11770
+ }).catch((error) => {
11771
+ callback(error, []);
11772
+ });
11773
+ }
11774
+ else {
11775
+ this.performJsonRpcRequest(request).then((result) => {
11776
+ callback(null, result);
11777
+ }).catch((error) => {
11778
+ callback(error, null);
11779
+ });
11780
+ }
11781
+ }
11782
+ async send(request, callbackOrParams, callback) {
11783
+ // Web3 >= 1.0.0-beta.38 calls `send` with method and parameters.
11784
+ if (typeof request === 'string') {
11785
+ if (typeof callbackOrParams === 'function') {
11786
+ return this.sendAsync({
11787
+ method: request,
11788
+ params: [],
11789
+ }, callbackOrParams);
11790
+ }
11791
+ if (callback) {
11792
+ return this.sendAsync({
11793
+ method: request,
11794
+ params: Array.isArray(callbackOrParams) ? callbackOrParams : [],
11795
+ }, callback);
11796
+ }
11797
+ return this.request({
11798
+ method: request,
11799
+ params: Array.isArray(callbackOrParams) ? callbackOrParams : [],
11800
+ });
11801
+ }
11802
+ // Web3 <= 1.0.0-beta.37 uses `send` with a callback for async queries.
11803
+ if (typeof callbackOrParams === 'function') {
11804
+ return this.sendAsync(request, callbackOrParams);
11805
+ }
11806
+ if (!Array.isArray(request) && typeof request === 'object') {
11807
+ return this.performJsonRpcRequest(request);
11808
+ }
11809
+ throw new JsonRpcError(exports.RpcErrorCode.INVALID_REQUEST, 'Invalid request');
11810
+ }
11811
+ on(event, listener) {
11812
+ this.eventEmitter.on(event, listener);
11813
+ }
11814
+ removeListener(event, listener) {
11815
+ this.eventEmitter.removeListener(event, listener);
11816
+ }
11817
+ }
11818
+
11091
11819
  class Passport {
11092
11820
  authManager;
11093
11821
  config;
@@ -11095,6 +11823,7 @@ class Passport {
11095
11823
  immutableXClient;
11096
11824
  magicAdapter;
11097
11825
  passportImxProviderFactory;
11826
+ multiRollupApiClients;
11098
11827
  constructor(passportModuleConfiguration) {
11099
11828
  this.config = new PassportConfiguration(passportModuleConfiguration);
11100
11829
  this.authManager = new AuthManager(this.config);
@@ -11104,6 +11833,7 @@ class Passport {
11104
11833
  || new ImmutableXClient({
11105
11834
  baseConfig: passportModuleConfiguration.baseConfig,
11106
11835
  });
11836
+ this.multiRollupApiClients = new MultiRollupApiClients(this.config.multiRollupConfig);
11107
11837
  this.passportImxProviderFactory = new PassportImxProviderFactory({
11108
11838
  authManager: this.authManager,
11109
11839
  config: this.config,
@@ -11133,12 +11863,29 @@ class Passport {
11133
11863
  async connectImxWithCredentials(tokenResponse) {
11134
11864
  return this.passportImxProviderFactory.getProviderWithCredentials(tokenResponse);
11135
11865
  }
11866
+ // TODO ID-926 Make method public once development has been finalised
11867
+ connectEvm() {
11868
+ return new ZkEvmProvider({
11869
+ authManager: this.authManager,
11870
+ magicAdapter: this.magicAdapter,
11871
+ config: this.config,
11872
+ confirmationScreen: this.confirmationScreen,
11873
+ multiRollupApiClients: this.multiRollupApiClients,
11874
+ });
11875
+ }
11136
11876
  async loginCallback() {
11137
11877
  return this.authManager.loginCallback();
11138
11878
  }
11139
11879
  async logout() {
11140
11880
  return this.authManager.logout();
11141
11881
  }
11882
+ /**
11883
+ * This method should only be called from the logout redirect uri
11884
+ * when logout mode is 'silent'.
11885
+ */
11886
+ async logoutSilentCallback(url) {
11887
+ return this.authManager.logoutSilentCallback(url);
11888
+ }
11142
11889
  async logoutDeviceFlow() {
11143
11890
  return this.authManager.logoutDeviceFlow();
11144
11891
  }
@@ -12055,31 +12802,25 @@ class ImmutableApiClientFactory {
12055
12802
  }
12056
12803
  }
12057
12804
 
12058
- const DEVNET_CHAIN_NAME = 'imtbl-zkevm-devnet';
12059
12805
  const TESTNET_CHAIN_NAME = 'imtbl-zkevm-testnet';
12060
12806
  const MAINNET_CHAIN_NAME = 'imtbl-zkevm-mainnet';
12061
- function getOrderbookConfig(chainName) {
12062
- switch (chainName) {
12063
- case DEVNET_CHAIN_NAME:
12807
+ function getOrderbookConfig(environment) {
12808
+ switch (environment) {
12809
+ case exports.Environment.SANDBOX:
12064
12810
  return {
12065
- seaportContractAddress: '0x41388404Efb7a68Fd31d75CEf71dF91e2BDBa2fb',
12066
- zoneContractAddress: '0xCb5063b0c1dcF4f7fed8E7eaa79faf9859792767',
12067
- apiEndpoint: 'https://order-book-mr.dev.imtbl.com',
12068
- provider: new ethers.providers.JsonRpcProvider('https://zkevm-rpc.dev.x.immutable.com'),
12069
- };
12070
- case TESTNET_CHAIN_NAME:
12071
- return {
12072
- seaportContractAddress: '0x45E23dA18804F99Cf67408AeBE85F67c958381Ff',
12073
- zoneContractAddress: '0x25b00b7eb97eab6194798E9B8eF63Aa526D5bd7E',
12811
+ seaportContractAddress: '0x474989C4D25DD41B0B9b1ECb4643B9Fe25f83B19',
12812
+ zoneContractAddress: '0x6FeDb4949E5b452700A8a8956999a7E05B6770F3',
12074
12813
  apiEndpoint: 'https://order-book-mr.sandbox.imtbl.com',
12814
+ chainName: TESTNET_CHAIN_NAME,
12075
12815
  provider: new ethers.providers.JsonRpcProvider('https://zkevm-rpc.sandbox.x.immutable.com'),
12076
12816
  };
12077
- case MAINNET_CHAIN_NAME:
12078
- // not yet deployed
12817
+ // not yet deployed
12818
+ case exports.Environment.PRODUCTION:
12079
12819
  return {
12080
12820
  seaportContractAddress: '',
12081
12821
  zoneContractAddress: '',
12082
12822
  apiEndpoint: 'https://order-book-mr.imtbl.com',
12823
+ chainName: MAINNET_CHAIN_NAME,
12083
12824
  provider: new ethers.providers.JsonRpcProvider('https://zkevm-rpc.x.immutable.com'),
12084
12825
  };
12085
12826
  default:
@@ -13038,21 +13779,19 @@ class Orderbook {
13038
13779
  apiClient;
13039
13780
  seaport;
13040
13781
  orderbookConfig;
13041
- constructor(config, localConfig) {
13042
- // either use preconfigured config or local config passed in
13043
- const maybeConfig = getOrderbookConfig(config.overrides?.chainName) || localConfig;
13044
- if (!maybeConfig) {
13045
- throw new Error('Orderbook configuration not passed, either select one of the preseet chainNames or pass in localConfig');
13046
- }
13047
- this.orderbookConfig = maybeConfig;
13048
- const { apiEndpoint } = this.orderbookConfig;
13049
- if (!apiEndpoint) {
13050
- throw new Error('API endpoint must be provided as an override');
13782
+ constructor(config) {
13783
+ const obConfig = getOrderbookConfig(config.baseConfig.environment);
13784
+ const finalConfig = {
13785
+ ...obConfig,
13786
+ ...config.overrides,
13787
+ };
13788
+ if (!finalConfig) {
13789
+ throw new Error('Orderbook configuration not passed, please specify the environment under config.baseConfig.environment');
13051
13790
  }
13052
- // TODO: Move chainId lookup to a map based on env. Just using override to get dev started
13053
- const chainName = config.overrides?.chainName;
13054
- if (!chainName) {
13055
- throw new Error('chainName must be provided as an override');
13791
+ this.orderbookConfig = finalConfig;
13792
+ const { apiEndpoint, chainName } = this.orderbookConfig;
13793
+ if (!apiEndpoint) {
13794
+ throw new Error('API endpoint must be provided');
13056
13795
  }
13057
13796
  this.apiClient = new ImmutableApiClientFactory(apiEndpoint, chainName, this.orderbookConfig.seaportContractAddress).create();
13058
13797
  const seaportLibFactory = new SeaportLibFactory(this.orderbookConfig.seaportContractAddress, this.orderbookConfig.provider);
@@ -24387,7 +25126,7 @@ const ETH_MAINNET_CHAIN_ID = 'eip155:1';
24387
25126
  /**
24388
25127
  * @constant {string} ZKEVM_DEVNET_CHAIN_ID - The chain ID for the zkEVM devnet (EIP-155 compatible format).
24389
25128
  */
24390
- const ZKEVM_DEVNET_CHAIN_ID = 'eip155:13403';
25129
+ const ZKEVM_DEVNET_CHAIN_ID = 'eip155:13423';
24391
25130
  /**
24392
25131
  /**
24393
25132
  * @constant {string} ZKEVM_TESTNET_CHAIN_ID - The chain ID for the zkEVM testnet (EIP-155 compatible format).
@@ -24445,14 +25184,14 @@ const SUPPORTED_BRIDGES_FOR_ENVIRONMENT = {
24445
25184
  */
24446
25185
  const CONTRACTS_FOR_BRIDGE = new Map()
24447
25186
  .set(ETH_SEPOLIA_TO_ZKEVM_DEVNET, {
24448
- rootChainERC20Predicate: '0x15Dd735de418B6d290727aed82cC25F8966dE4A5',
24449
- rootChainStateSender: '0xb3Bac13799dAca9D9eC9307303a65fA1218b4724',
25187
+ rootChainERC20Predicate: '0xf0b3435411A74F1aeCBD0fd6D53a90D5227fEeba',
25188
+ rootChainStateSender: '0x868097dbAcfD431F441d09D0e4D3B5eD3182E597',
24450
25189
  childChainERC20Predicate: '0x0000000000000000000000000000000000001004',
24451
25190
  childChainStateReceiver: '0x0000000000000000000000000000000000001001',
24452
25191
  })
24453
25192
  .set(ETH_SEPOLIA_TO_ZKEVM_TESTNET, {
24454
- rootChainERC20Predicate: '0x9A7E4C4337a70C6754a9672F5ba69084463794B8',
24455
- rootChainStateSender: '0xfBfF6FD165adFA113bE39eE85ef030A996153253',
25193
+ rootChainERC20Predicate: '0x0C15a8359865867CdCC44f98b2F3fd5DF098C7E0',
25194
+ rootChainStateSender: '0x4C80001188db53dbc2eaAb32d5ef825feEedECA5',
24456
25195
  childChainERC20Predicate: '0x0000000000000000000000000000000000001004',
24457
25196
  childChainStateReceiver: '0x0000000000000000000000000000000000001001',
24458
25197
  })
@@ -25044,7 +25783,7 @@ function getQuote(otherCurrency, tradeType, tradeInfo, slippage) {
25044
25783
  }
25045
25784
 
25046
25785
  const IMMUTABLE_TESTNET_RPC_URL = 'https://zkevm-rpc.sandbox.x.immutable.com';
25047
- const IMMUTABLE_TESTNET_CHAIN_ID = 13392;
25786
+ const IMMUTABLE_TESTNET_CHAIN_ID = 13372;
25048
25787
 
25049
25788
  const TIMX_IMMUTABLE_TESTNET = {
25050
25789
  chainId: IMMUTABLE_TESTNET_CHAIN_ID,
@@ -26683,16 +27422,28 @@ const SUPPORTED_CHAIN_IDS_FOR_ENVIRONMENT = {
26683
27422
  [exports.Environment.PRODUCTION]: SUPPORTED_PRODUCTION_CHAINS,
26684
27423
  };
26685
27424
  function validateOverrides(overrides) {
26686
- Object.entries(overrides).forEach(([key, value]) => {
26687
- if (!value) {
27425
+ const keysToCheck = ['rpcURL', 'exchangeContracts', 'commonRoutingTokens', 'nativeToken'];
27426
+ for (const key of keysToCheck) {
27427
+ if (!overrides[key]) {
26688
27428
  throw new InvalidConfigurationError(`Missing override: ${key}`);
26689
27429
  }
26690
- });
27430
+ }
26691
27431
  Object.entries(overrides.exchangeContracts).forEach(([key, contract]) => {
26692
27432
  if (!isValidNonZeroAddress(contract)) {
26693
27433
  throw new InvalidConfigurationError(`Invalid exchange contract address for ${key}`);
26694
27434
  }
26695
27435
  });
27436
+ if (!overrides.secondaryFees) {
27437
+ return;
27438
+ }
27439
+ for (const secondaryFee of overrides.secondaryFees) {
27440
+ if (!isValidNonZeroAddress(secondaryFee.feeRecipient)) {
27441
+ throw new InvalidConfigurationError(`Invalid secondary fee recipient address: ${secondaryFee.feeRecipient}`);
27442
+ }
27443
+ if (secondaryFee.feeBasisPoints < 0 || secondaryFee.feeBasisPoints > 10000) {
27444
+ throw new InvalidConfigurationError(`Invalid secondary fee percentage: ${secondaryFee.feeBasisPoints}`);
27445
+ }
27446
+ }
26696
27447
  }
26697
27448
  /**
26698
27449
  * {@link ExchangeConfiguration} is used to configure the {@link Exchange} class.
@@ -26702,6 +27453,7 @@ function validateOverrides(overrides) {
26702
27453
  class ExchangeConfiguration {
26703
27454
  baseConfig;
26704
27455
  chain;
27456
+ secondaryFees;
26705
27457
  constructor({ chainId, baseConfig, overrides }) {
26706
27458
  this.baseConfig = baseConfig;
26707
27459
  if (overrides) {
@@ -26713,8 +27465,10 @@ class ExchangeConfiguration {
26713
27465
  commonRoutingTokens: overrides.commonRoutingTokens,
26714
27466
  nativeToken: overrides.nativeToken,
26715
27467
  };
27468
+ this.secondaryFees = overrides.secondaryFees ? overrides.secondaryFees : [];
26716
27469
  return;
26717
27470
  }
27471
+ this.secondaryFees = [];
26718
27472
  const chain = SUPPORTED_CHAIN_IDS_FOR_ENVIRONMENT[baseConfig.environment][chainId];
26719
27473
  if (!chain) {
26720
27474
  throw new ChainNotSupportedError(chainId, baseConfig.environment);
@@ -26728,11 +27482,13 @@ class Exchange {
26728
27482
  router;
26729
27483
  chainId;
26730
27484
  nativeToken;
27485
+ secondaryFees;
26731
27486
  constructor(configuration) {
26732
27487
  const config = new ExchangeConfiguration(configuration);
26733
27488
  this.chainId = config.chain.chainId;
26734
27489
  this.nativeToken = config.chain.nativeToken;
26735
27490
  this.provider = new ethers.ethers.providers.JsonRpcProvider(config.chain.rpcUrl);
27491
+ this.secondaryFees = config.secondaryFees;
26736
27492
  this.router = new Router(this.provider, config.chain.commonRoutingTokens, {
26737
27493
  multicallAddress: config.chain.contracts.multicall,
26738
27494
  factoryAddress: config.chain.contracts.coreFactory,
@@ -26815,6 +27571,9 @@ class Exchange {
26815
27571
  async getUnsignedSwapTxFromAmountOut(fromAddress, tokenInAddress, tokenOutAddress, amountOut, slippagePercent = DEFAULT_SLIPPAGE, maxHops = DEFAULT_MAX_HOPS, deadline = DEFAULT_DEADLINE) {
26816
27572
  return await this.getUnsignedSwapTx(fromAddress, tokenInAddress, tokenOutAddress, amountOut, slippagePercent, maxHops, deadline, sdkCore.TradeType.EXACT_OUTPUT);
26817
27573
  }
27574
+ thereAreSecondaryFees() {
27575
+ return this.secondaryFees.length > 0;
27576
+ }
26818
27577
  }
26819
27578
 
26820
27579
  /* eslint-disable class-methods-use-this */
@@ -26891,8 +27650,8 @@ const $762782b6c862d954$export$db5daa1b5156ccfe = [
26891
27650
  */ exports.ChainId = void 0;
26892
27651
  (function(ChainId) {
26893
27652
  ChainId[ChainId["IMTBL_ZKEVM_MAINNET"] = 13371] = "IMTBL_ZKEVM_MAINNET";
26894
- ChainId[ChainId["IMTBL_ZKEVM_TESTNET"] = 13392] = "IMTBL_ZKEVM_TESTNET";
26895
- ChainId[ChainId["IMTBL_ZKEVM_DEVNET"] = 13403] = "IMTBL_ZKEVM_DEVNET";
27653
+ ChainId[ChainId["IMTBL_ZKEVM_TESTNET"] = 13372] = "IMTBL_ZKEVM_TESTNET";
27654
+ ChainId[ChainId["IMTBL_ZKEVM_DEVNET"] = 13423] = "IMTBL_ZKEVM_DEVNET";
26896
27655
  ChainId[ChainId["ETHEREUM"] = 1] = "ETHEREUM";
26897
27656
  ChainId[ChainId["SEPOLIA"] = 11155111] = "SEPOLIA";
26898
27657
  })(exports.ChainId || (exports.ChainId = {}));
@@ -26977,6 +27736,10 @@ const $d85ad1457a3f1a83$export$161d4a74df65fc08 = {
26977
27736
  [(exports.Environment).SANDBOX]: "https://checkout-api.sandbox.immutable.com",
26978
27737
  [(exports.Environment).PRODUCTION]: "https://checkout-api.immutable.com"
26979
27738
  };
27739
+ const $d85ad1457a3f1a83$export$7b057be2a3f512cc = {
27740
+ [(exports.Environment).SANDBOX]: "https://zkevm-rpc.sandbox.x.immutable.com",
27741
+ [(exports.Environment).PRODUCTION]: "https://zkevm-rpc.x.immutable.com"
27742
+ };
26980
27743
  const $d85ad1457a3f1a83$export$6f24f3cef7d501c4 = new Map([
26981
27744
  [
26982
27745
  (exports.ChainId).ETHEREUM,
@@ -27002,7 +27765,7 @@ const $d85ad1457a3f1a83$export$6f24f3cef7d501c4 = new Map([
27002
27765
  chainIdHex: `0x${(exports.ChainId).IMTBL_ZKEVM_MAINNET.toString(16)}`,
27003
27766
  chainName: (exports.ChainName).IMTBL_ZKEVM_MAINNET,
27004
27767
  rpcUrls: [
27005
- "https://zkevm-rpc.x.immutable.com"
27768
+ "https://rpc.immutable.com"
27006
27769
  ],
27007
27770
  nativeCurrency: {
27008
27771
  name: "IMX",
@@ -27037,7 +27800,7 @@ const $d85ad1457a3f1a83$export$3e81fc0987227f10 = new Map([
27037
27800
  chainIdHex: `0x${(exports.ChainId).IMTBL_ZKEVM_TESTNET.toString(16)}`,
27038
27801
  chainName: (exports.ChainName).IMTBL_ZKEVM_TESTNET,
27039
27802
  rpcUrls: [
27040
- "https://zkevm-rpc.sandbox.x.immutable.com"
27803
+ "https://rpc.testnet.immutable.com"
27041
27804
  ],
27042
27805
  nativeCurrency: {
27043
27806
  name: "IMX",
@@ -27413,16 +28176,19 @@ async function $5c763be0b0b81038$var$getMetaMaskProvider() {
27413
28176
  if (!provider || !provider.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("No MetaMask provider installed.", (exports.CheckoutErrorType).METAMASK_PROVIDER_ERROR);
27414
28177
  return new (providers.Web3Provider)(provider);
27415
28178
  }
27416
- async function $5c763be0b0b81038$export$500fbc0cd14cdbaa(defaultProvider) {
27417
- let web3Provider = null;
27418
- switch(defaultProvider){
28179
+ async function $5c763be0b0b81038$export$500fbc0cd14cdbaa(walletProviderName) {
28180
+ let provider = null;
28181
+ switch(walletProviderName){
27419
28182
  case (exports.WalletProviderName).METAMASK:
27420
- web3Provider = await $5c763be0b0b81038$var$getMetaMaskProvider();
28183
+ provider = await $5c763be0b0b81038$var$getMetaMaskProvider();
27421
28184
  break;
27422
28185
  default:
27423
28186
  throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Provider not supported", (exports.CheckoutErrorType).DEFAULT_PROVIDER_ERROR);
27424
28187
  }
27425
- return web3Provider;
28188
+ return {
28189
+ provider: provider,
28190
+ walletProviderName: walletProviderName
28191
+ };
27426
28192
  }
27427
28193
 
27428
28194
 
@@ -27431,9 +28197,8 @@ async function $5c763be0b0b81038$export$500fbc0cd14cdbaa(defaultProvider) {
27431
28197
 
27432
28198
 
27433
28199
 
27434
-
27435
28200
  function $bb88265fe45a0393$export$ebe4804963e71f98(web3Provider) {
27436
- if (web3Provider && web3Provider instanceof (providers.Web3Provider) && web3Provider.provider?.request) return true;
28201
+ if (web3Provider && web3Provider.provider?.request && typeof web3Provider.provider.request === "function") return true;
27437
28202
  return false;
27438
28203
  }
27439
28204
  async function $bb88265fe45a0393$export$9e1fd9cc88c637a0(config, web3Provider, validateProviderOptions) {
@@ -27643,10 +28408,23 @@ class $4013c5c91bb535f6$export$6ad73ea7e1b6f37f extends Error {
27643
28408
  this.message = message;
27644
28409
  }
27645
28410
  }
27646
- const $4013c5c91bb535f6$var$networkMap = (prod, dev)=>{
27647
- if (dev) return $d85ad1457a3f1a83$export$3a9ebede6a150274;
27648
- if (prod) return $d85ad1457a3f1a83$export$6f24f3cef7d501c4;
27649
- return $d85ad1457a3f1a83$export$3e81fc0987227f10;
28411
+ const $4013c5c91bb535f6$var$networkMap = (prod, dev, local)=>{
28412
+ let networks;
28413
+ if (dev) networks = ($d85ad1457a3f1a83$export$3a9ebede6a150274);
28414
+ else if (prod) {
28415
+ networks = ($d85ad1457a3f1a83$export$6f24f3cef7d501c4);
28416
+ if (local) {
28417
+ const rpcUrls = networks.get((exports.ChainId).IMTBL_ZKEVM_MAINNET)?.rpcUrls;
28418
+ rpcUrls?.splice(0, 1, ($d85ad1457a3f1a83$export$7b057be2a3f512cc)[(exports.Environment).PRODUCTION]);
28419
+ }
28420
+ } else {
28421
+ networks = ($d85ad1457a3f1a83$export$3e81fc0987227f10);
28422
+ if (local) {
28423
+ const rpcUrls = networks.get((exports.ChainId).IMTBL_ZKEVM_TESTNET)?.rpcUrls;
28424
+ rpcUrls?.splice(0, 1, ($d85ad1457a3f1a83$export$7b057be2a3f512cc)[(exports.Environment).SANDBOX]);
28425
+ }
28426
+ }
28427
+ return networks;
27650
28428
  };
27651
28429
  const $4013c5c91bb535f6$export$9b794d067cdd1af6 = (config)=>{
27652
28430
  // DevMode and Sandbox will both use Sepolia.
@@ -27664,6 +28442,11 @@ class $4013c5c91bb535f6$export$4823433c4a67bbc6 {
27664
28442
  // This will be used to get around the lack of
27665
28443
  // Environment.DEVELOPMENT
27666
28444
  isDevelopment = false;
28445
+ // This is a hidden feature that is only available
28446
+ // when building the project from source code.
28447
+ // This will be used to get around the lack of
28448
+ // Environment.LOCAL_DEVELOPMENT
28449
+ isLocal = false;
27667
28450
  isProduction;
27668
28451
  remote;
27669
28452
  environment;
@@ -27673,7 +28456,7 @@ class $4013c5c91bb535f6$export$4823433c4a67bbc6 {
27673
28456
  this.environment = config.baseConfig.environment;
27674
28457
  // Developer mode will super set any environment configuration
27675
28458
  this.isProduction = !this.isDevelopment && this.environment === (exports.Environment).PRODUCTION;
27676
- this.networkMap = $4013c5c91bb535f6$var$networkMap(this.isProduction, this.isDevelopment);
28459
+ this.networkMap = $4013c5c91bb535f6$var$networkMap(this.isProduction, this.isDevelopment, this.isLocal);
27677
28460
  this.remote = new ($a492ee374ae7b613$export$d902b56530cd5f87)({
27678
28461
  isDevelopment: this.isDevelopment,
27679
28462
  isProduction: this.isProduction
@@ -27819,10 +28602,7 @@ class $a8cb37a3fc8eb863$export$1f60ba4ec72508a0 {
27819
28602
  * @param {CreateProviderParams} params - The parameters for creating the provider.
27820
28603
  * @returns {Promise<CreateProviderResult>} A promise that resolves to the created provider.
27821
28604
  */ async createProvider(params) {
27822
- const web3Provider = await $5c763be0b0b81038$export$500fbc0cd14cdbaa(params.walletProvider);
27823
- return {
27824
- provider: web3Provider
27825
- };
28605
+ return await $5c763be0b0b81038$export$500fbc0cd14cdbaa(params.walletProvider);
27826
28606
  }
27827
28607
  /**
27828
28608
  * Checks if a wallet is connected to the specified provider.
@@ -27939,7 +28719,7 @@ class $a8cb37a3fc8eb863$export$1f60ba4ec72508a0 {
27939
28719
  function $parcel$export(e, n, v, s) {
27940
28720
  Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
27941
28721
  }
27942
- const $d663162fd5a0853f$export$38a083d9fb5551ca = "0.4.0-alpha.1";
28722
+ const $d663162fd5a0853f$export$38a083d9fb5551ca = "0.4.0-alpha.3";
27943
28723
  const $d663162fd5a0853f$export$83bf90b30cdfd29f = ()=>false;
27944
28724
  const $d663162fd5a0853f$export$1169f5475725171b = ()=>$d663162fd5a0853f$export$38a083d9fb5551ca;
27945
28725
 
@@ -29758,6 +30538,7 @@ exports.ERC721PermissionedMintable = ERC721PermissionedMintable;
29758
30538
  exports.GenericIMXProvider = GenericIMXProvider;
29759
30539
  exports.ImmutableConfiguration = ImmutableConfiguration;
29760
30540
  exports.ImmutableXClient = ImmutableXClient;
30541
+ exports.JsonRpcError = JsonRpcError;
29761
30542
  exports.MetaMaskIMXProvider = MetaMaskIMXProvider;
29762
30543
  exports.Orderbook = Orderbook;
29763
30544
  exports.Passport = Passport;