@spicenet-io/spiceflow-ui 4.20.0 → 4.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as k,jsxs as ie}from"react/jsx-runtime";import{useContext as ce,useRef as G,useLayoutEffect as st,useMemo as M,useEffect as L,createContext as le,useCallback as Ee,useState as _}from"react";import{isNativeToken as D,getChainMeta as Ce,getTokensForChain as it,getDelegateContract as ct,ZERO_ADDRESS as lt,getTokenByAddress as dt,DELEGATE_ABI as ut,ERC20_ABI as ft,spicenetEscrowAbi as mt,uniV3SwapRouterAbi as pt,normalizeNativeTokenAddress as Ie,getChainIdsByNetwork as ht}from"@spicenet-io/spiceflow-core";import{useQuery as gt,useMutation as yt}from"@tanstack/react-query";import{isAddress as N,getAddress as de,defineChain as bt,createPublicClient as wt,http as vt,erc20Abi as xt,createWalletClient as $t,custom as Et,formatUnits as V,isHex as Ct,decodeErrorResult as It,hexToString as kt}from"viem";import{useWallets as ke,usePrivy as ue,useActiveWallet as At,getEmbeddedConnectedWallet as Ae,useSign7702Authorization as St,useSignMessage as Bt,useLogin as Tt,useLogout as Rt}from"@privy-io/react-auth";import{useAccount as Se}from"wagmi";import{readContract as Pt}from"viem/actions";function O(t,e){return!t||!e?!1:D(t)&&D(e)?!0:N(t)&&N(e)?de(t)===de(e):t.toLowerCase()===e.toLowerCase()}const Ft="0xcA11bde05977b3631167028862bE2a173976CA11",Ut={4114:"0x860aFc632a6D625B95d8B96f39ECC48E988c6962"},Nt=new Set([5115]);function Wt(t){const e=Ut[t.id]??(Nt.has(t.id)?void 0:Ft);return bt({id:t.id,name:t.name,nativeCurrency:t.nativeCurrency,rpcUrls:{default:{http:[t.rpcUrl]}},blockExplorers:{default:{name:t.displayName,url:t.blockExplorer}},testnet:t.network==="testnet",...e?{contracts:{multicall3:{address:e}}}:{}})}const Lt=[1,8453,42161,4114,4663,56,137,143,11155111,421614,84532,5115,123420001114,688688,688689,46630],Y=Object.fromEntries(Lt.map(t=>Ce(t)).filter(t=>t!=null).map(t=>[t.id,{...t,viemChain:Wt(t),supportedTokens:it(t.id)}])),Ot=Y;let Be={};const fe=new Map,Te=t=>{Be={...t||{}},fe.clear()},K=(t,e=Be)=>{const r=e[t];return r&&typeof r=="string"&&r.length>0?r:Y[t]?.rpcUrl||void 0},q=t=>Y[t],Q=t=>{const e=Ce(t);return e?.displayName||e?.name||`Chain ${t}`},qt=t=>{const e=ct(t);if(!e)throw new Error(`Unsupported chain ID: ${t}`);if(e.toLowerCase()==="0xd4c4a222cdd42f5c3219249a083a5abf1420e9d8")throw new Error(`Delegation is unavailable for chain ID: ${t}`);return e},Mt=(t,e,r)=>{const n=q(t);return n?.blockExplorer?`${n.blockExplorer}/tx/${e}`:"#"};async function Dt(t,e){const r=`0x${e.toString(16)}`;try{await t.request({method:"wallet_switchEthereumChain",params:[{chainId:r}]});return}catch(a){if(!(a?.code===4902||typeof a?.message=="string"&&a.message.includes("Unrecognized chain ID")))throw a}const n=q(e);if(!n)throw new Error(`Cannot add unknown chain ${e} to wallet`);const o=K(e);if(!o)throw new Error(`Configure SpiceFlowProvider rpcOverrides[${e}] before adding this chain.`);await t.request({method:"wallet_addEthereumChain",params:[{chainId:r,chainName:n.name||`Chain ${e}`,nativeCurrency:n.nativeCurrency||{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:[o],blockExplorerUrls:n.blockExplorer?[n.blockExplorer]:void 0}]})}const Re=(t,e)=>{const r=q(t);if(!r)throw new Error(`Unsupported chain ID: ${t}`);const n=K(t,e);if(!n)throw new Error(`No RPC URL configured for chain ID: ${t}`);const o=`${t}:${n}`,a=fe.get(o);if(a)return a;const s=wt({chain:r.viemChain,transport:vt(n,{timeout:15e3,retryCount:2,retryDelay:300}),batch:{multicall:{wait:16}}});return fe.set(o,s),s},jt=t=>{const e={};return Object.values(Y).forEach(r=>{const n=K(r.id,t);n&&(e[r.id]={name:r.name,chain:r.viemChain,rpcUrl:n})}),e},_t=(t,e=[])=>{const r=q(t);if(!r)return[];const n=[];if(![11155111,421614,688689].includes(t)){const a=e.find(s=>s.chainId===t&&s.isNative);a?n.push(a):n.push({address:lt,name:r.nativeCurrency.name,symbol:r.nativeCurrency.symbol,decimals:r.nativeCurrency.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:void 0,isNative:!0,chainId:t})}if(!r.supportedTokens)return n;const o=n.some(a=>a.isNative);return r.supportedTokens.forEach(a=>{if(o&&D(a.address))return;const s=e.find(d=>d.chainId===t&&O(d.address,a.address));s?n.push(s):n.push({address:a.address,name:a.name,symbol:a.symbol,decimals:a.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:a.logo,isNative:!1,chainId:t})}),n},zt=async(t,e,r)=>{const n=q(t);if(!n)throw new Error(`Unsupported chain ID: ${t}`);const o=e.toLowerCase(),a=n.supportedTokens?.find(d=>O(d.address,o));let s;if(D(o)){if(n.nativeCurrency?.decimals==null)throw new Error(`Native currency decimals not configured for chain ${t}`);s=n.nativeCurrency.decimals}else if(a)s=a.decimals;else{if(!N(e,{strict:!1}))throw new Error(`Could not determine decimals for invalid token address: ${e}`);const d=Re(t,r);try{s=await Pt(d,{address:de(e),abi:xt,functionName:"decimals"})}catch(c){throw Object.assign(new Error(`Could not determine decimals for token ${e} on chain ${t}. Check the token contract and RPC configuration, then try again.`),{cause:c})}}if(!Number.isInteger(s)||s<0||s>255)throw new Error(`Invalid token decimals for ${e} on chain ${t}. Expected an integer from 0 to 255.`);return s},Jt=t=>{const e=t?.wallet;if(e?.address&&e.walletClientType==="privy"&&e.connectorType==="embedded"&&!e.imported)return e.address},Pe=async(t,e)=>{if(!t?.address)throw new Error("Wallet not available");if(typeof t.getWalletClient=="function"){const r=e===void 0?[void 0]:[String(e),e,void 0];let n=null;for(const o of r)try{const a=await t.getWalletClient(o);if(a)return a}catch(a){n=a}if(n)throw n}if(typeof t.getEthereumProvider=="function"){const r=await t.getEthereumProvider(),n=e?q(e)?.viemChain:void 0;return $t({account:t.address,chain:n,transport:Et(r)})}throw new Error("Wallet client not available")},Ht=async(t,e)=>{if(!t?.address)throw new Error("Wallet not available");if(typeof t.getEthereumProvider=="function")return t.getEthereumProvider();const r=await Pe(t,e);return{request:n=>r.request(n)}},me=t=>!t?.address||!N(t.address)?null:{address:t.address,wallet:t,getWalletClient:e=>Pe(t,e),getEthereumProvider:e=>Ht(t,e)},pe=()=>{const t=Se(),e=t.address,r=t.connector;let n=null,o=null,a=null;try{n=ke(),o=ue(),{wallet:a}=At()}catch{n=null,o=null,a=null}const s=n?.wallets||[],d=Ae(s),c=d?.address||Jt(o?.user),i=n?.ready&&o?.ready?s.filter(b=>N(b.address||"")&&b.type!=="solana"&&b.connectorType!=="embedded"&&!O(b.address,c)&&(typeof b.getEthereumProvider=="function"||typeof b.getWalletClient=="function")):[],l=a?.connectorType!=="embedded"&&a?.address?i.find(b=>O(b.address,a.address)):void 0,m=O(e,c),f=t.status==="connected"&&e&&N(e)&&typeof r?.getProvider=="function"?{address:e,connector:r,chainId:t.chainId,getEthereumProvider:()=>r.getProvider()}:null,p=!!e&&!m&&["connected","connecting","reconnecting"].includes(t.status),w=p?f||i.find(b=>O(b.address,e)):null,u=me(d),y=me(p?w:l),v=u?.address||c,g=me(f)||y;return{embeddedWallet:u,externalWallet:y,embeddedAddress:v,externalAddress:y?.address,activeWallet:g,activeAddress:g?.address}},Gt={base:0,raised:1,sticky:10,overlay:20,popover:40,modal:1e3,dropdown:1100,toast:1200,tooltip:1300},Vt={none:"0",sm:"4px",md:"6px",card:"8px",input:"10px",shell:"9px",modal:"12px",pill:"9999px",circle:"50%"},P={out:"cubic-bezier(0.22, 1, 0.36, 1)",inOut:"cubic-bezier(0.65, 0, 0.35, 1)",linear:"linear"},F={fast:"120ms",normal:"150ms",slow:"300ms",progress:"400ms"},Yt={interactive:`transform ${F.normal} ${P.out}, box-shadow ${F.normal} ${P.out}, background-color ${F.normal} ${P.out}, border-color ${F.normal} ${P.out}, color ${F.normal} ${P.out}`,color:`background-color ${F.normal} ${P.out}, border-color ${F.normal} ${P.out}, color ${F.normal} ${P.out}`,popover:`opacity ${F.normal} ${P.out}, transform ${F.normal} ${P.out}`},X={ui:'"Helvetica Neue", sans-serif',mono:'"IBM Plex Mono", monospace'};class $ extends Error{constructor(e,r,n={}){super(r),this.code=e,this.context=n,this.name="SpiceflowError",Error.captureStackTrace&&Error.captureStackTrace(this,$)}}function he(t){return t instanceof $}const Kt=["user rejected","user denied","user cancelled","rejected the request","action_rejected","4001"];function Fe(t){if(!t)return"";if(typeof t=="string")return t;const e=t,r=e.message||e.reason||"",n=e.details||"";return`${r} ${n}`.trim()}const Ue=t=>{if(he(t))return t.code==="WALLET_REJECTED";const e=Fe(t).toLowerCase();return Kt.some(r=>e.includes(r))};let ge=null;function Qt(t){return ge?.message===t?ge.detail:void 0}const Xt=(t,e="Something went wrong. Please try again.")=>{if(Ue(t))return"Transaction was rejected.";if(he(t)){const r=t.message||e,{requestId:n,httpStatus:o,responseBody:a,endpoint:s}=t.context;return(n||o||s)&&(ge={message:r,detail:{requestId:n,httpStatus:o,responseBody:a,endpoint:s}}),r}return Fe(t)||e},Zt=[...ut,...ft,...mt,...pt];function ye(t,e=0){return e>4||t==null?[]:typeof t=="string"?t.match(/0x[0-9a-fA-F]{8,}/g)??[]:Array.isArray(t)?t.flatMap(r=>ye(r,e+1)):typeof t=="object"?Object.values(t).flatMap(r=>ye(r,e+1)):[]}function Ne(t){try{const e=It({abi:Zt,data:t});if(e.errorName==="Error")return String(e.args?.[0]??"");if(e.errorName==="Panic")return`Panic(${e.args?.[0]})`;if(e.errorName==="CallReverted"){const r=e.args?.[4],n=r&&r!=="0x"?Ne(r):void 0;return n?`Call reverted: ${n}`:"Call reverted (no reason returned)"}return e.errorName}catch{try{const e=kt(t).replace(/\x00+$/g,"").trim();return/^[\x20-\x7e]+$/.test(e)&&e.length>1?e:void 0}catch{return}}}function er(t){for(const e of ye(t)){if(!Ct(e))continue;const r=Ne(e);if(r)return r}}function We(t,e){const r=e.match(/Output amount (\d+) is insufficient after fees (\d+) on chain (\d+)/);if(!r)return e;const[,n,o,a]=r,s=Number(a),d=BigInt(n),c=BigInt(o);let i;for(const v of t.intents){const g=v.chainBatches.find(b=>b.chainId===s);if(g){i=g;break}}const l=i?.tokenTransfers.find(v=>v.from==="escrow"&&O(v.to,t.user)&&!D(v.token)),m=Q(s);if(!l)return`Amount is too small to cover the estimated fee on ${m}.`;const f=dt(l.token,s),p=f?.decimals??18,w=f?.symbol??"tokens",u=V(d,p),y=V(c,p);return`Amount is too small to cover the estimated fee on ${m}. Amount: ${u} ${w}. Estimated fee: ${y} ${w}.`}function tr(t){return t?.code===4902||t?.name==="ChainNotConfiguredError"?"This network is not configured in your wallet. Please add it manually to continue.":t?.code===4001?"Network switch cancelled. Please switch manually in your wallet to continue.":"Unable to switch network. Please switch manually in your wallet to continue."}const rr="https://tx-submission-api.spicenet.io",Le=rr;function nr(t,e){return typeof e=="bigint"?e.toString():e}function j(t,e=""){if(Array.isArray(t))t.forEach((r,n)=>j(r,`${e}[${n}]`));else if(t&&typeof t=="object")for(const[r,n]of Object.entries(t)){const o=e?`${e}.${r}`:r;if(!n&&(r==="user"||r==="to"||r==="from"||r==="address"))throw new $("INVALID_PARAMS",`Wallet not ready: ${o} is missing from the request. Wait a moment and retry, or log in again.`,{path:o});j(n,o)}}function Oe(t){return typeof t.actionId=="string"&&t.actionId.length>0&&Array.isArray(t.intentIds)&&t.intentIds.length>0&&t.intentIds.every((e,r)=>typeof e=="string"&&e===`${t.actionId}/${r}`)&&(t.autoContinue===void 0||typeof t.autoContinue=="boolean")}async function Z(t,e){const r={...e?.headers},n=(e?.method??"GET").toUpperCase();(e?.body!=null||n!=="GET"&&n!=="HEAD")&&(r["x-request-id"]??(r["x-request-id"]=crypto.randomUUID()));const o=await fetch(t,{...e,headers:r}),a=o.headers.get("x-request-id")??"";return Object.assign(o,{requestId:a})}function z(t,e){if(!t)return e;const r=t.error,n=(typeof t.message=="string"?t.message:"")||(r&&typeof r=="object"&&"message"in r&&typeof r.message=="string"?r.message:"")||(typeof r=="string"?r:"")||e,o=er(t);return o&&!n.includes(o)?`${n} \u2014 ${o}`:n}async function ar(t){try{return await t.json()}catch{return null}}function or(t){return(Array.isArray(t?.balances)?t.balances:[]).flatMap(e=>{if(!e||typeof e!="object")return[];const r=e;return[{receiptToken:typeof r.receiptToken=="string"?r.receiptToken:void 0,tokenName:String(r.tokenName??""),balanceAvailable:String(r.balanceAvailable??"0"),chainTokens:Array.isArray(r.chainTokens)?r.chainTokens.filter(n=>typeof n=="string"):r.chainTokens&&typeof r.chainTokens=="object"?r.chainTokens:r.chainTokenConfig&&typeof r.chainTokenConfig=="object"?r.chainTokenConfig:void 0,decimals:typeof r.decimals=="number"?r.decimals:void 0,balanceUsd:typeof r.balanceUsd=="number"||typeof r.balanceUsd=="string"?r.balanceUsd:null}]})}class ae{constructor(){this.baseUrl=Le,this.feeValidationAvailable=!1}setBaseUrl(e){e!==this.baseUrl&&(this.feeValidationAvailable=!1),this.baseUrl=e}getBaseUrl(){return this.baseUrl}async requestJson(e,r){const n=`${this.baseUrl}${e}`,o=await Z(n,r.method&&r.method!=="GET"?{method:r.method,headers:{"Content-Type":"application/json",...r.headers},body:JSON.stringify(r.body,nr),signal:r.signal}:{headers:r.headers,signal:r.signal}),a=await o.text();let s;try{s=JSON.parse(a)}catch{s=null}if(!o.ok||!s||s.success===!1||r.ok&&!r.ok(s)){const d=z(s,r.fallbackError(o.status));throw new $(r.code??"RELAYER_ERROR",r.mapError?r.mapError(d):d,{httpStatus:o.status,requestId:o.requestId,responseBody:a,endpoint:e,...r.context})}return s}async createLimitOrder(e){try{return await this.requestJson("/orders",{method:"POST",body:e,fallbackError:r=>`Order registration failed: ${r}`})}catch(r){if(r instanceof $&&r.context.httpStatus===400)try{JSON.parse(String(r.context.responseBody??"{}"))?.submissionStatus==="rejected"&&(r.context.submissionStatus="rejected")}catch{}throw r}}async registerConditionalIntent(e){return this.requestJson("/conditional-intents",{method:"POST",body:e,fallbackError:r=>`Conditional intent registration failed: ${r}`})}async createConditionalReadToken(e){return this.requestJson("/conditional-intents/read-token",{method:"POST",body:e,fallbackError:r=>`Conditional intent read authorization failed: ${r}`})}async getConditionalIntent(e,r){return this.requestJson(`/conditional-intents/${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${r}`},fallbackError:n=>`Conditional intent status failed: ${n}`})}async listConditionalIntents(e,r){const n=new URLSearchParams({...r?.limit?{limit:String(r.limit)}:{},...r?.cursor?{cursor:r.cursor}:{}}).toString();return this.requestJson(`/conditional-intents${n?`?${n}`:""}`,{headers:{Authorization:`Bearer ${e}`},fallbackError:o=>`Conditional intent listing failed: ${o}`})}async cancelConditionalIntent(e,r){return this.requestJson(`/conditional-intents/${encodeURIComponent(e)}/cancel`,{method:"POST",body:r,fallbackError:n=>`Conditional intent cancellation failed: ${n}`})}async getLimitOrder(e){return this.requestJson(`/orders/${encodeURIComponent(e)}`,{fallbackError:r=>`Order lookup failed: ${r}`})}async listLimitOrders(e,r){const n=new URLSearchParams({user:e,...r?{after:r}:{}});return this.requestJson(`/orders?${n}`,{fallbackError:o=>`Order listing failed: ${o}`})}async cancelLimitOrder(e,r){return this.requestJson(`/orders/${encodeURIComponent(e)}/cancel`,{method:"POST",body:{signature:r},fallbackError:n=>`Order cancellation failed: ${n}`})}async supportsAutomaticContinuation(e){try{return(await this.requestJson("/actions/capabilities",{signal:e?.signal,fallbackError:r=>`Action capabilities unavailable: ${r}`})).automaticContinuation===!0}catch(r){if(r instanceof $&&r.context.httpStatus===404)return!1;throw r}}async createAction(e,r){if(j(e),r?.idempotencyKey!==void 0&&e.idempotencyKey!==void 0&&r.idempotencyKey.toLowerCase()!==e.idempotencyKey.toLowerCase())throw new $("INVALID_PARAMS","Action idempotency keys must identify the same original submission.");const n=this.baseUrl,o=new ae;o.setBaseUrl(n);const a=r?.idempotencyKey??e.idempotencyKey??`0x${Array.from(crypto.getRandomValues(new Uint8Array(32)),i=>i.toString(16).padStart(2,"0")).join("")}`;if(!/^0x[0-9a-f]{64}$/i.test(a))throw new $("INVALID_PARAMS","Action idempotency key must be exactly 32 bytes.");const s=r?.autoContinue??e.autoContinue,d={...e,idempotencyKey:a,...s!==void 0?{autoContinue:s}:{}},c=i=>{try{r?.onAccepted?.(i)}catch(l){console.warn("[relayer] accepted-action progress callback failed",l)}};try{const i=await o.requestJson("/actions",{method:"POST",body:d,signal:r?.signal,fallbackError:l=>`Relayer API error: ${l}`,ok:Oe});return c(i),i}catch(i){const l=i instanceof $?i.context:{};let m=l.httpStatus===401||l.httpStatus===403;if(l.httpStatus===400)try{m=JSON.parse(String(l.responseBody??"{}"))?.submissionStatus==="rejected"}catch{}for(let f=0;f<3;f++){f&&await new Promise(w=>setTimeout(w,1e3));let p;try{p=await o.getActionBySubmission(e.user,a)}catch{continue}if(p)return c(p),p;if(m&&i instanceof $)throw new $(i.code,i.message,{...l,idempotencyKey:a,user:e.user,submissionStatus:"rejected"})}throw new $("RELAYER_ERROR","The submission outcome is unknown. Check your activity and balances before submitting again.",{...l,idempotencyKey:a,user:e.user,submissionStatus:"unknown",cause:i})}}async getWalletActions(e,r){const n=r&&"aborted"in r?{signal:r}:r,o=n?.pendingOnly?"?pendingOnly=true":"",a=await this.requestJson(`/wallets/${encodeURIComponent(e)}/actions${o}`,{signal:n?.signal,fallbackError:c=>`Action status unavailable: ${c}`}),s=c=>{throw new $("RELAYER_ERROR","Action status response is invalid.",{endpoint:`/wallets/${encodeURIComponent(e)}/actions`,reason:c})},d=e.toLowerCase();return/^0x[0-9a-f]{40}$/i.test(e)||s("requested wallet is malformed"),(!Array.isArray(a.actions)||a.actions.length>100)&&s("actions must be a bounded array"),a.actions.map(c=>{if(!c||typeof c!="object")return s("action record is malformed");const i=c,l=i.user;if(typeof l!="string"||!/^0x[0-9a-f]{40}$/i.test(l)||l.toLowerCase()!==d)return s("action owner does not match the requested wallet");if(i.autoContinue!==!0)return s("action is not owned by automatic continuation");if(typeof i.actionId!="string"||i.actionId.length===0||i.actionId.length>200||i.actionId.includes("/")||typeof i.createdAt!="string"||typeof i.status!="string"||!Array.isArray(i.intents)||i.intents.length===0||i.intents.length>100)return s("action identity or intents are malformed");const m=i.intents.map((f,p)=>{if(!f||typeof f!="object")return s("intent record is malformed");const w=f;if(w.intentId!==`${i.actionId}/${p}`||typeof w.status!="string"||!Array.isArray(w.steps)||w.steps.length>100)return s("intent identity or steps are malformed");const u=w.steps.map((y,v)=>{if(!y||typeof y!="object")return s("step record is malformed");const g=y,b=typeof g.chainId=="number"?g.chainId:typeof g.chainId=="string"&&/^[1-9]\d*$/.test(g.chainId)?Number(g.chainId):NaN;return g.index!==v||!Number.isSafeInteger(b)||b<=0||typeof g.status!="string"||g.transactionHash!==null&&typeof g.transactionHash!="string"?s("step identity or state is malformed"):{...g,index:v,chainId:b,status:g.status,transactionHash:g.transactionHash}});return{...w,intentId:w.intentId,steps:u}});return{...i,user:l,autoContinue:!0,actionId:i.actionId,createdAt:i.createdAt,status:i.status,intents:m}})}async getActionBySubmission(e,r,n){if(!/^0x[0-9a-f]{40}$/i.test(e)||!/^0x[0-9a-f]{64}$/i.test(r))throw new $("INVALID_PARAMS","Submission lookup requires a wallet address and 32-byte key.");try{return await this.requestJson(`/actions/by-submission/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,{signal:n?.signal,fallbackError:o=>`Submission lookup failed: ${o}`,ok:Oe})}catch(o){if(o instanceof $&&o.context.httpStatus===404)return null;throw o}}async getIntentRecoveryStatus(e,r,n){if(!e||!Number.isSafeInteger(r)||r<0)throw new $("INVALID_PARAMS","Action recovery requires an action ID and non-negative intent index.");const o=await this.requestJson(`/actions/${encodeURIComponent(e)}/intents/${r}/recovery`,{signal:n?.signal,fallbackError:a=>`Action recovery check failed: ${a}`});if(o.status!=="completed"&&o.status!=="cancelled"&&o.status!=="unresolved")throw new $("RELAYER_ERROR","The relayer returned an unknown recovery status.",{actionId:e,intentIndex:r,recoveryStatus:o.status});return o.status}async getActionRecovery(e,r,n){return this.getIntentRecoveryStatus(e,r,n)}async estimateActionFees(e,r){j(e);const n=this.baseUrl,o=await this.requestJson("/actions/fees/estimate",{method:"POST",body:e,signal:r?.signal,fallbackError:a=>`Relayer fee estimate error: ${a}`,ok:a=>!!a.success&&!!a.data?.feeEstimate,mapError:a=>We(e,a)});return n===this.baseUrl&&(this.feeValidationAvailable=o.data?.supportsFeeValidation===!0),o.data.feeEstimate}canValidateActionFees(){return this.feeValidationAvailable}async validateActionFees(e,r){return j(e),(await this.requestJson("/actions/fees/validate",{method:"POST",body:e,signal:r?.signal,fallbackError:n=>`Relayer fee validation error: ${n}`,ok:n=>!!n.success&&!!n.data?.feeEstimate,mapError:n=>We(e,n)})).data.feeEstimate}async estimateBatchGas(e){j(e);const{signal:r,...n}=e,o=await this.requestJson("/actions/gas/estimate",{method:"POST",body:n,signal:r,fallbackError:a=>`Relayer gas estimate error: ${a}`,ok:a=>!!a.success&&!!a.data?.gasFee});return{...o.data.policy?{policy:o.data.policy}:{},gasFee:BigInt(o.data.gasFee),gasQuoteSource:o.data.gasQuoteSource,simulationVerified:o.data.simulationVerified===!0,platformFee:o.data.platformFee===void 0?void 0:BigInt(o.data.platformFee)}}async executeStep(e,r,n,o){const a=`${this.baseUrl}/actions/${e}/intents/${r}/steps/${n}`,s=`/actions/${e}/intents/${r}/steps/${n}`,d=crypto.randomUUID(),c=3e4,i=new Promise((f,p)=>setTimeout(()=>p(new $("RELAYER_EXECUTE_ERROR",`Execute step request timed out after ${c/1e3}s`,{actionId:e,intentIndex:r,stepIndex:n,endpoint:s,requestId:d})),c)),l=await Promise.race([Z(a,{method:"POST",headers:{"Content-Type":"application/json","x-request-id":d},body:JSON.stringify(o)}),i]),m=await l.json();if(!l.ok||m.success===!1)throw new $("RELAYER_EXECUTE_ERROR",z(m,`Execute step error: ${l.status}`),{httpStatus:l.status,requestId:l.requestId,responseBody:JSON.stringify(m),endpoint:s,actionId:e});if(m?.status==="error"||m?.status==="reverted"){const f=z(m,""),p=f?`: ${f}`:"";throw new $("RELAYER_EXECUTE_ERROR",`Step ${n} previously ${m.status}${p}`,{httpStatus:l.status,requestId:l.requestId,responseBody:JSON.stringify(m),endpoint:s,actionId:e,intentIndex:r,stepIndex:n,stepStatus:m.status})}return{success:!0,status:m.status,transactionHash:m.transactionHash}}async checkStepStatus(e,r,n=!1){const o=typeof n=="boolean"?n:n.includeExecutionStatus===!0,a=e.split("/"),s=a[0],d=a.length>=2?a[1]:"0",c=await this.requestJson(`/actions/${s}/intents/${d}/steps/${r}${o?"?includeExecutionStatus=true":""}`,{signal:typeof n=="boolean"?void 0:n.signal,fallbackError:i=>`Intent step status check failed: ${i}`,code:"RELAYER_STATUS_ERROR",context:{intentId:e}});return{success:!0,data:{status:c.status==="error"?"reverted":c.status,transactionHash:c.txid,error:z(c,""),...c.executionStatus==="success"||c.executionStatus==="reverted"?{executionStatus:c.executionStatus}:{}}}}async createWallet(e,r){return this.requestJson(`/wallets/${e}`,{method:"PUT",body:r,fallbackError:n=>`Create wallet error: ${n}`})}async getWallet(e){return this.requestJson(`/wallets/${e}`,{fallbackError:r=>`Get wallet error: ${r}`})}async createWithdrawal(e){return this.requestJson("/withdrawals",{method:"POST",body:e,fallbackError:r=>`Create withdrawal error: ${r}`})}async getWithdrawal(e){return this.requestJson(`/withdrawals/${e}`,{fallbackError:r=>`Get withdrawal error: ${r}`})}async getRollupTimestamp(){return this.requestJson("/time",{fallbackError:e=>`Get rollup timestamp error: ${e}`})}}const U=new ae;async function sr(t){const e=`${U.getBaseUrl()}/wallets/${t}/balance`,r=await Z(e,{cache:"no-store"}),n=await ar(r);if(!r.ok||n?.success===!1)throw new $("RELAYER_ERROR",z(n,`Unable to verify Spice balance: ${r.status}`),{httpStatus:r.status,requestId:r.requestId,responseBody:JSON.stringify(n),endpoint:`/wallets/${t}/balance`});return or(n)}const be=new Map,ee=new Set;function we(t){return JSON.stringify([U.getBaseUrl(),t.toLowerCase()])}function J(t,e){if(we(t)!==e)throw new Error("Wallet backend changed during registration. Please retry.")}function ir(t){if(!(t instanceof $))return!1;const e=t.context.httpStatus;return e===400||e===404?`${t.message} ${String(t.context.responseBody??"")}`.toLowerCase().includes("not found"):!1}async function qe(t){const e=we(t);if(ee.has(e))return!0;try{return await U.getWallet(t),J(t,e),ee.add(e),!0}catch(r){if(!ir(r))throw r;return!1}}async function Me(t,e){const r=we(t);if(ee.has(r))return;const n=be.get(r);if(n)return n;const o=(async()=>{const a=await qe(t);if(J(t,r),a)return;const{unix_timestamp:s}=await U.getRollupTimestamp();J(t,r);const d=`I am creating a new smart wallet and adding an admin wallet ethereum:0x${t.slice(2).toLowerCase()}. Nonce: ${s}`,c=await e(d);J(t,r);const i=typeof c=="string"?c:c.signature;if(!i)throw new Error("Wallet returned no smart wallet signature");await U.createWallet(t,{timestamp:s,signature:i}),J(t,r),ee.add(r)})();be.set(r,o);try{await o}finally{be.delete(r)}}const cr=(t,e)=>{const r=o=>e?e(o):Q(o),n=[];return t.forEach((o,a)=>{const s=o.calls&&o.calls.length>0,d=o.tokenTransfers&&o.tokenTransfers.length>0;!s&&!d||n.push({stepId:a,status:a===0?"processing":"pending",chainId:o.chainId,chainName:r(o.chainId),description:"Processing transaction"})}),n},De=()=>{const t=ce(re),e=t?.mode,{isConnected:r,address:n}=Se();let o=null,a=null,s=null,d=null,c=null;try{o=ue(),a=St(),s=Bt(),d=ke()}catch(h){c=h instanceof Error?h.message:String(h)}const{ready:i=!1,authenticated:l=!1}=o||{},m=t?.embeddedWalletAddress,f=Ae(d?.wallets||[]),p=m||f?.address,w=e==="ondemand"&&r?n:p,u=t?.apiUrl||U.getBaseUrl(),y=JSON.stringify([e,t?.provider,t?.network,t?.apiUrl,u,w?.toLowerCase(),p?.toLowerCase(),f?.address?.toLowerCase(),o?.user?.id??null,i,l,d?.ready,e==="ondemand"&&r,c]),v=G({key:y});v.current.key!==y&&(v.current={key:y});const g=v.current,b=G({mounted:!1});st(()=>{const h={mounted:!0};return b.current=h,()=>{h.mounted=!1}},[]);const A=()=>{const h=b.current,C=()=>{if(!h.mounted||v.current!==g||U.getBaseUrl()!==u)throw new Error("Wallet session changed before signing. Please review the action again.")};return C(),C};if(c)return e==="ondemand"&&r&&n?{isReady:!0,isAuthenticated:!0,isConnected:!0,address:n,provider:"privy",actions:{signAuthorization:async()=>{throw new Error("Not available in ondemand mode")},signMessage:async()=>{throw new Error("Not available in ondemand mode")},getEthereumProvider:async()=>{throw new Error("Not available in ondemand mode")}}}:{isReady:!1,isAuthenticated:!1,isConnected:!1,provider:null,actions:{signAuthorization:async()=>{throw new Error("Privy not available")},signMessage:async()=>{throw new Error("Privy not available")},getEthereumProvider:async()=>{throw new Error("Privy not available")}}};const B=!!p&&!!f,W={isReady:e==="ondemand"?!0:i,isAuthenticated:e==="ondemand"?!0:l||B,isConnected:e==="ondemand"?r&&!!n||i&&(l||B)&&B:i&&B,address:w,provider:"privy"},E=async(h,C,x=A())=>{if(x(),!f)throw new Error("Embedded wallet not available");const I=await f.getEthereumProvider();x();const{createWalletClient:R,custom:oe}=await import("viem");x();const se=R({account:f.address,transport:oe(I)});C?.(),x();const ot=await se.signMessage({account:f.address,message:h});return x(),{signature:ot}},T=async(h,C=A())=>{if(C(),s)try{const x=await s.signMessage({message:h});return C(),{signature:x.signature}}catch(x){if(C(),!f)throw x}if(!f)throw new Error("Privy sign message not available");return E(h,void 0,C)},S=async h=>{if(h(),!p)throw new Error("Embedded wallet not available for smart wallet setup");await Me(p,C=>T(C,h)),h()};return{...W,actions:{prepareSigning:async()=>{const h=A();if(!p)throw new Error("Embedded wallet not available");await qe(p),h()},signAuthorization:async(h,C)=>{const x=A();if(!a)throw new Error("Privy sign authorization not available");try{await S(x),C?.(),x();const I=await a.signAuthorization({contractAddress:h.contractAddress,chainId:h.chainId,nonce:h.nonce},{address:p});return x(),delete I.v,I}catch(I){const R=typeof I?.message=="string"?I.message:String(I?.message??I??"");throw R.includes("not configured")||R.includes("chain")?new Error(`Chain ${h.chainId} is not configured in PrivyProvider. Add this chain to your Privy dashboard or supportedChainIds.`):I}},signMessage:async(h,C)=>{const x=A();if(typeof h=="object"&&"raw"in h){if(await S(x),!f)throw new Error("Embedded wallet not available for raw signing");return E(h,C,x)}return C?.(),T(h,x)},getEthereumProvider:async()=>{if(!f)throw new Error("Embedded wallet not available");return f.getEthereumProvider()}}}},lr="https://portal-api.spicenet.io/api/v1",ve=t=>t.replace(/\/+$/,""),dr=(t,e)=>`${t}:${e}`;async function ur(t,e){const r=new URLSearchParams({walletAddress:e,campaignId:"spicenet-portal",campaignGroup:"1"}),n=await fetch(`${t}/portal/mainnet/linked-portal-wallet?${r.toString()}`,{cache:"no-store"});if(!n.ok){if(n.status>=500){const o=new Error(`Failed to resolve linked portal wallet: ${n.status}`);throw o.status=n.status,o}return null}return(await n.json()).portalWalletAddress?.toLowerCase()??null}async function fr(t,e,r){const n=new URLSearchParams({walletAddress:e,campaignId:r.campaignId,campaignGroup:r.campaignGroup,partnerId:r.partnerId}),o=await fetch(`${t}/portal/mainnet/whitelist/check?${n.toString()}`,{cache:"no-store"});if(!o.ok){const a=new Error(`Failed to check whitelist: ${o.status}`);throw a.status=o.status,a}return await o.json()}async function mr(t,e,r,n){const o=await fetch(`${t}/portal/mainnet/link-wallet`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({campaignId:e.campaignId,campaignGroup:e.campaignGroup,partnerId:e.partnerId,externalWalletAddress:r,embeddedWalletAddress:n})});if(!o.ok)throw new Error(`Failed to link wallet: ${o.status}`)}function je({walletAddress:t,campaignId:e,campaignGroup:r,partnerId:n,apiBaseUrl:o=lr,enabled:a=!0,staleTime:s=5*60*1e3,refetchInterval:d=!1}={}){const{isAuthenticated:c,isConnected:i}=De(),{externalAddress:l,embeddedAddress:m}=pe(),f=t??l,p=typeof f=="string"?f.toLowerCase():void 0,w=typeof m=="string"?m.toLowerCase():void 0,u=typeof l=="string"?l.toLowerCase():void 0,y=a&&c&&i&&!!l&&!!p&&N(p)&&!!e&&!!r&&!!n,v=M(()=>["partner-whitelist","check",p,e,r,n,ve(o)],[p,e,r,n,o]),g=gt({queryKey:v,enabled:y,staleTime:s,refetchInterval:d,retry:(E,T)=>{const S=T?.status;return typeof S=="number"&&S>=400&&S<500?!1:E<3},retryDelay:E=>Math.min(1e3*2**E,15e3),queryFn:async()=>{if(!p||!N(p))throw new Error("A valid wallet address is required");if(!e||!r||!n)throw new Error("campaignId, campaignGroup, and partnerId are required");const E=ve(o),T={campaignId:e,campaignGroup:r,partnerId:n},S=await ur(E,p);return S?fr(E,S,T):{walletAddress:p,campaignId:e,campaignGroup:r,partnerId:n,isWhitelisted:!1,isLinkedWallet:!1,whitelistedWalletAddress:null,externalWalletAddress:p}}}),b=a&&c&&i&&!!u&&N(u)&&!!w&&N(w)&&!!e&&!!r&&!!n,A=yt({mutationFn:E=>mr(ve(o),{campaignId:e,campaignGroup:r,partnerId:n},E.external,E.embedded)}),B=G(new Set),W=A.mutate;return L(()=>{if(!b||!u||!w||!e||!r||!n)return;const E=dr(u,w);B.current.has(E)||(B.current.add(E),W({external:u,embedded:w}))},[b,u,w,e,r,n,W]),{isWhitelisted:g.data?.isWhitelisted??!1,whitelistCheck:g.data,checkedWalletAddress:p,externalWalletAddress:l,embeddedWalletAddress:m,isExternalWalletConnected:!!l,isWhitelistCheckEnabled:y,linkWallet:A,isWalletLinked:A.isSuccess,...g}}const _e={assets:[],loading:!1,refreshing:!1,error:null,updatedAt:null};function ze(){const t=new Map,e=new Map,r=new WeakMap;let n=0;function o(){let a=_e;const s=new Map;let d,c=null,i=0,l=!1,m;const f=()=>s.forEach((u,y)=>y()),p=()=>{if(!m||!s.size)return Promise.resolve();if(c)return c;const u=++i;return a={...a,loading:a.updatedAt===null,refreshing:!0},f(),c=Promise.resolve().then(m).then(y=>{if(u!==i)return;const{assets:v,error:g=null}=Array.isArray(y)?{assets:y}:y;a={assets:v,loading:!1,refreshing:!1,error:g,updatedAt:Date.now()}},y=>{u===i&&(a={...a,loading:!1,refreshing:!1,error:y instanceof Error?y.message:"Unable to refresh balances"})}).finally(()=>{u===i&&(c=null,f(),l&&(l=!1,p()))}),c},w=()=>{clearInterval(d);const u=[...s.values()].filter(y=>y>0);u.length&&(d=setInterval(()=>void p(),Math.min(...u)))};return{snapshot:()=>a,refresh:p,invalidate:()=>c?(l=!0,c.then(()=>c??Promise.resolve())):p(),subscribe(u,y,v){return m=y,s.set(u,v),w(),p(),()=>{s.delete(u),w(),s.size||(i++,c=null,l=!1,a={...a,loading:!1,refreshing:!1})}}}}return{entry(a){let s=t.get(a);return s||(s=o(),t.set(a,s)),s},fetcherId(a){return r.has(a)||r.set(a,++n),r.get(a)},registerTokens(a){let s=!1;for(const d of a){const c=`${d.chainId}:${d.address.toLowerCase()}`;e.has(c)||(e.set(c,d),s=!0)}s&&t.forEach(d=>d.invalidate())},tokens:()=>[...e.values()],invalidate:()=>Promise.all([...t.values()].map(a=>a.invalidate())).then(()=>{})}}function Je(t,e){return t<=0n||e<=0n?0n:(t*e+10000n-1n)/10000n}function pr(t,e,r){const n=(t>e?t-e:0n)*10000n/(10000n+r),o=Je(n,r),a=n>0n,s=a?o+e:0n;return{netAmount:n,spicenetFee:a?o:0n,totalFee:s,grossAmount:n+s,coversFees:a}}function hr(t,e,r){if(t===e)return!0;const n=t>e?t:e;return n===0n?!1:(t>e?t-e:e-t)*10000n<=n*r}function xe(t=4e3){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("feeToleranceBps must be an integer between 0 and 10000");return t}function He(t,e,r){const n=BigInt(xe(r));return(t>e?t-e:e-t)*10000n<=t*n}function gr(t,e,r){return["gasFee","spicenetFee","bridgeFee"].every(n=>He(t[n]??0n,e[n]??0n,r))}function yr(t,e){const r=V(t,e);return r.includes(".")?r.replace(/\.?0+$/,"")||"0":r}function te(t){const e=BigInt(t.feeBreakdown.spicenetFee),r=BigInt(t.feeBreakdown.gasFee),n=BigInt(t.feeBreakdown.bridgeFee??"0"),o=e+r+n;return{spicenetFee:e,gasFee:r,bridgeFee:n,totalFee:o}}function br(t){const e=BigInt(t.quotedAmount),r=BigInt(t.totalDebit),{totalFee:n}=te(t);return e>0n||r>0n||n>0n}function wr(t){const e=BigInt(t.quotedAmount),r=BigInt(t.totalDebit),{totalFee:n}=te(t),o=e+n;return r>o?r:o}function vr(t){const e=[];for(const r of t.intents)for(const n of r.batches)e.push(BigInt(n.quotedAmount));return e.length!==1?null:e[0]}function xr(t,e,r){return t.length===0||!t.every(n=>n.domain!=="spicenet"&&!n.tokenTransfers?.length)?null:{...e,grossAmount:r,netAmount:r,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}}function $r(t,e){if(t.policy?.enforcement==="enforce"&&t.assessments?.some(l=>l.status==="unsupported"))throw new Error("This action does not have a supported fee assessment");const r=t.intents.flatMap(l=>l.batches).filter(br);if(r.length===0)return null;const n=r.filter(l=>l.chainId===e.chainId),o=n.length>0?n:r;if(o.length>1)return null;const a=o[0];if(a.paymentToken&&(a.chainId!==e.chainId||a.paymentToken.toLowerCase()!==e.tokenAddress.toLowerCase()))return null;const{gasFee:s,spicenetFee:d,bridgeFee:c,totalFee:i}=te(a);return{chainId:a.chainId,tokenAddress:e.tokenAddress,...t.policy?{feePolicy:t.policy}:{},symbol:e.symbol,decimals:e.decimals,grossAmount:wr(a),netAmount:BigInt(a.quotedAmount),totalFee:i,gasFee:s,spicenetFee:d,bridgeFee:c,gasQuoteSource:a.gasQuoteSource}}const Ge=(t,e=4)=>!isFinite(t)||t===0?"0":t>0&&t<1e-6?t.toFixed(12).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""):t<1e-4?t.toFixed(8).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""):t.toFixed(e).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""),Er=t=>isFinite(t)?t>0&&t<.01?"<$0.01":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(t):"$0.00",Ve=(t,e=6,r=4)=>t.length<=e+r?t:`${t.slice(0,e)}...${t.slice(-r)}`,Cr=(t,e)=>{const r=t.replace(/[^0-9.]/g,"").split("."),n=r[0]??"",o=r.slice(1).join(""),a=typeof e=="number"?Math.max(0,Math.min(e,18)):null;return r.length===1?n:`${n}.${a===null?o:o.slice(0,a)}`},Ir=(t,e=6)=>!Number.isFinite(t)||t<=0?"0":t.toFixed(Math.min(Math.max(e,0),18)).replace(/\.?0+$/,""),kr=async t=>{try{return await navigator.clipboard.writeText(t),!0}catch(e){return console.error("Failed to copy to clipboard:",e),!1}};function Ar(t,e){return e?.length?e.some(r=>{const n=r.toLowerCase();return n===t.symbol.toLowerCase()||Ie(n).toLowerCase()===Ie(t.address).toLowerCase()||n===t.displaySymbol?.toLowerCase()||n===t.receiptTokenName?.toLowerCase()||n==="native"&&(t.isNative||D(t.address))}):!0}function Ye(t){return t.displaySymbol||t.symbol}function Ke(t){return t.displayName||t.displaySymbol||t.name||t.symbol}function Sr(t,e){const r=t.location==="rollup"||t._source==="spice"||!!t.receiptTokenId&&!t.location&&!t._source,n=a=>a&&e?Object.entries(e).find(([s])=>s.toLowerCase()===a.toLowerCase())?.[1]:void 0,o=r?n(t.receiptTokenId)??n(t.receiptTokenName):void 0;return{symbol:o?.symbol||o?.name||Ye(t),name:o?.name||o?.symbol||Ke({...t,name:t.name||""}),logoURI:o?.logoURI===void 0?t.logoURI:o.logoURI||null}}function Br(t){return t.displayChainName||Q(t.chainId)}function Tr(t){if(t.balance===0n)return"0";const e=V(t.balance,t.decimals),r=Ge(Number(e));return Number(r)===0?e:r}const Qe=le(void 0);function Rr(){const t=ce(Qe);return Ee(e=>Sr(e,t),[t])}const Pr=["__spicenet_whitelist_blocked__"],Xe="spiceflow-mode",Ze=()=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Xe);return t==="7702"?"7702":t==="non7702"?"ondemand":t==="embedded"?"7702":t==="external"?"ondemand":null}catch{return null}},Fr=t=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Xe,t==="7702"?"7702":"non7702")}catch{}},Ur=()=>Ze()!==null,et=le(null),re=le(null),Nr=({children:t,value:e,whitelist:r})=>{const n=!!r&&r.enabled!==!1,{isWhitelisted:o,isLoading:a,whitelistCheck:s}=je(n?r:{enabled:!1}),d=n&&!o,c=M(()=>({...e,mode:d?"ondemand":e.mode,allowedTokens:d?Pr:e.allowedTokens,isUserWhitelisted:o,isWhitelistChecking:a,isWhitelistConfigured:n,isWhitelistGateActive:d,whitelistCheck:s}),[e,n,d,o,a,s]);return k(re.Provider,{value:c,children:t})},Wr=({feeToleranceBps:t,children:e,provider:r="privy",supportedChainIds:n,allowedTokens:o,network:a="testnet",mode:s,skipFlow:d=[],nativeChainId:c,appName:i="Spicenet",apiUrl:l,theme:m,rpcOverrides:f,swapper:p,liquidityVenues:w,additionalSourceTokens:u,whitelist:y,assetDisplay:v})=>{const g=xe(t);L(()=>{if(!l)return;const R=U.getBaseUrl();return U.setBaseUrl(l),()=>U.setBaseUrl(R)},[l]),L(()=>(Te(f),()=>Te(void 0)),[f]);const b=M(()=>ht(a),[a]),A=n??b,B=m??null,[W,E]=_(()=>s??Ze()??"7702");L(()=>{s&&E(s)},[s]);const T=Ee(R=>{if(s){E(s);return}E(R),Fr(R)},[s]),{embeddedAddress:S,externalAddress:h}=pe(),C=JSON.stringify(f),x=M(ze,[a,l,C,r]),I=M(()=>({feeToleranceBps:g,inventory:x,provider:r,supportedChainIds:A,allowedTokens:o,skipFlow:d,mode:W,setMode:T,network:a,nativeChainId:c,appName:i,apiUrl:l,rpcOverrides:f,swapper:p,liquidityVenues:w,additionalSourceTokens:u,embeddedWalletAddress:S,externalWalletAddress:h,isUserWhitelisted:null,isWhitelistChecking:!1,isWhitelistConfigured:!1,isWhitelistGateActive:!1}),[x,g,r,A,o,d,W,T,a,c,i,l,f,p,w,u,S,h]);return k(et.Provider,{value:B,children:k(re.Provider,{value:I,children:k(Nr,{value:I,whitelist:y,children:k(Qe.Provider,{value:v,children:e})})})})},Lr={spacing:{xs:"0.25rem",sm:"0.5rem",md:"1rem",lg:"1.5rem",xl:"2rem"},borderRadius:{sm:"0.25rem",md:"0.5rem",lg:"0.75rem",full:"9999px"},typography:{fontFamily:X.ui,fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.75rem"},fontWeight:{normal:400,medium:500,semibold:600,bold:700}},shadows:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1)"},animation:{fast:"150ms ease-in-out",normal:"200ms ease-in-out",slow:"300ms ease-in-out"}},Or={primary:"#EA4B4B",primaryHover:"#E43838",secondary:"#f3f4f6",background:"#ffffff",surface:"#f9fafb",surfaceHover:"#f3f4f6",border:"#e5e7eb",borderHover:"#d1d5db",text:"#111827",textSecondary:"#374151",textMuted:"#6b7280",success:"#10b981",error:"#ef4444",warning:"#f59e0b",info:"#3b82f6"},qr={primary:"#EA4B4B",primaryHover:"#E43838",secondary:"#171717",background:"#141414",surface:"#1e1e1e",surfaceHover:"#2a2a2a",border:"#2d2d2d",borderHover:"#3a3a3a",text:"#ffffff",textSecondary:"#888888",textMuted:"#666666",success:"#10b981",error:"#ef4444",warning:"#f59e0b",info:"#3b82f6"},tt=(t="light")=>({mode:t,...Lr,colors:t==="light"?Or:qr});function ne(t,e){const r=t.replace("#",""),n=Math.max(0,Math.round(parseInt(r.substring(0,2),16)*(1-e))),o=Math.max(0,Math.round(parseInt(r.substring(2,4),16)*(1-e))),a=Math.max(0,Math.round(parseInt(r.substring(4,6),16)*(1-e)));return`#${n.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}function Mr(t,e){return{shell:e?.shell??"#141414",shellBorder:e?.shellBorder??ne(e?.shell??"#141414",.35),shellInnerBorder:e?.shellInnerBorder??ne(e?.shell??"#141414",.55),cardBg:e?.cardBg??"#1e1e1e",inputBg:e?.inputBg??"#171717",hoverBg:e?.hoverBg??"#2a2a2a",textPrimary:e?.textPrimary??"#ffffff",textSecondary:e?.textSecondary??"#888888",inputText:e?.inputText??"#e0e0e0",inputPlaceholder:e?.inputPlaceholder??"#555555",cardBorder:e?.cardBorder??"rgba(255,255,255,0.08)",inputBorder:e?.inputBorder??"rgba(255,255,255,0.10)",buttonBorder:e?.buttonBorder??"rgba(255,255,255,0.12)",successBg:e?.successBg??"#0a1f18",successBorder:e?.successBorder??"#1a4a3a",successText:e?.successText??"#6ee7b7",warningBg:e?.warningBg??"#1f1a0d",warningBorder:e?.warningBorder??"#4a3820",warningText:e?.warningText??"#fbbf24",errorBg:e?.errorBg??"#1f0d0d",errorBorder:e?.errorBorder??"#4a2020",errorText:e?.errorText??"#f87171",infoBg:e?.infoBg??"#0d1325",infoBorder:e?.infoBorder??"#2a3a5a",infoText:e?.infoText??"#60a5fa"}}function Dr(t){return{shell:"#ffffff",shellBorder:"#E9E9E9",shellInnerBorder:"#D5D5D5",cardBg:"#f9fafb",inputBg:"#ffffff",hoverBg:"#f3f4f6",textPrimary:"#111827",textSecondary:"#6b7280",inputText:"#111827",inputPlaceholder:"#9ca3af",cardBorder:"#e5e7eb",inputBorder:"#d1d5db",buttonBorder:"#0e0d0b",successBg:"#d1fae5",successBorder:"#6ee7b7",successText:"#065f46",warningBg:"#fef3c7",warningBorder:"#fde68a",warningText:"#92400e",errorBg:"#fef2f2",errorBorder:"#fecaca",errorText:"#dc2626",infoBg:"#dbeafe",infoBorder:"#93c5fd",infoText:"#1e40af"}}function rt(t,e){const r=e?{...t,...e}:t,n=r.dark??!1,o=r.primaryColor,a=r.shell??(n?"#141414":"#ffffff");return{primaryColor:o,dark:n,fontFamily:r.fontFamily??'"Helvetica Neue", sans-serif',appName:r.appName??"Spicenet",logo:r.logo,borderRadius:r.borderRadius??"8px",shell:a,shellBorder:ne(a,n?.35:.085),shellInnerBorder:ne(a,n?.55:.165),card:r.card??(n?"#1e1e1e":"#f9fafb"),input:n?"#171717":"#ffffff",hover:n?"#2a2a2a":"#f3f4f6",text:r.text??(n?"#ffffff":"#111827"),textMuted:r.textMuted??(n?"#888888":"#6b7280"),inputText:n?"#e0e0e0":"#111827",inputPlaceholder:n?"#555555":"#9ca3af",border:r.border??(n?"rgba(255,255,255,0.08)":"#e5e7eb"),inputBorder:n?"rgba(255,255,255,0.10)":"#d1d5db",buttonBorder:n?"rgba(255,255,255,0.12)":"#0e0d0b",successBg:n?"#0a1f18":"#d1fae5",successBorder:n?"#1a4a3a":"#6ee7b7",successText:n?"#6ee7b7":"#065f46",warningBg:n?"#1f1a0d":"#fef3c7",warningBorder:n?"#4a3820":"#fde68a",warningText:n?"#fbbf24":"#92400e",errorBg:n?"#1f0d0d":"#fef2f2",errorBorder:n?"#4a2020":"#fecaca",errorText:n?"#f87171":"#dc2626",infoBg:n?"#0d1325":"#dbeafe",infoBorder:n?"#2a3a5a":"#93c5fd",infoText:n?"#60a5fa":"#1e40af"}}const jr=X.mono;function nt(t,e){const r=ce(et)??void 0;return M(()=>{const n=r??{primaryColor:"#EA4B4B"},o={...t?.primaryColor?{primaryColor:t.primaryColor}:{},...t?.fontFamily?{fontFamily:t.fontFamily}:{},...e!==void 0?{dark:e}:{}},a=rt(n,o),{dark:s,primaryColor:d,appName:c}=a,i=tt(s?"dark":"light"),l={...i,colors:{...i.colors,primary:d,primaryHover:`${d}dd`},typography:{...i.typography,fontFamily:a.fontFamily}},m={shell:a.shell,shellBorder:a.shellBorder,shellInnerBorder:a.shellInnerBorder,cardBg:a.card,inputBg:a.input,hoverBg:a.hover,textPrimary:a.text,textSecondary:a.textMuted,inputText:a.inputText,inputPlaceholder:a.inputPlaceholder,cardBorder:a.border,inputBorder:a.inputBorder,buttonBorder:a.buttonBorder,successBg:a.successBg,successBorder:a.successBorder,successText:a.successText,warningBg:a.warningBg,warningBorder:a.warningBorder,warningText:a.warningText,errorBg:a.errorBg,errorBorder:a.errorBorder,errorText:a.errorText,infoBg:a.infoBg,infoBorder:a.infoBorder,infoText:a.infoText},f=t?.inputVariant?t.inputVariant==="dark":s;return{brand:r,theme:l,dark:s,appName:c,primaryColor:d,dk:m,palette:m,fontFamily:a.fontFamily,monoFont:jr,inputDark:f,cardBg:f?m.cardBg:"#E9E9E9",cardBorder:f?m.cardBorder:"#C6C6C6",textPrimary:m.textPrimary,textSecondary:m.textSecondary,subtitleText:f?m.textSecondary:"#979AA0"}},[r,t,e])}const at="spiceflow-spinner-keyframes";function _r(){if(typeof document>"u"||document.getElementById(at))return;const t=document.createElement("style");t.id=at,t.textContent="@keyframes spiceflow-spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}",document.head.appendChild(t)}const $e=({size:t=16,borderWidth:e=2,color:r="currentColor",style:n})=>{const o=G(!1);return L(()=>{o.current||(_r(),o.current=!0)},[]),k("div",{role:"status","aria-label":"Loading",style:{width:`${t}px`,height:`${t}px`,border:`${e}px solid ${r}`,borderTop:`${e}px solid transparent`,borderRadius:"50%",animation:"spiceflow-spin 1s linear infinite",flexShrink:0,...n}})},H=({variant:t="primary",size:e="md",loading:r=!1,fullWidth:n=!1,disabled:o,children:a,className:s="",style:d,theme:c,styles:i,dark:l,...m})=>{const{theme:f,dark:p,palette:w}=nt(i,l),u=c||f,y=l??p,[v,g]=_(!1),[b,A]=_(!1),B=y?w.shell:"white",W=()=>{switch(t){case"primary":return{backgroundColor:i?.button?.backgroundColor||u.colors.primary,color:i?.button?.color||"#ffffff",border:`1px solid ${i?.button?.backgroundColor||u.colors.primary}`};case"secondary":return{backgroundColor:u.colors.secondary,color:u.colors.text,border:`1px solid ${u.colors.border}`};case"success":return{backgroundColor:u.colors.success,color:u.colors.text,border:`1px solid ${u.colors.success}`};case"error":return{backgroundColor:u.colors.error,color:u.colors.text,border:`1px solid ${u.colors.error}`};case"ghost":return{backgroundColor:"transparent",color:u.colors.textSecondary,border:`1px solid ${u.colors.border}`};case"outline":{const h=i?.button?.backgroundColor||u.colors.primary,C=i?.button?.color||(y?"#ffffff":"#0e0d0b"),x=i?.button?.borderColor||(y?`${u.colors.primary}88`:"#0e0d0b"),I=o||r,R=y?"1px":"1.5px",oe=i?.button?.disabledBackgroundColor||`${h}88`,se=i?.button?.disabledColor||C;return{height:"56px",backgroundColor:I?oe:b?`${h}cc`:v?`${h}ee`:h,color:I?se:C,border:`${R} solid ${x}`,borderRadius:i?.button?.borderRadius||"12px",fontSize:"22px",fontWeight:500,fontFamily:X.mono,opacity:I?.78:1,transform:I?"none":b?"scale(0.98)":v?"translateY(-2px)":"none",boxShadow:I?`3px 3px 0px ${B}, 4px 4px 0px ${x}`:b?`2px 2px 0px ${x}`:v?`5px 5px 0px ${B}, 6px 6px 0px ${x}`:`3px 3px 0px ${B}, 4px 4px 0px ${x}`,transition:"transform 150ms ease, box-shadow 150ms ease, background-color 150ms ease, border-color 150ms ease, color 150ms ease"}}default:return{}}},E=()=>{if(t==="outline")return{};switch(e){case"sm":return{padding:`${u.spacing.sm} ${u.spacing.md}`,fontSize:u.typography.fontSize.sm};case"md":return{padding:`${u.spacing.md} ${u.spacing.lg}`,fontSize:u.typography.fontSize.base};case"lg":return{padding:`${u.spacing.lg} ${u.spacing.xl}`,fontSize:u.typography.fontSize.lg};default:return{}}},T={borderRadius:i?.button?.borderRadius||u.borderRadius.md,fontWeight:i?.button?.fontWeight||u.typography.fontWeight.medium,fontFamily:i?.button?.fontFamily||u.typography.fontFamily,fontSize:i?.button?.fontSize||void 0,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease, opacity 150ms ease",cursor:o||r?"not-allowed":"pointer",opacity:(o||r)&&t!=="outline"?.6:1,width:n?"100%":"auto",display:"flex",alignItems:"center",justifyContent:"center",gap:u.spacing.sm,...W(),...E(),...i?.button?.fontSize&&{fontSize:i.button.fontSize}},S=o||r;return ie("button",{type:m.type??"button","data-spiceflow-focus":!0,"aria-busy":r||void 0,"aria-disabled":S||void 0,style:{...T,...d},className:s,disabled:S,onMouseEnter:h=>{g(!0),m.onMouseEnter?.(h)},onMouseLeave:h=>{g(!1),A(!1),m.onMouseLeave?.(h)},onMouseDown:h=>{A(!0),m.onMouseDown?.(h)},onMouseUp:h=>{A(!1),m.onMouseUp?.(h)},...m,children:[r&&k($e,{size:16}),a]})},zr=({onAuthSuccess:t,onAuthError:e,theme:r="light",className:n="",buttonText:o="Login with Privy",autoTrigger:a=!1})=>{const s=tt(r),[d,c]=_(!1),[i,l]=_(!1),{ready:m,authenticated:f,user:p}=ue(),{login:w}=Tt(),{logout:u}=Rt();L(()=>{c(!0)},[]),L(()=>{a&&m&&!f&&d&&!i&&(l(!0),y())},[a,m,f,d,i]),L(()=>{if(m&&f&&p&&t){const g=p.wallet?.address||p.email?.address;g&&t(g)}},[m,f,p,t]),L(()=>{},[m,f,e]);const y=()=>{try{w()}catch(g){const b=`Login failed: ${String(g)}`;e?e(b):console.error(b)}},v=()=>{try{u()}catch(g){const b=`Logout failed: ${String(g)}`;e?e(b):console.error(b)}};if(!d)return k("div",{className:n,children:k(H,{variant:"primary",disabled:!0,theme:s,children:o})});if(!m)return k("div",{className:n,children:k(H,{variant:"primary",disabled:!0,theme:s,children:"Loading..."})});if(f&&p){const g=p.wallet?.address||p.email?.address,b=g?Ve(g):"Connected";return k("div",{className:n,children:ie(H,{variant:"primary",onClick:v,theme:s,children:["Logout (",b,")"]})})}return a?k("div",{className:n,children:ie("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px",flexDirection:"column",gap:"12px"},children:[k($e,{size:40,borderWidth:3,color:"#3b82f6"}),k("p",{style:{color:"#6b7280",fontSize:"14px"},children:"Opening login..."})]})}):k("div",{className:n,children:k(H,{variant:"primary",onClick:y,theme:s,children:o})})};export{Ur as $,te as A,H as B,Ot as C,hr as D,_e as E,$r as F,vr as G,xr as H,He as I,gr as J,yr as K,pr as L,Dt as M,Ve as N,pe as O,zr as P,xe as Q,Le as R,$ as S,Qt as T,Ue as U,Ge as V,Rr as W,Cr as X,Er as Y,kr as Z,Tr as _,Re as a,Br as a0,Ke as a1,Ye as a2,Vt as a3,tr as a4,cr as a5,_t as a6,Ir as a7,Me as a8,Wr as a9,je as aa,Mr as ab,Dr as ac,rt as ad,he as ae,O as b,zt as c,K as d,re as e,ze as f,q as g,jt as h,Ar as i,U as j,ae as k,qt as l,Je as m,sr as n,Q as o,nt as p,Mt as q,Z as r,Xt as s,X as t,De as u,Yt as v,$e as w,F as x,P as y,Gt as z};
2
+ import{jsx as k,jsxs as ie}from"react/jsx-runtime";import{useContext as ce,useRef as G,useLayoutEffect as st,useMemo as M,useEffect as L,createContext as le,useCallback as Ee,useState as _}from"react";import{isNativeToken as D,getChainMeta as Ce,getTokensForChain as it,getDelegateContract as ct,ZERO_ADDRESS as lt,getTokenByAddress as dt,DELEGATE_ABI as ut,ERC20_ABI as ft,spicenetEscrowAbi as mt,uniV3SwapRouterAbi as pt,normalizeNativeTokenAddress as Ie,getChainIdsByNetwork as ht}from"@spicenet-io/spiceflow-core";import{useQuery as gt,useMutation as yt}from"@tanstack/react-query";import{isAddress as N,getAddress as de,defineChain as bt,createPublicClient as wt,http as vt,erc20Abi as xt,createWalletClient as $t,custom as Et,formatUnits as V,isHex as Ct,decodeErrorResult as It,hexToString as kt}from"viem";import{useWallets as ke,usePrivy as ue,useActiveWallet as At,getEmbeddedConnectedWallet as Ae,useSign7702Authorization as St,useSignMessage as Bt,useLogin as Tt,useLogout as Rt}from"@privy-io/react-auth";import{useAccount as Se}from"wagmi";import{readContract as Pt}from"viem/actions";function O(t,e){return!t||!e?!1:D(t)&&D(e)?!0:N(t)&&N(e)?de(t)===de(e):t.toLowerCase()===e.toLowerCase()}const Ft="0xcA11bde05977b3631167028862bE2a173976CA11",Ut={4114:"0x860aFc632a6D625B95d8B96f39ECC48E988c6962"},Nt=new Set([5115]);function Wt(t){const e=Ut[t.id]??(Nt.has(t.id)?void 0:Ft);return bt({id:t.id,name:t.name,nativeCurrency:t.nativeCurrency,rpcUrls:{default:{http:[t.rpcUrl]}},blockExplorers:{default:{name:t.displayName,url:t.blockExplorer}},testnet:t.network==="testnet",...e?{contracts:{multicall3:{address:e}}}:{}})}const Lt=[1,8453,42161,4114,4663,56,137,143,11155111,421614,84532,5115,123420001114,688688,688689,46630],Y=Object.fromEntries(Lt.map(t=>Ce(t)).filter(t=>t!=null).map(t=>[t.id,{...t,viemChain:Wt(t),supportedTokens:it(t.id)}])),Ot=Y;let Be={};const fe=new Map,Te=t=>{Be={...t||{}},fe.clear()},K=(t,e=Be)=>{const r=e[t];return r&&typeof r=="string"&&r.length>0?r:Y[t]?.rpcUrl||void 0},q=t=>Y[t],Q=t=>{const e=Ce(t);return e?.displayName||e?.name||`Chain ${t}`},qt=t=>{const e=ct(t);if(!e)throw new Error(`Unsupported chain ID: ${t}`);if(e.toLowerCase()==="0xd4c4a222cdd42f5c3219249a083a5abf1420e9d8")throw new Error(`Delegation is unavailable for chain ID: ${t}`);return e},Mt=(t,e,r)=>{const n=q(t);return n?.blockExplorer?`${n.blockExplorer}/tx/${e}`:"#"};async function Dt(t,e){const r=`0x${e.toString(16)}`;try{await t.request({method:"wallet_switchEthereumChain",params:[{chainId:r}]});return}catch(a){if(!(a?.code===4902||typeof a?.message=="string"&&a.message.includes("Unrecognized chain ID")))throw a}const n=q(e);if(!n)throw new Error(`Cannot add unknown chain ${e} to wallet`);const o=K(e);if(!o)throw new Error(`Configure SpiceFlowProvider rpcOverrides[${e}] before adding this chain.`);await t.request({method:"wallet_addEthereumChain",params:[{chainId:r,chainName:n.name||`Chain ${e}`,nativeCurrency:n.nativeCurrency||{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:[o],blockExplorerUrls:n.blockExplorer?[n.blockExplorer]:void 0}]})}const Re=(t,e)=>{const r=q(t);if(!r)throw new Error(`Unsupported chain ID: ${t}`);const n=K(t,e);if(!n)throw new Error(`No RPC URL configured for chain ID: ${t}`);const o=`${t}:${n}`,a=fe.get(o);if(a)return a;const s=wt({chain:r.viemChain,transport:vt(n,{timeout:15e3,retryCount:2,retryDelay:300}),batch:{multicall:{wait:16}}});return fe.set(o,s),s},jt=t=>{const e={};return Object.values(Y).forEach(r=>{const n=K(r.id,t);n&&(e[r.id]={name:r.name,chain:r.viemChain,rpcUrl:n})}),e},_t=(t,e=[])=>{const r=q(t);if(!r)return[];const n=[];if(![11155111,421614,688689].includes(t)){const a=e.find(s=>s.chainId===t&&s.isNative);a?n.push(a):n.push({address:lt,name:r.nativeCurrency.name,symbol:r.nativeCurrency.symbol,decimals:r.nativeCurrency.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:void 0,isNative:!0,chainId:t})}if(!r.supportedTokens)return n;const o=n.some(a=>a.isNative);return r.supportedTokens.forEach(a=>{if(o&&D(a.address))return;const s=e.find(d=>d.chainId===t&&O(d.address,a.address));s?n.push(s):n.push({address:a.address,name:a.name,symbol:a.symbol,decimals:a.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:a.logo,isNative:!1,chainId:t})}),n},zt=async(t,e,r)=>{const n=q(t);if(!n)throw new Error(`Unsupported chain ID: ${t}`);const o=e.toLowerCase(),a=n.supportedTokens?.find(d=>O(d.address,o));let s;if(D(o)){if(n.nativeCurrency?.decimals==null)throw new Error(`Native currency decimals not configured for chain ${t}`);s=n.nativeCurrency.decimals}else if(a)s=a.decimals;else{if(!N(e,{strict:!1}))throw new Error(`Could not determine decimals for invalid token address: ${e}`);const d=Re(t,r);try{s=await Pt(d,{address:de(e),abi:xt,functionName:"decimals"})}catch(c){throw Object.assign(new Error(`Could not determine decimals for token ${e} on chain ${t}. Check the token contract and RPC configuration, then try again.`),{cause:c})}}if(!Number.isInteger(s)||s<0||s>255)throw new Error(`Invalid token decimals for ${e} on chain ${t}. Expected an integer from 0 to 255.`);return s},Jt=t=>{const e=t?.wallet;if(e?.address&&e.walletClientType==="privy"&&e.connectorType==="embedded"&&!e.imported)return e.address},Pe=async(t,e)=>{if(!t?.address)throw new Error("Wallet not available");if(typeof t.getWalletClient=="function"){const r=e===void 0?[void 0]:[String(e),e,void 0];let n=null;for(const o of r)try{const a=await t.getWalletClient(o);if(a)return a}catch(a){n=a}if(n)throw n}if(typeof t.getEthereumProvider=="function"){const r=await t.getEthereumProvider(),n=e?q(e)?.viemChain:void 0;return $t({account:t.address,chain:n,transport:Et(r)})}throw new Error("Wallet client not available")},Ht=async(t,e)=>{if(!t?.address)throw new Error("Wallet not available");if(typeof t.getEthereumProvider=="function")return t.getEthereumProvider();const r=await Pe(t,e);return{request:n=>r.request(n)}},me=t=>!t?.address||!N(t.address)?null:{address:t.address,wallet:t,getWalletClient:e=>Pe(t,e),getEthereumProvider:e=>Ht(t,e)},pe=()=>{const t=Se(),e=t.address,r=t.connector;let n=null,o=null,a=null;try{n=ke(),o=ue(),{wallet:a}=At()}catch{n=null,o=null,a=null}const s=n?.wallets||[],d=Ae(s),c=d?.address||Jt(o?.user),i=n?.ready&&o?.ready?s.filter(b=>N(b.address||"")&&b.type!=="solana"&&b.connectorType!=="embedded"&&!O(b.address,c)&&(typeof b.getEthereumProvider=="function"||typeof b.getWalletClient=="function")):[],l=a?.connectorType!=="embedded"&&a?.address?i.find(b=>O(b.address,a.address)):void 0,m=O(e,c),f=t.status==="connected"&&e&&N(e)&&typeof r?.getProvider=="function"?{address:e,connector:r,chainId:t.chainId,getEthereumProvider:()=>r.getProvider()}:null,p=!!e&&!m&&["connected","connecting","reconnecting"].includes(t.status),w=p?f||i.find(b=>O(b.address,e)):null,u=me(d),y=me(p?w:l),v=u?.address||c,g=me(f)||y;return{embeddedWallet:u,externalWallet:y,embeddedAddress:v,externalAddress:y?.address,activeWallet:g,activeAddress:g?.address}},Gt={base:0,raised:1,sticky:10,overlay:20,popover:40,modal:1e3,dropdown:1100,toast:1200,tooltip:1300},Vt={none:"0",sm:"4px",md:"6px",card:"8px",input:"10px",shell:"9px",modal:"12px",pill:"9999px",circle:"50%"},P={out:"cubic-bezier(0.22, 1, 0.36, 1)",inOut:"cubic-bezier(0.65, 0, 0.35, 1)",linear:"linear"},F={fast:"120ms",normal:"150ms",slow:"300ms",progress:"400ms"},Yt={interactive:`transform ${F.normal} ${P.out}, box-shadow ${F.normal} ${P.out}, background-color ${F.normal} ${P.out}, border-color ${F.normal} ${P.out}, color ${F.normal} ${P.out}`,color:`background-color ${F.normal} ${P.out}, border-color ${F.normal} ${P.out}, color ${F.normal} ${P.out}`,popover:`opacity ${F.normal} ${P.out}, transform ${F.normal} ${P.out}`},X={ui:'"Helvetica Neue", sans-serif',mono:'"IBM Plex Mono", monospace'};class $ extends Error{constructor(e,r,n={}){super(r),this.code=e,this.context=n,this.name="SpiceflowError",Error.captureStackTrace&&Error.captureStackTrace(this,$)}}function he(t){return t instanceof $}const Kt=["user rejected","user denied","user cancelled","rejected the request","action_rejected","4001"];function Fe(t){if(!t)return"";if(typeof t=="string")return t;const e=t,r=e.message||e.reason||"",n=e.details||"";return`${r} ${n}`.trim()}const Ue=t=>{if(he(t))return t.code==="WALLET_REJECTED";const e=Fe(t).toLowerCase();return Kt.some(r=>e.includes(r))};let ge=null;function Qt(t){return ge?.message===t?ge.detail:void 0}const Xt=(t,e="Something went wrong. Please try again.")=>{if(Ue(t))return"Transaction was rejected.";if(he(t)){const r=t.message||e,{requestId:n,httpStatus:o,responseBody:a,endpoint:s}=t.context;return(n||o||s)&&(ge={message:r,detail:{requestId:n,httpStatus:o,responseBody:a,endpoint:s}}),r}return Fe(t)||e},Zt=[...ut,...ft,...mt,...pt];function ye(t,e=0){return e>4||t==null?[]:typeof t=="string"?t.match(/0x[0-9a-fA-F]{8,}/g)??[]:Array.isArray(t)?t.flatMap(r=>ye(r,e+1)):typeof t=="object"?Object.values(t).flatMap(r=>ye(r,e+1)):[]}function Ne(t){try{const e=It({abi:Zt,data:t});if(e.errorName==="Error")return String(e.args?.[0]??"");if(e.errorName==="Panic")return`Panic(${e.args?.[0]})`;if(e.errorName==="CallReverted"){const r=e.args?.[4],n=r&&r!=="0x"?Ne(r):void 0;return n?`Call reverted: ${n}`:"Call reverted (no reason returned)"}return e.errorName}catch{try{const e=kt(t).replace(/\x00+$/g,"").trim();return/^[\x20-\x7e]+$/.test(e)&&e.length>1?e:void 0}catch{return}}}function er(t){for(const e of ye(t)){if(!Ct(e))continue;const r=Ne(e);if(r)return r}}function We(t,e){const r=e.match(/Output amount (\d+) is insufficient after fees (\d+) on chain (\d+)/);if(!r)return e;const[,n,o,a]=r,s=Number(a),d=BigInt(n),c=BigInt(o);let i;for(const v of t.intents){const g=v.chainBatches.find(b=>b.chainId===s);if(g){i=g;break}}const l=i?.tokenTransfers.find(v=>v.from==="escrow"&&O(v.to,t.user)&&!D(v.token)),m=Q(s);if(!l)return`Amount is too small to cover the estimated fee on ${m}.`;const f=dt(l.token,s),p=f?.decimals??18,w=f?.symbol??"tokens",u=V(d,p),y=V(c,p);return`Amount is too small to cover the estimated fee on ${m}. Amount: ${u} ${w}. Estimated fee: ${y} ${w}.`}function tr(t){return t?.code===4902||t?.name==="ChainNotConfiguredError"?"This network is not configured in your wallet. Please add it manually to continue.":t?.code===4001?"Network switch cancelled. Please switch manually in your wallet to continue.":"Unable to switch network. Please switch manually in your wallet to continue."}const rr="https://tx-submission-api.spicenet.io",Le=rr;function nr(t,e){return typeof e=="bigint"?e.toString():e}function j(t,e=""){if(Array.isArray(t))t.forEach((r,n)=>j(r,`${e}[${n}]`));else if(t&&typeof t=="object")for(const[r,n]of Object.entries(t)){const o=e?`${e}.${r}`:r;if(!n&&(r==="user"||r==="to"||r==="from"||r==="address"))throw new $("INVALID_PARAMS",`Wallet not ready: ${o} is missing from the request. Wait a moment and retry, or log in again.`,{path:o});j(n,o)}}function Oe(t){return typeof t.actionId=="string"&&t.actionId.length>0&&Array.isArray(t.intentIds)&&t.intentIds.length>0&&t.intentIds.every((e,r)=>typeof e=="string"&&e===`${t.actionId}/${r}`)&&(t.autoContinue===void 0||typeof t.autoContinue=="boolean")}async function Z(t,e){const r={...e?.headers},n=(e?.method??"GET").toUpperCase();(e?.body!=null||n!=="GET"&&n!=="HEAD")&&(r["x-request-id"]??(r["x-request-id"]=crypto.randomUUID()));const o=await fetch(t,{...e,headers:r}),a=o.headers.get("x-request-id")??"";return Object.assign(o,{requestId:a})}function z(t,e){if(!t)return e;const r=t.error,n=(typeof t.message=="string"?t.message:"")||(r&&typeof r=="object"&&"message"in r&&typeof r.message=="string"?r.message:"")||(typeof r=="string"?r:"")||e,o=er(t);return o&&!n.includes(o)?`${n} \u2014 ${o}`:n}async function ar(t){try{return await t.json()}catch{return null}}function or(t){return(Array.isArray(t?.balances)?t.balances:[]).flatMap(e=>{if(!e||typeof e!="object")return[];const r=e;return[{receiptToken:typeof r.receiptToken=="string"?r.receiptToken:void 0,tokenName:String(r.tokenName??""),balanceAvailable:String(r.balanceAvailable??"0"),chainTokens:Array.isArray(r.chainTokens)?r.chainTokens.filter(n=>typeof n=="string"):r.chainTokens&&typeof r.chainTokens=="object"?r.chainTokens:r.chainTokenConfig&&typeof r.chainTokenConfig=="object"?r.chainTokenConfig:void 0,decimals:typeof r.decimals=="number"?r.decimals:void 0,balanceUsd:typeof r.balanceUsd=="number"||typeof r.balanceUsd=="string"?r.balanceUsd:null}]})}class ae{constructor(){this.baseUrl=Le,this.feeValidationAvailable=!1}setBaseUrl(e){e!==this.baseUrl&&(this.feeValidationAvailable=!1),this.baseUrl=e}getBaseUrl(){return this.baseUrl}async requestJson(e,r){const n=`${this.baseUrl}${e}`,o=await Z(n,r.method&&r.method!=="GET"?{method:r.method,headers:{"Content-Type":"application/json",...r.headers},body:JSON.stringify(r.body,nr),signal:r.signal}:{headers:r.headers,signal:r.signal}),a=await o.text();let s;try{s=JSON.parse(a)}catch{s=null}if(!o.ok||!s||s.success===!1||r.ok&&!r.ok(s)){const d=z(s,r.fallbackError(o.status));throw new $(r.code??"RELAYER_ERROR",r.mapError?r.mapError(d):d,{httpStatus:o.status,requestId:o.requestId,responseBody:a,endpoint:e,...r.context})}return s}async createLimitOrder(e){try{return await this.requestJson("/orders",{method:"POST",body:e,fallbackError:r=>`Order registration failed: ${r}`})}catch(r){if(r instanceof $&&r.context.httpStatus===400)try{JSON.parse(String(r.context.responseBody??"{}"))?.submissionStatus==="rejected"&&(r.context.submissionStatus="rejected")}catch{}throw r}}async registerConditionalIntent(e){return this.requestJson("/conditional-intents",{method:"POST",body:e,fallbackError:r=>`Conditional intent registration failed: ${r}`})}async createConditionalReadToken(e){return this.requestJson("/conditional-intents/read-token",{method:"POST",body:e,fallbackError:r=>`Conditional intent read authorization failed: ${r}`})}async getConditionalIntent(e,r){return this.requestJson(`/conditional-intents/${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${r}`},fallbackError:n=>`Conditional intent status failed: ${n}`})}async listConditionalIntents(e,r){const n=new URLSearchParams({...r?.limit?{limit:String(r.limit)}:{},...r?.cursor?{cursor:r.cursor}:{}}).toString();return this.requestJson(`/conditional-intents${n?`?${n}`:""}`,{headers:{Authorization:`Bearer ${e}`},fallbackError:o=>`Conditional intent listing failed: ${o}`})}async cancelConditionalIntent(e,r){return this.requestJson(`/conditional-intents/${encodeURIComponent(e)}/cancel`,{method:"POST",body:r,fallbackError:n=>`Conditional intent cancellation failed: ${n}`})}async getLimitOrder(e){return this.requestJson(`/orders/${encodeURIComponent(e)}`,{fallbackError:r=>`Order lookup failed: ${r}`})}async listLimitOrders(e,r){const n=new URLSearchParams({user:e,...r?{after:r}:{}});return this.requestJson(`/orders?${n}`,{fallbackError:o=>`Order listing failed: ${o}`})}async cancelLimitOrder(e,r){return this.requestJson(`/orders/${encodeURIComponent(e)}/cancel`,{method:"POST",body:{signature:r},fallbackError:n=>`Order cancellation failed: ${n}`})}async supportsAutomaticContinuation(e){try{return(await this.requestJson("/actions/capabilities",{signal:e?.signal,fallbackError:r=>`Action capabilities unavailable: ${r}`})).automaticContinuation===!0}catch(r){if(r instanceof $&&r.context.httpStatus===404)return!1;throw r}}async createAction(e,r){if(j(e),r?.idempotencyKey!==void 0&&e.idempotencyKey!==void 0&&r.idempotencyKey.toLowerCase()!==e.idempotencyKey.toLowerCase())throw new $("INVALID_PARAMS","Action idempotency keys must identify the same original submission.");const n=this.baseUrl,o=new ae;o.setBaseUrl(n);const a=r?.idempotencyKey??e.idempotencyKey??`0x${Array.from(crypto.getRandomValues(new Uint8Array(32)),i=>i.toString(16).padStart(2,"0")).join("")}`;if(!/^0x[0-9a-f]{64}$/i.test(a))throw new $("INVALID_PARAMS","Action idempotency key must be exactly 32 bytes.");const s=r?.autoContinue??e.autoContinue,d={...e,idempotencyKey:a,...s!==void 0?{autoContinue:s}:{}},c=i=>{try{r?.onAccepted?.(i)}catch(l){console.warn("[relayer] accepted-action progress callback failed",l)}};try{const i=await o.requestJson("/actions",{method:"POST",body:d,signal:r?.signal,fallbackError:l=>`Relayer API error: ${l}`,ok:Oe});return c(i),i}catch(i){const l=i instanceof $?i.context:{};let m=l.httpStatus===401||l.httpStatus===403;if(l.httpStatus===400)try{m=JSON.parse(String(l.responseBody??"{}"))?.submissionStatus==="rejected"}catch{}for(let f=0;f<3;f++){f&&await new Promise(w=>setTimeout(w,1e3));let p;try{p=await o.getActionBySubmission(e.user,a)}catch{continue}if(p)return c(p),p;if(m&&i instanceof $)throw new $(i.code,i.message,{...l,idempotencyKey:a,user:e.user,submissionStatus:"rejected"})}throw new $("RELAYER_ERROR","The submission outcome is unknown. Check your activity and balances before submitting again.",{...l,idempotencyKey:a,user:e.user,submissionStatus:"unknown",cause:i})}}async getWalletActions(e,r){const n=r&&"aborted"in r?{signal:r}:r,o=n?.pendingOnly?"?pendingOnly=true":"",a=await this.requestJson(`/wallets/${encodeURIComponent(e)}/actions${o}`,{signal:n?.signal,fallbackError:c=>`Action status unavailable: ${c}`}),s=c=>{throw new $("RELAYER_ERROR","Action status response is invalid.",{endpoint:`/wallets/${encodeURIComponent(e)}/actions`,reason:c})},d=e.toLowerCase();return/^0x[0-9a-f]{40}$/i.test(e)||s("requested wallet is malformed"),(!Array.isArray(a.actions)||a.actions.length>100)&&s("actions must be a bounded array"),a.actions.map(c=>{if(!c||typeof c!="object")return s("action record is malformed");const i=c,l=i.user;if(typeof l!="string"||!/^0x[0-9a-f]{40}$/i.test(l)||l.toLowerCase()!==d)return s("action owner does not match the requested wallet");if(i.autoContinue!==!0)return s("action is not owned by automatic continuation");if(typeof i.actionId!="string"||i.actionId.length===0||i.actionId.length>200||i.actionId.includes("/")||typeof i.createdAt!="string"||typeof i.status!="string"||!Array.isArray(i.intents)||i.intents.length===0||i.intents.length>100)return s("action identity or intents are malformed");const m=i.intents.map((f,p)=>{if(!f||typeof f!="object")return s("intent record is malformed");const w=f;if(w.intentId!==`${i.actionId}/${p}`||typeof w.status!="string"||!Array.isArray(w.steps)||w.steps.length>100)return s("intent identity or steps are malformed");const u=w.steps.map((y,v)=>{if(!y||typeof y!="object")return s("step record is malformed");const g=y,b=typeof g.chainId=="number"?g.chainId:typeof g.chainId=="string"&&/^[1-9]\d*$/.test(g.chainId)?Number(g.chainId):NaN;return g.index!==v||!Number.isSafeInteger(b)||b<=0||typeof g.status!="string"||g.transactionHash!==null&&typeof g.transactionHash!="string"?s("step identity or state is malformed"):{...g,index:v,chainId:b,status:g.status,transactionHash:g.transactionHash}});return{...w,intentId:w.intentId,steps:u}});return{...i,user:l,autoContinue:!0,actionId:i.actionId,createdAt:i.createdAt,status:i.status,intents:m}})}async getActionBySubmission(e,r,n){if(!/^0x[0-9a-f]{40}$/i.test(e)||!/^0x[0-9a-f]{64}$/i.test(r))throw new $("INVALID_PARAMS","Submission lookup requires a wallet address and 32-byte key.");try{return await this.requestJson(`/actions/by-submission/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,{signal:n?.signal,fallbackError:o=>`Submission lookup failed: ${o}`,ok:Oe})}catch(o){if(o instanceof $&&o.context.httpStatus===404)return null;throw o}}async getIntentRecoveryStatus(e,r,n){if(!e||!Number.isSafeInteger(r)||r<0)throw new $("INVALID_PARAMS","Action recovery requires an action ID and non-negative intent index.");const o=await this.requestJson(`/actions/${encodeURIComponent(e)}/intents/${r}/recovery`,{signal:n?.signal,fallbackError:a=>`Action recovery check failed: ${a}`});if(o.status!=="completed"&&o.status!=="cancelled"&&o.status!=="unresolved")throw new $("RELAYER_ERROR","The relayer returned an unknown recovery status.",{actionId:e,intentIndex:r,recoveryStatus:o.status});return o.status}async getActionRecovery(e,r,n){return this.getIntentRecoveryStatus(e,r,n)}async estimateActionFees(e,r){j(e);const n=this.baseUrl,o=await this.requestJson("/actions/fees/estimate",{method:"POST",body:e,signal:r?.signal,fallbackError:a=>`Relayer fee estimate error: ${a}`,ok:a=>!!a.success&&!!a.data?.feeEstimate,mapError:a=>We(e,a)});return n===this.baseUrl&&(this.feeValidationAvailable=o.data?.supportsFeeValidation===!0),o.data.feeEstimate}canValidateActionFees(){return this.feeValidationAvailable}async validateActionFees(e,r){return j(e),(await this.requestJson("/actions/fees/validate",{method:"POST",body:e,signal:r?.signal,fallbackError:n=>`Relayer fee validation error: ${n}`,ok:n=>!!n.success&&!!n.data?.feeEstimate,mapError:n=>We(e,n)})).data.feeEstimate}async estimateBatchGas(e){j(e);const{signal:r,...n}=e,o=await this.requestJson("/actions/gas/estimate",{method:"POST",body:n,signal:r,fallbackError:a=>`Relayer gas estimate error: ${a}`,ok:a=>!!a.success&&!!a.data?.gasFee});return{...o.data.policy?{policy:o.data.policy}:{},gasFee:BigInt(o.data.gasFee),gasQuoteSource:o.data.gasQuoteSource,simulationVerified:o.data.simulationVerified===!0,platformFee:o.data.platformFee===void 0?void 0:BigInt(o.data.platformFee)}}async executeStep(e,r,n,o){const a=`${this.baseUrl}/actions/${e}/intents/${r}/steps/${n}`,s=`/actions/${e}/intents/${r}/steps/${n}`,d=crypto.randomUUID(),c=3e4,i=new Promise((f,p)=>setTimeout(()=>p(new $("RELAYER_EXECUTE_ERROR",`Execute step request timed out after ${c/1e3}s`,{actionId:e,intentIndex:r,stepIndex:n,endpoint:s,requestId:d})),c)),l=await Promise.race([Z(a,{method:"POST",headers:{"Content-Type":"application/json","x-request-id":d},body:JSON.stringify(o)}),i]),m=await l.json();if(!l.ok||m.success===!1)throw new $("RELAYER_EXECUTE_ERROR",z(m,`Execute step error: ${l.status}`),{httpStatus:l.status,requestId:l.requestId,responseBody:JSON.stringify(m),endpoint:s,actionId:e});if(m?.status==="error"||m?.status==="reverted"){const f=z(m,""),p=f?`: ${f}`:"";throw new $("RELAYER_EXECUTE_ERROR",`Step ${n} previously ${m.status}${p}`,{httpStatus:l.status,requestId:l.requestId,responseBody:JSON.stringify(m),endpoint:s,actionId:e,intentIndex:r,stepIndex:n,stepStatus:m.status})}return{success:!0,status:m.status,transactionHash:m.transactionHash}}async checkStepStatus(e,r,n=!1){const o=typeof n=="boolean"?n:n.includeExecutionStatus===!0,a=e.split("/"),s=a[0],d=a.length>=2?a[1]:"0",c=await this.requestJson(`/actions/${s}/intents/${d}/steps/${r}${o?"?includeExecutionStatus=true":""}`,{signal:typeof n=="boolean"?void 0:n.signal,fallbackError:i=>`Intent step status check failed: ${i}`,code:"RELAYER_STATUS_ERROR",context:{intentId:e}});return{success:!0,data:{status:c.status==="error"?"reverted":c.status,transactionHash:c.txid,error:z(c,""),...c.executionStatus==="success"||c.executionStatus==="reverted"?{executionStatus:c.executionStatus}:{}}}}async createWallet(e,r){return this.requestJson(`/wallets/${e}`,{method:"PUT",body:r,fallbackError:n=>`Create wallet error: ${n}`})}async getWallet(e){return this.requestJson(`/wallets/${e}`,{fallbackError:r=>`Get wallet error: ${r}`})}async createWithdrawal(e){return this.requestJson("/withdrawals",{method:"POST",body:e,fallbackError:r=>`Create withdrawal error: ${r}`})}async getWithdrawal(e){return this.requestJson(`/withdrawals/${e}`,{fallbackError:r=>`Get withdrawal error: ${r}`})}async getRollupTimestamp(){return this.requestJson("/time",{fallbackError:e=>`Get rollup timestamp error: ${e}`})}}const U=new ae;async function sr(t){const e=`${U.getBaseUrl()}/wallets/${t}/balance`,r=await Z(e,{cache:"no-store"}),n=await ar(r);if(!r.ok||n?.success===!1)throw new $("RELAYER_ERROR",z(n,`Unable to verify Spice balance: ${r.status}`),{httpStatus:r.status,requestId:r.requestId,responseBody:JSON.stringify(n),endpoint:`/wallets/${t}/balance`});return or(n)}const be=new Map,ee=new Set;function we(t){return JSON.stringify([U.getBaseUrl(),t.toLowerCase()])}function J(t,e){if(we(t)!==e)throw new Error("Wallet backend changed during registration. Please retry.")}function ir(t){if(!(t instanceof $))return!1;const e=t.context.httpStatus;return e===400||e===404?`${t.message} ${String(t.context.responseBody??"")}`.toLowerCase().includes("not found"):!1}async function qe(t){const e=we(t);if(ee.has(e))return!0;try{return await U.getWallet(t),J(t,e),ee.add(e),!0}catch(r){if(!ir(r))throw r;return!1}}async function Me(t,e){const r=we(t);if(ee.has(r))return;const n=be.get(r);if(n)return n;const o=(async()=>{const a=await qe(t);if(J(t,r),a)return;const{unix_timestamp:s}=await U.getRollupTimestamp();J(t,r);const d=`I am creating a new smart wallet and adding an admin wallet ethereum:0x${t.slice(2).toLowerCase()}. Nonce: ${s}`,c=await e(d);J(t,r);const i=typeof c=="string"?c:c.signature;if(!i)throw new Error("Wallet returned no smart wallet signature");await U.createWallet(t,{timestamp:s,signature:i}),J(t,r),ee.add(r)})();be.set(r,o);try{await o}finally{be.delete(r)}}const cr=(t,e)=>{const r=o=>e?e(o):Q(o),n=[];return t.forEach((o,a)=>{const s=o.calls&&o.calls.length>0,d=o.tokenTransfers&&o.tokenTransfers.length>0;!s&&!d||n.push({stepId:a,status:a===0?"processing":"pending",chainId:o.chainId,chainName:r(o.chainId),description:"Processing transaction"})}),n},De=()=>{const t=ce(re),e=t?.mode,{isConnected:r,address:n}=Se();let o=null,a=null,s=null,d=null,c=null;try{o=ue(),a=St(),s=Bt(),d=ke()}catch(h){c=h instanceof Error?h.message:String(h)}const{ready:i=!1,authenticated:l=!1}=o||{},m=t?.embeddedWalletAddress,f=Ae(d?.wallets||[]),p=m||f?.address,w=e==="ondemand"&&r?n:p,u=t?.apiUrl||U.getBaseUrl(),y=JSON.stringify([e,t?.provider,t?.network,t?.apiUrl,u,w?.toLowerCase(),p?.toLowerCase(),f?.address?.toLowerCase(),o?.user?.id??null,i,l,d?.ready,e==="ondemand"&&r,c]),v=G({key:y});v.current.key!==y&&(v.current={key:y});const g=v.current,b=G({mounted:!1});st(()=>{const h={mounted:!0};return b.current=h,()=>{h.mounted=!1}},[]);const A=()=>{const h=b.current,C=()=>{if(!h.mounted||v.current!==g||U.getBaseUrl()!==u)throw new Error("Wallet session changed before signing. Please review the action again.")};return C(),C};if(c)return e==="ondemand"&&r&&n?{isReady:!0,isAuthenticated:!0,isConnected:!0,address:n,provider:"privy",actions:{signAuthorization:async()=>{throw new Error("Not available in ondemand mode")},signMessage:async()=>{throw new Error("Not available in ondemand mode")},getEthereumProvider:async()=>{throw new Error("Not available in ondemand mode")}}}:{isReady:!1,isAuthenticated:!1,isConnected:!1,provider:null,actions:{signAuthorization:async()=>{throw new Error("Privy not available")},signMessage:async()=>{throw new Error("Privy not available")},getEthereumProvider:async()=>{throw new Error("Privy not available")}}};const B=!!p&&!!f,W={isReady:e==="ondemand"?!0:i,isAuthenticated:e==="ondemand"?!0:l||B,isConnected:e==="ondemand"?r&&!!n||i&&(l||B)&&B:i&&B,address:w,provider:"privy"},E=async(h,C,x=A())=>{if(x(),!f)throw new Error("Embedded wallet not available");const I=await f.getEthereumProvider();x();const{createWalletClient:R,custom:oe}=await import("viem");x();const se=R({account:f.address,transport:oe(I)});C?.(),x();const ot=await se.signMessage({account:f.address,message:h});return x(),{signature:ot}},T=async(h,C=A())=>{if(C(),s)try{const x=await s.signMessage({message:h});return C(),{signature:x.signature}}catch(x){if(C(),!f)throw x}if(!f)throw new Error("Privy sign message not available");return E(h,void 0,C)},S=async h=>{if(h(),!p)throw new Error("Embedded wallet not available for smart wallet setup");await Me(p,C=>T(C,h)),h()};return{...W,actions:{prepareSigning:async()=>{const h=A();if(!p)throw new Error("Embedded wallet not available");await qe(p),h()},signAuthorization:async(h,C)=>{const x=A();if(!a)throw new Error("Privy sign authorization not available");try{await S(x),C?.(),x();const I=await a.signAuthorization({contractAddress:h.contractAddress,chainId:h.chainId,nonce:h.nonce},{address:p});return x(),delete I.v,I}catch(I){const R=typeof I?.message=="string"?I.message:String(I?.message??I??"");throw R.includes("not configured")||R.includes("chain")?new Error(`Chain ${h.chainId} is not configured in PrivyProvider. Add this chain to your Privy dashboard or supportedChainIds.`):I}},signMessage:async(h,C)=>{const x=A();if(typeof h=="object"&&"raw"in h){if(await S(x),!f)throw new Error("Embedded wallet not available for raw signing");return E(h,C,x)}return C?.(),T(h,x)},getEthereumProvider:async()=>{if(!f)throw new Error("Embedded wallet not available");return f.getEthereumProvider()}}}},lr="https://portal-api.spicenet.io/api/v1",ve=t=>t.replace(/\/+$/,""),dr=(t,e)=>`${t}:${e}`;async function ur(t,e){const r=new URLSearchParams({walletAddress:e,campaignId:"spicenet-portal",campaignGroup:"1"}),n=await fetch(`${t}/portal/mainnet/linked-portal-wallet?${r.toString()}`,{cache:"no-store"});if(!n.ok){if(n.status>=500){const o=new Error(`Failed to resolve linked portal wallet: ${n.status}`);throw o.status=n.status,o}return null}return(await n.json()).portalWalletAddress?.toLowerCase()??null}async function fr(t,e,r){const n=new URLSearchParams({walletAddress:e,campaignId:r.campaignId,campaignGroup:r.campaignGroup,partnerId:r.partnerId}),o=await fetch(`${t}/portal/mainnet/whitelist/check?${n.toString()}`,{cache:"no-store"});if(!o.ok){const a=new Error(`Failed to check whitelist: ${o.status}`);throw a.status=o.status,a}return await o.json()}async function mr(t,e,r,n){const o=await fetch(`${t}/portal/mainnet/link-wallet`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({campaignId:e.campaignId,campaignGroup:e.campaignGroup,partnerId:e.partnerId,externalWalletAddress:r,embeddedWalletAddress:n})});if(!o.ok)throw new Error(`Failed to link wallet: ${o.status}`)}function je({walletAddress:t,campaignId:e,campaignGroup:r,partnerId:n,apiBaseUrl:o=lr,enabled:a=!0,staleTime:s=5*60*1e3,refetchInterval:d=!1}={}){const{isAuthenticated:c,isConnected:i}=De(),{externalAddress:l,embeddedAddress:m}=pe(),f=t??l,p=typeof f=="string"?f.toLowerCase():void 0,w=typeof m=="string"?m.toLowerCase():void 0,u=typeof l=="string"?l.toLowerCase():void 0,y=a&&c&&i&&!!l&&!!p&&N(p)&&!!e&&!!r&&!!n,v=M(()=>["partner-whitelist","check",p,e,r,n,ve(o)],[p,e,r,n,o]),g=gt({queryKey:v,enabled:y,staleTime:s,refetchInterval:d,retry:(E,T)=>{const S=T?.status;return typeof S=="number"&&S>=400&&S<500?!1:E<3},retryDelay:E=>Math.min(1e3*2**E,15e3),queryFn:async()=>{if(!p||!N(p))throw new Error("A valid wallet address is required");if(!e||!r||!n)throw new Error("campaignId, campaignGroup, and partnerId are required");const E=ve(o),T={campaignId:e,campaignGroup:r,partnerId:n},S=await ur(E,p);return S?fr(E,S,T):{walletAddress:p,campaignId:e,campaignGroup:r,partnerId:n,isWhitelisted:!1,isLinkedWallet:!1,whitelistedWalletAddress:null,externalWalletAddress:p}}}),b=a&&c&&i&&!!u&&N(u)&&!!w&&N(w)&&!!e&&!!r&&!!n,A=yt({mutationFn:E=>mr(ve(o),{campaignId:e,campaignGroup:r,partnerId:n},E.external,E.embedded)}),B=G(new Set),W=A.mutate;return L(()=>{if(!b||!u||!w||!e||!r||!n)return;const E=dr(u,w);B.current.has(E)||(B.current.add(E),W({external:u,embedded:w}))},[b,u,w,e,r,n,W]),{isWhitelisted:g.data?.isWhitelisted??!1,whitelistCheck:g.data,checkedWalletAddress:p,externalWalletAddress:l,embeddedWalletAddress:m,isExternalWalletConnected:!!l,isWhitelistCheckEnabled:y,linkWallet:A,isWalletLinked:A.isSuccess,...g}}const _e={assets:[],loading:!1,refreshing:!1,error:null,updatedAt:null};function ze(){const t=new Map,e=new Map,r=new WeakMap;let n=0;function o(){let a=_e;const s=new Map;let d,c=null,i=0,l=!1,m;const f=()=>s.forEach((u,y)=>y()),p=()=>{if(!m||!s.size)return Promise.resolve();if(c)return c;const u=++i;return a={...a,loading:a.updatedAt===null,refreshing:!0},f(),c=Promise.resolve().then(m).then(y=>{if(u!==i)return;const{assets:v,error:g=null}=Array.isArray(y)?{assets:y}:y;a={assets:v,loading:!1,refreshing:!1,error:g,updatedAt:Date.now()}},y=>{u===i&&(a={...a,loading:!1,refreshing:!1,error:y instanceof Error?y.message:"Unable to refresh balances"})}).finally(()=>{u===i&&(c=null,f(),l&&(l=!1,p()))}),c},w=()=>{clearInterval(d);const u=[...s.values()].filter(y=>y>0);u.length&&(d=setInterval(()=>void p(),Math.min(...u)))};return{snapshot:()=>a,refresh:p,invalidate:()=>c?(l=!0,c.then(()=>c??Promise.resolve())):p(),subscribe(u,y,v){return m=y,s.set(u,v),w(),p(),()=>{s.delete(u),w(),s.size||(i++,c=null,l=!1,a={...a,loading:!1,refreshing:!1})}}}}return{entry(a){let s=t.get(a);return s||(s=o(),t.set(a,s)),s},fetcherId(a){return r.has(a)||r.set(a,++n),r.get(a)},registerTokens(a){let s=!1;for(const d of a){const c=`${d.chainId}:${d.address.toLowerCase()}`;e.has(c)||(e.set(c,d),s=!0)}s&&t.forEach(d=>d.invalidate())},tokens:()=>[...e.values()],invalidate:()=>Promise.all([...t.values()].map(a=>a.invalidate())).then(()=>{})}}function Je(t,e){return t<=0n||e<=0n?0n:(t*e+10000n-1n)/10000n}function pr(t,e,r){const n=(t>e?t-e:0n)*10000n/(10000n+r),o=Je(n,r),a=n>0n,s=a?o+e:0n;return{netAmount:n,spicenetFee:a?o:0n,totalFee:s,grossAmount:n+s,coversFees:a}}function hr(t,e,r){if(t===e)return!0;const n=t>e?t:e;return n===0n?!1:(t>e?t-e:e-t)*10000n<=n*r}function xe(t=2e4){if(!Number.isSafeInteger(t)||t<0)throw new Error("feeToleranceBps must be a non-negative safe integer");return t}function He(t,e,r){const n=BigInt(xe(r));return(t>e?t-e:e-t)*10000n<=t*n}function gr(t,e,r){return["gasFee","spicenetFee","bridgeFee"].every(n=>He(t[n]??0n,e[n]??0n,r))}function yr(t,e){const r=V(t,e);return r.includes(".")?r.replace(/\.?0+$/,"")||"0":r}function te(t){const e=BigInt(t.feeBreakdown.spicenetFee),r=BigInt(t.feeBreakdown.gasFee),n=BigInt(t.feeBreakdown.bridgeFee??"0"),o=e+r+n;return{spicenetFee:e,gasFee:r,bridgeFee:n,totalFee:o}}function br(t){const e=BigInt(t.quotedAmount),r=BigInt(t.totalDebit),{totalFee:n}=te(t);return e>0n||r>0n||n>0n}function wr(t){const e=BigInt(t.quotedAmount),r=BigInt(t.totalDebit),{totalFee:n}=te(t),o=e+n;return r>o?r:o}function vr(t){const e=[];for(const r of t.intents)for(const n of r.batches)e.push(BigInt(n.quotedAmount));return e.length!==1?null:e[0]}function xr(t,e,r){return t.length===0||!t.every(n=>n.domain!=="spicenet"&&!n.tokenTransfers?.length)?null:{...e,grossAmount:r,netAmount:r,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}}function $r(t,e){if(t.policy?.enforcement==="enforce"&&t.assessments?.some(l=>l.status==="unsupported"))throw new Error("This action does not have a supported fee assessment");const r=t.intents.flatMap(l=>l.batches).filter(br);if(r.length===0)return null;const n=r.filter(l=>l.chainId===e.chainId),o=n.length>0?n:r;if(o.length>1)return null;const a=o[0];if(a.paymentToken&&(a.chainId!==e.chainId||a.paymentToken.toLowerCase()!==e.tokenAddress.toLowerCase()))return null;const{gasFee:s,spicenetFee:d,bridgeFee:c,totalFee:i}=te(a);return{chainId:a.chainId,tokenAddress:e.tokenAddress,...t.policy?{feePolicy:t.policy}:{},symbol:e.symbol,decimals:e.decimals,grossAmount:wr(a),netAmount:BigInt(a.quotedAmount),totalFee:i,gasFee:s,spicenetFee:d,bridgeFee:c,gasQuoteSource:a.gasQuoteSource}}const Ge=(t,e=4)=>!isFinite(t)||t===0?"0":t>0&&t<1e-6?t.toFixed(12).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""):t<1e-4?t.toFixed(8).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""):t.toFixed(e).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""),Er=t=>isFinite(t)?t>0&&t<.01?"<$0.01":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(t):"$0.00",Ve=(t,e=6,r=4)=>t.length<=e+r?t:`${t.slice(0,e)}...${t.slice(-r)}`,Cr=(t,e)=>{const r=t.replace(/[^0-9.]/g,"").split("."),n=r[0]??"",o=r.slice(1).join(""),a=typeof e=="number"?Math.max(0,Math.min(e,18)):null;return r.length===1?n:`${n}.${a===null?o:o.slice(0,a)}`},Ir=(t,e=6)=>!Number.isFinite(t)||t<=0?"0":t.toFixed(Math.min(Math.max(e,0),18)).replace(/\.?0+$/,""),kr=async t=>{try{return await navigator.clipboard.writeText(t),!0}catch(e){return console.error("Failed to copy to clipboard:",e),!1}};function Ar(t,e){return e?.length?e.some(r=>{const n=r.toLowerCase();return n===t.symbol.toLowerCase()||Ie(n).toLowerCase()===Ie(t.address).toLowerCase()||n===t.displaySymbol?.toLowerCase()||n===t.receiptTokenName?.toLowerCase()||n==="native"&&(t.isNative||D(t.address))}):!0}function Ye(t){return t.displaySymbol||t.symbol}function Ke(t){return t.displayName||t.displaySymbol||t.name||t.symbol}function Sr(t,e){const r=t.location==="rollup"||t._source==="spice"||!!t.receiptTokenId&&!t.location&&!t._source,n=a=>a&&e?Object.entries(e).find(([s])=>s.toLowerCase()===a.toLowerCase())?.[1]:void 0,o=r?n(t.receiptTokenId)??n(t.receiptTokenName):void 0;return{symbol:o?.symbol||o?.name||Ye(t),name:o?.name||o?.symbol||Ke({...t,name:t.name||""}),logoURI:o?.logoURI===void 0?t.logoURI:o.logoURI||null}}function Br(t){return t.displayChainName||Q(t.chainId)}function Tr(t){if(t.balance===0n)return"0";const e=V(t.balance,t.decimals),r=Ge(Number(e));return Number(r)===0?e:r}const Qe=le(void 0);function Rr(){const t=ce(Qe);return Ee(e=>Sr(e,t),[t])}const Pr=["__spicenet_whitelist_blocked__"],Xe="spiceflow-mode",Ze=()=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Xe);return t==="7702"?"7702":t==="non7702"?"ondemand":t==="embedded"?"7702":t==="external"?"ondemand":null}catch{return null}},Fr=t=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Xe,t==="7702"?"7702":"non7702")}catch{}},Ur=()=>Ze()!==null,et=le(null),re=le(null),Nr=({children:t,value:e,whitelist:r})=>{const n=!!r&&r.enabled!==!1,{isWhitelisted:o,isLoading:a,whitelistCheck:s}=je(n?r:{enabled:!1}),d=n&&!o,c=M(()=>({...e,mode:d?"ondemand":e.mode,allowedTokens:d?Pr:e.allowedTokens,isUserWhitelisted:o,isWhitelistChecking:a,isWhitelistConfigured:n,isWhitelistGateActive:d,whitelistCheck:s}),[e,n,d,o,a,s]);return k(re.Provider,{value:c,children:t})},Wr=({feeToleranceBps:t,children:e,provider:r="privy",supportedChainIds:n,allowedTokens:o,network:a="testnet",mode:s,skipFlow:d=[],nativeChainId:c,appName:i="Spicenet",apiUrl:l,theme:m,rpcOverrides:f,swapper:p,liquidityVenues:w,additionalSourceTokens:u,whitelist:y,assetDisplay:v})=>{const g=xe(t);L(()=>{if(!l)return;const R=U.getBaseUrl();return U.setBaseUrl(l),()=>U.setBaseUrl(R)},[l]),L(()=>(Te(f),()=>Te(void 0)),[f]);const b=M(()=>ht(a),[a]),A=n??b,B=m??null,[W,E]=_(()=>s??Ze()??"7702");L(()=>{s&&E(s)},[s]);const T=Ee(R=>{if(s){E(s);return}E(R),Fr(R)},[s]),{embeddedAddress:S,externalAddress:h}=pe(),C=JSON.stringify(f),x=M(ze,[a,l,C,r]),I=M(()=>({feeToleranceBps:g,inventory:x,provider:r,supportedChainIds:A,allowedTokens:o,skipFlow:d,mode:W,setMode:T,network:a,nativeChainId:c,appName:i,apiUrl:l,rpcOverrides:f,swapper:p,liquidityVenues:w,additionalSourceTokens:u,embeddedWalletAddress:S,externalWalletAddress:h,isUserWhitelisted:null,isWhitelistChecking:!1,isWhitelistConfigured:!1,isWhitelistGateActive:!1}),[x,g,r,A,o,d,W,T,a,c,i,l,f,p,w,u,S,h]);return k(et.Provider,{value:B,children:k(re.Provider,{value:I,children:k(Nr,{value:I,whitelist:y,children:k(Qe.Provider,{value:v,children:e})})})})},Lr={spacing:{xs:"0.25rem",sm:"0.5rem",md:"1rem",lg:"1.5rem",xl:"2rem"},borderRadius:{sm:"0.25rem",md:"0.5rem",lg:"0.75rem",full:"9999px"},typography:{fontFamily:X.ui,fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.75rem"},fontWeight:{normal:400,medium:500,semibold:600,bold:700}},shadows:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1)"},animation:{fast:"150ms ease-in-out",normal:"200ms ease-in-out",slow:"300ms ease-in-out"}},Or={primary:"#EA4B4B",primaryHover:"#E43838",secondary:"#f3f4f6",background:"#ffffff",surface:"#f9fafb",surfaceHover:"#f3f4f6",border:"#e5e7eb",borderHover:"#d1d5db",text:"#111827",textSecondary:"#374151",textMuted:"#6b7280",success:"#10b981",error:"#ef4444",warning:"#f59e0b",info:"#3b82f6"},qr={primary:"#EA4B4B",primaryHover:"#E43838",secondary:"#171717",background:"#141414",surface:"#1e1e1e",surfaceHover:"#2a2a2a",border:"#2d2d2d",borderHover:"#3a3a3a",text:"#ffffff",textSecondary:"#888888",textMuted:"#666666",success:"#10b981",error:"#ef4444",warning:"#f59e0b",info:"#3b82f6"},tt=(t="light")=>({mode:t,...Lr,colors:t==="light"?Or:qr});function ne(t,e){const r=t.replace("#",""),n=Math.max(0,Math.round(parseInt(r.substring(0,2),16)*(1-e))),o=Math.max(0,Math.round(parseInt(r.substring(2,4),16)*(1-e))),a=Math.max(0,Math.round(parseInt(r.substring(4,6),16)*(1-e)));return`#${n.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}function Mr(t,e){return{shell:e?.shell??"#141414",shellBorder:e?.shellBorder??ne(e?.shell??"#141414",.35),shellInnerBorder:e?.shellInnerBorder??ne(e?.shell??"#141414",.55),cardBg:e?.cardBg??"#1e1e1e",inputBg:e?.inputBg??"#171717",hoverBg:e?.hoverBg??"#2a2a2a",textPrimary:e?.textPrimary??"#ffffff",textSecondary:e?.textSecondary??"#888888",inputText:e?.inputText??"#e0e0e0",inputPlaceholder:e?.inputPlaceholder??"#555555",cardBorder:e?.cardBorder??"rgba(255,255,255,0.08)",inputBorder:e?.inputBorder??"rgba(255,255,255,0.10)",buttonBorder:e?.buttonBorder??"rgba(255,255,255,0.12)",successBg:e?.successBg??"#0a1f18",successBorder:e?.successBorder??"#1a4a3a",successText:e?.successText??"#6ee7b7",warningBg:e?.warningBg??"#1f1a0d",warningBorder:e?.warningBorder??"#4a3820",warningText:e?.warningText??"#fbbf24",errorBg:e?.errorBg??"#1f0d0d",errorBorder:e?.errorBorder??"#4a2020",errorText:e?.errorText??"#f87171",infoBg:e?.infoBg??"#0d1325",infoBorder:e?.infoBorder??"#2a3a5a",infoText:e?.infoText??"#60a5fa"}}function Dr(t){return{shell:"#ffffff",shellBorder:"#E9E9E9",shellInnerBorder:"#D5D5D5",cardBg:"#f9fafb",inputBg:"#ffffff",hoverBg:"#f3f4f6",textPrimary:"#111827",textSecondary:"#6b7280",inputText:"#111827",inputPlaceholder:"#9ca3af",cardBorder:"#e5e7eb",inputBorder:"#d1d5db",buttonBorder:"#0e0d0b",successBg:"#d1fae5",successBorder:"#6ee7b7",successText:"#065f46",warningBg:"#fef3c7",warningBorder:"#fde68a",warningText:"#92400e",errorBg:"#fef2f2",errorBorder:"#fecaca",errorText:"#dc2626",infoBg:"#dbeafe",infoBorder:"#93c5fd",infoText:"#1e40af"}}function rt(t,e){const r=e?{...t,...e}:t,n=r.dark??!1,o=r.primaryColor,a=r.shell??(n?"#141414":"#ffffff");return{primaryColor:o,dark:n,fontFamily:r.fontFamily??'"Helvetica Neue", sans-serif',appName:r.appName??"Spicenet",logo:r.logo,borderRadius:r.borderRadius??"8px",shell:a,shellBorder:ne(a,n?.35:.085),shellInnerBorder:ne(a,n?.55:.165),card:r.card??(n?"#1e1e1e":"#f9fafb"),input:n?"#171717":"#ffffff",hover:n?"#2a2a2a":"#f3f4f6",text:r.text??(n?"#ffffff":"#111827"),textMuted:r.textMuted??(n?"#888888":"#6b7280"),inputText:n?"#e0e0e0":"#111827",inputPlaceholder:n?"#555555":"#9ca3af",border:r.border??(n?"rgba(255,255,255,0.08)":"#e5e7eb"),inputBorder:n?"rgba(255,255,255,0.10)":"#d1d5db",buttonBorder:n?"rgba(255,255,255,0.12)":"#0e0d0b",successBg:n?"#0a1f18":"#d1fae5",successBorder:n?"#1a4a3a":"#6ee7b7",successText:n?"#6ee7b7":"#065f46",warningBg:n?"#1f1a0d":"#fef3c7",warningBorder:n?"#4a3820":"#fde68a",warningText:n?"#fbbf24":"#92400e",errorBg:n?"#1f0d0d":"#fef2f2",errorBorder:n?"#4a2020":"#fecaca",errorText:n?"#f87171":"#dc2626",infoBg:n?"#0d1325":"#dbeafe",infoBorder:n?"#2a3a5a":"#93c5fd",infoText:n?"#60a5fa":"#1e40af"}}const jr=X.mono;function nt(t,e){const r=ce(et)??void 0;return M(()=>{const n=r??{primaryColor:"#EA4B4B"},o={...t?.primaryColor?{primaryColor:t.primaryColor}:{},...t?.fontFamily?{fontFamily:t.fontFamily}:{},...e!==void 0?{dark:e}:{}},a=rt(n,o),{dark:s,primaryColor:d,appName:c}=a,i=tt(s?"dark":"light"),l={...i,colors:{...i.colors,primary:d,primaryHover:`${d}dd`},typography:{...i.typography,fontFamily:a.fontFamily}},m={shell:a.shell,shellBorder:a.shellBorder,shellInnerBorder:a.shellInnerBorder,cardBg:a.card,inputBg:a.input,hoverBg:a.hover,textPrimary:a.text,textSecondary:a.textMuted,inputText:a.inputText,inputPlaceholder:a.inputPlaceholder,cardBorder:a.border,inputBorder:a.inputBorder,buttonBorder:a.buttonBorder,successBg:a.successBg,successBorder:a.successBorder,successText:a.successText,warningBg:a.warningBg,warningBorder:a.warningBorder,warningText:a.warningText,errorBg:a.errorBg,errorBorder:a.errorBorder,errorText:a.errorText,infoBg:a.infoBg,infoBorder:a.infoBorder,infoText:a.infoText},f=t?.inputVariant?t.inputVariant==="dark":s;return{brand:r,theme:l,dark:s,appName:c,primaryColor:d,dk:m,palette:m,fontFamily:a.fontFamily,monoFont:jr,inputDark:f,cardBg:f?m.cardBg:"#E9E9E9",cardBorder:f?m.cardBorder:"#C6C6C6",textPrimary:m.textPrimary,textSecondary:m.textSecondary,subtitleText:f?m.textSecondary:"#979AA0"}},[r,t,e])}const at="spiceflow-spinner-keyframes";function _r(){if(typeof document>"u"||document.getElementById(at))return;const t=document.createElement("style");t.id=at,t.textContent="@keyframes spiceflow-spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}",document.head.appendChild(t)}const $e=({size:t=16,borderWidth:e=2,color:r="currentColor",style:n})=>{const o=G(!1);return L(()=>{o.current||(_r(),o.current=!0)},[]),k("div",{role:"status","aria-label":"Loading",style:{width:`${t}px`,height:`${t}px`,border:`${e}px solid ${r}`,borderTop:`${e}px solid transparent`,borderRadius:"50%",animation:"spiceflow-spin 1s linear infinite",flexShrink:0,...n}})},H=({variant:t="primary",size:e="md",loading:r=!1,fullWidth:n=!1,disabled:o,children:a,className:s="",style:d,theme:c,styles:i,dark:l,...m})=>{const{theme:f,dark:p,palette:w}=nt(i,l),u=c||f,y=l??p,[v,g]=_(!1),[b,A]=_(!1),B=y?w.shell:"white",W=()=>{switch(t){case"primary":return{backgroundColor:i?.button?.backgroundColor||u.colors.primary,color:i?.button?.color||"#ffffff",border:`1px solid ${i?.button?.backgroundColor||u.colors.primary}`};case"secondary":return{backgroundColor:u.colors.secondary,color:u.colors.text,border:`1px solid ${u.colors.border}`};case"success":return{backgroundColor:u.colors.success,color:u.colors.text,border:`1px solid ${u.colors.success}`};case"error":return{backgroundColor:u.colors.error,color:u.colors.text,border:`1px solid ${u.colors.error}`};case"ghost":return{backgroundColor:"transparent",color:u.colors.textSecondary,border:`1px solid ${u.colors.border}`};case"outline":{const h=i?.button?.backgroundColor||u.colors.primary,C=i?.button?.color||(y?"#ffffff":"#0e0d0b"),x=i?.button?.borderColor||(y?`${u.colors.primary}88`:"#0e0d0b"),I=o||r,R=y?"1px":"1.5px",oe=i?.button?.disabledBackgroundColor||`${h}88`,se=i?.button?.disabledColor||C;return{height:"56px",backgroundColor:I?oe:b?`${h}cc`:v?`${h}ee`:h,color:I?se:C,border:`${R} solid ${x}`,borderRadius:i?.button?.borderRadius||"12px",fontSize:"22px",fontWeight:500,fontFamily:X.mono,opacity:I?.78:1,transform:I?"none":b?"scale(0.98)":v?"translateY(-2px)":"none",boxShadow:I?`3px 3px 0px ${B}, 4px 4px 0px ${x}`:b?`2px 2px 0px ${x}`:v?`5px 5px 0px ${B}, 6px 6px 0px ${x}`:`3px 3px 0px ${B}, 4px 4px 0px ${x}`,transition:"transform 150ms ease, box-shadow 150ms ease, background-color 150ms ease, border-color 150ms ease, color 150ms ease"}}default:return{}}},E=()=>{if(t==="outline")return{};switch(e){case"sm":return{padding:`${u.spacing.sm} ${u.spacing.md}`,fontSize:u.typography.fontSize.sm};case"md":return{padding:`${u.spacing.md} ${u.spacing.lg}`,fontSize:u.typography.fontSize.base};case"lg":return{padding:`${u.spacing.lg} ${u.spacing.xl}`,fontSize:u.typography.fontSize.lg};default:return{}}},T={borderRadius:i?.button?.borderRadius||u.borderRadius.md,fontWeight:i?.button?.fontWeight||u.typography.fontWeight.medium,fontFamily:i?.button?.fontFamily||u.typography.fontFamily,fontSize:i?.button?.fontSize||void 0,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease, opacity 150ms ease",cursor:o||r?"not-allowed":"pointer",opacity:(o||r)&&t!=="outline"?.6:1,width:n?"100%":"auto",display:"flex",alignItems:"center",justifyContent:"center",gap:u.spacing.sm,...W(),...E(),...i?.button?.fontSize&&{fontSize:i.button.fontSize}},S=o||r;return ie("button",{type:m.type??"button","data-spiceflow-focus":!0,"aria-busy":r||void 0,"aria-disabled":S||void 0,style:{...T,...d},className:s,disabled:S,onMouseEnter:h=>{g(!0),m.onMouseEnter?.(h)},onMouseLeave:h=>{g(!1),A(!1),m.onMouseLeave?.(h)},onMouseDown:h=>{A(!0),m.onMouseDown?.(h)},onMouseUp:h=>{A(!1),m.onMouseUp?.(h)},...m,children:[r&&k($e,{size:16}),a]})},zr=({onAuthSuccess:t,onAuthError:e,theme:r="light",className:n="",buttonText:o="Login with Privy",autoTrigger:a=!1})=>{const s=tt(r),[d,c]=_(!1),[i,l]=_(!1),{ready:m,authenticated:f,user:p}=ue(),{login:w}=Tt(),{logout:u}=Rt();L(()=>{c(!0)},[]),L(()=>{a&&m&&!f&&d&&!i&&(l(!0),y())},[a,m,f,d,i]),L(()=>{if(m&&f&&p&&t){const g=p.wallet?.address||p.email?.address;g&&t(g)}},[m,f,p,t]),L(()=>{},[m,f,e]);const y=()=>{try{w()}catch(g){const b=`Login failed: ${String(g)}`;e?e(b):console.error(b)}},v=()=>{try{u()}catch(g){const b=`Logout failed: ${String(g)}`;e?e(b):console.error(b)}};if(!d)return k("div",{className:n,children:k(H,{variant:"primary",disabled:!0,theme:s,children:o})});if(!m)return k("div",{className:n,children:k(H,{variant:"primary",disabled:!0,theme:s,children:"Loading..."})});if(f&&p){const g=p.wallet?.address||p.email?.address,b=g?Ve(g):"Connected";return k("div",{className:n,children:ie(H,{variant:"primary",onClick:v,theme:s,children:["Logout (",b,")"]})})}return a?k("div",{className:n,children:ie("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px",flexDirection:"column",gap:"12px"},children:[k($e,{size:40,borderWidth:3,color:"#3b82f6"}),k("p",{style:{color:"#6b7280",fontSize:"14px"},children:"Opening login..."})]})}):k("div",{className:n,children:k(H,{variant:"primary",onClick:y,theme:s,children:o})})};export{Ur as $,te as A,H as B,Ot as C,hr as D,_e as E,$r as F,vr as G,xr as H,He as I,gr as J,yr as K,pr as L,Dt as M,Ve as N,pe as O,zr as P,xe as Q,Le as R,$ as S,Qt as T,Ue as U,Ge as V,Rr as W,Cr as X,Er as Y,kr as Z,Tr as _,Re as a,Br as a0,Ke as a1,Ye as a2,Vt as a3,tr as a4,cr as a5,_t as a6,Ir as a7,Me as a8,Wr as a9,je as aa,Mr as ab,Dr as ac,rt as ad,he as ae,O as b,zt as c,K as d,re as e,ze as f,q as g,jt as h,Ar as i,U as j,ae as k,qt as l,Je as m,sr as n,Q as o,nt as p,Mt as q,Z as r,Xt as s,X as t,De as u,Yt as v,$e as w,F as x,P as y,Gt as z};
@@ -1 +1 @@
1
- "use strict";var Ye=Object.create;var he=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var Xe=Object.getPrototypeOf,Ze=Object.prototype.hasOwnProperty;var et=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Qe(e))!Ze.call(t,o)&&o!==r&&he(t,o,{get:()=>e[o],enumerable:!(n=Ke(e,o))||n.enumerable});return t};var tt=(t,e,r)=>(r=t!=null?Ye(Xe(t)):{},et(e||!t||!t.__esModule?he(r,"default",{value:t,enumerable:!0}):r,t));const k=require("react/jsx-runtime"),v=require("react"),B=require("@spicenet-io/spiceflow-core"),ge=require("@tanstack/react-query"),C=require("viem"),F=require("@privy-io/react-auth"),ye=require("wagmi"),rt=require("viem/actions");function M(t,e){return!t||!e?!1:B.isNativeToken(t)&&B.isNativeToken(e)?!0:C.isAddress(t)&&C.isAddress(e)?C.getAddress(t)===C.getAddress(e):t.toLowerCase()===e.toLowerCase()}const nt="0xcA11bde05977b3631167028862bE2a173976CA11",at={4114:"0x860aFc632a6D625B95d8B96f39ECC48E988c6962"},ot=new Set([5115]);function st(t){const e=at[t.id]??(ot.has(t.id)?void 0:nt);return C.defineChain({id:t.id,name:t.name,nativeCurrency:t.nativeCurrency,rpcUrls:{default:{http:[t.rpcUrl]}},blockExplorers:{default:{name:t.displayName,url:t.blockExplorer}},testnet:t.network==="testnet",...e?{contracts:{multicall3:{address:e}}}:{}})}const it=[1,8453,42161,4114,4663,56,137,143,11155111,421614,84532,5115,123420001114,688688,688689,46630],H=Object.fromEntries(it.map(t=>B.getChainMeta(t)).filter(t=>t!=null).map(t=>[t.id,{...t,viemChain:st(t),supportedTokens:B.getTokensForChain(t.id)}])),ct=H;let be={};const ae=new Map,we=t=>{be={...t||{}},ae.clear()},G=(t,e=be)=>{const r=e[t];return r&&typeof r=="string"&&r.length>0?r:H[t]?.rpcUrl||void 0},j=t=>H[t],V=t=>{const e=B.getChainMeta(t);return e?.displayName||e?.name||`Chain ${t}`},lt=t=>{const e=B.getDelegateContract(t);if(!e)throw new Error(`Unsupported chain ID: ${t}`);if(e.toLowerCase()==="0xd4c4a222cdd42f5c3219249a083a5abf1420e9d8")throw new Error(`Delegation is unavailable for chain ID: ${t}`);return e},dt=(t,e,r)=>{const n=j(t);return n?.blockExplorer?`${n.blockExplorer}/tx/${e}`:"#"};async function ut(t,e){const r=`0x${e.toString(16)}`;try{await t.request({method:"wallet_switchEthereumChain",params:[{chainId:r}]});return}catch(a){if(!(a?.code===4902||typeof a?.message=="string"&&a.message.includes("Unrecognized chain ID")))throw a}const n=j(e);if(!n)throw new Error(`Cannot add unknown chain ${e} to wallet`);const o=G(e);if(!o)throw new Error(`Configure SpiceFlowProvider rpcOverrides[${e}] before adding this chain.`);await t.request({method:"wallet_addEthereumChain",params:[{chainId:r,chainName:n.name||`Chain ${e}`,nativeCurrency:n.nativeCurrency||{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:[o],blockExplorerUrls:n.blockExplorer?[n.blockExplorer]:void 0}]})}const ve=(t,e)=>{const r=j(t);if(!r)throw new Error(`Unsupported chain ID: ${t}`);const n=G(t,e);if(!n)throw new Error(`No RPC URL configured for chain ID: ${t}`);const o=`${t}:${n}`,a=ae.get(o);if(a)return a;const s=C.createPublicClient({chain:r.viemChain,transport:C.http(n,{timeout:15e3,retryCount:2,retryDelay:300}),batch:{multicall:{wait:16}}});return ae.set(o,s),s},ft=t=>{const e={};return Object.values(H).forEach(r=>{const n=G(r.id,t);n&&(e[r.id]={name:r.name,chain:r.viemChain,rpcUrl:n})}),e},mt=(t,e=[])=>{const r=j(t);if(!r)return[];const n=[];if(![11155111,421614,688689].includes(t)){const a=e.find(s=>s.chainId===t&&s.isNative);a?n.push(a):n.push({address:B.ZERO_ADDRESS,name:r.nativeCurrency.name,symbol:r.nativeCurrency.symbol,decimals:r.nativeCurrency.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:void 0,isNative:!0,chainId:t})}if(!r.supportedTokens)return n;const o=n.some(a=>a.isNative);return r.supportedTokens.forEach(a=>{if(o&&B.isNativeToken(a.address))return;const s=e.find(d=>d.chainId===t&&M(d.address,a.address));s?n.push(s):n.push({address:a.address,name:a.name,symbol:a.symbol,decimals:a.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:a.logo,isNative:!1,chainId:t})}),n},pt=async(t,e,r)=>{const n=j(t);if(!n)throw new Error(`Unsupported chain ID: ${t}`);const o=e.toLowerCase(),a=n.supportedTokens?.find(d=>M(d.address,o));let s;if(B.isNativeToken(o)){if(n.nativeCurrency?.decimals==null)throw new Error(`Native currency decimals not configured for chain ${t}`);s=n.nativeCurrency.decimals}else if(a)s=a.decimals;else{if(!C.isAddress(e,{strict:!1}))throw new Error(`Could not determine decimals for invalid token address: ${e}`);const d=ve(t,r);try{s=await rt.readContract(d,{address:C.getAddress(e),abi:C.erc20Abi,functionName:"decimals"})}catch(c){throw Object.assign(new Error(`Could not determine decimals for token ${e} on chain ${t}. Check the token contract and RPC configuration, then try again.`),{cause:c})}}if(!Number.isInteger(s)||s<0||s>255)throw new Error(`Invalid token decimals for ${e} on chain ${t}. Expected an integer from 0 to 255.`);return s},ht=t=>{const e=t?.wallet;if(e?.address&&e.walletClientType==="privy"&&e.connectorType==="embedded"&&!e.imported)return e.address},xe=async(t,e)=>{if(!t?.address)throw new Error("Wallet not available");if(typeof t.getWalletClient=="function"){const r=e===void 0?[void 0]:[String(e),e,void 0];let n=null;for(const o of r)try{const a=await t.getWalletClient(o);if(a)return a}catch(a){n=a}if(n)throw n}if(typeof t.getEthereumProvider=="function"){const r=await t.getEthereumProvider(),n=e?j(e)?.viemChain:void 0;return C.createWalletClient({account:t.address,chain:n,transport:C.custom(r)})}throw new Error("Wallet client not available")},gt=async(t,e)=>{if(!t?.address)throw new Error("Wallet not available");if(typeof t.getEthereumProvider=="function")return t.getEthereumProvider();const r=await xe(t,e);return{request:n=>r.request(n)}},oe=t=>!t?.address||!C.isAddress(t.address)?null:{address:t.address,wallet:t,getWalletClient:e=>xe(t,e),getEthereumProvider:e=>gt(t,e)},se=()=>{const t=ye.useAccount(),e=t.address,r=t.connector;let n=null,o=null,a=null;try{n=F.useWallets(),o=F.usePrivy(),{wallet:a}=F.useActiveWallet()}catch{n=null,o=null,a=null}const s=n?.wallets||[],d=F.getEmbeddedConnectedWallet(s),c=d?.address||ht(o?.user),i=n?.ready&&o?.ready?s.filter(b=>C.isAddress(b.address||"")&&b.type!=="solana"&&b.connectorType!=="embedded"&&!M(b.address,c)&&(typeof b.getEthereumProvider=="function"||typeof b.getWalletClient=="function")):[],l=a?.connectorType!=="embedded"&&a?.address?i.find(b=>M(b.address,a.address)):void 0,m=M(e,c),f=t.status==="connected"&&e&&C.isAddress(e)&&typeof r?.getProvider=="function"?{address:e,connector:r,chainId:t.chainId,getEthereumProvider:()=>r.getProvider()}:null,p=!!e&&!m&&["connected","connecting","reconnecting"].includes(t.status),w=p?f||i.find(b=>M(b.address,e)):null,u=oe(d),y=oe(p?w:l),x=u?.address||c,g=oe(f)||y;return{embeddedWallet:u,externalWallet:y,embeddedAddress:x,externalAddress:y?.address,activeWallet:g,activeAddress:g?.address}},yt={base:0,raised:1,sticky:10,overlay:20,popover:40,modal:1e3,dropdown:1100,toast:1200,tooltip:1300},bt={none:"0",sm:"4px",md:"6px",card:"8px",input:"10px",shell:"9px",modal:"12px",pill:"9999px",circle:"50%"},W={out:"cubic-bezier(0.22, 1, 0.36, 1)",inOut:"cubic-bezier(0.65, 0, 0.35, 1)",linear:"linear"},L={fast:"120ms",normal:"150ms",slow:"300ms",progress:"400ms"},wt={interactive:`transform ${L.normal} ${W.out}, box-shadow ${L.normal} ${W.out}, background-color ${L.normal} ${W.out}, border-color ${L.normal} ${W.out}, color ${L.normal} ${W.out}`,color:`background-color ${L.normal} ${W.out}, border-color ${L.normal} ${W.out}, color ${L.normal} ${W.out}`,popover:`opacity ${L.normal} ${W.out}, transform ${L.normal} ${W.out}`},Y={ui:'"Helvetica Neue", sans-serif',mono:'"IBM Plex Mono", monospace'};class $ extends Error{constructor(e,r,n={}){super(r),this.code=e,this.context=n,this.name="SpiceflowError",Error.captureStackTrace&&Error.captureStackTrace(this,$)}}function ie(t){return t instanceof $}const vt=["user rejected","user denied","user cancelled","rejected the request","action_rejected","4001"];function Ee(t){if(!t)return"";if(typeof t=="string")return t;const e=t,r=e.message||e.reason||"",n=e.details||"";return`${r} ${n}`.trim()}const Ce=t=>{if(ie(t))return t.code==="WALLET_REJECTED";const e=Ee(t).toLowerCase();return vt.some(r=>e.includes(r))};let ce=null;function xt(t){return ce?.message===t?ce.detail:void 0}const Et=(t,e="Something went wrong. Please try again.")=>{if(Ce(t))return"Transaction was rejected.";if(ie(t)){const r=t.message||e,{requestId:n,httpStatus:o,responseBody:a,endpoint:s}=t.context;return(n||o||s)&&(ce={message:r,detail:{requestId:n,httpStatus:o,responseBody:a,endpoint:s}}),r}return Ee(t)||e},Ct=[...B.DELEGATE_ABI,...B.ERC20_ABI,...B.spicenetEscrowAbi,...B.uniV3SwapRouterAbi];function le(t,e=0){return e>4||t==null?[]:typeof t=="string"?t.match(/0x[0-9a-fA-F]{8,}/g)??[]:Array.isArray(t)?t.flatMap(r=>le(r,e+1)):typeof t=="object"?Object.values(t).flatMap(r=>le(r,e+1)):[]}function $e(t){try{const e=C.decodeErrorResult({abi:Ct,data:t});if(e.errorName==="Error")return String(e.args?.[0]??"");if(e.errorName==="Panic")return`Panic(${e.args?.[0]})`;if(e.errorName==="CallReverted"){const r=e.args?.[4],n=r&&r!=="0x"?$e(r):void 0;return n?`Call reverted: ${n}`:"Call reverted (no reason returned)"}return e.errorName}catch{try{const e=C.hexToString(t).replace(/\x00+$/g,"").trim();return/^[\x20-\x7e]+$/.test(e)&&e.length>1?e:void 0}catch{return}}}function $t(t){for(const e of le(t)){if(!C.isHex(e))continue;const r=$e(e);if(r)return r}}function Ae(t,e){const r=e.match(/Output amount (\d+) is insufficient after fees (\d+) on chain (\d+)/);if(!r)return e;const[,n,o,a]=r,s=Number(a),d=BigInt(n),c=BigInt(o);let i;for(const x of t.intents){const g=x.chainBatches.find(b=>b.chainId===s);if(g){i=g;break}}const l=i?.tokenTransfers.find(x=>x.from==="escrow"&&M(x.to,t.user)&&!B.isNativeToken(x.token)),m=V(s);if(!l)return`Amount is too small to cover the estimated fee on ${m}.`;const f=B.getTokenByAddress(l.token,s),p=f?.decimals??18,w=f?.symbol??"tokens",u=C.formatUnits(d,p),y=C.formatUnits(c,p);return`Amount is too small to cover the estimated fee on ${m}. Amount: ${u} ${w}. Estimated fee: ${y} ${w}.`}function At(t){return t?.code===4902||t?.name==="ChainNotConfiguredError"?"This network is not configured in your wallet. Please add it manually to continue.":t?.code===4001?"Network switch cancelled. Please switch manually in your wallet to continue.":"Unable to switch network. Please switch manually in your wallet to continue."}const It="https://tx-submission-api.spicenet.io",Ie=It;function kt(t,e){return typeof e=="bigint"?e.toString():e}function D(t,e=""){if(Array.isArray(t))t.forEach((r,n)=>D(r,`${e}[${n}]`));else if(t&&typeof t=="object")for(const[r,n]of Object.entries(t)){const o=e?`${e}.${r}`:r;if(!n&&(r==="user"||r==="to"||r==="from"||r==="address"))throw new $("INVALID_PARAMS",`Wallet not ready: ${o} is missing from the request. Wait a moment and retry, or log in again.`,{path:o});D(n,o)}}function ke(t){return typeof t.actionId=="string"&&t.actionId.length>0&&Array.isArray(t.intentIds)&&t.intentIds.length>0&&t.intentIds.every((e,r)=>typeof e=="string"&&e===`${t.actionId}/${r}`)&&(t.autoContinue===void 0||typeof t.autoContinue=="boolean")}async function K(t,e){const r={...e?.headers},n=(e?.method??"GET").toUpperCase();(e?.body!=null||n!=="GET"&&n!=="HEAD")&&(r["x-request-id"]??(r["x-request-id"]=crypto.randomUUID()));const o=await fetch(t,{...e,headers:r}),a=o.headers.get("x-request-id")??"";return Object.assign(o,{requestId:a})}function _(t,e){if(!t)return e;const r=t.error,n=(typeof t.message=="string"?t.message:"")||(r&&typeof r=="object"&&"message"in r&&typeof r.message=="string"?r.message:"")||(typeof r=="string"?r:"")||e,o=$t(t);return o&&!n.includes(o)?`${n} \u2014 ${o}`:n}async function St(t){try{return await t.json()}catch{return null}}function Bt(t){return(Array.isArray(t?.balances)?t.balances:[]).flatMap(e=>{if(!e||typeof e!="object")return[];const r=e;return[{receiptToken:typeof r.receiptToken=="string"?r.receiptToken:void 0,tokenName:String(r.tokenName??""),balanceAvailable:String(r.balanceAvailable??"0"),chainTokens:Array.isArray(r.chainTokens)?r.chainTokens.filter(n=>typeof n=="string"):r.chainTokens&&typeof r.chainTokens=="object"?r.chainTokens:r.chainTokenConfig&&typeof r.chainTokenConfig=="object"?r.chainTokenConfig:void 0,decimals:typeof r.decimals=="number"?r.decimals:void 0,balanceUsd:typeof r.balanceUsd=="number"||typeof r.balanceUsd=="string"?r.balanceUsd:null}]})}class te{constructor(){this.baseUrl=Ie,this.feeValidationAvailable=!1}setBaseUrl(e){e!==this.baseUrl&&(this.feeValidationAvailable=!1),this.baseUrl=e}getBaseUrl(){return this.baseUrl}async requestJson(e,r){const n=`${this.baseUrl}${e}`,o=await K(n,r.method&&r.method!=="GET"?{method:r.method,headers:{"Content-Type":"application/json",...r.headers},body:JSON.stringify(r.body,kt),signal:r.signal}:{headers:r.headers,signal:r.signal}),a=await o.text();let s;try{s=JSON.parse(a)}catch{s=null}if(!o.ok||!s||s.success===!1||r.ok&&!r.ok(s)){const d=_(s,r.fallbackError(o.status));throw new $(r.code??"RELAYER_ERROR",r.mapError?r.mapError(d):d,{httpStatus:o.status,requestId:o.requestId,responseBody:a,endpoint:e,...r.context})}return s}async createLimitOrder(e){try{return await this.requestJson("/orders",{method:"POST",body:e,fallbackError:r=>`Order registration failed: ${r}`})}catch(r){if(r instanceof $&&r.context.httpStatus===400)try{JSON.parse(String(r.context.responseBody??"{}"))?.submissionStatus==="rejected"&&(r.context.submissionStatus="rejected")}catch{}throw r}}async registerConditionalIntent(e){return this.requestJson("/conditional-intents",{method:"POST",body:e,fallbackError:r=>`Conditional intent registration failed: ${r}`})}async createConditionalReadToken(e){return this.requestJson("/conditional-intents/read-token",{method:"POST",body:e,fallbackError:r=>`Conditional intent read authorization failed: ${r}`})}async getConditionalIntent(e,r){return this.requestJson(`/conditional-intents/${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${r}`},fallbackError:n=>`Conditional intent status failed: ${n}`})}async listConditionalIntents(e,r){const n=new URLSearchParams({...r?.limit?{limit:String(r.limit)}:{},...r?.cursor?{cursor:r.cursor}:{}}).toString();return this.requestJson(`/conditional-intents${n?`?${n}`:""}`,{headers:{Authorization:`Bearer ${e}`},fallbackError:o=>`Conditional intent listing failed: ${o}`})}async cancelConditionalIntent(e,r){return this.requestJson(`/conditional-intents/${encodeURIComponent(e)}/cancel`,{method:"POST",body:r,fallbackError:n=>`Conditional intent cancellation failed: ${n}`})}async getLimitOrder(e){return this.requestJson(`/orders/${encodeURIComponent(e)}`,{fallbackError:r=>`Order lookup failed: ${r}`})}async listLimitOrders(e,r){const n=new URLSearchParams({user:e,...r?{after:r}:{}});return this.requestJson(`/orders?${n}`,{fallbackError:o=>`Order listing failed: ${o}`})}async cancelLimitOrder(e,r){return this.requestJson(`/orders/${encodeURIComponent(e)}/cancel`,{method:"POST",body:{signature:r},fallbackError:n=>`Order cancellation failed: ${n}`})}async supportsAutomaticContinuation(e){try{return(await this.requestJson("/actions/capabilities",{signal:e?.signal,fallbackError:r=>`Action capabilities unavailable: ${r}`})).automaticContinuation===!0}catch(r){if(r instanceof $&&r.context.httpStatus===404)return!1;throw r}}async createAction(e,r){if(D(e),r?.idempotencyKey!==void 0&&e.idempotencyKey!==void 0&&r.idempotencyKey.toLowerCase()!==e.idempotencyKey.toLowerCase())throw new $("INVALID_PARAMS","Action idempotency keys must identify the same original submission.");const n=this.baseUrl,o=new te;o.setBaseUrl(n);const a=r?.idempotencyKey??e.idempotencyKey??`0x${Array.from(crypto.getRandomValues(new Uint8Array(32)),i=>i.toString(16).padStart(2,"0")).join("")}`;if(!/^0x[0-9a-f]{64}$/i.test(a))throw new $("INVALID_PARAMS","Action idempotency key must be exactly 32 bytes.");const s=r?.autoContinue??e.autoContinue,d={...e,idempotencyKey:a,...s!==void 0?{autoContinue:s}:{}},c=i=>{try{r?.onAccepted?.(i)}catch(l){console.warn("[relayer] accepted-action progress callback failed",l)}};try{const i=await o.requestJson("/actions",{method:"POST",body:d,signal:r?.signal,fallbackError:l=>`Relayer API error: ${l}`,ok:ke});return c(i),i}catch(i){const l=i instanceof $?i.context:{};let m=l.httpStatus===401||l.httpStatus===403;if(l.httpStatus===400)try{m=JSON.parse(String(l.responseBody??"{}"))?.submissionStatus==="rejected"}catch{}for(let f=0;f<3;f++){f&&await new Promise(w=>setTimeout(w,1e3));let p;try{p=await o.getActionBySubmission(e.user,a)}catch{continue}if(p)return c(p),p;if(m&&i instanceof $)throw new $(i.code,i.message,{...l,idempotencyKey:a,user:e.user,submissionStatus:"rejected"})}throw new $("RELAYER_ERROR","The submission outcome is unknown. Check your activity and balances before submitting again.",{...l,idempotencyKey:a,user:e.user,submissionStatus:"unknown",cause:i})}}async getWalletActions(e,r){const n=r&&"aborted"in r?{signal:r}:r,o=n?.pendingOnly?"?pendingOnly=true":"",a=await this.requestJson(`/wallets/${encodeURIComponent(e)}/actions${o}`,{signal:n?.signal,fallbackError:c=>`Action status unavailable: ${c}`}),s=c=>{throw new $("RELAYER_ERROR","Action status response is invalid.",{endpoint:`/wallets/${encodeURIComponent(e)}/actions`,reason:c})},d=e.toLowerCase();return/^0x[0-9a-f]{40}$/i.test(e)||s("requested wallet is malformed"),(!Array.isArray(a.actions)||a.actions.length>100)&&s("actions must be a bounded array"),a.actions.map(c=>{if(!c||typeof c!="object")return s("action record is malformed");const i=c,l=i.user;if(typeof l!="string"||!/^0x[0-9a-f]{40}$/i.test(l)||l.toLowerCase()!==d)return s("action owner does not match the requested wallet");if(i.autoContinue!==!0)return s("action is not owned by automatic continuation");if(typeof i.actionId!="string"||i.actionId.length===0||i.actionId.length>200||i.actionId.includes("/")||typeof i.createdAt!="string"||typeof i.status!="string"||!Array.isArray(i.intents)||i.intents.length===0||i.intents.length>100)return s("action identity or intents are malformed");const m=i.intents.map((f,p)=>{if(!f||typeof f!="object")return s("intent record is malformed");const w=f;if(w.intentId!==`${i.actionId}/${p}`||typeof w.status!="string"||!Array.isArray(w.steps)||w.steps.length>100)return s("intent identity or steps are malformed");const u=w.steps.map((y,x)=>{if(!y||typeof y!="object")return s("step record is malformed");const g=y,b=typeof g.chainId=="number"?g.chainId:typeof g.chainId=="string"&&/^[1-9]\d*$/.test(g.chainId)?Number(g.chainId):NaN;return g.index!==x||!Number.isSafeInteger(b)||b<=0||typeof g.status!="string"||g.transactionHash!==null&&typeof g.transactionHash!="string"?s("step identity or state is malformed"):{...g,index:x,chainId:b,status:g.status,transactionHash:g.transactionHash}});return{...w,intentId:w.intentId,steps:u}});return{...i,user:l,autoContinue:!0,actionId:i.actionId,createdAt:i.createdAt,status:i.status,intents:m}})}async getActionBySubmission(e,r,n){if(!/^0x[0-9a-f]{40}$/i.test(e)||!/^0x[0-9a-f]{64}$/i.test(r))throw new $("INVALID_PARAMS","Submission lookup requires a wallet address and 32-byte key.");try{return await this.requestJson(`/actions/by-submission/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,{signal:n?.signal,fallbackError:o=>`Submission lookup failed: ${o}`,ok:ke})}catch(o){if(o instanceof $&&o.context.httpStatus===404)return null;throw o}}async getIntentRecoveryStatus(e,r,n){if(!e||!Number.isSafeInteger(r)||r<0)throw new $("INVALID_PARAMS","Action recovery requires an action ID and non-negative intent index.");const o=await this.requestJson(`/actions/${encodeURIComponent(e)}/intents/${r}/recovery`,{signal:n?.signal,fallbackError:a=>`Action recovery check failed: ${a}`});if(o.status!=="completed"&&o.status!=="cancelled"&&o.status!=="unresolved")throw new $("RELAYER_ERROR","The relayer returned an unknown recovery status.",{actionId:e,intentIndex:r,recoveryStatus:o.status});return o.status}async getActionRecovery(e,r,n){return this.getIntentRecoveryStatus(e,r,n)}async estimateActionFees(e,r){D(e);const n=this.baseUrl,o=await this.requestJson("/actions/fees/estimate",{method:"POST",body:e,signal:r?.signal,fallbackError:a=>`Relayer fee estimate error: ${a}`,ok:a=>!!a.success&&!!a.data?.feeEstimate,mapError:a=>Ae(e,a)});return n===this.baseUrl&&(this.feeValidationAvailable=o.data?.supportsFeeValidation===!0),o.data.feeEstimate}canValidateActionFees(){return this.feeValidationAvailable}async validateActionFees(e,r){return D(e),(await this.requestJson("/actions/fees/validate",{method:"POST",body:e,signal:r?.signal,fallbackError:n=>`Relayer fee validation error: ${n}`,ok:n=>!!n.success&&!!n.data?.feeEstimate,mapError:n=>Ae(e,n)})).data.feeEstimate}async estimateBatchGas(e){D(e);const{signal:r,...n}=e,o=await this.requestJson("/actions/gas/estimate",{method:"POST",body:n,signal:r,fallbackError:a=>`Relayer gas estimate error: ${a}`,ok:a=>!!a.success&&!!a.data?.gasFee});return{...o.data.policy?{policy:o.data.policy}:{},gasFee:BigInt(o.data.gasFee),gasQuoteSource:o.data.gasQuoteSource,simulationVerified:o.data.simulationVerified===!0,platformFee:o.data.platformFee===void 0?void 0:BigInt(o.data.platformFee)}}async executeStep(e,r,n,o){const a=`${this.baseUrl}/actions/${e}/intents/${r}/steps/${n}`,s=`/actions/${e}/intents/${r}/steps/${n}`,d=crypto.randomUUID(),c=3e4,i=new Promise((f,p)=>setTimeout(()=>p(new $("RELAYER_EXECUTE_ERROR",`Execute step request timed out after ${c/1e3}s`,{actionId:e,intentIndex:r,stepIndex:n,endpoint:s,requestId:d})),c)),l=await Promise.race([K(a,{method:"POST",headers:{"Content-Type":"application/json","x-request-id":d},body:JSON.stringify(o)}),i]),m=await l.json();if(!l.ok||m.success===!1)throw new $("RELAYER_EXECUTE_ERROR",_(m,`Execute step error: ${l.status}`),{httpStatus:l.status,requestId:l.requestId,responseBody:JSON.stringify(m),endpoint:s,actionId:e});if(m?.status==="error"||m?.status==="reverted"){const f=_(m,""),p=f?`: ${f}`:"";throw new $("RELAYER_EXECUTE_ERROR",`Step ${n} previously ${m.status}${p}`,{httpStatus:l.status,requestId:l.requestId,responseBody:JSON.stringify(m),endpoint:s,actionId:e,intentIndex:r,stepIndex:n,stepStatus:m.status})}return{success:!0,status:m.status,transactionHash:m.transactionHash}}async checkStepStatus(e,r,n=!1){const o=typeof n=="boolean"?n:n.includeExecutionStatus===!0,a=e.split("/"),s=a[0],d=a.length>=2?a[1]:"0",c=await this.requestJson(`/actions/${s}/intents/${d}/steps/${r}${o?"?includeExecutionStatus=true":""}`,{signal:typeof n=="boolean"?void 0:n.signal,fallbackError:i=>`Intent step status check failed: ${i}`,code:"RELAYER_STATUS_ERROR",context:{intentId:e}});return{success:!0,data:{status:c.status==="error"?"reverted":c.status,transactionHash:c.txid,error:_(c,""),...c.executionStatus==="success"||c.executionStatus==="reverted"?{executionStatus:c.executionStatus}:{}}}}async createWallet(e,r){return this.requestJson(`/wallets/${e}`,{method:"PUT",body:r,fallbackError:n=>`Create wallet error: ${n}`})}async getWallet(e){return this.requestJson(`/wallets/${e}`,{fallbackError:r=>`Get wallet error: ${r}`})}async createWithdrawal(e){return this.requestJson("/withdrawals",{method:"POST",body:e,fallbackError:r=>`Create withdrawal error: ${r}`})}async getWithdrawal(e){return this.requestJson(`/withdrawals/${e}`,{fallbackError:r=>`Get withdrawal error: ${r}`})}async getRollupTimestamp(){return this.requestJson("/time",{fallbackError:e=>`Get rollup timestamp error: ${e}`})}}const q=new te;async function Tt(t){const e=`${q.getBaseUrl()}/wallets/${t}/balance`,r=await K(e,{cache:"no-store"}),n=await St(r);if(!r.ok||n?.success===!1)throw new $("RELAYER_ERROR",_(n,`Unable to verify Spice balance: ${r.status}`),{httpStatus:r.status,requestId:r.requestId,responseBody:JSON.stringify(n),endpoint:`/wallets/${t}/balance`});return Bt(n)}const de=new Map,Q=new Set;function ue(t){return JSON.stringify([q.getBaseUrl(),t.toLowerCase()])}function z(t,e){if(ue(t)!==e)throw new Error("Wallet backend changed during registration. Please retry.")}function Rt(t){if(!(t instanceof $))return!1;const e=t.context.httpStatus;return e===400||e===404?`${t.message} ${String(t.context.responseBody??"")}`.toLowerCase().includes("not found"):!1}async function Se(t){const e=ue(t);if(Q.has(e))return!0;try{return await q.getWallet(t),z(t,e),Q.add(e),!0}catch(r){if(!Rt(r))throw r;return!1}}async function Be(t,e){const r=ue(t);if(Q.has(r))return;const n=de.get(r);if(n)return n;const o=(async()=>{const a=await Se(t);if(z(t,r),a)return;const{unix_timestamp:s}=await q.getRollupTimestamp();z(t,r);const d=`I am creating a new smart wallet and adding an admin wallet ethereum:0x${t.slice(2).toLowerCase()}. Nonce: ${s}`,c=await e(d);z(t,r);const i=typeof c=="string"?c:c.signature;if(!i)throw new Error("Wallet returned no smart wallet signature");await q.createWallet(t,{timestamp:s,signature:i}),z(t,r),Q.add(r)})();de.set(r,o);try{await o}finally{de.delete(r)}}const Pt=(t,e)=>{const r=o=>e?e(o):V(o),n=[];return t.forEach((o,a)=>{const s=o.calls&&o.calls.length>0,d=o.tokenTransfers&&o.tokenTransfers.length>0;!s&&!d||n.push({stepId:a,status:a===0?"processing":"pending",chainId:o.chainId,chainName:r(o.chainId),description:"Processing transaction"})}),n},Te=()=>{const t=v.useContext(Z),e=t?.mode,{isConnected:r,address:n}=ye.useAccount();let o=null,a=null,s=null,d=null,c=null;try{o=F.usePrivy(),a=F.useSign7702Authorization(),s=F.useSignMessage(),d=F.useWallets()}catch(h){c=h instanceof Error?h.message:String(h)}const{ready:i=!1,authenticated:l=!1}=o||{},m=t?.embeddedWalletAddress,f=F.getEmbeddedConnectedWallet(d?.wallets||[]),p=m||f?.address,w=e==="ondemand"&&r?n:p,u=t?.apiUrl||q.getBaseUrl(),y=JSON.stringify([e,t?.provider,t?.network,t?.apiUrl,u,w?.toLowerCase(),p?.toLowerCase(),f?.address?.toLowerCase(),o?.user?.id??null,i,l,d?.ready,e==="ondemand"&&r,c]),x=v.useRef({key:y});x.current.key!==y&&(x.current={key:y});const g=x.current,b=v.useRef({mounted:!1});v.useLayoutEffect(()=>{const h={mounted:!0};return b.current=h,()=>{h.mounted=!1}},[]);const T=()=>{const h=b.current,I=()=>{if(!h.mounted||x.current!==g||q.getBaseUrl()!==u)throw new Error("Wallet session changed before signing. Please review the action again.")};return I(),I};if(c)return e==="ondemand"&&r&&n?{isReady:!0,isAuthenticated:!0,isConnected:!0,address:n,provider:"privy",actions:{signAuthorization:async()=>{throw new Error("Not available in ondemand mode")},signMessage:async()=>{throw new Error("Not available in ondemand mode")},getEthereumProvider:async()=>{throw new Error("Not available in ondemand mode")}}}:{isReady:!1,isAuthenticated:!1,isConnected:!1,provider:null,actions:{signAuthorization:async()=>{throw new Error("Privy not available")},signMessage:async()=>{throw new Error("Privy not available")},getEthereumProvider:async()=>{throw new Error("Privy not available")}}};const P=!!p&&!!f,O={isReady:e==="ondemand"?!0:i,isAuthenticated:e==="ondemand"?!0:l||P,isConnected:e==="ondemand"?r&&!!n||i&&(l||P)&&P:i&&P,address:w,provider:"privy"},A=async(h,I,E=T())=>{if(E(),!f)throw new Error("Embedded wallet not available");const S=await f.getEthereumProvider();E();const{createWalletClient:U,custom:re}=await import("viem");E();const ne=U({account:f.address,transport:re(S)});I?.(),E();const Ve=await ne.signMessage({account:f.address,message:h});return E(),{signature:Ve}},N=async(h,I=T())=>{if(I(),s)try{const E=await s.signMessage({message:h});return I(),{signature:E.signature}}catch(E){if(I(),!f)throw E}if(!f)throw new Error("Privy sign message not available");return A(h,void 0,I)},R=async h=>{if(h(),!p)throw new Error("Embedded wallet not available for smart wallet setup");await Be(p,I=>N(I,h)),h()};return{...O,actions:{prepareSigning:async()=>{const h=T();if(!p)throw new Error("Embedded wallet not available");await Se(p),h()},signAuthorization:async(h,I)=>{const E=T();if(!a)throw new Error("Privy sign authorization not available");try{await R(E),I?.(),E();const S=await a.signAuthorization({contractAddress:h.contractAddress,chainId:h.chainId,nonce:h.nonce},{address:p});return E(),delete S.v,S}catch(S){const U=typeof S?.message=="string"?S.message:String(S?.message??S??"");throw U.includes("not configured")||U.includes("chain")?new Error(`Chain ${h.chainId} is not configured in PrivyProvider. Add this chain to your Privy dashboard or supportedChainIds.`):S}},signMessage:async(h,I)=>{const E=T();if(typeof h=="object"&&"raw"in h){if(await R(E),!f)throw new Error("Embedded wallet not available for raw signing");return A(h,I,E)}return I?.(),N(h,E)},getEthereumProvider:async()=>{if(!f)throw new Error("Embedded wallet not available");return f.getEthereumProvider()}}}},Ft="https://portal-api.spicenet.io/api/v1",fe=t=>t.replace(/\/+$/,""),Nt=(t,e)=>`${t}:${e}`;async function Ut(t,e){const r=new URLSearchParams({walletAddress:e,campaignId:"spicenet-portal",campaignGroup:"1"}),n=await fetch(`${t}/portal/mainnet/linked-portal-wallet?${r.toString()}`,{cache:"no-store"});if(!n.ok){if(n.status>=500){const o=new Error(`Failed to resolve linked portal wallet: ${n.status}`);throw o.status=n.status,o}return null}return(await n.json()).portalWalletAddress?.toLowerCase()??null}async function Wt(t,e,r){const n=new URLSearchParams({walletAddress:e,campaignId:r.campaignId,campaignGroup:r.campaignGroup,partnerId:r.partnerId}),o=await fetch(`${t}/portal/mainnet/whitelist/check?${n.toString()}`,{cache:"no-store"});if(!o.ok){const a=new Error(`Failed to check whitelist: ${o.status}`);throw a.status=o.status,a}return await o.json()}async function Lt(t,e,r,n){const o=await fetch(`${t}/portal/mainnet/link-wallet`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({campaignId:e.campaignId,campaignGroup:e.campaignGroup,partnerId:e.partnerId,externalWalletAddress:r,embeddedWalletAddress:n})});if(!o.ok)throw new Error(`Failed to link wallet: ${o.status}`)}function Re({walletAddress:t,campaignId:e,campaignGroup:r,partnerId:n,apiBaseUrl:o=Ft,enabled:a=!0,staleTime:s=5*60*1e3,refetchInterval:d=!1}={}){const{isAuthenticated:c,isConnected:i}=Te(),{externalAddress:l,embeddedAddress:m}=se(),f=t??l,p=typeof f=="string"?f.toLowerCase():void 0,w=typeof m=="string"?m.toLowerCase():void 0,u=typeof l=="string"?l.toLowerCase():void 0,y=a&&c&&i&&!!l&&!!p&&C.isAddress(p)&&!!e&&!!r&&!!n,x=v.useMemo(()=>["partner-whitelist","check",p,e,r,n,fe(o)],[p,e,r,n,o]),g=ge.useQuery({queryKey:x,enabled:y,staleTime:s,refetchInterval:d,retry:(A,N)=>{const R=N?.status;return typeof R=="number"&&R>=400&&R<500?!1:A<3},retryDelay:A=>Math.min(1e3*2**A,15e3),queryFn:async()=>{if(!p||!C.isAddress(p))throw new Error("A valid wallet address is required");if(!e||!r||!n)throw new Error("campaignId, campaignGroup, and partnerId are required");const A=fe(o),N={campaignId:e,campaignGroup:r,partnerId:n},R=await Ut(A,p);return R?Wt(A,R,N):{walletAddress:p,campaignId:e,campaignGroup:r,partnerId:n,isWhitelisted:!1,isLinkedWallet:!1,whitelistedWalletAddress:null,externalWalletAddress:p}}}),b=a&&c&&i&&!!u&&C.isAddress(u)&&!!w&&C.isAddress(w)&&!!e&&!!r&&!!n,T=ge.useMutation({mutationFn:A=>Lt(fe(o),{campaignId:e,campaignGroup:r,partnerId:n},A.external,A.embedded)}),P=v.useRef(new Set),O=T.mutate;return v.useEffect(()=>{if(!b||!u||!w||!e||!r||!n)return;const A=Nt(u,w);P.current.has(A)||(P.current.add(A),O({external:u,embedded:w}))},[b,u,w,e,r,n,O]),{isWhitelisted:g.data?.isWhitelisted??!1,whitelistCheck:g.data,checkedWalletAddress:p,externalWalletAddress:l,embeddedWalletAddress:m,isExternalWalletConnected:!!l,isWhitelistCheckEnabled:y,linkWallet:T,isWalletLinked:T.isSuccess,...g}}const Pe={assets:[],loading:!1,refreshing:!1,error:null,updatedAt:null};function Fe(){const t=new Map,e=new Map,r=new WeakMap;let n=0;function o(){let a=Pe;const s=new Map;let d,c=null,i=0,l=!1,m;const f=()=>s.forEach((u,y)=>y()),p=()=>{if(!m||!s.size)return Promise.resolve();if(c)return c;const u=++i;return a={...a,loading:a.updatedAt===null,refreshing:!0},f(),c=Promise.resolve().then(m).then(y=>{if(u!==i)return;const{assets:x,error:g=null}=Array.isArray(y)?{assets:y}:y;a={assets:x,loading:!1,refreshing:!1,error:g,updatedAt:Date.now()}},y=>{u===i&&(a={...a,loading:!1,refreshing:!1,error:y instanceof Error?y.message:"Unable to refresh balances"})}).finally(()=>{u===i&&(c=null,f(),l&&(l=!1,p()))}),c},w=()=>{clearInterval(d);const u=[...s.values()].filter(y=>y>0);u.length&&(d=setInterval(()=>void p(),Math.min(...u)))};return{snapshot:()=>a,refresh:p,invalidate:()=>c?(l=!0,c.then(()=>c??Promise.resolve())):p(),subscribe(u,y,x){return m=y,s.set(u,x),w(),p(),()=>{s.delete(u),w(),s.size||(i++,c=null,l=!1,a={...a,loading:!1,refreshing:!1})}}}}return{entry(a){let s=t.get(a);return s||(s=o(),t.set(a,s)),s},fetcherId(a){return r.has(a)||r.set(a,++n),r.get(a)},registerTokens(a){let s=!1;for(const d of a){const c=`${d.chainId}:${d.address.toLowerCase()}`;e.has(c)||(e.set(c,d),s=!0)}s&&t.forEach(d=>d.invalidate())},tokens:()=>[...e.values()],invalidate:()=>Promise.all([...t.values()].map(a=>a.invalidate())).then(()=>{})}}function Ne(t,e){return t<=0n||e<=0n?0n:(t*e+10000n-1n)/10000n}function qt(t,e,r){const n=(t>e?t-e:0n)*10000n/(10000n+r),o=Ne(n,r),a=n>0n,s=a?o+e:0n;return{netAmount:n,spicenetFee:a?o:0n,totalFee:s,grossAmount:n+s,coversFees:a}}function Ot(t,e,r){if(t===e)return!0;const n=t>e?t:e;return n===0n?!1:(t>e?t-e:e-t)*10000n<=n*r}function me(t=4e3){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("feeToleranceBps must be an integer between 0 and 10000");return t}function Ue(t,e,r){const n=BigInt(me(r));return(t>e?t-e:e-t)*10000n<=t*n}function Mt(t,e,r){return["gasFee","spicenetFee","bridgeFee"].every(n=>Ue(t[n]??0n,e[n]??0n,r))}function jt(t,e){const r=C.formatUnits(t,e);return r.includes(".")?r.replace(/\.?0+$/,"")||"0":r}function X(t){const e=BigInt(t.feeBreakdown.spicenetFee),r=BigInt(t.feeBreakdown.gasFee),n=BigInt(t.feeBreakdown.bridgeFee??"0"),o=e+r+n;return{spicenetFee:e,gasFee:r,bridgeFee:n,totalFee:o}}function Dt(t){const e=BigInt(t.quotedAmount),r=BigInt(t.totalDebit),{totalFee:n}=X(t);return e>0n||r>0n||n>0n}function _t(t){const e=BigInt(t.quotedAmount),r=BigInt(t.totalDebit),{totalFee:n}=X(t),o=e+n;return r>o?r:o}function zt(t){const e=[];for(const r of t.intents)for(const n of r.batches)e.push(BigInt(n.quotedAmount));return e.length!==1?null:e[0]}function Jt(t,e,r){return t.length===0||!t.every(n=>n.domain!=="spicenet"&&!n.tokenTransfers?.length)?null:{...e,grossAmount:r,netAmount:r,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}}function Ht(t,e){if(t.policy?.enforcement==="enforce"&&t.assessments?.some(l=>l.status==="unsupported"))throw new Error("This action does not have a supported fee assessment");const r=t.intents.flatMap(l=>l.batches).filter(Dt);if(r.length===0)return null;const n=r.filter(l=>l.chainId===e.chainId),o=n.length>0?n:r;if(o.length>1)return null;const a=o[0];if(a.paymentToken&&(a.chainId!==e.chainId||a.paymentToken.toLowerCase()!==e.tokenAddress.toLowerCase()))return null;const{gasFee:s,spicenetFee:d,bridgeFee:c,totalFee:i}=X(a);return{chainId:a.chainId,tokenAddress:e.tokenAddress,...t.policy?{feePolicy:t.policy}:{},symbol:e.symbol,decimals:e.decimals,grossAmount:_t(a),netAmount:BigInt(a.quotedAmount),totalFee:i,gasFee:s,spicenetFee:d,bridgeFee:c,gasQuoteSource:a.gasQuoteSource}}const We=(t,e=4)=>!isFinite(t)||t===0?"0":t>0&&t<1e-6?t.toFixed(12).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""):t<1e-4?t.toFixed(8).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""):t.toFixed(e).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""),Gt=t=>isFinite(t)?t>0&&t<.01?"<$0.01":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(t):"$0.00",Le=(t,e=6,r=4)=>t.length<=e+r?t:`${t.slice(0,e)}...${t.slice(-r)}`,Vt=(t,e)=>{const r=t.replace(/[^0-9.]/g,"").split("."),n=r[0]??"",o=r.slice(1).join(""),a=typeof e=="number"?Math.max(0,Math.min(e,18)):null;return r.length===1?n:`${n}.${a===null?o:o.slice(0,a)}`},Yt=(t,e=6)=>!Number.isFinite(t)||t<=0?"0":t.toFixed(Math.min(Math.max(e,0),18)).replace(/\.?0+$/,""),Kt=async t=>{try{return await navigator.clipboard.writeText(t),!0}catch(e){return console.error("Failed to copy to clipboard:",e),!1}};function Qt(t,e){return e?.length?e.some(r=>{const n=r.toLowerCase();return n===t.symbol.toLowerCase()||B.normalizeNativeTokenAddress(n).toLowerCase()===B.normalizeNativeTokenAddress(t.address).toLowerCase()||n===t.displaySymbol?.toLowerCase()||n===t.receiptTokenName?.toLowerCase()||n==="native"&&(t.isNative||B.isNativeToken(t.address))}):!0}function qe(t){return t.displaySymbol||t.symbol}function Oe(t){return t.displayName||t.displaySymbol||t.name||t.symbol}function Xt(t,e){const r=t.location==="rollup"||t._source==="spice"||!!t.receiptTokenId&&!t.location&&!t._source,n=a=>a&&e?Object.entries(e).find(([s])=>s.toLowerCase()===a.toLowerCase())?.[1]:void 0,o=r?n(t.receiptTokenId)??n(t.receiptTokenName):void 0;return{symbol:o?.symbol||o?.name||qe(t),name:o?.name||o?.symbol||Oe({...t,name:t.name||""}),logoURI:o?.logoURI===void 0?t.logoURI:o.logoURI||null}}function Zt(t){return t.displayChainName||V(t.chainId)}function er(t){if(t.balance===0n)return"0";const e=C.formatUnits(t.balance,t.decimals),r=We(Number(e));return Number(r)===0?e:r}const Me=v.createContext(void 0);function tr(){const t=v.useContext(Me);return v.useCallback(e=>Xt(e,t),[t])}const rr=["__spicenet_whitelist_blocked__"],je="spiceflow-mode",De=()=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(je);return t==="7702"?"7702":t==="non7702"?"ondemand":t==="embedded"?"7702":t==="external"?"ondemand":null}catch{return null}},nr=t=>{if(!(typeof window>"u"))try{window.localStorage.setItem(je,t==="7702"?"7702":"non7702")}catch{}},ar=()=>De()!==null,_e=v.createContext(null),Z=v.createContext(null),or=({children:t,value:e,whitelist:r})=>{const n=!!r&&r.enabled!==!1,{isWhitelisted:o,isLoading:a,whitelistCheck:s}=Re(n?r:{enabled:!1}),d=n&&!o,c=v.useMemo(()=>({...e,mode:d?"ondemand":e.mode,allowedTokens:d?rr:e.allowedTokens,isUserWhitelisted:o,isWhitelistChecking:a,isWhitelistConfigured:n,isWhitelistGateActive:d,whitelistCheck:s}),[e,n,d,o,a,s]);return k.jsx(Z.Provider,{value:c,children:t})},sr=({feeToleranceBps:t,children:e,provider:r="privy",supportedChainIds:n,allowedTokens:o,network:a="testnet",mode:s,skipFlow:d=[],nativeChainId:c,appName:i="Spicenet",apiUrl:l,theme:m,rpcOverrides:f,swapper:p,liquidityVenues:w,additionalSourceTokens:u,whitelist:y,assetDisplay:x})=>{const g=me(t);v.useEffect(()=>{if(!l)return;const U=q.getBaseUrl();return q.setBaseUrl(l),()=>q.setBaseUrl(U)},[l]),v.useEffect(()=>(we(f),()=>we(void 0)),[f]);const b=v.useMemo(()=>B.getChainIdsByNetwork(a),[a]),T=n??b,P=m??null,[O,A]=v.useState(()=>s??De()??"7702");v.useEffect(()=>{s&&A(s)},[s]);const N=v.useCallback(U=>{if(s){A(s);return}A(U),nr(U)},[s]),{embeddedAddress:R,externalAddress:h}=se(),I=JSON.stringify(f),E=v.useMemo(Fe,[a,l,I,r]),S=v.useMemo(()=>({feeToleranceBps:g,inventory:E,provider:r,supportedChainIds:T,allowedTokens:o,skipFlow:d,mode:O,setMode:N,network:a,nativeChainId:c,appName:i,apiUrl:l,rpcOverrides:f,swapper:p,liquidityVenues:w,additionalSourceTokens:u,embeddedWalletAddress:R,externalWalletAddress:h,isUserWhitelisted:null,isWhitelistChecking:!1,isWhitelistConfigured:!1,isWhitelistGateActive:!1}),[E,g,r,T,o,d,O,N,a,c,i,l,f,p,w,u,R,h]);return k.jsx(_e.Provider,{value:P,children:k.jsx(Z.Provider,{value:S,children:k.jsx(or,{value:S,whitelist:y,children:k.jsx(Me.Provider,{value:x,children:e})})})})},ir={spacing:{xs:"0.25rem",sm:"0.5rem",md:"1rem",lg:"1.5rem",xl:"2rem"},borderRadius:{sm:"0.25rem",md:"0.5rem",lg:"0.75rem",full:"9999px"},typography:{fontFamily:Y.ui,fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.75rem"},fontWeight:{normal:400,medium:500,semibold:600,bold:700}},shadows:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1)"},animation:{fast:"150ms ease-in-out",normal:"200ms ease-in-out",slow:"300ms ease-in-out"}},cr={primary:"#EA4B4B",primaryHover:"#E43838",secondary:"#f3f4f6",background:"#ffffff",surface:"#f9fafb",surfaceHover:"#f3f4f6",border:"#e5e7eb",borderHover:"#d1d5db",text:"#111827",textSecondary:"#374151",textMuted:"#6b7280",success:"#10b981",error:"#ef4444",warning:"#f59e0b",info:"#3b82f6"},lr={primary:"#EA4B4B",primaryHover:"#E43838",secondary:"#171717",background:"#141414",surface:"#1e1e1e",surfaceHover:"#2a2a2a",border:"#2d2d2d",borderHover:"#3a3a3a",text:"#ffffff",textSecondary:"#888888",textMuted:"#666666",success:"#10b981",error:"#ef4444",warning:"#f59e0b",info:"#3b82f6"},ze=(t="light")=>({mode:t,...ir,colors:t==="light"?cr:lr});function ee(t,e){const r=t.replace("#",""),n=Math.max(0,Math.round(parseInt(r.substring(0,2),16)*(1-e))),o=Math.max(0,Math.round(parseInt(r.substring(2,4),16)*(1-e))),a=Math.max(0,Math.round(parseInt(r.substring(4,6),16)*(1-e)));return`#${n.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}function dr(t,e){return{shell:e?.shell??"#141414",shellBorder:e?.shellBorder??ee(e?.shell??"#141414",.35),shellInnerBorder:e?.shellInnerBorder??ee(e?.shell??"#141414",.55),cardBg:e?.cardBg??"#1e1e1e",inputBg:e?.inputBg??"#171717",hoverBg:e?.hoverBg??"#2a2a2a",textPrimary:e?.textPrimary??"#ffffff",textSecondary:e?.textSecondary??"#888888",inputText:e?.inputText??"#e0e0e0",inputPlaceholder:e?.inputPlaceholder??"#555555",cardBorder:e?.cardBorder??"rgba(255,255,255,0.08)",inputBorder:e?.inputBorder??"rgba(255,255,255,0.10)",buttonBorder:e?.buttonBorder??"rgba(255,255,255,0.12)",successBg:e?.successBg??"#0a1f18",successBorder:e?.successBorder??"#1a4a3a",successText:e?.successText??"#6ee7b7",warningBg:e?.warningBg??"#1f1a0d",warningBorder:e?.warningBorder??"#4a3820",warningText:e?.warningText??"#fbbf24",errorBg:e?.errorBg??"#1f0d0d",errorBorder:e?.errorBorder??"#4a2020",errorText:e?.errorText??"#f87171",infoBg:e?.infoBg??"#0d1325",infoBorder:e?.infoBorder??"#2a3a5a",infoText:e?.infoText??"#60a5fa"}}function ur(t){return{shell:"#ffffff",shellBorder:"#E9E9E9",shellInnerBorder:"#D5D5D5",cardBg:"#f9fafb",inputBg:"#ffffff",hoverBg:"#f3f4f6",textPrimary:"#111827",textSecondary:"#6b7280",inputText:"#111827",inputPlaceholder:"#9ca3af",cardBorder:"#e5e7eb",inputBorder:"#d1d5db",buttonBorder:"#0e0d0b",successBg:"#d1fae5",successBorder:"#6ee7b7",successText:"#065f46",warningBg:"#fef3c7",warningBorder:"#fde68a",warningText:"#92400e",errorBg:"#fef2f2",errorBorder:"#fecaca",errorText:"#dc2626",infoBg:"#dbeafe",infoBorder:"#93c5fd",infoText:"#1e40af"}}function Je(t,e){const r=e?{...t,...e}:t,n=r.dark??!1,o=r.primaryColor,a=r.shell??(n?"#141414":"#ffffff");return{primaryColor:o,dark:n,fontFamily:r.fontFamily??'"Helvetica Neue", sans-serif',appName:r.appName??"Spicenet",logo:r.logo,borderRadius:r.borderRadius??"8px",shell:a,shellBorder:ee(a,n?.35:.085),shellInnerBorder:ee(a,n?.55:.165),card:r.card??(n?"#1e1e1e":"#f9fafb"),input:n?"#171717":"#ffffff",hover:n?"#2a2a2a":"#f3f4f6",text:r.text??(n?"#ffffff":"#111827"),textMuted:r.textMuted??(n?"#888888":"#6b7280"),inputText:n?"#e0e0e0":"#111827",inputPlaceholder:n?"#555555":"#9ca3af",border:r.border??(n?"rgba(255,255,255,0.08)":"#e5e7eb"),inputBorder:n?"rgba(255,255,255,0.10)":"#d1d5db",buttonBorder:n?"rgba(255,255,255,0.12)":"#0e0d0b",successBg:n?"#0a1f18":"#d1fae5",successBorder:n?"#1a4a3a":"#6ee7b7",successText:n?"#6ee7b7":"#065f46",warningBg:n?"#1f1a0d":"#fef3c7",warningBorder:n?"#4a3820":"#fde68a",warningText:n?"#fbbf24":"#92400e",errorBg:n?"#1f0d0d":"#fef2f2",errorBorder:n?"#4a2020":"#fecaca",errorText:n?"#f87171":"#dc2626",infoBg:n?"#0d1325":"#dbeafe",infoBorder:n?"#2a3a5a":"#93c5fd",infoText:n?"#60a5fa":"#1e40af"}}const fr=Y.mono;function He(t,e){const r=v.useContext(_e)??void 0;return v.useMemo(()=>{const n=r??{primaryColor:"#EA4B4B"},o={...t?.primaryColor?{primaryColor:t.primaryColor}:{},...t?.fontFamily?{fontFamily:t.fontFamily}:{},...e!==void 0?{dark:e}:{}},a=Je(n,o),{dark:s,primaryColor:d,appName:c}=a,i=ze(s?"dark":"light"),l={...i,colors:{...i.colors,primary:d,primaryHover:`${d}dd`},typography:{...i.typography,fontFamily:a.fontFamily}},m={shell:a.shell,shellBorder:a.shellBorder,shellInnerBorder:a.shellInnerBorder,cardBg:a.card,inputBg:a.input,hoverBg:a.hover,textPrimary:a.text,textSecondary:a.textMuted,inputText:a.inputText,inputPlaceholder:a.inputPlaceholder,cardBorder:a.border,inputBorder:a.inputBorder,buttonBorder:a.buttonBorder,successBg:a.successBg,successBorder:a.successBorder,successText:a.successText,warningBg:a.warningBg,warningBorder:a.warningBorder,warningText:a.warningText,errorBg:a.errorBg,errorBorder:a.errorBorder,errorText:a.errorText,infoBg:a.infoBg,infoBorder:a.infoBorder,infoText:a.infoText},f=t?.inputVariant?t.inputVariant==="dark":s;return{brand:r,theme:l,dark:s,appName:c,primaryColor:d,dk:m,palette:m,fontFamily:a.fontFamily,monoFont:fr,inputDark:f,cardBg:f?m.cardBg:"#E9E9E9",cardBorder:f?m.cardBorder:"#C6C6C6",textPrimary:m.textPrimary,textSecondary:m.textSecondary,subtitleText:f?m.textSecondary:"#979AA0"}},[r,t,e])}const Ge="spiceflow-spinner-keyframes";function mr(){if(typeof document>"u"||document.getElementById(Ge))return;const t=document.createElement("style");t.id=Ge,t.textContent="@keyframes spiceflow-spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}",document.head.appendChild(t)}const pe=({size:t=16,borderWidth:e=2,color:r="currentColor",style:n})=>{const o=v.useRef(!1);return v.useEffect(()=>{o.current||(mr(),o.current=!0)},[]),k.jsx("div",{role:"status","aria-label":"Loading",style:{width:`${t}px`,height:`${t}px`,border:`${e}px solid ${r}`,borderTop:`${e}px solid transparent`,borderRadius:"50%",animation:"spiceflow-spin 1s linear infinite",flexShrink:0,...n}})},J=({variant:t="primary",size:e="md",loading:r=!1,fullWidth:n=!1,disabled:o,children:a,className:s="",style:d,theme:c,styles:i,dark:l,...m})=>{const{theme:f,dark:p,palette:w}=He(i,l),u=c||f,y=l??p,[x,g]=v.useState(!1),[b,T]=v.useState(!1),P=y?w.shell:"white",O=()=>{switch(t){case"primary":return{backgroundColor:i?.button?.backgroundColor||u.colors.primary,color:i?.button?.color||"#ffffff",border:`1px solid ${i?.button?.backgroundColor||u.colors.primary}`};case"secondary":return{backgroundColor:u.colors.secondary,color:u.colors.text,border:`1px solid ${u.colors.border}`};case"success":return{backgroundColor:u.colors.success,color:u.colors.text,border:`1px solid ${u.colors.success}`};case"error":return{backgroundColor:u.colors.error,color:u.colors.text,border:`1px solid ${u.colors.error}`};case"ghost":return{backgroundColor:"transparent",color:u.colors.textSecondary,border:`1px solid ${u.colors.border}`};case"outline":{const h=i?.button?.backgroundColor||u.colors.primary,I=i?.button?.color||(y?"#ffffff":"#0e0d0b"),E=i?.button?.borderColor||(y?`${u.colors.primary}88`:"#0e0d0b"),S=o||r,U=y?"1px":"1.5px",re=i?.button?.disabledBackgroundColor||`${h}88`,ne=i?.button?.disabledColor||I;return{height:"56px",backgroundColor:S?re:b?`${h}cc`:x?`${h}ee`:h,color:S?ne:I,border:`${U} solid ${E}`,borderRadius:i?.button?.borderRadius||"12px",fontSize:"22px",fontWeight:500,fontFamily:Y.mono,opacity:S?.78:1,transform:S?"none":b?"scale(0.98)":x?"translateY(-2px)":"none",boxShadow:S?`3px 3px 0px ${P}, 4px 4px 0px ${E}`:b?`2px 2px 0px ${E}`:x?`5px 5px 0px ${P}, 6px 6px 0px ${E}`:`3px 3px 0px ${P}, 4px 4px 0px ${E}`,transition:"transform 150ms ease, box-shadow 150ms ease, background-color 150ms ease, border-color 150ms ease, color 150ms ease"}}default:return{}}},A=()=>{if(t==="outline")return{};switch(e){case"sm":return{padding:`${u.spacing.sm} ${u.spacing.md}`,fontSize:u.typography.fontSize.sm};case"md":return{padding:`${u.spacing.md} ${u.spacing.lg}`,fontSize:u.typography.fontSize.base};case"lg":return{padding:`${u.spacing.lg} ${u.spacing.xl}`,fontSize:u.typography.fontSize.lg};default:return{}}},N={borderRadius:i?.button?.borderRadius||u.borderRadius.md,fontWeight:i?.button?.fontWeight||u.typography.fontWeight.medium,fontFamily:i?.button?.fontFamily||u.typography.fontFamily,fontSize:i?.button?.fontSize||void 0,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease, opacity 150ms ease",cursor:o||r?"not-allowed":"pointer",opacity:(o||r)&&t!=="outline"?.6:1,width:n?"100%":"auto",display:"flex",alignItems:"center",justifyContent:"center",gap:u.spacing.sm,...O(),...A(),...i?.button?.fontSize&&{fontSize:i.button.fontSize}},R=o||r;return k.jsxs("button",{type:m.type??"button","data-spiceflow-focus":!0,"aria-busy":r||void 0,"aria-disabled":R||void 0,style:{...N,...d},className:s,disabled:R,onMouseEnter:h=>{g(!0),m.onMouseEnter?.(h)},onMouseLeave:h=>{g(!1),T(!1),m.onMouseLeave?.(h)},onMouseDown:h=>{T(!0),m.onMouseDown?.(h)},onMouseUp:h=>{T(!1),m.onMouseUp?.(h)},...m,children:[r&&k.jsx(pe,{size:16}),a]})},pr=({onAuthSuccess:t,onAuthError:e,theme:r="light",className:n="",buttonText:o="Login with Privy",autoTrigger:a=!1})=>{const s=ze(r),[d,c]=v.useState(!1),[i,l]=v.useState(!1),{ready:m,authenticated:f,user:p}=F.usePrivy(),{login:w}=F.useLogin(),{logout:u}=F.useLogout();v.useEffect(()=>{c(!0)},[]),v.useEffect(()=>{a&&m&&!f&&d&&!i&&(l(!0),y())},[a,m,f,d,i]),v.useEffect(()=>{if(m&&f&&p&&t){const g=p.wallet?.address||p.email?.address;g&&t(g)}},[m,f,p,t]),v.useEffect(()=>{},[m,f,e]);const y=()=>{try{w()}catch(g){const b=`Login failed: ${String(g)}`;e?e(b):console.error(b)}},x=()=>{try{u()}catch(g){const b=`Logout failed: ${String(g)}`;e?e(b):console.error(b)}};if(!d)return k.jsx("div",{className:n,children:k.jsx(J,{variant:"primary",disabled:!0,theme:s,children:o})});if(!m)return k.jsx("div",{className:n,children:k.jsx(J,{variant:"primary",disabled:!0,theme:s,children:"Loading..."})});if(f&&p){const g=p.wallet?.address||p.email?.address,b=g?Le(g):"Connected";return k.jsx("div",{className:n,children:k.jsxs(J,{variant:"primary",onClick:x,theme:s,children:["Logout (",b,")"]})})}return a?k.jsx("div",{className:n,children:k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px",flexDirection:"column",gap:"12px"},children:[k.jsx(pe,{size:40,borderWidth:3,color:"#3b82f6"}),k.jsx("p",{style:{color:"#6b7280",fontSize:"14px"},children:"Opening login..."})]})}):k.jsx("div",{className:n,children:k.jsx(J,{variant:"primary",onClick:y,theme:s,children:o})})};exports.Button=J,exports.CHAIN_CONFIGS=ct,exports.EMPTY_INVENTORY=Pe,exports.PrivyLogin=pr,exports.RELAYER_API_URL=Ie,exports.RelayerService=te,exports.SpiceFlowProvider=sr,exports.SpiceFlowProviderContext=Z,exports.SpiceflowError=$,exports.Spinner=pe,exports.addressesEqual=M,exports.amountsWithinBps=Ot,exports.buildDarkPalette=dr,exports.buildLightPalette=ur,exports.calculateBpsFee=Ne,exports.copyToClipboard=Kt,exports.createInitialSteps=Pt,exports.createInventoryStore=Fe,exports.describeChainSwitchError=At,exports.duration=L,exports.easing=W,exports.ensureSmartWallet=Be,exports.ensureWalletOnChain=ut,exports.feeAmountsWithinTolerance=Ue,exports.feeBreakdownsWithinTolerance=Mt,exports.font=Y,exports.formatAssetBalance=er,exports.formatBalance=We,exports.formatDecimalInput=Yt,exports.formatRawTokenInput=jt,exports.formatUsd=Gt,exports.getAllAssetsForChain=mt,exports.getAssetDisplayChainName=Zt,exports.getAssetDisplayName=Oe,exports.getAssetDisplaySymbol=qe,exports.getBatchFees=X,exports.getChainConfig=j,exports.getChainName=V,exports.getChainsForAssets=ft,exports.getClientForChain=ve,exports.getDelegateContractAddress=lt,exports.getEscrowFreeFeePreview=Jt,exports.getExplorerUrl=dt,exports.getRelayerErrorDetail=xt,exports.getRpcUrlForChain=G,exports.getSingleNetOutput=zt,exports.getSupplyFeePreview=Ht,exports.getTokenDecimals=pt,exports.getWalletBalanceEntries=Tt,exports.hasStoredSpiceFlowMode=ar,exports.isAssetAllowed=Qt,exports.isSpiceflowError=ie,exports.isUserRejection=Ce,exports.parseNumericInput=Vt,exports.radius=bt,exports.relayerFetch=K,exports.relayerService=q,exports.resolveFeeToleranceBps=me,exports.resolveTheme=Je,exports.sanitizeError=Et,exports.splitFeeInclusiveAmount=qt,exports.transition=wt,exports.truncateAddress=Le,exports.useAssetDisplay=tr,exports.useIsUserWhitelisted=Re,exports.useProviderWallets=se,exports.useSpiceBrand=He,exports.useWallet=Te,exports.z=yt;
1
+ "use strict";var Ye=Object.create;var he=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var Xe=Object.getPrototypeOf,Ze=Object.prototype.hasOwnProperty;var et=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Qe(e))!Ze.call(t,o)&&o!==r&&he(t,o,{get:()=>e[o],enumerable:!(n=Ke(e,o))||n.enumerable});return t};var tt=(t,e,r)=>(r=t!=null?Ye(Xe(t)):{},et(e||!t||!t.__esModule?he(r,"default",{value:t,enumerable:!0}):r,t));const k=require("react/jsx-runtime"),v=require("react"),B=require("@spicenet-io/spiceflow-core"),ge=require("@tanstack/react-query"),C=require("viem"),F=require("@privy-io/react-auth"),ye=require("wagmi"),rt=require("viem/actions");function M(t,e){return!t||!e?!1:B.isNativeToken(t)&&B.isNativeToken(e)?!0:C.isAddress(t)&&C.isAddress(e)?C.getAddress(t)===C.getAddress(e):t.toLowerCase()===e.toLowerCase()}const nt="0xcA11bde05977b3631167028862bE2a173976CA11",at={4114:"0x860aFc632a6D625B95d8B96f39ECC48E988c6962"},ot=new Set([5115]);function st(t){const e=at[t.id]??(ot.has(t.id)?void 0:nt);return C.defineChain({id:t.id,name:t.name,nativeCurrency:t.nativeCurrency,rpcUrls:{default:{http:[t.rpcUrl]}},blockExplorers:{default:{name:t.displayName,url:t.blockExplorer}},testnet:t.network==="testnet",...e?{contracts:{multicall3:{address:e}}}:{}})}const it=[1,8453,42161,4114,4663,56,137,143,11155111,421614,84532,5115,123420001114,688688,688689,46630],H=Object.fromEntries(it.map(t=>B.getChainMeta(t)).filter(t=>t!=null).map(t=>[t.id,{...t,viemChain:st(t),supportedTokens:B.getTokensForChain(t.id)}])),ct=H;let be={};const ae=new Map,we=t=>{be={...t||{}},ae.clear()},G=(t,e=be)=>{const r=e[t];return r&&typeof r=="string"&&r.length>0?r:H[t]?.rpcUrl||void 0},j=t=>H[t],V=t=>{const e=B.getChainMeta(t);return e?.displayName||e?.name||`Chain ${t}`},lt=t=>{const e=B.getDelegateContract(t);if(!e)throw new Error(`Unsupported chain ID: ${t}`);if(e.toLowerCase()==="0xd4c4a222cdd42f5c3219249a083a5abf1420e9d8")throw new Error(`Delegation is unavailable for chain ID: ${t}`);return e},dt=(t,e,r)=>{const n=j(t);return n?.blockExplorer?`${n.blockExplorer}/tx/${e}`:"#"};async function ut(t,e){const r=`0x${e.toString(16)}`;try{await t.request({method:"wallet_switchEthereumChain",params:[{chainId:r}]});return}catch(a){if(!(a?.code===4902||typeof a?.message=="string"&&a.message.includes("Unrecognized chain ID")))throw a}const n=j(e);if(!n)throw new Error(`Cannot add unknown chain ${e} to wallet`);const o=G(e);if(!o)throw new Error(`Configure SpiceFlowProvider rpcOverrides[${e}] before adding this chain.`);await t.request({method:"wallet_addEthereumChain",params:[{chainId:r,chainName:n.name||`Chain ${e}`,nativeCurrency:n.nativeCurrency||{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:[o],blockExplorerUrls:n.blockExplorer?[n.blockExplorer]:void 0}]})}const ve=(t,e)=>{const r=j(t);if(!r)throw new Error(`Unsupported chain ID: ${t}`);const n=G(t,e);if(!n)throw new Error(`No RPC URL configured for chain ID: ${t}`);const o=`${t}:${n}`,a=ae.get(o);if(a)return a;const s=C.createPublicClient({chain:r.viemChain,transport:C.http(n,{timeout:15e3,retryCount:2,retryDelay:300}),batch:{multicall:{wait:16}}});return ae.set(o,s),s},ft=t=>{const e={};return Object.values(H).forEach(r=>{const n=G(r.id,t);n&&(e[r.id]={name:r.name,chain:r.viemChain,rpcUrl:n})}),e},mt=(t,e=[])=>{const r=j(t);if(!r)return[];const n=[];if(![11155111,421614,688689].includes(t)){const a=e.find(s=>s.chainId===t&&s.isNative);a?n.push(a):n.push({address:B.ZERO_ADDRESS,name:r.nativeCurrency.name,symbol:r.nativeCurrency.symbol,decimals:r.nativeCurrency.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:void 0,isNative:!0,chainId:t})}if(!r.supportedTokens)return n;const o=n.some(a=>a.isNative);return r.supportedTokens.forEach(a=>{if(o&&B.isNativeToken(a.address))return;const s=e.find(d=>d.chainId===t&&M(d.address,a.address));s?n.push(s):n.push({address:a.address,name:a.name,symbol:a.symbol,decimals:a.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:a.logo,isNative:!1,chainId:t})}),n},pt=async(t,e,r)=>{const n=j(t);if(!n)throw new Error(`Unsupported chain ID: ${t}`);const o=e.toLowerCase(),a=n.supportedTokens?.find(d=>M(d.address,o));let s;if(B.isNativeToken(o)){if(n.nativeCurrency?.decimals==null)throw new Error(`Native currency decimals not configured for chain ${t}`);s=n.nativeCurrency.decimals}else if(a)s=a.decimals;else{if(!C.isAddress(e,{strict:!1}))throw new Error(`Could not determine decimals for invalid token address: ${e}`);const d=ve(t,r);try{s=await rt.readContract(d,{address:C.getAddress(e),abi:C.erc20Abi,functionName:"decimals"})}catch(c){throw Object.assign(new Error(`Could not determine decimals for token ${e} on chain ${t}. Check the token contract and RPC configuration, then try again.`),{cause:c})}}if(!Number.isInteger(s)||s<0||s>255)throw new Error(`Invalid token decimals for ${e} on chain ${t}. Expected an integer from 0 to 255.`);return s},ht=t=>{const e=t?.wallet;if(e?.address&&e.walletClientType==="privy"&&e.connectorType==="embedded"&&!e.imported)return e.address},xe=async(t,e)=>{if(!t?.address)throw new Error("Wallet not available");if(typeof t.getWalletClient=="function"){const r=e===void 0?[void 0]:[String(e),e,void 0];let n=null;for(const o of r)try{const a=await t.getWalletClient(o);if(a)return a}catch(a){n=a}if(n)throw n}if(typeof t.getEthereumProvider=="function"){const r=await t.getEthereumProvider(),n=e?j(e)?.viemChain:void 0;return C.createWalletClient({account:t.address,chain:n,transport:C.custom(r)})}throw new Error("Wallet client not available")},gt=async(t,e)=>{if(!t?.address)throw new Error("Wallet not available");if(typeof t.getEthereumProvider=="function")return t.getEthereumProvider();const r=await xe(t,e);return{request:n=>r.request(n)}},oe=t=>!t?.address||!C.isAddress(t.address)?null:{address:t.address,wallet:t,getWalletClient:e=>xe(t,e),getEthereumProvider:e=>gt(t,e)},se=()=>{const t=ye.useAccount(),e=t.address,r=t.connector;let n=null,o=null,a=null;try{n=F.useWallets(),o=F.usePrivy(),{wallet:a}=F.useActiveWallet()}catch{n=null,o=null,a=null}const s=n?.wallets||[],d=F.getEmbeddedConnectedWallet(s),c=d?.address||ht(o?.user),i=n?.ready&&o?.ready?s.filter(b=>C.isAddress(b.address||"")&&b.type!=="solana"&&b.connectorType!=="embedded"&&!M(b.address,c)&&(typeof b.getEthereumProvider=="function"||typeof b.getWalletClient=="function")):[],l=a?.connectorType!=="embedded"&&a?.address?i.find(b=>M(b.address,a.address)):void 0,m=M(e,c),f=t.status==="connected"&&e&&C.isAddress(e)&&typeof r?.getProvider=="function"?{address:e,connector:r,chainId:t.chainId,getEthereumProvider:()=>r.getProvider()}:null,p=!!e&&!m&&["connected","connecting","reconnecting"].includes(t.status),w=p?f||i.find(b=>M(b.address,e)):null,u=oe(d),y=oe(p?w:l),x=u?.address||c,g=oe(f)||y;return{embeddedWallet:u,externalWallet:y,embeddedAddress:x,externalAddress:y?.address,activeWallet:g,activeAddress:g?.address}},yt={base:0,raised:1,sticky:10,overlay:20,popover:40,modal:1e3,dropdown:1100,toast:1200,tooltip:1300},bt={none:"0",sm:"4px",md:"6px",card:"8px",input:"10px",shell:"9px",modal:"12px",pill:"9999px",circle:"50%"},W={out:"cubic-bezier(0.22, 1, 0.36, 1)",inOut:"cubic-bezier(0.65, 0, 0.35, 1)",linear:"linear"},L={fast:"120ms",normal:"150ms",slow:"300ms",progress:"400ms"},wt={interactive:`transform ${L.normal} ${W.out}, box-shadow ${L.normal} ${W.out}, background-color ${L.normal} ${W.out}, border-color ${L.normal} ${W.out}, color ${L.normal} ${W.out}`,color:`background-color ${L.normal} ${W.out}, border-color ${L.normal} ${W.out}, color ${L.normal} ${W.out}`,popover:`opacity ${L.normal} ${W.out}, transform ${L.normal} ${W.out}`},Y={ui:'"Helvetica Neue", sans-serif',mono:'"IBM Plex Mono", monospace'};class $ extends Error{constructor(e,r,n={}){super(r),this.code=e,this.context=n,this.name="SpiceflowError",Error.captureStackTrace&&Error.captureStackTrace(this,$)}}function ie(t){return t instanceof $}const vt=["user rejected","user denied","user cancelled","rejected the request","action_rejected","4001"];function Ee(t){if(!t)return"";if(typeof t=="string")return t;const e=t,r=e.message||e.reason||"",n=e.details||"";return`${r} ${n}`.trim()}const Ce=t=>{if(ie(t))return t.code==="WALLET_REJECTED";const e=Ee(t).toLowerCase();return vt.some(r=>e.includes(r))};let ce=null;function xt(t){return ce?.message===t?ce.detail:void 0}const Et=(t,e="Something went wrong. Please try again.")=>{if(Ce(t))return"Transaction was rejected.";if(ie(t)){const r=t.message||e,{requestId:n,httpStatus:o,responseBody:a,endpoint:s}=t.context;return(n||o||s)&&(ce={message:r,detail:{requestId:n,httpStatus:o,responseBody:a,endpoint:s}}),r}return Ee(t)||e},Ct=[...B.DELEGATE_ABI,...B.ERC20_ABI,...B.spicenetEscrowAbi,...B.uniV3SwapRouterAbi];function le(t,e=0){return e>4||t==null?[]:typeof t=="string"?t.match(/0x[0-9a-fA-F]{8,}/g)??[]:Array.isArray(t)?t.flatMap(r=>le(r,e+1)):typeof t=="object"?Object.values(t).flatMap(r=>le(r,e+1)):[]}function $e(t){try{const e=C.decodeErrorResult({abi:Ct,data:t});if(e.errorName==="Error")return String(e.args?.[0]??"");if(e.errorName==="Panic")return`Panic(${e.args?.[0]})`;if(e.errorName==="CallReverted"){const r=e.args?.[4],n=r&&r!=="0x"?$e(r):void 0;return n?`Call reverted: ${n}`:"Call reverted (no reason returned)"}return e.errorName}catch{try{const e=C.hexToString(t).replace(/\x00+$/g,"").trim();return/^[\x20-\x7e]+$/.test(e)&&e.length>1?e:void 0}catch{return}}}function $t(t){for(const e of le(t)){if(!C.isHex(e))continue;const r=$e(e);if(r)return r}}function Ae(t,e){const r=e.match(/Output amount (\d+) is insufficient after fees (\d+) on chain (\d+)/);if(!r)return e;const[,n,o,a]=r,s=Number(a),d=BigInt(n),c=BigInt(o);let i;for(const x of t.intents){const g=x.chainBatches.find(b=>b.chainId===s);if(g){i=g;break}}const l=i?.tokenTransfers.find(x=>x.from==="escrow"&&M(x.to,t.user)&&!B.isNativeToken(x.token)),m=V(s);if(!l)return`Amount is too small to cover the estimated fee on ${m}.`;const f=B.getTokenByAddress(l.token,s),p=f?.decimals??18,w=f?.symbol??"tokens",u=C.formatUnits(d,p),y=C.formatUnits(c,p);return`Amount is too small to cover the estimated fee on ${m}. Amount: ${u} ${w}. Estimated fee: ${y} ${w}.`}function At(t){return t?.code===4902||t?.name==="ChainNotConfiguredError"?"This network is not configured in your wallet. Please add it manually to continue.":t?.code===4001?"Network switch cancelled. Please switch manually in your wallet to continue.":"Unable to switch network. Please switch manually in your wallet to continue."}const It="https://tx-submission-api.spicenet.io",Ie=It;function kt(t,e){return typeof e=="bigint"?e.toString():e}function D(t,e=""){if(Array.isArray(t))t.forEach((r,n)=>D(r,`${e}[${n}]`));else if(t&&typeof t=="object")for(const[r,n]of Object.entries(t)){const o=e?`${e}.${r}`:r;if(!n&&(r==="user"||r==="to"||r==="from"||r==="address"))throw new $("INVALID_PARAMS",`Wallet not ready: ${o} is missing from the request. Wait a moment and retry, or log in again.`,{path:o});D(n,o)}}function ke(t){return typeof t.actionId=="string"&&t.actionId.length>0&&Array.isArray(t.intentIds)&&t.intentIds.length>0&&t.intentIds.every((e,r)=>typeof e=="string"&&e===`${t.actionId}/${r}`)&&(t.autoContinue===void 0||typeof t.autoContinue=="boolean")}async function K(t,e){const r={...e?.headers},n=(e?.method??"GET").toUpperCase();(e?.body!=null||n!=="GET"&&n!=="HEAD")&&(r["x-request-id"]??(r["x-request-id"]=crypto.randomUUID()));const o=await fetch(t,{...e,headers:r}),a=o.headers.get("x-request-id")??"";return Object.assign(o,{requestId:a})}function _(t,e){if(!t)return e;const r=t.error,n=(typeof t.message=="string"?t.message:"")||(r&&typeof r=="object"&&"message"in r&&typeof r.message=="string"?r.message:"")||(typeof r=="string"?r:"")||e,o=$t(t);return o&&!n.includes(o)?`${n} \u2014 ${o}`:n}async function St(t){try{return await t.json()}catch{return null}}function Bt(t){return(Array.isArray(t?.balances)?t.balances:[]).flatMap(e=>{if(!e||typeof e!="object")return[];const r=e;return[{receiptToken:typeof r.receiptToken=="string"?r.receiptToken:void 0,tokenName:String(r.tokenName??""),balanceAvailable:String(r.balanceAvailable??"0"),chainTokens:Array.isArray(r.chainTokens)?r.chainTokens.filter(n=>typeof n=="string"):r.chainTokens&&typeof r.chainTokens=="object"?r.chainTokens:r.chainTokenConfig&&typeof r.chainTokenConfig=="object"?r.chainTokenConfig:void 0,decimals:typeof r.decimals=="number"?r.decimals:void 0,balanceUsd:typeof r.balanceUsd=="number"||typeof r.balanceUsd=="string"?r.balanceUsd:null}]})}class te{constructor(){this.baseUrl=Ie,this.feeValidationAvailable=!1}setBaseUrl(e){e!==this.baseUrl&&(this.feeValidationAvailable=!1),this.baseUrl=e}getBaseUrl(){return this.baseUrl}async requestJson(e,r){const n=`${this.baseUrl}${e}`,o=await K(n,r.method&&r.method!=="GET"?{method:r.method,headers:{"Content-Type":"application/json",...r.headers},body:JSON.stringify(r.body,kt),signal:r.signal}:{headers:r.headers,signal:r.signal}),a=await o.text();let s;try{s=JSON.parse(a)}catch{s=null}if(!o.ok||!s||s.success===!1||r.ok&&!r.ok(s)){const d=_(s,r.fallbackError(o.status));throw new $(r.code??"RELAYER_ERROR",r.mapError?r.mapError(d):d,{httpStatus:o.status,requestId:o.requestId,responseBody:a,endpoint:e,...r.context})}return s}async createLimitOrder(e){try{return await this.requestJson("/orders",{method:"POST",body:e,fallbackError:r=>`Order registration failed: ${r}`})}catch(r){if(r instanceof $&&r.context.httpStatus===400)try{JSON.parse(String(r.context.responseBody??"{}"))?.submissionStatus==="rejected"&&(r.context.submissionStatus="rejected")}catch{}throw r}}async registerConditionalIntent(e){return this.requestJson("/conditional-intents",{method:"POST",body:e,fallbackError:r=>`Conditional intent registration failed: ${r}`})}async createConditionalReadToken(e){return this.requestJson("/conditional-intents/read-token",{method:"POST",body:e,fallbackError:r=>`Conditional intent read authorization failed: ${r}`})}async getConditionalIntent(e,r){return this.requestJson(`/conditional-intents/${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${r}`},fallbackError:n=>`Conditional intent status failed: ${n}`})}async listConditionalIntents(e,r){const n=new URLSearchParams({...r?.limit?{limit:String(r.limit)}:{},...r?.cursor?{cursor:r.cursor}:{}}).toString();return this.requestJson(`/conditional-intents${n?`?${n}`:""}`,{headers:{Authorization:`Bearer ${e}`},fallbackError:o=>`Conditional intent listing failed: ${o}`})}async cancelConditionalIntent(e,r){return this.requestJson(`/conditional-intents/${encodeURIComponent(e)}/cancel`,{method:"POST",body:r,fallbackError:n=>`Conditional intent cancellation failed: ${n}`})}async getLimitOrder(e){return this.requestJson(`/orders/${encodeURIComponent(e)}`,{fallbackError:r=>`Order lookup failed: ${r}`})}async listLimitOrders(e,r){const n=new URLSearchParams({user:e,...r?{after:r}:{}});return this.requestJson(`/orders?${n}`,{fallbackError:o=>`Order listing failed: ${o}`})}async cancelLimitOrder(e,r){return this.requestJson(`/orders/${encodeURIComponent(e)}/cancel`,{method:"POST",body:{signature:r},fallbackError:n=>`Order cancellation failed: ${n}`})}async supportsAutomaticContinuation(e){try{return(await this.requestJson("/actions/capabilities",{signal:e?.signal,fallbackError:r=>`Action capabilities unavailable: ${r}`})).automaticContinuation===!0}catch(r){if(r instanceof $&&r.context.httpStatus===404)return!1;throw r}}async createAction(e,r){if(D(e),r?.idempotencyKey!==void 0&&e.idempotencyKey!==void 0&&r.idempotencyKey.toLowerCase()!==e.idempotencyKey.toLowerCase())throw new $("INVALID_PARAMS","Action idempotency keys must identify the same original submission.");const n=this.baseUrl,o=new te;o.setBaseUrl(n);const a=r?.idempotencyKey??e.idempotencyKey??`0x${Array.from(crypto.getRandomValues(new Uint8Array(32)),i=>i.toString(16).padStart(2,"0")).join("")}`;if(!/^0x[0-9a-f]{64}$/i.test(a))throw new $("INVALID_PARAMS","Action idempotency key must be exactly 32 bytes.");const s=r?.autoContinue??e.autoContinue,d={...e,idempotencyKey:a,...s!==void 0?{autoContinue:s}:{}},c=i=>{try{r?.onAccepted?.(i)}catch(l){console.warn("[relayer] accepted-action progress callback failed",l)}};try{const i=await o.requestJson("/actions",{method:"POST",body:d,signal:r?.signal,fallbackError:l=>`Relayer API error: ${l}`,ok:ke});return c(i),i}catch(i){const l=i instanceof $?i.context:{};let m=l.httpStatus===401||l.httpStatus===403;if(l.httpStatus===400)try{m=JSON.parse(String(l.responseBody??"{}"))?.submissionStatus==="rejected"}catch{}for(let f=0;f<3;f++){f&&await new Promise(w=>setTimeout(w,1e3));let p;try{p=await o.getActionBySubmission(e.user,a)}catch{continue}if(p)return c(p),p;if(m&&i instanceof $)throw new $(i.code,i.message,{...l,idempotencyKey:a,user:e.user,submissionStatus:"rejected"})}throw new $("RELAYER_ERROR","The submission outcome is unknown. Check your activity and balances before submitting again.",{...l,idempotencyKey:a,user:e.user,submissionStatus:"unknown",cause:i})}}async getWalletActions(e,r){const n=r&&"aborted"in r?{signal:r}:r,o=n?.pendingOnly?"?pendingOnly=true":"",a=await this.requestJson(`/wallets/${encodeURIComponent(e)}/actions${o}`,{signal:n?.signal,fallbackError:c=>`Action status unavailable: ${c}`}),s=c=>{throw new $("RELAYER_ERROR","Action status response is invalid.",{endpoint:`/wallets/${encodeURIComponent(e)}/actions`,reason:c})},d=e.toLowerCase();return/^0x[0-9a-f]{40}$/i.test(e)||s("requested wallet is malformed"),(!Array.isArray(a.actions)||a.actions.length>100)&&s("actions must be a bounded array"),a.actions.map(c=>{if(!c||typeof c!="object")return s("action record is malformed");const i=c,l=i.user;if(typeof l!="string"||!/^0x[0-9a-f]{40}$/i.test(l)||l.toLowerCase()!==d)return s("action owner does not match the requested wallet");if(i.autoContinue!==!0)return s("action is not owned by automatic continuation");if(typeof i.actionId!="string"||i.actionId.length===0||i.actionId.length>200||i.actionId.includes("/")||typeof i.createdAt!="string"||typeof i.status!="string"||!Array.isArray(i.intents)||i.intents.length===0||i.intents.length>100)return s("action identity or intents are malformed");const m=i.intents.map((f,p)=>{if(!f||typeof f!="object")return s("intent record is malformed");const w=f;if(w.intentId!==`${i.actionId}/${p}`||typeof w.status!="string"||!Array.isArray(w.steps)||w.steps.length>100)return s("intent identity or steps are malformed");const u=w.steps.map((y,x)=>{if(!y||typeof y!="object")return s("step record is malformed");const g=y,b=typeof g.chainId=="number"?g.chainId:typeof g.chainId=="string"&&/^[1-9]\d*$/.test(g.chainId)?Number(g.chainId):NaN;return g.index!==x||!Number.isSafeInteger(b)||b<=0||typeof g.status!="string"||g.transactionHash!==null&&typeof g.transactionHash!="string"?s("step identity or state is malformed"):{...g,index:x,chainId:b,status:g.status,transactionHash:g.transactionHash}});return{...w,intentId:w.intentId,steps:u}});return{...i,user:l,autoContinue:!0,actionId:i.actionId,createdAt:i.createdAt,status:i.status,intents:m}})}async getActionBySubmission(e,r,n){if(!/^0x[0-9a-f]{40}$/i.test(e)||!/^0x[0-9a-f]{64}$/i.test(r))throw new $("INVALID_PARAMS","Submission lookup requires a wallet address and 32-byte key.");try{return await this.requestJson(`/actions/by-submission/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,{signal:n?.signal,fallbackError:o=>`Submission lookup failed: ${o}`,ok:ke})}catch(o){if(o instanceof $&&o.context.httpStatus===404)return null;throw o}}async getIntentRecoveryStatus(e,r,n){if(!e||!Number.isSafeInteger(r)||r<0)throw new $("INVALID_PARAMS","Action recovery requires an action ID and non-negative intent index.");const o=await this.requestJson(`/actions/${encodeURIComponent(e)}/intents/${r}/recovery`,{signal:n?.signal,fallbackError:a=>`Action recovery check failed: ${a}`});if(o.status!=="completed"&&o.status!=="cancelled"&&o.status!=="unresolved")throw new $("RELAYER_ERROR","The relayer returned an unknown recovery status.",{actionId:e,intentIndex:r,recoveryStatus:o.status});return o.status}async getActionRecovery(e,r,n){return this.getIntentRecoveryStatus(e,r,n)}async estimateActionFees(e,r){D(e);const n=this.baseUrl,o=await this.requestJson("/actions/fees/estimate",{method:"POST",body:e,signal:r?.signal,fallbackError:a=>`Relayer fee estimate error: ${a}`,ok:a=>!!a.success&&!!a.data?.feeEstimate,mapError:a=>Ae(e,a)});return n===this.baseUrl&&(this.feeValidationAvailable=o.data?.supportsFeeValidation===!0),o.data.feeEstimate}canValidateActionFees(){return this.feeValidationAvailable}async validateActionFees(e,r){return D(e),(await this.requestJson("/actions/fees/validate",{method:"POST",body:e,signal:r?.signal,fallbackError:n=>`Relayer fee validation error: ${n}`,ok:n=>!!n.success&&!!n.data?.feeEstimate,mapError:n=>Ae(e,n)})).data.feeEstimate}async estimateBatchGas(e){D(e);const{signal:r,...n}=e,o=await this.requestJson("/actions/gas/estimate",{method:"POST",body:n,signal:r,fallbackError:a=>`Relayer gas estimate error: ${a}`,ok:a=>!!a.success&&!!a.data?.gasFee});return{...o.data.policy?{policy:o.data.policy}:{},gasFee:BigInt(o.data.gasFee),gasQuoteSource:o.data.gasQuoteSource,simulationVerified:o.data.simulationVerified===!0,platformFee:o.data.platformFee===void 0?void 0:BigInt(o.data.platformFee)}}async executeStep(e,r,n,o){const a=`${this.baseUrl}/actions/${e}/intents/${r}/steps/${n}`,s=`/actions/${e}/intents/${r}/steps/${n}`,d=crypto.randomUUID(),c=3e4,i=new Promise((f,p)=>setTimeout(()=>p(new $("RELAYER_EXECUTE_ERROR",`Execute step request timed out after ${c/1e3}s`,{actionId:e,intentIndex:r,stepIndex:n,endpoint:s,requestId:d})),c)),l=await Promise.race([K(a,{method:"POST",headers:{"Content-Type":"application/json","x-request-id":d},body:JSON.stringify(o)}),i]),m=await l.json();if(!l.ok||m.success===!1)throw new $("RELAYER_EXECUTE_ERROR",_(m,`Execute step error: ${l.status}`),{httpStatus:l.status,requestId:l.requestId,responseBody:JSON.stringify(m),endpoint:s,actionId:e});if(m?.status==="error"||m?.status==="reverted"){const f=_(m,""),p=f?`: ${f}`:"";throw new $("RELAYER_EXECUTE_ERROR",`Step ${n} previously ${m.status}${p}`,{httpStatus:l.status,requestId:l.requestId,responseBody:JSON.stringify(m),endpoint:s,actionId:e,intentIndex:r,stepIndex:n,stepStatus:m.status})}return{success:!0,status:m.status,transactionHash:m.transactionHash}}async checkStepStatus(e,r,n=!1){const o=typeof n=="boolean"?n:n.includeExecutionStatus===!0,a=e.split("/"),s=a[0],d=a.length>=2?a[1]:"0",c=await this.requestJson(`/actions/${s}/intents/${d}/steps/${r}${o?"?includeExecutionStatus=true":""}`,{signal:typeof n=="boolean"?void 0:n.signal,fallbackError:i=>`Intent step status check failed: ${i}`,code:"RELAYER_STATUS_ERROR",context:{intentId:e}});return{success:!0,data:{status:c.status==="error"?"reverted":c.status,transactionHash:c.txid,error:_(c,""),...c.executionStatus==="success"||c.executionStatus==="reverted"?{executionStatus:c.executionStatus}:{}}}}async createWallet(e,r){return this.requestJson(`/wallets/${e}`,{method:"PUT",body:r,fallbackError:n=>`Create wallet error: ${n}`})}async getWallet(e){return this.requestJson(`/wallets/${e}`,{fallbackError:r=>`Get wallet error: ${r}`})}async createWithdrawal(e){return this.requestJson("/withdrawals",{method:"POST",body:e,fallbackError:r=>`Create withdrawal error: ${r}`})}async getWithdrawal(e){return this.requestJson(`/withdrawals/${e}`,{fallbackError:r=>`Get withdrawal error: ${r}`})}async getRollupTimestamp(){return this.requestJson("/time",{fallbackError:e=>`Get rollup timestamp error: ${e}`})}}const q=new te;async function Tt(t){const e=`${q.getBaseUrl()}/wallets/${t}/balance`,r=await K(e,{cache:"no-store"}),n=await St(r);if(!r.ok||n?.success===!1)throw new $("RELAYER_ERROR",_(n,`Unable to verify Spice balance: ${r.status}`),{httpStatus:r.status,requestId:r.requestId,responseBody:JSON.stringify(n),endpoint:`/wallets/${t}/balance`});return Bt(n)}const de=new Map,Q=new Set;function ue(t){return JSON.stringify([q.getBaseUrl(),t.toLowerCase()])}function z(t,e){if(ue(t)!==e)throw new Error("Wallet backend changed during registration. Please retry.")}function Rt(t){if(!(t instanceof $))return!1;const e=t.context.httpStatus;return e===400||e===404?`${t.message} ${String(t.context.responseBody??"")}`.toLowerCase().includes("not found"):!1}async function Se(t){const e=ue(t);if(Q.has(e))return!0;try{return await q.getWallet(t),z(t,e),Q.add(e),!0}catch(r){if(!Rt(r))throw r;return!1}}async function Be(t,e){const r=ue(t);if(Q.has(r))return;const n=de.get(r);if(n)return n;const o=(async()=>{const a=await Se(t);if(z(t,r),a)return;const{unix_timestamp:s}=await q.getRollupTimestamp();z(t,r);const d=`I am creating a new smart wallet and adding an admin wallet ethereum:0x${t.slice(2).toLowerCase()}. Nonce: ${s}`,c=await e(d);z(t,r);const i=typeof c=="string"?c:c.signature;if(!i)throw new Error("Wallet returned no smart wallet signature");await q.createWallet(t,{timestamp:s,signature:i}),z(t,r),Q.add(r)})();de.set(r,o);try{await o}finally{de.delete(r)}}const Pt=(t,e)=>{const r=o=>e?e(o):V(o),n=[];return t.forEach((o,a)=>{const s=o.calls&&o.calls.length>0,d=o.tokenTransfers&&o.tokenTransfers.length>0;!s&&!d||n.push({stepId:a,status:a===0?"processing":"pending",chainId:o.chainId,chainName:r(o.chainId),description:"Processing transaction"})}),n},Te=()=>{const t=v.useContext(Z),e=t?.mode,{isConnected:r,address:n}=ye.useAccount();let o=null,a=null,s=null,d=null,c=null;try{o=F.usePrivy(),a=F.useSign7702Authorization(),s=F.useSignMessage(),d=F.useWallets()}catch(h){c=h instanceof Error?h.message:String(h)}const{ready:i=!1,authenticated:l=!1}=o||{},m=t?.embeddedWalletAddress,f=F.getEmbeddedConnectedWallet(d?.wallets||[]),p=m||f?.address,w=e==="ondemand"&&r?n:p,u=t?.apiUrl||q.getBaseUrl(),y=JSON.stringify([e,t?.provider,t?.network,t?.apiUrl,u,w?.toLowerCase(),p?.toLowerCase(),f?.address?.toLowerCase(),o?.user?.id??null,i,l,d?.ready,e==="ondemand"&&r,c]),x=v.useRef({key:y});x.current.key!==y&&(x.current={key:y});const g=x.current,b=v.useRef({mounted:!1});v.useLayoutEffect(()=>{const h={mounted:!0};return b.current=h,()=>{h.mounted=!1}},[]);const T=()=>{const h=b.current,I=()=>{if(!h.mounted||x.current!==g||q.getBaseUrl()!==u)throw new Error("Wallet session changed before signing. Please review the action again.")};return I(),I};if(c)return e==="ondemand"&&r&&n?{isReady:!0,isAuthenticated:!0,isConnected:!0,address:n,provider:"privy",actions:{signAuthorization:async()=>{throw new Error("Not available in ondemand mode")},signMessage:async()=>{throw new Error("Not available in ondemand mode")},getEthereumProvider:async()=>{throw new Error("Not available in ondemand mode")}}}:{isReady:!1,isAuthenticated:!1,isConnected:!1,provider:null,actions:{signAuthorization:async()=>{throw new Error("Privy not available")},signMessage:async()=>{throw new Error("Privy not available")},getEthereumProvider:async()=>{throw new Error("Privy not available")}}};const P=!!p&&!!f,O={isReady:e==="ondemand"?!0:i,isAuthenticated:e==="ondemand"?!0:l||P,isConnected:e==="ondemand"?r&&!!n||i&&(l||P)&&P:i&&P,address:w,provider:"privy"},A=async(h,I,E=T())=>{if(E(),!f)throw new Error("Embedded wallet not available");const S=await f.getEthereumProvider();E();const{createWalletClient:U,custom:re}=await import("viem");E();const ne=U({account:f.address,transport:re(S)});I?.(),E();const Ve=await ne.signMessage({account:f.address,message:h});return E(),{signature:Ve}},N=async(h,I=T())=>{if(I(),s)try{const E=await s.signMessage({message:h});return I(),{signature:E.signature}}catch(E){if(I(),!f)throw E}if(!f)throw new Error("Privy sign message not available");return A(h,void 0,I)},R=async h=>{if(h(),!p)throw new Error("Embedded wallet not available for smart wallet setup");await Be(p,I=>N(I,h)),h()};return{...O,actions:{prepareSigning:async()=>{const h=T();if(!p)throw new Error("Embedded wallet not available");await Se(p),h()},signAuthorization:async(h,I)=>{const E=T();if(!a)throw new Error("Privy sign authorization not available");try{await R(E),I?.(),E();const S=await a.signAuthorization({contractAddress:h.contractAddress,chainId:h.chainId,nonce:h.nonce},{address:p});return E(),delete S.v,S}catch(S){const U=typeof S?.message=="string"?S.message:String(S?.message??S??"");throw U.includes("not configured")||U.includes("chain")?new Error(`Chain ${h.chainId} is not configured in PrivyProvider. Add this chain to your Privy dashboard or supportedChainIds.`):S}},signMessage:async(h,I)=>{const E=T();if(typeof h=="object"&&"raw"in h){if(await R(E),!f)throw new Error("Embedded wallet not available for raw signing");return A(h,I,E)}return I?.(),N(h,E)},getEthereumProvider:async()=>{if(!f)throw new Error("Embedded wallet not available");return f.getEthereumProvider()}}}},Ft="https://portal-api.spicenet.io/api/v1",fe=t=>t.replace(/\/+$/,""),Nt=(t,e)=>`${t}:${e}`;async function Ut(t,e){const r=new URLSearchParams({walletAddress:e,campaignId:"spicenet-portal",campaignGroup:"1"}),n=await fetch(`${t}/portal/mainnet/linked-portal-wallet?${r.toString()}`,{cache:"no-store"});if(!n.ok){if(n.status>=500){const o=new Error(`Failed to resolve linked portal wallet: ${n.status}`);throw o.status=n.status,o}return null}return(await n.json()).portalWalletAddress?.toLowerCase()??null}async function Wt(t,e,r){const n=new URLSearchParams({walletAddress:e,campaignId:r.campaignId,campaignGroup:r.campaignGroup,partnerId:r.partnerId}),o=await fetch(`${t}/portal/mainnet/whitelist/check?${n.toString()}`,{cache:"no-store"});if(!o.ok){const a=new Error(`Failed to check whitelist: ${o.status}`);throw a.status=o.status,a}return await o.json()}async function Lt(t,e,r,n){const o=await fetch(`${t}/portal/mainnet/link-wallet`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({campaignId:e.campaignId,campaignGroup:e.campaignGroup,partnerId:e.partnerId,externalWalletAddress:r,embeddedWalletAddress:n})});if(!o.ok)throw new Error(`Failed to link wallet: ${o.status}`)}function Re({walletAddress:t,campaignId:e,campaignGroup:r,partnerId:n,apiBaseUrl:o=Ft,enabled:a=!0,staleTime:s=5*60*1e3,refetchInterval:d=!1}={}){const{isAuthenticated:c,isConnected:i}=Te(),{externalAddress:l,embeddedAddress:m}=se(),f=t??l,p=typeof f=="string"?f.toLowerCase():void 0,w=typeof m=="string"?m.toLowerCase():void 0,u=typeof l=="string"?l.toLowerCase():void 0,y=a&&c&&i&&!!l&&!!p&&C.isAddress(p)&&!!e&&!!r&&!!n,x=v.useMemo(()=>["partner-whitelist","check",p,e,r,n,fe(o)],[p,e,r,n,o]),g=ge.useQuery({queryKey:x,enabled:y,staleTime:s,refetchInterval:d,retry:(A,N)=>{const R=N?.status;return typeof R=="number"&&R>=400&&R<500?!1:A<3},retryDelay:A=>Math.min(1e3*2**A,15e3),queryFn:async()=>{if(!p||!C.isAddress(p))throw new Error("A valid wallet address is required");if(!e||!r||!n)throw new Error("campaignId, campaignGroup, and partnerId are required");const A=fe(o),N={campaignId:e,campaignGroup:r,partnerId:n},R=await Ut(A,p);return R?Wt(A,R,N):{walletAddress:p,campaignId:e,campaignGroup:r,partnerId:n,isWhitelisted:!1,isLinkedWallet:!1,whitelistedWalletAddress:null,externalWalletAddress:p}}}),b=a&&c&&i&&!!u&&C.isAddress(u)&&!!w&&C.isAddress(w)&&!!e&&!!r&&!!n,T=ge.useMutation({mutationFn:A=>Lt(fe(o),{campaignId:e,campaignGroup:r,partnerId:n},A.external,A.embedded)}),P=v.useRef(new Set),O=T.mutate;return v.useEffect(()=>{if(!b||!u||!w||!e||!r||!n)return;const A=Nt(u,w);P.current.has(A)||(P.current.add(A),O({external:u,embedded:w}))},[b,u,w,e,r,n,O]),{isWhitelisted:g.data?.isWhitelisted??!1,whitelistCheck:g.data,checkedWalletAddress:p,externalWalletAddress:l,embeddedWalletAddress:m,isExternalWalletConnected:!!l,isWhitelistCheckEnabled:y,linkWallet:T,isWalletLinked:T.isSuccess,...g}}const Pe={assets:[],loading:!1,refreshing:!1,error:null,updatedAt:null};function Fe(){const t=new Map,e=new Map,r=new WeakMap;let n=0;function o(){let a=Pe;const s=new Map;let d,c=null,i=0,l=!1,m;const f=()=>s.forEach((u,y)=>y()),p=()=>{if(!m||!s.size)return Promise.resolve();if(c)return c;const u=++i;return a={...a,loading:a.updatedAt===null,refreshing:!0},f(),c=Promise.resolve().then(m).then(y=>{if(u!==i)return;const{assets:x,error:g=null}=Array.isArray(y)?{assets:y}:y;a={assets:x,loading:!1,refreshing:!1,error:g,updatedAt:Date.now()}},y=>{u===i&&(a={...a,loading:!1,refreshing:!1,error:y instanceof Error?y.message:"Unable to refresh balances"})}).finally(()=>{u===i&&(c=null,f(),l&&(l=!1,p()))}),c},w=()=>{clearInterval(d);const u=[...s.values()].filter(y=>y>0);u.length&&(d=setInterval(()=>void p(),Math.min(...u)))};return{snapshot:()=>a,refresh:p,invalidate:()=>c?(l=!0,c.then(()=>c??Promise.resolve())):p(),subscribe(u,y,x){return m=y,s.set(u,x),w(),p(),()=>{s.delete(u),w(),s.size||(i++,c=null,l=!1,a={...a,loading:!1,refreshing:!1})}}}}return{entry(a){let s=t.get(a);return s||(s=o(),t.set(a,s)),s},fetcherId(a){return r.has(a)||r.set(a,++n),r.get(a)},registerTokens(a){let s=!1;for(const d of a){const c=`${d.chainId}:${d.address.toLowerCase()}`;e.has(c)||(e.set(c,d),s=!0)}s&&t.forEach(d=>d.invalidate())},tokens:()=>[...e.values()],invalidate:()=>Promise.all([...t.values()].map(a=>a.invalidate())).then(()=>{})}}function Ne(t,e){return t<=0n||e<=0n?0n:(t*e+10000n-1n)/10000n}function qt(t,e,r){const n=(t>e?t-e:0n)*10000n/(10000n+r),o=Ne(n,r),a=n>0n,s=a?o+e:0n;return{netAmount:n,spicenetFee:a?o:0n,totalFee:s,grossAmount:n+s,coversFees:a}}function Ot(t,e,r){if(t===e)return!0;const n=t>e?t:e;return n===0n?!1:(t>e?t-e:e-t)*10000n<=n*r}function me(t=2e4){if(!Number.isSafeInteger(t)||t<0)throw new Error("feeToleranceBps must be a non-negative safe integer");return t}function Ue(t,e,r){const n=BigInt(me(r));return(t>e?t-e:e-t)*10000n<=t*n}function Mt(t,e,r){return["gasFee","spicenetFee","bridgeFee"].every(n=>Ue(t[n]??0n,e[n]??0n,r))}function jt(t,e){const r=C.formatUnits(t,e);return r.includes(".")?r.replace(/\.?0+$/,"")||"0":r}function X(t){const e=BigInt(t.feeBreakdown.spicenetFee),r=BigInt(t.feeBreakdown.gasFee),n=BigInt(t.feeBreakdown.bridgeFee??"0"),o=e+r+n;return{spicenetFee:e,gasFee:r,bridgeFee:n,totalFee:o}}function Dt(t){const e=BigInt(t.quotedAmount),r=BigInt(t.totalDebit),{totalFee:n}=X(t);return e>0n||r>0n||n>0n}function _t(t){const e=BigInt(t.quotedAmount),r=BigInt(t.totalDebit),{totalFee:n}=X(t),o=e+n;return r>o?r:o}function zt(t){const e=[];for(const r of t.intents)for(const n of r.batches)e.push(BigInt(n.quotedAmount));return e.length!==1?null:e[0]}function Jt(t,e,r){return t.length===0||!t.every(n=>n.domain!=="spicenet"&&!n.tokenTransfers?.length)?null:{...e,grossAmount:r,netAmount:r,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}}function Ht(t,e){if(t.policy?.enforcement==="enforce"&&t.assessments?.some(l=>l.status==="unsupported"))throw new Error("This action does not have a supported fee assessment");const r=t.intents.flatMap(l=>l.batches).filter(Dt);if(r.length===0)return null;const n=r.filter(l=>l.chainId===e.chainId),o=n.length>0?n:r;if(o.length>1)return null;const a=o[0];if(a.paymentToken&&(a.chainId!==e.chainId||a.paymentToken.toLowerCase()!==e.tokenAddress.toLowerCase()))return null;const{gasFee:s,spicenetFee:d,bridgeFee:c,totalFee:i}=X(a);return{chainId:a.chainId,tokenAddress:e.tokenAddress,...t.policy?{feePolicy:t.policy}:{},symbol:e.symbol,decimals:e.decimals,grossAmount:_t(a),netAmount:BigInt(a.quotedAmount),totalFee:i,gasFee:s,spicenetFee:d,bridgeFee:c,gasQuoteSource:a.gasQuoteSource}}const We=(t,e=4)=>!isFinite(t)||t===0?"0":t>0&&t<1e-6?t.toFixed(12).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""):t<1e-4?t.toFixed(8).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""):t.toFixed(e).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""),Gt=t=>isFinite(t)?t>0&&t<.01?"<$0.01":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(t):"$0.00",Le=(t,e=6,r=4)=>t.length<=e+r?t:`${t.slice(0,e)}...${t.slice(-r)}`,Vt=(t,e)=>{const r=t.replace(/[^0-9.]/g,"").split("."),n=r[0]??"",o=r.slice(1).join(""),a=typeof e=="number"?Math.max(0,Math.min(e,18)):null;return r.length===1?n:`${n}.${a===null?o:o.slice(0,a)}`},Yt=(t,e=6)=>!Number.isFinite(t)||t<=0?"0":t.toFixed(Math.min(Math.max(e,0),18)).replace(/\.?0+$/,""),Kt=async t=>{try{return await navigator.clipboard.writeText(t),!0}catch(e){return console.error("Failed to copy to clipboard:",e),!1}};function Qt(t,e){return e?.length?e.some(r=>{const n=r.toLowerCase();return n===t.symbol.toLowerCase()||B.normalizeNativeTokenAddress(n).toLowerCase()===B.normalizeNativeTokenAddress(t.address).toLowerCase()||n===t.displaySymbol?.toLowerCase()||n===t.receiptTokenName?.toLowerCase()||n==="native"&&(t.isNative||B.isNativeToken(t.address))}):!0}function qe(t){return t.displaySymbol||t.symbol}function Oe(t){return t.displayName||t.displaySymbol||t.name||t.symbol}function Xt(t,e){const r=t.location==="rollup"||t._source==="spice"||!!t.receiptTokenId&&!t.location&&!t._source,n=a=>a&&e?Object.entries(e).find(([s])=>s.toLowerCase()===a.toLowerCase())?.[1]:void 0,o=r?n(t.receiptTokenId)??n(t.receiptTokenName):void 0;return{symbol:o?.symbol||o?.name||qe(t),name:o?.name||o?.symbol||Oe({...t,name:t.name||""}),logoURI:o?.logoURI===void 0?t.logoURI:o.logoURI||null}}function Zt(t){return t.displayChainName||V(t.chainId)}function er(t){if(t.balance===0n)return"0";const e=C.formatUnits(t.balance,t.decimals),r=We(Number(e));return Number(r)===0?e:r}const Me=v.createContext(void 0);function tr(){const t=v.useContext(Me);return v.useCallback(e=>Xt(e,t),[t])}const rr=["__spicenet_whitelist_blocked__"],je="spiceflow-mode",De=()=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(je);return t==="7702"?"7702":t==="non7702"?"ondemand":t==="embedded"?"7702":t==="external"?"ondemand":null}catch{return null}},nr=t=>{if(!(typeof window>"u"))try{window.localStorage.setItem(je,t==="7702"?"7702":"non7702")}catch{}},ar=()=>De()!==null,_e=v.createContext(null),Z=v.createContext(null),or=({children:t,value:e,whitelist:r})=>{const n=!!r&&r.enabled!==!1,{isWhitelisted:o,isLoading:a,whitelistCheck:s}=Re(n?r:{enabled:!1}),d=n&&!o,c=v.useMemo(()=>({...e,mode:d?"ondemand":e.mode,allowedTokens:d?rr:e.allowedTokens,isUserWhitelisted:o,isWhitelistChecking:a,isWhitelistConfigured:n,isWhitelistGateActive:d,whitelistCheck:s}),[e,n,d,o,a,s]);return k.jsx(Z.Provider,{value:c,children:t})},sr=({feeToleranceBps:t,children:e,provider:r="privy",supportedChainIds:n,allowedTokens:o,network:a="testnet",mode:s,skipFlow:d=[],nativeChainId:c,appName:i="Spicenet",apiUrl:l,theme:m,rpcOverrides:f,swapper:p,liquidityVenues:w,additionalSourceTokens:u,whitelist:y,assetDisplay:x})=>{const g=me(t);v.useEffect(()=>{if(!l)return;const U=q.getBaseUrl();return q.setBaseUrl(l),()=>q.setBaseUrl(U)},[l]),v.useEffect(()=>(we(f),()=>we(void 0)),[f]);const b=v.useMemo(()=>B.getChainIdsByNetwork(a),[a]),T=n??b,P=m??null,[O,A]=v.useState(()=>s??De()??"7702");v.useEffect(()=>{s&&A(s)},[s]);const N=v.useCallback(U=>{if(s){A(s);return}A(U),nr(U)},[s]),{embeddedAddress:R,externalAddress:h}=se(),I=JSON.stringify(f),E=v.useMemo(Fe,[a,l,I,r]),S=v.useMemo(()=>({feeToleranceBps:g,inventory:E,provider:r,supportedChainIds:T,allowedTokens:o,skipFlow:d,mode:O,setMode:N,network:a,nativeChainId:c,appName:i,apiUrl:l,rpcOverrides:f,swapper:p,liquidityVenues:w,additionalSourceTokens:u,embeddedWalletAddress:R,externalWalletAddress:h,isUserWhitelisted:null,isWhitelistChecking:!1,isWhitelistConfigured:!1,isWhitelistGateActive:!1}),[E,g,r,T,o,d,O,N,a,c,i,l,f,p,w,u,R,h]);return k.jsx(_e.Provider,{value:P,children:k.jsx(Z.Provider,{value:S,children:k.jsx(or,{value:S,whitelist:y,children:k.jsx(Me.Provider,{value:x,children:e})})})})},ir={spacing:{xs:"0.25rem",sm:"0.5rem",md:"1rem",lg:"1.5rem",xl:"2rem"},borderRadius:{sm:"0.25rem",md:"0.5rem",lg:"0.75rem",full:"9999px"},typography:{fontFamily:Y.ui,fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.75rem"},fontWeight:{normal:400,medium:500,semibold:600,bold:700}},shadows:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1)"},animation:{fast:"150ms ease-in-out",normal:"200ms ease-in-out",slow:"300ms ease-in-out"}},cr={primary:"#EA4B4B",primaryHover:"#E43838",secondary:"#f3f4f6",background:"#ffffff",surface:"#f9fafb",surfaceHover:"#f3f4f6",border:"#e5e7eb",borderHover:"#d1d5db",text:"#111827",textSecondary:"#374151",textMuted:"#6b7280",success:"#10b981",error:"#ef4444",warning:"#f59e0b",info:"#3b82f6"},lr={primary:"#EA4B4B",primaryHover:"#E43838",secondary:"#171717",background:"#141414",surface:"#1e1e1e",surfaceHover:"#2a2a2a",border:"#2d2d2d",borderHover:"#3a3a3a",text:"#ffffff",textSecondary:"#888888",textMuted:"#666666",success:"#10b981",error:"#ef4444",warning:"#f59e0b",info:"#3b82f6"},ze=(t="light")=>({mode:t,...ir,colors:t==="light"?cr:lr});function ee(t,e){const r=t.replace("#",""),n=Math.max(0,Math.round(parseInt(r.substring(0,2),16)*(1-e))),o=Math.max(0,Math.round(parseInt(r.substring(2,4),16)*(1-e))),a=Math.max(0,Math.round(parseInt(r.substring(4,6),16)*(1-e)));return`#${n.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}function dr(t,e){return{shell:e?.shell??"#141414",shellBorder:e?.shellBorder??ee(e?.shell??"#141414",.35),shellInnerBorder:e?.shellInnerBorder??ee(e?.shell??"#141414",.55),cardBg:e?.cardBg??"#1e1e1e",inputBg:e?.inputBg??"#171717",hoverBg:e?.hoverBg??"#2a2a2a",textPrimary:e?.textPrimary??"#ffffff",textSecondary:e?.textSecondary??"#888888",inputText:e?.inputText??"#e0e0e0",inputPlaceholder:e?.inputPlaceholder??"#555555",cardBorder:e?.cardBorder??"rgba(255,255,255,0.08)",inputBorder:e?.inputBorder??"rgba(255,255,255,0.10)",buttonBorder:e?.buttonBorder??"rgba(255,255,255,0.12)",successBg:e?.successBg??"#0a1f18",successBorder:e?.successBorder??"#1a4a3a",successText:e?.successText??"#6ee7b7",warningBg:e?.warningBg??"#1f1a0d",warningBorder:e?.warningBorder??"#4a3820",warningText:e?.warningText??"#fbbf24",errorBg:e?.errorBg??"#1f0d0d",errorBorder:e?.errorBorder??"#4a2020",errorText:e?.errorText??"#f87171",infoBg:e?.infoBg??"#0d1325",infoBorder:e?.infoBorder??"#2a3a5a",infoText:e?.infoText??"#60a5fa"}}function ur(t){return{shell:"#ffffff",shellBorder:"#E9E9E9",shellInnerBorder:"#D5D5D5",cardBg:"#f9fafb",inputBg:"#ffffff",hoverBg:"#f3f4f6",textPrimary:"#111827",textSecondary:"#6b7280",inputText:"#111827",inputPlaceholder:"#9ca3af",cardBorder:"#e5e7eb",inputBorder:"#d1d5db",buttonBorder:"#0e0d0b",successBg:"#d1fae5",successBorder:"#6ee7b7",successText:"#065f46",warningBg:"#fef3c7",warningBorder:"#fde68a",warningText:"#92400e",errorBg:"#fef2f2",errorBorder:"#fecaca",errorText:"#dc2626",infoBg:"#dbeafe",infoBorder:"#93c5fd",infoText:"#1e40af"}}function Je(t,e){const r=e?{...t,...e}:t,n=r.dark??!1,o=r.primaryColor,a=r.shell??(n?"#141414":"#ffffff");return{primaryColor:o,dark:n,fontFamily:r.fontFamily??'"Helvetica Neue", sans-serif',appName:r.appName??"Spicenet",logo:r.logo,borderRadius:r.borderRadius??"8px",shell:a,shellBorder:ee(a,n?.35:.085),shellInnerBorder:ee(a,n?.55:.165),card:r.card??(n?"#1e1e1e":"#f9fafb"),input:n?"#171717":"#ffffff",hover:n?"#2a2a2a":"#f3f4f6",text:r.text??(n?"#ffffff":"#111827"),textMuted:r.textMuted??(n?"#888888":"#6b7280"),inputText:n?"#e0e0e0":"#111827",inputPlaceholder:n?"#555555":"#9ca3af",border:r.border??(n?"rgba(255,255,255,0.08)":"#e5e7eb"),inputBorder:n?"rgba(255,255,255,0.10)":"#d1d5db",buttonBorder:n?"rgba(255,255,255,0.12)":"#0e0d0b",successBg:n?"#0a1f18":"#d1fae5",successBorder:n?"#1a4a3a":"#6ee7b7",successText:n?"#6ee7b7":"#065f46",warningBg:n?"#1f1a0d":"#fef3c7",warningBorder:n?"#4a3820":"#fde68a",warningText:n?"#fbbf24":"#92400e",errorBg:n?"#1f0d0d":"#fef2f2",errorBorder:n?"#4a2020":"#fecaca",errorText:n?"#f87171":"#dc2626",infoBg:n?"#0d1325":"#dbeafe",infoBorder:n?"#2a3a5a":"#93c5fd",infoText:n?"#60a5fa":"#1e40af"}}const fr=Y.mono;function He(t,e){const r=v.useContext(_e)??void 0;return v.useMemo(()=>{const n=r??{primaryColor:"#EA4B4B"},o={...t?.primaryColor?{primaryColor:t.primaryColor}:{},...t?.fontFamily?{fontFamily:t.fontFamily}:{},...e!==void 0?{dark:e}:{}},a=Je(n,o),{dark:s,primaryColor:d,appName:c}=a,i=ze(s?"dark":"light"),l={...i,colors:{...i.colors,primary:d,primaryHover:`${d}dd`},typography:{...i.typography,fontFamily:a.fontFamily}},m={shell:a.shell,shellBorder:a.shellBorder,shellInnerBorder:a.shellInnerBorder,cardBg:a.card,inputBg:a.input,hoverBg:a.hover,textPrimary:a.text,textSecondary:a.textMuted,inputText:a.inputText,inputPlaceholder:a.inputPlaceholder,cardBorder:a.border,inputBorder:a.inputBorder,buttonBorder:a.buttonBorder,successBg:a.successBg,successBorder:a.successBorder,successText:a.successText,warningBg:a.warningBg,warningBorder:a.warningBorder,warningText:a.warningText,errorBg:a.errorBg,errorBorder:a.errorBorder,errorText:a.errorText,infoBg:a.infoBg,infoBorder:a.infoBorder,infoText:a.infoText},f=t?.inputVariant?t.inputVariant==="dark":s;return{brand:r,theme:l,dark:s,appName:c,primaryColor:d,dk:m,palette:m,fontFamily:a.fontFamily,monoFont:fr,inputDark:f,cardBg:f?m.cardBg:"#E9E9E9",cardBorder:f?m.cardBorder:"#C6C6C6",textPrimary:m.textPrimary,textSecondary:m.textSecondary,subtitleText:f?m.textSecondary:"#979AA0"}},[r,t,e])}const Ge="spiceflow-spinner-keyframes";function mr(){if(typeof document>"u"||document.getElementById(Ge))return;const t=document.createElement("style");t.id=Ge,t.textContent="@keyframes spiceflow-spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}",document.head.appendChild(t)}const pe=({size:t=16,borderWidth:e=2,color:r="currentColor",style:n})=>{const o=v.useRef(!1);return v.useEffect(()=>{o.current||(mr(),o.current=!0)},[]),k.jsx("div",{role:"status","aria-label":"Loading",style:{width:`${t}px`,height:`${t}px`,border:`${e}px solid ${r}`,borderTop:`${e}px solid transparent`,borderRadius:"50%",animation:"spiceflow-spin 1s linear infinite",flexShrink:0,...n}})},J=({variant:t="primary",size:e="md",loading:r=!1,fullWidth:n=!1,disabled:o,children:a,className:s="",style:d,theme:c,styles:i,dark:l,...m})=>{const{theme:f,dark:p,palette:w}=He(i,l),u=c||f,y=l??p,[x,g]=v.useState(!1),[b,T]=v.useState(!1),P=y?w.shell:"white",O=()=>{switch(t){case"primary":return{backgroundColor:i?.button?.backgroundColor||u.colors.primary,color:i?.button?.color||"#ffffff",border:`1px solid ${i?.button?.backgroundColor||u.colors.primary}`};case"secondary":return{backgroundColor:u.colors.secondary,color:u.colors.text,border:`1px solid ${u.colors.border}`};case"success":return{backgroundColor:u.colors.success,color:u.colors.text,border:`1px solid ${u.colors.success}`};case"error":return{backgroundColor:u.colors.error,color:u.colors.text,border:`1px solid ${u.colors.error}`};case"ghost":return{backgroundColor:"transparent",color:u.colors.textSecondary,border:`1px solid ${u.colors.border}`};case"outline":{const h=i?.button?.backgroundColor||u.colors.primary,I=i?.button?.color||(y?"#ffffff":"#0e0d0b"),E=i?.button?.borderColor||(y?`${u.colors.primary}88`:"#0e0d0b"),S=o||r,U=y?"1px":"1.5px",re=i?.button?.disabledBackgroundColor||`${h}88`,ne=i?.button?.disabledColor||I;return{height:"56px",backgroundColor:S?re:b?`${h}cc`:x?`${h}ee`:h,color:S?ne:I,border:`${U} solid ${E}`,borderRadius:i?.button?.borderRadius||"12px",fontSize:"22px",fontWeight:500,fontFamily:Y.mono,opacity:S?.78:1,transform:S?"none":b?"scale(0.98)":x?"translateY(-2px)":"none",boxShadow:S?`3px 3px 0px ${P}, 4px 4px 0px ${E}`:b?`2px 2px 0px ${E}`:x?`5px 5px 0px ${P}, 6px 6px 0px ${E}`:`3px 3px 0px ${P}, 4px 4px 0px ${E}`,transition:"transform 150ms ease, box-shadow 150ms ease, background-color 150ms ease, border-color 150ms ease, color 150ms ease"}}default:return{}}},A=()=>{if(t==="outline")return{};switch(e){case"sm":return{padding:`${u.spacing.sm} ${u.spacing.md}`,fontSize:u.typography.fontSize.sm};case"md":return{padding:`${u.spacing.md} ${u.spacing.lg}`,fontSize:u.typography.fontSize.base};case"lg":return{padding:`${u.spacing.lg} ${u.spacing.xl}`,fontSize:u.typography.fontSize.lg};default:return{}}},N={borderRadius:i?.button?.borderRadius||u.borderRadius.md,fontWeight:i?.button?.fontWeight||u.typography.fontWeight.medium,fontFamily:i?.button?.fontFamily||u.typography.fontFamily,fontSize:i?.button?.fontSize||void 0,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease, opacity 150ms ease",cursor:o||r?"not-allowed":"pointer",opacity:(o||r)&&t!=="outline"?.6:1,width:n?"100%":"auto",display:"flex",alignItems:"center",justifyContent:"center",gap:u.spacing.sm,...O(),...A(),...i?.button?.fontSize&&{fontSize:i.button.fontSize}},R=o||r;return k.jsxs("button",{type:m.type??"button","data-spiceflow-focus":!0,"aria-busy":r||void 0,"aria-disabled":R||void 0,style:{...N,...d},className:s,disabled:R,onMouseEnter:h=>{g(!0),m.onMouseEnter?.(h)},onMouseLeave:h=>{g(!1),T(!1),m.onMouseLeave?.(h)},onMouseDown:h=>{T(!0),m.onMouseDown?.(h)},onMouseUp:h=>{T(!1),m.onMouseUp?.(h)},...m,children:[r&&k.jsx(pe,{size:16}),a]})},pr=({onAuthSuccess:t,onAuthError:e,theme:r="light",className:n="",buttonText:o="Login with Privy",autoTrigger:a=!1})=>{const s=ze(r),[d,c]=v.useState(!1),[i,l]=v.useState(!1),{ready:m,authenticated:f,user:p}=F.usePrivy(),{login:w}=F.useLogin(),{logout:u}=F.useLogout();v.useEffect(()=>{c(!0)},[]),v.useEffect(()=>{a&&m&&!f&&d&&!i&&(l(!0),y())},[a,m,f,d,i]),v.useEffect(()=>{if(m&&f&&p&&t){const g=p.wallet?.address||p.email?.address;g&&t(g)}},[m,f,p,t]),v.useEffect(()=>{},[m,f,e]);const y=()=>{try{w()}catch(g){const b=`Login failed: ${String(g)}`;e?e(b):console.error(b)}},x=()=>{try{u()}catch(g){const b=`Logout failed: ${String(g)}`;e?e(b):console.error(b)}};if(!d)return k.jsx("div",{className:n,children:k.jsx(J,{variant:"primary",disabled:!0,theme:s,children:o})});if(!m)return k.jsx("div",{className:n,children:k.jsx(J,{variant:"primary",disabled:!0,theme:s,children:"Loading..."})});if(f&&p){const g=p.wallet?.address||p.email?.address,b=g?Le(g):"Connected";return k.jsx("div",{className:n,children:k.jsxs(J,{variant:"primary",onClick:x,theme:s,children:["Logout (",b,")"]})})}return a?k.jsx("div",{className:n,children:k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px",flexDirection:"column",gap:"12px"},children:[k.jsx(pe,{size:40,borderWidth:3,color:"#3b82f6"}),k.jsx("p",{style:{color:"#6b7280",fontSize:"14px"},children:"Opening login..."})]})}):k.jsx("div",{className:n,children:k.jsx(J,{variant:"primary",onClick:y,theme:s,children:o})})};exports.Button=J,exports.CHAIN_CONFIGS=ct,exports.EMPTY_INVENTORY=Pe,exports.PrivyLogin=pr,exports.RELAYER_API_URL=Ie,exports.RelayerService=te,exports.SpiceFlowProvider=sr,exports.SpiceFlowProviderContext=Z,exports.SpiceflowError=$,exports.Spinner=pe,exports.addressesEqual=M,exports.amountsWithinBps=Ot,exports.buildDarkPalette=dr,exports.buildLightPalette=ur,exports.calculateBpsFee=Ne,exports.copyToClipboard=Kt,exports.createInitialSteps=Pt,exports.createInventoryStore=Fe,exports.describeChainSwitchError=At,exports.duration=L,exports.easing=W,exports.ensureSmartWallet=Be,exports.ensureWalletOnChain=ut,exports.feeAmountsWithinTolerance=Ue,exports.feeBreakdownsWithinTolerance=Mt,exports.font=Y,exports.formatAssetBalance=er,exports.formatBalance=We,exports.formatDecimalInput=Yt,exports.formatRawTokenInput=jt,exports.formatUsd=Gt,exports.getAllAssetsForChain=mt,exports.getAssetDisplayChainName=Zt,exports.getAssetDisplayName=Oe,exports.getAssetDisplaySymbol=qe,exports.getBatchFees=X,exports.getChainConfig=j,exports.getChainName=V,exports.getChainsForAssets=ft,exports.getClientForChain=ve,exports.getDelegateContractAddress=lt,exports.getEscrowFreeFeePreview=Jt,exports.getExplorerUrl=dt,exports.getRelayerErrorDetail=xt,exports.getRpcUrlForChain=G,exports.getSingleNetOutput=zt,exports.getSupplyFeePreview=Ht,exports.getTokenDecimals=pt,exports.getWalletBalanceEntries=Tt,exports.hasStoredSpiceFlowMode=ar,exports.isAssetAllowed=Qt,exports.isSpiceflowError=ie,exports.isUserRejection=Ce,exports.parseNumericInput=Vt,exports.radius=bt,exports.relayerFetch=K,exports.relayerService=q,exports.resolveFeeToleranceBps=me,exports.resolveTheme=Je,exports.sanitizeError=Et,exports.splitFeeInclusiveAmount=qt,exports.transition=wt,exports.truncateAddress=Le,exports.useAssetDisplay=tr,exports.useIsUserWhitelisted=Re,exports.useProviderWallets=se,exports.useSpiceBrand=He,exports.useWallet=Te,exports.z=yt;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spicenet-io/spiceflow-ui",
3
- "version": "4.20.0",
3
+ "version": "4.20.1",
4
4
  "description": "Spiceflow UI SDK",
5
5
  "type": "module",
6
6
  "workspaces": [