@imtbl/sdk 0.17.6 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import globalAxios$1, { HttpStatusCode as HttpStatusCode$2 } from 'axios';
2
2
  import { ImmutableX, Config, IMXError, createStarkSigner, generateLegacyStarkPrivateKey, TransfersApi, OrdersApi as OrdersApi$1, UsersApi, Contracts, TradesApi, ExchangesApi, WithdrawalsApi, MintsApi, DepositsApi, EncodingApi, TokensApi as TokensApi$1 } from '@imtbl/core-sdk';
3
- import { UserManager } from 'oidc-client-ts';
3
+ import { UserManager, WebStorageStateStore } from 'oidc-client-ts';
4
4
  import jwt_decode from 'jwt-decode';
5
5
  import * as crypto from 'crypto';
6
6
  import { Magic } from 'magic-sdk';
@@ -11,7 +11,7 @@ import * as encUtils from 'enc-utils';
11
11
  import { Web3Provider, JsonRpcProvider } from '@ethersproject/providers';
12
12
  import { EventEmitter } from 'events';
13
13
  import { walletContracts } from '@0xsequence/abi';
14
- import { encodeSignature } from '@0xsequence/config';
14
+ import { encodeSignature, decodeSignature } from '@0xsequence/config';
15
15
  import FormData$2 from 'form-data';
16
16
  import { Seaport as Seaport$1 } from '@opensea/seaport-js';
17
17
  import { parseUnits } from '@ethersproject/units';
@@ -22,6 +22,7 @@ import assert from 'assert';
22
22
  import { FeeAmount, Route, SwapQuoter, Pool, Trade, toHex as toHex$1, encodeRouteToPath } from '@uniswap/v3-sdk';
23
23
  import { keccak256 as keccak256$1 } from '@ethersproject/solidity';
24
24
  import { SwapRouter } from '@uniswap/router-sdk';
25
+ import { parseUnits as parseUnits$1 } from 'ethers/lib/utils';
25
26
  import { jsx } from 'react/jsx-runtime';
26
27
  import { useEffect } from 'react';
27
28
 
@@ -2702,7 +2703,7 @@ class MultiRollupApiClients {
2702
2703
  }
2703
2704
 
2704
2705
  // eslint-disable-next-line @typescript-eslint/naming-convention
