From 80fb283cba31239b4ca016bb89e51c39ab3b65b0 Mon Sep 17 00:00:00 2001 From: SamueleA Date: Fri, 20 Sep 2024 14:50:42 +0000 Subject: [PATCH] Build: (1087291) payment select modal (#129) * logic for triggering new payment select modal * payment seleciton(wip) * added buy with currency flow * send transactions utility function * swap and buy * utility function * sardine checkout (wip) * credit card payment * card height adjustment * disable other buttons when a TX is in progress * adde sales contract-specific hook * renamed tokenId, collectionAddress and price fields * replaced chainId field with more generic chain field * clean up helpers * transfer to wallet * transfer funds modal context * export transfer funds modal * transfer funds modal * fixed add funds modal, trigger modal * new pnpm lock file * return txhash from onsuccess callback * fix peer deps * onClose callbacks * rename erc1155 sales contract setting modal * callback fns * disable mock connector * moved sardine * refactor selectpaymentmodal settings * regenerate lockfile * added variant to Text tags --- ...owser-external_commonjs-proxy-BKpD9f8m.js} | 2 +- assets/{ccip-DWFRyvlP.js => ccip-CI9Y3o6i.js} | 2 +- ...e-B0yPPEfe.js => hooks.module-DH-Wk4N-.js} | 4 +- .../{index-DhrVQl1N.js => index-03y2NvI2.js} | 4 +- .../{index-CIeoByUV.js => index-B1JZcE-u.js} | 6 +- .../{index-BIe9O6t-.js => index-Br1ln1tf.js} | 4 +- .../{index-BzPqRlsG.js => index-CsHzCx6e.js} | 4625 ++++++++++------- .../{index-CyfTH7LX.js => index-DGLMhC4E.js} | 6 +- ...ex.es-C_0Ilmtr.js => index.es-DMLMwzgY.js} | 8 +- index.html | 2 +- 10 files changed, 2722 insertions(+), 1941 deletions(-) rename assets/{___vite-browser-external_commonjs-proxy-BBNlhQUO.js => ___vite-browser-external_commonjs-proxy-BKpD9f8m.js} (99%) rename assets/{ccip-DWFRyvlP.js => ccip-CI9Y3o6i.js} (99%) rename assets/{hooks.module-B0yPPEfe.js => hooks.module-DH-Wk4N-.js} (99%) rename assets/{index-DhrVQl1N.js => index-03y2NvI2.js} (99%) rename assets/{index-CIeoByUV.js => index-B1JZcE-u.js} (99%) rename assets/{index-BIe9O6t-.js => index-Br1ln1tf.js} (99%) rename assets/{index-BzPqRlsG.js => index-CsHzCx6e.js} (98%) rename assets/{index-CyfTH7LX.js => index-DGLMhC4E.js} (99%) rename assets/{index.es-C_0Ilmtr.js => index.es-DMLMwzgY.js} (99%) diff --git a/assets/___vite-browser-external_commonjs-proxy-BBNlhQUO.js b/assets/___vite-browser-external_commonjs-proxy-BKpD9f8m.js similarity index 99% rename from assets/___vite-browser-external_commonjs-proxy-BBNlhQUO.js rename to assets/___vite-browser-external_commonjs-proxy-BKpD9f8m.js index c630e416..c6e42413 100644 --- a/assets/___vite-browser-external_commonjs-proxy-BBNlhQUO.js +++ b/assets/___vite-browser-external_commonjs-proxy-BKpD9f8m.js @@ -1,4 +1,4 @@ -import { g as getDefaultExportFromCjs, a as getAugmentedNamespace } from "./index-BzPqRlsG.js"; +import { g as getDefaultExportFromCjs, a as getAugmentedNamespace } from "./index-CsHzCx6e.js"; var events = { exports: {} }; var R = typeof Reflect === "object" ? Reflect : null; var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply2(target, receiver, args) { diff --git a/assets/ccip-DWFRyvlP.js b/assets/ccip-CI9Y3o6i.js similarity index 99% rename from assets/ccip-DWFRyvlP.js rename to assets/ccip-CI9Y3o6i.js index f57231e7..495c3328 100644 --- a/assets/ccip-DWFRyvlP.js +++ b/assets/ccip-CI9Y3o6i.js @@ -1,4 +1,4 @@ -import { f as BaseError, h as getUrl, s as stringify, i as decodeErrorResult, j as isAddressEqual, k as call, l as concat, m as encodeAbiParameters, H as HttpRequestError, n as isHex } from "./index-BzPqRlsG.js"; +import { f as BaseError, h as getUrl, s as stringify, i as decodeErrorResult, j as isAddressEqual, k as call, l as concat, m as encodeAbiParameters, H as HttpRequestError, n as isHex } from "./index-CsHzCx6e.js"; class OffchainLookupError extends BaseError { constructor({ callbackSelector, cause, data, extraData, sender, urls }) { var _a; diff --git a/assets/hooks.module-B0yPPEfe.js b/assets/hooks.module-DH-Wk4N-.js similarity index 99% rename from assets/hooks.module-B0yPPEfe.js rename to assets/hooks.module-DH-Wk4N-.js index 6953756f..644aa19d 100644 --- a/assets/hooks.module-B0yPPEfe.js +++ b/assets/hooks.module-DH-Wk4N-.js @@ -1,5 +1,5 @@ -import { a as getAugmentedNamespace, d as dist, p as process$1, c as commonjsGlobal, B as Buffer$7 } from "./index-BzPqRlsG.js"; -import { e as eventsExports, r as require$$3 } from "./___vite-browser-external_commonjs-proxy-BBNlhQUO.js"; +import { a as getAugmentedNamespace, d as dist, p as process$1, c as commonjsGlobal, B as Buffer$7 } from "./index-CsHzCx6e.js"; +import { e as eventsExports, r as require$$3 } from "./___vite-browser-external_commonjs-proxy-BKpD9f8m.js"; var readableBrowser = { exports: {} }; var streamBrowser = eventsExports.EventEmitter; const require$$0$1 = /* @__PURE__ */ getAugmentedNamespace(dist); diff --git a/assets/index-DhrVQl1N.js b/assets/index-03y2NvI2.js similarity index 99% rename from assets/index-DhrVQl1N.js rename to assets/index-03y2NvI2.js index bf53047e..e3db9a4b 100644 --- a/assets/index-DhrVQl1N.js +++ b/assets/index-03y2NvI2.js @@ -1,5 +1,5 @@ -import { B as Buffer, c as commonjsGlobal, e as eventemitter3Exports, g as getDefaultExportFromCjs } from "./index-BzPqRlsG.js"; -import { j as js, s as sha_jsExports, r as require$$0, a as require$$1, b as require$$2 } from "./hooks.module-B0yPPEfe.js"; +import { B as Buffer, c as commonjsGlobal, e as eventemitter3Exports, g as getDefaultExportFromCjs } from "./index-CsHzCx6e.js"; +import { j as js, s as sha_jsExports, r as require$$0, a as require$$1, b as require$$2 } from "./hooks.module-DH-Wk4N-.js"; function _mergeNamespaces(n, m) { for (var i = 0; i < m.length; i++) { const e = m[i]; diff --git a/assets/index-CIeoByUV.js b/assets/index-B1JZcE-u.js similarity index 99% rename from assets/index-CIeoByUV.js rename to assets/index-B1JZcE-u.js index 409a1f6b..e53f5973 100644 --- a/assets/index-CIeoByUV.js +++ b/assets/index-B1JZcE-u.js @@ -1,5 +1,5 @@ -const __vite__fileDeps=["./index-BIe9O6t-.js","./index-BzPqRlsG.js","./index-B7cGsFOk.css"],__vite__mapDeps=i=>i.map(i=>__vite__fileDeps[i]); -import { _ as __vitePreload } from "./index-BzPqRlsG.js"; +const __vite__fileDeps=["./index-Br1ln1tf.js","./index-CsHzCx6e.js","./index-B7cGsFOk.css"],__vite__mapDeps=i=>i.map(i=>__vite__fileDeps[i]); +import { _ as __vitePreload } from "./index-CsHzCx6e.js"; const t = Symbol(); const s = Object.getPrototypeOf, c$1 = /* @__PURE__ */ new WeakMap(), l = (e) => e && (c$1.has(e) ? c$1.get(e) : s(e) === Object.prototype || s(e) === Array.prototype), y$1 = (e) => l(e) && e[t] || null, h = (e, t2 = true) => { c$1.set(e, t2); @@ -487,7 +487,7 @@ class d { } async initUi() { if (typeof window < "u") { - await __vitePreload(() => import("./index-BIe9O6t-.js"), true ? __vite__mapDeps([0,1,2]) : void 0, import.meta.url); + await __vitePreload(() => import("./index-Br1ln1tf.js"), true ? __vite__mapDeps([0,1,2]) : void 0, import.meta.url); const e = document.createElement("wcm-modal"); document.body.insertAdjacentElement("beforeend", e), p.setIsUiLoaded(true); } diff --git a/assets/index-BIe9O6t-.js b/assets/index-Br1ln1tf.js similarity index 99% rename from assets/index-BIe9O6t-.js rename to assets/index-Br1ln1tf.js index 9e109acc..129e0eaa 100644 --- a/assets/index-BIe9O6t-.js +++ b/assets/index-Br1ln1tf.js @@ -1,5 +1,5 @@ -import { n as ne$1, s as se$1, T as T$2, t as te$1, a as a$2, o as oe$1, R as R$1, p as p$1, y as y$1 } from "./index-CIeoByUV.js"; -import "./index-BzPqRlsG.js"; +import { n as ne$1, s as se$1, T as T$2, t as te$1, a as a$2, o as oe$1, R as R$1, p as p$1, y as y$1 } from "./index-B1JZcE-u.js"; +import "./index-CsHzCx6e.js"; function addUniqueItem(array, item) { array.indexOf(item) === -1 && array.push(item); } diff --git a/assets/index-BzPqRlsG.js b/assets/index-CsHzCx6e.js similarity index 98% rename from assets/index-BzPqRlsG.js rename to assets/index-CsHzCx6e.js index bfe62abd..1e6763ad 100644 --- a/assets/index-BzPqRlsG.js +++ b/assets/index-CsHzCx6e.js @@ -1,4 +1,4 @@ -const __vite__fileDeps=["./index-DhrVQl1N.js","./hooks.module-B0yPPEfe.js","./___vite-browser-external_commonjs-proxy-BBNlhQUO.js","./index-CyfTH7LX.js","./index.es-C_0Ilmtr.js"],__vite__mapDeps=i=>i.map(i=>__vite__fileDeps[i]); +const __vite__fileDeps=["./index-03y2NvI2.js","./hooks.module-DH-Wk4N-.js","./___vite-browser-external_commonjs-proxy-BKpD9f8m.js","./index-DGLMhC4E.js","./index.es-DMLMwzgY.js"],__vite__mapDeps=i=>i.map(i=>__vite__fileDeps[i]); var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => { @@ -25667,6 +25667,46 @@ const Tooltip = (props) => { ) ] }) }); }; +const useMediaQuery = (queryInput, options = {}) => { + const bp = (/* @__PURE__ */ new Map()).set("isMobile", `@media screen and (max-width: ${breakpoints.lg - 1}px)`).set("isDesktop", `@media screen and (min-width: ${breakpoints.lg}px)`); + if (!queryInput.startsWith("@media")) { + const bpQuery = bp.get(queryInput); + if (!bpQuery || bpQuery === "") { + throw new Error( + `useMediaQuery failed to get breakpoint from theme for: ${queryInput}` + ); + } + queryInput = bpQuery; + } + const query = queryInput.replace(/^@media( ?)/m, ""); + const supportMatchMedia = typeof window !== "undefined" && typeof window.matchMedia !== "undefined"; + const { defaultMatches = false } = options; + const [match, setMatch] = reactExports.useState(() => { + if (supportMatchMedia) { + return window.matchMedia(query).matches; + } + return defaultMatches; + }); + reactExports.useEffect(() => { + let active = true; + if (!supportMatchMedia) { + return void 0; + } + const queryList = window.matchMedia(query); + const updateMatch = () => { + if (active) { + setMatch(queryList.matches); + } + }; + updateMatch(); + queryList.addListener(updateMatch); + return () => { + active = false; + queryList.removeListener(updateMatch); + }; + }, [query, supportMatchMedia]); + return match; +}; const abi$7 = [{ inputs: [{ internalType: "bytes32", @@ -75902,7 +75942,7 @@ async function call(client2, args) { return { data: response }; } catch (err) { const data2 = getRevertErrorData(err); - const { offchainLookup, offchainLookupSignature } = await __vitePreload(() => import("./ccip-DWFRyvlP.js"), true ? [] : void 0, import.meta.url); + const { offchainLookup, offchainLookupSignature } = await __vitePreload(() => import("./ccip-CI9Y3o6i.js"), true ? [] : void 0, import.meta.url); if (client2.ccipRead !== false && (data2 == null ? void 0 : data2.slice(0, 10)) === offchainLookupSignature && to) return { data: await offchainLookup(client2, { data: data2, to }) }; throw getCallError(err, { @@ -75990,7 +76030,7 @@ function getRevertErrorData(err) { const error = err.walk(); return typeof (error == null ? void 0 : error.data) === "object" ? (_a2 = error.data) == null ? void 0 : _a2.data : error.data; } -async function readContract(client2, parameters) { +async function readContract$1(client2, parameters) { const { abi: abi2, address, args, functionName, ...rest } = parameters; const calldata = encodeFunctionData({ abi: abi2, @@ -76044,7 +76084,7 @@ async function getEnsAddress(client2, { blockNumber, blockTag, coinType, name: n blockNumber, blockTag }; - const readContractAction = getAction$1(client2, readContract, "readContract"); + const readContractAction = getAction$1(client2, readContract$1, "readContract"); const res = gatewayUrls ? await readContractAction({ ...readContractParameters, args: [...readContractParameters.args, gatewayUrls] @@ -76256,7 +76296,7 @@ function parseNftUri(uri_) { } async function getNftTokenUri(client2, { nft }) { if (nft.namespace === "erc721") { - return readContract(client2, { + return readContract$1(client2, { address: nft.contractAddress, abi: [ { @@ -76272,7 +76312,7 @@ async function getNftTokenUri(client2, { nft }) { }); } if (nft.namespace === "erc1155") { - return readContract(client2, { + return readContract$1(client2, { address: nft.contractAddress, abi: [ { @@ -76344,7 +76384,7 @@ async function getEnsText(client2, { blockNumber, blockTag, name: name2, key, ga blockNumber, blockTag }; - const readContractAction = getAction$1(client2, readContract, "readContract"); + const readContractAction = getAction$1(client2, readContract$1, "readContract"); const res = gatewayUrls ? await readContractAction({ ...readContractParameters, args: [...readContractParameters.args, gatewayUrls] @@ -76407,7 +76447,7 @@ async function getEnsName(client2, { address, blockNumber, blockTag, gatewayUrls blockNumber, blockTag }; - const readContractAction = getAction$1(client2, readContract, "readContract"); + const readContractAction = getAction$1(client2, readContract$1, "readContract"); const [name2, resolvedAddress] = gatewayUrls ? await readContractAction({ ...readContractParameters, args: [...readContractParameters.args, gatewayUrls] @@ -76434,7 +76474,7 @@ async function getEnsResolver(client2, { blockNumber, blockTag, name: name2, uni contract: "ensUniversalResolver" }); } - const [resolverAddress] = await getAction$1(client2, readContract, "readContract")({ + const [resolverAddress] = await getAction$1(client2, readContract$1, "readContract")({ address: universalResolverAddress, abi: [ { @@ -77072,7 +77112,7 @@ async function multicall(client2, parameters) { ]; } } - const aggregate3Results = await Promise.allSettled(chunkedCalls.map((calls) => getAction$1(client2, readContract, "readContract")({ + const aggregate3Results = await Promise.allSettled(chunkedCalls.map((calls) => getAction$1(client2, readContract$1, "readContract")({ abi: multicall3Abi, address: multicallAddress, args: [calls], @@ -78966,7 +79006,7 @@ function publicActions(client2) { getTransactionReceipt: (args) => getTransactionReceipt$1(client2, args), multicall: (args) => multicall(client2, args), prepareTransactionRequest: (args) => prepareTransactionRequest(client2, args), - readContract: (args) => readContract(client2, args), + readContract: (args) => readContract$1(client2, args), sendRawTransaction: (args) => sendRawTransaction(client2, args), simulateContract: (args) => simulateContract$1(client2, args), verifyMessage: (args) => verifyMessage(client2, args), @@ -80770,6 +80810,12 @@ function getAccount(config2) { }; } } +function readContract(config2, parameters) { + const { chainId, ...rest } = parameters; + const client2 = config2.getClient({ chainId }); + const action = getAction(client2, readContract$1, "readContract"); + return action(rest); +} function getChainId(config2) { return config2.state.chainId; } @@ -84002,6 +84048,11 @@ function useAccount(parameters = {}) { const config2 = useConfig(parameters); return useSyncExternalStoreWithTracked((onChange) => watchAccount(config2, { onChange }), () => getAccount(config2)); } +function structuralSharing(oldData, newData) { + if (deepEqual$1(oldData, newData)) + return oldData; + return replaceEqualDeep(oldData, newData); +} function hashFn(queryKey) { return JSON.stringify(queryKey, (_, value) => { if (isPlainObject(value)) @@ -84049,7 +84100,7 @@ function filterQueryOptions(options) { queryKeyHashFn, retry, retryDelay, - structuralSharing, + structuralSharing: structuralSharing2, // import('@tanstack/query-core').InfiniteQueryObserverOptions // biome-ignore lint/correctness/noUnusedVariables: remove properties getPreviousPageParam: getPreviousPageParam2, @@ -84116,6 +84167,35 @@ function getWalletClientQueryKey(options = {}) { { ...filterQueryOptions(parameters), connectorUid: connector == null ? void 0 : connector.uid } ]; } +function readContractQueryOptions(config2, options = {}) { + return { + // TODO: Support `signal` once Viem actions allow passthrough + // https://tkdodo.eu/blog/why-you-want-react-query#bonus-cancellation + async queryFn({ queryKey }) { + const abi2 = options.abi; + if (!abi2) + throw new Error("abi is required"); + const { address, functionName, scopeKey: _, ...parameters } = queryKey[1]; + if (!address) + throw new Error("address is required"); + if (!functionName) + throw new Error("functionName is required"); + const args = parameters.args; + return readContract(config2, { + abi: abi2, + address, + functionName, + args, + ...parameters + }); + }, + queryKey: readContractQueryKey(options) + }; +} +function readContractQueryKey(options = {}) { + const { abi: _, ...rest } = options; + return ["readContract", filterQueryOptions(rest)]; +} function sendTransactionMutationOptions(config2) { return { mutationFn(variables) { @@ -84205,6 +84285,19 @@ function usePublicClient(parameters = {}) { const config2 = useConfig(parameters); return withSelectorExports.useSyncExternalStoreWithSelector((onChange) => watchPublicClient(config2, { onChange }), () => getPublicClient(config2, parameters), () => getPublicClient(config2, parameters), (x2) => x2, (a2, b2) => (a2 == null ? void 0 : a2.uid) === (b2 == null ? void 0 : b2.uid)); } +function useReadContract(parameters = {}) { + const { abi: abi2, address, functionName, query = {} } = parameters; + const config2 = useConfig(parameters); + const chainId = useChainId({ config: config2 }); + const options = readContractQueryOptions(config2, { ...parameters, chainId: parameters.chainId ?? chainId }); + const enabled = Boolean(address && abi2 && functionName && (query.enabled ?? true)); + return useQuery({ + ...query, + ...options, + enabled, + structuralSharing: query.structuralSharing ?? structuralSharing + }); +} function useSendTransaction(parameters = {}) { const { mutation } = parameters; const config2 = useConfig(parameters); @@ -84295,6 +84388,7 @@ var LocalStorageKey; LocalStorageKey2["WaasSignInEmail"] = "@kit.waasSignInEmail"; })(LocalStorageKey || (LocalStorageKey = {})); const DEFAULT_SESSION_EXPIRATION = 60 * 60 * 24 * 7; +const TRANSACTION_CONFIRMATIONS_DEFAULT = 4; const createGenericContext$2 = () => { const genericContext = reactExports.createContext(void 0); const useGenericContext = () => { @@ -93178,7 +93272,7 @@ function feeOptions({ }) }); } -function sendTransactions({ +function sendTransactions$1({ lifespan, wallet, identifier, @@ -93266,7 +93360,7 @@ function sendERC20(_ref) { to, value } = _ref, args = _objectWithoutPropertiesLoose$2(_ref, _excluded$1$1); - return sendTransactions(_extends$2({ + return sendTransactions$1(_extends$2({ transactions: [erc20({ tokenAddress: token, to, @@ -93282,7 +93376,7 @@ function sendERC721(_ref2) { safe, data } = _ref2, args = _objectWithoutPropertiesLoose$2(_ref2, _excluded2$1); - return sendTransactions(_extends$2({ + return sendTransactions$1(_extends$2({ transactions: [erc721({ tokenAddress: token, to, @@ -93303,7 +93397,7 @@ function sendERC1155(_ref3) { id: v3.id, amount: BigInt(v3.amount).toString() })); - return sendTransactions(_extends$2({ + return sendTransactions$1(_extends$2({ transactions: [erc1155({ tokenAddress: token, to, @@ -93320,7 +93414,7 @@ function sendDelayedEncode(_ref4) { func, args } = _ref4, otherArgs = _objectWithoutPropertiesLoose$2(_ref4, _excluded4); - return sendTransactions(_extends$2({ + return sendTransactions$1(_extends$2({ transactions: [delayedEncode({ to, value: BigInt(value).toString(), @@ -94059,7 +94153,7 @@ class SequenceWaaSBase { * @returns a payload that must be sent to the waas API to complete the transaction */ async sendTransaction(args) { - const intent = sendTransactions(await this.commonArgs(args)); + const intent = sendTransactions$1(await this.commonArgs(args)); return this.signIntent(intent); } async getTransactionReceipt(args) { @@ -96825,6 +96919,67 @@ const useTransactionHistory = (args) => { enabled: !!args.chainId && !!args.accountAddress }); }; +const getSwapQuotes = async (apiClient, metadataClient, indexerClient, args) => { + if (!args.chainId || !args.userAddress || !args.currencyAddress || !args.currencyAmount || args.currencyAmount === "0") { + return []; + } + const res = await apiClient.getSwapQuotes({ + ...args, + includeApprove: true + }); + if (res.swapQuotes === null) { + return []; + } + const currencyInfoMap = /* @__PURE__ */ new Map(); + if (args.withContractInfo) { + res == null ? void 0 : res.swapQuotes.forEach((quote) => { + const { currencyAddress } = quote; + if (currencyAddress && !currencyInfoMap.has(currencyAddress)) { + currencyInfoMap.set(currencyAddress, metadataClient.getContractInfo({ + chainID: String(args.chainId), + contractAddress: currencyAddress + }).then((data) => data.contractInfo)); + } + }); + } + const currencyBalanceInfoMap = /* @__PURE__ */ new Map(); + res == null ? void 0 : res.swapQuotes.forEach((quote) => { + const { currencyAddress } = quote; + if (currencyAddress && !currencyBalanceInfoMap.has(currencyAddress)) { + currencyBalanceInfoMap.set(currencyAddress, indexerClient.getTokenBalances({ + accountAddress: args.userAddress, + contractAddress: currencyAddress, + includeMetadata: true, + metadataOptions: { + verifiedOnly: true + } + }).then((balances) => { + var _a2; + return ((_a2 = balances.balances) == null ? void 0 : _a2[0]) || []; + })); + } + }); + return Promise.all((res == null ? void 0 : res.swapQuotes.map(async (quote) => ({ + quote, + info: await currencyInfoMap.get(quote.currencyAddress) || void 0, + balance: await currencyBalanceInfoMap.get(quote.currencyAddress) || void 0 + }))) || []); +}; +const useSwapQuotes = (args) => { + const apiClient = useAPIClient(); + const metadataClient = useMetadataClient(); + const indexerClient = useIndexerClient(args.chainId); + const enabled = !!args.chainId && !!args.userAddress && !!args.currencyAddress && !!args.currencyAmount && args.currencyAmount !== "0"; + return useQuery$1({ + queryKey: ["swapQuotes", args], + queryFn: () => getSwapQuotes(apiClient, metadataClient, indexerClient, args), + retry: true, + // We must keep a long staletime to avoid the list of quotes being refreshed while the user is doing the transactions + // Instead, we will invalidate the query manually + staleTime: time$1.oneHour, + enabled + }); +}; const chains$1 = allNetworks.reduce((acc, network2) => { if (network2.deprecated) { return acc; @@ -97558,7 +97713,7 @@ function version4(parameters) { }, async getProvider() { if (!walletProvider) { - const { default: CoinbaseSDK_ } = await __vitePreload(() => import("./index-DhrVQl1N.js").then((n2) => n2.i), true ? __vite__mapDeps([0,1,2]) : void 0, import.meta.url); + const { default: CoinbaseSDK_ } = await __vitePreload(() => import("./index-03y2NvI2.js").then((n2) => n2.i), true ? __vite__mapDeps([0,1,2]) : void 0, import.meta.url); const CoinbaseSDK = (() => { if (typeof CoinbaseSDK_ !== "function" && typeof CoinbaseSDK_.default === "function") return CoinbaseSDK_.default; @@ -97735,7 +97890,7 @@ function version3(parameters) { async getProvider() { var _a2; if (!walletProvider) { - const { default: SDK_ } = await __vitePreload(() => import("./index-CyfTH7LX.js").then((n2) => n2.i), true ? __vite__mapDeps([3,1,2]) : void 0, import.meta.url); + const { default: SDK_ } = await __vitePreload(() => import("./index-DGLMhC4E.js").then((n2) => n2.i), true ? __vite__mapDeps([3,1,2]) : void 0, import.meta.url); let SDK; if (typeof SDK_ !== "function" && typeof SDK_.default === "function") SDK = SDK_.default; @@ -97969,7 +98124,7 @@ function walletConnect$1(parameters) { const optionalChains = config2.chains.map((x2) => x2.id); if (!optionalChains.length) return; - const { EthereumProvider } = await __vitePreload(() => import("./index.es-C_0Ilmtr.js"), true ? __vite__mapDeps([4,2]) : void 0, import.meta.url); + const { EthereumProvider } = await __vitePreload(() => import("./index.es-DMLMwzgY.js"), true ? __vite__mapDeps([4,2]) : void 0, import.meta.url); return await EthereumProvider.init({ ...parameters, disableProviderPing: true, @@ -98562,6 +98717,64 @@ const validateEthProof = async (walletClient, publicClient, proof) => { const isValid2 = await sequence$1.utils.isValidTypedDataSignature(walletAddress, proof.typedData, decodedProof.signature, provider2); return isValid2; }; +const sendTransactions = async ({ chainId, senderAddress, publicClient, walletClient, connector, transactions: transactions2, transactionConfirmations = TRANSACTION_CONFIRMATIONS_DEFAULT }) => { + var _a2; + const walletClientChainId = await walletClient.getChainId(); + if (walletClientChainId !== chainId) { + await walletClient.switchChain({ id: chainId }); + } + const sequenceWaaS = connector == null ? void 0 : connector["sequenceWaas"]; + const isEmbeddedWallet = !!sequenceWaaS; + const isSequenceUniversalWallet = !!((_a2 = connector == null ? void 0 : connector._wallet) == null ? void 0 : _a2.isSequenceBased); + if (isEmbeddedWallet) { + const resp = await sequenceWaaS.feeOptions({ + transactions: transactions2, + network: chainId + }); + const transactionsFeeOption = resp.data.feeOptions[0]; + const transactionsFeeQuote = resp.data.feeQuote; + const response = await sequenceWaaS.sendTransaction({ + transactions: transactions2, + transactionsFeeOption, + transactionsFeeQuote + }); + if (response.code === "transactionFailed") { + throw new Error(response.data.error); + } + const txnHash = response.data.txHash; + await publicClient.waitForTransactionReceipt({ + hash: txnHash, + confirmations: transactionConfirmations + }); + return txnHash; + } else if (isSequenceUniversalWallet) { + const wallet = sequence$1.getWallet(); + const signer2 = wallet.getSigner(); + const response = await signer2.sendTransaction(transactions2); + await publicClient.waitForTransactionReceipt({ + hash: response.hash, + confirmations: transactionConfirmations + }); + return response.hash; + } else { + let txHash = ""; + for (const transaction2 of transactions2) { + const txnHash = await walletClient.sendTransaction({ + account: senderAddress, + to: transaction2.to, + value: transaction2 == null ? void 0 : transaction2.value, + data: transaction2 == null ? void 0 : transaction2.data, + chain: void 0 + }); + await publicClient.waitForTransactionReceipt({ + hash: txnHash, + confirmations: transactionConfirmations + }); + txHash = txnHash; + } + return txHash; + } +}; const mock = (options) => ({ id: "mock", isSequenceBased: true, @@ -98647,7 +98860,11 @@ const createGenericContext$1 = () => { const [useAddFundsModalContext, AddFundsContextProvider] = createGenericContext$1(); const [useCheckoutModalContext, CheckoutModalContextProvider] = createGenericContext$1(); const [useNavigationContext$1, NavigationContextProvider$1] = createGenericContext$1(); +const [useSelectPaymentContext, SelectPaymentContextProvider] = createGenericContext$1(); +const [useTransferFundsModalContext, TransferFundsContextProvider] = createGenericContext$1(); const HEADER_HEIGHT$1 = "54px"; +const CARD_HEIGHT = "130px"; +const CARD_HEIGHT_MOBILE = "180px"; const useNavigation$1 = () => { const { setHistory, history, defaultLocation } = useNavigationContext$1(); const setNavigation = (navigation2) => { @@ -98816,6 +99033,71 @@ const useSardineClientToken = (args, disabled) => { refetchOnWindowFocus: false }); }; +const useSelectPaymentModal = () => { + const { openSelectPaymentModal, closeSelectPaymentModal, selectPaymentSettings } = useSelectPaymentContext(); + return { openSelectPaymentModal, closeSelectPaymentModal, selectPaymentSettings }; +}; +const getERC1155SaleContractConfig = ({ chain, price, currencyAddress = ZeroAddress, recipientAddress, tokenId, collectionAddress, nftQuantity, isDev = false, ...restProps }) => { + const erc1155SalesContractAbi = [ + { + type: "function", + name: "mint", + inputs: [ + { name: "to", type: "address", internalType: "address" }, + { name: "tokenIds", type: "uint256[]", internalType: "uint256[]" }, + { name: "amounts", type: "uint256[]", internalType: "uint256[]" }, + { name: "data", type: "bytes", internalType: "bytes" }, + { name: "expectedPaymentToken", type: "address", internalType: "address" }, + { name: "maxTotal", type: "uint256", internalType: "uint256" }, + { name: "proof", type: "bytes32[]", internalType: "bytes32[]" } + ], + outputs: [], + stateMutability: "payable" + } + ]; + const purchaseTransactionData = encodeFunctionData({ + abi: erc1155SalesContractAbi, + functionName: "mint", + args: [recipientAddress, [BigInt(tokenId)], [BigInt(nftQuantity)], toHex$1(0), currencyAddress, price, [toHex$1(0, { size: 32 })]] + }); + return { + chain, + price, + currencyAddress, + recipientAddress, + tokenId, + collectionAddress, + nftQuantity, + isDev, + txData: purchaseTransactionData, + ...restProps + }; +}; +const useERC1155SaleContractPaymentModal = () => { + const { openSelectPaymentModal, closeSelectPaymentModal, selectPaymentSettings } = useSelectPaymentModal(); + const openERC1155SaleContractPaymentModal = (saleContractSettings) => { + openSelectPaymentModal(getERC1155SaleContractConfig(saleContractSettings)); + }; + return { + openERC1155SaleContractPaymentModal, + closeERC1155SaleContractPaymentModal: closeSelectPaymentModal, + selectPaymentSettings + }; +}; +const useClearCachedBalances = () => { + const queryClient2 = useQueryClient(); + return { + clearCachedBalances: () => { + queryClient2.invalidateQueries({ + queryKey: ["balances"] + }); + } + }; +}; +const useTransferFundsModal = () => { + const { openTransferFundsModal, closeTransferFundsModal, transferFundsSettings } = useTransferFundsModalContext(); + return { openTransferFundsModal, closeTransferFundsModal, transferFundsSettings }; +}; const POLLING_TIME = 10 * 1e3; const PendingTransaction = () => { var _a2; @@ -99054,2026 +99336,2487 @@ const AddFundsContent = () => { return; } const link = getTransakLink(addFundsSettings); - return jsxRuntimeExports$1.jsx(Box, { alignItems: "center", width: "full", paddingX: "4", paddingBottom: "4", height: "full", style: { height: "600px" }, children: jsxRuntimeExports$1.jsx(Box, { as: "iframe", width: "full", height: "full", borderWidth: "none", src: link }) }); + return jsxRuntimeExports$1.jsx(Box, { alignItems: "center", width: "full", paddingX: "4", paddingBottom: "4", height: "full", style: { + height: "600px", + paddingTop: HEADER_HEIGHT$1 + }, children: jsxRuntimeExports$1.jsx(Box, { as: "iframe", width: "full", height: "full", borderWidth: "none", src: link }) }); }; -const KitCheckoutProvider = (props) => { - const queryClient2 = new QueryClient(); - return jsxRuntimeExports$1.jsx(QueryClientProvider, { client: queryClient2, children: jsxRuntimeExports$1.jsx(KitCheckoutContent, { ...props }) }); +const getCardHeight = (isMobile) => { + if (isMobile) { + return CARD_HEIGHT_MOBILE; + } + return CARD_HEIGHT; }; -const KitCheckoutContent = ({ children }) => { - const { theme, position } = useTheme(); - const [openCheckoutModal, setOpenCheckoutModal] = reactExports.useState(false); - const [openAddFundsModal, setOpenAddFundsModal] = reactExports.useState(false); - const [settings, setSettings] = reactExports.useState(); - const [addFundsSettings, setAddFundsSettings] = reactExports.useState(); - const [history, setHistory] = reactExports.useState([]); - const getDefaultLocation = () => { - const orderSummaryItems = (settings == null ? void 0 : settings.orderSummaryItems) || []; - const creditCardSettings = settings == null ? void 0 : settings.creditCardCheckout; - if (orderSummaryItems.length === 0 && creditCardSettings) { - return { - location: "transaction-pending", - params: { - creditCardCheckout: creditCardSettings +const ERC_20_CONTRACT_ABI = [ + { + type: "function", + name: "allowance", + inputs: [ + { name: "owner", type: "address", internalType: "address" }, + { name: "spender", type: "address", internalType: "address" } + ], + outputs: [{ name: "", type: "uint256", internalType: "uint256" }], + stateMutability: "view" + }, + { + type: "function", + name: "approve", + inputs: [ + { name: "spender", type: "address", internalType: "address" }, + { name: "amount", type: "uint256", internalType: "uint256" } + ], + outputs: [{ name: "", type: "bool", internalType: "bool" }], + stateMutability: "nonpayable" + } +]; +const PayWithMainCurrency = ({ settings, disableButtons, setDisableButtons }) => { + const { chain, currencyAddress, targetContractAddress, price, txData, transactionConfirmations = TRANSACTION_CONFIRMATIONS_DEFAULT, onSuccess = () => { + }, onError = () => { + } } = settings; + const { address: userAddress, connector } = useAccount(); + const isMobile = useMediaQuery("isMobile"); + const { data: walletClient } = useWalletClient(); + const publicClient = usePublicClient(); + const [purchaseInProgress, setPurchaseInProgress] = reactExports.useState(false); + const { clearCachedBalances } = useClearCachedBalances(); + const { closeSelectPaymentModal } = useSelectPaymentModal(); + const network2 = findSupportedNetwork(chain); + const chainId = (network2 == null ? void 0 : network2.chainId) || 137; + const { data: allowanceData, isLoading: allowanceIsLoading, refetch: refechAllowance } = useReadContract({ + abi: ERC_20_CONTRACT_ABI, + functionName: "allowance", + chainId, + address: currencyAddress, + args: [userAddress, targetContractAddress], + query: { + enabled: !!userAddress + } + }); + const { data: currencyBalanceData, isLoading: currencyBalanceIsLoading } = useBalances({ + chainIds: [chainId], + contractAddress: currencyAddress, + accountAddress: userAddress || "", + // includeMetadata must be false to work around a bug + includeMetadata: false + }); + const { data: currencyInfoData, isLoading: isLoadingCurrencyInfo } = useContractInfo(chainId, currencyAddress); + const isLoading = allowanceIsLoading || currencyBalanceIsLoading || isLoadingCurrencyInfo; + if (isLoading) { + return jsxRuntimeExports$1.jsx(Card, { width: "full", flexDirection: "column", alignItems: "center", justifyContent: "center", style: { + minHeight: getCardHeight(isMobile) + }, children: jsxRuntimeExports$1.jsx(Spinner, {}) }); + } + const priceFormatted = formatUnits(BigInt(price), (currencyInfoData == null ? void 0 : currencyInfoData.decimals) || 0); + const isApproved = allowanceData >= BigInt(price); + const balanceInfo = currencyBalanceData == null ? void 0 : currencyBalanceData.find((balanceData) => compareAddress$2(currencyAddress, balanceData.contractAddress)); + const balance = BigInt((balanceInfo == null ? void 0 : balanceInfo.balance) || "0"); + let balanceFormatted = Number(formatUnits(balance, (currencyInfoData == null ? void 0 : currencyInfoData.decimals) || 0)); + balanceFormatted = Math.trunc(Number(balanceFormatted) * 1e4) / 1e4; + const isNotEnoughFunds = BigInt(price) > balance; + const onClickPurchase = async () => { + if (!walletClient || !userAddress || !publicClient || !userAddress || !connector) { + return; + } + setPurchaseInProgress(true); + setDisableButtons(true); + try { + const walletClientChainId = await walletClient.getChainId(); + if (walletClientChainId !== chainId) { + await walletClient.switchChain({ id: chainId }); + } + const approveTxData = encodeFunctionData({ + abi: ERC_20_CONTRACT_ABI, + functionName: "approve", + args: [targetContractAddress, price] + }); + const transactions2 = [ + ...isApproved ? [] : [ + { + to: currencyAddress, + data: approveTxData, + chainId + } + ], + { + to: targetContractAddress, + data: txData, + chainId } - }; - } else { - return { - location: "select-method-checkout" - }; + ]; + const txHash = await sendTransactions({ + chainId, + senderAddress: userAddress, + publicClient, + walletClient, + connector, + transactions: transactions2, + transactionConfirmations + }); + closeSelectPaymentModal(); + refechAllowance(); + clearCachedBalances(); + onSuccess(txHash); + } catch (e2) { + console.error("Failed to purchase...", e2); + onError(e2); } + setPurchaseInProgress(false); + setDisableButtons(false); }; - const navigation = history.length > 0 ? history[history.length - 1] : getDefaultLocation(); - const triggerCheckout = (settings2) => { - setSettings(settings2); - setOpenCheckoutModal(true); - }; - const closeCheckout = () => { - setOpenCheckoutModal(false); - }; - const triggerAddFunds = (settings2) => { - setAddFundsSettings(settings2); - setOpenAddFundsModal(true); - }; - const closeAddFunds = () => { - setOpenAddFundsModal(false); - }; - const getCheckoutContent = () => { - const { location: location2 } = navigation; - switch (location2) { - case "select-method-checkout": - return jsxRuntimeExports$1.jsx(CheckoutSelection, {}); - case "transaction-pending": - return jsxRuntimeExports$1.jsx(PendingTransaction, {}); - case "transaction-success": - return jsxRuntimeExports$1.jsx(TransactionSuccess, {}); - case "transaction-error": - return jsxRuntimeExports$1.jsx(TransactionError, {}); - case "transaction-form": - default: - return jsxRuntimeExports$1.jsx(CheckoutSelection, {}); + const StatusMessage = () => { + if (isNotEnoughFunds) { + return jsxRuntimeExports$1.jsxs(Box, { flexDirection: "row", gap: "1", alignItems: "center", justifyContent: isMobile ? "center" : "flex-start", children: [jsxRuntimeExports$1.jsx(Text, { variant: "small", color: "negative", children: "Not enough funds" }), jsxRuntimeExports$1.jsx(Box, { style: { height: "22px", width: "22px" } })] }); } - }; - const getCheckoutHeader = () => { - const { location: location2 } = navigation; - switch (location2) { - case "select-method-checkout": - return jsxRuntimeExports$1.jsx(NavigationHeader$1, { primaryText: "Checkout" }); - case "transaction-success": - case "transaction-error": - case "transaction-pending": - return jsxRuntimeExports$1.jsx(NavigationHeader$1, { disableBack: true, primaryText: "Pay with credit or debit card" }); - case "transaction-form": - default: - return jsxRuntimeExports$1.jsx(NavigationHeader$1, { primaryText: "Pay with credit or debit card" }); + if (purchaseInProgress) { + return jsxRuntimeExports$1.jsxs(Box, { flexDirection: "row", gap: "1", alignItems: "center", justifyContent: isMobile ? "center" : "flex-start", children: [jsxRuntimeExports$1.jsx(Text, { variant: "small", color: "text100", children: "In progress..." }), jsxRuntimeExports$1.jsx(Box, { justifyContent: "center", alignItems: "center", style: { height: "22px", width: "22px" }, children: jsxRuntimeExports$1.jsx(Spinner, { size: "sm" }) })] }); } + return null; }; - const getAddFundsHeader = () => { - const { location: location2 } = navigation; - switch (location2) { - default: - return jsxRuntimeExports$1.jsx(NavigationHeader$1, { primaryText: "Add funds with credit card or debit card" }); + return jsxRuntimeExports$1.jsxs(Card, { width: "full", flexDirection: isMobile ? "column" : "row", alignItems: "center", justifyContent: "space-between", gap: isMobile ? "2" : "0", style: { + minHeight: getCardHeight(isMobile) + }, children: [jsxRuntimeExports$1.jsxs(Box, { flexDirection: "column", gap: "2", justifyContent: isMobile ? "center" : "flex-start", children: [jsxRuntimeExports$1.jsx(Box, { justifyContent: isMobile ? "center" : "flex-start", children: jsxRuntimeExports$1.jsxs(Text, { variant: "normal", color: "text100", children: ["Buy With ", currencyInfoData == null ? void 0 : currencyInfoData.name] }) }), jsxRuntimeExports$1.jsxs(Box, { flexDirection: "row", gap: "1", alignItems: "center", justifyContent: isMobile ? "center" : "flex-start", children: [jsxRuntimeExports$1.jsx(Text, { variant: "small", color: "text100", children: `Price: ${priceFormatted} ${currencyInfoData == null ? void 0 : currencyInfoData.symbol}` }), jsxRuntimeExports$1.jsx(TokenImage, { size: "xs", src: currencyInfoData == null ? void 0 : currencyInfoData.logoURI })] }), jsxRuntimeExports$1.jsxs(Box, { flexDirection: "row", gap: "1", alignItems: "center", justifyContent: isMobile ? "center" : "flex-start", children: [jsxRuntimeExports$1.jsx(Text, { variant: "small", color: "text100", children: `Balance: ${balanceFormatted} ${currencyInfoData == null ? void 0 : currencyInfoData.symbol}` }), jsxRuntimeExports$1.jsx(TokenImage, { size: "xs", src: currencyInfoData == null ? void 0 : currencyInfoData.logoURI })] }), jsxRuntimeExports$1.jsx(StatusMessage, {})] }), jsxRuntimeExports$1.jsx(Box, { flexDirection: "column", gap: "2", alignItems: isMobile ? "center" : "flex-start", style: { ...isMobile ? { width: "200px" } : {} }, children: jsxRuntimeExports$1.jsx(Button, { label: "Purchase", onClick: onClickPurchase, disabled: purchaseInProgress || isNotEnoughFunds || disableButtons, variant: "primary", shape: "square", pending: purchaseInProgress }) })] }); +}; +const SwapAndPay = ({ settings, disableButtons, setDisableButtons }) => { + const { chain, currencyAddress, targetContractAddress, price: priceRaw, txData, transactionConfirmations = TRANSACTION_CONFIRMATIONS_DEFAULT, onSuccess = () => { + }, onError = () => { + } } = settings; + const isMobile = useMediaQuery("isMobile"); + const { address: userAddress, connector } = useAccount(); + const { clearCachedBalances } = useClearCachedBalances(); + const { data: walletClient } = useWalletClient(); + const publicClient = usePublicClient(); + const [swapsInProgress, setSwapsInProgress] = reactExports.useState([]); + const { closeSelectPaymentModal } = useSelectPaymentModal(); + const network2 = findSupportedNetwork(chain); + const chainId = (network2 == null ? void 0 : network2.chainId) || 137; + const { data: allowanceData, isLoading: allowanceIsLoading, refetch: refechAllowance } = useReadContract({ + abi: ERC_20_CONTRACT_ABI, + functionName: "allowance", + chainId, + address: targetContractAddress, + args: [userAddress, targetContractAddress], + query: { + enabled: !!userAddress } - }; - const getAddFundsContent = () => { - const { location: location2 } = navigation; - switch (location2) { - default: - return jsxRuntimeExports$1.jsx(AddFundsContent, {}); + }); + const price = BigInt(priceRaw) || 0n; + const isApproved = allowanceData >= BigInt(price); + const { data: swapQuotes, isLoading: swapQuotesIsLoading } = useSwapQuotes({ + userAddress: userAddress ?? "", + currencyAddress: settings == null ? void 0 : settings.currencyAddress, + chainId, + currencyAmount: priceRaw, + withContractInfo: true + }); + const StatusMessage = ({ purchaseInProgress }) => { + if (purchaseInProgress) { + return jsxRuntimeExports$1.jsxs(Box, { flexDirection: "row", gap: "1", alignItems: "center", justifyContent: isMobile ? "center" : "flex-start", children: [jsxRuntimeExports$1.jsx(Text, { variant: "small", color: "text100", children: "In progress..." }), jsxRuntimeExports$1.jsx(Box, { justifyContent: "center", alignItems: "center", style: { height: "22px", width: "22px" }, children: jsxRuntimeExports$1.jsx(Spinner, { size: "sm" }) })] }); } + return null; }; reactExports.useEffect(() => { - if (openCheckoutModal || openAddFundsModal) { - setHistory([]); - } - }, [openCheckoutModal, openAddFundsModal]); - return jsxRuntimeExports$1.jsx(AddFundsContextProvider, { value: { - triggerAddFunds, - closeAddFunds, - addFundsSettings - }, children: jsxRuntimeExports$1.jsx(CheckoutModalContextProvider, { value: { - triggerCheckout, - closeCheckout, - settings, - theme - }, children: jsxRuntimeExports$1.jsxs(NavigationContextProvider$1, { value: { history, setHistory, defaultLocation: getDefaultLocation() }, children: [jsxRuntimeExports$1.jsx("div", { id: "kit-checkout", children: jsxRuntimeExports$1.jsx(ThemeProvider, { root: "#kit-checkout", scope: "kit", theme, children: jsxRuntimeExports$1.jsxs(AnimatePresence, { children: [openCheckoutModal && jsxRuntimeExports$1.jsx(Modal, { contentProps: { - style: { - maxWidth: "400px", - height: "auto", - ...getModalPositionCss(position) + clearCachedBalances(); + setSwapsInProgress([]); + }, []); + const isLoading = swapQuotesIsLoading || allowanceIsLoading; + if (isLoading) { + return jsxRuntimeExports$1.jsx(Card, { width: "full", flexDirection: "column", alignItems: "center", justifyContent: "center", style: { + minHeight: getCardHeight(isMobile) + }, children: jsxRuntimeExports$1.jsx(Spinner, {}) }); + } + const onClickPurchase = async (swapQuote) => { + var _a2; + if (!walletClient || !userAddress || !publicClient || !userAddress || !connector) { + return; } - }, scroll: false, backdropColor: "backgroundBackdrop", onClose: () => setOpenCheckoutModal(false), children: jsxRuntimeExports$1.jsxs(Box, { id: "sequence-kit-checkout-content", children: [getCheckoutHeader(), getCheckoutContent()] }) }), openAddFundsModal && jsxRuntimeExports$1.jsx(Modal, { contentProps: { - style: { - maxWidth: "400px", - height: "auto", - ...getModalPositionCss(position) + const swapQuoteAddress = ((_a2 = swapQuote.info) == null ? void 0 : _a2.address) || ""; + setDisableButtons(true); + setSwapsInProgress([...swapsInProgress.filter((address) => compareAddress$2(address, swapQuoteAddress)), swapQuoteAddress]); + try { + const walletClientChainId = await walletClient.getChainId(); + if (walletClientChainId !== chainId) { + await walletClient.switchChain({ id: chainId }); + } + const approveTxData = encodeFunctionData({ + abi: ERC_20_CONTRACT_ABI, + functionName: "approve", + args: [targetContractAddress, price] + }); + const transactions2 = [ + // Swap quote optional approve step + ...swapQuote.quote.approveData ? [ + { + to: swapQuote.quote.currencyAddress, + data: swapQuote.quote.approveData, + chain: chainId + } + ] : [], + // Swap quote tx + { + to: swapQuote.quote.to, + data: swapQuote.quote.transactionData, + chain: chainId + }, + // Actual transaction optional approve step + ...isApproved ? [] : [ + { + to: currencyAddress, + data: approveTxData, + chainId + } + ], + // transaction on the contract + { + to: targetContractAddress, + data: txData, + chainId + } + ]; + const txHash = await sendTransactions({ + chainId, + senderAddress: userAddress, + publicClient, + walletClient, + connector, + transactions: transactions2, + transactionConfirmations + }); + closeSelectPaymentModal(); + refechAllowance(); + clearCachedBalances(); + onSuccess(txHash); + } catch (e2) { + console.error("Failed to purchase...", e2); + onError(e2); + } + setDisableButtons(false); + setSwapsInProgress([...swapsInProgress.filter((address) => compareAddress$2(address, swapQuoteAddress))]); + }; + return swapQuotes == null ? void 0 : swapQuotes.map((swapQuote, index2) => { + var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _i2, _j2, _k2, _l2; + const swapQuotePriceFormatted = formatUnits(BigInt(swapQuote.quote.price), ((_a2 = swapQuote.info) == null ? void 0 : _a2.decimals) || 18); + const balanceFormatted = formatUnits(BigInt(((_b2 = swapQuote.balance) == null ? void 0 : _b2.balance) || 0), ((_c2 = swapQuote.info) == null ? void 0 : _c2.decimals) || 18); + const swapQuoteAddress = ((_d2 = swapQuote.info) == null ? void 0 : _d2.address) || ""; + const purchaseInProgress = swapsInProgress.includes(swapQuoteAddress); + const currencyInfoNotFound = !swapQuote.info || ((_e2 = swapQuote == null ? void 0 : swapQuote.info) == null ? void 0 : _e2.decimals) === void 0 || !((_f2 = swapQuote.balance) == null ? void 0 : _f2.balance); + if (currencyInfoNotFound) { + return null; } - }, scroll: false, backdropColor: "backgroundBackdrop", onClose: () => setOpenAddFundsModal(false), children: jsxRuntimeExports$1.jsxs(Box, { id: "sequence-kit-add-funds-content", children: [getAddFundsHeader(), getAddFundsContent()] }) })] }) }) }), children] }) }) }); + return jsxRuntimeExports$1.jsxs(Card, { width: "full", flexDirection: isMobile ? "column" : "row", alignItems: "center", justifyContent: "space-between", gap: isMobile ? "2" : "0", style: { + minHeight: getCardHeight(isMobile) + }, children: [jsxRuntimeExports$1.jsxs(Box, { flexDirection: "column", gap: "2", justifyContent: isMobile ? "center" : "flex-start", children: [jsxRuntimeExports$1.jsx(Box, { justifyContent: isMobile ? "center" : "flex-start", children: jsxRuntimeExports$1.jsxs(Text, { variant: "normal", color: "text100", children: ["Buy With ", ((_g2 = swapQuote.info) == null ? void 0 : _g2.name) || "Unknown"] }) }), jsxRuntimeExports$1.jsxs(Box, { flexDirection: "row", gap: "1", alignItems: "center", justifyContent: isMobile ? "center" : "flex-start", children: [jsxRuntimeExports$1.jsx(Text, { variant: "small", color: "text100", children: `Price: ${swapQuotePriceFormatted} ${(_h2 = swapQuote.info) == null ? void 0 : _h2.symbol}` }), jsxRuntimeExports$1.jsx(TokenImage, { size: "xs", src: (_i2 = swapQuote.info) == null ? void 0 : _i2.logoURI })] }), jsxRuntimeExports$1.jsxs(Box, { flexDirection: "row", gap: "1", alignItems: "center", justifyContent: isMobile ? "center" : "flex-start", children: [jsxRuntimeExports$1.jsx(Text, { variant: "small", color: "text100", children: `Balance: ${balanceFormatted} ${(_j2 = swapQuote.info) == null ? void 0 : _j2.symbol}` }), jsxRuntimeExports$1.jsx(TokenImage, { size: "xs", src: (_k2 = swapQuote.info) == null ? void 0 : _k2.logoURI })] }), jsxRuntimeExports$1.jsx(StatusMessage, { purchaseInProgress })] }), jsxRuntimeExports$1.jsx(Box, { flexDirection: "column", gap: "2", alignItems: isMobile ? "center" : "flex-start", style: { ...isMobile ? { width: "200px" } : {} }, children: jsxRuntimeExports$1.jsx(Button, { label: "Purchase", onClick: () => onClickPurchase(swapQuote), disabled: purchaseInProgress || disableButtons, variant: "primary", shape: "square", pending: purchaseInProgress }) })] }, ((_l2 = swapQuote.info) == null ? void 0 : _l2.address) || index2); + }); }; -const ERC_1155_ABI = [ - { - inputs: [ - { - internalType: "address", - name: "_from", - type: "address" - }, - { - internalType: "address", - name: "_to", - type: "address" - }, - { - internalType: "uint256[]", - name: "_ids", - type: "uint256[]" - }, - { - internalType: "uint256[]", - name: "_amounts", - type: "uint256[]" - }, - { - internalType: "bytes", - name: "_data", - type: "bytes" - } - ], - name: "safeBatchTransferFrom", - outputs: [], - stateMutability: "nonpayable", - type: "function" - } -]; -const ERC_20_ABI = [ - { - constant: false, - inputs: [ - { - internalType: "address", - name: "recipient", - type: "address" - }, - { - internalType: "uint256", - name: "amount", - type: "uint256" - } - ], - name: "transfer", - outputs: [ - { - internalType: "bool", - name: "", - type: "bool" - } - ], - payable: false, - stateMutability: "nonpayable", - type: "function" - } -]; -const ERC_721_ABI = [ - { - inputs: [ - { - internalType: "address", - name: "from", - type: "address" - }, - { - internalType: "address", - name: "to", - type: "address" - }, - { - internalType: "uint256", - name: "tokenId", - type: "uint256" - } - ], - name: "safeTransferFrom", - outputs: [], - stateMutability: "nonpayable", - type: "function" - } -]; -const supportedFiatCurrencies = [ - { symbol: "USD", sign: "$", name: { message: "US Dollar" }, decimals: 2 }, - { symbol: "CAD", sign: "$", name: { message: "Canadian Dollar" }, decimals: 2 }, - { symbol: "GBP", sign: "£", name: { message: "British Pound Sterling" }, decimals: 2 }, - { symbol: "EUR", sign: "€", name: { message: "Euro" }, decimals: 2 }, - { symbol: "CNY", sign: "¥", name: { message: "Chinese Yuan" }, decimals: 2 }, - { symbol: "JPY", sign: "¥", name: { message: "Japanese Yen" }, decimals: 2 }, - { symbol: "KRW", sign: "₩", name: { message: "South Korean Won" }, decimals: 2 }, - { symbol: "SGD", sign: "$", name: { message: "Singapore Dollar" }, decimals: 2 }, - { symbol: "CHF", sign: "CHF ", name: { message: "Swiss Franc" }, decimals: 2 }, - { symbol: "AUD", sign: "$", name: { message: "Australian Dollar" }, decimals: 2 }, - { symbol: "NZD", sign: "$", name: { message: "New Zealand Dollar" }, decimals: 2 }, - { symbol: "SEK", sign: "kr ", name: { message: "Swedish Krona" }, decimals: 2 }, - { symbol: "NOK", sign: "kr ", name: { message: "Norwegian Krone" }, decimals: 2 }, - { symbol: "MXN", sign: "$", name: { message: "Mexican Peso" }, decimals: 2 }, - { symbol: "INR", sign: "₹", name: { message: "Indian Rupee" }, decimals: 2 }, - { symbol: "ZAR", sign: "R ", name: { message: "South African Rand" }, decimals: 2 }, - { symbol: "TRY", sign: "₺", name: { message: "Turkish Lira" }, decimals: 2 }, - { symbol: "BRL", sign: "R$", name: { message: "Brazilian Real" }, decimals: 2 }, - { symbol: "DKK", sign: "kr ", name: { message: "Danish Krone" }, decimals: 2 }, - { symbol: "PLN", sign: "zł ", name: { message: "Polish Zloty" }, decimals: 2 }, - { symbol: "THB", sign: "฿", name: { message: "Thai Baht" }, decimals: 2 }, - { symbol: "IDR", sign: "Rp", name: { message: "Indonesian Rupiah" }, decimals: 2 } -]; -const defaultFiatCurrency = supportedFiatCurrencies[0]; -const HEADER_HEIGHT = "54px"; -const createGenericContext = () => { - const genericContext = reactExports.createContext(void 0); - const useGenericContext = () => { - const contextIsDefined = reactExports.useContext(genericContext); - if (!contextIsDefined) { - throw new Error("useGenericContext must be used within a Provider"); +const PayWithCrypto = ({ settings, disableButtons, setDisableButtons }) => { + const { enableSwapPayments } = settings; + return jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment, { children: [jsxRuntimeExports$1.jsx(PayWithMainCurrency, { settings, disableButtons, setDisableButtons }), enableSwapPayments && jsxRuntimeExports$1.jsx(SwapAndPay, { settings, disableButtons, setDisableButtons })] }); +}; +const PayWithCreditCard = ({ settings, disableButtons }) => { + const { chain, currencyAddress, targetContractAddress, price, txData, tokenId, collectionAddress, nftQuantity, nftDecimals = "0", isDev = false, onSuccess = () => { + }, onError = () => { + } } = settings; + const { address: userAddress } = useAccount(); + const isMobile = useMediaQuery("isMobile"); + const { clearCachedBalances } = useClearCachedBalances(); + const { closeSelectPaymentModal } = useSelectPaymentModal(); + const { triggerCheckout } = useCheckoutModal(); + const network2 = findSupportedNetwork(chain); + const chainId = (network2 == null ? void 0 : network2.chainId) || 137; + const { data: currencyInfoData, isLoading: isLoadingContractInfo } = useContractInfo(chainId, currencyAddress); + const isLoading = isLoadingContractInfo; + const onClickPurchase = () => { + if (!userAddress || !currencyInfoData) { + return; } - return contextIsDefined; + const checkoutSettings = { + creditCardCheckout: { + onSuccess: (txHash) => { + clearCachedBalances(); + onSuccess(txHash); + }, + onError, + chainId, + recipientAddress: userAddress, + contractAddress: targetContractAddress, + currencyQuantity: price, + currencySymbol: currencyInfoData.symbol, + currencyAddress, + currencyDecimals: String((currencyInfoData == null ? void 0 : currencyInfoData.decimals) || 0), + nftId: tokenId, + nftAddress: collectionAddress, + nftQuantity, + nftDecimals, + isDev, + calldata: txData, + approvedSpenderAddress: targetContractAddress + } + }; + closeSelectPaymentModal(); + triggerCheckout(checkoutSettings); + }; + if (isLoading) { + return jsxRuntimeExports$1.jsx(Card, { width: "full", flexDirection: "column", alignItems: "center", justifyContent: "center", style: { + minHeight: getCardHeight(isMobile) + }, children: jsxRuntimeExports$1.jsx(Spinner, {}) }); + } + return jsxRuntimeExports$1.jsxs(Card, { width: "full", flexDirection: isMobile ? "column" : "row", alignItems: "center", justifyContent: "space-between", gap: isMobile ? "2" : "0", style: { + minHeight: getCardHeight(isMobile) + }, children: [jsxRuntimeExports$1.jsx(Box, { justifyContent: isMobile ? "center" : "flex-start", children: jsxRuntimeExports$1.jsx(Text, { variant: "normal", color: "text100", children: "Buy With Credit Card" }) }), jsxRuntimeExports$1.jsx(Box, { flexDirection: "column", gap: "2", alignItems: isMobile ? "center" : "flex-start", style: { ...isMobile ? { width: "200px" } : {} }, children: jsxRuntimeExports$1.jsx(Button, { disabled: disableButtons, label: "Purchase", onClick: onClickPurchase, variant: "primary", shape: "square" }) })] }); +}; +const TransferFunds = ({ disableButtons }) => { + const isMobile = useMediaQuery("isMobile"); + const { openTransferFundsModal } = useTransferFundsModal(); + const { address: userAddress } = useAccount(); + const { closeSelectPaymentModal, openSelectPaymentModal, selectPaymentSettings } = useSelectPaymentModal(); + const onClickTransfer = () => { + if (!userAddress) { + return; + } + closeSelectPaymentModal(); + openTransferFundsModal({ + walletAddress: userAddress, + onClose: () => { + setTimeout(() => { + if (selectPaymentSettings) { + openSelectPaymentModal(selectPaymentSettings); + } + }, 500); + } + }); }; - return [useGenericContext, genericContext.Provider]; -}; -const [useWalletModalContext, WalletModalContextProvider] = createGenericContext(); -const [useNavigationContext, NavigationContextProvider] = createGenericContext(); -const useOpenWalletModal = () => { - const { setOpenWalletModal, openWalletModalState } = useWalletModalContext(); - return { setOpenWalletModal, openWalletModalState }; + return jsxRuntimeExports$1.jsxs(Card, { width: "full", flexDirection: isMobile ? "column" : "row", alignItems: "center", justifyContent: "space-between", gap: isMobile ? "2" : "0", style: { + minHeight: getCardHeight(isMobile) + }, children: [jsxRuntimeExports$1.jsx(Box, { justifyContent: isMobile ? "center" : "flex-start", children: jsxRuntimeExports$1.jsx(Text, { color: "text100", children: "Transfer Funds to Wallet" }) }), jsxRuntimeExports$1.jsx(Box, { flexDirection: "column", gap: "2", alignItems: isMobile ? "center" : "flex-start", style: { ...isMobile ? { width: "200px" } : {} }, children: jsxRuntimeExports$1.jsx(Button, { disabled: disableButtons, label: "Transfer", onClick: onClickTransfer, variant: "primary", shape: "square" }) })] }); }; -const compareAddress = (a2, b2) => { - return a2.toLowerCase() === b2.toLowerCase(); +const FiatOnRamp = ({ disableButtons }) => { + const isMobile = useMediaQuery("isMobile"); + const { closeSelectPaymentModal, openSelectPaymentModal, selectPaymentSettings } = useSelectPaymentModal(); + const { triggerAddFunds } = useAddFundsModal(); + const { address: userAddress } = useAccount(); + const onClickPurchase = () => { + closeSelectPaymentModal(); + triggerAddFunds({ + walletAddress: userAddress || "", + onClose: () => { + setTimeout(() => { + if (selectPaymentSettings) { + openSelectPaymentModal(selectPaymentSettings); + } + }, 500); + } + }); + }; + return jsxRuntimeExports$1.jsxs(Card, { width: "full", flexDirection: isMobile ? "column" : "row", alignItems: "center", justifyContent: "space-between", gap: isMobile ? "2" : "0", style: { + minHeight: getCardHeight(isMobile) + }, children: [jsxRuntimeExports$1.jsx(Box, { justifyContent: isMobile ? "center" : "flex-start", children: jsxRuntimeExports$1.jsx(Text, { variant: "normal", color: "text100", children: "Purchase Crypto" }) }), jsxRuntimeExports$1.jsx(Box, { flexDirection: "column", gap: "2", alignItems: isMobile ? "center" : "flex-start", style: { ...isMobile ? { width: "200px" } : {} }, children: jsxRuntimeExports$1.jsx(Button, { disabled: disableButtons, label: "Purchase", onClick: onClickPurchase, variant: "primary", shape: "square" }) })] }); }; -const truncateAtMiddle = (text2, truncateAt) => { - let finalText = text2; - if (text2.length >= truncateAt) { - finalText = text2.slice(0, truncateAt / 2) + "..." + text2.slice(text2.length - truncateAt / 2, text2.length); - } - return finalText; +const PaymentSelection = () => { + return jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment, { children: [jsxRuntimeExports$1.jsx(PaymentSelectionHeader, {}), jsxRuntimeExports$1.jsx(PaymentSelectionContent, {})] }); }; -const formatAddress = (text2) => { - return `0x${truncateAtMiddle((text2 == null ? void 0 : text2.substring(2)) || "", 8)}`; +const PaymentSelectionHeader = () => { + return jsxRuntimeExports$1.jsx(NavigationHeader$1, { primaryText: "Select Payment Method" }); }; -var ValueType; -(function(ValueType2) { - ValueType2[ValueType2["VERY_LARGE"] = 0] = "VERY_LARGE"; - ValueType2[ValueType2["FRACTION"] = 1] = "FRACTION"; - ValueType2[ValueType2["VERY_TINY"] = 2] = "VERY_TINY"; - ValueType2[ValueType2["MIXED"] = 3] = "MIXED"; -})(ValueType || (ValueType = {})); -const formatDisplay = (_val2) => { - if (isNaN(Number(_val2))) { - console.error(`display format error ${_val2} is not a number`); - return "NaN"; - } - const val = Number(_val2); - if (val === 0) { - return "0"; - } - let valMode; - if (val > 1e8) { - valMode = ValueType.VERY_LARGE; - } else if (val < 1e-10) { - valMode = ValueType.VERY_TINY; - } else if (val < 1) { - valMode = ValueType.FRACTION; - } else { - valMode = ValueType.MIXED; - } - let notation = void 0; - let config2; - switch (valMode) { - case ValueType.VERY_LARGE: - notation = "compact"; - config2 = { - maximumFractionDigits: 4 - }; - break; - case ValueType.VERY_TINY: - notation = "scientific"; - config2 = { - maximumFractionDigits: 4 - }; - break; - case ValueType.FRACTION: - notation = "standard"; - config2 = { - maximumSignificantDigits: 4 - }; - break; - default: - notation = "standard"; - config2 = { - maximumFractionDigits: 2 - }; +const PaymentSelectionContent = () => { + const { selectPaymentSettings } = useSelectPaymentModal(); + const [disableButtons, setDisableButtons] = reactExports.useState(false); + if (!selectPaymentSettings) { + return null; } - return Intl.NumberFormat("en-US", { - notation, - ...config2 - }).format(val); + const enableMainCurrencyPayment = (selectPaymentSettings == null ? void 0 : selectPaymentSettings.enableMainCurrencyPayment) === void 0; + const enableSwapPayments = (selectPaymentSettings == null ? void 0 : selectPaymentSettings.enableSwapPayments) === void 0; + const enableCreditCardPayments = (selectPaymentSettings == null ? void 0 : selectPaymentSettings.enableCreditCardPayments) ?? true; + const enableTransferFunds = (selectPaymentSettings == null ? void 0 : selectPaymentSettings.enableTransferFunds) ?? true; + const enableFiatOnRamp = (selectPaymentSettings == null ? void 0 : selectPaymentSettings.enableFiatOnRamp) ?? true; + const noPaymentOptionFound = !enableMainCurrencyPayment && !enableSwapPayments && !enableTransferFunds && !enableFiatOnRamp && !enableCreditCardPayments; + return jsxRuntimeExports$1.jsxs(Box, { flexDirection: "column", gap: "2", alignItems: "flex-start", width: "full", paddingX: "4", paddingBottom: "4", height: "full", style: { height: "600px", paddingTop: HEADER_HEIGHT$1 }, children: [enableCreditCardPayments && jsxRuntimeExports$1.jsx(PayWithCreditCard, { settings: selectPaymentSettings, disableButtons }), (enableMainCurrencyPayment || enableSwapPayments) && jsxRuntimeExports$1.jsx(PayWithCrypto, { settings: selectPaymentSettings, disableButtons, setDisableButtons }), enableTransferFunds && jsxRuntimeExports$1.jsx(TransferFunds, { disableButtons }), enableFiatOnRamp && jsxRuntimeExports$1.jsx(FiatOnRamp, { disableButtons }), noPaymentOptionFound && jsxRuntimeExports$1.jsx(Box, { width: "full", justifyContent: "center", alignItems: "center", marginTop: "10", children: jsxRuntimeExports$1.jsx(Text, { color: "text100", children: "No Payment Option Found" }) })] }); }; -const limitDecimals = (value, decimals) => { - const splitValue = value.split("."); - if (splitValue.length === 1) { - return value; - } - return `${splitValue[0]}.${splitValue[1].slice(0, decimals)}`; +var __defProp2 = Object.defineProperty; +var __getOwnPropSymbols = Object.getOwnPropertySymbols; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __propIsEnum = Object.prototype.propertyIsEnumerable; +var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues = (a2, b2) => { + for (var prop in b2 || (b2 = {})) + if (__hasOwnProp.call(b2, prop)) + __defNormalProp2(a2, prop, b2[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b2)) { + if (__propIsEnum.call(b2, prop)) + __defNormalProp2(a2, prop, b2[prop]); + } + return a2; }; -const isEthAddress = (value) => { - const ethAddressRegEx = /0x[a-fA-F0-9]{40}/; - const isEthAddress2 = ethAddressRegEx.test(value); - return isEthAddress2; +var __objRest = (source, exclude) => { + var target = {}; + for (var prop in source) + if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0) + target[prop] = source[prop]; + if (source != null && __getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(source)) { + if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop)) + target[prop] = source[prop]; + } + return target; }; -const sampleSize = (collection, n2) => { - const length = collection.length; - if (!length || n2 < 1) { - return []; - } - n2 = n2 > length ? length : n2; - const sampled = new Array(n2); - const indexes = /* @__PURE__ */ new Set(); - while (indexes.size < n2) { - indexes.add(Math.floor(Math.random() * length)); - } - let index2 = 0; - for (const i of indexes) { - sampled[index2++] = collection[i]; - } - return sampled; -}; -const isTruthy = (value) => Boolean(value); -const getPercentageColor = (value) => { - if (value > 0) { - return vars.colors.positive; - } else if (value < 0) { - return vars.colors.negative; - } else { - return vars.colors.text50; - } -}; -const getPercentagePriceChange = (balance, prices) => { - var _a2; - const priceForToken = prices.find((p2) => compareAddress(p2.token.contractAddress, balance.contractAddress)); - if (!priceForToken) { - return 0; - } - const price24HourChange = ((_a2 = priceForToken == null ? void 0 : priceForToken.price24hChange) == null ? void 0 : _a2.value) || 0; - return price24HourChange; -}; -const computeBalanceFiat = ({ balance, prices, decimals, conversionRate }) => { - var _a2; - let totalUsd = 0; - const priceForToken = prices.find((p2) => compareAddress(p2.token.contractAddress, balance.contractAddress)); - if (!priceForToken) { - return "0.00"; - } - const priceFiat = ((_a2 = priceForToken.price) == null ? void 0 : _a2.value) || 0; - const valueFormatted = formatUnits$2(balance.balance, decimals); - const usdValue = parseFloat(valueFormatted) * priceFiat; - totalUsd += usdValue; - const fiatValue = totalUsd * conversionRate; - return `${fiatValue.toFixed(2)}`; -}; -const compareTokenBalanceIds = (a2, b2) => { - return (a2.tokenID || "").localeCompare(b2.tokenID || ""); -}; -const sortBalancesByType = (balances) => { - const nativeTokens = []; - const erc20Tokens = []; - const collectibles = []; - balances.forEach((balance) => { - if (balance.contractAddress === ZeroAddress) { - nativeTokens.push(balance); - } else if (balance.contractType === "ERC20") { - erc20Tokens.push(balance); - } else if (balance.contractType === "ERC721" || balance.contractType === "ERC1155") { - collectibles.push(balance); - } - }); - const sortedNativeTokens = nativeTokens.sort(compareTokenBalanceIds); - const sortedErc20Tokens = erc20Tokens.sort(compareTokenBalanceIds); - const sortedCollectibles = collectibles.sort(compareTokenBalanceIds); - return { - nativeTokens: sortedNativeTokens, - erc20Tokens: sortedErc20Tokens, - collectibles: sortedCollectibles - }; -}; -const flattenPaginatedTransactionHistory = (transactionHistoryData) => { - const transactionHistory = []; - transactionHistoryData == null ? void 0 : transactionHistoryData.pages.forEach((page) => { - transactionHistory.push(...page.transactions); - }); - return transactionHistory; -}; -const time = { - oneSecond: 1 * 1e3, - oneMinute: 60 * 1e3, - oneHour: 60 * 60 * 1e3 -}; -const getBalancesAssetsSummary = async (apiClient, metadataClient, indexerClients, { accountAddress, displayAssets, hideCollectibles, verifiedOnly }) => { - const indexerClientsArr = Array.from(indexerClients.entries()); - const MAX_COLLECTIBLES_AMOUNTS = 10; - let tokenBalances = []; - const customDisplayAssets = displayAssets.length > 0; - try { - if (customDisplayAssets) { - const nativeTokens2 = displayAssets.filter((asset) => compareAddress(asset.contractAddress, ZeroAddress)); - const otherAssets = displayAssets.filter((asset) => !compareAddress(asset.contractAddress, ZeroAddress)); - const nativeTokensByChainId = {}; - const otherAssetsByChainId = {}; - nativeTokens2.forEach((asset) => { - if (!nativeTokensByChainId[asset.chainId]) { - nativeTokensByChainId[asset.chainId] = []; +/** + * @license QR Code generator library (TypeScript) + * Copyright (c) Project Nayuki. + * SPDX-License-Identifier: MIT + */ +var qrcodegen; +((qrcodegen2) => { + const _QrCode = class { + constructor(version2, errorCorrectionLevel, dataCodewords, msk) { + this.version = version2; + this.errorCorrectionLevel = errorCorrectionLevel; + this.modules = []; + this.isFunction = []; + if (version2 < _QrCode.MIN_VERSION || version2 > _QrCode.MAX_VERSION) + throw new RangeError("Version value out of range"); + if (msk < -1 || msk > 7) + throw new RangeError("Mask value out of range"); + this.size = version2 * 4 + 17; + let row = []; + for (let i = 0; i < this.size; i++) + row.push(false); + for (let i = 0; i < this.size; i++) { + this.modules.push(row.slice()); + this.isFunction.push(row.slice()); + } + this.drawFunctionPatterns(); + const allCodewords = this.addEccAndInterleave(dataCodewords); + this.drawCodewords(allCodewords); + if (msk == -1) { + let minPenalty = 1e9; + for (let i = 0; i < 8; i++) { + this.applyMask(i); + this.drawFormatBits(i); + const penalty = this.getPenaltyScore(); + if (penalty < minPenalty) { + msk = i; + minPenalty = penalty; + } + this.applyMask(i); } - nativeTokensByChainId[asset.chainId].push(asset); - }); - otherAssets.forEach((asset) => { - if (!otherAssetsByChainId[asset.chainId]) { - otherAssetsByChainId[asset.chainId] = []; + } + assert2(0 <= msk && msk <= 7); + this.mask = msk; + this.applyMask(msk); + this.drawFormatBits(msk); + this.isFunction = []; + } + static encodeText(text2, ecl) { + const segs = qrcodegen2.QrSegment.makeSegments(text2); + return _QrCode.encodeSegments(segs, ecl); + } + static encodeBinary(data, ecl) { + const seg = qrcodegen2.QrSegment.makeBytes(data); + return _QrCode.encodeSegments([seg], ecl); + } + static encodeSegments(segs, ecl, minVersion = 1, maxVersion = 40, mask2 = -1, boostEcl = true) { + if (!(_QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= _QrCode.MAX_VERSION) || mask2 < -1 || mask2 > 7) + throw new RangeError("Invalid value"); + let version2; + let dataUsedBits; + for (version2 = minVersion; ; version2++) { + const dataCapacityBits2 = _QrCode.getNumDataCodewords(version2, ecl) * 8; + const usedBits = QrSegment.getTotalBits(segs, version2); + if (usedBits <= dataCapacityBits2) { + dataUsedBits = usedBits; + break; } - otherAssetsByChainId[asset.chainId].push(asset); - }); - tokenBalances = (await Promise.all([ - ...Object.keys(nativeTokensByChainId).map((chainId) => { - const indexerClient = indexerClients.get(Number(chainId)); - if (!indexerClient) { - console.error(`Indexer client not found for chainId: ${chainId}, did you forget to add this Chain?`); - return null; - } - return getNativeTokenBalance(indexerClient, Number(chainId), accountAddress); - }), - ...Object.keys(otherAssetsByChainId).map((chainId) => otherAssetsByChainId[Number(chainId)].map((asset) => { - const indexerClient = indexerClients.get(Number(chainId)); - if (!indexerClient) { - console.error(`Indexer client not found for chainId: ${chainId}, did you forget to add this Chain?`); - return []; - } - return getTokenBalances(indexerClient, { - accountAddress, - contractAddress: asset.contractAddress, - includeMetadata: false, - hideCollectibles, - verifiedOnly - }); - })).flat() - ])).flat().filter(isTruthy); - } else { - tokenBalances = (await Promise.all([ - ...indexerClientsArr.map(([chainId, indexerClient]) => getNativeTokenBalance(indexerClient, chainId, accountAddress)), - ...indexerClientsArr.map(([_chainId4, indexerClient]) => getTokenBalances(indexerClient, { - accountAddress, - hideCollectibles, - includeMetadata: false, - verifiedOnly - })) - ])).flat(); + if (version2 >= maxVersion) + throw new RangeError("Data too long"); + } + for (const newEcl of [_QrCode.Ecc.MEDIUM, _QrCode.Ecc.QUARTILE, _QrCode.Ecc.HIGH]) { + if (boostEcl && dataUsedBits <= _QrCode.getNumDataCodewords(version2, newEcl) * 8) + ecl = newEcl; + } + let bb2 = []; + for (const seg of segs) { + appendBits(seg.mode.modeBits, 4, bb2); + appendBits(seg.numChars, seg.mode.numCharCountBits(version2), bb2); + for (const b2 of seg.getData()) + bb2.push(b2); + } + assert2(bb2.length == dataUsedBits); + const dataCapacityBits = _QrCode.getNumDataCodewords(version2, ecl) * 8; + assert2(bb2.length <= dataCapacityBits); + appendBits(0, Math.min(4, dataCapacityBits - bb2.length), bb2); + appendBits(0, (8 - bb2.length % 8) % 8, bb2); + assert2(bb2.length % 8 == 0); + for (let padByte = 236; bb2.length < dataCapacityBits; padByte ^= 236 ^ 17) + appendBits(padByte, 8, bb2); + let dataCodewords = []; + while (dataCodewords.length * 8 < bb2.length) + dataCodewords.push(0); + bb2.forEach((b2, i) => dataCodewords[i >>> 3] |= b2 << 7 - (i & 7)); + return new _QrCode(version2, ecl, dataCodewords, mask2); } - const { nativeTokens, erc20Tokens, collectibles: collectionBalances } = sortBalancesByType(tokenBalances); - const fetchPricesPromise = new Promise(async (resolve) => { - if (erc20Tokens.length > 0) { - const tokens = erc20Tokens.map((token) => ({ - chainId: token.chainId, - contractAddress: token.contractAddress - })); - const prices2 = await getCoinPrices(apiClient, tokens) || []; - resolve(prices2); - } else { - resolve([]); + getModule(x2, y2) { + return 0 <= x2 && x2 < this.size && 0 <= y2 && y2 < this.size && this.modules[y2][x2]; + } + getModules() { + return this.modules; + } + drawFunctionPatterns() { + for (let i = 0; i < this.size; i++) { + this.setFunctionModule(6, i, i % 2 == 0); + this.setFunctionModule(i, 6, i % 2 == 0); } - }); - const fetchCollectiblesPromises = collectionBalances.map(async (collectionBalance) => { - if (customDisplayAssets) { - return collectionBalance; + this.drawFinderPattern(3, 3); + this.drawFinderPattern(this.size - 4, 3); + this.drawFinderPattern(3, this.size - 4); + const alignPatPos = this.getAlignmentPatternPositions(); + const numAlign = alignPatPos.length; + for (let i = 0; i < numAlign; i++) { + for (let j2 = 0; j2 < numAlign; j2++) { + if (!(i == 0 && j2 == 0 || i == 0 && j2 == numAlign - 1 || i == numAlign - 1 && j2 == 0)) + this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j2]); + } } - const indexerClient = indexerClients.get(collectionBalance.chainId); - if (!indexerClient) { - throw new Error(`Indexer client not found for chainId: ${collectionBalance.chainId}, did you forget to add this Chain?`); + this.drawFormatBits(0); + this.drawVersion(); + } + drawFormatBits(mask2) { + const data = this.errorCorrectionLevel.formatBits << 3 | mask2; + let rem = data; + for (let i = 0; i < 10; i++) + rem = rem << 1 ^ (rem >>> 9) * 1335; + const bits = (data << 10 | rem) ^ 21522; + assert2(bits >>> 15 == 0); + for (let i = 0; i <= 5; i++) + this.setFunctionModule(8, i, getBit(bits, i)); + this.setFunctionModule(8, 7, getBit(bits, 6)); + this.setFunctionModule(8, 8, getBit(bits, 7)); + this.setFunctionModule(7, 8, getBit(bits, 8)); + for (let i = 9; i < 15; i++) + this.setFunctionModule(14 - i, 8, getBit(bits, i)); + for (let i = 0; i < 8; i++) + this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i)); + for (let i = 8; i < 15; i++) + this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i)); + this.setFunctionModule(8, this.size - 8, true); + } + drawVersion() { + if (this.version < 7) + return; + let rem = this.version; + for (let i = 0; i < 12; i++) + rem = rem << 1 ^ (rem >>> 11) * 7973; + const bits = this.version << 12 | rem; + assert2(bits >>> 18 == 0); + for (let i = 0; i < 18; i++) { + const color2 = getBit(bits, i); + const a2 = this.size - 11 + i % 3; + const b2 = Math.floor(i / 3); + this.setFunctionModule(a2, b2, color2); + this.setFunctionModule(b2, a2, color2); } - const balance = await getCollectionBalance(indexerClient, { - accountAddress, - chainId: collectionBalance.chainId, - contractAddress: collectionBalance.contractAddress, - includeMetadata: false - }); - return balance; - }); - const fetchErc20ContractInfoPromise = async () => { - const contractInfoMapByChainId2 = {}; - const erc20BalanceByChainId = {}; - erc20Tokens.forEach((erc20Token) => { - if (!erc20BalanceByChainId[erc20Token.chainId]) { - erc20BalanceByChainId[erc20Token.chainId] = [erc20Token]; - } else { - erc20BalanceByChainId[erc20Token.chainId].push(erc20Token); + } + drawFinderPattern(x2, y2) { + for (let dy = -4; dy <= 4; dy++) { + for (let dx = -4; dx <= 4; dx++) { + const dist2 = Math.max(Math.abs(dx), Math.abs(dy)); + const xx = x2 + dx; + const yy = y2 + dy; + if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size) + this.setFunctionModule(xx, yy, dist2 != 2 && dist2 != 4); } - }); - const contractInfoPromises = Object.keys(erc20BalanceByChainId).map(async (chainId) => { - const tokenBalances2 = erc20BalanceByChainId[Number(chainId)]; - const contractAddresses = tokenBalances2.map((balance) => balance.contractAddress); - const result = await metadataClient.getContractInfoBatch({ - chainID: String(chainId), - contractAddresses - }); - contractInfoMapByChainId2[Number(chainId)] = result; - }); - await Promise.all([...contractInfoPromises]); - return contractInfoMapByChainId2; - }; - const [prices, contractInfoMapByChainId, ...collectionCollectibles] = await Promise.all([ - fetchPricesPromise, - fetchErc20ContractInfoPromise(), - ...fetchCollectiblesPromises - ]); - const erc20HighestValue = erc20Tokens.sort((a2, b2) => { - var _a2, _b2; - const aPriceData = prices.find((price) => compareAddress(price.token.contractAddress, a2.contractAddress)); - const bPriceData = prices.find((price) => compareAddress(price.token.contractAddress, b2.contractAddress)); - const aPrice = (aPriceData == null ? void 0 : aPriceData.price) ? aPriceData.price.value : 0; - const bPrice = (bPriceData == null ? void 0 : bPriceData.price) ? bPriceData.price.value : 0; - const aDecimals = (_a2 = contractInfoMapByChainId[a2.chainId].contractInfoMap[a2.contractAddress]) == null ? void 0 : _a2.decimals; - const bDecimals = (_b2 = contractInfoMapByChainId[b2.chainId].contractInfoMap[b2.contractAddress]) == null ? void 0 : _b2.decimals; - const aFormattedBalance = aDecimals === void 0 ? 0 : Number(formatUnits$2(a2.balance, aDecimals)); - const bFormattedBalance = bDecimals === void 0 ? 0 : Number(formatUnits$2(b2.balance, bDecimals)); - const aValue = aFormattedBalance * aPrice; - const bValue = bFormattedBalance * bPrice; - return bValue - aValue; - }); - const collectibles = sampleSize(collectionCollectibles.flat(), MAX_COLLECTIBLES_AMOUNTS).sort((a2, b2) => { - return a2.contractAddress.localeCompare(b2.contractAddress); - }); - if (hideCollectibles) { - const summaryBalances2 = [ - ...nativeTokens.length > 0 ? [nativeTokens[0]] : [], - // the spots normally occupied by collectibles will be filled by erc20 tokens - ...erc20HighestValue.length > 0 ? erc20HighestValue.slice(0, MAX_COLLECTIBLES_AMOUNTS + 1) : [] - ]; - return summaryBalances2; + } } - const summaryBalances = [ - ...nativeTokens.length > 0 ? [nativeTokens[0]] : [], - ...erc20HighestValue.length > 0 ? [erc20HighestValue[0]] : [], - ...collectibles.length > 0 ? [...collectibles] : [] - ]; - return summaryBalances; - } catch (e2) { - console.error(e2); - return []; - } -}; -const useBalancesAssetsSummary = (args) => { - const apiClient = useAPIClient(); - const metadataClient = useMetadataClient(); - const indexerClients = useIndexerClients(args.chainIds); - return useQuery$1({ - queryKey: ["balancesAssetsSummary", args], - queryFn: () => getBalancesAssetsSummary(apiClient, metadataClient, indexerClients, args), - retry: true, - refetchInterval: time.oneSecond * 4, - refetchOnMount: true, - staleTime: time.oneSecond, - enabled: args.chainIds.length > 0 && !!args.accountAddress - }); -}; -const getTransactionHistorySummary = async (indexerClients, { accountAddress }) => { - const histories = await Promise.all(Array.from(indexerClients.values()).map((indexerClient) => getTransactionHistory(indexerClient, { - accountAddress, - page: { - page: 1 + drawAlignmentPattern(x2, y2) { + for (let dy = -2; dy <= 2; dy++) { + for (let dx = -2; dx <= 2; dx++) + this.setFunctionModule(x2 + dx, y2 + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1); + } } - }))); - const unorderedTransactions = histories.map((history) => history.transactions).flat(); - const orderedTransactions = unorderedTransactions.sort((a2, b2) => { - const firstDate = new Date(a2.timestamp).getTime(); - const secondDate = new Date(b2.timestamp).getTime(); - return secondDate - firstDate; - }); - return orderedTransactions; -}; -const useTransactionHistorySummary = (args) => { - const indexerClients = useIndexerClients(args.chainIds); - return useQuery$1({ - queryKey: ["transactionHistorySummary", args], - queryFn: () => getTransactionHistorySummary(indexerClients, args), - retry: true, - staleTime: time.oneSecond, - refetchOnMount: true, - enabled: args.chainIds.length > 0 && !!args.accountAddress - }); -}; -const useNavigation = () => { - const { setHistory, history } = useNavigationContext(); - const setNavigation = (navigation) => { - const childElement = document.getElementById("sequence-kit-wallet-content"); - const parentElement = childElement == null ? void 0 : childElement.parentElement; - parentElement == null ? void 0 : parentElement.scrollTo(0, 0); - const newHistory = navigation.location === "home" ? [] : [...history, navigation]; - setHistory(newHistory); - }; - const goBack = () => { - const newHistory = [...history]; - newHistory.pop(); - setHistory(newHistory); - }; - return { setNavigation, history, setHistory, goBack }; -}; -const useSettings = () => { - const { chains: chains2 } = useConfig(); - const getSettingsFromStorage = () => { - let hideUnlistedTokens = true; - let hideCollectibles = false; - let fiatCurrency = defaultFiatCurrency; - let selectedNetworks = chains2.map((chain) => chain.id); - try { - const settingsStorage = localStorage.getItem(LocalStorageKey.Settings); - const settings2 = JSON.parse(settingsStorage || "{}"); - if ((settings2 == null ? void 0 : settings2.hideUnlistedTokens) !== void 0) { - hideUnlistedTokens = settings2 == null ? void 0 : settings2.hideUnlistedTokens; + setFunctionModule(x2, y2, isDark) { + this.modules[y2][x2] = isDark; + this.isFunction[y2][x2] = true; + } + addEccAndInterleave(data) { + const ver = this.version; + const ecl = this.errorCorrectionLevel; + if (data.length != _QrCode.getNumDataCodewords(ver, ecl)) + throw new RangeError("Invalid argument"); + const numBlocks = _QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]; + const blockEccLen = _QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver]; + const rawCodewords = Math.floor(_QrCode.getNumRawDataModules(ver) / 8); + const numShortBlocks = numBlocks - rawCodewords % numBlocks; + const shortBlockLen = Math.floor(rawCodewords / numBlocks); + let blocks = []; + const rsDiv = _QrCode.reedSolomonComputeDivisor(blockEccLen); + for (let i = 0, k2 = 0; i < numBlocks; i++) { + let dat = data.slice(k2, k2 + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1)); + k2 += dat.length; + const ecc = _QrCode.reedSolomonComputeRemainder(dat, rsDiv); + if (i < numShortBlocks) + dat.push(0); + blocks.push(dat.concat(ecc)); } - if ((settings2 == null ? void 0 : settings2.hideCollectibles) !== void 0) { - hideCollectibles = settings2 == null ? void 0 : settings2.hideCollectibles; + let result = []; + for (let i = 0; i < blocks[0].length; i++) { + blocks.forEach((block, j2) => { + if (i != shortBlockLen - blockEccLen || j2 >= numShortBlocks) + result.push(block[i]); + }); } - if ((settings2 == null ? void 0 : settings2.fiatCurrency) !== void 0) { - fiatCurrency = settings2 == null ? void 0 : settings2.fiatCurrency; + assert2(result.length == rawCodewords); + return result; + } + drawCodewords(data) { + if (data.length != Math.floor(_QrCode.getNumRawDataModules(this.version) / 8)) + throw new RangeError("Invalid argument"); + let i = 0; + for (let right = this.size - 1; right >= 1; right -= 2) { + if (right == 6) + right = 5; + for (let vert = 0; vert < this.size; vert++) { + for (let j2 = 0; j2 < 2; j2++) { + const x2 = right - j2; + const upward = (right + 1 & 2) == 0; + const y2 = upward ? this.size - 1 - vert : vert; + if (!this.isFunction[y2][x2] && i < data.length * 8) { + this.modules[y2][x2] = getBit(data[i >>> 3], 7 - (i & 7)); + i++; + } + } + } } - if ((settings2 == null ? void 0 : settings2.selectedNetworks) !== void 0) { - let areSelectedNetworksValid = true; - settings2.selectedNetworks.forEach((chainId) => { - if (chains2.find((chain) => chain.id === chainId) === void 0) { - areSelectedNetworksValid = false; + assert2(i == data.length * 8); + } + applyMask(mask2) { + if (mask2 < 0 || mask2 > 7) + throw new RangeError("Mask value out of range"); + for (let y2 = 0; y2 < this.size; y2++) { + for (let x2 = 0; x2 < this.size; x2++) { + let invert2; + switch (mask2) { + case 0: + invert2 = (x2 + y2) % 2 == 0; + break; + case 1: + invert2 = y2 % 2 == 0; + break; + case 2: + invert2 = x2 % 3 == 0; + break; + case 3: + invert2 = (x2 + y2) % 3 == 0; + break; + case 4: + invert2 = (Math.floor(x2 / 3) + Math.floor(y2 / 2)) % 2 == 0; + break; + case 5: + invert2 = x2 * y2 % 2 + x2 * y2 % 3 == 0; + break; + case 6: + invert2 = (x2 * y2 % 2 + x2 * y2 % 3) % 2 == 0; + break; + case 7: + invert2 = ((x2 + y2) % 2 + x2 * y2 % 3) % 2 == 0; + break; + default: + throw new Error("Unreachable"); } - }); - if (areSelectedNetworksValid) { - selectedNetworks = settings2 == null ? void 0 : settings2.selectedNetworks; + if (!this.isFunction[y2][x2] && invert2) + this.modules[y2][x2] = !this.modules[y2][x2]; } } - } catch (e2) { - console.error(e2, "Failed to fetch settings"); } - return { - hideUnlistedTokens, - hideCollectibles, - fiatCurrency, - selectedNetworks - }; - }; - const defaultSettings = getSettingsFromStorage(); - const [settings, setSettings] = reactExports.useState(defaultSettings); - const setHideUnlistedTokens = (newState) => { - const oldSettings = getSettingsFromStorage(); - const newSettings = { - ...oldSettings, - hideUnlistedTokens: newState - }; - localStorage.setItem(LocalStorageKey.Settings, JSON.stringify(newSettings)); - setSettings(newSettings); - }; - const setHideCollectibles = (newState) => { - const oldSettings = getSettingsFromStorage(); - const newSettings = { - ...oldSettings, - hideCollectibles: newState - }; - localStorage.setItem(LocalStorageKey.Settings, JSON.stringify(newSettings)); - setSettings(newSettings); - }; - const setFiatCurrency = (newFiatCurrency) => { - const oldSettings = getSettingsFromStorage(); - const newSettings = { - ...oldSettings, - fiatCurrency: newFiatCurrency - }; - localStorage.setItem(LocalStorageKey.Settings, JSON.stringify(newSettings)); - setSettings(newSettings); - }; - const setSelectedNetworks = (newSelectedNetworks) => { - const oldSettings = getSettingsFromStorage(); - const newSettings = { - ...oldSettings, - selectedNetworks: newSelectedNetworks - }; - localStorage.setItem(LocalStorageKey.Settings, JSON.stringify(newSettings)); - setSettings(newSettings); - }; - return { - ...settings, - setFiatCurrency, - setHideCollectibles, - setHideUnlistedTokens, - setSelectedNetworks - }; -}; -const CoinTileContent = ({ logoUrl, tokenName, balance, balanceFiat, priceChangePercentage, symbol, chainId }) => { - const { fiatCurrency } = useSettings(); - const priceChangeSymbol = priceChangePercentage > 0 ? "+" : ""; - return jsxRuntimeExports$1.jsxs(Box, { background: "backgroundSecondary", width: "full", height: "full", borderRadius: "md", padding: "4", flexDirection: "column", justifyContent: "center", alignItems: "flex-start", gap: "1", children: [jsxRuntimeExports$1.jsx(Box, { marginBottom: "1", children: jsxRuntimeExports$1.jsx(TokenImage, { src: logoUrl, symbol, size: "xl" }) }), jsxRuntimeExports$1.jsxs(Box, { marginBottom: "3", children: [jsxRuntimeExports$1.jsxs(Box, { flexDirection: "row", gap: "1", justifyContent: "flex-start", alignItems: "center", children: [jsxRuntimeExports$1.jsx(Text, { fontWeight: "bold", whiteSpace: "nowrap", color: "text100", style: { maxWidth: "130px", textOverflow: "ellipsis", overflow: "hidden" }, children: tokenName }), jsxRuntimeExports$1.jsx(NetworkImage, { chainId, size: "xs" })] }), jsxRuntimeExports$1.jsx(Text, { color: "text50", whiteSpace: "nowrap", style: { display: "block", maxWidth: "150px", textOverflow: "ellipsis", overflow: "hidden" }, children: `${balance} ${symbol}` })] }), jsxRuntimeExports$1.jsxs(Box, { children: [jsxRuntimeExports$1.jsx(Box, { children: jsxRuntimeExports$1.jsx(Text, { fontWeight: "bold", color: "text100", children: `${fiatCurrency.sign}${balanceFiat}` }) }), jsxRuntimeExports$1.jsx(Text, { style: { color: getPercentageColor(priceChangePercentage) }, children: `${priceChangeSymbol}${priceChangePercentage.toFixed(2)}%` })] })] }); -}; -const CoinTile = ({ balance }) => { - const { chains: chains2 } = useConfig(); - const { fiatCurrency } = useSettings(); - const isNativeToken = compareAddress(balance.contractAddress, ZeroAddress); - const nativeTokenInfo = getNativeTokenInfoByChainId(balance.chainId, chains2); - const { data: dataCoinPrices = [], isPending: isPendingCoinPrice } = useCoinPrices([ - { - chainId: balance.chainId, - contractAddress: balance.contractAddress + getPenaltyScore() { + let result = 0; + for (let y2 = 0; y2 < this.size; y2++) { + let runColor = false; + let runX = 0; + let runHistory = [0, 0, 0, 0, 0, 0, 0]; + for (let x2 = 0; x2 < this.size; x2++) { + if (this.modules[y2][x2] == runColor) { + runX++; + if (runX == 5) + result += _QrCode.PENALTY_N1; + else if (runX > 5) + result++; + } else { + this.finderPenaltyAddHistory(runX, runHistory); + if (!runColor) + result += this.finderPenaltyCountPatterns(runHistory) * _QrCode.PENALTY_N3; + runColor = this.modules[y2][x2]; + runX = 1; + } + } + result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * _QrCode.PENALTY_N3; + } + for (let x2 = 0; x2 < this.size; x2++) { + let runColor = false; + let runY = 0; + let runHistory = [0, 0, 0, 0, 0, 0, 0]; + for (let y2 = 0; y2 < this.size; y2++) { + if (this.modules[y2][x2] == runColor) { + runY++; + if (runY == 5) + result += _QrCode.PENALTY_N1; + else if (runY > 5) + result++; + } else { + this.finderPenaltyAddHistory(runY, runHistory); + if (!runColor) + result += this.finderPenaltyCountPatterns(runHistory) * _QrCode.PENALTY_N3; + runColor = this.modules[y2][x2]; + runY = 1; + } + } + result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * _QrCode.PENALTY_N3; + } + for (let y2 = 0; y2 < this.size - 1; y2++) { + for (let x2 = 0; x2 < this.size - 1; x2++) { + const color2 = this.modules[y2][x2]; + if (color2 == this.modules[y2][x2 + 1] && color2 == this.modules[y2 + 1][x2] && color2 == this.modules[y2 + 1][x2 + 1]) + result += _QrCode.PENALTY_N2; + } + } + let dark2 = 0; + for (const row of this.modules) + dark2 = row.reduce((sum, color2) => sum + (color2 ? 1 : 0), dark2); + const total = this.size * this.size; + const k2 = Math.ceil(Math.abs(dark2 * 20 - total * 10) / total) - 1; + assert2(0 <= k2 && k2 <= 9); + result += k2 * _QrCode.PENALTY_N4; + assert2(0 <= result && result <= 2568888); + return result; } - ]); - const { data: conversionRate = 1, isPending: isPendingConversionRate } = useExchangeRate(fiatCurrency.symbol); - const { data: contractInfo, isPending: isPendingContractInfo } = useContractInfo(balance.chainId, balance.contractAddress); - const isPending = isPendingCoinPrice || isPendingConversionRate || isPendingContractInfo; - if (isPending) { - return jsxRuntimeExports$1.jsx(Box, { background: "backgroundSecondary", width: "full", height: "full", borderRadius: "md" }); + getAlignmentPatternPositions() { + if (this.version == 1) + return []; + else { + const numAlign = Math.floor(this.version / 7) + 2; + const step = this.version == 32 ? 26 : Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2; + let result = [6]; + for (let pos = this.size - 7; result.length < numAlign; pos -= step) + result.splice(1, 0, pos); + return result; + } + } + static getNumRawDataModules(ver) { + if (ver < _QrCode.MIN_VERSION || ver > _QrCode.MAX_VERSION) + throw new RangeError("Version number out of range"); + let result = (16 * ver + 128) * ver + 64; + if (ver >= 2) { + const numAlign = Math.floor(ver / 7) + 2; + result -= (25 * numAlign - 10) * numAlign - 55; + if (ver >= 7) + result -= 36; + } + assert2(208 <= result && result <= 29648); + return result; + } + static getNumDataCodewords(ver, ecl) { + return Math.floor(_QrCode.getNumRawDataModules(ver) / 8) - _QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver] * _QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]; + } + static reedSolomonComputeDivisor(degree) { + if (degree < 1 || degree > 255) + throw new RangeError("Degree out of range"); + let result = []; + for (let i = 0; i < degree - 1; i++) + result.push(0); + result.push(1); + let root2 = 1; + for (let i = 0; i < degree; i++) { + for (let j2 = 0; j2 < result.length; j2++) { + result[j2] = _QrCode.reedSolomonMultiply(result[j2], root2); + if (j2 + 1 < result.length) + result[j2] ^= result[j2 + 1]; + } + root2 = _QrCode.reedSolomonMultiply(root2, 2); + } + return result; + } + static reedSolomonComputeRemainder(data, divisor) { + let result = divisor.map((_) => 0); + for (const b2 of data) { + const factor = b2 ^ result.shift(); + result.push(0); + divisor.forEach((coef, i) => result[i] ^= _QrCode.reedSolomonMultiply(coef, factor)); + } + return result; + } + static reedSolomonMultiply(x2, y2) { + if (x2 >>> 8 != 0 || y2 >>> 8 != 0) + throw new RangeError("Byte out of range"); + let z2 = 0; + for (let i = 7; i >= 0; i--) { + z2 = z2 << 1 ^ (z2 >>> 7) * 285; + z2 ^= (y2 >>> i & 1) * x2; + } + assert2(z2 >>> 8 == 0); + return z2; + } + finderPenaltyCountPatterns(runHistory) { + const n2 = runHistory[1]; + assert2(n2 <= this.size * 3); + const core2 = n2 > 0 && runHistory[2] == n2 && runHistory[3] == n2 * 3 && runHistory[4] == n2 && runHistory[5] == n2; + return (core2 && runHistory[0] >= n2 * 4 && runHistory[6] >= n2 ? 1 : 0) + (core2 && runHistory[6] >= n2 * 4 && runHistory[0] >= n2 ? 1 : 0); + } + finderPenaltyTerminateAndCount(currentRunColor, currentRunLength, runHistory) { + if (currentRunColor) { + this.finderPenaltyAddHistory(currentRunLength, runHistory); + currentRunLength = 0; + } + currentRunLength += this.size; + this.finderPenaltyAddHistory(currentRunLength, runHistory); + return this.finderPenaltyCountPatterns(runHistory); + } + finderPenaltyAddHistory(currentRunLength, runHistory) { + if (runHistory[0] == 0) + currentRunLength += this.size; + runHistory.pop(); + runHistory.unshift(currentRunLength); + } + }; + let QrCode = _QrCode; + QrCode.MIN_VERSION = 1; + QrCode.MAX_VERSION = 40; + QrCode.PENALTY_N1 = 3; + QrCode.PENALTY_N2 = 3; + QrCode.PENALTY_N3 = 40; + QrCode.PENALTY_N4 = 10; + QrCode.ECC_CODEWORDS_PER_BLOCK = [ + [-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], + [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28], + [-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], + [-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30] + ]; + QrCode.NUM_ERROR_CORRECTION_BLOCKS = [ + [-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25], + [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49], + [-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68], + [-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81] + ]; + qrcodegen2.QrCode = QrCode; + function appendBits(val, len, bb2) { + if (len < 0 || len > 31 || val >>> len != 0) + throw new RangeError("Value out of range"); + for (let i = len - 1; i >= 0; i--) + bb2.push(val >>> i & 1); } - if (isNativeToken) { - const computedBalance2 = computeBalanceFiat({ - balance, - prices: dataCoinPrices, - conversionRate, - decimals: nativeTokenInfo.decimals - }); - const priceChangePercentage2 = getPercentagePriceChange(balance, dataCoinPrices); - const formattedBalance2 = formatUnits$2(balance.balance, nativeTokenInfo.decimals); - const balanceDisplayed2 = formatDisplay(formattedBalance2); - return jsxRuntimeExports$1.jsx(CoinTileContent, { chainId: balance.chainId, logoUrl: nativeTokenInfo.logoURI, tokenName: nativeTokenInfo.name, balance: balanceDisplayed2, balanceFiat: computedBalance2, priceChangePercentage: priceChangePercentage2, symbol: nativeTokenInfo.symbol }); + function getBit(x2, i) { + return (x2 >>> i & 1) != 0; } - const decimals = (contractInfo == null ? void 0 : contractInfo.decimals) ?? 18; - const computedBalance = computeBalanceFiat({ - balance, - prices: dataCoinPrices, - conversionRate, - decimals - }); - const priceChangePercentage = getPercentagePriceChange(balance, dataCoinPrices); - const formattedBalance = formatUnits$2(balance.balance, decimals); - const balanceDisplayed = formatDisplay(formattedBalance); - const name2 = (contractInfo == null ? void 0 : contractInfo.name) || "Unknown"; - const symbol = (contractInfo == null ? void 0 : contractInfo.name) || "TOKEN"; - const url = contractInfo == null ? void 0 : contractInfo.logoURI; - return jsxRuntimeExports$1.jsx(CoinTileContent, { chainId: balance.chainId, logoUrl: url, tokenName: name2, balance: balanceDisplayed, balanceFiat: computedBalance, priceChangePercentage, symbol }); -}; -const CollectibleTileImage = ({ imageUrl }) => { - return jsxRuntimeExports$1.jsx(Card, { padding: "0", aspectRatio: "1/1", justifyContent: "center", alignItems: "center", overflow: "hidden", borderRadius: "sm", background: "backgroundSecondary", children: jsxRuntimeExports$1.jsx(Image$1, { style: { height: "100%" }, src: imageUrl }) }); -}; -const CollectibleTile = ({ balance }) => { - var _a2; - const { data: tokenMetadata } = useTokenMetadata(balance.chainId, balance.contractAddress, [balance.tokenID || ""]); - const imageUrl = (_a2 = tokenMetadata == null ? void 0 : tokenMetadata[0]) == null ? void 0 : _a2.image; - return jsxRuntimeExports$1.jsx(CollectibleTileImage, { imageUrl }); -}; -const SkeletonTiles = () => { - return jsxRuntimeExports$1.jsx(Box, { style: { - display: "grid", - gridTemplateColumns: `calc(50% - ${vars.space[1]}) calc(50% - ${vars.space[1]})`, - gap: vars.space[2] - }, children: Array(12).fill(null).map((_, i) => jsxRuntimeExports$1.jsx(Box, { children: jsxRuntimeExports$1.jsx(Skeleton, { height: "full", width: "full", aspectRatio: "1/1" }) }, i)) }); -}; -const AssetSummary = () => { - const { address } = useAccount(); - const { setNavigation } = useNavigation(); - const { displayedAssets } = useWalletSettings(); - const { hideUnlistedTokens, hideCollectibles, selectedNetworks } = useSettings(); - const { data: balances = [], isPending: isPendingBalances } = useBalancesAssetsSummary({ - accountAddress: address || "", - chainIds: selectedNetworks, - displayAssets: displayedAssets, - hideCollectibles, - verifiedOnly: hideUnlistedTokens - }); - if (isPendingBalances) { - return jsxRuntimeExports$1.jsx(SkeletonTiles, {}); + function assert2(cond) { + if (!cond) + throw new Error("Assertion error"); } - const { nativeTokens, erc20Tokens, collectibles } = sortBalancesByType(balances); - const onClickItem = (balance) => { - if (balance.contractType === "ERC1155" || balance.contractType === "ERC721") { - setNavigation && setNavigation({ - location: "collectible-details", - params: { - contractAddress: balance.contractAddress, - chainId: balance.chainId, - tokenId: balance.tokenID || "" - } - }); - } else if (balance.contractType === "ERC20") { - setNavigation && setNavigation({ - location: "coin-details", - params: { - contractAddress: balance.contractAddress, - chainId: balance.chainId - } - }); - } else { - setNavigation && setNavigation({ - location: "coin-details", - params: { - contractAddress: balance.contractAddress, - chainId: balance.chainId - } - }); + const _QrSegment = class { + constructor(mode, numChars, bitData) { + this.mode = mode; + this.numChars = numChars; + this.bitData = bitData; + if (numChars < 0) + throw new RangeError("Invalid argument"); + this.bitData = bitData.slice(); + } + static makeBytes(data) { + let bb2 = []; + for (const b2 of data) + appendBits(b2, 8, bb2); + return new _QrSegment(_QrSegment.Mode.BYTE, data.length, bb2); + } + static makeNumeric(digits) { + if (!_QrSegment.isNumeric(digits)) + throw new RangeError("String contains non-numeric characters"); + let bb2 = []; + for (let i = 0; i < digits.length; ) { + const n2 = Math.min(digits.length - i, 3); + appendBits(parseInt(digits.substr(i, n2), 10), n2 * 3 + 1, bb2); + i += n2; + } + return new _QrSegment(_QrSegment.Mode.NUMERIC, digits.length, bb2); + } + static makeAlphanumeric(text2) { + if (!_QrSegment.isAlphanumeric(text2)) + throw new RangeError("String contains unencodable characters in alphanumeric mode"); + let bb2 = []; + let i; + for (i = 0; i + 2 <= text2.length; i += 2) { + let temp = _QrSegment.ALPHANUMERIC_CHARSET.indexOf(text2.charAt(i)) * 45; + temp += _QrSegment.ALPHANUMERIC_CHARSET.indexOf(text2.charAt(i + 1)); + appendBits(temp, 11, bb2); + } + if (i < text2.length) + appendBits(_QrSegment.ALPHANUMERIC_CHARSET.indexOf(text2.charAt(i)), 6, bb2); + return new _QrSegment(_QrSegment.Mode.ALPHANUMERIC, text2.length, bb2); + } + static makeSegments(text2) { + if (text2 == "") + return []; + else if (_QrSegment.isNumeric(text2)) + return [_QrSegment.makeNumeric(text2)]; + else if (_QrSegment.isAlphanumeric(text2)) + return [_QrSegment.makeAlphanumeric(text2)]; + else + return [_QrSegment.makeBytes(_QrSegment.toUtf8ByteArray(text2))]; + } + static makeEci(assignVal) { + let bb2 = []; + if (assignVal < 0) + throw new RangeError("ECI assignment value out of range"); + else if (assignVal < 1 << 7) + appendBits(assignVal, 8, bb2); + else if (assignVal < 1 << 14) { + appendBits(2, 2, bb2); + appendBits(assignVal, 14, bb2); + } else if (assignVal < 1e6) { + appendBits(6, 3, bb2); + appendBits(assignVal, 21, bb2); + } else + throw new RangeError("ECI assignment value out of range"); + return new _QrSegment(_QrSegment.Mode.ECI, 0, bb2); } - }; - return jsxRuntimeExports$1.jsxs(Box, { style: { - display: "grid", - gridTemplateColumns: `calc(50% - ${vars.space[1]}) calc(50% - ${vars.space[1]})`, - gap: vars.space[2] - }, children: [nativeTokens.map((balance, index2) => { - return jsxRuntimeExports$1.jsx(Box, { userSelect: "none", cursor: "pointer", opacity: { hover: "80" }, aspectRatio: "1/1", onClick: () => onClickItem(balance), children: jsxRuntimeExports$1.jsx(CoinTile, { balance }) }, index2); - }), erc20Tokens.map((balance, index2) => { - return jsxRuntimeExports$1.jsx(Box, { userSelect: "none", cursor: "pointer", opacity: { hover: "80" }, aspectRatio: "1/1", onClick: () => onClickItem(balance), children: jsxRuntimeExports$1.jsx(CoinTile, { balance }) }, index2); - }), collectibles.map((balance, index2) => { - return jsxRuntimeExports$1.jsx(Box, { userSelect: "none", cursor: "pointer", opacity: { hover: "80" }, aspectRatio: "1/1", onClick: () => onClickItem(balance), children: jsxRuntimeExports$1.jsx(CollectibleTile, { balance }) }, index2); - })] }); -}; -const Home = () => { - return jsxRuntimeExports$1.jsx(Box, { paddingX: "4", paddingBottom: "5", gap: "4", flexDirection: "column", children: jsxRuntimeExports$1.jsx(AssetSummary, {}) }); -}; -var __defProp2 = Object.defineProperty; -var __getOwnPropSymbols = Object.getOwnPropertySymbols; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __propIsEnum = Object.prototype.propertyIsEnumerable; -var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __spreadValues = (a2, b2) => { - for (var prop in b2 || (b2 = {})) - if (__hasOwnProp.call(b2, prop)) - __defNormalProp2(a2, prop, b2[prop]); - if (__getOwnPropSymbols) - for (var prop of __getOwnPropSymbols(b2)) { - if (__propIsEnum.call(b2, prop)) - __defNormalProp2(a2, prop, b2[prop]); + static isNumeric(text2) { + return _QrSegment.NUMERIC_REGEX.test(text2); } - return a2; -}; -var __objRest = (source, exclude) => { - var target = {}; - for (var prop in source) - if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0) - target[prop] = source[prop]; - if (source != null && __getOwnPropSymbols) - for (var prop of __getOwnPropSymbols(source)) { - if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop)) - target[prop] = source[prop]; + static isAlphanumeric(text2) { + return _QrSegment.ALPHANUMERIC_REGEX.test(text2); } - return target; -}; + getData() { + return this.bitData.slice(); + } + static getTotalBits(segs, version2) { + let result = 0; + for (const seg of segs) { + const ccbits = seg.mode.numCharCountBits(version2); + if (seg.numChars >= 1 << ccbits) + return Infinity; + result += 4 + ccbits + seg.bitData.length; + } + return result; + } + static toUtf8ByteArray(str) { + str = encodeURI(str); + let result = []; + for (let i = 0; i < str.length; i++) { + if (str.charAt(i) != "%") + result.push(str.charCodeAt(i)); + else { + result.push(parseInt(str.substr(i + 1, 2), 16)); + i += 2; + } + } + return result; + } + }; + let QrSegment = _QrSegment; + QrSegment.NUMERIC_REGEX = /^[0-9]*$/; + QrSegment.ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+.\/:-]*$/; + QrSegment.ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; + qrcodegen2.QrSegment = QrSegment; +})(qrcodegen || (qrcodegen = {})); +((qrcodegen2) => { + ((QrCode2) => { + const _Ecc = class { + constructor(ordinal, formatBits) { + this.ordinal = ordinal; + this.formatBits = formatBits; + } + }; + let Ecc = _Ecc; + Ecc.LOW = new _Ecc(0, 1); + Ecc.MEDIUM = new _Ecc(1, 0); + Ecc.QUARTILE = new _Ecc(2, 3); + Ecc.HIGH = new _Ecc(3, 2); + QrCode2.Ecc = Ecc; + })(qrcodegen2.QrCode || (qrcodegen2.QrCode = {})); +})(qrcodegen || (qrcodegen = {})); +((qrcodegen2) => { + ((QrSegment2) => { + const _Mode = class { + constructor(modeBits, numBitsCharCount) { + this.modeBits = modeBits; + this.numBitsCharCount = numBitsCharCount; + } + numCharCountBits(ver) { + return this.numBitsCharCount[Math.floor((ver + 7) / 17)]; + } + }; + let Mode = _Mode; + Mode.NUMERIC = new _Mode(1, [10, 12, 14]); + Mode.ALPHANUMERIC = new _Mode(2, [9, 11, 13]); + Mode.BYTE = new _Mode(4, [8, 16, 16]); + Mode.KANJI = new _Mode(8, [8, 10, 12]); + Mode.ECI = new _Mode(7, [0, 0, 0]); + QrSegment2.Mode = Mode; + })(qrcodegen2.QrSegment || (qrcodegen2.QrSegment = {})); +})(qrcodegen || (qrcodegen = {})); +var qrcodegen_default = qrcodegen; /** - * @license QR Code generator library (TypeScript) - * Copyright (c) Project Nayuki. - * SPDX-License-Identifier: MIT + * @license qrcode.react + * Copyright (c) Paul O'Shannessy + * SPDX-License-Identifier: ISC */ -var qrcodegen; -((qrcodegen2) => { - const _QrCode = class { - constructor(version2, errorCorrectionLevel, dataCodewords, msk) { - this.version = version2; - this.errorCorrectionLevel = errorCorrectionLevel; - this.modules = []; - this.isFunction = []; - if (version2 < _QrCode.MIN_VERSION || version2 > _QrCode.MAX_VERSION) - throw new RangeError("Version value out of range"); - if (msk < -1 || msk > 7) - throw new RangeError("Mask value out of range"); - this.size = version2 * 4 + 17; - let row = []; - for (let i = 0; i < this.size; i++) - row.push(false); - for (let i = 0; i < this.size; i++) { - this.modules.push(row.slice()); - this.isFunction.push(row.slice()); +var ERROR_LEVEL_MAP = { + L: qrcodegen_default.QrCode.Ecc.LOW, + M: qrcodegen_default.QrCode.Ecc.MEDIUM, + Q: qrcodegen_default.QrCode.Ecc.QUARTILE, + H: qrcodegen_default.QrCode.Ecc.HIGH +}; +var DEFAULT_SIZE = 128; +var DEFAULT_LEVEL = "L"; +var DEFAULT_BGCOLOR = "#FFFFFF"; +var DEFAULT_FGCOLOR = "#000000"; +var DEFAULT_INCLUDEMARGIN = false; +var MARGIN_SIZE = 4; +var DEFAULT_IMG_SCALE = 0.1; +function generatePath(modules, margin = 0) { + const ops = []; + modules.forEach(function(row, y2) { + let start = null; + row.forEach(function(cell, x2) { + if (!cell && start !== null) { + ops.push(`M${start + margin} ${y2 + margin}h${x2 - start}v1H${start + margin}z`); + start = null; + return; } - this.drawFunctionPatterns(); - const allCodewords = this.addEccAndInterleave(dataCodewords); - this.drawCodewords(allCodewords); - if (msk == -1) { - let minPenalty = 1e9; - for (let i = 0; i < 8; i++) { - this.applyMask(i); - this.drawFormatBits(i); - const penalty = this.getPenaltyScore(); - if (penalty < minPenalty) { - msk = i; - minPenalty = penalty; - } - this.applyMask(i); + if (x2 === row.length - 1) { + if (!cell) { + return; + } + if (start === null) { + ops.push(`M${x2 + margin},${y2 + margin} h1v1H${x2 + margin}z`); + } else { + ops.push(`M${start + margin},${y2 + margin} h${x2 + 1 - start}v1H${start + margin}z`); } + return; } - assert2(0 <= msk && msk <= 7); - this.mask = msk; - this.applyMask(msk); - this.drawFormatBits(msk); - this.isFunction = []; - } - static encodeText(text2, ecl) { - const segs = qrcodegen2.QrSegment.makeSegments(text2); - return _QrCode.encodeSegments(segs, ecl); - } - static encodeBinary(data, ecl) { - const seg = qrcodegen2.QrSegment.makeBytes(data); - return _QrCode.encodeSegments([seg], ecl); + if (cell && start === null) { + start = x2; + } + }); + }); + return ops.join(""); +} +function excavateModules(modules, excavation) { + return modules.slice().map((row, y2) => { + if (y2 < excavation.y || y2 >= excavation.y + excavation.h) { + return row; } - static encodeSegments(segs, ecl, minVersion = 1, maxVersion = 40, mask2 = -1, boostEcl = true) { - if (!(_QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= _QrCode.MAX_VERSION) || mask2 < -1 || mask2 > 7) - throw new RangeError("Invalid value"); - let version2; - let dataUsedBits; - for (version2 = minVersion; ; version2++) { - const dataCapacityBits2 = _QrCode.getNumDataCodewords(version2, ecl) * 8; - const usedBits = QrSegment.getTotalBits(segs, version2); - if (usedBits <= dataCapacityBits2) { - dataUsedBits = usedBits; - break; + return row.map((cell, x2) => { + if (x2 < excavation.x || x2 >= excavation.x + excavation.w) { + return cell; + } + return false; + }); + }); +} +function getImageSettings(cells, size2, includeMargin, imageSettings) { + if (imageSettings == null) { + return null; + } + const margin = includeMargin ? MARGIN_SIZE : 0; + const numCells = cells.length + margin * 2; + const defaultSize = Math.floor(size2 * DEFAULT_IMG_SCALE); + const scale2 = numCells / size2; + const w2 = (imageSettings.width || defaultSize) * scale2; + const h2 = (imageSettings.height || defaultSize) * scale2; + const x2 = imageSettings.x == null ? cells.length / 2 - w2 / 2 : imageSettings.x * scale2; + const y2 = imageSettings.y == null ? cells.length / 2 - h2 / 2 : imageSettings.y * scale2; + let excavation = null; + if (imageSettings.excavate) { + let floorX = Math.floor(x2); + let floorY = Math.floor(y2); + let ceilW = Math.ceil(w2 + x2 - floorX); + let ceilH = Math.ceil(h2 + y2 - floorY); + excavation = { x: floorX, y: floorY, w: ceilW, h: ceilH }; + } + return { x: x2, y: y2, h: h2, w: w2, excavation }; +} +var SUPPORTS_PATH2D = function() { + try { + new Path2D().addPath(new Path2D()); + } catch (e2) { + return false; + } + return true; +}(); +function QRCodeCanvas(props) { + const _a2 = props, { + value, + size: size2 = DEFAULT_SIZE, + level = DEFAULT_LEVEL, + bgColor = DEFAULT_BGCOLOR, + fgColor = DEFAULT_FGCOLOR, + includeMargin = DEFAULT_INCLUDEMARGIN, + style, + imageSettings + } = _a2, otherProps = __objRest(_a2, [ + "value", + "size", + "level", + "bgColor", + "fgColor", + "includeMargin", + "style", + "imageSettings" + ]); + const imgSrc = imageSettings == null ? void 0 : imageSettings.src; + const _canvas = reactExports.useRef(null); + const _image = reactExports.useRef(null); + const [isImgLoaded, setIsImageLoaded] = reactExports.useState(false); + reactExports.useEffect(() => { + if (_canvas.current != null) { + const canvas = _canvas.current; + const ctx = canvas.getContext("2d"); + if (!ctx) { + return; + } + let cells = qrcodegen_default.QrCode.encodeText(value, ERROR_LEVEL_MAP[level]).getModules(); + const margin = includeMargin ? MARGIN_SIZE : 0; + const numCells = cells.length + margin * 2; + const calculatedImageSettings = getImageSettings(cells, size2, includeMargin, imageSettings); + const image = _image.current; + const haveImageToRender = calculatedImageSettings != null && image !== null && image.complete && image.naturalHeight !== 0 && image.naturalWidth !== 0; + if (haveImageToRender) { + if (calculatedImageSettings.excavation != null) { + cells = excavateModules(cells, calculatedImageSettings.excavation); } - if (version2 >= maxVersion) - throw new RangeError("Data too long"); } - for (const newEcl of [_QrCode.Ecc.MEDIUM, _QrCode.Ecc.QUARTILE, _QrCode.Ecc.HIGH]) { - if (boostEcl && dataUsedBits <= _QrCode.getNumDataCodewords(version2, newEcl) * 8) - ecl = newEcl; + const pixelRatio = window.devicePixelRatio || 1; + canvas.height = canvas.width = size2 * pixelRatio; + const scale2 = size2 / numCells * pixelRatio; + ctx.scale(scale2, scale2); + ctx.fillStyle = bgColor; + ctx.fillRect(0, 0, numCells, numCells); + ctx.fillStyle = fgColor; + if (SUPPORTS_PATH2D) { + ctx.fill(new Path2D(generatePath(cells, margin))); + } else { + cells.forEach(function(row, rdx) { + row.forEach(function(cell, cdx) { + if (cell) { + ctx.fillRect(cdx + margin, rdx + margin, 1, 1); + } + }); + }); } - let bb2 = []; - for (const seg of segs) { - appendBits(seg.mode.modeBits, 4, bb2); - appendBits(seg.numChars, seg.mode.numCharCountBits(version2), bb2); - for (const b2 of seg.getData()) - bb2.push(b2); + if (haveImageToRender) { + ctx.drawImage(image, calculatedImageSettings.x + margin, calculatedImageSettings.y + margin, calculatedImageSettings.w, calculatedImageSettings.h); } - assert2(bb2.length == dataUsedBits); - const dataCapacityBits = _QrCode.getNumDataCodewords(version2, ecl) * 8; - assert2(bb2.length <= dataCapacityBits); - appendBits(0, Math.min(4, dataCapacityBits - bb2.length), bb2); - appendBits(0, (8 - bb2.length % 8) % 8, bb2); - assert2(bb2.length % 8 == 0); - for (let padByte = 236; bb2.length < dataCapacityBits; padByte ^= 236 ^ 17) - appendBits(padByte, 8, bb2); - let dataCodewords = []; - while (dataCodewords.length * 8 < bb2.length) - dataCodewords.push(0); - bb2.forEach((b2, i) => dataCodewords[i >>> 3] |= b2 << 7 - (i & 7)); - return new _QrCode(version2, ecl, dataCodewords, mask2); } - getModule(x2, y2) { - return 0 <= x2 && x2 < this.size && 0 <= y2 && y2 < this.size && this.modules[y2][x2]; + }); + reactExports.useEffect(() => { + setIsImageLoaded(false); + }, [imgSrc]); + const canvasStyle = __spreadValues({ height: size2, width: size2 }, style); + let img2 = null; + if (imgSrc != null) { + img2 = /* @__PURE__ */ React.createElement("img", { + src: imgSrc, + key: imgSrc, + style: { display: "none" }, + onLoad: () => { + setIsImageLoaded(true); + }, + ref: _image + }); + } + return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("canvas", __spreadValues({ + style: canvasStyle, + height: size2, + width: size2, + ref: _canvas + }, otherProps)), img2); +} +function QRCodeSVG(props) { + const _a2 = props, { + value, + size: size2 = DEFAULT_SIZE, + level = DEFAULT_LEVEL, + bgColor = DEFAULT_BGCOLOR, + fgColor = DEFAULT_FGCOLOR, + includeMargin = DEFAULT_INCLUDEMARGIN, + imageSettings + } = _a2, otherProps = __objRest(_a2, [ + "value", + "size", + "level", + "bgColor", + "fgColor", + "includeMargin", + "imageSettings" + ]); + let cells = qrcodegen_default.QrCode.encodeText(value, ERROR_LEVEL_MAP[level]).getModules(); + const margin = includeMargin ? MARGIN_SIZE : 0; + const numCells = cells.length + margin * 2; + const calculatedImageSettings = getImageSettings(cells, size2, includeMargin, imageSettings); + let image = null; + if (imageSettings != null && calculatedImageSettings != null) { + if (calculatedImageSettings.excavation != null) { + cells = excavateModules(cells, calculatedImageSettings.excavation); } - getModules() { - return this.modules; + image = /* @__PURE__ */ React.createElement("image", { + xlinkHref: imageSettings.src, + height: calculatedImageSettings.h, + width: calculatedImageSettings.w, + x: calculatedImageSettings.x + margin, + y: calculatedImageSettings.y + margin, + preserveAspectRatio: "none" + }); + } + const fgPath = generatePath(cells, margin); + return /* @__PURE__ */ React.createElement("svg", __spreadValues({ + height: size2, + width: size2, + viewBox: `0 0 ${numCells} ${numCells}` + }, otherProps), /* @__PURE__ */ React.createElement("path", { + fill: bgColor, + d: `M0,0 h${numCells}v${numCells}H0z`, + shapeRendering: "crispEdges" + }), /* @__PURE__ */ React.createElement("path", { + fill: fgColor, + d: fgPath, + shapeRendering: "crispEdges" + }), image); +} +var QRCode$1 = (props) => { + const _a2 = props, { renderAs } = _a2, otherProps = __objRest(_a2, ["renderAs"]); + if (renderAs === "svg") { + return /* @__PURE__ */ React.createElement(QRCodeSVG, __spreadValues({}, otherProps)); + } + return /* @__PURE__ */ React.createElement(QRCodeCanvas, __spreadValues({}, otherProps)); +}; +var Component = {}; +var toggleSelection = function() { + var selection = document.getSelection(); + if (!selection.rangeCount) { + return function() { + }; + } + var active = document.activeElement; + var ranges = []; + for (var i = 0; i < selection.rangeCount; i++) { + ranges.push(selection.getRangeAt(i)); + } + switch (active.tagName.toUpperCase()) { + case "INPUT": + case "TEXTAREA": + active.blur(); + break; + default: + active = null; + break; + } + selection.removeAllRanges(); + return function() { + selection.type === "Caret" && selection.removeAllRanges(); + if (!selection.rangeCount) { + ranges.forEach(function(range2) { + selection.addRange(range2); + }); } - drawFunctionPatterns() { - for (let i = 0; i < this.size; i++) { - this.setFunctionModule(6, i, i % 2 == 0); - this.setFunctionModule(i, 6, i % 2 == 0); - } - this.drawFinderPattern(3, 3); - this.drawFinderPattern(this.size - 4, 3); - this.drawFinderPattern(3, this.size - 4); - const alignPatPos = this.getAlignmentPatternPositions(); - const numAlign = alignPatPos.length; - for (let i = 0; i < numAlign; i++) { - for (let j2 = 0; j2 < numAlign; j2++) { - if (!(i == 0 && j2 == 0 || i == 0 && j2 == numAlign - 1 || i == numAlign - 1 && j2 == 0)) - this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j2]); + active && active.focus(); + }; +}; +var deselectCurrent = toggleSelection; +var clipboardToIE11Formatting = { + "text/plain": "Text", + "text/html": "Url", + "default": "Text" +}; +var defaultMessage = "Copy to clipboard: #{key}, Enter"; +function format$1(message) { + var copyKey = (/mac os x/i.test(navigator.userAgent) ? "⌘" : "Ctrl") + "+C"; + return message.replace(/#{\s*key\s*}/g, copyKey); +} +function copy(text2, options) { + var debug2, message, reselectPrevious, range2, selection, mark, success = false; + if (!options) { + options = {}; + } + debug2 = options.debug || false; + try { + reselectPrevious = deselectCurrent(); + range2 = document.createRange(); + selection = document.getSelection(); + mark = document.createElement("span"); + mark.textContent = text2; + mark.ariaHidden = "true"; + mark.style.all = "unset"; + mark.style.position = "fixed"; + mark.style.top = 0; + mark.style.clip = "rect(0, 0, 0, 0)"; + mark.style.whiteSpace = "pre"; + mark.style.webkitUserSelect = "text"; + mark.style.MozUserSelect = "text"; + mark.style.msUserSelect = "text"; + mark.style.userSelect = "text"; + mark.addEventListener("copy", function(e2) { + e2.stopPropagation(); + if (options.format) { + e2.preventDefault(); + if (typeof e2.clipboardData === "undefined") { + debug2 && console.warn("unable to use e.clipboardData"); + debug2 && console.warn("trying IE specific stuff"); + window.clipboardData.clearData(); + var format2 = clipboardToIE11Formatting[options.format] || clipboardToIE11Formatting["default"]; + window.clipboardData.setData(format2, text2); + } else { + e2.clipboardData.clearData(); + e2.clipboardData.setData(options.format, text2); } } - this.drawFormatBits(0); - this.drawVersion(); - } - drawFormatBits(mask2) { - const data = this.errorCorrectionLevel.formatBits << 3 | mask2; - let rem = data; - for (let i = 0; i < 10; i++) - rem = rem << 1 ^ (rem >>> 9) * 1335; - const bits = (data << 10 | rem) ^ 21522; - assert2(bits >>> 15 == 0); - for (let i = 0; i <= 5; i++) - this.setFunctionModule(8, i, getBit(bits, i)); - this.setFunctionModule(8, 7, getBit(bits, 6)); - this.setFunctionModule(8, 8, getBit(bits, 7)); - this.setFunctionModule(7, 8, getBit(bits, 8)); - for (let i = 9; i < 15; i++) - this.setFunctionModule(14 - i, 8, getBit(bits, i)); - for (let i = 0; i < 8; i++) - this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i)); - for (let i = 8; i < 15; i++) - this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i)); - this.setFunctionModule(8, this.size - 8, true); - } - drawVersion() { - if (this.version < 7) - return; - let rem = this.version; - for (let i = 0; i < 12; i++) - rem = rem << 1 ^ (rem >>> 11) * 7973; - const bits = this.version << 12 | rem; - assert2(bits >>> 18 == 0); - for (let i = 0; i < 18; i++) { - const color2 = getBit(bits, i); - const a2 = this.size - 11 + i % 3; - const b2 = Math.floor(i / 3); - this.setFunctionModule(a2, b2, color2); - this.setFunctionModule(b2, a2, color2); + if (options.onCopy) { + e2.preventDefault(); + options.onCopy(e2.clipboardData); } + }); + document.body.appendChild(mark); + range2.selectNodeContents(mark); + selection.addRange(range2); + var successful = document.execCommand("copy"); + if (!successful) { + throw new Error("copy command was unsuccessful"); } - drawFinderPattern(x2, y2) { - for (let dy = -4; dy <= 4; dy++) { - for (let dx = -4; dx <= 4; dx++) { - const dist2 = Math.max(Math.abs(dx), Math.abs(dy)); - const xx = x2 + dx; - const yy = y2 + dy; - if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size) - this.setFunctionModule(xx, yy, dist2 != 2 && dist2 != 4); - } - } + success = true; + } catch (err) { + debug2 && console.error("unable to copy using execCommand: ", err); + debug2 && console.warn("trying IE specific stuff"); + try { + window.clipboardData.setData(options.format || "text", text2); + options.onCopy && options.onCopy(window.clipboardData); + success = true; + } catch (err2) { + debug2 && console.error("unable to copy using clipboardData: ", err2); + debug2 && console.error("falling back to prompt"); + message = format$1("message" in options ? options.message : defaultMessage); + window.prompt(message, text2); } - drawAlignmentPattern(x2, y2) { - for (let dy = -2; dy <= 2; dy++) { - for (let dx = -2; dx <= 2; dx++) - this.setFunctionModule(x2 + dx, y2 + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1); + } finally { + if (selection) { + if (typeof selection.removeRange == "function") { + selection.removeRange(range2); + } else { + selection.removeAllRanges(); } } - setFunctionModule(x2, y2, isDark) { - this.modules[y2][x2] = isDark; - this.isFunction[y2][x2] = true; - } - addEccAndInterleave(data) { - const ver = this.version; - const ecl = this.errorCorrectionLevel; - if (data.length != _QrCode.getNumDataCodewords(ver, ecl)) - throw new RangeError("Invalid argument"); - const numBlocks = _QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]; - const blockEccLen = _QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver]; - const rawCodewords = Math.floor(_QrCode.getNumRawDataModules(ver) / 8); - const numShortBlocks = numBlocks - rawCodewords % numBlocks; - const shortBlockLen = Math.floor(rawCodewords / numBlocks); - let blocks = []; - const rsDiv = _QrCode.reedSolomonComputeDivisor(blockEccLen); - for (let i = 0, k2 = 0; i < numBlocks; i++) { - let dat = data.slice(k2, k2 + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1)); - k2 += dat.length; - const ecc = _QrCode.reedSolomonComputeRemainder(dat, rsDiv); - if (i < numShortBlocks) - dat.push(0); - blocks.push(dat.concat(ecc)); - } - let result = []; - for (let i = 0; i < blocks[0].length; i++) { - blocks.forEach((block, j2) => { - if (i != shortBlockLen - blockEccLen || j2 >= numShortBlocks) - result.push(block[i]); - }); - } - assert2(result.length == rawCodewords); - return result; + if (mark) { + document.body.removeChild(mark); } - drawCodewords(data) { - if (data.length != Math.floor(_QrCode.getNumRawDataModules(this.version) / 8)) - throw new RangeError("Invalid argument"); - let i = 0; - for (let right = this.size - 1; right >= 1; right -= 2) { - if (right == 6) - right = 5; - for (let vert = 0; vert < this.size; vert++) { - for (let j2 = 0; j2 < 2; j2++) { - const x2 = right - j2; - const upward = (right + 1 & 2) == 0; - const y2 = upward ? this.size - 1 - vert : vert; - if (!this.isFunction[y2][x2] && i < data.length * 8) { - this.modules[y2][x2] = getBit(data[i >>> 3], 7 - (i & 7)); - i++; - } - } - } - } - assert2(i == data.length * 8); + reselectPrevious(); + } + return success; +} +var copyToClipboard = copy; +function _typeof(obj) { + "@babel/helpers - typeof"; + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj2) { + return typeof obj2; + } : function(obj2) { + return obj2 && "function" == typeof Symbol && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; + }, _typeof(obj); +} +Object.defineProperty(Component, "__esModule", { + value: true +}); +Component.CopyToClipboard = void 0; +var _react = _interopRequireDefault(reactExports); +var _copyToClipboard = _interopRequireDefault(copyToClipboard); +var _excluded = ["text", "onCopy", "options", "children"]; +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { "default": obj }; +} +function ownKeys(object2, enumerableOnly) { + var keys = Object.keys(object2); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object2); + enumerableOnly && (symbols = symbols.filter(function(sym) { + return Object.getOwnPropertyDescriptor(object2, sym).enumerable; + })), keys.push.apply(keys, symbols); + } + return keys; +} +function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source = null != arguments[i] ? arguments[i] : {}; + i % 2 ? ownKeys(Object(source), true).forEach(function(key) { + _defineProperty(target, key, source[key]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + return target; +} +function _objectWithoutProperties(source, excluded) { + if (source == null) + return {}; + var target = _objectWithoutPropertiesLoose(source, excluded); + var key, i; + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); + for (i = 0; i < sourceSymbolKeys.length; i++) { + key = sourceSymbolKeys[i]; + if (excluded.indexOf(key) >= 0) + continue; + if (!Object.prototype.propertyIsEnumerable.call(source, key)) + continue; + target[key] = source[key]; } - applyMask(mask2) { - if (mask2 < 0 || mask2 > 7) - throw new RangeError("Mask value out of range"); - for (let y2 = 0; y2 < this.size; y2++) { - for (let x2 = 0; x2 < this.size; x2++) { - let invert2; - switch (mask2) { - case 0: - invert2 = (x2 + y2) % 2 == 0; - break; - case 1: - invert2 = y2 % 2 == 0; - break; - case 2: - invert2 = x2 % 3 == 0; - break; - case 3: - invert2 = (x2 + y2) % 3 == 0; - break; - case 4: - invert2 = (Math.floor(x2 / 3) + Math.floor(y2 / 2)) % 2 == 0; - break; - case 5: - invert2 = x2 * y2 % 2 + x2 * y2 % 3 == 0; - break; - case 6: - invert2 = (x2 * y2 % 2 + x2 * y2 % 3) % 2 == 0; - break; - case 7: - invert2 = ((x2 + y2) % 2 + x2 * y2 % 3) % 2 == 0; - break; - default: - throw new Error("Unreachable"); - } - if (!this.isFunction[y2][x2] && invert2) - this.modules[y2][x2] = !this.modules[y2][x2]; - } - } + } + return target; +} +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) + return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) + continue; + target[key] = source[key]; + } + return target; +} +function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +} +function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) + descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } +} +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) + _defineProperties(Constructor.prototype, protoProps); + Object.defineProperty(Constructor, "prototype", { writable: false }); + return Constructor; +} +function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); + Object.defineProperty(subClass, "prototype", { writable: false }); + if (superClass) + _setPrototypeOf(subClass, superClass); +} +function _setPrototypeOf(o2, p2) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o3, p3) { + o3.__proto__ = p3; + return o3; + }; + return _setPrototypeOf(o2, p2); +} +function _createSuper(Derived) { + var hasNativeReflectConstruct = _isNativeReflectConstruct(); + return function _createSuperInternal() { + var Super = _getPrototypeOf(Derived), result; + if (hasNativeReflectConstruct) { + var NewTarget = _getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); } - getPenaltyScore() { - let result = 0; - for (let y2 = 0; y2 < this.size; y2++) { - let runColor = false; - let runX = 0; - let runHistory = [0, 0, 0, 0, 0, 0, 0]; - for (let x2 = 0; x2 < this.size; x2++) { - if (this.modules[y2][x2] == runColor) { - runX++; - if (runX == 5) - result += _QrCode.PENALTY_N1; - else if (runX > 5) - result++; - } else { - this.finderPenaltyAddHistory(runX, runHistory); - if (!runColor) - result += this.finderPenaltyCountPatterns(runHistory) * _QrCode.PENALTY_N3; - runColor = this.modules[y2][x2]; - runX = 1; - } - } - result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * _QrCode.PENALTY_N3; - } - for (let x2 = 0; x2 < this.size; x2++) { - let runColor = false; - let runY = 0; - let runHistory = [0, 0, 0, 0, 0, 0, 0]; - for (let y2 = 0; y2 < this.size; y2++) { - if (this.modules[y2][x2] == runColor) { - runY++; - if (runY == 5) - result += _QrCode.PENALTY_N1; - else if (runY > 5) - result++; - } else { - this.finderPenaltyAddHistory(runY, runHistory); - if (!runColor) - result += this.finderPenaltyCountPatterns(runHistory) * _QrCode.PENALTY_N3; - runColor = this.modules[y2][x2]; - runY = 1; - } - } - result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * _QrCode.PENALTY_N3; - } - for (let y2 = 0; y2 < this.size - 1; y2++) { - for (let x2 = 0; x2 < this.size - 1; x2++) { - const color2 = this.modules[y2][x2]; - if (color2 == this.modules[y2][x2 + 1] && color2 == this.modules[y2 + 1][x2] && color2 == this.modules[y2 + 1][x2 + 1]) - result += _QrCode.PENALTY_N2; - } - } - let dark2 = 0; - for (const row of this.modules) - dark2 = row.reduce((sum, color2) => sum + (color2 ? 1 : 0), dark2); - const total = this.size * this.size; - const k2 = Math.ceil(Math.abs(dark2 * 20 - total * 10) / total) - 1; - assert2(0 <= k2 && k2 <= 9); - result += k2 * _QrCode.PENALTY_N4; - assert2(0 <= result && result <= 2568888); - return result; + return _possibleConstructorReturn(this, result); + }; +} +function _possibleConstructorReturn(self2, call2) { + if (call2 && (_typeof(call2) === "object" || typeof call2 === "function")) { + return call2; + } else if (call2 !== void 0) { + throw new TypeError("Derived constructors may only return object or undefined"); + } + return _assertThisInitialized(self2); +} +function _assertThisInitialized(self2) { + if (self2 === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return self2; +} +function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) + return false; + if (Reflect.construct.sham) + return false; + if (typeof Proxy === "function") + return true; + try { + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() { + })); + return true; + } catch (e2) { + return false; + } +} +function _getPrototypeOf(o2) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf2(o3) { + return o3.__proto__ || Object.getPrototypeOf(o3); + }; + return _getPrototypeOf(o2); +} +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value; + } + return obj; +} +var CopyToClipboard$1 = /* @__PURE__ */ function(_React$PureComponent) { + _inherits(CopyToClipboard2, _React$PureComponent); + var _super = _createSuper(CopyToClipboard2); + function CopyToClipboard2() { + var _this; + _classCallCheck(this, CopyToClipboard2); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; } - getAlignmentPatternPositions() { - if (this.version == 1) - return []; - else { - const numAlign = Math.floor(this.version / 7) + 2; - const step = this.version == 32 ? 26 : Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2; - let result = [6]; - for (let pos = this.size - 7; result.length < numAlign; pos -= step) - result.splice(1, 0, pos); - return result; + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty(_assertThisInitialized(_this), "onClick", function(event) { + var _this$props = _this.props, text2 = _this$props.text, onCopy = _this$props.onCopy, children = _this$props.children, options = _this$props.options; + var elem = _react["default"].Children.only(children); + var result = (0, _copyToClipboard["default"])(text2, options); + if (onCopy) { + onCopy(text2, result); } - } - static getNumRawDataModules(ver) { - if (ver < _QrCode.MIN_VERSION || ver > _QrCode.MAX_VERSION) - throw new RangeError("Version number out of range"); - let result = (16 * ver + 128) * ver + 64; - if (ver >= 2) { - const numAlign = Math.floor(ver / 7) + 2; - result -= (25 * numAlign - 10) * numAlign - 55; - if (ver >= 7) - result -= 36; + if (elem && elem.props && typeof elem.props.onClick === "function") { + elem.props.onClick(event); } - assert2(208 <= result && result <= 29648); - return result; + }); + return _this; + } + _createClass(CopyToClipboard2, [{ + key: "render", + value: function render() { + var _this$props2 = this.props; + _this$props2.text; + _this$props2.onCopy; + _this$props2.options; + var children = _this$props2.children, props = _objectWithoutProperties(_this$props2, _excluded); + var elem = _react["default"].Children.only(children); + return /* @__PURE__ */ _react["default"].cloneElement(elem, _objectSpread(_objectSpread({}, props), {}, { + onClick: this.onClick + })); } - static getNumDataCodewords(ver, ecl) { - return Math.floor(_QrCode.getNumRawDataModules(ver) / 8) - _QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver] * _QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]; + }]); + return CopyToClipboard2; +}(_react["default"].PureComponent); +Component.CopyToClipboard = CopyToClipboard$1; +_defineProperty(CopyToClipboard$1, "defaultProps", { + onCopy: void 0, + options: void 0 +}); +var _require = Component, CopyToClipboard = _require.CopyToClipboard; +CopyToClipboard.CopyToClipboard = CopyToClipboard; +var lib = CopyToClipboard; +const CopyButton$1 = (props) => { + const { text: text2, size: size2 = "xs", inline = false, ...rest } = props; + const [isCopied, setCopy] = reactExports.useState(false); + reactExports.useEffect(() => { + if (isCopied) { + setTimeout(() => { + setCopy(false); + }, 4e3); } - static reedSolomonComputeDivisor(degree) { - if (degree < 1 || degree > 255) - throw new RangeError("Degree out of range"); - let result = []; - for (let i = 0; i < degree - 1; i++) - result.push(0); - result.push(1); - let root2 = 1; - for (let i = 0; i < degree; i++) { - for (let j2 = 0; j2 < result.length; j2++) { - result[j2] = _QrCode.reedSolomonMultiply(result[j2], root2); - if (j2 + 1 < result.length) - result[j2] ^= result[j2 + 1]; + }, [isCopied]); + const handleCopy = () => { + setCopy(true); + }; + return jsxRuntimeExports$1.jsx(lib.CopyToClipboard, { text: text2, onCopy: handleCopy, children: inline ? jsxRuntimeExports$1.jsx(Button, { size: size2, variant: "text", leftIcon: isCopied ? SvgCheckmarkIcon : SvgCopyIcon }) : jsxRuntimeExports$1.jsx(Button, { size: size2, leftIcon: isCopied ? SvgCheckmarkIcon : SvgCopyIcon, label: isCopied ? "Copied" : "Copy", ...rest }) }); +}; +const QRCode = (props) => { + const { value } = props; + return jsxRuntimeExports$1.jsxs(Box, { alignItems: "center", flexDirection: "column", gap: "4", children: [value ? jsxRuntimeExports$1.jsx(Box, { background: "white", padding: "4", borderRadius: "sm", style: { width: 232, height: 232 }, children: jsxRuntimeExports$1.jsx(QRCode$1, { value, size: 200, bgColor: "white", fgColor: "black", "data-id": "qr-code" }) }) : jsxRuntimeExports$1.jsx(Skeleton, { style: { width: 232, height: 232 } }), jsxRuntimeExports$1.jsx(CopyButton$1, { text: value || "", disabled: !value })] }); +}; +const TransferToWallet = () => { + const { address: userAddress } = useAccount(); + const { transferFundsSettings } = useTransferFundsModal(); + const address = (transferFundsSettings == null ? void 0 : transferFundsSettings.walletAddress) || userAddress || ""; + return jsxRuntimeExports$1.jsx(Box, { flexDirection: "column", gap: "2", alignItems: "center", justifyContent: "center", width: "full", paddingX: "4", paddingBottom: "4", height: "full", style: { paddingTop: HEADER_HEIGHT$1 }, children: jsxRuntimeExports$1.jsx(Box, { flexDirection: "column", alignItems: "center", paddingX: "4", paddingBottom: "4", minHeight: "full", children: jsxRuntimeExports$1.jsxs(Box, { flexDirection: "column", placeItems: "center", width: "full", children: [jsxRuntimeExports$1.jsx(Text, { as: "p", variant: "normal", color: "text50", textAlign: "center", children: "Share your wallet address to receive coins" }), jsxRuntimeExports$1.jsx(Box, { marginY: "4", children: jsxRuntimeExports$1.jsx(QRCode, { value: address, "data-id": "receiveQR" }) }), jsxRuntimeExports$1.jsx(Text, { as: "div", width: "full", variant: "normal", color: "text50", textAlign: "center", "data-id": "receiveAddress", children: address })] }) }) }); +}; +const KitCheckoutProvider = (props) => { + const queryClient2 = new QueryClient(); + return jsxRuntimeExports$1.jsx(QueryClientProvider, { client: queryClient2, children: jsxRuntimeExports$1.jsx(KitCheckoutContent, { ...props }) }); +}; +const KitCheckoutContent = ({ children }) => { + const { theme, position } = useTheme(); + const [openCheckoutModal, setOpenCheckoutModal] = reactExports.useState(false); + const [openAddFundsModal, setOpenAddFundsModal] = reactExports.useState(false); + const [openTransferFundsModal, setOpenTransferFundsModal] = reactExports.useState(false); + const [openPaymentSelectionModal, setOpenPaymentSelectionModal] = reactExports.useState(false); + const [settings, setSettings] = reactExports.useState(); + const [selectPaymentSettings, setSelectPaymentSettings] = reactExports.useState(); + const [addFundsSettings, setAddFundsSettings] = reactExports.useState(); + const [transferFundsSettings, setTransferFundsSettings] = reactExports.useState(); + const [history, setHistory] = reactExports.useState([]); + const getDefaultLocation = () => { + const orderSummaryItems = (settings == null ? void 0 : settings.orderSummaryItems) || []; + const creditCardSettings = settings == null ? void 0 : settings.creditCardCheckout; + if (orderSummaryItems.length === 0 && creditCardSettings) { + return { + location: "transaction-pending", + params: { + creditCardCheckout: creditCardSettings } - root2 = _QrCode.reedSolomonMultiply(root2, 2); - } - return result; - } - static reedSolomonComputeRemainder(data, divisor) { - let result = divisor.map((_) => 0); - for (const b2 of data) { - const factor = b2 ^ result.shift(); - result.push(0); - divisor.forEach((coef, i) => result[i] ^= _QrCode.reedSolomonMultiply(coef, factor)); - } - return result; - } - static reedSolomonMultiply(x2, y2) { - if (x2 >>> 8 != 0 || y2 >>> 8 != 0) - throw new RangeError("Byte out of range"); - let z2 = 0; - for (let i = 7; i >= 0; i--) { - z2 = z2 << 1 ^ (z2 >>> 7) * 285; - z2 ^= (y2 >>> i & 1) * x2; - } - assert2(z2 >>> 8 == 0); - return z2; + }; + } else { + return { + location: "select-method-checkout" + }; } - finderPenaltyCountPatterns(runHistory) { - const n2 = runHistory[1]; - assert2(n2 <= this.size * 3); - const core2 = n2 > 0 && runHistory[2] == n2 && runHistory[3] == n2 * 3 && runHistory[4] == n2 && runHistory[5] == n2; - return (core2 && runHistory[0] >= n2 * 4 && runHistory[6] >= n2 ? 1 : 0) + (core2 && runHistory[6] >= n2 * 4 && runHistory[0] >= n2 ? 1 : 0); + }; + const navigation = history.length > 0 ? history[history.length - 1] : getDefaultLocation(); + const triggerCheckout = (settings2) => { + setSettings(settings2); + setOpenCheckoutModal(true); + }; + const closeCheckout = () => { + setOpenCheckoutModal(false); + }; + const triggerAddFunds = (settings2) => { + setAddFundsSettings(settings2); + setOpenAddFundsModal(true); + }; + const closeAddFunds = () => { + setOpenAddFundsModal(false); + if (addFundsSettings == null ? void 0 : addFundsSettings.onClose) { + addFundsSettings.onClose(); } - finderPenaltyTerminateAndCount(currentRunColor, currentRunLength, runHistory) { - if (currentRunColor) { - this.finderPenaltyAddHistory(currentRunLength, runHistory); - currentRunLength = 0; + }; + const openTransferFunds = (settings2) => { + setTransferFundsSettings(settings2); + setOpenTransferFundsModal(true); + }; + const closeTransferFunds = () => { + if (openTransferFundsModal) { + setOpenTransferFundsModal(false); + if (transferFundsSettings == null ? void 0 : transferFundsSettings.onClose) { + transferFundsSettings.onClose(); } - currentRunLength += this.size; - this.finderPenaltyAddHistory(currentRunLength, runHistory); - return this.finderPenaltyCountPatterns(runHistory); - } - finderPenaltyAddHistory(currentRunLength, runHistory) { - if (runHistory[0] == 0) - currentRunLength += this.size; - runHistory.pop(); - runHistory.unshift(currentRunLength); } }; - let QrCode = _QrCode; - QrCode.MIN_VERSION = 1; - QrCode.MAX_VERSION = 40; - QrCode.PENALTY_N1 = 3; - QrCode.PENALTY_N2 = 3; - QrCode.PENALTY_N3 = 40; - QrCode.PENALTY_N4 = 10; - QrCode.ECC_CODEWORDS_PER_BLOCK = [ - [-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], - [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28], - [-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], - [-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30] - ]; - QrCode.NUM_ERROR_CORRECTION_BLOCKS = [ - [-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25], - [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49], - [-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68], - [-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81] - ]; - qrcodegen2.QrCode = QrCode; - function appendBits(val, len, bb2) { - if (len < 0 || len > 31 || val >>> len != 0) - throw new RangeError("Value out of range"); - for (let i = len - 1; i >= 0; i--) - bb2.push(val >>> i & 1); - } - function getBit(x2, i) { - return (x2 >>> i & 1) != 0; - } - function assert2(cond) { - if (!cond) - throw new Error("Assertion error"); - } - const _QrSegment = class { - constructor(mode, numChars, bitData) { - this.mode = mode; - this.numChars = numChars; - this.bitData = bitData; - if (numChars < 0) - throw new RangeError("Invalid argument"); - this.bitData = bitData.slice(); + const openSelectPaymentModal = (settings2) => { + setSelectPaymentSettings(settings2); + setOpenPaymentSelectionModal(true); + }; + const closeSelectPaymentModal = () => { + setOpenPaymentSelectionModal(false); + }; + const getCheckoutContent = () => { + const { location: location2 } = navigation; + switch (location2) { + case "select-method-checkout": + return jsxRuntimeExports$1.jsx(CheckoutSelection, {}); + case "transaction-pending": + return jsxRuntimeExports$1.jsx(PendingTransaction, {}); + case "transaction-success": + return jsxRuntimeExports$1.jsx(TransactionSuccess, {}); + case "transaction-error": + return jsxRuntimeExports$1.jsx(TransactionError, {}); + case "transaction-form": + default: + return jsxRuntimeExports$1.jsx(CheckoutSelection, {}); } - static makeBytes(data) { - let bb2 = []; - for (const b2 of data) - appendBits(b2, 8, bb2); - return new _QrSegment(_QrSegment.Mode.BYTE, data.length, bb2); + }; + const getCheckoutHeader = () => { + const { location: location2 } = navigation; + switch (location2) { + case "select-method-checkout": + return jsxRuntimeExports$1.jsx(NavigationHeader$1, { primaryText: "Checkout" }); + case "transaction-success": + case "transaction-error": + case "transaction-pending": + return jsxRuntimeExports$1.jsx(NavigationHeader$1, { disableBack: true, primaryText: "Pay with credit or debit card" }); + case "transaction-form": + default: + return jsxRuntimeExports$1.jsx(NavigationHeader$1, { primaryText: "Pay with credit or debit card" }); } - static makeNumeric(digits) { - if (!_QrSegment.isNumeric(digits)) - throw new RangeError("String contains non-numeric characters"); - let bb2 = []; - for (let i = 0; i < digits.length; ) { - const n2 = Math.min(digits.length - i, 3); - appendBits(parseInt(digits.substr(i, n2), 10), n2 * 3 + 1, bb2); - i += n2; - } - return new _QrSegment(_QrSegment.Mode.NUMERIC, digits.length, bb2); + }; + const getAddFundsHeader = () => { + const { location: location2 } = navigation; + switch (location2) { + default: + return jsxRuntimeExports$1.jsx(NavigationHeader$1, { primaryText: "Add funds with credit card or debit card" }); } - static makeAlphanumeric(text2) { - if (!_QrSegment.isAlphanumeric(text2)) - throw new RangeError("String contains unencodable characters in alphanumeric mode"); - let bb2 = []; - let i; - for (i = 0; i + 2 <= text2.length; i += 2) { - let temp = _QrSegment.ALPHANUMERIC_CHARSET.indexOf(text2.charAt(i)) * 45; - temp += _QrSegment.ALPHANUMERIC_CHARSET.indexOf(text2.charAt(i + 1)); - appendBits(temp, 11, bb2); - } - if (i < text2.length) - appendBits(_QrSegment.ALPHANUMERIC_CHARSET.indexOf(text2.charAt(i)), 6, bb2); - return new _QrSegment(_QrSegment.Mode.ALPHANUMERIC, text2.length, bb2); + }; + const getAddFundsContent = () => { + const { location: location2 } = navigation; + switch (location2) { + default: + return jsxRuntimeExports$1.jsx(AddFundsContent, {}); } - static makeSegments(text2) { - if (text2 == "") - return []; - else if (_QrSegment.isNumeric(text2)) - return [_QrSegment.makeNumeric(text2)]; - else if (_QrSegment.isAlphanumeric(text2)) - return [_QrSegment.makeAlphanumeric(text2)]; - else - return [_QrSegment.makeBytes(_QrSegment.toUtf8ByteArray(text2))]; + }; + reactExports.useEffect(() => { + if (openCheckoutModal || openAddFundsModal || openPaymentSelectionModal) { + setHistory([]); } - static makeEci(assignVal) { - let bb2 = []; - if (assignVal < 0) - throw new RangeError("ECI assignment value out of range"); - else if (assignVal < 1 << 7) - appendBits(assignVal, 8, bb2); - else if (assignVal < 1 << 14) { - appendBits(2, 2, bb2); - appendBits(assignVal, 14, bb2); - } else if (assignVal < 1e6) { - appendBits(6, 3, bb2); - appendBits(assignVal, 21, bb2); - } else - throw new RangeError("ECI assignment value out of range"); - return new _QrSegment(_QrSegment.Mode.ECI, 0, bb2); + }, [openCheckoutModal, openAddFundsModal, openPaymentSelectionModal]); + return jsxRuntimeExports$1.jsx(SelectPaymentContextProvider, { value: { + openSelectPaymentModal, + closeSelectPaymentModal, + selectPaymentSettings + }, children: jsxRuntimeExports$1.jsx(AddFundsContextProvider, { value: { + triggerAddFunds, + closeAddFunds, + addFundsSettings + }, children: jsxRuntimeExports$1.jsx(CheckoutModalContextProvider, { value: { + triggerCheckout, + closeCheckout, + settings, + theme + }, children: jsxRuntimeExports$1.jsx(TransferFundsContextProvider, { value: { + openTransferFundsModal: openTransferFunds, + closeTransferFundsModal: closeTransferFunds, + transferFundsSettings + }, children: jsxRuntimeExports$1.jsxs(NavigationContextProvider$1, { value: { history, setHistory, defaultLocation: getDefaultLocation() }, children: [jsxRuntimeExports$1.jsx("div", { id: "kit-checkout", children: jsxRuntimeExports$1.jsx(ThemeProvider, { root: "#kit-checkout", scope: "kit", theme, children: jsxRuntimeExports$1.jsxs(AnimatePresence, { children: [openCheckoutModal && jsxRuntimeExports$1.jsx(Modal, { contentProps: { + style: { + maxWidth: "400px", + height: "auto", + ...getModalPositionCss(position) } - static isNumeric(text2) { - return _QrSegment.NUMERIC_REGEX.test(text2); + }, scroll: false, backdropColor: "backgroundBackdrop", onClose: () => setOpenCheckoutModal(false), children: jsxRuntimeExports$1.jsxs(Box, { id: "sequence-kit-checkout-content", children: [getCheckoutHeader(), getCheckoutContent()] }) }), openAddFundsModal && jsxRuntimeExports$1.jsx(Modal, { contentProps: { + style: { + maxWidth: "400px", + height: "auto", + ...getModalPositionCss(position) } - static isAlphanumeric(text2) { - return _QrSegment.ALPHANUMERIC_REGEX.test(text2); + }, scroll: false, backdropColor: "backgroundBackdrop", onClose: closeAddFunds, children: jsxRuntimeExports$1.jsxs(Box, { id: "sequence-kit-add-funds-content", children: [getAddFundsHeader(), getAddFundsContent()] }) }), openPaymentSelectionModal && jsxRuntimeExports$1.jsx(Modal, { contentProps: { + style: { + height: "auto", + ...getModalPositionCss(position) } - getData() { - return this.bitData.slice(); + }, backdropColor: "backgroundBackdrop", onClose: () => setOpenPaymentSelectionModal(false), children: jsxRuntimeExports$1.jsx(Box, { id: "sequence-kit-payment-selection-content", children: jsxRuntimeExports$1.jsx(PaymentSelection, {}) }) }), openTransferFundsModal && jsxRuntimeExports$1.jsx(Modal, { contentProps: { + style: { + height: "auto", + ...getModalPositionCss(position) } - static getTotalBits(segs, version2) { - let result = 0; - for (const seg of segs) { - const ccbits = seg.mode.numCharCountBits(version2); - if (seg.numChars >= 1 << ccbits) - return Infinity; - result += 4 + ccbits + seg.bitData.length; + }, backdropColor: "backgroundBackdrop", onClose: closeTransferFunds, children: jsxRuntimeExports$1.jsxs(Box, { id: "sequence-kit-transfer-funds-modal", children: [jsxRuntimeExports$1.jsx(NavigationHeader$1, { primaryText: "Receive" }), jsxRuntimeExports$1.jsx(TransferToWallet, {})] }) })] }) }) }), children] }) }) }) }) }); +}; +const ERC_1155_ABI = [ + { + inputs: [ + { + internalType: "address", + name: "_from", + type: "address" + }, + { + internalType: "address", + name: "_to", + type: "address" + }, + { + internalType: "uint256[]", + name: "_ids", + type: "uint256[]" + }, + { + internalType: "uint256[]", + name: "_amounts", + type: "uint256[]" + }, + { + internalType: "bytes", + name: "_data", + type: "bytes" } - return result; - } - static toUtf8ByteArray(str) { - str = encodeURI(str); - let result = []; - for (let i = 0; i < str.length; i++) { - if (str.charAt(i) != "%") - result.push(str.charCodeAt(i)); - else { - result.push(parseInt(str.substr(i + 1, 2), 16)); - i += 2; - } + ], + name: "safeBatchTransferFrom", + outputs: [], + stateMutability: "nonpayable", + type: "function" + } +]; +const ERC_20_ABI = [ + { + constant: false, + inputs: [ + { + internalType: "address", + name: "recipient", + type: "address" + }, + { + internalType: "uint256", + name: "amount", + type: "uint256" } - return result; + ], + name: "transfer", + outputs: [ + { + internalType: "bool", + name: "", + type: "bool" + } + ], + payable: false, + stateMutability: "nonpayable", + type: "function" + } +]; +const ERC_721_ABI = [ + { + inputs: [ + { + internalType: "address", + name: "from", + type: "address" + }, + { + internalType: "address", + name: "to", + type: "address" + }, + { + internalType: "uint256", + name: "tokenId", + type: "uint256" + } + ], + name: "safeTransferFrom", + outputs: [], + stateMutability: "nonpayable", + type: "function" + } +]; +const supportedFiatCurrencies = [ + { symbol: "USD", sign: "$", name: { message: "US Dollar" }, decimals: 2 }, + { symbol: "CAD", sign: "$", name: { message: "Canadian Dollar" }, decimals: 2 }, + { symbol: "GBP", sign: "£", name: { message: "British Pound Sterling" }, decimals: 2 }, + { symbol: "EUR", sign: "€", name: { message: "Euro" }, decimals: 2 }, + { symbol: "CNY", sign: "¥", name: { message: "Chinese Yuan" }, decimals: 2 }, + { symbol: "JPY", sign: "¥", name: { message: "Japanese Yen" }, decimals: 2 }, + { symbol: "KRW", sign: "₩", name: { message: "South Korean Won" }, decimals: 2 }, + { symbol: "SGD", sign: "$", name: { message: "Singapore Dollar" }, decimals: 2 }, + { symbol: "CHF", sign: "CHF ", name: { message: "Swiss Franc" }, decimals: 2 }, + { symbol: "AUD", sign: "$", name: { message: "Australian Dollar" }, decimals: 2 }, + { symbol: "NZD", sign: "$", name: { message: "New Zealand Dollar" }, decimals: 2 }, + { symbol: "SEK", sign: "kr ", name: { message: "Swedish Krona" }, decimals: 2 }, + { symbol: "NOK", sign: "kr ", name: { message: "Norwegian Krone" }, decimals: 2 }, + { symbol: "MXN", sign: "$", name: { message: "Mexican Peso" }, decimals: 2 }, + { symbol: "INR", sign: "₹", name: { message: "Indian Rupee" }, decimals: 2 }, + { symbol: "ZAR", sign: "R ", name: { message: "South African Rand" }, decimals: 2 }, + { symbol: "TRY", sign: "₺", name: { message: "Turkish Lira" }, decimals: 2 }, + { symbol: "BRL", sign: "R$", name: { message: "Brazilian Real" }, decimals: 2 }, + { symbol: "DKK", sign: "kr ", name: { message: "Danish Krone" }, decimals: 2 }, + { symbol: "PLN", sign: "zł ", name: { message: "Polish Zloty" }, decimals: 2 }, + { symbol: "THB", sign: "฿", name: { message: "Thai Baht" }, decimals: 2 }, + { symbol: "IDR", sign: "Rp", name: { message: "Indonesian Rupiah" }, decimals: 2 } +]; +const defaultFiatCurrency = supportedFiatCurrencies[0]; +const HEADER_HEIGHT = "54px"; +const createGenericContext = () => { + const genericContext = reactExports.createContext(void 0); + const useGenericContext = () => { + const contextIsDefined = reactExports.useContext(genericContext); + if (!contextIsDefined) { + throw new Error("useGenericContext must be used within a Provider"); + } + return contextIsDefined; + }; + return [useGenericContext, genericContext.Provider]; +}; +const [useWalletModalContext, WalletModalContextProvider] = createGenericContext(); +const [useNavigationContext, NavigationContextProvider] = createGenericContext(); +const useOpenWalletModal = () => { + const { setOpenWalletModal, openWalletModalState } = useWalletModalContext(); + return { setOpenWalletModal, openWalletModalState }; +}; +const compareAddress = (a2, b2) => { + return a2.toLowerCase() === b2.toLowerCase(); +}; +const truncateAtMiddle = (text2, truncateAt) => { + let finalText = text2; + if (text2.length >= truncateAt) { + finalText = text2.slice(0, truncateAt / 2) + "..." + text2.slice(text2.length - truncateAt / 2, text2.length); + } + return finalText; +}; +const formatAddress = (text2) => { + return `0x${truncateAtMiddle((text2 == null ? void 0 : text2.substring(2)) || "", 8)}`; +}; +var ValueType; +(function(ValueType2) { + ValueType2[ValueType2["VERY_LARGE"] = 0] = "VERY_LARGE"; + ValueType2[ValueType2["FRACTION"] = 1] = "FRACTION"; + ValueType2[ValueType2["VERY_TINY"] = 2] = "VERY_TINY"; + ValueType2[ValueType2["MIXED"] = 3] = "MIXED"; +})(ValueType || (ValueType = {})); +const formatDisplay = (_val2) => { + if (isNaN(Number(_val2))) { + console.error(`display format error ${_val2} is not a number`); + return "NaN"; + } + const val = Number(_val2); + if (val === 0) { + return "0"; + } + let valMode; + if (val > 1e8) { + valMode = ValueType.VERY_LARGE; + } else if (val < 1e-10) { + valMode = ValueType.VERY_TINY; + } else if (val < 1) { + valMode = ValueType.FRACTION; + } else { + valMode = ValueType.MIXED; + } + let notation = void 0; + let config2; + switch (valMode) { + case ValueType.VERY_LARGE: + notation = "compact"; + config2 = { + maximumFractionDigits: 4 + }; + break; + case ValueType.VERY_TINY: + notation = "scientific"; + config2 = { + maximumFractionDigits: 4 + }; + break; + case ValueType.FRACTION: + notation = "standard"; + config2 = { + maximumSignificantDigits: 4 + }; + break; + default: + notation = "standard"; + config2 = { + maximumFractionDigits: 2 + }; + } + return Intl.NumberFormat("en-US", { + notation, + ...config2 + }).format(val); +}; +const limitDecimals = (value, decimals) => { + const splitValue = value.split("."); + if (splitValue.length === 1) { + return value; + } + return `${splitValue[0]}.${splitValue[1].slice(0, decimals)}`; +}; +const isEthAddress = (value) => { + const ethAddressRegEx = /0x[a-fA-F0-9]{40}/; + const isEthAddress2 = ethAddressRegEx.test(value); + return isEthAddress2; +}; +const sampleSize = (collection, n2) => { + const length = collection.length; + if (!length || n2 < 1) { + return []; + } + n2 = n2 > length ? length : n2; + const sampled = new Array(n2); + const indexes = /* @__PURE__ */ new Set(); + while (indexes.size < n2) { + indexes.add(Math.floor(Math.random() * length)); + } + let index2 = 0; + for (const i of indexes) { + sampled[index2++] = collection[i]; + } + return sampled; +}; +const isTruthy = (value) => Boolean(value); +const getPercentageColor = (value) => { + if (value > 0) { + return vars.colors.positive; + } else if (value < 0) { + return vars.colors.negative; + } else { + return vars.colors.text50; + } +}; +const getPercentagePriceChange = (balance, prices) => { + var _a2; + const priceForToken = prices.find((p2) => compareAddress(p2.token.contractAddress, balance.contractAddress)); + if (!priceForToken) { + return 0; + } + const price24HourChange = ((_a2 = priceForToken == null ? void 0 : priceForToken.price24hChange) == null ? void 0 : _a2.value) || 0; + return price24HourChange; +}; +const computeBalanceFiat = ({ balance, prices, decimals, conversionRate }) => { + var _a2; + let totalUsd = 0; + const priceForToken = prices.find((p2) => compareAddress(p2.token.contractAddress, balance.contractAddress)); + if (!priceForToken) { + return "0.00"; + } + const priceFiat = ((_a2 = priceForToken.price) == null ? void 0 : _a2.value) || 0; + const valueFormatted = formatUnits$2(balance.balance, decimals); + const usdValue = parseFloat(valueFormatted) * priceFiat; + totalUsd += usdValue; + const fiatValue = totalUsd * conversionRate; + return `${fiatValue.toFixed(2)}`; +}; +const compareTokenBalanceIds = (a2, b2) => { + return (a2.tokenID || "").localeCompare(b2.tokenID || ""); +}; +const sortBalancesByType = (balances) => { + const nativeTokens = []; + const erc20Tokens = []; + const collectibles = []; + balances.forEach((balance) => { + if (balance.contractAddress === ZeroAddress) { + nativeTokens.push(balance); + } else if (balance.contractType === "ERC20") { + erc20Tokens.push(balance); + } else if (balance.contractType === "ERC721" || balance.contractType === "ERC1155") { + collectibles.push(balance); } + }); + const sortedNativeTokens = nativeTokens.sort(compareTokenBalanceIds); + const sortedErc20Tokens = erc20Tokens.sort(compareTokenBalanceIds); + const sortedCollectibles = collectibles.sort(compareTokenBalanceIds); + return { + nativeTokens: sortedNativeTokens, + erc20Tokens: sortedErc20Tokens, + collectibles: sortedCollectibles }; - let QrSegment = _QrSegment; - QrSegment.NUMERIC_REGEX = /^[0-9]*$/; - QrSegment.ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+.\/:-]*$/; - QrSegment.ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; - qrcodegen2.QrSegment = QrSegment; -})(qrcodegen || (qrcodegen = {})); -((qrcodegen2) => { - ((QrCode2) => { - const _Ecc = class { - constructor(ordinal, formatBits) { - this.ordinal = ordinal; - this.formatBits = formatBits; - } - }; - let Ecc = _Ecc; - Ecc.LOW = new _Ecc(0, 1); - Ecc.MEDIUM = new _Ecc(1, 0); - Ecc.QUARTILE = new _Ecc(2, 3); - Ecc.HIGH = new _Ecc(3, 2); - QrCode2.Ecc = Ecc; - })(qrcodegen2.QrCode || (qrcodegen2.QrCode = {})); -})(qrcodegen || (qrcodegen = {})); -((qrcodegen2) => { - ((QrSegment2) => { - const _Mode = class { - constructor(modeBits, numBitsCharCount) { - this.modeBits = modeBits; - this.numBitsCharCount = numBitsCharCount; - } - numCharCountBits(ver) { - return this.numBitsCharCount[Math.floor((ver + 7) / 17)]; - } - }; - let Mode = _Mode; - Mode.NUMERIC = new _Mode(1, [10, 12, 14]); - Mode.ALPHANUMERIC = new _Mode(2, [9, 11, 13]); - Mode.BYTE = new _Mode(4, [8, 16, 16]); - Mode.KANJI = new _Mode(8, [8, 10, 12]); - Mode.ECI = new _Mode(7, [0, 0, 0]); - QrSegment2.Mode = Mode; - })(qrcodegen2.QrSegment || (qrcodegen2.QrSegment = {})); -})(qrcodegen || (qrcodegen = {})); -var qrcodegen_default = qrcodegen; -/** - * @license qrcode.react - * Copyright (c) Paul O'Shannessy - * SPDX-License-Identifier: ISC - */ -var ERROR_LEVEL_MAP = { - L: qrcodegen_default.QrCode.Ecc.LOW, - M: qrcodegen_default.QrCode.Ecc.MEDIUM, - Q: qrcodegen_default.QrCode.Ecc.QUARTILE, - H: qrcodegen_default.QrCode.Ecc.HIGH }; -var DEFAULT_SIZE = 128; -var DEFAULT_LEVEL = "L"; -var DEFAULT_BGCOLOR = "#FFFFFF"; -var DEFAULT_FGCOLOR = "#000000"; -var DEFAULT_INCLUDEMARGIN = false; -var MARGIN_SIZE = 4; -var DEFAULT_IMG_SCALE = 0.1; -function generatePath(modules, margin = 0) { - const ops = []; - modules.forEach(function(row, y2) { - let start = null; - row.forEach(function(cell, x2) { - if (!cell && start !== null) { - ops.push(`M${start + margin} ${y2 + margin}h${x2 - start}v1H${start + margin}z`); - start = null; - return; - } - if (x2 === row.length - 1) { - if (!cell) { - return; +const flattenPaginatedTransactionHistory = (transactionHistoryData) => { + const transactionHistory = []; + transactionHistoryData == null ? void 0 : transactionHistoryData.pages.forEach((page) => { + transactionHistory.push(...page.transactions); + }); + return transactionHistory; +}; +const time = { + oneSecond: 1 * 1e3, + oneMinute: 60 * 1e3, + oneHour: 60 * 60 * 1e3 +}; +const getBalancesAssetsSummary = async (apiClient, metadataClient, indexerClients, { accountAddress, displayAssets, hideCollectibles, verifiedOnly }) => { + const indexerClientsArr = Array.from(indexerClients.entries()); + const MAX_COLLECTIBLES_AMOUNTS = 10; + let tokenBalances = []; + const customDisplayAssets = displayAssets.length > 0; + try { + if (customDisplayAssets) { + const nativeTokens2 = displayAssets.filter((asset) => compareAddress(asset.contractAddress, ZeroAddress)); + const otherAssets = displayAssets.filter((asset) => !compareAddress(asset.contractAddress, ZeroAddress)); + const nativeTokensByChainId = {}; + const otherAssetsByChainId = {}; + nativeTokens2.forEach((asset) => { + if (!nativeTokensByChainId[asset.chainId]) { + nativeTokensByChainId[asset.chainId] = []; } - if (start === null) { - ops.push(`M${x2 + margin},${y2 + margin} h1v1H${x2 + margin}z`); - } else { - ops.push(`M${start + margin},${y2 + margin} h${x2 + 1 - start}v1H${start + margin}z`); + nativeTokensByChainId[asset.chainId].push(asset); + }); + otherAssets.forEach((asset) => { + if (!otherAssetsByChainId[asset.chainId]) { + otherAssetsByChainId[asset.chainId] = []; } - return; - } - if (cell && start === null) { - start = x2; - } - }); - }); - return ops.join(""); -} -function excavateModules(modules, excavation) { - return modules.slice().map((row, y2) => { - if (y2 < excavation.y || y2 >= excavation.y + excavation.h) { - return row; + otherAssetsByChainId[asset.chainId].push(asset); + }); + tokenBalances = (await Promise.all([ + ...Object.keys(nativeTokensByChainId).map((chainId) => { + const indexerClient = indexerClients.get(Number(chainId)); + if (!indexerClient) { + console.error(`Indexer client not found for chainId: ${chainId}, did you forget to add this Chain?`); + return null; + } + return getNativeTokenBalance(indexerClient, Number(chainId), accountAddress); + }), + ...Object.keys(otherAssetsByChainId).map((chainId) => otherAssetsByChainId[Number(chainId)].map((asset) => { + const indexerClient = indexerClients.get(Number(chainId)); + if (!indexerClient) { + console.error(`Indexer client not found for chainId: ${chainId}, did you forget to add this Chain?`); + return []; + } + return getTokenBalances(indexerClient, { + accountAddress, + contractAddress: asset.contractAddress, + includeMetadata: false, + hideCollectibles, + verifiedOnly + }); + })).flat() + ])).flat().filter(isTruthy); + } else { + tokenBalances = (await Promise.all([ + ...indexerClientsArr.map(([chainId, indexerClient]) => getNativeTokenBalance(indexerClient, chainId, accountAddress)), + ...indexerClientsArr.map(([_chainId4, indexerClient]) => getTokenBalances(indexerClient, { + accountAddress, + hideCollectibles, + includeMetadata: false, + verifiedOnly + })) + ])).flat(); } - return row.map((cell, x2) => { - if (x2 < excavation.x || x2 >= excavation.x + excavation.w) { - return cell; + const { nativeTokens, erc20Tokens, collectibles: collectionBalances } = sortBalancesByType(tokenBalances); + const fetchPricesPromise = new Promise(async (resolve) => { + if (erc20Tokens.length > 0) { + const tokens = erc20Tokens.map((token) => ({ + chainId: token.chainId, + contractAddress: token.contractAddress + })); + const prices2 = await getCoinPrices(apiClient, tokens) || []; + resolve(prices2); + } else { + resolve([]); } - return false; }); - }); -} -function getImageSettings(cells, size2, includeMargin, imageSettings) { - if (imageSettings == null) { - return null; - } - const margin = includeMargin ? MARGIN_SIZE : 0; - const numCells = cells.length + margin * 2; - const defaultSize = Math.floor(size2 * DEFAULT_IMG_SCALE); - const scale2 = numCells / size2; - const w2 = (imageSettings.width || defaultSize) * scale2; - const h2 = (imageSettings.height || defaultSize) * scale2; - const x2 = imageSettings.x == null ? cells.length / 2 - w2 / 2 : imageSettings.x * scale2; - const y2 = imageSettings.y == null ? cells.length / 2 - h2 / 2 : imageSettings.y * scale2; - let excavation = null; - if (imageSettings.excavate) { - let floorX = Math.floor(x2); - let floorY = Math.floor(y2); - let ceilW = Math.ceil(w2 + x2 - floorX); - let ceilH = Math.ceil(h2 + y2 - floorY); - excavation = { x: floorX, y: floorY, w: ceilW, h: ceilH }; - } - return { x: x2, y: y2, h: h2, w: w2, excavation }; -} -var SUPPORTS_PATH2D = function() { - try { - new Path2D().addPath(new Path2D()); - } catch (e2) { - return false; - } - return true; -}(); -function QRCodeCanvas(props) { - const _a2 = props, { - value, - size: size2 = DEFAULT_SIZE, - level = DEFAULT_LEVEL, - bgColor = DEFAULT_BGCOLOR, - fgColor = DEFAULT_FGCOLOR, - includeMargin = DEFAULT_INCLUDEMARGIN, - style, - imageSettings - } = _a2, otherProps = __objRest(_a2, [ - "value", - "size", - "level", - "bgColor", - "fgColor", - "includeMargin", - "style", - "imageSettings" - ]); - const imgSrc = imageSettings == null ? void 0 : imageSettings.src; - const _canvas = reactExports.useRef(null); - const _image = reactExports.useRef(null); - const [isImgLoaded, setIsImageLoaded] = reactExports.useState(false); - reactExports.useEffect(() => { - if (_canvas.current != null) { - const canvas = _canvas.current; - const ctx = canvas.getContext("2d"); - if (!ctx) { - return; + const fetchCollectiblesPromises = collectionBalances.map(async (collectionBalance) => { + if (customDisplayAssets) { + return collectionBalance; } - let cells = qrcodegen_default.QrCode.encodeText(value, ERROR_LEVEL_MAP[level]).getModules(); - const margin = includeMargin ? MARGIN_SIZE : 0; - const numCells = cells.length + margin * 2; - const calculatedImageSettings = getImageSettings(cells, size2, includeMargin, imageSettings); - const image = _image.current; - const haveImageToRender = calculatedImageSettings != null && image !== null && image.complete && image.naturalHeight !== 0 && image.naturalWidth !== 0; - if (haveImageToRender) { - if (calculatedImageSettings.excavation != null) { - cells = excavateModules(cells, calculatedImageSettings.excavation); - } + const indexerClient = indexerClients.get(collectionBalance.chainId); + if (!indexerClient) { + throw new Error(`Indexer client not found for chainId: ${collectionBalance.chainId}, did you forget to add this Chain?`); } - const pixelRatio = window.devicePixelRatio || 1; - canvas.height = canvas.width = size2 * pixelRatio; - const scale2 = size2 / numCells * pixelRatio; - ctx.scale(scale2, scale2); - ctx.fillStyle = bgColor; - ctx.fillRect(0, 0, numCells, numCells); - ctx.fillStyle = fgColor; - if (SUPPORTS_PATH2D) { - ctx.fill(new Path2D(generatePath(cells, margin))); - } else { - cells.forEach(function(row, rdx) { - row.forEach(function(cell, cdx) { - if (cell) { - ctx.fillRect(cdx + margin, rdx + margin, 1, 1); - } - }); + const balance = await getCollectionBalance(indexerClient, { + accountAddress, + chainId: collectionBalance.chainId, + contractAddress: collectionBalance.contractAddress, + includeMetadata: false + }); + return balance; + }); + const fetchErc20ContractInfoPromise = async () => { + const contractInfoMapByChainId2 = {}; + const erc20BalanceByChainId = {}; + erc20Tokens.forEach((erc20Token) => { + if (!erc20BalanceByChainId[erc20Token.chainId]) { + erc20BalanceByChainId[erc20Token.chainId] = [erc20Token]; + } else { + erc20BalanceByChainId[erc20Token.chainId].push(erc20Token); + } + }); + const contractInfoPromises = Object.keys(erc20BalanceByChainId).map(async (chainId) => { + const tokenBalances2 = erc20BalanceByChainId[Number(chainId)]; + const contractAddresses = tokenBalances2.map((balance) => balance.contractAddress); + const result = await metadataClient.getContractInfoBatch({ + chainID: String(chainId), + contractAddresses }); - } - if (haveImageToRender) { - ctx.drawImage(image, calculatedImageSettings.x + margin, calculatedImageSettings.y + margin, calculatedImageSettings.w, calculatedImageSettings.h); - } - } - }); - reactExports.useEffect(() => { - setIsImageLoaded(false); - }, [imgSrc]); - const canvasStyle = __spreadValues({ height: size2, width: size2 }, style); - let img2 = null; - if (imgSrc != null) { - img2 = /* @__PURE__ */ React.createElement("img", { - src: imgSrc, - key: imgSrc, - style: { display: "none" }, - onLoad: () => { - setIsImageLoaded(true); - }, - ref: _image + contractInfoMapByChainId2[Number(chainId)] = result; + }); + await Promise.all([...contractInfoPromises]); + return contractInfoMapByChainId2; + }; + const [prices, contractInfoMapByChainId, ...collectionCollectibles] = await Promise.all([ + fetchPricesPromise, + fetchErc20ContractInfoPromise(), + ...fetchCollectiblesPromises + ]); + const erc20HighestValue = erc20Tokens.sort((a2, b2) => { + var _a2, _b2; + const aPriceData = prices.find((price) => compareAddress(price.token.contractAddress, a2.contractAddress)); + const bPriceData = prices.find((price) => compareAddress(price.token.contractAddress, b2.contractAddress)); + const aPrice = (aPriceData == null ? void 0 : aPriceData.price) ? aPriceData.price.value : 0; + const bPrice = (bPriceData == null ? void 0 : bPriceData.price) ? bPriceData.price.value : 0; + const aDecimals = (_a2 = contractInfoMapByChainId[a2.chainId].contractInfoMap[a2.contractAddress]) == null ? void 0 : _a2.decimals; + const bDecimals = (_b2 = contractInfoMapByChainId[b2.chainId].contractInfoMap[b2.contractAddress]) == null ? void 0 : _b2.decimals; + const aFormattedBalance = aDecimals === void 0 ? 0 : Number(formatUnits$2(a2.balance, aDecimals)); + const bFormattedBalance = bDecimals === void 0 ? 0 : Number(formatUnits$2(b2.balance, bDecimals)); + const aValue = aFormattedBalance * aPrice; + const bValue = bFormattedBalance * bPrice; + return bValue - aValue; }); - } - return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("canvas", __spreadValues({ - style: canvasStyle, - height: size2, - width: size2, - ref: _canvas - }, otherProps)), img2); -} -function QRCodeSVG(props) { - const _a2 = props, { - value, - size: size2 = DEFAULT_SIZE, - level = DEFAULT_LEVEL, - bgColor = DEFAULT_BGCOLOR, - fgColor = DEFAULT_FGCOLOR, - includeMargin = DEFAULT_INCLUDEMARGIN, - imageSettings - } = _a2, otherProps = __objRest(_a2, [ - "value", - "size", - "level", - "bgColor", - "fgColor", - "includeMargin", - "imageSettings" - ]); - let cells = qrcodegen_default.QrCode.encodeText(value, ERROR_LEVEL_MAP[level]).getModules(); - const margin = includeMargin ? MARGIN_SIZE : 0; - const numCells = cells.length + margin * 2; - const calculatedImageSettings = getImageSettings(cells, size2, includeMargin, imageSettings); - let image = null; - if (imageSettings != null && calculatedImageSettings != null) { - if (calculatedImageSettings.excavation != null) { - cells = excavateModules(cells, calculatedImageSettings.excavation); - } - image = /* @__PURE__ */ React.createElement("image", { - xlinkHref: imageSettings.src, - height: calculatedImageSettings.h, - width: calculatedImageSettings.w, - x: calculatedImageSettings.x + margin, - y: calculatedImageSettings.y + margin, - preserveAspectRatio: "none" + const collectibles = sampleSize(collectionCollectibles.flat(), MAX_COLLECTIBLES_AMOUNTS).sort((a2, b2) => { + return a2.contractAddress.localeCompare(b2.contractAddress); }); + if (hideCollectibles) { + const summaryBalances2 = [ + ...nativeTokens.length > 0 ? [nativeTokens[0]] : [], + // the spots normally occupied by collectibles will be filled by erc20 tokens + ...erc20HighestValue.length > 0 ? erc20HighestValue.slice(0, MAX_COLLECTIBLES_AMOUNTS + 1) : [] + ]; + return summaryBalances2; + } + const summaryBalances = [ + ...nativeTokens.length > 0 ? [nativeTokens[0]] : [], + ...erc20HighestValue.length > 0 ? [erc20HighestValue[0]] : [], + ...collectibles.length > 0 ? [...collectibles] : [] + ]; + return summaryBalances; + } catch (e2) { + console.error(e2); + return []; } - const fgPath = generatePath(cells, margin); - return /* @__PURE__ */ React.createElement("svg", __spreadValues({ - height: size2, - width: size2, - viewBox: `0 0 ${numCells} ${numCells}` - }, otherProps), /* @__PURE__ */ React.createElement("path", { - fill: bgColor, - d: `M0,0 h${numCells}v${numCells}H0z`, - shapeRendering: "crispEdges" - }), /* @__PURE__ */ React.createElement("path", { - fill: fgColor, - d: fgPath, - shapeRendering: "crispEdges" - }), image); -} -var QRCode = (props) => { - const _a2 = props, { renderAs } = _a2, otherProps = __objRest(_a2, ["renderAs"]); - if (renderAs === "svg") { - return /* @__PURE__ */ React.createElement(QRCodeSVG, __spreadValues({}, otherProps)); - } - return /* @__PURE__ */ React.createElement(QRCodeCanvas, __spreadValues({}, otherProps)); }; -var Component = {}; -var toggleSelection = function() { - var selection = document.getSelection(); - if (!selection.rangeCount) { - return function() { - }; - } - var active = document.activeElement; - var ranges = []; - for (var i = 0; i < selection.rangeCount; i++) { - ranges.push(selection.getRangeAt(i)); - } - switch (active.tagName.toUpperCase()) { - case "INPUT": - case "TEXTAREA": - active.blur(); - break; - default: - active = null; - break; - } - selection.removeAllRanges(); - return function() { - selection.type === "Caret" && selection.removeAllRanges(); - if (!selection.rangeCount) { - ranges.forEach(function(range2) { - selection.addRange(range2); - }); +const useBalancesAssetsSummary = (args) => { + const apiClient = useAPIClient(); + const metadataClient = useMetadataClient(); + const indexerClients = useIndexerClients(args.chainIds); + return useQuery$1({ + queryKey: ["balancesAssetsSummary", args], + queryFn: () => getBalancesAssetsSummary(apiClient, metadataClient, indexerClients, args), + retry: true, + refetchInterval: time.oneSecond * 4, + refetchOnMount: true, + staleTime: time.oneSecond, + enabled: args.chainIds.length > 0 && !!args.accountAddress + }); +}; +const getTransactionHistorySummary = async (indexerClients, { accountAddress }) => { + const histories = await Promise.all(Array.from(indexerClients.values()).map((indexerClient) => getTransactionHistory(indexerClient, { + accountAddress, + page: { + page: 1 } - active && active.focus(); + }))); + const unorderedTransactions = histories.map((history) => history.transactions).flat(); + const orderedTransactions = unorderedTransactions.sort((a2, b2) => { + const firstDate = new Date(a2.timestamp).getTime(); + const secondDate = new Date(b2.timestamp).getTime(); + return secondDate - firstDate; + }); + return orderedTransactions; +}; +const useTransactionHistorySummary = (args) => { + const indexerClients = useIndexerClients(args.chainIds); + return useQuery$1({ + queryKey: ["transactionHistorySummary", args], + queryFn: () => getTransactionHistorySummary(indexerClients, args), + retry: true, + staleTime: time.oneSecond, + refetchOnMount: true, + enabled: args.chainIds.length > 0 && !!args.accountAddress + }); +}; +const useNavigation = () => { + const { setHistory, history } = useNavigationContext(); + const setNavigation = (navigation) => { + const childElement = document.getElementById("sequence-kit-wallet-content"); + const parentElement = childElement == null ? void 0 : childElement.parentElement; + parentElement == null ? void 0 : parentElement.scrollTo(0, 0); + const newHistory = navigation.location === "home" ? [] : [...history, navigation]; + setHistory(newHistory); }; + const goBack = () => { + const newHistory = [...history]; + newHistory.pop(); + setHistory(newHistory); + }; + return { setNavigation, history, setHistory, goBack }; }; -var deselectCurrent = toggleSelection; -var clipboardToIE11Formatting = { - "text/plain": "Text", - "text/html": "Url", - "default": "Text" -}; -var defaultMessage = "Copy to clipboard: #{key}, Enter"; -function format$1(message) { - var copyKey = (/mac os x/i.test(navigator.userAgent) ? "⌘" : "Ctrl") + "+C"; - return message.replace(/#{\s*key\s*}/g, copyKey); -} -function copy(text2, options) { - var debug2, message, reselectPrevious, range2, selection, mark, success = false; - if (!options) { - options = {}; - } - debug2 = options.debug || false; - try { - reselectPrevious = deselectCurrent(); - range2 = document.createRange(); - selection = document.getSelection(); - mark = document.createElement("span"); - mark.textContent = text2; - mark.ariaHidden = "true"; - mark.style.all = "unset"; - mark.style.position = "fixed"; - mark.style.top = 0; - mark.style.clip = "rect(0, 0, 0, 0)"; - mark.style.whiteSpace = "pre"; - mark.style.webkitUserSelect = "text"; - mark.style.MozUserSelect = "text"; - mark.style.msUserSelect = "text"; - mark.style.userSelect = "text"; - mark.addEventListener("copy", function(e2) { - e2.stopPropagation(); - if (options.format) { - e2.preventDefault(); - if (typeof e2.clipboardData === "undefined") { - debug2 && console.warn("unable to use e.clipboardData"); - debug2 && console.warn("trying IE specific stuff"); - window.clipboardData.clearData(); - var format2 = clipboardToIE11Formatting[options.format] || clipboardToIE11Formatting["default"]; - window.clipboardData.setData(format2, text2); - } else { - e2.clipboardData.clearData(); - e2.clipboardData.setData(options.format, text2); - } +const useSettings = () => { + const { chains: chains2 } = useConfig(); + const getSettingsFromStorage = () => { + let hideUnlistedTokens = true; + let hideCollectibles = false; + let fiatCurrency = defaultFiatCurrency; + let selectedNetworks = chains2.map((chain) => chain.id); + try { + const settingsStorage = localStorage.getItem(LocalStorageKey.Settings); + const settings2 = JSON.parse(settingsStorage || "{}"); + if ((settings2 == null ? void 0 : settings2.hideUnlistedTokens) !== void 0) { + hideUnlistedTokens = settings2 == null ? void 0 : settings2.hideUnlistedTokens; } - if (options.onCopy) { - e2.preventDefault(); - options.onCopy(e2.clipboardData); + if ((settings2 == null ? void 0 : settings2.hideCollectibles) !== void 0) { + hideCollectibles = settings2 == null ? void 0 : settings2.hideCollectibles; } - }); - document.body.appendChild(mark); - range2.selectNodeContents(mark); - selection.addRange(range2); - var successful = document.execCommand("copy"); - if (!successful) { - throw new Error("copy command was unsuccessful"); - } - success = true; - } catch (err) { - debug2 && console.error("unable to copy using execCommand: ", err); - debug2 && console.warn("trying IE specific stuff"); - try { - window.clipboardData.setData(options.format || "text", text2); - options.onCopy && options.onCopy(window.clipboardData); - success = true; - } catch (err2) { - debug2 && console.error("unable to copy using clipboardData: ", err2); - debug2 && console.error("falling back to prompt"); - message = format$1("message" in options ? options.message : defaultMessage); - window.prompt(message, text2); - } - } finally { - if (selection) { - if (typeof selection.removeRange == "function") { - selection.removeRange(range2); - } else { - selection.removeAllRanges(); + if ((settings2 == null ? void 0 : settings2.fiatCurrency) !== void 0) { + fiatCurrency = settings2 == null ? void 0 : settings2.fiatCurrency; + } + if ((settings2 == null ? void 0 : settings2.selectedNetworks) !== void 0) { + let areSelectedNetworksValid = true; + settings2.selectedNetworks.forEach((chainId) => { + if (chains2.find((chain) => chain.id === chainId) === void 0) { + areSelectedNetworksValid = false; + } + }); + if (areSelectedNetworksValid) { + selectedNetworks = settings2 == null ? void 0 : settings2.selectedNetworks; + } } + } catch (e2) { + console.error(e2, "Failed to fetch settings"); } - if (mark) { - document.body.removeChild(mark); + return { + hideUnlistedTokens, + hideCollectibles, + fiatCurrency, + selectedNetworks + }; + }; + const defaultSettings = getSettingsFromStorage(); + const [settings, setSettings] = reactExports.useState(defaultSettings); + const setHideUnlistedTokens = (newState) => { + const oldSettings = getSettingsFromStorage(); + const newSettings = { + ...oldSettings, + hideUnlistedTokens: newState + }; + localStorage.setItem(LocalStorageKey.Settings, JSON.stringify(newSettings)); + setSettings(newSettings); + }; + const setHideCollectibles = (newState) => { + const oldSettings = getSettingsFromStorage(); + const newSettings = { + ...oldSettings, + hideCollectibles: newState + }; + localStorage.setItem(LocalStorageKey.Settings, JSON.stringify(newSettings)); + setSettings(newSettings); + }; + const setFiatCurrency = (newFiatCurrency) => { + const oldSettings = getSettingsFromStorage(); + const newSettings = { + ...oldSettings, + fiatCurrency: newFiatCurrency + }; + localStorage.setItem(LocalStorageKey.Settings, JSON.stringify(newSettings)); + setSettings(newSettings); + }; + const setSelectedNetworks = (newSelectedNetworks) => { + const oldSettings = getSettingsFromStorage(); + const newSettings = { + ...oldSettings, + selectedNetworks: newSelectedNetworks + }; + localStorage.setItem(LocalStorageKey.Settings, JSON.stringify(newSettings)); + setSettings(newSettings); + }; + return { + ...settings, + setFiatCurrency, + setHideCollectibles, + setHideUnlistedTokens, + setSelectedNetworks + }; +}; +const CoinTileContent = ({ logoUrl, tokenName, balance, balanceFiat, priceChangePercentage, symbol, chainId }) => { + const { fiatCurrency } = useSettings(); + const priceChangeSymbol = priceChangePercentage > 0 ? "+" : ""; + return jsxRuntimeExports$1.jsxs(Box, { background: "backgroundSecondary", width: "full", height: "full", borderRadius: "md", padding: "4", flexDirection: "column", justifyContent: "center", alignItems: "flex-start", gap: "1", children: [jsxRuntimeExports$1.jsx(Box, { marginBottom: "1", children: jsxRuntimeExports$1.jsx(TokenImage, { src: logoUrl, symbol, size: "xl" }) }), jsxRuntimeExports$1.jsxs(Box, { marginBottom: "3", children: [jsxRuntimeExports$1.jsxs(Box, { flexDirection: "row", gap: "1", justifyContent: "flex-start", alignItems: "center", children: [jsxRuntimeExports$1.jsx(Text, { fontWeight: "bold", whiteSpace: "nowrap", color: "text100", style: { maxWidth: "130px", textOverflow: "ellipsis", overflow: "hidden" }, children: tokenName }), jsxRuntimeExports$1.jsx(NetworkImage, { chainId, size: "xs" })] }), jsxRuntimeExports$1.jsx(Text, { color: "text50", whiteSpace: "nowrap", style: { display: "block", maxWidth: "150px", textOverflow: "ellipsis", overflow: "hidden" }, children: `${balance} ${symbol}` })] }), jsxRuntimeExports$1.jsxs(Box, { children: [jsxRuntimeExports$1.jsx(Box, { children: jsxRuntimeExports$1.jsx(Text, { fontWeight: "bold", color: "text100", children: `${fiatCurrency.sign}${balanceFiat}` }) }), jsxRuntimeExports$1.jsx(Text, { style: { color: getPercentageColor(priceChangePercentage) }, children: `${priceChangeSymbol}${priceChangePercentage.toFixed(2)}%` })] })] }); +}; +const CoinTile = ({ balance }) => { + const { chains: chains2 } = useConfig(); + const { fiatCurrency } = useSettings(); + const isNativeToken = compareAddress(balance.contractAddress, ZeroAddress); + const nativeTokenInfo = getNativeTokenInfoByChainId(balance.chainId, chains2); + const { data: dataCoinPrices = [], isPending: isPendingCoinPrice } = useCoinPrices([ + { + chainId: balance.chainId, + contractAddress: balance.contractAddress } - reselectPrevious(); - } - return success; -} -var copyToClipboard = copy; -function _typeof(obj) { - "@babel/helpers - typeof"; - return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj2) { - return typeof obj2; - } : function(obj2) { - return obj2 && "function" == typeof Symbol && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; - }, _typeof(obj); -} -Object.defineProperty(Component, "__esModule", { - value: true -}); -Component.CopyToClipboard = void 0; -var _react = _interopRequireDefault(reactExports); -var _copyToClipboard = _interopRequireDefault(copyToClipboard); -var _excluded = ["text", "onCopy", "options", "children"]; -function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { "default": obj }; -} -function ownKeys(object2, enumerableOnly) { - var keys = Object.keys(object2); - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object2); - enumerableOnly && (symbols = symbols.filter(function(sym) { - return Object.getOwnPropertyDescriptor(object2, sym).enumerable; - })), keys.push.apply(keys, symbols); + ]); + const { data: conversionRate = 1, isPending: isPendingConversionRate } = useExchangeRate(fiatCurrency.symbol); + const { data: contractInfo, isPending: isPendingContractInfo } = useContractInfo(balance.chainId, balance.contractAddress); + const isPending = isPendingCoinPrice || isPendingConversionRate || isPendingContractInfo; + if (isPending) { + return jsxRuntimeExports$1.jsx(Box, { background: "backgroundSecondary", width: "full", height: "full", borderRadius: "md" }); } - return keys; -} -function _objectSpread(target) { - for (var i = 1; i < arguments.length; i++) { - var source = null != arguments[i] ? arguments[i] : {}; - i % 2 ? ownKeys(Object(source), true).forEach(function(key) { - _defineProperty(target, key, source[key]); - }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + if (isNativeToken) { + const computedBalance2 = computeBalanceFiat({ + balance, + prices: dataCoinPrices, + conversionRate, + decimals: nativeTokenInfo.decimals }); + const priceChangePercentage2 = getPercentagePriceChange(balance, dataCoinPrices); + const formattedBalance2 = formatUnits$2(balance.balance, nativeTokenInfo.decimals); + const balanceDisplayed2 = formatDisplay(formattedBalance2); + return jsxRuntimeExports$1.jsx(CoinTileContent, { chainId: balance.chainId, logoUrl: nativeTokenInfo.logoURI, tokenName: nativeTokenInfo.name, balance: balanceDisplayed2, balanceFiat: computedBalance2, priceChangePercentage: priceChangePercentage2, symbol: nativeTokenInfo.symbol }); } - return target; -} -function _objectWithoutProperties(source, excluded) { - if (source == null) - return {}; - var target = _objectWithoutPropertiesLoose(source, excluded); - var key, i; - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) - continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) - continue; - target[key] = source[key]; - } - } - return target; -} -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) - return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) - continue; - target[key] = source[key]; - } - return target; -} -function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -} -function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) - descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } -} -function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) - _defineProperties(Constructor.prototype, protoProps); - Object.defineProperty(Constructor, "prototype", { writable: false }); - return Constructor; -} -function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function"); + const decimals = (contractInfo == null ? void 0 : contractInfo.decimals) ?? 18; + const computedBalance = computeBalanceFiat({ + balance, + prices: dataCoinPrices, + conversionRate, + decimals + }); + const priceChangePercentage = getPercentagePriceChange(balance, dataCoinPrices); + const formattedBalance = formatUnits$2(balance.balance, decimals); + const balanceDisplayed = formatDisplay(formattedBalance); + const name2 = (contractInfo == null ? void 0 : contractInfo.name) || "Unknown"; + const symbol = (contractInfo == null ? void 0 : contractInfo.name) || "TOKEN"; + const url = contractInfo == null ? void 0 : contractInfo.logoURI; + return jsxRuntimeExports$1.jsx(CoinTileContent, { chainId: balance.chainId, logoUrl: url, tokenName: name2, balance: balanceDisplayed, balanceFiat: computedBalance, priceChangePercentage, symbol }); +}; +const CollectibleTileImage = ({ imageUrl }) => { + return jsxRuntimeExports$1.jsx(Card, { padding: "0", aspectRatio: "1/1", justifyContent: "center", alignItems: "center", overflow: "hidden", borderRadius: "sm", background: "backgroundSecondary", children: jsxRuntimeExports$1.jsx(Image$1, { style: { height: "100%" }, src: imageUrl }) }); +}; +const CollectibleTile = ({ balance }) => { + var _a2; + const { data: tokenMetadata } = useTokenMetadata(balance.chainId, balance.contractAddress, [balance.tokenID || ""]); + const imageUrl = (_a2 = tokenMetadata == null ? void 0 : tokenMetadata[0]) == null ? void 0 : _a2.image; + return jsxRuntimeExports$1.jsx(CollectibleTileImage, { imageUrl }); +}; +const SkeletonTiles = () => { + return jsxRuntimeExports$1.jsx(Box, { style: { + display: "grid", + gridTemplateColumns: `calc(50% - ${vars.space[1]}) calc(50% - ${vars.space[1]})`, + gap: vars.space[2] + }, children: Array(12).fill(null).map((_, i) => jsxRuntimeExports$1.jsx(Box, { children: jsxRuntimeExports$1.jsx(Skeleton, { height: "full", width: "full", aspectRatio: "1/1" }) }, i)) }); +}; +const AssetSummary = () => { + const { address } = useAccount(); + const { setNavigation } = useNavigation(); + const { displayedAssets } = useWalletSettings(); + const { hideUnlistedTokens, hideCollectibles, selectedNetworks } = useSettings(); + const { data: balances = [], isPending: isPendingBalances } = useBalancesAssetsSummary({ + accountAddress: address || "", + chainIds: selectedNetworks, + displayAssets: displayedAssets, + hideCollectibles, + verifiedOnly: hideUnlistedTokens + }); + if (isPendingBalances) { + return jsxRuntimeExports$1.jsx(SkeletonTiles, {}); } - subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); - Object.defineProperty(subClass, "prototype", { writable: false }); - if (superClass) - _setPrototypeOf(subClass, superClass); -} -function _setPrototypeOf(o2, p2) { - _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o3, p3) { - o3.__proto__ = p3; - return o3; - }; - return _setPrototypeOf(o2, p2); -} -function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct(); - return function _createSuperInternal() { - var Super = _getPrototypeOf(Derived), result; - if (hasNativeReflectConstruct) { - var NewTarget = _getPrototypeOf(this).constructor; - result = Reflect.construct(Super, arguments, NewTarget); + const { nativeTokens, erc20Tokens, collectibles } = sortBalancesByType(balances); + const onClickItem = (balance) => { + if (balance.contractType === "ERC1155" || balance.contractType === "ERC721") { + setNavigation && setNavigation({ + location: "collectible-details", + params: { + contractAddress: balance.contractAddress, + chainId: balance.chainId, + tokenId: balance.tokenID || "" + } + }); + } else if (balance.contractType === "ERC20") { + setNavigation && setNavigation({ + location: "coin-details", + params: { + contractAddress: balance.contractAddress, + chainId: balance.chainId + } + }); } else { - result = Super.apply(this, arguments); + setNavigation && setNavigation({ + location: "coin-details", + params: { + contractAddress: balance.contractAddress, + chainId: balance.chainId + } + }); } - return _possibleConstructorReturn(this, result); - }; -} -function _possibleConstructorReturn(self2, call2) { - if (call2 && (_typeof(call2) === "object" || typeof call2 === "function")) { - return call2; - } else if (call2 !== void 0) { - throw new TypeError("Derived constructors may only return object or undefined"); - } - return _assertThisInitialized(self2); -} -function _assertThisInitialized(self2) { - if (self2 === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - return self2; -} -function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) - return false; - if (Reflect.construct.sham) - return false; - if (typeof Proxy === "function") - return true; - try { - Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() { - })); - return true; - } catch (e2) { - return false; - } -} -function _getPrototypeOf(o2) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf2(o3) { - return o3.__proto__ || Object.getPrototypeOf(o3); }; - return _getPrototypeOf(o2); -} -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value; - } - return obj; -} -var CopyToClipboard$1 = /* @__PURE__ */ function(_React$PureComponent) { - _inherits(CopyToClipboard2, _React$PureComponent); - var _super = _createSuper(CopyToClipboard2); - function CopyToClipboard2() { - var _this; - _classCallCheck(this, CopyToClipboard2); - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - _this = _super.call.apply(_super, [this].concat(args)); - _defineProperty(_assertThisInitialized(_this), "onClick", function(event) { - var _this$props = _this.props, text2 = _this$props.text, onCopy = _this$props.onCopy, children = _this$props.children, options = _this$props.options; - var elem = _react["default"].Children.only(children); - var result = (0, _copyToClipboard["default"])(text2, options); - if (onCopy) { - onCopy(text2, result); - } - if (elem && elem.props && typeof elem.props.onClick === "function") { - elem.props.onClick(event); - } - }); - return _this; - } - _createClass(CopyToClipboard2, [{ - key: "render", - value: function render() { - var _this$props2 = this.props; - _this$props2.text; - _this$props2.onCopy; - _this$props2.options; - var children = _this$props2.children, props = _objectWithoutProperties(_this$props2, _excluded); - var elem = _react["default"].Children.only(children); - return /* @__PURE__ */ _react["default"].cloneElement(elem, _objectSpread(_objectSpread({}, props), {}, { - onClick: this.onClick - })); - } - }]); - return CopyToClipboard2; -}(_react["default"].PureComponent); -Component.CopyToClipboard = CopyToClipboard$1; -_defineProperty(CopyToClipboard$1, "defaultProps", { - onCopy: void 0, - options: void 0 -}); -var _require = Component, CopyToClipboard = _require.CopyToClipboard; -CopyToClipboard.CopyToClipboard = CopyToClipboard; -var lib = CopyToClipboard; + return jsxRuntimeExports$1.jsxs(Box, { style: { + display: "grid", + gridTemplateColumns: `calc(50% - ${vars.space[1]}) calc(50% - ${vars.space[1]})`, + gap: vars.space[2] + }, children: [nativeTokens.map((balance, index2) => { + return jsxRuntimeExports$1.jsx(Box, { userSelect: "none", cursor: "pointer", opacity: { hover: "80" }, aspectRatio: "1/1", onClick: () => onClickItem(balance), children: jsxRuntimeExports$1.jsx(CoinTile, { balance }) }, index2); + }), erc20Tokens.map((balance, index2) => { + return jsxRuntimeExports$1.jsx(Box, { userSelect: "none", cursor: "pointer", opacity: { hover: "80" }, aspectRatio: "1/1", onClick: () => onClickItem(balance), children: jsxRuntimeExports$1.jsx(CoinTile, { balance }) }, index2); + }), collectibles.map((balance, index2) => { + return jsxRuntimeExports$1.jsx(Box, { userSelect: "none", cursor: "pointer", opacity: { hover: "80" }, aspectRatio: "1/1", onClick: () => onClickItem(balance), children: jsxRuntimeExports$1.jsx(CollectibleTile, { balance }) }, index2); + })] }); +}; +const Home = () => { + return jsxRuntimeExports$1.jsx(Box, { paddingX: "4", paddingBottom: "5", gap: "4", flexDirection: "column", children: jsxRuntimeExports$1.jsx(AssetSummary, {}) }); +}; const Receive = () => { const { address, chain } = useAccount(); const { chains: chains2 } = useConfig(); @@ -101094,7 +101837,7 @@ const Receive = () => { window.open(`https://twitter.com/intent/tweet?text=Here%20is%20my%20address%20${address}`); } }; - return jsxRuntimeExports$1.jsx(Box, { style: { paddingTop: HEADER_HEIGHT }, children: jsxRuntimeExports$1.jsxs(Box, { padding: "5", paddingTop: "3", flexDirection: "column", justifyContent: "center", alignItems: "center", gap: "4", children: [jsxRuntimeExports$1.jsx(Box, { marginTop: "1", width: "fit", background: "white", borderRadius: "md", alignItems: "center", justifyContent: "center", padding: "4", children: jsxRuntimeExports$1.jsx(QRCode, { value: address || "", size: 200, bgColor: "white", fgColor: "black", "data-id": "receiveQR" }) }), jsxRuntimeExports$1.jsxs(Box, { children: [jsxRuntimeExports$1.jsxs(Box, { flexDirection: "row", alignItems: "center", justifyContent: "center", gap: "2", children: [jsxRuntimeExports$1.jsx(Text, { variant: "medium", color: "text100", textAlign: "center", lineHeight: "inherit", style: { fontWeight: "700" }, children: "My Wallet" }), jsxRuntimeExports$1.jsx(Image$1, { width: "5", src: nativeTokenInfo.logoURI, alt: "icon" })] }), jsxRuntimeExports$1.jsx(Box, { marginTop: "2", style: { maxWidth: "180px", textAlign: "center" }, children: jsxRuntimeExports$1.jsx(Text, { textAlign: "center", color: "text50", style: { + return jsxRuntimeExports$1.jsx(Box, { style: { paddingTop: HEADER_HEIGHT }, children: jsxRuntimeExports$1.jsxs(Box, { padding: "5", paddingTop: "3", flexDirection: "column", justifyContent: "center", alignItems: "center", gap: "4", children: [jsxRuntimeExports$1.jsx(Box, { marginTop: "1", width: "fit", background: "white", borderRadius: "md", alignItems: "center", justifyContent: "center", padding: "4", children: jsxRuntimeExports$1.jsx(QRCode$1, { value: address || "", size: 200, bgColor: "white", fgColor: "black", "data-id": "receiveQR" }) }), jsxRuntimeExports$1.jsxs(Box, { children: [jsxRuntimeExports$1.jsxs(Box, { flexDirection: "row", alignItems: "center", justifyContent: "center", gap: "2", children: [jsxRuntimeExports$1.jsx(Text, { variant: "medium", color: "text100", textAlign: "center", lineHeight: "inherit", style: { fontWeight: "700" }, children: "My Wallet" }), jsxRuntimeExports$1.jsx(Image$1, { width: "5", src: nativeTokenInfo.logoURI, alt: "icon" })] }), jsxRuntimeExports$1.jsx(Box, { marginTop: "2", style: { maxWidth: "180px", textAlign: "center" }, children: jsxRuntimeExports$1.jsx(Text, { textAlign: "center", color: "text50", style: { fontSize: "14px", maxWidth: "180px", overflowWrap: "anywhere" @@ -108545,6 +109288,7 @@ const Connected = () => { const { setOpenWalletModal } = useOpenWalletModal(); const { triggerCheckout } = useCheckoutModal(); const { triggerAddFunds } = useAddFundsModal(); + const { openERC1155SaleContractPaymentModal } = useERC1155SaleContractPaymentModal(); const { data: walletClient } = useWalletClient(); const storage = useStorage(); const [isCheckoutInfoModalOpen, setIsCheckoutInfoModalOpen] = React.useState(false); @@ -108693,6 +109437,35 @@ const Connected = () => { const onClickCheckout = () => { setIsCheckoutInfoModalOpen(true); }; + const onClickSelectPayment = () => { + if (!address) { + return; + } + const currencyAddress = "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"; + const salesContractAddress = "0xe65b75eb7c58ffc0bf0e671d64d0e1c6cd0d3e5b"; + const price = "20000"; + const chainId2 = 137; + const tokenId = "1"; + const nftQuantity = "1"; + const collectionAddress = "0xdeb398f41ccd290ee5114df7e498cf04fac916cb"; + openERC1155SaleContractPaymentModal({ + chain: chainId2, + price, + targetContractAddress: salesContractAddress, + recipientAddress: address, + currencyAddress, + tokenId, + collectionAddress, + nftQuantity, + isDev: true, + onSuccess: (txnHash) => { + console.log("success!", txnHash); + }, + onError: (error2) => { + console.error(error2); + } + }); + }; const onCheckoutInfoConfirm = () => { setIsCheckoutInfoModalOpen(false); if (checkoutOrderId !== "" && checkoutTokenContractAddress !== "" && checkoutTokenId !== "") { @@ -108825,7 +109598,15 @@ const Connected = () => { onClick: onClickCheckout } ) - ] }) + ] }), + /* @__PURE__ */ jsxRuntimeExports$1.jsx( + CardButton, + { + title: "Select Payment Method", + description: "Purchase an NFT through various purchase methods", + onClick: onClickSelectPayment + } + ) ] }), pendingFeeOptionConfirmation && feeOptionBalances.length > 0 && /* @__PURE__ */ jsxRuntimeExports$1.jsxs(Box, { marginY: "3", children: [ /* @__PURE__ */ jsxRuntimeExports$1.jsx( @@ -109173,9 +109954,9 @@ const kitConfig = { projectAccessKey, defaultTheme: "dark", signIn: { - projectName: "Kit Demo", + projectName: "Kit Demo" // logoUrl: 'sw-logo-white.svg', - useMock: isDebugMode + // useMock: isDebugMode }, displayedAssets: [ // Native token diff --git a/assets/index-CyfTH7LX.js b/assets/index-DGLMhC4E.js similarity index 99% rename from assets/index-CyfTH7LX.js rename to assets/index-DGLMhC4E.js index 2e16e313..6f0455d7 100644 --- a/assets/index-CyfTH7LX.js +++ b/assets/index-DGLMhC4E.js @@ -1,6 +1,6 @@ -import { c as commonjsGlobal, B as Buffer, a as getAugmentedNamespace, p as process$1, t as tslib_es6, e as eventemitter3Exports, g as getDefaultExportFromCjs } from "./index-BzPqRlsG.js"; -import { c as require$$0$1, s as sha_jsExports, a as require$$1$1, b as require$$2, r as require$$0$2, j as js } from "./hooks.module-B0yPPEfe.js"; -import { e as eventsExports } from "./___vite-browser-external_commonjs-proxy-BBNlhQUO.js"; +import { c as commonjsGlobal, B as Buffer, a as getAugmentedNamespace, p as process$1, t as tslib_es6, e as eventemitter3Exports, g as getDefaultExportFromCjs } from "./index-CsHzCx6e.js"; +import { c as require$$0$1, s as sha_jsExports, a as require$$1$1, b as require$$2, r as require$$0$2, j as js } from "./hooks.module-DH-Wk4N-.js"; +import { e as eventsExports } from "./___vite-browser-external_commonjs-proxy-BKpD9f8m.js"; function _mergeNamespaces(n, m) { for (var i = 0; i < m.length; i++) { const e = m[i]; diff --git a/assets/index.es-C_0Ilmtr.js b/assets/index.es-DMLMwzgY.js similarity index 99% rename from assets/index.es-C_0Ilmtr.js rename to assets/index.es-DMLMwzgY.js index 8e535fdb..924be41b 100644 --- a/assets/index.es-C_0Ilmtr.js +++ b/assets/index.es-DMLMwzgY.js @@ -1,6 +1,6 @@ -const __vite__fileDeps=["./index-CIeoByUV.js","./index-BzPqRlsG.js","./index-B7cGsFOk.css"],__vite__mapDeps=i=>i.map(i=>__vite__fileDeps[i]); -import { p as process$1, r as require$$0$1, b as global, B as Buffer, g as getDefaultExportFromCjs, c as commonjsGlobal, a as getAugmentedNamespace, _ as __vitePreload } from "./index-BzPqRlsG.js"; -import { r as require$$3, e as eventsExports, W as Wg } from "./___vite-browser-external_commonjs-proxy-BBNlhQUO.js"; +const __vite__fileDeps=["./index-B1JZcE-u.js","./index-CsHzCx6e.js","./index-B7cGsFOk.css"],__vite__mapDeps=i=>i.map(i=>__vite__fileDeps[i]); +import { p as process$1, r as require$$0$1, b as global, B as Buffer, g as getDefaultExportFromCjs, c as commonjsGlobal, a as getAugmentedNamespace, _ as __vitePreload } from "./index-CsHzCx6e.js"; +import { r as require$$3, e as eventsExports, W as Wg } from "./___vite-browser-external_commonjs-proxy-BKpD9f8m.js"; var __spreadArray = function(to2, from2, pack) { if (pack || arguments.length === 2) for (var i3 = 0, l2 = from2.length, ar2; i3 < l2; i3++) { @@ -19748,7 +19748,7 @@ class C { if (this.rpc = this.getRpcConfig(t), this.chainId = this.rpc.chains.length ? m2(this.rpc.chains) : m2(this.rpc.optionalChains), this.signer = await hv.init({ projectId: this.rpc.projectId, metadata: this.rpc.metadata, disableProviderPing: t.disableProviderPing, relayUrl: t.relayUrl, storageOptions: t.storageOptions }), this.registerEventListeners(), await this.loadPersistedSession(), this.rpc.showQrModal) { let s2; try { - const { WalletConnectModal: i3 } = await __vitePreload(() => import("./index-CIeoByUV.js").then((n4) => n4.i), true ? __vite__mapDeps([0,1,2]) : void 0, import.meta.url); + const { WalletConnectModal: i3 } = await __vitePreload(() => import("./index-B1JZcE-u.js").then((n4) => n4.i), true ? __vite__mapDeps([0,1,2]) : void 0, import.meta.url); s2 = i3; } catch { throw new Error("To use QR modal, please install @walletconnect/modal package"); diff --git a/index.html b/index.html index 558c632a..521618a0 100644 --- a/index.html +++ b/index.html @@ -24,7 +24,7 @@ Learn how to configure a non-root public URL by running `npm run build`. --> Sequence Kit Demo - +