UNPKG

@0xsequence/anypay-sdk

Version:

SDK for Anypay functionality

1,140 lines (1,139 loc) 35.5 kB
import { useQuery as He } from "./node_modules/.pnpm/@tanstack_react-query@5.80.7_react@19.1.0/node_modules/@tanstack/react-query/build/modern/useQuery.js"; import { useMutation as Wn } from "./node_modules/.pnpm/@tanstack_react-query@5.80.7_react@19.1.0/node_modules/@tanstack/react-query/build/modern/useMutation.js"; import { useState as p, useCallback as Zn, useEffect as Z, useMemo as ne, useRef as $e } from "react"; import { zeroAddress as L, isAddressEqual as Vn, createPublicClient as zn, http as Qn, parseUnits as ee, formatUnits as te, createWalletClient as oe, custom as se } from "viem"; import * as Me from "./node_modules/.pnpm/viem@2.31.2_bufferutil@4.0.9_typescript@5.8.3_utf-8-validate@5.0.10_zod@3.25.64/node_modules/viem/_esm/chains/index.js"; import { useSwitchChain as Ne, useSendTransaction as Fe, useEstimateGas as Pe, useWaitForTransactionReceipt as Ue } from "wagmi"; import { useAPIClient as Be } from "./apiClient.js"; import { getERC20TransferData as Dn } from "./encoders.js"; import { calculateIntentAddress as An, sendOriginTransaction as Kn, getIntentCallsPayloads as le, commitIntentConfig as Oe } from "./intents.js"; import { useMetaTxnsMonitor as qe, getMetaTxStatus as ie } from "./metaTxnMonitor.js"; import { relayerSendMetaTx as ae } from "./metaTxns.js"; import { findFirstPreconditionForChainId as Re, findPreconditionAddress as re } from "./preconditions.js"; import { useRelayers as De } from "./relayer.js"; import { getChainInfo as Mn } from "./tokenBalances.js"; import { requestWithTimeout as je } from "./utils.js"; import { from as $n } from "./node_modules/.pnpm/ox@0.7.2_typescript@5.8.3_zod@3.25.64/node_modules/ox/_esm/core/Address.js"; const ce = 1e4; function st(z) { const { account: o, disableAutoExecute: r = !1, env: c, useV3Relayers: hn = !0, sequenceApiKey: G } = z, M = Be({ projectAccessKey: G }), [C, B] = p(!r), [Tn, mn] = p(!1), [H, cn] = p( {} ), [u, Q] = p(null), [S, R] = p(null), [A, W] = p(null), [F, nn] = p(null), [gn, V] = p(null), [E, In] = p(), [D, Y] = p(null), [t, Sn] = p(null), [Yn, En] = p({}), [b, w] = p(!1), [pn, P] = p(!1), { switchChain: wn, isPending: ln, error: en } = Ne(), { sendTransaction: dn, isPending: yn } = Fe(), [Nn, bn] = p(!1), [d, $] = p(null), [j, f] = p(null), [_, y] = p({}), [h, g] = p(null), { getRelayer: un } = De({ env: c, useV3Relayers: hn }), { data: xn, isError: K, error: fn } = Pe( t != null && t.to && (t != null && t.chainId) && !t.error ? { to: t.to || void 0, data: t.data || void 0, value: t.value || void 0, chainId: t.chainId || void 0 } : void 0 ), T = Wn({ mutationFn: async (n) => { if (!M) throw new Error("API client not available"); if (!n.lifiInfos) throw new Error("LifiInfos not available"); try { console.log("Calculating intent address..."), console.log("Main signer:", n.mainSigner), console.log("Calls:", n.calls), console.log("LifiInfos:", n.lifiInfos); const e = An( n.mainSigner, n.calls, // TODO: Add proper type n.lifiInfos // TODO: Add proper type ), s = re(n.preconditions); console.log("Calculated address:", e.toString()), console.log("Received address:", s); const l = Vn( $n(s), e ); if (g({ success: l, receivedAddress: s, calculatedAddress: e.toString() }), !l) throw new Error( "Address verification failed: Calculated address does not match received address." ); const a = await M.commitIntentConfig({ walletAddress: e.toString(), mainSigner: n.mainSigner, calls: n.calls, preconditions: n.preconditions, lifiInfos: n.lifiInfos }); return console.log("API Commit Response:", a), { calculatedAddress: e.toString(), response: a }; } catch (e) { if (console.error("Error during commit intent mutation:", e), !(h != null && h.success) && !(h != null && h.receivedAddress)) try { const s = An( n.mainSigner, n.calls, // TODO: Add proper type n.lifiInfos // TODO: Add proper type ), l = re(n.preconditions); g({ success: !1, receivedAddress: l, calculatedAddress: s.toString() }); } catch (s) { console.error( "Error calculating addresses for verification status on failure:", s ), g({ success: !1 }); } throw e; } }, onSuccess: (n) => { console.log( "Intent config committed successfully, Wallet Address:", n.calculatedAddress ), Y(n.calculatedAddress); }, onError: (n) => { console.error("Failed to commit intent config:", n), Y(null); } }), { data: Fn, isLoading: Pn, error: Un } = He({ queryKey: ["getIntentConfig", D], queryFn: async () => { if (!M || !D) throw new Error("API client or committed intent address not available"); return console.log("Fetching intent config for address:", D), await M.getIntentConfig({ walletAddress: D }); }, enabled: !!D && !!M && T.isSuccess, staleTime: 1e3 * 60 * 5, // 5 minutes retry: 1 }); async function i(n) { return le(M, n); } const m = Wn({ mutationFn: async (n) => { if (n.originChainId === n.destinationChainId && Vn( $n(n.originTokenAddress), $n(n.destinationTokenAddress) )) throw new Error( "The same token cannot be used as both the source and destination token." ); if (!o.address) throw new Error("Missing selected token or account address"); Y(null), g(null), V(null), Q(null), R(null), W(null), nn(null); const e = await i(n); return Q(e.metaTxns), R(e.calls), W(e.preconditions), nn(e.lifiInfos), V(e.anypayFee), Y(null), g(null), e; }, onSuccess: (n) => { console.log("Intent Config Success:", n), V(n.anypayFee || null), nn(n.lifiInfos || null), n != null && n.calls && n.calls.length > 0 && n.preconditions && n.preconditions.length > 0 && n.metaTxns && n.metaTxns.length > 0 ? (R(n.calls), W(n.preconditions), Q(n.metaTxns)) : (console.warn("API returned success but no operations found."), R(null), W(null), Q(null)); }, onError: (n) => { console.error("Intent Config Error:", n), R(null), W(null), Q(null), nn(null), V(null); } }); function I(n) { m.mutate(n); } const O = Zn(() => { console.log("[AnyPay] Clearing intent state"), R(null), W(null), Q(null), nn(null), V(null), Y(null), g(null), En({}), mn(!1), y({}); }, []), x = Zn( (n, e, s, l, a) => { $({ txnHash: n, status: e === "success" ? "Success" : e === "reverted" ? "Failed" : e === "sending" ? "Sending..." : "Pending", revertReason: e === "reverted" ? a || "Transaction reverted" : void 0, gasUsed: s ? Number(s) : void 0, effectiveGasPrice: l == null ? void 0 : l.toString() }); }, [] ), J = async () => { if (console.log("Sending origin transaction..."), console.log( b, t, t == null ? void 0 : t.error, t == null ? void 0 : t.to, t == null ? void 0 : t.data, t == null ? void 0 : t.value, t == null ? void 0 : t.chainId ), b || // Prevent duplicate transactions !t || t.error || !t.to || t.data === null || t.value === null || t.chainId === null) { console.error( "Origin call parameters not available or invalid:", t ), x( void 0, "reverted", void 0, void 0, "Origin call parameters not ready" ); return; } if (o.chainId !== t.chainId) { P(!0), x( void 0, "pending", void 0, void 0, `Switching to chain ${t.chainId}...` ); const n = oe({ chain: Mn(t.chainId), transport: se(await o.connector.getProvider()) // TODO: Add proper type }); try { await jn(n, t.chainId), P(!1); } catch (e) { console.error("Chain switch failed:", e), e instanceof Error && e.message.includes("User rejected") && B(!1), x( void 0, "reverted", void 0, void 0, e instanceof Error ? e.message : "Unknown error switching chain" ), P(!1); return; } } if (b) console.warn( "Transaction already in progress. Skipping duplicate request." ); else { if (w(!0), In(void 0), x(void 0, "sending"), !xn && !K) { bn(!0); return; } if (K) { console.error("Gas estimation failed:", fn), x( void 0, "reverted", void 0, void 0, `Gas estimation failed: ${fn == null ? void 0 : fn.message}` ), w(!1); return; } const n = xn ? BigInt(Math.floor(Number(xn) * 1.2)) : void 0; dn( { to: t.to, data: t.data, value: t.value, chainId: t.chainId, gas: n }, { onSuccess: (e) => { console.log("Transaction sent, hash:", e), In(e), w(!1); }, onError: (e) => { console.error("Transaction failed:", e), e instanceof Error && (e.message.includes("User rejected") || e.message.includes("user rejected")) && B(!1), x( void 0, "reverted", void 0, void 0, e instanceof Error ? e.message : "Unknown error" ), w(!1); } } ); } }; Z(() => { en && (console.error("Chain switch error:", en), x( void 0, "reverted", void 0, void 0, `Chain switch failed: ${en.message || "Unknown error"}` ), P(!1)); }, [en, x]), Z(() => { bn(!1); }, []), Z(() => { t != null && t.chainId && o.chainId === t.chainId && (console.log("No chain switch required"), P(!1)); }, [o.chainId, t == null ? void 0 : t.chainId]), Z(() => { if (t != null && t.chainId && o.chainId !== t.chainId) { async function n() { try { const e = t.chainId, s = oe({ chain: Mn(e), transport: se(await o.connector.getProvider()) // TODO: Add proper type }); await jn(s, e); } catch (e) { console.error("Chain switch failed:", e); } } n().catch(console.error); } }, [o, t]); const { data: k, isLoading: tn, isSuccess: _n, isError: Ln, error: on } = Ue({ hash: E, confirmations: 1, query: { enabled: !!E } }); Z(() => { var n; if (!E) { d != null && d.txnHash && $(null), f(null), Object.keys(H).length > 0 && cn({}); return; } if (!((d == null ? void 0 : d.txnHash) === E && ((d == null ? void 0 : d.status) === "Success" || (d == null ? void 0 : d.status) === "Failed") && !tn)) { if (tn) { $((e) => ({ ...(e == null ? void 0 : e.txnHash) === E ? e : { gasUsed: void 0, effectiveGasPrice: void 0, revertReason: void 0 }, txnHash: E, status: "Pending" })); return; } if (_n && k) { const e = k.status === "success" ? "Success" : "Failed"; $({ txnHash: k.transactionHash, status: e, gasUsed: k.gasUsed ? Number(k.gasUsed) : void 0, effectiveGasPrice: (n = k.effectiveGasPrice) == null ? void 0 : n.toString(), revertReason: k.status === "reverted" ? (on == null ? void 0 : on.message) || "Transaction reverted by receipt" : void 0 }), e === "Success" && k.blockNumber ? (async () => { try { if (!(t != null && t.chainId)) { console.error( "[AnyPay] Origin chainId not available for fetching origin block timestamp." ), f(null); return; } const l = Mn(t.chainId), N = await zn({ chain: l, transport: Qn() }).getBlock({ blockNumber: BigInt(k.blockNumber) }); f(Number(N.timestamp)); } catch (l) { console.error( "[AnyPay] Error fetching origin block timestamp:", l ), f(null); } })() : e !== "Success" && f(null), e === "Success" && u && u.length > 0 && C && !u.some((s) => H[`${s.chainId}-${s.id}`]) && (console.log( "Origin transaction successful, auto-sending all meta transactions..." ), vn.mutate({ selectedId: null })); } else Ln && ($({ txnHash: E, status: "Failed", revertReason: (on == null ? void 0 : on.message) || "Failed to get receipt", gasUsed: void 0, effectiveGasPrice: void 0 }), f(null)); } }, [ E, tn, _n, Ln, k, on, u, H, C, t == null ? void 0 : t.chainId, d == null ? void 0 : d.status, d == null ? void 0 : d.txnHash ]), Z(() => { C && T.isSuccess && (t == null ? void 0 : t.chainId) && o.chainId === t.chainId && !t.error && t.to && t.data !== null && t.value !== null && !yn && !tn && !E && !pn && !d && !Tn && (console.log("Auto-executing transaction: All conditions met."), mn(!0), $({ status: "Sending..." }), dn( { to: t.to, data: t.data, value: t.value, chainId: t.chainId }, { onSuccess: (e) => { console.log("Auto-executed transaction sent, hash:", e), In(e); }, onError: (e) => { console.error("Auto-executed transaction failed:", e), e instanceof Error && (e.message.includes("User rejected") || e.message.includes("user rejected")) && B(!1), $({ status: "Failed", revertReason: e instanceof Error ? e.message : "Unknown error" }), mn(!1); } } )); }, [ C, T.isSuccess, t, o.chainId, yn, tn, E, pn, d, Tn, dn ]), Z(() => { C && S && A && F && o.address && Bn && !T.isPending && !T.isSuccess && (console.log("Auto-committing intent configuration..."), T.mutate({ walletAddress: Bn.toString(), mainSigner: o.address, calls: S, preconditions: A, lifiInfos: F })); }, [ C, S, A, F, // Add lifiInfos dependency o.address, T, T.isPending, T.isSuccess ]); const vn = Wn({ mutationFn: async ({ selectedId: n }) => { if (!S || !A || !u || !o.address || !F) throw new Error("Missing required data for meta-transaction"); const e = An( o.address, S, F ), s = n ? [u.find((a) => a.id === n)] : u; if (!s || n && !s[0]) throw new Error("Meta transaction not found"); const l = []; for (const a of s) { if (!a) continue; const N = `${a.chainId}-${a.id}`, X = H[N], q = Date.now(); if (X && q - X < ce) { const v = Math.ceil( (ce - (q - X)) / 1e3 ); console.log( `Meta transaction for ${N} was sent recently. Wait ${v}s before retry` ); continue; } try { const v = parseInt(a.chainId); if (Number.isNaN(v) || v <= 0) throw new Error(`Invalid chainId for meta transaction: ${v}`); const an = un(v); if (!an) throw new Error(`No relayer found for chainId: ${v}`); const On = A.filter( (U) => U.chainId && parseInt(U.chainId) === v ); console.log( `Relaying meta transaction ${N} to intent ${e} via relayer:`, an ); const { opHash: qn } = await an.sendMetaTxn( a.walletAddress, a.contract, a.input, BigInt(a.chainId), void 0, On ), Jn = !1; l.push({ operationKey: N, opHash: qn, success: !0 }); } catch (v) { l.push({ operationKey: N, error: v instanceof Error ? v.message : "Unknown error", success: !1 }); } } return l; }, onSuccess: (n) => { n.forEach(({ operationKey: e, opHash: s, success: l }) => { l && s && (cn((a) => ({ ...a, [e]: Date.now() })), En((a) => ({ ...a, [e]: s }))); }); }, onError: (n) => { console.error("Error in meta-transaction process:", n); }, retry: 5, // Allow up to 2 retries retryDelay: (n) => Math.min(1e3 * 2 ** n, 3e4) // Exponential backoff }), [kn, de] = p(null), [Cn, ue] = p(null); Z(() => { var n, e, s, l, a, N, X; if (!((n = S == null ? void 0 : S[0]) != null && n.chainId) || !kn || !Cn || !A || !o.address) { Sn(null); return; } try { const q = Bn; let v, an = "0x", On = 0n; const qn = q; if (kn === L) { const U = A.find( (rn) => (rn.type === "transfer-native" || rn.type === "native-balance") && rn.chainId === Cn.toString() ), Hn = ((s = (e = U == null ? void 0 : U.data) == null ? void 0 : e.minAmount) == null ? void 0 : s.toString()) ?? ((a = (l = U == null ? void 0 : U.data) == null ? void 0 : l.min) == null ? void 0 : a.toString()); if (Hn === void 0) throw new Error( "Could not find native precondition (transfer-native or native-balance) or min amount" ); On = BigInt(Hn), v = qn; } else { const U = A.find( (rn) => { var Xn; return rn.type === "erc20-balance" && rn.chainId === Cn.toString() && ((Xn = rn.data) == null ? void 0 : Xn.token) && Vn( $n(rn.data.token), $n(kn) ); } ), Hn = (X = (N = U == null ? void 0 : U.data) == null ? void 0 : N.min) == null ? void 0 : X.toString(); if (Hn === void 0) throw new Error( "Could not find ERC20 balance precondition or min amount" ); an = Dn(qn, Hn), v = kn; } Sn({ to: v, data: an, value: On, chainId: Cn, error: void 0 }); } catch (q) { console.error("Failed to calculate origin call params for UI:", q), Sn({ to: null, data: null, value: null, chainId: null, error: q instanceof Error ? q.message : "Unknown error" }); } }, [ S, kn, Cn, A, o.address ]); const sn = qe( u, un ); ne(() => !u || Object.keys(sn).length === 0 ? "no_statuses" : u.map((e) => `${e.chainId}-${e.id}`).sort().map((e) => { const s = sn[e]; return `${e}:${s ? s.status : "loading"}`; }).join(","), [u, sn]); const Gn = $e(/* @__PURE__ */ new Set()); Z(() => { if (console.log("[AnyPay] Running meta-transaction block timestamp effect:", { metaTxnsLength: u == null ? void 0 : u.length, monitorStatusesLength: Object.keys(sn).length }), !u || u.length === 0) { console.log("[AnyPay] No meta transactions, clearing timestamps"), Gn.current.clear(), Object.keys(_).length > 0 && y({}); return; } if (!Object.keys(sn).length) { console.log("[AnyPay] No monitor statuses yet, waiting..."); return; } u.forEach(async (n) => { const e = `${n.chainId}-${n.id}`; if (Gn.current.has(e)) { console.log( `[AnyPay] MetaTxn ${e}: Already processed, skipping` ); return; } const s = sn[e]; if (!s || s.status !== "confirmed") { console.log( `[AnyPay] MetaTxn ${e}: Status not confirmed, skipping` ); return; } const l = s.transactionHash; if (!l) { console.log( `[AnyPay] MetaTxn ${e}: No transaction hash, skipping` ); return; } console.log( `[AnyPay] MetaTxn ${e}: Processing transaction ${l}` ), Gn.current.add(e); try { const a = parseInt(n.chainId); if (Number.isNaN(a) || a <= 0) throw new Error( `Invalid chainId for meta transaction: ${n.chainId}` ); const N = Mn(a), X = zn({ chain: N, transport: Qn() }), q = await X.getTransactionReceipt({ hash: l }); if (q && typeof q.blockNumber == "bigint") { const v = await X.getBlock({ blockNumber: q.blockNumber }); console.log( `[AnyPay] MetaTxn ${e}: Got block timestamp ${v.timestamp}` ), y((an) => ({ ...an, [e]: { timestamp: Number(v.timestamp), error: void 0 } })); } else console.warn( `[AnyPay] MetaTxn ${e}: No block number in receipt` ), y((v) => ({ ...v, [e]: { timestamp: null, error: "Block number not found in receipt" } })); } catch (a) { console.error(`[AnyPay] MetaTxn ${e}: Error:`, a), y((N) => ({ ...N, [e]: { timestamp: null, error: a.message || "Failed to fetch receipt/timestamp" } })); } }); }, [u, sn, _]); const fe = (n) => { B(n); }; function he(n) { m.mutate(n); } const Bn = ne(() => !o.address || !S || !F ? null : An( o.address, S, F ), [o.address, S, F]), me = m.isPending, ge = m.isSuccess, Ie = m.error, pe = m.variables; function we(n) { console.log("commitIntentConfig", n), T.mutate(n); } function ye(n) { if (!n) { Sn(null); return; } const { originChainId: e, tokenAddress: s } = n; ue(e), de(s); } function ve(n) { vn.mutate({ selectedId: n }); } const Ae = T.isPending, Te = T.isSuccess, Se = T.error, Ee = T.variables, be = vn.isPending, xe = vn.isSuccess, ke = vn.error, Ce = vn.variables; return { apiClient: M, metaTxns: u, intentCallsPayloads: S, intentPreconditions: A, lifiInfos: F, anypayFee: gn, txnHash: E, committedIntentAddress: D, verificationStatus: h, getRelayer: un, estimatedGas: xn, isEstimateError: K, estimateError: fn, calculateIntentAddress: An, committedIntentConfig: Fn, isLoadingCommittedConfig: Pn, committedConfigError: Un, commitIntentConfig: we, commitIntentConfigPending: Ae, commitIntentConfigSuccess: Te, commitIntentConfigError: Se, commitIntentConfigArgs: Ee, getIntentCallsPayloads: i, operationHashes: Yn, callIntentCallsPayload: I, sendOriginTransaction: J, switchChain: wn, isSwitchingChain: ln, switchChainError: en, isTransactionInProgress: b, isChainSwitchRequired: pn, sendTransaction: dn, isSendingTransaction: yn, originCallStatus: d, updateOriginCallStatus: x, isEstimatingGas: Nn, isAutoExecute: C, updateAutoExecute: fe, receipt: k, isWaitingForReceipt: tn, receiptIsSuccess: _n, receiptIsError: Ln, receiptError: on, hasAutoExecuted: Tn, sentMetaTxns: H, sendMetaTxn: ve, sendMetaTxnPending: be, sendMetaTxnSuccess: xe, sendMetaTxnError: ke, sendMetaTxnArgs: Ce, clearIntent: O, metaTxnMonitorStatuses: sn, createIntent: he, createIntentPending: me, createIntentSuccess: ge, createIntentError: Ie, createIntentArgs: pe, calculatedIntentAddress: Bn, originCallParams: t, updateOriginCallParams: ye, originBlockTimestamp: j, metaTxnBlockTimestamps: _ }; } async function it(z) { var en, dn, yn, Nn, bn, d; const { account: o, originTokenAddress: r, originChainId: c, originTokenAmount: hn, // account balance destinationChainId: G, recipient: M, destinationTokenAddress: C, destinationTokenAmount: B, destinationTokenSymbol: Tn, fee: mn, client: H, dryMode: cn, apiClient: u, originRelayer: Q, destinationRelayer: S, destinationCalldata: R, onTransactionStateChange: A, sourceTokenPriceUsd: W, destinationTokenPriceUsd: F, sourceTokenDecimals: nn, destinationTokenDecimals: gn } = z; if (!H) throw new Error("Wallet client not provided"); const V = Mn(c), E = c === G, In = r === C, D = zn({ chain: V, transport: Qn() }), Y = o.address, t = R || (C === L ? "0x" : Dn(M, BigInt(B))), En = { userAddress: Y, originChainId: c, originTokenAddress: r, originTokenAmount: r === C ? B : hn, // max amount destinationChainId: G, destinationToAddress: R || C === L ? M : C, destinationTokenAddress: C, destinationTokenAmount: B, destinationTokenSymbol: Tn, destinationCallData: t, destinationCallValue: C === L ? B : "0" }, b = []; if (b.push({ transactionHash: "", explorerUrl: "", chainId: c, state: "pending" }), E || (b.push({ transactionHash: "", explorerUrl: "", chainId: c, state: "pending" }), b.push({ transactionHash: "", explorerUrl: "", chainId: G, state: "pending" })), E && !In && b.push({ transactionHash: "", explorerUrl: "", chainId: c, state: "pending" }), In && E) return { send: async ($) => { const j = { to: R || r === L ? M : r, data: R || (r === L ? "0x" : Dn( M, BigInt(B) )), value: r === L ? BigInt(B) : "0", chainId: c, chain: V }; console.log("origin call params", j); let f = null; const _ = null, y = null; if (await jn(H, c), !cn) { A([ { transactionHash: "", explorerUrl: "", chainId: c, state: "pending" } ]), console.log("origin call params", j); const h = await Kn( o, H, j ); console.log("origin tx", h), $ && $(); const g = await D.waitForTransactionReceipt({ hash: h }); console.log("receipt", g), f = g, A([ { transactionHash: f == null ? void 0 : f.transactionHash, explorerUrl: Rn( f == null ? void 0 : f.transactionHash, c ), chainId: c, state: (f == null ? void 0 : f.status) === "success" ? "confirmed" : "failed" } ]); } return { originUserTxReceipt: f, originMetaTxnReceipt: _, destinationMetaTxnReceipt: y }; } }; console.log("Creating intent with args:", En); const w = await le( u, En ); if (console.log("Got intent:", w), !w) throw new Error("Invalid intent"); if (!((en = w.preconditions) != null && en.length) || !((dn = w.calls) != null && dn.length) || !((yn = w.lifiInfos) != null && yn.length)) throw new Error("Invalid intent"); const pn = An( Y, w.calls, w.lifiInfos ); console.log("Calculated intent address:", pn.toString()), await Oe( u, Y, w.calls, w.preconditions, w.lifiInfos ), console.log("Committed intent config"); const P = Re( w.preconditions, c ); if (!P) throw new Error("No precondition found for origin chain"); const wn = (Nn = P == null ? void 0 : P.data) == null ? void 0 : Nn.address, ln = (d = (bn = P == null ? void 0 : P.data) == null ? void 0 : bn.min) == null ? void 0 : d.toString(); return { intentAddress: pn, originSendAmount: ln, send: async ($) => { var T, Fn, Pn, Un; console.log("sending origin transaction"); let j = !1, f = ee("0.00005", 18).toString(); if (c === 137 && (f = ee("1.5", 18).toString()), console.log("sourceTokenPriceUsd", W), console.log("destinationTokenPriceUsd", F), console.log("sourceTokenDecimals", nn), console.log("destinationTokenDecimals", gn), r !== L && W && F && ln && gn !== void 0 && nn !== void 0) { const i = Number( te(BigInt(B), gn) ), m = Number( te(BigInt(ln), gn) ); console.log("destinationAmount", i), console.log("preconditionMin", m); const I = i * F, O = m * W, x = O - I; console.log( "destinationAmountUsd", I, "preconditionMinUsd", O, "diff", x ), x >= 0 && x <= 0.02 && (j = !0); } console.log("needsNativeFee", j); const _ = { to: r === L ? wn : r, data: r === L ? "0x" : Dn( wn, BigInt(ln) + BigInt(mn) ), value: r === L ? BigInt(ln) + BigInt(mn) : "0", chain: V }; let y = null, h = null, g = null; A(b), await jn(H, c); let un = !1; if (j) try { const i = await je( H, [ { method: "wallet_getCapabilities", params: [o.address] } ], 1e4 ); console.log("capabilities", i); const m = `0x${c.toString(16)}`, I = i[m]; un = ((T = I == null ? void 0 : I.atomic) == null ? void 0 : T.status) === "supported"; } catch (i) { console.error("Error getting capabilities", i); } if (cn && console.log("dry mode, skipping send calls"), console.log(un ? "using sendCalls" : "using sendTransaction"), un) { if (!cn) { const i = []; j && i.push({ to: wn, data: "0x00", value: `0x${BigInt(f).toString(16)}` }), i.push({ to: _.to, data: _.data, value: _.value ? `0x${BigInt(_.value).toString(16)}` : "0x0" }); const m = await H.request({ method: "wallet_sendCalls", params: [ { version: "2.0.0", chainId: `0x${c.toString(16)}`, atomicRequired: !0, calls: i } ] }); console.log("sendCalls result", m); const I = m.requestId || m.id; let O; for (; !O; ) { const J = await H.request({ method: "wallet_getCallsStatus", params: [I] }); console.log("getCallsStatus result", J); const k = (Fn = J == null ? void 0 : J.receipts) == null ? void 0 : Fn[0]; if (J.status === 200 && (k != null && k.transactionHash)) { O = k.transactionHash; break; } else if (J.status === 500) throw new Error(`Transaction failed: ${J.error}`); await new Promise((tn) => setTimeout(tn, 2e3)); } $ && $(); const x = await D.waitForTransactionReceipt({ hash: O }); console.log("receipt", x), y = x; } } else if (!cn) { if (j) { const I = await Kn(o, H, { to: wn, data: "0x00", value: f, chain: V }); console.log("origin tx", I); const O = await D.waitForTransactionReceipt({ hash: I }); console.log("nativeFeeReceipt", O); } const i = await Kn( o, H, _ ); console.log("origin tx", i), $ && $(); const m = await D.waitForTransactionReceipt({ hash: i }); console.log("receipt", m), y = m; } b[0] = { transactionHash: y == null ? void 0 : y.transactionHash, explorerUrl: Rn( y == null ? void 0 : y.transactionHash, c ), chainId: c, state: (y == null ? void 0 : y.status) === "success" ? "confirmed" : "failed" }, A(b), await new Promise((i) => setTimeout(i, 2e3)); const K = w.metaTxns[0]; console.log("metaTx", K); const fn = await ae(Q, K, [ w.preconditions[0] ]); for (console.log("opHash", fn); ; ) { console.log( "polling status", K.id, BigInt(K.chainId) ); const i = await ie( Q, K.id, Number(K.chainId) ); if (console.log("status", i), i.transactionHash) { h = (Pn = i.data) == null ? void 0 : Pn.receipt; break; } await new Promise((m) => setTimeout(m, 1e3)); } if (b[1] = { transactionHash: h == null ? void 0 : h.txnHash, explorerUrl: Rn( h == null ? void 0 : h.txnHash, c ), chainId: c, state: (h == null ? void 0 : h.status) === "SUCCEEDED" ? "confirmed" : "failed" }, A(b), !E) { await new Promise((I) => setTimeout(I, 2e3)); const i = w.metaTxns[1]; console.log("metaTx2", i); const m = await ae(S, i, [ w.preconditions[1] ]); for (console.log("opHash2", m); ; ) { console.log( "polling status", i.id, BigInt(i.chainId) ); const I = await ie( S, i.id, Number(i.chainId) ); if (console.log("receipt", I), I != null && I.transactionHash) { g = (Un = I.data) == null ? void 0 : Un.receipt; break; } await new Promise((O) => setTimeout(O, 1e3)); } b[2] = { transactionHash: g == null ? void 0 : g.txnHash, explorerUrl: Rn( g == null ? void 0 : g.txnHash, G ), chainId: G, state: (g == null ? void 0 : g.status) === "SUCCEEDED" ? "confirmed" : "failed" }, A(b); } return { originUserTxReceipt: y, originMetaTxnReceipt: h, destinationMetaTxnReceipt: g }; } }; } function Rn(z, o) { var c, hn; const r = Object.values(Me); for (const G of r) if (G.id === o) return `${(hn = (c = G.blockExplorers) == null ? void 0 : c.default) == null ? void 0 : hn.url}/tx/${z}`; return ""; } async function jn(z, o) { try { let r = await z.getChainId(); if (r === o) { console.log("Chain already switched to:", o); return; } if (console.log( "Switching to chain:", o, "currentChainId", r ), await z.switchChain({ id: o }), r = await z.getChainId(), r !== o) throw new Error("Failed to switch chain"); console.log("Chain switched to:", o); } catch (r) { throw console.error("Chain switch failed:", r), new Error( `Failed to switch chain: ${r instanceof Error ? r.message : "Unknown error"}` ); } } export { Rn as getExplorerUrl, it as prepareSend, st as useAnyPay };