@imtbl/sdk 0.31.3 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -40,7 +40,6 @@ class ImmutableConfiguration {
40
40
  }
41
41
  const API_KEY_PREFIX = 'sk_imapik-';
42
42
  const PUBLISHABLE_KEY_PREFIX = 'pk_imapik-';
43
- const PUBLISHABLE_KEY_LENGTH = 30;
44
43
  const addApiKeyToAxiosHeader = (apiKey) => {
45
44
  if (!apiKey.startsWith(API_KEY_PREFIX)) {
46
45
  throw new Error('Invalid API key. Create your api key in Immutable developer hub. https://hub.immutable.com');
@@ -48,7 +47,7 @@ const addApiKeyToAxiosHeader = (apiKey) => {
48
47
  globalAxios$1.defaults.headers.common['x-immutable-api-key'] = apiKey;
49
48
  };
50
49
  const addPublishableKeyToAxiosHeader = (publishableKey) => {
51
- if (!publishableKey.startsWith(PUBLISHABLE_KEY_PREFIX) || publishableKey.length !== PUBLISHABLE_KEY_LENGTH) {
50
+ if (!publishableKey.startsWith(PUBLISHABLE_KEY_PREFIX)) {
52
51
  throw new Error('Invalid Publishable key. Create your Publishable key in Immutable developer hub.'
53
52
  + ' https://hub.immutable.com');
54
53
  }
@@ -3770,7 +3769,7 @@ class MultiRollupApiClients {
3770
3769
  }
3771
3770
 
3772
3771
  // eslint-disable-next-line @typescript-eslint/naming-convention
3773
- const defaultHeaders$1 = { 'x-sdk-version': 'ts-immutable-sdk-0.31.3' };
3772
+ const defaultHeaders$1 = { 'x-sdk-version': 'ts-immutable-sdk-0.33.0' };
3774
3773
  const createConfig = ({ basePath, headers, }) => {
3775
3774
  if (!basePath.trim()) {
3776
3775
  throw Error('basePath can not be empty');
@@ -3830,7 +3829,7 @@ class APIError extends Error {
3830
3829
 
3831
3830
  /* eslint-disable implicit-arrow-linebreak */
3832
3831
  const defaultHeaders = {
3833
- sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-0.31.3',
3832
+ sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-0.33.0',
3834
3833
  };
3835
3834
  /**
3836
3835
  * createAPIConfiguration to create a custom Configuration
@@ -4241,7 +4240,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
4241
4240
  chainID,
4242
4241
  coreContractAddress,
4243
4242
  registrationContractAddress,
4244
- sdkVersion: 'ts-immutable-sdk-0.31.3',
4243
+ sdkVersion: 'ts-immutable-sdk-0.33.0',
4245
4244
  });
4246
4245
  /**
4247
4246
  * Sets `sdkVersion` at the time of build
@@ -28666,13 +28665,13 @@ const subtractAmount = (a, b) => {
28666
28665
  /**
28667
28666
  * Converts our internal token type which could be ERC20 or Native
28668
28667
  * into a format consumable by Checkout. They require an address to be
28669
- * present. We populate the address with empty string if it's Native.
28668
+ * present. We populate the address with the string 'native' if it's Native.
28670
28669
  * If it's ERC20, we don't need to change it.
28671
28670
  */
28672
28671
  const toPublicTokenType = (token) => {
28673
28672
  if (token.type === 'native') {
28674
28673
  return {
28675
- address: '',
28674
+ address: 'native',
28676
28675
  chainId: token.chainId,
28677
28676
  decimals: token.decimals,
28678
28677
  symbol: token.symbol,
@@ -28984,7 +28983,7 @@ const doesChainSupportEIP1559$1 = (fee) => {
28984
28983
  /**
28985
28984
  * Fetch the current gas price estimate. Supports both EIP-1559 and non-EIP1559 chains
28986
28985
  * @param {JsonRpcProvider} provider - The JSON RPC provider used to fetch fee data
28987
- * @param {Coin} nativeToken - The native token of the chain. Gas prices will be denominated in this token
28986
+ * @param {Native} nativeToken - The native token of the chain. Gas prices will be denominated in this token
28988
28987
  * @returns {Amount | null} - The gas price in the smallest denomination of the chain's currency,
28989
28988
  * or null if no gas price is available
28990
28989
  */
@@ -29109,9 +29108,6 @@ class NativeTokenService {
29109
29108
  this.wrappedToken = wrappedToken;
29110
29109
  }
29111
29110
  wrapAmount(amount) {
29112
- if (!canUnwrapToken(amount.token)) {
29113
- throw new Error(`cannot wrap non-native token: ${amount.token.address}`);
29114
- }
29115
29111
  return newAmount(amount.value, this.wrappedToken);
29116
29112
  }
29117
29113
  unwrapAmount(amount) {
@@ -29990,14 +29986,333 @@ const validateProviderDefaults = {
29990
29986
  allowUnsupportedProvider: false,
29991
29987
  };
29992
29988
 
29989
+ /**
29990
+ * An enum representing the checkout status types
29991
+ * @enum {string}
29992
+ * @property {string} SUCCESS - If checkout succeeded as the transactions were able to be processed
29993
+ * @property {string} FAILED - If checkout failed due to transactions not settling on chain
29994
+ * @property {string} INSUFFICIENT_FUNDS - If checkout failed due to insufficient funds
29995
+ */
29996
+ var CheckoutStatus;
29997
+ (function (CheckoutStatus) {
29998
+ CheckoutStatus["SUCCESS"] = "SUCCESS";
29999
+ CheckoutStatus["FAILED"] = "FAILED";
30000
+ CheckoutStatus["INSUFFICIENT_FUNDS"] = "INSUFFICIENT_FUNDS";
30001
+ })(CheckoutStatus || (CheckoutStatus = {}));
30002
+ /**
30003
+ * An enum representing the item types
30004
+ * @enum {string}
30005
+ * @property {string} NATIVE - If the item is a native token.
30006
+ * @property {string} ERC20 - If the item is an ERC20 token.
30007
+ * @property {string} ERC721 - If the item is an ERC721 token.
30008
+ */
30009
+ var ItemType;
30010
+ (function (ItemType) {
30011
+ ItemType["NATIVE"] = "NATIVE";
30012
+ ItemType["ERC20"] = "ERC20";
30013
+ ItemType["ERC721"] = "ERC721";
30014
+ })(ItemType || (ItemType = {}));
30015
+ /**
30016
+ * An enum representing transaction or gas types
30017
+ * @enum {string}
30018
+ * @property {string} TRANSACTION - If the type is a transaction
30019
+ * @property {string} GAS - If the type is the gas amount
30020
+ */
30021
+ var TransactionOrGasType;
30022
+ (function (TransactionOrGasType) {
30023
+ TransactionOrGasType["TRANSACTION"] = "TRANSACTION";
30024
+ TransactionOrGasType["GAS"] = "GAS";
30025
+ })(TransactionOrGasType || (TransactionOrGasType = {}));
30026
+ /**
30027
+ * An enum representing the gas token types
30028
+ * @enum {string}
30029
+ * @property {string} NATIVE - If the gas token is a native token.
30030
+ * @property {string} ERC20 - If the gas token is an ERC20 token.
30031
+ */
30032
+ var GasTokenType;
30033
+ (function (GasTokenType) {
30034
+ GasTokenType["NATIVE"] = "NATIVE";
30035
+ GasTokenType["ERC20"] = "ERC20";
30036
+ })(GasTokenType || (GasTokenType = {}));
30037
+ /**
30038
+ * An enum representing the routing outcome types
30039
+ * @enum {string}
30040
+ * @property {string} ROUTES_FOUND - If funding routes were found for the transaction.
30041
+ * @property {string} NO_ROUTES_FOUND - If no funding routes were found for the transaction.
30042
+ * @property {string} NO_ROUTE_OPTIONS - If no routing options were available for the transaction.
30043
+ */
30044
+ var RoutingOutcomeType;
30045
+ (function (RoutingOutcomeType) {
30046
+ RoutingOutcomeType["ROUTES_FOUND"] = "ROUTES_FOUND";
30047
+ RoutingOutcomeType["NO_ROUTES_FOUND"] = "NO_ROUTES_FOUND";
30048
+ RoutingOutcomeType["NO_ROUTE_OPTIONS"] = "NO_ROUTE_OPTIONS";
30049
+ })(RoutingOutcomeType || (RoutingOutcomeType = {}));
30050
+ /**
30051
+ * An enum representing the funding step types
30052
+ * @enum {string}
30053
+ * @property {string} BRIDGE - If the funding step is a bridge.
30054
+ * @property {string} SWAP - If the funding step is a swap.
30055
+ * @property {string} ONRAMP - If the funding step is an onramp.
30056
+ */
30057
+ var FundingStepType;
30058
+ (function (FundingStepType) {
30059
+ FundingStepType["BRIDGE"] = "BRIDGE";
30060
+ FundingStepType["SWAP"] = "SWAP";
30061
+ FundingStepType["ONRAMP"] = "ONRAMP";
30062
+ })(FundingStepType || (FundingStepType = {}));
30063
+
30064
+ // import { Passport } from '@imtbl/passport';
30065
+ /**
30066
+ * An enum representing the type of exchange.
30067
+ * @enum {string}
30068
+ * @property {string} ONRAMP - The exchange type for transacting.
30069
+ */
30070
+ var ExchangeType;
30071
+ (function (ExchangeType) {
30072
+ ExchangeType["ONRAMP"] = "onramp";
30073
+ })(ExchangeType || (ExchangeType = {}));
30074
+
30075
+ /**
30076
+ * Enum representing different types of errors that can occur during the checkout process.
30077
+ */
30078
+ var CheckoutErrorType;
30079
+ (function (CheckoutErrorType) {
30080
+ CheckoutErrorType["WEB3_PROVIDER_ERROR"] = "WEB3_PROVIDER_ERROR";
30081
+ CheckoutErrorType["PROVIDER_ERROR"] = "PROVIDER_ERROR";
30082
+ CheckoutErrorType["DEFAULT_PROVIDER_ERROR"] = "DEFAULT_PROVIDER_ERROR";
30083
+ CheckoutErrorType["CONNECT_PROVIDER_ERROR"] = "CONNECT_PROVIDER_ERROR";
30084
+ CheckoutErrorType["GET_BALANCE_ERROR"] = "GET_BALANCE_ERROR";
30085
+ CheckoutErrorType["GET_INDEXER_BALANCE_ERROR"] = "GET_INDEXER_BALANCE_ERROR";
30086
+ CheckoutErrorType["GET_ERC20_BALANCE_ERROR"] = "GET_ERC20_BALANCE_ERROR";
30087
+ CheckoutErrorType["GET_ERC721_BALANCE_ERROR"] = "GET_ERC721_BALANCE_ERROR";
30088
+ CheckoutErrorType["GET_NETWORK_INFO_ERROR"] = "GET_NETWORK_INFO_ERROR";
30089
+ CheckoutErrorType["METAMASK_PROVIDER_ERROR"] = "METAMASK_PROVIDER_ERROR";
30090
+ CheckoutErrorType["CHAIN_NOT_SUPPORTED_ERROR"] = "CHAIN_NOT_SUPPORTED_ERROR";
30091
+ CheckoutErrorType["PROVIDER_REQUEST_MISSING_ERROR"] = "PROVIDER_REQUEST_MISSING_ERROR";
30092
+ CheckoutErrorType["PROVIDER_REQUEST_FAILED_ERROR"] = "PROVIDER_REQUEST_FAILED_ERROR";
30093
+ CheckoutErrorType["USER_REJECTED_REQUEST_ERROR"] = "USER_REJECTED_REQUEST_ERROR";
30094
+ CheckoutErrorType["TRANSACTION_FAILED"] = "TRANSACTION_FAILED";
30095
+ CheckoutErrorType["INSUFFICIENT_FUNDS"] = "INSUFFICIENT_FUNDS";
30096
+ CheckoutErrorType["UNPREDICTABLE_GAS_LIMIT"] = "UNPREDICTABLE_GAS_LIMIT";
30097
+ CheckoutErrorType["INVALID_GAS_ESTIMATE_TYPE"] = "INVALID_GAS_ESTIMATE_TYPE";
30098
+ CheckoutErrorType["UNSUPPORTED_TOKEN_TYPE_ERROR"] = "UNSUPPORTED_TOKEN_TYPE_ERROR";
30099
+ CheckoutErrorType["UNSUPPORTED_BALANCE_REQUIREMENT_ERROR"] = "UNSUPPORTED_BALANCE_REQUIREMENT_ERROR";
30100
+ CheckoutErrorType["GET_ORDER_LISTING_ERROR"] = "GET_ORDER_LISTING_ERROR";
30101
+ CheckoutErrorType["CANCEL_ORDER_LISTING_ERROR"] = "CANCEL_ORDER_LISTING_ERROR";
30102
+ CheckoutErrorType["PREPARE_ORDER_LISTING_ERROR"] = "PREPARE_ORDER_LISTING_ERROR";
30103
+ CheckoutErrorType["CREATE_ORDER_LISTING_ERROR"] = "CREATE_ORDER_LISTING_ERROR";
30104
+ CheckoutErrorType["FULFILL_ORDER_LISTING_ERROR"] = "FULFILL_ORDER_LISTING_ERROR";
30105
+ CheckoutErrorType["SWITCH_NETWORK_UNSUPPORTED"] = "SWITCH_NETWORK_UNSUPPORTED";
30106
+ CheckoutErrorType["GET_ERC20_ALLOWANCE_ERROR"] = "GET_ERC20_ALLOWANCE_ERROR";
30107
+ CheckoutErrorType["GET_ERC721_ALLOWANCE_ERROR"] = "GET_ERC721_ALLOWANCE_ERROR";
30108
+ CheckoutErrorType["EXECUTE_APPROVAL_TRANSACTION_ERROR"] = "EXECUTE_APPROVAL_TRANSACTION_ERROR";
30109
+ CheckoutErrorType["EXECUTE_FULFILLMENT_TRANSACTION_ERROR"] = "EXECUTE_FULFILLMENT_TRANSACTION_ERROR";
30110
+ CheckoutErrorType["SIGN_MESSAGE_ERROR"] = "SIGN_MESSAGE_ERROR";
30111
+ CheckoutErrorType["BRIDGE_GAS_ESTIMATE_ERROR"] = "BRIDGE_GAS_ESTIMATE_ERROR";
30112
+ CheckoutErrorType["ORDER_FEE_ERROR"] = "ORDER_FEE_ERROR";
30113
+ CheckoutErrorType["ITEM_REQUIREMENTS_ERROR"] = "ITEM_REQUIREMENTS_ERROR";
30114
+ CheckoutErrorType["API_ERROR"] = "API_ERROR";
30115
+ CheckoutErrorType["ORDER_EXPIRED_ERROR"] = "ORDER_EXPIRED_ERROR";
30116
+ CheckoutErrorType["WIDGETS_SCRIPT_LOAD_ERROR"] = "WIDGETS_SCRIPT_LOAD_ERROR";
30117
+ })(CheckoutErrorType || (CheckoutErrorType = {}));
30118
+ /* The CheckoutError class is a custom error class in TypeScript that includes a message, type, and
30119
+ optional data object. */
30120
+ class CheckoutError extends Error {
30121
+ message;
30122
+ type;
30123
+ data;
30124
+ constructor(message, type, data) {
30125
+ super(message);
30126
+ this.message = message;
30127
+ this.type = type;
30128
+ this.data = data;
30129
+ }
30130
+ }
30131
+ var CheckoutInternalErrorType;
30132
+ (function (CheckoutInternalErrorType) {
30133
+ CheckoutInternalErrorType["REJECTED_SWITCH_AFTER_ADDING_NETWORK"] = "REJECTED_SWITCH_AFTER_ADDING_NETWORK";
30134
+ })(CheckoutInternalErrorType || (CheckoutInternalErrorType = {}));
30135
+ const withCheckoutError = async (
30136
+ /**
30137
+ * Wraps a function that returns a Promise and catches any errors that occur. If an error is caught,
30138
+ * it is wrapped in a CheckoutError and rethrown.
30139
+ */
30140
+ fn, customError) => {
30141
+ try {
30142
+ return await fn();
30143
+ }
30144
+ catch (error) {
30145
+ const cause = `${error.message}` || 'UnknownError';
30146
+ const errorMessage = customError.message
30147
+ ? `[${customError.type}]:${customError.message}. Cause:${cause}`
30148
+ : `[${customError.type}] Cause:${cause}`;
30149
+ if (error instanceof CheckoutError) {
30150
+ throw new CheckoutError(errorMessage, customError.type, {
30151
+ ...customError.data,
30152
+ innerErrorType: error.type,
30153
+ ...error.data,
30154
+ });
30155
+ }
30156
+ throw new CheckoutError(errorMessage, customError.type, {
30157
+ ...customError.data,
30158
+ });
30159
+ }
30160
+ };
30161
+
30162
+ // this function needs to be in a separate file to prevent circular dependencies with ./network
30163
+ // this gives us access to the properties of the underlying provider object
30164
+ async function getUnderlyingChainId(web3Provider) {
30165
+ if (!web3Provider.provider?.request) {
30166
+ throw new CheckoutError('Parsed provider is not a valid Web3Provider', CheckoutErrorType.WEB3_PROVIDER_ERROR);
30167
+ }
30168
+ const chainId = await web3Provider.provider.request({
30169
+ method: WalletAction.GET_CHAINID,
30170
+ params: [],
30171
+ });
30172
+ return parseInt(chainId, 16);
30173
+ }
30174
+
30175
+ /* eslint-disable @typescript-eslint/no-explicit-any */
30176
+ const UNRECOGNISED_CHAIN_ERROR_CODE = 4902; // error code (MetaMask)
30177
+ // these functions should not be exported. These functions should be used as part of an exported function e.g switchWalletNetwork() above.
30178
+ // make sure to check if(provider.provider?.request) in the exported function and throw an error
30179
+ // eslint-disable-next-line consistent-return
30180
+ async function switchNetworkInWallet(networkMap, web3Provider, chainId) {
30181
+ if (web3Provider.provider?.request) {
30182
+ return await web3Provider.provider.request({
30183
+ method: WalletAction.SWITCH_NETWORK,
30184
+ params: [
30185
+ {
30186
+ chainId: networkMap.get(chainId)?.chainIdHex,
30187
+ },
30188
+ ],
30189
+ });
30190
+ }
30191
+ }
30192
+ // TODO: Should these functions always return something?
30193
+ // eslint-disable-next-line consistent-return
30194
+ async function addNetworkToWallet(networkMap, web3Provider, chainId) {
30195
+ if (web3Provider.provider?.request) {
30196
+ const networkDetails = networkMap.get(chainId);
30197
+ const addNetwork = {
30198
+ chainId: networkDetails?.chainIdHex,
30199
+ chainName: networkDetails?.chainName,
30200
+ rpcUrls: networkDetails?.rpcUrls,
30201
+ nativeCurrency: networkDetails?.nativeCurrency,
30202
+ blockExplorerUrls: networkDetails?.blockExplorerUrls,
30203
+ };
30204
+ return await web3Provider.provider.request({
30205
+ method: WalletAction.ADD_NETWORK,
30206
+ params: [addNetwork],
30207
+ });
30208
+ }
30209
+ }
30210
+ async function getNetworkAllowList(config, { type = NetworkFilterTypes.ALL, exclude }) {
30211
+ const { networkMap } = config;
30212
+ const allowedNetworkConfig = (await config.remote.getConfig('allowedNetworks'));
30213
+ const list = allowedNetworkConfig.filter((network) => {
30214
+ const allowAllTokens = type === NetworkFilterTypes.ALL;
30215
+ const networkNotExcluded = !(exclude || [])
30216
+ .map((exc) => exc.chainId)
30217
+ .includes(network.chainId);
30218
+ return allowAllTokens && networkNotExcluded;
30219
+ });
30220
+ const allowedNetworks = [];
30221
+ list.forEach((element) => {
30222
+ const newNetwork = networkMap.get(element.chainId);
30223
+ if (newNetwork) {
30224
+ allowedNetworks.push({
30225
+ name: newNetwork.chainName,
30226
+ chainId: parseInt(newNetwork.chainIdHex, 16),
30227
+ nativeCurrency: newNetwork.nativeCurrency,
30228
+ isSupported: true,
30229
+ });
30230
+ }
30231
+ });
30232
+ return {
30233
+ networks: allowedNetworks,
30234
+ };
30235
+ }
30236
+ async function getNetworkInfo(config, web3Provider) {
30237
+ const { networkMap } = config;
30238
+ return withCheckoutError(async () => {
30239
+ try {
30240
+ const network = await web3Provider.getNetwork();
30241
+ if (Array.from(networkMap.keys()).includes(network.chainId)) {
30242
+ const chainIdNetworkInfo = networkMap.get(network.chainId);
30243
+ return {
30244
+ name: chainIdNetworkInfo.chainName,
30245
+ chainId: parseInt(chainIdNetworkInfo.chainIdHex, 16),
30246
+ nativeCurrency: chainIdNetworkInfo.nativeCurrency,
30247
+ isSupported: true,
30248
+ };
30249
+ }
30250
+ return {
30251
+ chainId: network.chainId,
30252
+ name: network.name,
30253
+ isSupported: false,
30254
+ };
30255
+ }
30256
+ catch (err) {
30257
+ const chainId = await getUnderlyingChainId(web3Provider);
30258
+ const isSupported = Array.from(networkMap.keys()).includes(chainId);
30259
+ return {
30260
+ chainId,
30261
+ isSupported,
30262
+ };
30263
+ }
30264
+ }, {
30265
+ type: CheckoutErrorType.GET_NETWORK_INFO_ERROR,
30266
+ });
30267
+ }
30268
+ async function switchWalletNetwork(config, web3Provider, chainId) {
30269
+ const { networkMap } = config;
30270
+ const allowedNetworks = await getNetworkAllowList(config, {
30271
+ type: NetworkFilterTypes.ALL,
30272
+ });
30273
+ if (!allowedNetworks.networks.some((network) => network.chainId === chainId)) {
30274
+ throw new CheckoutError(`Chain:${chainId} is not a supported chain`, CheckoutErrorType.CHAIN_NOT_SUPPORTED_ERROR);
30275
+ }
30276
+ if (web3Provider.provider?.isPassport) {
30277
+ throw new CheckoutError('Switching networks with Passport provider is not supported', CheckoutErrorType.SWITCH_NETWORK_UNSUPPORTED);
30278
+ }
30279
+ // WT-1146 - Refer to the README in this folder for explanation on the switch network flow
30280
+ try {
30281
+ await switchNetworkInWallet(networkMap, web3Provider, chainId);
30282
+ }
30283
+ catch (err) {
30284
+ if (err.code === UNRECOGNISED_CHAIN_ERROR_CODE) {
30285
+ try {
30286
+ await addNetworkToWallet(networkMap, web3Provider, chainId);
30287
+ // eslint-disable-next-line @typescript-eslint/no-shadow
30288
+ }
30289
+ catch (err) {
30290
+ throw new CheckoutError('User cancelled add network request', CheckoutErrorType.USER_REJECTED_REQUEST_ERROR);
30291
+ }
30292
+ }
30293
+ else {
30294
+ throw new CheckoutError('User cancelled switch network request', CheckoutErrorType.USER_REJECTED_REQUEST_ERROR);
30295
+ }
30296
+ }
30297
+ const newProvider = new Web3Provider(web3Provider.provider);
30298
+ const newProviderNetwork = await newProvider.getNetwork();
30299
+ if (newProviderNetwork.chainId !== chainId) {
30300
+ throw new CheckoutError('User cancelled switch network request', CheckoutErrorType.USER_REJECTED_REQUEST_ERROR);
30301
+ }
30302
+ const networkInfo = await getNetworkInfo(config, newProvider);
30303
+ return {
30304
+ network: networkInfo,
30305
+ provider: newProvider,
30306
+ };
30307
+ }
30308
+
29993
30309
  const ENV_DEVELOPMENT = 'development';
29994
- const IMX_ADDRESS_ZKEVM = '0x0000000000000000000000000000000000001010';
29995
30310
  const DEFAULT_TOKEN_DECIMALS$1 = 18;
30311
+ const NATIVE = 'native';
29996
30312
  const ZKEVM_NATIVE_TOKEN = {
29997
30313
  name: 'IMX',
29998
30314
  symbol: 'IMX',
29999
30315
  decimals: DEFAULT_TOKEN_DECIMALS$1,
30000
- address: IMX_ADDRESS_ZKEVM,
30001
30316
  };
30002
30317
  /**
30003
30318
  * Base URL for the Immutable API based on the environment.
@@ -30328,332 +30643,23 @@ const ERC721ABI = [
30328
30643
  type: 'function',
30329
30644
  },
30330
30645
  ];
30331
-
30332
- /**
30333
- * An enum representing the checkout status types
30334
- * @enum {string}
30335
- * @property {string} SUCCESS - If checkout succeeded as the transactions were able to be processed
30336
- * @property {string} FAILED - If checkout failed due to transactions not settling on chain
30337
- * @property {string} INSUFFICIENT_FUNDS - If checkout failed due to insufficient funds
30338
- */
30339
- var CheckoutStatus;
30340
- (function (CheckoutStatus) {
30341
- CheckoutStatus["SUCCESS"] = "SUCCESS";
30342
- CheckoutStatus["FAILED"] = "FAILED";
30343
- CheckoutStatus["INSUFFICIENT_FUNDS"] = "INSUFFICIENT_FUNDS";
30344
- })(CheckoutStatus || (CheckoutStatus = {}));
30345
- /**
30346
- * An enum representing the item types
30347
- * @enum {string}
30348
- * @property {string} NATIVE - If the item is a native token.
30349
- * @property {string} ERC20 - If the item is an ERC20 token.
30350
- * @property {string} ERC721 - If the item is an ERC721 token.
30351
- */
30352
- var ItemType;
30353
- (function (ItemType) {
30354
- ItemType["NATIVE"] = "NATIVE";
30355
- ItemType["ERC20"] = "ERC20";
30356
- ItemType["ERC721"] = "ERC721";
30357
- })(ItemType || (ItemType = {}));
30358
- /**
30359
- * An enum representing transaction or gas types
30360
- * @enum {string}
30361
- * @property {string} TRANSACTION - If the type is a transaction
30362
- * @property {string} GAS - If the type is the gas amount
30363
- */
30364
- var TransactionOrGasType;
30365
- (function (TransactionOrGasType) {
30366
- TransactionOrGasType["TRANSACTION"] = "TRANSACTION";
30367
- TransactionOrGasType["GAS"] = "GAS";
30368
- })(TransactionOrGasType || (TransactionOrGasType = {}));
30369
- /**
30370
- * An enum representing the gas token types
30371
- * @enum {string}
30372
- * @property {string} NATIVE - If the gas token is a native token.
30373
- * @property {string} ERC20 - If the gas token is an ERC20 token.
30374
- */
30375
- var GasTokenType;
30376
- (function (GasTokenType) {
30377
- GasTokenType["NATIVE"] = "NATIVE";
30378
- GasTokenType["ERC20"] = "ERC20";
30379
- })(GasTokenType || (GasTokenType = {}));
30380
- /**
30381
- * An enum representing the routing outcome types
30382
- * @enum {string}
30383
- * @property {string} ROUTES_FOUND - If funding routes were found for the transaction.
30384
- * @property {string} NO_ROUTES_FOUND - If no funding routes were found for the transaction.
30385
- * @property {string} NO_ROUTE_OPTIONS - If no routing options were available for the transaction.
30386
- */
30387
- var RoutingOutcomeType;
30388
- (function (RoutingOutcomeType) {
30389
- RoutingOutcomeType["ROUTES_FOUND"] = "ROUTES_FOUND";
30390
- RoutingOutcomeType["NO_ROUTES_FOUND"] = "NO_ROUTES_FOUND";
30391
- RoutingOutcomeType["NO_ROUTE_OPTIONS"] = "NO_ROUTE_OPTIONS";
30392
- })(RoutingOutcomeType || (RoutingOutcomeType = {}));
30393
- /**
30394
- * An enum representing the funding step types
30395
- * @enum {string}
30396
- * @property {string} BRIDGE - If the funding step is a bridge.
30397
- * @property {string} SWAP - If the funding step is a swap.
30398
- * @property {string} ONRAMP - If the funding step is an onramp.
30399
- */
30400
- var FundingStepType;
30401
- (function (FundingStepType) {
30402
- FundingStepType["BRIDGE"] = "BRIDGE";
30403
- FundingStepType["SWAP"] = "SWAP";
30404
- FundingStepType["ONRAMP"] = "ONRAMP";
30405
- })(FundingStepType || (FundingStepType = {}));
30406
-
30407
- // import { Passport } from '@imtbl/passport';
30408
- /**
30409
- * An enum representing the type of exchange.
30410
- * @enum {string}
30411
- * @property {string} ONRAMP - The exchange type for transacting.
30412
- */
30413
- var ExchangeType;
30414
- (function (ExchangeType) {
30415
- ExchangeType["ONRAMP"] = "onramp";
30416
- })(ExchangeType || (ExchangeType = {}));
30417
-
30418
- /**
30419
- * Enum representing different types of errors that can occur during the checkout process.
30420
- */
30421
- var CheckoutErrorType;
30422
- (function (CheckoutErrorType) {
30423
- CheckoutErrorType["WEB3_PROVIDER_ERROR"] = "WEB3_PROVIDER_ERROR";
30424
- CheckoutErrorType["PROVIDER_ERROR"] = "PROVIDER_ERROR";
30425
- CheckoutErrorType["DEFAULT_PROVIDER_ERROR"] = "DEFAULT_PROVIDER_ERROR";
30426
- CheckoutErrorType["CONNECT_PROVIDER_ERROR"] = "CONNECT_PROVIDER_ERROR";
30427
- CheckoutErrorType["GET_BALANCE_ERROR"] = "GET_BALANCE_ERROR";
30428
- CheckoutErrorType["GET_INDEXER_BALANCE_ERROR"] = "GET_INDEXER_BALANCE_ERROR";
30429
- CheckoutErrorType["GET_ERC20_BALANCE_ERROR"] = "GET_ERC20_BALANCE_ERROR";
30430
- CheckoutErrorType["GET_ERC721_BALANCE_ERROR"] = "GET_ERC721_BALANCE_ERROR";
30431
- CheckoutErrorType["GET_NETWORK_INFO_ERROR"] = "GET_NETWORK_INFO_ERROR";
30432
- CheckoutErrorType["METAMASK_PROVIDER_ERROR"] = "METAMASK_PROVIDER_ERROR";
30433
- CheckoutErrorType["CHAIN_NOT_SUPPORTED_ERROR"] = "CHAIN_NOT_SUPPORTED_ERROR";
30434
- CheckoutErrorType["PROVIDER_REQUEST_MISSING_ERROR"] = "PROVIDER_REQUEST_MISSING_ERROR";
30435
- CheckoutErrorType["PROVIDER_REQUEST_FAILED_ERROR"] = "PROVIDER_REQUEST_FAILED_ERROR";
30436
- CheckoutErrorType["USER_REJECTED_REQUEST_ERROR"] = "USER_REJECTED_REQUEST_ERROR";
30437
- CheckoutErrorType["TRANSACTION_FAILED"] = "TRANSACTION_FAILED";
30438
- CheckoutErrorType["INSUFFICIENT_FUNDS"] = "INSUFFICIENT_FUNDS";
30439
- CheckoutErrorType["UNPREDICTABLE_GAS_LIMIT"] = "UNPREDICTABLE_GAS_LIMIT";
30440
- CheckoutErrorType["INVALID_GAS_ESTIMATE_TYPE"] = "INVALID_GAS_ESTIMATE_TYPE";
30441
- CheckoutErrorType["UNSUPPORTED_TOKEN_TYPE_ERROR"] = "UNSUPPORTED_TOKEN_TYPE_ERROR";
30442
- CheckoutErrorType["UNSUPPORTED_BALANCE_REQUIREMENT_ERROR"] = "UNSUPPORTED_BALANCE_REQUIREMENT_ERROR";
30443
- CheckoutErrorType["GET_ORDER_LISTING_ERROR"] = "GET_ORDER_LISTING_ERROR";
30444
- CheckoutErrorType["CANCEL_ORDER_LISTING_ERROR"] = "CANCEL_ORDER_LISTING_ERROR";
30445
- CheckoutErrorType["PREPARE_ORDER_LISTING_ERROR"] = "PREPARE_ORDER_LISTING_ERROR";
30446
- CheckoutErrorType["CREATE_ORDER_LISTING_ERROR"] = "CREATE_ORDER_LISTING_ERROR";
30447
- CheckoutErrorType["FULFILL_ORDER_LISTING_ERROR"] = "FULFILL_ORDER_LISTING_ERROR";
30448
- CheckoutErrorType["SWITCH_NETWORK_UNSUPPORTED"] = "SWITCH_NETWORK_UNSUPPORTED";
30449
- CheckoutErrorType["GET_ERC20_ALLOWANCE_ERROR"] = "GET_ERC20_ALLOWANCE_ERROR";
30450
- CheckoutErrorType["GET_ERC721_ALLOWANCE_ERROR"] = "GET_ERC721_ALLOWANCE_ERROR";
30451
- CheckoutErrorType["EXECUTE_APPROVAL_TRANSACTION_ERROR"] = "EXECUTE_APPROVAL_TRANSACTION_ERROR";
30452
- CheckoutErrorType["EXECUTE_FULFILLMENT_TRANSACTION_ERROR"] = "EXECUTE_FULFILLMENT_TRANSACTION_ERROR";
30453
- CheckoutErrorType["SIGN_MESSAGE_ERROR"] = "SIGN_MESSAGE_ERROR";
30454
- CheckoutErrorType["BRIDGE_GAS_ESTIMATE_ERROR"] = "BRIDGE_GAS_ESTIMATE_ERROR";
30455
- CheckoutErrorType["ORDER_FEE_ERROR"] = "ORDER_FEE_ERROR";
30456
- CheckoutErrorType["ITEM_REQUIREMENTS_ERROR"] = "ITEM_REQUIREMENTS_ERROR";
30457
- CheckoutErrorType["API_ERROR"] = "API_ERROR";
30458
- CheckoutErrorType["ORDER_EXPIRED_ERROR"] = "ORDER_EXPIRED_ERROR";
30459
- CheckoutErrorType["WIDGETS_SCRIPT_LOAD_ERROR"] = "WIDGETS_SCRIPT_LOAD_ERROR";
30460
- })(CheckoutErrorType || (CheckoutErrorType = {}));
30461
- /* The CheckoutError class is a custom error class in TypeScript that includes a message, type, and
30462
- optional data object. */
30463
- class CheckoutError extends Error {
30464
- message;
30465
- type;
30466
- data;
30467
- constructor(message, type, data) {
30468
- super(message);
30469
- this.message = message;
30470
- this.type = type;
30471
- this.data = data;
30472
- }
30473
- }
30474
- var CheckoutInternalErrorType;
30475
- (function (CheckoutInternalErrorType) {
30476
- CheckoutInternalErrorType["REJECTED_SWITCH_AFTER_ADDING_NETWORK"] = "REJECTED_SWITCH_AFTER_ADDING_NETWORK";
30477
- })(CheckoutInternalErrorType || (CheckoutInternalErrorType = {}));
30478
- const withCheckoutError = async (
30479
- /**
30480
- * Wraps a function that returns a Promise and catches any errors that occur. If an error is caught,
30481
- * it is wrapped in a CheckoutError and rethrown.
30482
- */
30483
- fn, customError) => {
30484
- try {
30485
- return await fn();
30486
- }
30487
- catch (error) {
30488
- const cause = `${error.message}` || 'UnknownError';
30489
- const errorMessage = customError.message
30490
- ? `[${customError.type}]:${customError.message}. Cause:${cause}`
30491
- : `[${customError.type}] Cause:${cause}`;
30492
- if (error instanceof CheckoutError) {
30493
- throw new CheckoutError(errorMessage, customError.type, {
30494
- ...customError.data,
30495
- innerErrorType: error.type,
30496
- ...error.data,
30497
- });
30498
- }
30499
- throw new CheckoutError(errorMessage, customError.type, {
30500
- ...customError.data,
30501
- });
30502
- }
30646
+ // Gas overrides -- Anti-spam mechanism for when the baseFee drops low
30647
+ // https://github.com/immutable/imx-docs/blob/main/docs/main/zkEVM/overview/gas-configuration.md
30648
+ const GAS_OVERRIDES = {
30649
+ maxFeePerGas: BigNumber$1.from(102e9),
30650
+ maxPriorityFeePerGas: BigNumber$1.from(101e9),
30503
30651
  };
30504
30652
 
30505
- // this function needs to be in a separate file to prevent circular dependencies with ./network
30506
- // this gives us access to the properties of the underlying provider object
30507
- async function getUnderlyingChainId(web3Provider) {
30508
- if (!web3Provider.provider?.request) {
30509
- throw new CheckoutError('Parsed provider is not a valid Web3Provider', CheckoutErrorType.WEB3_PROVIDER_ERROR);
30510
- }
30511
- const chainId = await web3Provider.provider.request({
30512
- method: WalletAction.GET_CHAINID,
30513
- params: [],
30514
- });
30515
- return parseInt(chainId, 16);
30516
- }
30517
-
30518
- /* eslint-disable @typescript-eslint/no-explicit-any */
30519
- const UNRECOGNISED_CHAIN_ERROR_CODE = 4902; // error code (MetaMask)
30520
- // these functions should not be exported. These functions should be used as part of an exported function e.g switchWalletNetwork() above.
30521
- // make sure to check if(provider.provider?.request) in the exported function and throw an error
30522
- // eslint-disable-next-line consistent-return
30523
- async function switchNetworkInWallet(networkMap, web3Provider, chainId) {
30524
- if (web3Provider.provider?.request) {
30525
- return await web3Provider.provider.request({
30526
- method: WalletAction.SWITCH_NETWORK,
30527
- params: [
30528
- {
30529
- chainId: networkMap.get(chainId)?.chainIdHex,
30530
- },
30531
- ],
30532
- });
30533
- }
30534
- }
30535
- // TODO: Should these functions always return something?
30536
- // eslint-disable-next-line consistent-return
30537
- async function addNetworkToWallet(networkMap, web3Provider, chainId) {
30538
- if (web3Provider.provider?.request) {
30539
- const networkDetails = networkMap.get(chainId);
30540
- const addNetwork = {
30541
- chainId: networkDetails?.chainIdHex,
30542
- chainName: networkDetails?.chainName,
30543
- rpcUrls: networkDetails?.rpcUrls,
30544
- nativeCurrency: networkDetails?.nativeCurrency,
30545
- blockExplorerUrls: networkDetails?.blockExplorerUrls,
30546
- };
30547
- return await web3Provider.provider.request({
30548
- method: WalletAction.ADD_NETWORK,
30549
- params: [addNetwork],
30550
- });
30551
- }
30552
- }
30553
- async function getNetworkAllowList(config, { type = NetworkFilterTypes.ALL, exclude }) {
30554
- const { networkMap } = config;
30555
- const allowedNetworkConfig = (await config.remote.getConfig('allowedNetworks'));
30556
- const list = allowedNetworkConfig.filter((network) => {
30557
- const allowAllTokens = type === NetworkFilterTypes.ALL;
30558
- const networkNotExcluded = !(exclude || [])
30559
- .map((exc) => exc.chainId)
30560
- .includes(network.chainId);
30561
- return allowAllTokens && networkNotExcluded;
30562
- });
30563
- const allowedNetworks = [];
30564
- list.forEach((element) => {
30565
- const newNetwork = networkMap.get(element.chainId);
30566
- if (newNetwork) {
30567
- allowedNetworks.push({
30568
- name: newNetwork.chainName,
30569
- chainId: parseInt(newNetwork.chainIdHex, 16),
30570
- nativeCurrency: newNetwork.nativeCurrency,
30571
- isSupported: true,
30572
- });
30573
- }
30574
- });
30575
- return {
30576
- networks: allowedNetworks,
30577
- };
30578
- }
30579
- async function getNetworkInfo(config, web3Provider) {
30580
- const { networkMap } = config;
30581
- return withCheckoutError(async () => {
30582
- try {
30583
- const network = await web3Provider.getNetwork();
30584
- if (Array.from(networkMap.keys()).includes(network.chainId)) {
30585
- const chainIdNetworkInfo = networkMap.get(network.chainId);
30586
- return {
30587
- name: chainIdNetworkInfo.chainName,
30588
- chainId: parseInt(chainIdNetworkInfo.chainIdHex, 16),
30589
- nativeCurrency: chainIdNetworkInfo.nativeCurrency,
30590
- isSupported: true,
30591
- };
30592
- }
30593
- return {
30594
- chainId: network.chainId,
30595
- name: network.name,
30596
- isSupported: false,
30597
- };
30598
- }
30599
- catch (err) {
30600
- const chainId = await getUnderlyingChainId(web3Provider);
30601
- const isSupported = Array.from(networkMap.keys()).includes(chainId);
30602
- return {
30603
- chainId,
30604
- isSupported,
30605
- };
30606
- }
30607
- }, {
30608
- type: CheckoutErrorType.GET_NETWORK_INFO_ERROR,
30609
- });
30610
- }
30611
- async function switchWalletNetwork(config, web3Provider, chainId) {
30612
- const { networkMap } = config;
30613
- const allowedNetworks = await getNetworkAllowList(config, {
30614
- type: NetworkFilterTypes.ALL,
30615
- });
30616
- if (!allowedNetworks.networks.some((network) => network.chainId === chainId)) {
30617
- throw new CheckoutError(`Chain:${chainId} is not a supported chain`, CheckoutErrorType.CHAIN_NOT_SUPPORTED_ERROR);
30618
- }
30619
- if (web3Provider.provider?.isPassport) {
30620
- throw new CheckoutError('Switching networks with Passport provider is not supported', CheckoutErrorType.SWITCH_NETWORK_UNSUPPORTED);
30621
- }
30622
- // WT-1146 - Refer to the README in this folder for explanation on the switch network flow
30623
- try {
30624
- await switchNetworkInWallet(networkMap, web3Provider, chainId);
30625
- }
30626
- catch (err) {
30627
- if (err.code === UNRECOGNISED_CHAIN_ERROR_CODE) {
30628
- try {
30629
- await addNetworkToWallet(networkMap, web3Provider, chainId);
30630
- // eslint-disable-next-line @typescript-eslint/no-shadow
30631
- }
30632
- catch (err) {
30633
- throw new CheckoutError('User cancelled add network request', CheckoutErrorType.USER_REJECTED_REQUEST_ERROR);
30634
- }
30635
- }
30636
- else {
30637
- throw new CheckoutError('User cancelled switch network request', CheckoutErrorType.USER_REJECTED_REQUEST_ERROR);
30638
- }
30639
- }
30640
- const newProvider = new Web3Provider(web3Provider.provider);
30641
- const newProviderNetwork = await newProvider.getNetwork();
30642
- if (newProviderNetwork.chainId !== chainId) {
30643
- throw new CheckoutError('User cancelled switch network request', CheckoutErrorType.USER_REJECTED_REQUEST_ERROR);
30644
- }
30645
- const networkInfo = await getNetworkInfo(config, newProvider);
30646
- return {
30647
- network: networkInfo,
30648
- provider: newProvider,
30649
- };
30650
- }
30653
+ const SDK_VERSION_MARKER = '0.33.0';
30654
+ // This SDK version is replaced by the `yarn build` command ran on the root level
30655
+ const globalPackageVersion = () => SDK_VERSION_MARKER;
30651
30656
 
30652
30657
  class RemoteConfigFetcher {
30653
30658
  isDevelopment;
30654
30659
  isProduction;
30655
30660
  configCache;
30656
30661
  tokensCache;
30662
+ version = 'v1';
30657
30663
  constructor(params) {
30658
30664
  this.isDevelopment = params.isDevelopment;
30659
30665
  this.isProduction = params.isProduction;
@@ -30681,14 +30687,14 @@ class RemoteConfigFetcher {
30681
30687
  async loadConfig() {
30682
30688
  if (this.configCache)
30683
30689
  return this.configCache;
30684
- const response = await RemoteConfigFetcher.makeHttpRequest(`${this.getEndpoint()}/v1/config`);
30690
+ const response = await RemoteConfigFetcher.makeHttpRequest(`${this.getEndpoint()}/${this.version}/config`);
30685
30691
  this.configCache = response.data;
30686
30692
  return this.configCache;
30687
30693
  }
30688
30694
  async loadConfigTokens() {
30689
30695
  if (this.tokensCache)
30690
30696
  return this.tokensCache;
30691
- const response = await RemoteConfigFetcher.makeHttpRequest(`${this.getEndpoint()}/v1/config/tokens`);
30697
+ const response = await RemoteConfigFetcher.makeHttpRequest(`${this.getEndpoint()}/${this.version}/config/tokens`);
30692
30698
  this.tokensCache = response.data;
30693
30699
  return this.tokensCache;
30694
30700
  }
@@ -30804,6 +30810,7 @@ const getTokenAllowList = async (config, { type = TokenFilterTypes.ALL, chainId,
30804
30810
  tokens: tokens.filter((token) => !exclude.map((e) => e.address).includes(token.address || '')),
30805
30811
  };
30806
30812
  };
30813
+ const isNativeToken = (address) => !address || address.toLocaleLowerCase() === NATIVE;
30807
30814
 
30808
30815
  const CACHE_DATA_TTL = 60; // seconds
30809
30816
  /**
@@ -31003,7 +31010,7 @@ const getIndexerBalance = async (walletAddress, chainId, filterTokens) => {
31003
31010
  // Shuffle the mapping of the tokens configuration so it is a hashmap
31004
31011
  // for faster access to tokens config objects.
31005
31012
  const shouldFilter = filterTokens.length > 0;
31006
- const mapFilterTokens = Object.assign({}, ...(filterTokens.map((t) => ({ [t.address || '']: t }))));
31013
+ const mapFilterTokens = Object.assign({}, ...(filterTokens.map((t) => ({ [t.address || NATIVE]: t }))));
31007
31014
  // Get blockscout client for the given chain
31008
31015
  let blockscoutClient = blockscoutClientMap.get(chainId);
31009
31016
  if (!blockscoutClient) {
@@ -31044,6 +31051,7 @@ const getIndexerBalance = async (walletAddress, chainId, filterTokens) => {
31044
31051
  const nativeBalances = async (client) => {
31045
31052
  try {
31046
31053
  const respNative = await client.getNativeTokenByWalletAddress({ walletAddress });
31054
+ respNative.token.address ||= NATIVE;
31047
31055
  items.push(respNative);
31048
31056
  }
31049
31057
  catch (err) {
@@ -31086,8 +31094,7 @@ const getBalances = async (config, web3Provider, walletAddress, tokens) => {
31086
31094
  const allBalancePromises = [];
31087
31095
  tokens
31088
31096
  .forEach((token) => {
31089
- // Check for NATIVE token
31090
- if (!token.address || token.address === IMX_ADDRESS_ZKEVM) {
31097
+ if (!token.address || token.address.toLocaleLowerCase() === NATIVE) {
31091
31098
  allBalancePromises.push(getBalance(config, web3Provider, walletAddress));
31092
31099
  }
31093
31100
  else {
@@ -31273,11 +31280,17 @@ async function getWalletAllowList(params) {
31273
31280
  };
31274
31281
  }
31275
31282
 
31283
+ const setTransactionGasLimits = (transaction) => {
31284
+ const rawTx = transaction;
31285
+ rawTx.maxFeePerGas = GAS_OVERRIDES.maxFeePerGas;
31286
+ rawTx.maxPriorityFeePerGas = GAS_OVERRIDES.maxPriorityFeePerGas;
31287
+ return rawTx;
31288
+ };
31276
31289
  const sendTransaction = async (web3Provider, transaction) => {
31277
31290
  try {
31278
- const transactionResponse = await web3Provider
31279
- .getSigner()
31280
- .sendTransaction(transaction);
31291
+ const signer = web3Provider.getSigner();
31292
+ const rawTx = setTransactionGasLimits(transaction);
31293
+ const transactionResponse = await signer.sendTransaction(rawTx);
31281
31294
  return {
31282
31295
  transactionResponse,
31283
31296
  };
@@ -31440,25 +31453,21 @@ async function swapGasEstimator(config) {
31440
31453
  const exchange = await createExchangeInstance(chainId, config);
31441
31454
  // Create a fake transaction to get the gas from the quote
31442
31455
  const { swap } = await exchange.getUnsignedSwapTxFromAmountIn(DUMMY_WALLET_ADDRESS, inAddress, outAddress, BigNumber$1.from(utils$1.parseUnits('1', DEFAULT_TOKEN_DECIMALS)));
31443
- if (swap.gasFeeEstimate === null) {
31456
+ if (!swap.gasFeeEstimate) {
31444
31457
  return {
31445
31458
  gasEstimateType: GasEstimateType.SWAP,
31446
31459
  gasFee: {},
31447
31460
  };
31448
31461
  }
31449
- let estimatedAmount;
31450
- if (swap.gasFeeEstimate.value) {
31451
- estimatedAmount = BigNumber$1.from(swap.gasFeeEstimate.value);
31452
- }
31453
31462
  return {
31454
31463
  gasEstimateType: GasEstimateType.SWAP,
31455
31464
  gasFee: {
31456
- estimatedAmount,
31465
+ estimatedAmount: swap.gasFeeEstimate.value ? BigNumber$1.from(swap.gasFeeEstimate.value) : undefined,
31457
31466
  token: {
31458
- address: swap.gasFeeEstimate?.token.address,
31459
- symbol: swap.gasFeeEstimate?.token.symbol ?? '',
31460
- name: swap.gasFeeEstimate?.token.name ?? '',
31461
- decimals: swap.gasFeeEstimate?.token.decimals ?? DEFAULT_TOKEN_DECIMALS,
31467
+ address: swap.gasFeeEstimate.token.address,
31468
+ symbol: swap.gasFeeEstimate.token.symbol ?? '',
31469
+ name: swap.gasFeeEstimate.token.name ?? '',
31470
+ decimals: swap.gasFeeEstimate.token.decimals ?? DEFAULT_TOKEN_DECIMALS,
31462
31471
  },
31463
31472
  },
31464
31473
  };
@@ -31849,7 +31858,7 @@ const getTokensFromRequirements = (itemRequirements) => itemRequirements
31849
31858
  .map((itemRequirement) => {
31850
31859
  if (itemRequirement.type === ItemType.NATIVE) {
31851
31860
  return {
31852
- address: IMX_ADDRESS_ZKEVM,
31861
+ address: NATIVE,
31853
31862
  };
31854
31863
  }
31855
31864
  return {
@@ -31909,8 +31918,7 @@ const getTokenBalanceRequirement = (itemRequirement, balances) => {
31909
31918
  }
31910
31919
  else if (itemRequirement.type === ItemType.NATIVE) {
31911
31920
  itemBalanceResult = balances.find((balance) => {
31912
- return balance.token?.address === ''
31913
- || balance.token?.address === IMX_ADDRESS_ZKEVM;
31921
+ return isNativeToken(balance.token?.address);
31914
31922
  });
31915
31923
  }
31916
31924
  // Calculate the balance delta
@@ -31938,7 +31946,6 @@ const getTokenBalanceRequirement = (itemRequirement, balances) => {
31938
31946
  name,
31939
31947
  symbol,
31940
31948
  decimals: DEFAULT_TOKEN_DECIMALS$1,
31941
- address: IMX_ADDRESS_ZKEVM,
31942
31949
  },
31943
31950
  };
31944
31951
  }
@@ -31997,9 +32004,13 @@ const getTokenBalanceRequirement = (itemRequirement, balances) => {
31997
32004
  const getTokenBalances = async (config, provider, ownerAddress, itemRequirements) => {
31998
32005
  try {
31999
32006
  const tokenMap = new Map();
32000
- getTokensFromRequirements(itemRequirements).forEach((item) => tokenMap.set((item.address || '').toLocaleLowerCase(), item));
32001
- const { balances } = await getAllBalances(config, provider, ownerAddress);
32002
- return balances.filter((balance) => tokenMap.get((balance.token.address || '').toLocaleLowerCase()));
32007
+ getTokensFromRequirements(itemRequirements).forEach((item) => {
32008
+ if (!item.address)
32009
+ return;
32010
+ tokenMap.set(item.address.toLocaleLowerCase(), item);
32011
+ });
32012
+ const { balances } = await getAllBalances(config, provider, ownerAddress, getL2ChainId(config));
32013
+ return balances.filter((balance) => tokenMap.get((balance.token.address || NATIVE).toLocaleLowerCase()));
32003
32014
  }
32004
32015
  catch (error) {
32005
32016
  throw new CheckoutError('Failed to get balances', CheckoutErrorType.GET_BALANCE_ERROR);
@@ -32405,7 +32416,7 @@ const constructFees$1 = (approvalGasFees, swapGasFees, swapFees) => {
32405
32416
  const constructSwapRoute = (chainId, fundsRequired, userBalance, fees) => {
32406
32417
  const tokenAddress = userBalance.token.address;
32407
32418
  let type = ItemType.ERC20;
32408
- if (tokenAddress === IMX_ADDRESS_ZKEVM) {
32419
+ if (isNativeToken(tokenAddress)) {
32409
32420
  type = ItemType.NATIVE;
32410
32421
  }
32411
32422
  return {
@@ -32426,16 +32437,24 @@ const constructSwapRoute = (chainId, fundsRequired, userBalance, fees) => {
32426
32437
  fees,
32427
32438
  };
32428
32439
  };
32440
+ const isBalanceRequirementTokenValid = (balanceRequirement) => {
32441
+ if (balanceRequirement.type === ItemType.ERC20) {
32442
+ return !!balanceRequirement.required.token.address;
32443
+ }
32444
+ if (balanceRequirement.type === ItemType.NATIVE) {
32445
+ return isNativeToken(balanceRequirement.required.token.address);
32446
+ }
32447
+ return false;
32448
+ };
32429
32449
  const getRequiredToken = (balanceRequirement) => {
32430
32450
  let address = '';
32431
32451
  let amount = BigNumber$1.from(0);
32432
32452
  switch (balanceRequirement.type) {
32433
32453
  case ItemType.ERC20:
32434
- address = balanceRequirement.required.token.address ?? '';
32454
+ address = balanceRequirement.required.token.address;
32435
32455
  amount = balanceRequirement.delta.balance;
32436
32456
  break;
32437
32457
  case ItemType.NATIVE:
32438
- address = IMX_ADDRESS_ZKEVM;
32439
32458
  amount = balanceRequirement.delta.balance;
32440
32459
  break;
32441
32460
  }
@@ -32456,7 +32475,8 @@ const checkUserCanCoverApprovalFees = (l2Balances, approval) => {
32456
32475
  };
32457
32476
  }
32458
32477
  // Find the users balance of the approval token
32459
- const l2BalanceOfApprovalToken = l2Balances.find((balance) => balance.token.address === approvalGasTokenAddress);
32478
+ const l2BalanceOfApprovalToken = l2Balances.find((balance) => (isNativeToken(balance.token.address) && isNativeToken(approvalGasTokenAddress))
32479
+ || balance.token.address === approvalGasTokenAddress);
32460
32480
  if (!l2BalanceOfApprovalToken)
32461
32481
  return { sufficient: false, approvalGasFee, approvalGasTokenAddress };
32462
32482
  // If the user does not have enough of the token to cover approval fees then return sufficient false
@@ -32474,7 +32494,7 @@ const checkUserCanCoverSwapFees = (l2Balances, approvalFees, swapGasFees, swapFe
32474
32494
  // Set up a map of token addresses to amounts for each of the swap fees
32475
32495
  const feeMap = new Map();
32476
32496
  // Add the approval fee to list of fees
32477
- if (approvalFees.approvalGasTokenAddress !== '') {
32497
+ if (approvalFees.approvalGasFee.gt(BigNumber$1.from(0))) {
32478
32498
  feeMap.set(approvalFees.approvalGasTokenAddress, approvalFees.approvalGasFee);
32479
32499
  }
32480
32500
  // Add the swap gas fee to list of fees
@@ -32510,7 +32530,8 @@ const checkUserCanCoverSwapFees = (l2Balances, approvalFees, swapGasFees, swapFe
32510
32530
  for (const [tokenAddress, fee] of feeMap.entries()) {
32511
32531
  if (fee === BigNumber$1.from(0))
32512
32532
  continue;
32513
- const l2BalanceOfFeeToken = l2Balances.find((balance) => balance.token.address === tokenAddress);
32533
+ const l2BalanceOfFeeToken = l2Balances.find((balance) => (isNativeToken(balance.token.address) && isNativeToken(tokenAddress))
32534
+ || balance.token.address === tokenAddress);
32514
32535
  if (!l2BalanceOfFeeToken) {
32515
32536
  return false;
32516
32537
  }
@@ -32562,9 +32583,9 @@ const swapRoute = async (config, availableRoutingOptions, walletAddress, balance
32562
32583
  return fundingSteps;
32563
32584
  if (swappableTokens.length === 0)
32564
32585
  return fundingSteps;
32565
- const requiredToken = getRequiredToken(balanceRequirement);
32566
- if (requiredToken.address === '')
32586
+ if (!isBalanceRequirementTokenValid(balanceRequirement))
32567
32587
  return fundingSteps;
32588
+ const requiredToken = getRequiredToken(balanceRequirement);
32568
32589
  const chainId = getL2ChainId(config);
32569
32590
  const l2TokenBalanceResult = tokenBalanceResults.get(chainId);
32570
32591
  if (!l2TokenBalanceResult)
@@ -32661,7 +32682,7 @@ const allowListCheck = async (config, tokenBalances, availableRoutingOptions) =>
32661
32682
 
32662
32683
  const getEthBalance = (balances) => {
32663
32684
  for (const balance of balances.balances) {
32664
- if (!balance.token.address || balance.token.address === '') {
32685
+ if (isNativeToken(balance.token.address)) {
32665
32686
  return balance.balance;
32666
32687
  }
32667
32688
  }
@@ -32717,25 +32738,28 @@ const getImxL1Representation = async (chainId, config) => {
32717
32738
  return imxMappingConfig[chainId] ?? '';
32718
32739
  };
32719
32740
  const fetchL1Representation = async (config, l2address) => {
32720
- if (l2address === '')
32721
- return { l1address: '', l2address };
32722
- if (l2address === IMX_ADDRESS_ZKEVM) {
32741
+ if (isNativeToken(l2address)) {
32723
32742
  return {
32724
32743
  l1address: await getImxL1Representation(getL1ChainId(config), config),
32725
- l2address: IMX_ADDRESS_ZKEVM,
32744
+ l2address: NATIVE,
32726
32745
  };
32727
32746
  }
32728
32747
  const chainName = getIndexerChainName(getL2ChainId(config));
32729
- if (chainName === '')
32730
- return { l1address: '', l2address }; // Chain name not a valid indexer chain name
32731
32748
  const blockchainData = createBlockchainDataInstance(config);
32732
32749
  const tokenData = await blockchainData.getToken({
32733
32750
  chainName,
32734
32751
  contractAddress: l2address,
32735
32752
  });
32753
+ // TODO: When bridge is ready we need to understand how L2 ETH will be mapped back to L1 ETH
32736
32754
  const l1address = tokenData.result.root_contract_address;
32755
+ if (l1address === INDEXER_ETH_ROOT_CONTRACT_ADDRESS) {
32756
+ return {
32757
+ l1address: 'native',
32758
+ l2address,
32759
+ };
32760
+ }
32737
32761
  if (l1address === null)
32738
- return { l1address: '', l2address }; // No L1 representation of this token
32762
+ return undefined; // No L1 representation of this token
32739
32763
  return {
32740
32764
  l1address,
32741
32765
  l2address,
@@ -32822,16 +32846,9 @@ const constructBridgeFundingRoute = (chainId, balance, bridgeRequirement, itemTy
32822
32846
  },
32823
32847
  fees,
32824
32848
  });
32825
- const isNativeEth = (address) => {
32826
- if (!address || address === '')
32827
- return true;
32828
- return false;
32829
- };
32830
32849
  const bridgeRoute = async (config, readOnlyProviders, depositorAddress, availableRoutingOptions, bridgeRequirement, tokenBalanceResults, feeEstimates) => {
32831
32850
  if (!availableRoutingOptions.bridge)
32832
32851
  return undefined;
32833
- if (bridgeRequirement.l2address === undefined || bridgeRequirement.l2address === '')
32834
- return undefined;
32835
32852
  const chainId = getL1ChainId(config);
32836
32853
  const tokenBalanceResult = tokenBalanceResults.get(chainId);
32837
32854
  const l1provider = readOnlyProviders.get(chainId);
@@ -32849,12 +32866,11 @@ const bridgeRoute = async (config, readOnlyProviders, depositorAddress, availabl
32849
32866
  if (!hasSufficientL1Eth(tokenBalanceResult, bridgeFeeEstimate.totalFees))
32850
32867
  return undefined;
32851
32868
  const l1RepresentationResult = await fetchL1Representation(config, bridgeRequirement.l2address);
32852
- // No mapping on L1 for this token
32853
- const { l1address } = l1RepresentationResult;
32854
- if (l1address === '')
32869
+ if (!l1RepresentationResult)
32855
32870
  return undefined;
32856
32871
  // Ensure l1address is in the allowed token list
32857
- if (l1address === INDEXER_ETH_ROOT_CONTRACT_ADDRESS) {
32872
+ const { l1address } = l1RepresentationResult;
32873
+ if (isNativeToken(l1address)) {
32858
32874
  if (!allowedTokenList.find((token) => !('address' in token)))
32859
32875
  return undefined;
32860
32876
  }
@@ -32864,9 +32880,9 @@ const bridgeRoute = async (config, readOnlyProviders, depositorAddress, availabl
32864
32880
  const gasForApproval = await estimateGasForBridgeApproval(config, readOnlyProviders, l1provider, depositorAddress, l1address, bridgeRequirement.amount);
32865
32881
  let totalFees = bridgeFeeEstimate.bridgeFee.estimatedAmount;
32866
32882
  // If the L1 representation of the requirement is ETH then find the ETH balance and check if the balance covers the delta
32867
- if (l1address === INDEXER_ETH_ROOT_CONTRACT_ADDRESS) {
32883
+ if (isNativeToken(l1address)) {
32868
32884
  const nativeETHBalance = tokenBalanceResult.balances
32869
- .find((balance) => isNativeEth(balance.token.address));
32885
+ .find((balance) => isNativeToken(balance.token.address));
32870
32886
  if (bridgeFeeEstimate.gasFee.estimatedAmount) {
32871
32887
  totalFees = totalFees.add(bridgeFeeEstimate.gasFee.estimatedAmount);
32872
32888
  }
@@ -33022,8 +33038,10 @@ const constructBridgeRequirements = (dexQuotes, l1balances, l2balances, l1tol2ad
33022
33038
  };
33023
33039
 
33024
33040
  const fetchL1ToL2Mappings = async (config, swappableTokens) => {
33025
- const l1tol2addressMappingPromises = swappableTokens.map((token) => fetchL1Representation(config, token.address ?? ''));
33026
- return await Promise.all(l1tol2addressMappingPromises);
33041
+ const l1tol2addressMappingPromises = swappableTokens
33042
+ .map((token) => fetchL1Representation(config, token.address ?? ''));
33043
+ const mappings = await Promise.all(l1tol2addressMappingPromises);
33044
+ return mappings.filter((mapping) => mapping !== undefined);
33027
33045
  };
33028
33046
 
33029
33047
  // Fetch all the dex quotes from the list of swappable tokens
@@ -33063,10 +33081,7 @@ const abortBridgeAndSwap = (bridgeableTokens, swappableTokens, l1balances, l2bal
33063
33081
  const filterSwappableTokensByBridgeableAddresses = (requiredTokenAddress, bridgeableTokens, swappableTokens, l1tol2Addresses) => {
33064
33082
  const filteredSwappableTokens = [];
33065
33083
  for (const addresses of l1tol2Addresses) {
33066
- if (addresses.l1address === '')
33067
- continue;
33068
- if (addresses.l2address === '')
33069
- continue;
33084
+ // TODO: Check for ETH (native) L1 in bridgeableTokens first
33070
33085
  if (!bridgeableTokens.includes(addresses.l1address))
33071
33086
  continue;
33072
33087
  // Filter out the token that is required from the swappable tokens list
@@ -33255,7 +33270,7 @@ const onRampRoute = async (config, availableRoutingOptions, balanceRequirement)
33255
33270
  type: FundingStepType.ONRAMP,
33256
33271
  chainId: getL2ChainId(config),
33257
33272
  fundingItem: {
33258
- type: required.token.address === IMX_ADDRESS_ZKEVM ? ItemType.NATIVE : ItemType.ERC20,
33273
+ type: isNativeToken(required.token.address) ? ItemType.NATIVE : ItemType.ERC20,
33259
33274
  fundsRequired: {
33260
33275
  amount: delta.balance,
33261
33276
  formattedAmount: delta.formattedBalance,
@@ -33491,8 +33506,8 @@ var SignTransactionStatusType;
33491
33506
  const signApprovalTransactions = async (provider, approvalTransactions) => {
33492
33507
  let receipts = [];
33493
33508
  try {
33494
- const response = await Promise.all(approvalTransactions.map((transaction) => provider.getSigner().sendTransaction(transaction)));
33495
- receipts = await Promise.all(response.map((transaction) => transaction.wait()));
33509
+ const response = await Promise.all(approvalTransactions.map((transaction) => sendTransaction(provider, transaction)));
33510
+ receipts = await Promise.all(response.map((transaction) => transaction.transactionResponse.wait()));
33496
33511
  }
33497
33512
  catch (err) {
33498
33513
  throw new CheckoutError('An error occurred while executing the approval transaction', CheckoutErrorType.EXECUTE_APPROVAL_TRANSACTION_ERROR, {
@@ -33515,8 +33530,8 @@ const signApprovalTransactions = async (provider, approvalTransactions) => {
33515
33530
  const signFulfillmentTransactions = async (provider, fulfillmentTransactions) => {
33516
33531
  let receipts = [];
33517
33532
  try {
33518
- const response = await Promise.all(fulfillmentTransactions.map((transaction) => provider.getSigner().sendTransaction(transaction)));
33519
- receipts = await Promise.all(response.map((transaction) => transaction.wait()));
33533
+ const response = await Promise.all(fulfillmentTransactions.map((transaction) => sendTransaction(provider, transaction)));
33534
+ receipts = await Promise.all(response.map((transaction) => transaction.transactionResponse.wait()));
33520
33535
  }
33521
33536
  catch (err) {
33522
33537
  throw new CheckoutError('An error occurred while executing the fulfillment transaction', CheckoutErrorType.EXECUTE_FULFILLMENT_TRANSACTION_ERROR, {
@@ -34092,10 +34107,6 @@ async function getItemRequirementsFromRequirements(provider, requirements) {
34092
34107
  return itemRequirements;
34093
34108
  }
34094
34109
 
34095
- const SDK_VERSION_MARKER = '0.31.3';
34096
- // This SDK version is replaced by the `yarn build` command ran on the root level
34097
- const globalPackageVersion = () => SDK_VERSION_MARKER;
34098
-
34099
34110
  /**
34100
34111
  * Validates and builds a version string based on the given SemanticVersion object.
34101
34112
  * If the version is undefined or has an invalid major version, it returns the default checkout version.
@@ -34448,7 +34459,7 @@ class Checkout {
34448
34459
  }
34449
34460
  }
34450
34461
 
34451
- var checkout_sdk = /*#__PURE__*/Object.freeze({
34462
+ var checkout = /*#__PURE__*/Object.freeze({
34452
34463
  __proto__: null,
34453
34464
  get BridgeEventType () { return BridgeEventType; },
34454
34465
  CHECKOUT_API_BASE_URL: CHECKOUT_API_BASE_URL,
@@ -34482,4 +34493,4 @@ var checkout_sdk = /*#__PURE__*/Object.freeze({
34482
34493
  get WidgetType () { return WidgetType; }
34483
34494
  });
34484
34495
 
34485
- export { blockchain_data as blockchainData, checkout_sdk as checkoutSdk, config, immutablex_client as immutablexClient, orderbook, passport, provider };
34496
+ export { blockchain_data as blockchainData, checkout, config, immutablex_client as immutablexClient, orderbook, passport, provider };