2705
- const defaultHeaders$1 = { 'x-sdk-version': 'ts-immutable-sdk-0.17.6' };
2706
+ const defaultHeaders$1 = { 'x-sdk-version': 'ts-immutable-sdk-0.18.1' };
2706
2707
  const createConfig = ({ basePath, headers, }) => {
2707
2708
  if (!basePath.trim()) {
2708
2709
  throw Error('basePath can not be empty');
@@ -2762,7 +2763,7 @@ class APIError extends Error {
2762
2763
 
2763
2764
  /* eslint-disable implicit-arrow-linebreak */
2764
2765
  const defaultHeaders = {
2765
- sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-0.17.6',
2766
+ sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-0.18.1',
2766
2767
  };
2767
2768
  /**
2768
2769
  * createAPIConfiguration to create a custom Configuration
@@ -3048,7 +3049,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
3048
3049
  chainID,
3049
3050
  coreContractAddress,
3050
3051
  registrationContractAddress,
3051
- sdkVersion: 'ts-immutable-sdk-0.17.6',
3052
+ sdkVersion: 'ts-immutable-sdk-0.18.1',
3052
3053
  });
3053
3054
  /**
3054
3055
  * Sets `sdkVersion` at the time of build
@@ -6780,6 +6781,8 @@ var globalAxios = axios;
6780
6781
  * https://openapi-generator.tech
6781
6782
  * Do not edit the class manually.
6782
6783
  */
6784
+ // Some imports not used depending on template conditions
6785
+ // @ts-ignore
6783
6786
  const BASE_PATH = "https://guardian.sandbox.imtbl.com".replace(/\/+$/, "");
6784
6787
  /**
6785
6788
  *
@@ -6807,10 +6810,10 @@ class BaseAPI {
6807
6810
  */
6808
6811
  class RequiredError extends Error {
6809
6812
  field;
6813
+ name = "RequiredError";
6810
6814
  constructor(field, msg) {
6811
6815
  super(msg);
6812
6816
  this.field = field;
6813
- this.name = "RequiredError";
6814
6817
  }
6815
6818
  }
6816
6819
 
@@ -6855,8 +6858,6 @@ const setBearerAuthToObject = async function (object, configuration) {
6855
6858
  }
6856
6859
  };
6857
6860
  function setFlattenedQueryParams(urlSearchParams, parameter, key = "") {
6858
- if (parameter == null)
6859
- return;
6860
6861
  if (typeof parameter === "object") {
6861
6862
  if (Array.isArray(parameter)) {
6862
6863
  parameter.forEach(item => setFlattenedQueryParams(urlSearchParams, item, key));
@@ -6914,6 +6915,208 @@ const createRequestFunction = function (axiosArgs, globalAxios, BASE_PATH, confi
6914
6915
  };
6915
6916
  };
6916
6917
 
6918
+ /* tslint:disable */
6919
+ /* eslint-disable */
6920
+ /**
6921
+ * Guardian
6922
+ * Guardian API
6923
+ *
6924
+ * The version of the OpenAPI document: 1.0.0
6925
+ * Contact: support@immutable.com
6926
+ *
6927
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
6928
+ * https://openapi-generator.tech
6929
+ * Do not edit the class manually.
6930
+ */
6931
+ /**
6932
+ * MessagesApi - axios parameter creator
6933
+ * @export
6934
+ */
6935
+ const MessagesApiAxiosParamCreator = function (configuration) {
6936
+ return {
6937
+ /**
6938
+ * Approve a pending evm message
6939
+ * @summary Approve a pending evm message
6940
+ * @param {string} messageID id for the message
6941
+ * @param {*} [options] Override http request option.
6942
+ * @throws {RequiredError}
6943
+ */
6944
+ approvePendingMessage: async (messageID, options = {}) => {
6945
+ // verify required parameter 'messageID' is not null or undefined
6946
+ assertParamExists('approvePendingMessage', 'messageID', messageID);
6947
+ const localVarPath = `/guardian/v1/messages/{messageID}/approve`
6948
+ .replace(`{${"messageID"}}`, encodeURIComponent(String(messageID)));
6949
+ // use dummy base URL string because the URL constructor only accepts absolute URLs.
6950
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
6951
+ let baseOptions;
6952
+ if (configuration) {
6953
+ baseOptions = configuration.baseOptions;
6954
+ }
6955
+ const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options };
6956
+ const localVarHeaderParameter = {};
6957
+ const localVarQueryParameter = {};
6958
+ // authentication BearerAuth required
6959
+ // http bearer authentication required
6960
+ await setBearerAuthToObject(localVarHeaderParameter, configuration);
6961
+ setSearchParams(localVarUrlObj, localVarQueryParameter);
6962
+ let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
6963
+ localVarRequestOptions.headers = { ...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers };
6964
+ return {
6965
+ url: toPathString(localVarUrlObj),
6966
+ options: localVarRequestOptions,
6967
+ };
6968
+ },
6969
+ /**
6970
+ * Check if a given message is valid for EVM
6971
+ * @summary Evaluate an evm message to sign
6972
+ * @param {MessageEvaluationRequest} messageEvaluationRequest Specifies the kind of transaction
6973
+ * @param {*} [options] Override http request option.
6974
+ * @throws {RequiredError}
6975
+ */
6976
+ evaluateMessage: async (messageEvaluationRequest, options = {}) => {
6977
+ // verify required parameter 'messageEvaluationRequest' is not null or undefined
6978
+ assertParamExists('evaluateMessage', 'messageEvaluationRequest', messageEvaluationRequest);
6979
+ const localVarPath = `/guardian/v1/messages/evaluate`;
6980
+ // use dummy base URL string because the URL constructor only accepts absolute URLs.
6981
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
6982
+ let baseOptions;
6983
+ if (configuration) {
6984
+ baseOptions = configuration.baseOptions;
6985
+ }
6986
+ const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options };
6987
+ const localVarHeaderParameter = {};
6988
+ const localVarQueryParameter = {};
6989
+ // authentication BearerAuth required
6990
+ // http bearer authentication required
6991
+ await setBearerAuthToObject(localVarHeaderParameter, configuration);
6992
+ localVarHeaderParameter['Content-Type'] = 'application/json';
6993
+ setSearchParams(localVarUrlObj, localVarQueryParameter);
6994
+ let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
6995
+ localVarRequestOptions.headers = { ...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers };
6996
+ localVarRequestOptions.data = serializeDataIfNeeded(messageEvaluationRequest, localVarRequestOptions, configuration);
6997
+ return {
6998
+ url: toPathString(localVarUrlObj),
6999
+ options: localVarRequestOptions,
7000
+ };
7001
+ },
7002
+ /**
7003
+ * Get an evm message by id
7004
+ * @summary Info for a specific evm message
7005
+ * @param {string} messageID The id of the evm message
7006
+ * @param {*} [options] Override http request option.
7007
+ * @throws {RequiredError}
7008
+ */
7009
+ getMessageByID: async (messageID, options = {}) => {
7010
+ // verify required parameter 'messageID' is not null or undefined
7011
+ assertParamExists('getMessageByID', 'messageID', messageID);
7012
+ const localVarPath = `/guardian/v1/messages/{messageID}`
7013
+ .replace(`{${"messageID"}}`, encodeURIComponent(String(messageID)));
7014
+ // use dummy base URL string because the URL constructor only accepts absolute URLs.
7015
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
7016
+ let baseOptions;
7017
+ if (configuration) {
7018
+ baseOptions = configuration.baseOptions;
7019
+ }
7020
+ const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options };
7021
+ const localVarHeaderParameter = {};
7022
+ const localVarQueryParameter = {};
7023
+ // authentication BearerAuth required
7024
+ // http bearer authentication required
7025
+ await setBearerAuthToObject(localVarHeaderParameter, configuration);
7026
+ setSearchParams(localVarUrlObj, localVarQueryParameter);
7027
+ let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
7028
+ localVarRequestOptions.headers = { ...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers };
7029
+ return {
7030
+ url: toPathString(localVarUrlObj),
7031
+ options: localVarRequestOptions,
7032
+ };
7033
+ },
7034
+ };
7035
+ };
7036
+ /**
7037
+ * MessagesApi - functional programming interface
7038
+ * @export
7039
+ */
7040
+ const MessagesApiFp = function (configuration) {
7041
+ const localVarAxiosParamCreator = MessagesApiAxiosParamCreator(configuration);
7042
+ return {
7043
+ /**
7044
+ * Approve a pending evm message
7045
+ * @summary Approve a pending evm message
7046
+ * @param {string} messageID id for the message
7047
+ * @param {*} [options] Override http request option.
7048
+ * @throws {RequiredError}
7049
+ */
7050
+ async approvePendingMessage(messageID, options) {
7051
+ const localVarAxiosArgs = await localVarAxiosParamCreator.approvePendingMessage(messageID, options);
7052
+ return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
7053
+ },
7054
+ /**
7055
+ * Check if a given message is valid for EVM
7056
+ * @summary Evaluate an evm message to sign
7057
+ * @param {MessageEvaluationRequest} messageEvaluationRequest Specifies the kind of transaction
7058
+ * @param {*} [options] Override http request option.
7059
+ * @throws {RequiredError}
7060
+ */
7061
+ async evaluateMessage(messageEvaluationRequest, options) {
7062
+ const localVarAxiosArgs = await localVarAxiosParamCreator.evaluateMessage(messageEvaluationRequest, options);
7063
+ return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
7064
+ },
7065
+ /**
7066
+ * Get an evm message by id
7067
+ * @summary Info for a specific evm message
7068
+ * @param {string} messageID The id of the evm message
7069
+ * @param {*} [options] Override http request option.
7070
+ * @throws {RequiredError}
7071
+ */
7072
+ async getMessageByID(messageID, options) {
7073
+ const localVarAxiosArgs = await localVarAxiosParamCreator.getMessageByID(messageID, options);
7074
+ return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
7075
+ },
7076
+ };
7077
+ };
7078
+ /**
7079
+ * MessagesApi - object-oriented interface
7080
+ * @export
7081
+ * @class MessagesApi
7082
+ * @extends {BaseAPI}
7083
+ */
7084
+ class MessagesApi extends BaseAPI {
7085
+ /**
7086
+ * Approve a pending evm message
7087
+ * @summary Approve a pending evm message
7088
+ * @param {MessagesApiApprovePendingMessageRequest} requestParameters Request parameters.
7089
+ * @param {*} [options] Override http request option.
7090
+ * @throws {RequiredError}
7091
+ * @memberof MessagesApi
7092
+ */
7093
+ approvePendingMessage(requestParameters, options) {
7094
+ return MessagesApiFp(this.configuration).approvePendingMessage(requestParameters.messageID, options).then((request) => request(this.axios, this.basePath));
7095
+ }
7096
+ /**
7097
+ * Check if a given message is valid for EVM
7098
+ * @summary Evaluate an evm message to sign
7099
+ * @param {MessagesApiEvaluateMessageRequest} requestParameters Request parameters.
7100
+ * @param {*} [options] Override http request option.
7101
+ * @throws {RequiredError}
7102
+ * @memberof MessagesApi
7103
+ */
7104
+ evaluateMessage(requestParameters, options) {
7105
+ return MessagesApiFp(this.configuration).evaluateMessage(requestParameters.messageEvaluationRequest, options).then((request) => request(this.axios, this.basePath));
7106
+ }
7107
+ /**
7108
+ * Get an evm message by id
7109
+ * @summary Info for a specific evm message
7110
+ * @param {MessagesApiGetMessageByIDRequest} requestParameters Request parameters.
7111
+ * @param {*} [options] Override http request option.
7112
+ * @throws {RequiredError}
7113
+ * @memberof MessagesApi
7114
+ */
7115
+ getMessageByID(requestParameters, options) {
7116
+ return MessagesApiFp(this.configuration).getMessageByID(requestParameters.messageID, options).then((request) => request(this.axios, this.basePath));
7117
+ }
7118
+ }
7119
+
6917
7120
  /* tslint:disable */
6918
7121
  /* eslint-disable */
6919
7122
  /**
@@ -6937,7 +7140,7 @@ const TransactionsApiAxiosParamCreator = function (configuration) {
6937
7140
  * Approve a pending transaction
6938
7141
  * @summary Approve a pending transaction given chain
6939
7142
  * @param {string} payloadHash Hash for the payload
6940
- * @param {TransactionApprovalRequest} transactionApprovalRequest request body for approving a pending transactio
7143
+ * @param {TransactionApprovalRequest} transactionApprovalRequest request body for approving a pending transaction
6941
7144
  * @param {*} [options] Override http request option.
6942
7145
  * @throws {RequiredError}
6943
7146
  */
@@ -7062,7 +7265,7 @@ const TransactionsApiFp = function (configuration) {
7062
7265
  * Approve a pending transaction
7063
7266
  * @summary Approve a pending transaction given chain
7064
7267
  * @param {string} payloadHash Hash for the payload
7065
- * @param {TransactionApprovalRequest} transactionApprovalRequest request body for approving a pending transactio
7268
+ * @param {TransactionApprovalRequest} transactionApprovalRequest request body for approving a pending transaction
7066
7269
  * @param {*} [options] Override http request option.
7067
7270
  * @throws {RequiredError}
7068
7271
  */
@@ -7429,6 +7632,7 @@ const getAuthConfiguration = ({ oidcConfiguration, authenticationDomain, }) => {
7429
7632
  mergeClaims: true,
7430
7633
  loadUserInfo: true,
7431
7634
  scope: oidcConfiguration.scope,
7635
+ userStore: new WebStorageStateStore({ store: window.localStorage }),
7432
7636
  };
7433
7637
  if (oidcConfiguration.audience) {
7434
7638
  baseConfiguration.extraQueryParams = {
@@ -7828,18 +8032,18 @@ const transformGuardianTransactions = (txs) => {
7828
8032
  };
7829
8033
  class GuardianClient {
7830
8034
  transactionAPI;
8035
+ messageAPI;
7831
8036
  confirmationScreen;
7832
8037
  // TODO: ID-977, make this rollup agnostic
7833
8038
  imxEtherAddress;
7834
8039
  crossSdkBridgeEnabled;
7835
8040
  constructor({ accessToken, confirmationScreen, imxEtherAddress, config, }) {
8041
+ const guardianConfiguration = new Configuration({ accessToken, basePath: config.imxPublicApiDomain });
7836
8042
  this.confirmationScreen = confirmationScreen;
7837
- this.transactionAPI = new TransactionsApi(new Configuration({
7838
- accessToken,
7839
- basePath: config.imxPublicApiDomain,
7840
- }));
8043
+ this.transactionAPI = new TransactionsApi(new Configuration(guardianConfiguration));
7841
8044
  this.imxEtherAddress = imxEtherAddress;
7842
8045
  this.crossSdkBridgeEnabled = config.crossSdkBridgeEnabled;
8046
+ this.messageAPI = new MessagesApi(guardianConfiguration);
7843
8047
  }
7844
8048
  /**
7845
8049
  * Open confirmation screen and close it automatically if the
@@ -7938,6 +8142,31 @@ class GuardianClient {
7938
8142
  this.confirmationScreen.closeWindow();
7939
8143
  }
7940
8144
  }
8145
+ async evaluateMessage({ chainID, payload, user }) {
8146
+ try {
8147
+ const messageEvalResponse = await this.messageAPI.evaluateMessage({ messageEvaluationRequest: { chainID, payload } }, { headers: { Authorization: `Bearer ${user.accessToken}` } });
8148
+ return messageEvalResponse.data;
8149
+ }
8150
+ catch (error) {
8151
+ const errorMessage = error instanceof Error ? error.message : String(error);
8152
+ throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, `Message failed to validate with error: ${errorMessage}`);
8153
+ }
8154
+ }
8155
+ async validateMessage({ chainID, payload, user }) {
8156
+ const { messageId, confirmationRequired } = await this.evaluateMessage({ chainID, payload, user });
8157
+ if (confirmationRequired && this.crossSdkBridgeEnabled) {
8158
+ throw new JsonRpcError(RpcErrorCode.TRANSACTION_REJECTED, transactionRejectedCrossSdkBridgeError);
8159
+ }
8160
+ if (confirmationRequired && !!messageId) {
8161
+ const confirmationResult = await this.confirmationScreen.requestMessageConfirmation(messageId);
8162
+ if (!confirmationResult.confirmed) {
8163
+ throw new JsonRpcError(RpcErrorCode.TRANSACTION_REJECTED, 'Signature rejected by user');
8164
+ }
8165
+ }
8166
+ else {
8167
+ this.confirmationScreen.closeWindow();
8168
+ }
8169
+ }
7941
8170
  }
7942
8171
 
7943
8172
  var PassportEvents;
@@ -8565,6 +8794,8 @@ var ReceiveMessage;
8565
8794
  ReceiveMessage["CONFIRMATION_WINDOW_READY"] = "confirmation_window_ready";
8566
8795
  ReceiveMessage["TRANSACTION_CONFIRMED"] = "transaction_confirmed";
8567
8796
  ReceiveMessage["TRANSACTION_ERROR"] = "transaction_error";
8797
+ ReceiveMessage["MESSAGE_CONFIRMED"] = "message_confirmed";
8798
+ ReceiveMessage["MESSAGE_REJECTED"] = "message_rejected";
8568
8799
  })(ReceiveMessage || (ReceiveMessage = {}));
8569
8800
  const PASSPORT_EVENT_TYPE = 'imx_passport_confirmation';
8570
8801
 
@@ -8618,11 +8849,11 @@ class ConfirmationScreen {
8618
8849
  reject(new Error('Unsupported message type'));
8619
8850
  }
8620
8851
  };
8621
- window.addEventListener('message', messageHandler);
8622
8852
  if (!this.confirmationWindow) {
8623
8853
  resolve({ confirmed: false });
8624
8854
  return;
8625
8855
  }
8856
+ window.addEventListener('message', messageHandler);
8626
8857
  let href = '';
8627
8858
  if (chainType === TransactionApprovalRequestChainTypeEnum.Starkex) {
8628
8859
  // eslint-disable-next-line max-len
@@ -8632,15 +8863,39 @@ class ConfirmationScreen {
8632
8863
  // eslint-disable-next-line max-len
8633
8864
  href = `${this.config.passportDomain}/transaction-confirmation/zkevm?transactionId=${transactionId}&imxEtherAddress=${imxEtherAddress}&chainType=evm&chainId=${chainId}`;
8634
8865
  }
8635
- this.confirmationWindow.location.href = href;
8636
- // https://stackoverflow.com/questions/9388380/capture-the-close-event-of-popup-window-in-javascript/48240128#48240128
8637
- const timer = setInterval(() => {
8638
- if (this.confirmationWindow?.closed) {
8639
- clearInterval(timer);
8640
- window.removeEventListener('message', messageHandler);
8641
- resolve({ confirmed: false });
8866
+ this.showConfirmationScreen(href, messageHandler, resolve);
8867
+ });
8868
+ }
8869
+ requestMessageConfirmation(messageId) {
8870
+ return new Promise((resolve, reject) => {
8871
+ const messageHandler = ({ data, origin }) => {
8872
+ if (origin !== this.config.passportDomain
8873
+ || data.eventType !== PASSPORT_EVENT_TYPE) {
8874
+ return;
8875
+ }
8876
+ switch (data.messageType) {
8877
+ case ReceiveMessage.CONFIRMATION_WINDOW_READY: {
8878
+ break;
8879
+ }
8880
+ case ReceiveMessage.MESSAGE_CONFIRMED: {
8881
+ resolve({ confirmed: true });
8882
+ break;
8883
+ }
8884
+ case ReceiveMessage.MESSAGE_REJECTED: {
8885
+ reject(new Error('Message rejected'));
8886
+ break;
8887
+ }
8888
+ default:
8889
+ reject(new Error('Unsupported message type'));
8642
8890
  }
8643
- }, CONFIRMATION_WINDOW_CLOSED_POLLING_DURATION);
8891
+ };
8892
+ if (!this.confirmationWindow) {
8893
+ resolve({ confirmed: false });
8894
+ return;
8895
+ }
8896
+ window.addEventListener('message', messageHandler);
8897
+ const href = `${this.config.passportDomain}/transaction-confirmation/zkevm/message?messageID=${messageId}`;
8898
+ this.showConfirmationScreen(href, messageHandler, resolve);
8644
8899
  });
8645
8900
  }
8646
8901
  loading(popupOptions) {
@@ -8658,6 +8913,17 @@ class ConfirmationScreen {
8658
8913
  closeWindow() {
8659
8914
  this.confirmationWindow?.close();
8660
8915
  }
8916
+ showConfirmationScreen(href, messageHandler, resolve) {
8917
+ this.confirmationWindow.location.href = href;
8918
+ // https://stackoverflow.com/questions/9388380/capture-the-close-event-of-popup-window-in-javascript/48240128#48240128
8919
+ const timer = setInterval(() => {
8920
+ if (this.confirmationWindow?.closed) {
8921
+ clearInterval(timer);
8922
+ window.removeEventListener('message', messageHandler);
8923
+ resolve({ confirmed: false });
8924
+ }
8925
+ }, CONFIRMATION_WINDOW_CLOSED_POLLING_DURATION);
8926
+ }
8661
8927
  }
8662
8928
 
8663
8929
  var RelayerTransactionStatus;
@@ -8686,13 +8952,9 @@ class TypedEventEmitter {
8686
8952
  }
8687
8953
  }
8688
8954
 
8689
- // These are ignored by the Relayer but for consistency we set them to the
8690
- // appropriate values for a 1/1 wallet.
8691
- //
8692
- // Weight of a single signature in the multisig
8693
- const SIGNATURE_WEIGHT = 1;
8694
- // Total required weight in the multisig
8695
- const SIGNATURE_THRESHOLD = 1;
8955
+ const SIGNATURE_WEIGHT = 1; // Weight of a single signature in the multi-sig
8956
+ const TRANSACTION_SIGNATURE_THRESHOLD = 1; // Total required weight in the multi-sig for a transaction
8957
+ const EIP712_SIGNATURE_THRESHOLD = 2; // Total required weight in the multi-sig for data signing
8696
8958
  const ETH_SIGN_FLAG = '02';
8697
8959
  const ETH_SIGN_PREFIX = '\x19\x01';
8698
8960
  const META_TRANSACTIONS_TYPE = `tuple(
@@ -8725,11 +8987,12 @@ const getNonce = async (jsonRpcProvider, smartContractWalletAddress) => {
8725
8987
  }
8726
8988
  return 0;
8727
8989
  };
8990
+ const encodeMessageSubDigest = (chainId, walletAddress, digest) => (ethers.utils.solidityPack(['string', 'uint256', 'address', 'bytes32'], [ETH_SIGN_PREFIX, chainId, walletAddress, digest]));
8728
8991
  const getSignedMetaTransactions = async (metaTransactions, nonce, chainId, walletAddress, signer) => {
8729
8992
  const normalisedMetaTransactions = getNormalisedTransactions(metaTransactions);
8730
8993
  // Get the hash
8731
8994
  const digest = digestOfTransactionsAndNonce(nonce, normalisedMetaTransactions);
8732
- const completePayload = ethers.utils.solidityPack(['string', 'uint256', 'address', 'bytes32'], [ETH_SIGN_PREFIX, chainId, walletAddress, digest]);
8995
+ const completePayload = encodeMessageSubDigest(chainId, walletAddress, digest);
8733
8996
  const hash = ethers.utils.keccak256(completePayload);
8734
8997
  // Sign the digest
8735
8998
  const hashArray = ethers.utils.arrayify(hash);
@@ -8737,7 +9000,7 @@ const getSignedMetaTransactions = async (metaTransactions, nonce, chainId, walle
8737
9000
  const signedDigest = `${ethsigNoType}${ETH_SIGN_FLAG}`;
8738
9001
  // Add metadata
8739
9002
  const encodedSignature = encodeSignature({
8740
- threshold: SIGNATURE_THRESHOLD,
9003
+ threshold: TRANSACTION_SIGNATURE_THRESHOLD,
8741
9004
  signers: [
8742
9005
  {
8743
9006
  weight: SIGNATURE_WEIGHT,
@@ -8753,6 +9016,35 @@ const getSignedMetaTransactions = async (metaTransactions, nonce, chainId, walle
8753
9016
  encodedSignature,
8754
9017
  ]);
8755
9018
  };
9019
+ const decodeRelayerTypedDataSignature = (relayerSignature) => {
9020
+ const signatureWithThreshold = `0000${relayerSignature}`;
9021
+ return decodeSignature(signatureWithThreshold);
9022
+ };
9023
+ const getSignedTypedData = async (typedData, relayerSignature, chainId, walletAddress, signer) => {
9024
+ // Ethers auto-generates the EIP712Domain type in the TypedDataEncoder, and so it needs to be removed
9025
+ const types = { ...typedData.types };
9026
+ // @ts-ignore
9027
+ delete types.EIP712Domain;
9028
+ // eslint-disable-next-line no-underscore-dangle
9029
+ const digest = ethers.utils._TypedDataEncoder.hash(typedData.domain, types, typedData.message);
9030
+ const completePayload = encodeMessageSubDigest(chainId, walletAddress, digest);
9031
+ const hash = ethers.utils.keccak256(completePayload);
9032
+ // Sign the digest
9033
+ const hashArray = ethers.utils.arrayify(hash);
9034
+ const ethsigNoType = await signer.signMessage(hashArray);
9035
+ const signedDigest = `${ethsigNoType}${ETH_SIGN_FLAG}`;
9036
+ const { signers } = decodeRelayerTypedDataSignature(relayerSignature);
9037
+ return encodeSignature({
9038
+ threshold: EIP712_SIGNATURE_THRESHOLD,
9039
+ signers: [
9040
+ ...signers,
9041
+ {
9042
+ weight: SIGNATURE_WEIGHT,
9043
+ signature: signedDigest,
9044
+ },
9045
+ ],
9046
+ });
9047
+ };
8756
9048
  const getEip155ChainId = (chainId) => `eip155:${chainId}`;
8757
9049
 
8758
9050
  class RelayerClient {
@@ -8818,6 +9110,19 @@ class RelayerClient {
8818
9110
  const { result } = await this.postToRelayer(payload);
8819
9111
  return result;
8820
9112
  }
9113
+ async imSignTypedData(address, eip712Payload) {
9114
+ const { chainId } = await this.jsonRpcProvider.ready;
9115
+ const payload = {
9116
+ method: 'im_signTypedData',
9117
+ params: [{
9118
+ address,
9119
+ eip712Payload,
9120
+ chainId: getEip155ChainId(chainId),
9121
+ }],
9122
+ };
9123
+ const { result } = await this.postToRelayer(payload);
9124
+ return result;
9125
+ }
8821
9126
  }
8822
9127
 
8823
9128
  const MESSAGE_TO_SIGN = 'Only sign this message from Immutable Passport';
@@ -8958,6 +9263,60 @@ const sendTransaction = ({ params, magicProvider, jsonRpcProvider, relayerClient
8958
9263
  return relayerTransaction.hash;
8959
9264
  });
8960
9265
 
9266
+ const REQUIRED_TYPED_DATA_PROPERTIES = ['types', 'domain', 'primaryType', 'message'];
9267
+ const isValidTypedDataPayload = (typedData) => (REQUIRED_TYPED_DATA_PROPERTIES.every((key) => key in typedData));
9268
+ const transformTypedData = (typedData, chainId) => {
9269
+ let transformedTypedData;
9270
+ if (typeof typedData === 'string') {
9271
+ try {
9272
+ transformedTypedData = JSON.parse(typedData);
9273
+ }
9274
+ catch (err) {
9275
+ throw new JsonRpcError(RpcErrorCode.INVALID_PARAMS, `Failed to parse typed data JSON: ${err}`);
9276
+ }
9277
+ }
9278
+ else if (typeof typedData === 'object') {
9279
+ transformedTypedData = typedData;
9280
+ }
9281
+ else {
9282
+ throw new JsonRpcError(RpcErrorCode.INVALID_PARAMS, `Invalid typed data argument: ${typedData}`);
9283
+ }
9284
+ if (!isValidTypedDataPayload(transformedTypedData)) {
9285
+ throw new JsonRpcError(RpcErrorCode.INVALID_PARAMS, `Invalid typed data argument. The following properties are required: ${REQUIRED_TYPED_DATA_PROPERTIES.join(', ')}`);
9286
+ }
9287
+ const providedChainId = transformedTypedData.domain?.chainId;
9288
+ if (providedChainId) {
9289
+ // domain.chainId (if defined) can be a number, string, or hex value, but the relayer & guardian only accept a number.
9290
+ if (typeof providedChainId === 'string') {
9291
+ if (providedChainId.startsWith('0x')) {
9292
+ transformedTypedData.domain.chainId = parseInt(providedChainId, 16);
9293
+ }
9294
+ else {
9295
+ transformedTypedData.domain.chainId = parseInt(providedChainId, 10);
9296
+ }
9297
+ }
9298
+ if (transformedTypedData.domain.chainId !== chainId) {
9299
+ throw new JsonRpcError(RpcErrorCode.INVALID_PARAMS, `Invalid chainId, expected ${chainId}`);
9300
+ }
9301
+ }
9302
+ return transformedTypedData;
9303
+ };
9304
+ const signTypedDataV4 = async ({ params, method, magicProvider, jsonRpcProvider, relayerClient, guardianClient, user, }) => guardianClient
9305
+ .withConfirmationScreen({ width: 480, height: 730 })(async () => {
9306
+ const fromAddress = params[0];
9307
+ const typedDataParam = params[1];
9308
+ if (!fromAddress || !typedDataParam) {
9309
+ throw new JsonRpcError(RpcErrorCode.INVALID_PARAMS, `${method} requires an address and a typed data JSON`);
9310
+ }
9311
+ const { chainId } = await jsonRpcProvider.ready;
9312
+ const typedData = transformTypedData(typedDataParam, chainId);
9313
+ await guardianClient.validateMessage({ chainID: String(chainId), payload: typedData, user });
9314
+ const relayerSignature = await relayerClient.imSignTypedData(fromAddress, typedData);
9315
+ const magicWeb3Provider = new Web3Provider(magicProvider);
9316
+ const signer = magicWeb3Provider.getSigner();
9317
+ return getSignedTypedData(typedData, relayerSignature, BigNumber$1.from(chainId), fromAddress, signer);
9318
+ });
9319
+
8961
9320
  class ZkEvmProvider {
8962
9321
  authManager;
8963
9322
  config;
@@ -9041,6 +9400,21 @@ class ZkEvmProvider {
9041
9400
  case 'eth_accounts': {
9042
9401
  return this.isLoggedIn() ? [this.user.zkEvm.ethAddress] : [];
9043
9402
  }
9403
+ case 'eth_signTypedData':
9404
+ case 'eth_signTypedData_v4': {
9405
+ if (!this.isLoggedIn()) {
9406
+ throw new JsonRpcError(ProviderErrorCode.UNAUTHORIZED, 'Unauthorised - call eth_requestAccounts first');
9407
+ }
9408
+ return signTypedDataV4({
9409
+ method: request.method,
9410
+ params: request.params || [],
9411
+ magicProvider: this.magicProvider,
9412
+ jsonRpcProvider: this.jsonRpcProvider,
9413
+ relayerClient: this.relayerClient,
9414
+ user: this.user,
9415
+ guardianClient: this.guardianClient,
9416
+ });
9417
+ }
9044
9418
  // Pass through methods
9045
9419
  case 'eth_gasPrice':
9046
9420
  case 'eth_getBalance':
@@ -27361,6 +27735,8 @@ var $bc2bfebf768286d3$export$8cb0af6b2bed4b64;
27361
27735
 
27362
27736
 
27363
27737
 
27738
+
27739
+
27364
27740
  var $de275b98d2b651c3$export$788b1fd17f3dad84;
27365
27741
  (function(GasEstimateType) {
27366
27742
  GasEstimateType["BRIDGE_TO_L2"] = "BRIDGE_TO_L2";
@@ -27766,6 +28142,12 @@ var $4b58188d47aafe8d$export$537fa3efd10ed435;
27766
28142
  GasTokenType["NATIVE"] = "NATIVE";
27767
28143
  GasTokenType["ERC20"] = "ERC20";
27768
28144
  })($4b58188d47aafe8d$export$537fa3efd10ed435 || ($4b58188d47aafe8d$export$537fa3efd10ed435 = {}));
28145
+ var $4b58188d47aafe8d$export$3af78bb3e8650ee6;
28146
+ (function(FundingRouteType) {
28147
+ FundingRouteType["BRIDGE"] = "BRIDGE";
28148
+ FundingRouteType["ONRAMP"] = "ONRAMP";
28149
+ FundingRouteType["SWAP"] = "SWAP";
28150
+ })($4b58188d47aafe8d$export$3af78bb3e8650ee6 || ($4b58188d47aafe8d$export$3af78bb3e8650ee6 = {}));
27769
28151
 
27770
28152
 
27771
28153
  var $e055e79256bbc1dd$export$80f4da0d409a629d;
@@ -27811,6 +28193,7 @@ var $e055e79256bbc1dd$export$80f4da0d409a629d;
27811
28193
  CheckoutErrorType["EXECUTE_FULFILMENT_TRANSACTION_ERROR"] = "EXECUTE_FULFILMENT_TRANSACTION_ERROR";
27812
28194
  CheckoutErrorType["SIGN_MESSAGE_ERROR"] = "SIGN_MESSAGE_ERROR";
27813
28195
  CheckoutErrorType["BRIDGE_GAS_ESTIMATE_ERROR"] = "BRIDGE_GAS_ESTIMATE_ERROR";
28196
+ CheckoutErrorType["ORDER_FEE_ERROR"] = "ORDER_FEE_ERROR";
27814
28197
  })($a8bc256d81a5e2c1$export$e3dc0620abde7f5a || ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a = {}));
27815
28198
  class $a8bc256d81a5e2c1$export$b722478a3cbfa3bc extends Error {
27816
28199
  message;
@@ -29457,12 +29840,6 @@ var $b23305044c0e096a$export$3057de18ac0c076;
29457
29840
  RouteCalculatorType["NO_ROUTES"] = "NO_ROUTES";
29458
29841
  RouteCalculatorType["NO_OPTIONS"] = "NO_OPTIONS";
29459
29842
  })($b23305044c0e096a$export$3057de18ac0c076 || ($b23305044c0e096a$export$3057de18ac0c076 = {}));
29460
- var $b23305044c0e096a$export$3af78bb3e8650ee6;
29461
- (function(FundingRouteType) {
29462
- FundingRouteType["BRIDGE"] = "BRIDGE";
29463
- FundingRouteType["ON_RAMP"] = "ONRAMP";
29464
- FundingRouteType["SWAP"] = "SWAP";
29465
- })($b23305044c0e096a$export$3af78bb3e8650ee6 || ($b23305044c0e096a$export$3af78bb3e8650ee6 = {}));
29466
29843
 
29467
29844
 
29468
29845
 
@@ -29522,7 +29899,6 @@ const $33acec7b4a26c053$export$23ddeb2642d2f9d = async (config, readOnlyProvider
29522
29899
 
29523
29900
 
29524
29901
 
29525
-
29526
29902
  const $f730af3b727f04ac$export$22fea095b15361de = (balances)=>{
29527
29903
  for (const balance of balances.balances){
29528
29904
  if (!balance.token.address || balance.token.address === "") return balance.balance;
@@ -29606,6 +29982,18 @@ const $5a5ccedc98d53d25$var$filterTokens = (allowedTokens, balances)=>{
29606
29982
  });
29607
29983
  return [];
29608
29984
  };
29985
+ const $5a5ccedc98d53d25$export$9ec9fc71f3ce62c4 = async (config, availableRoutingOptions)=>{
29986
+ if (availableRoutingOptions.onRamp) {
29987
+ const onRampOptions = await config.remote.getConfig("onramp");
29988
+ const onRampAllowList = {};
29989
+ Object.entries(onRampOptions).forEach(([onRampProvider, onRampProviderConfig])=>{
29990
+ // Allowed list per onRamp provider
29991
+ onRampAllowList[onRampProvider] = onRampProviderConfig.tokens ?? [];
29992
+ });
29993
+ return onRampAllowList;
29994
+ }
29995
+ return {};
29996
+ };
29609
29997
  const $5a5ccedc98d53d25$export$d744af9f1c0712bc = async (config, tokenBalances, availableRoutingOptions)=>{
29610
29998
  if (availableRoutingOptions.bridge) {
29611
29999
  const allowedTokens = (await config.remote.getConfig("bridge"))?.tokens ?? [];
@@ -29614,6 +30002,21 @@ const $5a5ccedc98d53d25$export$d744af9f1c0712bc = async (config, tokenBalances,
29614
30002
  }
29615
30003
  return [];
29616
30004
  };
30005
+ const $5a5ccedc98d53d25$export$87ed7f956d73690 = async (config, tokenBalances, availableRoutingOptions)=>{
30006
+ if (availableRoutingOptions.swap) {
30007
+ const allowedTokens = (await config.remote.getConfig("dex"))?.tokens ?? [];
30008
+ const balances = tokenBalances.get(($4013c5c91bb535f6$export$c9af4e4b001c6476)(config));
30009
+ return $5a5ccedc98d53d25$var$filterTokens(allowedTokens, balances);
30010
+ }
30011
+ return [];
30012
+ };
30013
+ const $5a5ccedc98d53d25$export$1ad29657d49c5440 = async (config, tokenBalances, availableRoutingOptions)=>{
30014
+ const tokenAllowList = {};
30015
+ tokenAllowList.swap = await $5a5ccedc98d53d25$export$87ed7f956d73690(config, tokenBalances, availableRoutingOptions);
30016
+ tokenAllowList.bridge = await $5a5ccedc98d53d25$export$d744af9f1c0712bc(config, tokenBalances, availableRoutingOptions);
30017
+ tokenAllowList.onRamp = await $5a5ccedc98d53d25$export$9ec9fc71f3ce62c4(config, availableRoutingOptions);
30018
+ return tokenAllowList;
30019
+ };
29617
30020
 
29618
30021
 
29619
30022
  const $fa9ac5bfdbbf9dfa$export$9994ad18c2f0e665 = (balances, totalFees)=>{
@@ -29641,14 +30044,14 @@ const $fa9ac5bfdbbf9dfa$export$952cdf461a00a8c6 = async (config, balanceRequirem
29641
30044
  return l1address;
29642
30045
  };
29643
30046
  const $fa9ac5bfdbbf9dfa$export$da05aed50d75046 = async (config, readOnlyProviders, feeEstimates)=>{
29644
- let bridgeFeeEstimate = feeEstimates.get(($b23305044c0e096a$export$3af78bb3e8650ee6).BRIDGE);
30047
+ let bridgeFeeEstimate = feeEstimates.get(($4b58188d47aafe8d$export$3af78bb3e8650ee6).BRIDGE);
29645
30048
  if (bridgeFeeEstimate) return bridgeFeeEstimate;
29646
30049
  bridgeFeeEstimate = await ($8a49d1a3783a2640$export$3aff971444a4f244)(config, readOnlyProviders);
29647
- feeEstimates.set(($b23305044c0e096a$export$3af78bb3e8650ee6).BRIDGE, bridgeFeeEstimate);
30050
+ feeEstimates.set(($4b58188d47aafe8d$export$3af78bb3e8650ee6).BRIDGE, bridgeFeeEstimate);
29648
30051
  return bridgeFeeEstimate;
29649
30052
  };
29650
30053
  const $fa9ac5bfdbbf9dfa$var$constructBridgeFundingRoute = (chainId, balance)=>({
29651
- type: ($b23305044c0e096a$export$3af78bb3e8650ee6).BRIDGE,
30054
+ type: ($4b58188d47aafe8d$export$3af78bb3e8650ee6).BRIDGE,
29652
30055
  chainId: chainId,
29653
30056
  asset: {
29654
30057
  balance: balance.balance,
@@ -29704,6 +30107,7 @@ const $fa9ac5bfdbbf9dfa$export$ddc7ba2b57d7c5fa = async (config, readOnlyProvide
29704
30107
 
29705
30108
 
29706
30109
 
30110
+
29707
30111
  async function $0e0060cb42e136d2$export$339cb2be73677b30(config, existingReadOnlyProviders) {
29708
30112
  if (config.isProduction && existingReadOnlyProviders?.has(($0472f23319457bfb$export$c06e1e7429de6283).ETHEREUM)) return existingReadOnlyProviders;
29709
30113
  if (existingReadOnlyProviders?.has(($0472f23319457bfb$export$c06e1e7429de6283).SEPOLIA)) return existingReadOnlyProviders;
@@ -29721,16 +30125,199 @@ async function $0e0060cb42e136d2$export$339cb2be73677b30(config, existingReadOnl
29721
30125
 
29722
30126
 
29723
30127
 
30128
+
30129
+
30130
+
30131
+
30132
+
30133
+ const $049bba630af05555$export$6946a1f17c2bbf26 = async (config, chainId, walletAddress, requiredToken, swappableTokens)=>{
30134
+ const dexQuotes = new Map();
30135
+ try {
30136
+ const exchange = await $67fc622a2b913d5f$export$7cf6178417769841(chainId, config);
30137
+ const dexTransactionResponsePromises = [];
30138
+ // Create a quote for each swappable token
30139
+ for (const swappableToken of swappableTokens)dexTransactionResponsePromises.push(exchange.getUnsignedSwapTxFromAmountOut(walletAddress, swappableToken, requiredToken.address, requiredToken.amount));
30140
+ // Resolve all the quotes and link them back to the swappable token
30141
+ // The swappable token array is in the same position in the array as the quote in the promise array
30142
+ const dexTransactionResponse = await Promise.all(dexTransactionResponsePromises);
30143
+ dexTransactionResponse.forEach((response, index)=>{
30144
+ const swappableToken = swappableTokens[index];
30145
+ dexQuotes.set(swappableToken, {
30146
+ quote: response.quote,
30147
+ approval: response.approval?.gasFeeEstimate,
30148
+ swap: response.swap.gasFeeEstimate
30149
+ });
30150
+ });
30151
+ return dexQuotes;
30152
+ } catch {
30153
+ return dexQuotes;
30154
+ }
30155
+ };
30156
+
30157
+
30158
+ const $3ee85f12225c19f3$export$fb80fe94a81a3132 = async (config, dexQuoteCache, walletAddress, requiredToken, swappableTokens)=>{
30159
+ const dexQuotes = dexQuoteCache.get(requiredToken.address);
30160
+ if (dexQuotes) return dexQuotes;
30161
+ const quotes = await ($049bba630af05555$export$6946a1f17c2bbf26)(config, ($4013c5c91bb535f6$export$c9af4e4b001c6476)(config), walletAddress, requiredToken, swappableTokens);
30162
+ dexQuoteCache.set(requiredToken.address, quotes);
30163
+ return quotes;
30164
+ };
30165
+
30166
+
30167
+ const $91807edfd7057288$export$85e4d8628aabb217 = (balanceRequirement)=>{
30168
+ let address = "";
30169
+ let amount = (BigNumber$1).from(0);
30170
+ switch(balanceRequirement.type){
30171
+ case ($4b58188d47aafe8d$export$1fc8f52ad1810e52).ERC20:
30172
+ address = balanceRequirement.required.token.address ?? "";
30173
+ amount = balanceRequirement.delta.balance;
30174
+ break;
30175
+ case ($4b58188d47aafe8d$export$1fc8f52ad1810e52).NATIVE:
30176
+ address = ($d85ad1457a3f1a83$export$b80040cb173ba6e9);
30177
+ amount = balanceRequirement.delta.balance;
30178
+ break;
30179
+ }
30180
+ return {
30181
+ address: address,
30182
+ amount: amount
30183
+ };
30184
+ };
30185
+ const $91807edfd7057288$export$7b6318fc1a8067b3 = (l2Balances, approval)=>{
30186
+ // Check if approval required
30187
+ if (!approval) return {
30188
+ sufficient: true,
30189
+ approvalGasFee: (BigNumber$1).from(0),
30190
+ approvalGasTokenAddress: ""
30191
+ };
30192
+ const approvalGasFee = approval.value;
30193
+ const approvalGasTokenAddress = approval.token.address;
30194
+ // No balance on L2 to cover approval fees
30195
+ if (l2Balances.length === 0) return {
30196
+ sufficient: false,
30197
+ approvalGasFee: approvalGasFee,
30198
+ approvalGasTokenAddress: approvalGasTokenAddress
30199
+ };
30200
+ // Find the users balance of the approval token
30201
+ const l2BalanceOfApprovalToken = l2Balances.find((balance)=>balance.token.address === approvalGasTokenAddress);
30202
+ if (!l2BalanceOfApprovalToken) return {
30203
+ sufficient: false,
30204
+ approvalGasFee: approvalGasFee,
30205
+ approvalGasTokenAddress: approvalGasTokenAddress
30206
+ };
30207
+ // If the user does not have enough of the token to cover approval fees then return sufficient false
30208
+ if (l2BalanceOfApprovalToken.balance.lt(approvalGasFee)) return {
30209
+ sufficient: false,
30210
+ approvalGasFee: approvalGasFee,
30211
+ approvalGasTokenAddress: approvalGasTokenAddress
30212
+ };
30213
+ // The user has enough to cover approval gas fees
30214
+ return {
30215
+ sufficient: true,
30216
+ approvalGasFee: approvalGasFee,
30217
+ approvalGasTokenAddress: approvalGasTokenAddress
30218
+ };
30219
+ };
30220
+ const $91807edfd7057288$export$38077235fe748d40 = (l2Balances, swapFees, approvalFees, tokenBeingSwapped)=>{
30221
+ // Set up a map of token addresses to amounts for each of the swap fees
30222
+ const feeMap = new Map();
30223
+ // Add the approval fee to list of fees
30224
+ if (approvalFees.approvalGasTokenAddress !== "") feeMap.set(approvalFees.approvalGasTokenAddress, approvalFees.approvalGasFee);
30225
+ // Add the token being swapped to list of fees to ensure the user can cover the fee + the token swap
30226
+ if (tokenBeingSwapped) {
30227
+ const fee = feeMap.get(tokenBeingSwapped.address);
30228
+ if (fee) feeMap.set(tokenBeingSwapped.address, fee.add(tokenBeingSwapped.amount));
30229
+ else feeMap.set(tokenBeingSwapped.address, tokenBeingSwapped.amount);
30230
+ }
30231
+ // Get all the fees and key them by their token id
30232
+ for (const swapFee of swapFees){
30233
+ const fee = feeMap.get(swapFee.amount.token.address);
30234
+ if (fee) {
30235
+ feeMap.set(swapFee.amount.token.address, fee.add(swapFee.amount.value));
30236
+ continue;
30237
+ }
30238
+ feeMap.set(swapFee.amount.token.address, swapFee.amount.value);
30239
+ }
30240
+ // Go through the map and for each token address check if the user has enough balance to cover the fee
30241
+ for (const [tokenAddress, fee] of feeMap.entries()){
30242
+ if (fee === (BigNumber$1).from(0)) continue;
30243
+ const l2BalanceOfFeeToken = l2Balances.find((balance)=>balance.token.address === tokenAddress);
30244
+ if (!l2BalanceOfFeeToken) return false;
30245
+ if (l2BalanceOfFeeToken.balance.lt(fee)) return false;
30246
+ }
30247
+ return true;
30248
+ };
30249
+ const $91807edfd7057288$export$8e03ea04d59f2402 = async (config, availableRoutingOptions, dexQuoteCache, walletAddress, balanceRequirement, tokenBalanceResults, swappableTokens)=>{
30250
+ if (!availableRoutingOptions.swap) return undefined;
30251
+ if (swappableTokens.length === 0) return undefined;
30252
+ const requiredToken = $91807edfd7057288$export$85e4d8628aabb217(balanceRequirement);
30253
+ if (requiredToken.address === "") return undefined;
30254
+ const l2TokenBalanceResult = tokenBalanceResults.get(($4013c5c91bb535f6$export$c9af4e4b001c6476)(config));
30255
+ if (!l2TokenBalanceResult) return undefined;
30256
+ const l2Balances = l2TokenBalanceResult.balances;
30257
+ if (l2Balances.length === 0) return undefined;
30258
+ const quotes = await ($3ee85f12225c19f3$export$fb80fe94a81a3132)(config, dexQuoteCache, walletAddress, requiredToken, swappableTokens);
30259
+ const quoteTokenAddresses = Array.from(quotes.keys());
30260
+ for (const quoteTokenAddress of quoteTokenAddresses){
30261
+ const quote = quotes.get(quoteTokenAddress);
30262
+ if (!quote) continue;
30263
+ // Find the balance the user has for this quoted token
30264
+ const userBalanceOfQuotedToken = l2Balances.find((balance)=>balance.token.address === quoteTokenAddress);
30265
+ // If no balance found on L2 for this quoted token then continue
30266
+ if (!userBalanceOfQuotedToken) continue;
30267
+ // Check the amount of quoted token required against the user balance
30268
+ const amountOfQuoteTokenRequired = quote.quote.amount;
30269
+ // If user does not have enough balance to perform the swap with this token then continue
30270
+ if (userBalanceOfQuotedToken.balance.lt(amountOfQuoteTokenRequired.value)) continue;
30271
+ const approvalFees = $91807edfd7057288$export$7b6318fc1a8067b3(l2Balances, quote.approval);
30272
+ // If user does not have enough to cover approval fees then continue
30273
+ if (!approvalFees.sufficient) continue;
30274
+ // If user does not have enough to cover swap fees then continue
30275
+ if (!$91807edfd7057288$export$38077235fe748d40(l2Balances, quote.quote.fees, approvalFees, {
30276
+ amount: amountOfQuoteTokenRequired.value,
30277
+ address: quoteTokenAddress
30278
+ })) continue;
30279
+ // User has sufficient funds to cover any approval and swap fees so use this token for the funding route
30280
+ // Currently we are not prioritising any particular token so just taking the first sufficient token
30281
+ return {
30282
+ type: ($4b58188d47aafe8d$export$3af78bb3e8650ee6).SWAP,
30283
+ chainId: ($4013c5c91bb535f6$export$c9af4e4b001c6476)(config),
30284
+ asset: {
30285
+ balance: userBalanceOfQuotedToken.balance,
30286
+ formattedBalance: userBalanceOfQuotedToken.formattedBalance,
30287
+ token: userBalanceOfQuotedToken.token
30288
+ }
30289
+ };
30290
+ }
30291
+ return undefined;
30292
+ };
30293
+
30294
+
30295
+
30296
+
30297
+
29724
30298
  const $c16168a9c28ae4fd$export$31ce7ba1a2956195 = (balanceRequirements)=>{
29725
30299
  let insufficientBalanceCount = 0;
29726
- let insufficientBridgeRequirement;
30300
+ let insufficientRequirement;
29727
30301
  for (const balanceRequirement of balanceRequirements.balanceRequirements)if (!balanceRequirement.sufficient) {
29728
30302
  insufficientBalanceCount++;
29729
- insufficientBridgeRequirement = balanceRequirement;
30303
+ insufficientRequirement = balanceRequirement;
29730
30304
  }
29731
- if (insufficientBalanceCount === 1) return insufficientBridgeRequirement;
30305
+ if (insufficientBalanceCount === 1) return insufficientRequirement;
29732
30306
  return undefined;
29733
30307
  };
30308
+ const $c16168a9c28ae4fd$export$c39a7b7dc167cdb4 = async (config, availableRoutingOptions, insufficientRequirement, dexQuoteCache, ownerAddress, tokenBalances, swapTokenAllowList)=>{
30309
+ if (!availableRoutingOptions.swap) return undefined;
30310
+ if (insufficientRequirement === undefined) return undefined;
30311
+ if (swapTokenAllowList === undefined) return undefined;
30312
+ const tokenBalanceResult = tokenBalances.get(($4013c5c91bb535f6$export$c9af4e4b001c6476)(config));
30313
+ if (!tokenBalanceResult) return undefined;
30314
+ if (tokenBalanceResult.error !== undefined || !tokenBalanceResult.success) return undefined;
30315
+ if (swapTokenAllowList.length === 0) return undefined;
30316
+ const swappableTokens = swapTokenAllowList.filter((token)=>token.address).map((token)=>token.address);
30317
+ if (swappableTokens.length === 0) return undefined;
30318
+ const swapFundingStep = await ($91807edfd7057288$export$8e03ea04d59f2402)(config, availableRoutingOptions, dexQuoteCache, ownerAddress, insufficientRequirement, tokenBalances, swappableTokens);
30319
+ return swapFundingStep;
30320
+ };
29734
30321
  const $c16168a9c28ae4fd$export$92606e71d0a264ff = async (config, ownerAddress, balanceRequirements, availableRoutingOptions)=>{
29735
30322
  let readOnlyProviders;
29736
30323
  try {
@@ -29741,40 +30328,52 @@ const $c16168a9c28ae4fd$export$92606e71d0a264ff = async (config, ownerAddress, b
29741
30328
  });
29742
30329
  }
29743
30330
  const tokenBalances = await ($33acec7b4a26c053$export$23ddeb2642d2f9d)(config, readOnlyProviders, ownerAddress, availableRoutingOptions);
30331
+ const allowList = await ($5a5ccedc98d53d25$export$1ad29657d49c5440)(config, tokenBalances, availableRoutingOptions);
29744
30332
  // Bridge and swap fee cache
29745
30333
  const feeEstimates = new Map();
29746
- // Ensures only 1 balance requirement is insufficient otherwise one bridge route cannot be recommended
29747
- let bridgeFundingStep;
30334
+ // Dex quotes cache
30335
+ const dexQuoteCache = new Map();
30336
+ // Ensures only 1 balance requirement is insufficient otherwise one bridge or one swap route cannot be recommended
29748
30337
  const insufficientRequirement = $c16168a9c28ae4fd$export$31ce7ba1a2956195(balanceRequirements);
30338
+ let bridgeFundingStep;
29749
30339
  if (availableRoutingOptions.bridge && insufficientRequirement) bridgeFundingStep = await ($fa9ac5bfdbbf9dfa$export$ddc7ba2b57d7c5fa)(config, readOnlyProviders, ownerAddress, availableRoutingOptions, insufficientRequirement, tokenBalances, feeEstimates);
30340
+ const swapFundingStep = await $c16168a9c28ae4fd$export$c39a7b7dc167cdb4(config, availableRoutingOptions, insufficientRequirement, dexQuoteCache, ownerAddress, tokenBalances, allowList.swap);
29750
30341
  // Check on-ramp routes
29751
30342
  // Check swap routes
29752
30343
  // > Could bridge first
29753
30344
  // > Could on-ramp first
29754
30345
  // > Could double swap
29755
- if (bridgeFundingStep) return {
29756
- availableOptions: [],
29757
- response: {
29758
- type: ($b23305044c0e096a$export$3057de18ac0c076).ROUTES_FOUND,
29759
- message: "Routes found"
29760
- },
29761
- fundingRoutes: [
29762
- {
29763
- priority: 1,
29764
- steps: [
29765
- bridgeFundingStep
29766
- ]
29767
- }
29768
- ]
29769
- };
29770
- return {
29771
- availableOptions: [],
30346
+ const response = {
29772
30347
  response: {
29773
30348
  type: ($b23305044c0e096a$export$3057de18ac0c076).NO_ROUTES,
29774
30349
  message: "Routes not found"
29775
30350
  },
29776
30351
  fundingRoutes: []
29777
30352
  };
30353
+ let priority = 0;
30354
+ if (bridgeFundingStep || swapFundingStep) {
30355
+ response.response.type = ($b23305044c0e096a$export$3057de18ac0c076).ROUTES_FOUND;
30356
+ response.response.message = "Routes found";
30357
+ }
30358
+ if (bridgeFundingStep) {
30359
+ priority++;
30360
+ response.fundingRoutes.push({
30361
+ priority: priority,
30362
+ steps: [
30363
+ bridgeFundingStep
30364
+ ]
30365
+ });
30366
+ }
30367
+ if (swapFundingStep) {
30368
+ priority++;
30369
+ response.fundingRoutes.push({
30370
+ priority: priority,
30371
+ steps: [
30372
+ swapFundingStep
30373
+ ]
30374
+ });
30375
+ }
30376
+ return response;
29778
30377
  };
29779
30378
 
29780
30379
 
@@ -30098,27 +30697,80 @@ const $9c3db1bb9c8b69d3$export$70b61ad426ddbe54 = async (config, provider, order
30098
30697
 
30099
30698
 
30100
30699
 
30700
+
30701
+
30702
+
30703
+
30704
+ const $9051cee080948594$export$9ac1563efd38130 = 1; // 100%
30705
+ const $9051cee080948594$export$768e717351d4b176 = 6; // will allow 0.000001 (0.0001%) as the minimum value
30706
+ const $9051cee080948594$var$calculateFeesPercent = (orderFee, amountBn)=>{
30707
+ const feePercentage = orderFee.amount;
30708
+ // note: multiply in and out of the maximum decimal places to the power of ten to do the math in big number integers
30709
+ const feePercentageMultiplier = Math.round(feePercentage.percentageDecimal * 10 ** $9051cee080948594$export$768e717351d4b176);
30710
+ const bnFeeAmount = amountBn.mul((BigNumber$1).from(feePercentageMultiplier)).div(10 ** $9051cee080948594$export$768e717351d4b176);
30711
+ return bnFeeAmount;
30712
+ };
30713
+ const $9051cee080948594$var$calculateFeesToken = (orderFee, decimals)=>{
30714
+ const feeToken = orderFee.amount;
30715
+ const bnFeeAmount = (parseUnits$1)(feeToken.token, decimals);
30716
+ return bnFeeAmount;
30717
+ };
30718
+ const $9051cee080948594$export$1e69c9cfc42e28d8 = (orderFees, weiAmount, decimals = 18)=>{
30719
+ let totalTokenFees = (BigNumber$1).from(0);
30720
+ const amountBn = (BigNumber$1).from(weiAmount);
30721
+ // note: multiply in and out of the maximum decimal places to the power of ten to do the math in big number integers
30722
+ const totalAllowableFees = amountBn.mul($9051cee080948594$export$9ac1563efd38130 * 10 ** $9051cee080948594$export$768e717351d4b176).div(10 ** $9051cee080948594$export$768e717351d4b176);
30723
+ const calculateFeesResult = [];
30724
+ for (const orderFee of orderFees){
30725
+ let currentFeeBn = (BigNumber$1).from(0);
30726
+ if (Object.hasOwn(orderFee.amount, "percentageDecimal")) {
30727
+ currentFeeBn = $9051cee080948594$var$calculateFeesPercent(orderFee, amountBn);
30728
+ totalTokenFees = totalTokenFees.add(currentFeeBn);
30729
+ } else if (Object.hasOwn(orderFee.amount, "token")) {
30730
+ currentFeeBn = $9051cee080948594$var$calculateFeesToken(orderFee, decimals);
30731
+ totalTokenFees = totalTokenFees.add(currentFeeBn);
30732
+ } else throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Unknown fee type parsed, must be percentageDecimal or token", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).ORDER_FEE_ERROR);
30733
+ if (totalTokenFees.gt(totalAllowableFees)) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)(`The combined fees are above the allowed maximum of ${$9051cee080948594$export$9ac1563efd38130 * 100}%`, ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).ORDER_FEE_ERROR);
30734
+ if (currentFeeBn.gt(0)) calculateFeesResult.push({
30735
+ amount: currentFeeBn.toString(),
30736
+ recipient: orderFee.recipient
30737
+ });
30738
+ } // for
30739
+ return calculateFeesResult;
30740
+ };
30741
+
30742
+
30101
30743
  const $9085b221b72ac69e$export$af768ccdf17d5c04 = (id, contractAddress, spenderAddress)=>({
30102
30744
  type: ($4b58188d47aafe8d$export$1fc8f52ad1810e52).ERC721,
30103
30745
  id: id,
30104
30746
  contractAddress: contractAddress,
30105
30747
  spenderAddress: spenderAddress
30106
30748
  });
30107
- const $9085b221b72ac69e$export$586d02673c66d423 = (buyToken)=>{
30749
+ const $9085b221b72ac69e$export$586d02673c66d423 = (buyToken, decimals = 18)=>{
30750
+ const bnAmount = (parseUnits$1)(buyToken.amount, decimals);
30108
30751
  if (buyToken.type === ($4b58188d47aafe8d$export$1fc8f52ad1810e52).NATIVE) return {
30109
30752
  type: ($4b58188d47aafe8d$export$1fc8f52ad1810e52).NATIVE,
30110
- amount: buyToken.amount.toString()
30753
+ amount: bnAmount.toString()
30111
30754
  };
30112
30755
  return {
30113
30756
  type: ($4b58188d47aafe8d$export$1fc8f52ad1810e52).ERC20,
30114
- amount: buyToken.amount.toString(),
30757
+ amount: bnAmount.toString(),
30115
30758
  contractAddress: buyToken.contractAddress
30116
30759
  };
30117
30760
  };
30118
- const $9085b221b72ac69e$export$e761f9e0703de895 = async (config, provider, id, contractAddress, buyToken)=>{
30761
+ const $9085b221b72ac69e$export$e761f9e0703de895 = async (config, provider, orders)=>{
30119
30762
  let orderbook;
30120
30763
  let listing;
30121
30764
  let spenderAddress = "";
30765
+ if (orders.length === 0) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("No orders were parsed, must parse at least one order", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).PREPARE_ORDER_LISTING_ERROR);
30766
+ const { buyToken: buyToken, sellToken: sellToken, makerFees: makerFees } = orders[0];
30767
+ let decimals = 18;
30768
+ if (buyToken.type === ($4b58188d47aafe8d$export$1fc8f52ad1810e52).ERC20) {
30769
+ // get this from the allowed list
30770
+ const buyTokenContract = new (Contract$1)(buyToken.contractAddress, JSON.stringify(($d85ad1457a3f1a83$export$db5daa1b5156ccfe)), provider);
30771
+ decimals = buyTokenContract.decimals();
30772
+ }
30773
+ const buyTokenOrNative = $9085b221b72ac69e$export$586d02673c66d423(buyToken, decimals);
30122
30774
  try {
30123
30775
  const walletAddress = await provider.getSigner().getAddress();
30124
30776
  orderbook = await $67fc622a2b913d5f$export$c60ce6c6a92bc2ff(config);
@@ -30126,22 +30778,22 @@ const $9085b221b72ac69e$export$e761f9e0703de895 = async (config, provider, id, c
30126
30778
  spenderAddress = seaportContractAddress;
30127
30779
  listing = await orderbook.prepareListing({
30128
30780
  makerAddress: walletAddress,
30129
- buy: $9085b221b72ac69e$export$586d02673c66d423(buyToken),
30781
+ buy: buyTokenOrNative,
30130
30782
  sell: {
30131
30783
  type: (0, $4b58188d47aafe8d$export$1fc8f52ad1810e52).ERC721,
30132
- contractAddress: contractAddress,
30133
- tokenId: id
30784
+ contractAddress: sellToken.collectionAddress,
30785
+ tokenId: sellToken.id
30134
30786
  }
30135
30787
  });
30136
30788
  } catch (err) {
30137
30789
  throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("An error occurred while preparing the listing", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).PREPARE_ORDER_LISTING_ERROR, {
30138
30790
  message: err.message,
30139
- id: id,
30140
- collectionAddress: contractAddress
30791
+ id: sellToken.id,
30792
+ collectionAddress: sellToken.collectionAddress
30141
30793
  });
30142
30794
  }
30143
30795
  const itemRequirements = [
30144
- $9085b221b72ac69e$export$af768ccdf17d5c04(id, contractAddress, spenderAddress)
30796
+ $9085b221b72ac69e$export$af768ccdf17d5c04(sellToken.id, sellToken.collectionAddress, spenderAddress)
30145
30797
  ];
30146
30798
  const smartCheckoutResult = await ($0e7419077c373b24$export$9e073f9ada8c81e6)(config, provider, itemRequirements, {
30147
30799
  type: ($4b58188d47aafe8d$export$65c64e46348ee3c1).GAS,
@@ -30155,15 +30807,15 @@ const $9085b221b72ac69e$export$e761f9e0703de895 = async (config, provider, id, c
30155
30807
  if (!unsignedMessage) // For sell it is expected the orderbook will always return an unsigned message
30156
30808
  // If for some reason it is missing then we cannot proceed with the create listing
30157
30809
  throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("The unsigned message is missing after preparing the listing", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).SIGN_MESSAGE_ERROR, {
30158
- id: id,
30159
- collectionAddress: contractAddress
30810
+ id: sellToken.id,
30811
+ collectionAddress: sellToken.collectionAddress
30160
30812
  });
30161
30813
  const signedMessage = await ($25ac589234c10b67$export$1d9a7a8a40780de)(provider, unsignedMessage);
30162
30814
  const unsignedTransactions = await ($a7367d01c6e76b1c$export$b087719c36e0f2dc)(listing.actions);
30163
30815
  const approvalResult = await ($25ac589234c10b67$export$19693ca396db083e)(provider, unsignedTransactions.approvalTransactions);
30164
30816
  if (approvalResult.type === ($d855a5ba32004345$export$f51b97f3aaf2d5a8).FAILED) return {
30165
- id: id,
30166
- collectionAddress: contractAddress,
30817
+ id: sellToken.id,
30818
+ collectionAddress: sellToken.collectionAddress,
30167
30819
  smartCheckoutResult: smartCheckoutResult,
30168
30820
  status: {
30169
30821
  type: ($c2874b006e92b115$export$a9780122aaa0801a).FAILED,
@@ -30172,23 +30824,31 @@ const $9085b221b72ac69e$export$e761f9e0703de895 = async (config, provider, id, c
30172
30824
  }
30173
30825
  };
30174
30826
  let orderId = "";
30827
+ const createListingParams = {
30828
+ orderComponents: signedMessage.orderComponents,
30829
+ orderHash: signedMessage.orderHash,
30830
+ orderSignature: signedMessage.signedMessage
30831
+ };
30832
+ if (makerFees !== undefined) {
30833
+ const orderBookFees = ($9051cee080948594$export$1e69c9cfc42e28d8)(makerFees, buyTokenOrNative.amount, decimals);
30834
+ // @TODO add support for an array of fees when the orderbook enables it
30835
+ if (orderBookFees.length !== makerFees.length) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("One of the fees is too small, must be greater than 0.000001", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).CREATE_ORDER_LISTING_ERROR);
30836
+ const [makerFee] = orderBookFees;
30837
+ createListingParams.makerFee = makerFee;
30838
+ }
30175
30839
  try {
30176
- const order = await orderbook.createListing({
30177
- orderComponents: signedMessage.orderComponents,
30178
- orderHash: signedMessage.orderHash,
30179
- orderSignature: signedMessage.signedMessage
30180
- });
30840
+ const order = await orderbook.createListing(createListingParams);
30181
30841
  orderId = order.result.id;
30182
30842
  } catch (err) {
30183
30843
  throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("An error occurred while creating the listing", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).CREATE_ORDER_LISTING_ERROR, {
30184
30844
  message: err.message,
30185
- id: id,
30186
- collectionAddress: contractAddress
30845
+ collectionId: sellToken.id,
30846
+ collectionAddress: sellToken.collectionAddress
30187
30847
  });
30188
30848
  }
30189
30849
  return {
30190
- id: id,
30191
- collectionAddress: contractAddress,
30850
+ id: sellToken.id,
30851
+ collectionAddress: sellToken.collectionAddress,
30192
30852
  smartCheckoutResult: smartCheckoutResult,
30193
30853
  status: {
30194
30854
  type: ($c2874b006e92b115$export$a9780122aaa0801a).SUCCESS,
@@ -30197,8 +30857,8 @@ const $9085b221b72ac69e$export$e761f9e0703de895 = async (config, provider, id, c
30197
30857
  };
30198
30858
  }
30199
30859
  return {
30200
- id: id,
30201
- collectionAddress: contractAddress,
30860
+ id: sellToken.id,
30861
+ collectionAddress: sellToken.collectionAddress,
30202
30862
  smartCheckoutResult: smartCheckoutResult
30203
30863
  };
30204
30864
  };
@@ -30384,12 +31044,16 @@ class $a8cb37a3fc8eb863$export$1f60ba4ec72508a0 {
30384
31044
  /**
30385
31045
  * Determines the requirements for performing a sell.
30386
31046
  * @param {SellParams} params - The parameters for the sell.
31047
+ * Only currently actions the first order in the array until we support batch processing.
31048
+ * Only currently actions the first fee in the fees array of each order until we support multiple fees.
30387
31049
  */ async sell(params) {
30388
31050
  if (this.config.isProduction) throw new Error("This endpoint is not currently available.");
30389
31051
  // eslint-disable-next-line no-console
30390
31052
  console.warn("This endpoint is currently under construction.");
31053
+ if (params.orders.length > 1) // eslint-disable-next-line no-console
31054
+ console.warn("This endpoint currently only actions the first order in the array.");
30391
31055
  const web3Provider = await $bb88265fe45a0393$export$9e1fd9cc88c637a0(this.config, params.provider);
30392
- await $9085b221b72ac69e$export$e761f9e0703de895(this.config, web3Provider, params.id, params.collectionAddress, params.buyToken);
31056
+ await $9085b221b72ac69e$export$e761f9e0703de895(this.config, web3Provider, params.orders);
30393
31057
  }
30394
31058
  /**
30395
31059
  * Cancels a sell.
@@ -30487,31 +31151,30 @@ var checkout_sdk = /*#__PURE__*/Object.freeze({
30487
31151
  function $parcel$export(e, n, v, s) {
30488
31152
  Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
30489
31153
  }
30490
- const $d663162fd5a0853f$export$38a083d9fb5551ca = "0.17.6";
31154
+ const $d663162fd5a0853f$export$38a083d9fb5551ca = "0.18.1";
30491
31155
  const $d663162fd5a0853f$export$83bf90b30cdfd29f = ()=>false;
30492
31156
  const $d663162fd5a0853f$export$1169f5475725171b = ()=>$d663162fd5a0853f$export$38a083d9fb5551ca;
30493
31157
 
30494
31158
 
30495
31159
  function $430e3eda76fa4d5f$export$46b1ae20f762ad4c(version) {
30496
31160
  const defaultPackageVersion = ($d663162fd5a0853f$export$1169f5475725171b)();
30497
- if (version === undefined) return defaultPackageVersion;
30498
- // Pre-production release
30499
- // TODO: https://immutable.atlassian.net/browse/WT-1501
30500
- if (version.major === undefined || version.minor === undefined || version.patch === undefined || version.prerelease === undefined) return defaultPackageVersion;
30501
- if (version.major < 0) return defaultPackageVersion;
30502
- if (version.minor < 0) return defaultPackageVersion;
30503
- if (version.patch < 0) return defaultPackageVersion;
30504
- if (version.prerelease !== "alpha") return defaultPackageVersion;
31161
+ if (version === undefined || version.major === undefined) return defaultPackageVersion;
31162
+ if (!Number.isInteger(version.major) || version.major < 0) return defaultPackageVersion;
31163
+ if (version.minor !== undefined && version.minor < 0) return defaultPackageVersion;
31164
+ if (version.patch !== undefined && version.patch < 0) return defaultPackageVersion;
31165
+ if (version.major === 0 && version.minor === undefined) return defaultPackageVersion;
31166
+ if (version.major === 0 && version.minor === 0 && version.patch === undefined) return defaultPackageVersion;
31167
+ if (version.major === 0 && version.minor === undefined && version.patch === undefined) return defaultPackageVersion;
30505
31168
  if (version.major === 0 && version.minor === 0 && version.patch === 0) return defaultPackageVersion;
30506
- let validatedVersion = defaultPackageVersion;
30507
- if (!Number.isNaN(version.major) && version.major >= 0) validatedVersion = version.major.toString();
30508
- if (!Number.isNaN(version.minor)) validatedVersion += `.${version.minor.toString()}`;
30509
- if (!Number.isNaN(version.patch)) validatedVersion += `.${version.patch.toString()}`;
30510
- // TODO: https://immutable.atlassian.net/browse/WT-1501
30511
- // Ensure this is gated by `version.prerelease !== undefined`
30512
- // once we go to prod with checkout.
30513
- validatedVersion += `-${version.prerelease}`;
30514
- if (version.build !== undefined && version.build > 0) validatedVersion += `.${version.build}`;
31169
+ let validatedVersion = version.major.toString();
31170
+ if (version.minor === undefined) return validatedVersion;
31171
+ if (Number.isInteger(version.minor)) validatedVersion += `.${version.minor.toString()}`;
31172
+ if (version.patch === undefined) return validatedVersion;
31173
+ if (Number.isInteger(version.patch)) validatedVersion += `.${version.patch.toString()}`;
31174
+ if (version.prerelease === undefined || version.prerelease !== "alpha") return validatedVersion;
31175
+ if (version.prerelease === "alpha") validatedVersion += `-${version.prerelease}`;
31176
+ if (version.build === undefined) return validatedVersion;
31177
+ if (Number.isInteger(version.build) && version.build >= 0) validatedVersion += `.${version.build.toString()}`;
30515
31178
  return validatedVersion;
30516
31179
  }
30517
31180
  function $430e3eda76fa4d5f$export$af210a0808087845(config) {
@@ -30643,7 +31306,6 @@ $parcel$export($045213b18e9f1f94$exports, "CheckoutWidgetTagNames", () => $04521
30643
31306
  (function(WidgetTheme) {
30644
31307
  WidgetTheme["LIGHT"] = "light";
30645
31308
  WidgetTheme["DARK"] = "dark";
30646
- WidgetTheme["CUSTOM"] = "custom";
30647
31309
  })($045213b18e9f1f94$export$c88931fdc51854eb || ($045213b18e9f1f94$export$c88931fdc51854eb = {}));
30648
31310
  var $045213b18e9f1f94$export$75be0f6af9650f2c;
30649
31311
  (function(CheckoutWidgetTagNames) {