@spicenet-io/spiceflow-ui 4.1.2 → 4.2.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth-privy.cjs.js +1 -1
- package/dist/auth-privy.js +1 -1
- package/dist/components/SpiceDeposit/lib/swapper.d.ts +27 -0
- package/dist/components/SpiceDeposit/steps/SelectSourceModal.d.ts +3 -0
- package/dist/components/SpiceDeposit/steps/SwapperDepositModal.d.ts +3 -0
- package/dist/index.cjs.js +7 -7
- package/dist/index.d.ts +1 -0
- package/dist/index.js +9 -9
- package/dist/privy-Bc1n_r6h.js +2 -0
- package/dist/privy-C-sOsJ4F.js +2 -0
- package/dist/providers/SpiceFlowProvider.d.ts +3 -0
- package/dist/types/deposit.d.ts +42 -0
- package/package.json +2 -1
- package/dist/privy-Dcad3cmM.js +0 -2
- package/dist/privy-KaNyb2oB.js +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import{jsx as $,jsxs as Y}from"react/jsx-runtime";import{useContext as de,useMemo as L,useRef as ce,useEffect as A,createContext as ue,useState as M,useCallback as De}from"react";import{getChainMeta as fe,getTokensForChain as je,ZERO_ADDRESS as ze,isNativeToken as Q,getDelegateContract as _e,getTokenByAddress as Ge,DELEGATE_ABI as He,ERC20_ABI as Je,spicenetEscrowAbi as Ye,uniV3SwapRouterAbi as Qe,getChainIdsByNetwork as Ve}from"@spicenet-io/spiceflow-core";import{isAddress as R,getAddress as V,defineChain as Xe,createPublicClient as Ke,http as Ze,erc20Abi as et,formatUnits as pe,isHex as tt,decodeErrorResult as rt,hexToString as at,createWalletClient as nt,custom as ot}from"viem";import{readContract as st}from"viem/actions";import{useWallets as me,usePrivy as X,getEmbeddedConnectedWallet as he,useSign7702Authorization as it,useSignMessage as lt,useLogin as dt,useLogout as ct}from"@privy-io/react-auth";import{useAccount as ge}from"wagmi";import{useQuery as ut,useMutation as ft}from"@tanstack/react-query";const pt={base:0,raised:1,sticky:10,overlay:20,popover:40,modal:1e3,dropdown:1100,toast:1200,tooltip:1300},mt={none:"0",sm:"4px",md:"6px",card:"8px",input:"10px",shell:"9px",modal:"12px",pill:"9999px",circle:"50%"},B={out:"cubic-bezier(0.22, 1, 0.36, 1)",inOut:"cubic-bezier(0.65, 0, 0.35, 1)",linear:"linear"},k={fast:"120ms",normal:"150ms",slow:"300ms",progress:"400ms"},ht={interactive:`transform ${k.normal} ${B.out}, box-shadow ${k.normal} ${B.out}, background-color ${k.normal} ${B.out}, border-color ${k.normal} ${B.out}, color ${k.normal} ${B.out}`,color:`background-color ${k.normal} ${B.out}, border-color ${k.normal} ${B.out}, color ${k.normal} ${B.out}`,popover:`opacity ${k.normal} ${B.out}, transform ${k.normal} ${B.out}`},D={ui:'"Helvetica Neue", sans-serif',mono:'"IBM Plex Mono", monospace'};function j(t,e){return!t||!e?!1:R(t)&&R(e)?V(t)===V(e):t.toLowerCase()===e.toLowerCase()}const gt="0xcA11bde05977b3631167028862bE2a173976CA11",yt={4114:"0x860aFc632a6D625B95d8B96f39ECC48E988c6962"},bt=new Set([5115]);function wt(t){const e=yt[t.id]??(bt.has(t.id)?void 0:gt);return Xe({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 xt=[1,8453,42161,4114,11155111,421614,84532,5115,123420001114,688688,688689],z=Object.fromEntries(xt.map(t=>fe(t)).filter(t=>t!=null).map(t=>[t.id,{...t,viemChain:wt(t),supportedTokens:je(t.id)}])),vt=z;let ye={};const K=new Map,be=t=>{ye={...t||{}},K.clear()},Z=t=>{const e=ye[t];return e&&typeof e=="string"&&e.length>0?e:z[t]?.rpcUrl},W=t=>z[t],ee=t=>{const e=fe(t);return e?.displayName||e?.name||`Chain ${t}`},$t=t=>{const e=_e(t);if(!e)throw new Error(`Unsupported chain ID: ${t}`);return e},Et=(t,e,r)=>{const a=W(t);return a?.blockExplorer?`${a.blockExplorer}/tx/${e}`:"#"};async function Ct(t,e){const r=`0x${e.toString(16)}`;try{await t.request({method:"wallet_switchEthereumChain",params:[{chainId:r}]});return}catch(o){if(!(o?.code===4902||typeof o?.message=="string"&&o.message.includes("Unrecognized chain ID")))throw o}const a=W(e);if(!a)throw new Error(`Cannot add unknown chain ${e} to wallet`);await t.request({method:"wallet_addEthereumChain",params:[{chainId:r,chainName:a.name||`Chain ${e}`,nativeCurrency:a.nativeCurrency||{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:[Z(e)||a.rpcUrl],blockExplorerUrls:a.blockExplorer?[a.blockExplorer]:void 0}]})}const we=t=>{const e=W(t);if(!e)throw new Error(`Unsupported chain ID: ${t}`);const r=Z(t);if(!r)throw new Error(`No RPC URL configured for chain ID: ${t}`);const a=`${t}:${r}`,o=K.get(a);if(o)return o;const n=Ke({chain:e.viemChain,transport:Ze(r,{timeout:15e3,retryCount:2,retryDelay:300}),batch:{multicall:{wait:16}}});return K.set(a,n),n},Bt=()=>{const t={};return Object.values(z).forEach(e=>{t[e.id]={name:e.name,moralisName:e.moralisId||"",chain:e.viemChain,rpcUrl:Z(e.id)||e.rpcUrl}}),t},kt=(t,e=[])=>{const r=W(t);if(!r)return[];const a=[];if(![11155111,421614,84532,688689].includes(t)){const n=e.find(s=>s.chainId===t&&s.isNative);n?a.push(n):a.push({address:ze,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 a;const o=a.some(n=>n.isNative);return r.supportedTokens.forEach(n=>{if(o&&Q(n.address))return;const s=e.find(u=>u.chainId===t&&j(u.address,n.address));s?a.push(s):a.push({address:n.address,name:n.name,symbol:n.symbol,decimals:n.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:n.logo,isNative:!1,chainId:t})}),a},St=async(t,e)=>{const r=W(t);if(!r)throw new Error(`Unsupported chain ID: ${t}`);const a=e.toLowerCase();if(Q(a)){if(!r.nativeCurrency?.decimals)throw new Error(`Native currency decimals not configured for chain ${t}`);return r.nativeCurrency.decimals}if(r.supportedTokens){const o=r.supportedTokens.find(n=>j(n.address,a));if(o)return o.decimals}try{if(!R(e,{strict:!1}))throw new Error(`Invalid token address: ${e}`);const o=V(e),n=we(t),s=await st(n,{address:o,abi:et,functionName:"decimals"});return Number(s)}catch{throw new Error(`Could not determine decimals for token ${e} on chain ${t}`)}};class S extends Error{constructor(e,r,a={}){super(r),this.code=e,this.context=a,this.name="SpiceflowError",Error.captureStackTrace&&Error.captureStackTrace(this,S)}}function te(t){return t instanceof S}const It=["user rejected","user denied","user cancelled","rejected the request","action_rejected","4001"];function xe(t){if(!t)return"";if(typeof t=="string")return t;const e=t,r=e.message||e.reason||"",a=e.details||"";return`${r} ${a}`.trim()}const ve=t=>{if(te(t))return t.code==="WALLET_REJECTED";const e=xe(t).toLowerCase();return It.some(r=>e.includes(r))};let re=null;function Tt(t){return re?.message===t?re.detail:void 0}const At=(t,e="Something went wrong. Please try again.")=>{if(ve(t))return"Transaction was rejected.";if(te(t)){const r=t.message||e,{requestId:a,httpStatus:o,responseBody:n,endpoint:s}=t.context;return(a||o||s)&&(re={message:r,detail:{requestId:a,httpStatus:o,responseBody:n,endpoint:s}}),r}return xe(t)||e},Pt=[...He,...Je,...Ye,...Qe];function ae(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=>ae(r,e+1)):typeof t=="object"?Object.values(t).flatMap(r=>ae(r,e+1)):[]}function $e(t){try{const e=rt({abi:Pt,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],a=r&&r!=="0x"?$e(r):void 0;return a?`Call reverted: ${a}`:"Call reverted (no reason returned)"}return e.errorName}catch{try{const e=at(t).replace(/\x00+$/g,"").trim();return/^[\x20-\x7e]+$/.test(e)&&e.length>1?e:void 0}catch{return}}}function Rt(t){for(const e of ae(t)){if(!tt(e))continue;const r=$e(e);if(r)return r}}function Wt(t,e){const r=e.match(/Output amount (\d+) is insufficient after fees (\d+) on chain (\d+)/);if(!r)return e;const[,a,o,n]=r,s=Number(n),u=BigInt(a),h=BigInt(o);let d;for(const w of t.intents){const g=w.chainBatches.find(f=>f.chainId===s);if(g){d=g;break}}const m=d?.tokenTransfers.find(w=>w.from==="escrow"&&j(w.to,t.user)&&!Q(w.token)),i=ee(s);if(!m)return`Amount is too small to cover the estimated fee on ${i}.`;const c=Ge(m.token,s),p=c?.decimals??18,y=c?.symbol??"tokens",l=pe(u,p),v=pe(h,p);return`Amount is too small to cover the estimated fee on ${i}. Amount: ${l} ${y}. Estimated fee: ${v} ${y}.`}function Ut(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 Nt="https://tx-submission-api.spicenet.io",Ee=Nt;function Ft(t,e){return typeof e=="bigint"?e.toString():e}async function _(t,e){const r={...e?.headers},a=r["x-request-id"]??crypto.randomUUID();r["x-request-id"]=a;const o=await fetch(t,{...e,headers:r}),n=o.headers.get("x-request-id")??"";return Object.assign(o,{requestId:n})}function q(t,e){if(!t)return e;const r=t.error,a=(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=Rt(t);return o&&!a.includes(o)?`${a} \u2014 ${o}`:a}async function Lt(t){try{return await t.json()}catch{return null}}function Mt(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(a=>typeof a=="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 qt{constructor(){this.baseUrl=Ee}setBaseUrl(e){this.baseUrl=e}getBaseUrl(){return this.baseUrl}async requestJson(e,r){const a=`${this.baseUrl}${e}`,o=await _(a,r.method&&r.method!=="GET"?{method:r.method,headers:{"Content-Type":"application/json"},body:JSON.stringify(r.body,Ft)}:void 0),n=await o.json();if(!o.ok||n.success===!1||r.ok&&!r.ok(n)){const s=q(n,r.fallbackError(o.status));throw new S(r.code??"RELAYER_ERROR",r.mapError?r.mapError(s):s,{httpStatus:o.status,requestId:o.requestId,responseBody:JSON.stringify(n),endpoint:e,...r.context})}return n}async createAction(e){return this.requestJson("/actions",{method:"POST",body:e,fallbackError:r=>`Relayer API error: ${r}`})}async estimateActionFees(e){return(await this.requestJson("/actions/fees/estimate",{method:"POST",body:e,fallbackError:r=>`Relayer fee estimate error: ${r}`,ok:r=>!!r.success&&!!r.data?.feeEstimate,mapError:r=>Wt(e,r)})).data.feeEstimate}async estimateBatchGas(e){const r=await this.requestJson("/actions/gas/estimate",{method:"POST",body:e,fallbackError:a=>`Relayer gas estimate error: ${a}`,ok:a=>!!a.success&&!!a.data?.gasFee});return{gasFee:BigInt(r.data.gasFee),gasQuoteSource:r.data.gasQuoteSource}}async executeStep(e,r,a,o){const n=`${this.baseUrl}/actions/${e}/intents/${r}/steps/${a}`,s=`/actions/${e}/intents/${r}/steps/${a}`,u=crypto.randomUUID(),h=3e4,d=new Promise((c,p)=>setTimeout(()=>p(new S("RELAYER_EXECUTE_ERROR",`Execute step request timed out after ${h/1e3}s`,{actionId:e,intentIndex:r,stepIndex:a,endpoint:s,requestId:u})),h)),m=await Promise.race([_(n,{method:"POST",headers:{"Content-Type":"application/json","x-request-id":u},body:JSON.stringify(o)}),d]),i=await m.json();if(!m.ok||i.success===!1)throw new S("RELAYER_EXECUTE_ERROR",q(i,`Execute step error: ${m.status}`),{httpStatus:m.status,requestId:m.requestId,responseBody:JSON.stringify(i),endpoint:s,actionId:e});if(i?.status==="error"||i?.status==="reverted"){const c=q(i,""),p=c?`: ${c}`:"";throw new S("RELAYER_EXECUTE_ERROR",`Step ${a} previously ${i.status}${p}`,{httpStatus:m.status,requestId:m.requestId,responseBody:JSON.stringify(i),endpoint:s,actionId:e,intentIndex:r,stepIndex:a,stepStatus:i.status})}return{success:!0,transactionHash:i.transactionHash}}async checkStepStatus(e,r){const a=e.split("/"),o=a[0],n=a.length>=2?a[1]:"0",s=await this.requestJson(`/actions/${o}/intents/${n}/steps/${r}`,{fallbackError:u=>`Intent step status check failed: ${u}`,code:"RELAYER_STATUS_ERROR",context:{intentId:e}});return{success:!0,data:{status:s.status==="error"?"reverted":s.status,transactionHash:s.txid,error:q(s,"")}}}async createWallet(e,r){return this.requestJson(`/wallets/${e}`,{method:"PUT",body:r,fallbackError:a=>`Create wallet error: ${a}`})}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 P=new qt;async function Ot(t){const e=`${P.getBaseUrl()}/wallets/${t}/balance`,r=await _(e,{cache:"no-store"}),a=await Lt(r);if(!r.ok||a?.success===!1)throw new S("RELAYER_ERROR",q(a,`Unable to verify Spice balance: ${r.status}`),{httpStatus:r.status,requestId:r.requestId,responseBody:JSON.stringify(a),endpoint:`/wallets/${t}/balance`});return Mt(a)}const ne=new Map,Dt="spiceflow.smartWallet.";function Ce(t){return`${Dt}${t.toLowerCase()}`}function jt(t){try{return typeof localStorage<"u"&&localStorage.getItem(Ce(t))==="1"}catch{return!1}}function Be(t){try{typeof localStorage<"u"&&localStorage.setItem(Ce(t),"1")}catch{}}function zt(t){if(!(t instanceof S))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 ke(t,e){if(jt(t))return;const r=t.toLowerCase(),a=ne.get(r);if(a)return a;const o=(async()=>{try{await P.getWallet(t),Be(t);return}catch(d){if(!zt(d))throw d}const{unix_timestamp:n}=await P.getRollupTimestamp(),s=`I am creating a new smart wallet and adding an admin wallet ethereum:0x${t.slice(2).toLowerCase()}. Nonce: ${n}`,u=await e(s),h=typeof u=="string"?u:u.signature;if(!h)throw new Error("Wallet returned no smart wallet signature");await P.createWallet(t,{timestamp:n,signature:h}),Be(t)})();ne.set(r,o);try{await o}finally{ne.delete(r)}}const _t=(t,e)=>{const r=o=>e?e(o):ee(o),a=[];return t.forEach((o,n)=>{const s=o.calls&&o.calls.length>0,u=o.tokenTransfers&&o.tokenTransfers.length>0;!s&&!u||a.push({stepId:n,status:n===0?"processing":"pending",chainId:o.chainId,chainName:r(o.chainId),description:"Processing transaction"})}),a},Gt=t=>{const e=t?.wallet;if(e?.address&&e.walletClientType==="privy"&&e.connectorType==="embedded"&&!e.imported)return e.address},Se=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 a=null;for(const o of r)try{const n=await t.getWalletClient(o);if(n)return n}catch(n){a=n}if(a)throw a}if(typeof t.getEthereumProvider=="function"){const r=await t.getEthereumProvider(),a=e?W(e)?.viemChain:void 0;return nt({account:t.address,chain:a,transport:ot(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 Se(t,e);return{request:a=>r.request(a)}},G=t=>t?.address?{address:t.address,wallet:t,getWalletClient:e=>Se(t,e),getEthereumProvider:e=>Ht(t,e)}:null,oe=()=>{const{address:t,connector:e}=ge();let r=null,a=null;try{r=me(),{user:a}=X()}catch{r=null,a=null}const o=r?.wallets||[],n=he(o),s=n?.address?.toLowerCase(),u=o.find(l=>l.connectorType!=="embedded"&&l.address?.toLowerCase()!==s),h=t?.toLowerCase(),d=t&&e&&!(h&&s&&h===s)?{address:t,connector:e,getEthereumProvider:()=>e.getProvider()}:null,m=t&&e?{address:t,connector:e,getEthereumProvider:()=>e.getProvider()}:null,i=G(n),c=G(d)||G(u),p=i?.address||Gt(a),y=G(m)||c;return{embeddedWallet:i,externalWallet:c,embeddedAddress:p,externalAddress:c?.address,activeWallet:y,activeAddress:y?.address}},Ie=()=>{const t=de(H),e=t?.mode,{isConnected:r,address:a}=ge();let o=null,n=null,s=null,u=null,h=null;try{o=X(),n=it(),s=lt(),u=me()}catch(f){h=f instanceof Error?f.message:String(f)}if(h)return e==="ondemand"&&r&&a?{isReady:!0,isAuthenticated:!0,isConnected:!0,address:a,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{ready:d=!1,authenticated:m=!1}=o||{},i=t?.embeddedWalletAddress,c=he(u?.wallets||[]),p=i||c?.address,y=!!p&&!!c,l={isReady:e==="ondemand"?!0:d,isAuthenticated:e==="ondemand"?!0:m||y,isConnected:e==="ondemand"?r&&!!a||d&&(m||y)&&y:d&&y,address:e==="ondemand"&&r?a:p,provider:"privy"},v=async f=>{if(!c)throw new Error("Embedded wallet not available");const b=await c.getEthereumProvider(),{createWalletClient:E,custom:I}=await import("viem");return{signature:await E({account:c.address,transport:I(b)}).signMessage({account:c.address,message:f})}},w=async f=>{if(s)try{return{signature:(await s.signMessage({message:f})).signature}}catch(b){if(!c)throw b}if(!c)throw new Error("Privy sign message not available");return v(f)},g=async()=>{if(!p)throw new Error("Embedded wallet not available for smart wallet setup");await ke(p,w)};return{...l,actions:{signAuthorization:async f=>{if(!n)throw new Error("Privy sign authorization not available");try{await g();const b=await n.signAuthorization({contractAddress:f.contractAddress,chainId:f.chainId,nonce:f.nonce},{address:p});return delete b.v,b}catch(b){const E=typeof b?.message=="string"?b.message:String(b?.message??b??"");throw E.includes("not configured")||E.includes("chain")?new Error(`Chain ${f.chainId} is not configured in PrivyProvider. Add this chain to your Privy dashboard or supportedChainIds.`):b}},signMessage:async f=>{if(typeof f=="object"&&"raw"in f){if(await g(),!c)throw new Error("Embedded wallet not available for raw signing");return v(f)}return w(f)},getEthereumProvider:async()=>{if(!c)throw new Error("Embedded wallet not available");return c.getEthereumProvider()}}}},Jt="https://portal-api.spicenet.io/api/v1",se=t=>t.replace(/\/+$/,""),Yt=(t,e)=>`${t}:${e}`;async function Qt(t,e){const r=new URLSearchParams({walletAddress:e,campaignId:"spicenet-portal",campaignGroup:"1"}),a=await fetch(`${t}/portal/mainnet/linked-portal-wallet?${r.toString()}`,{cache:"no-store"});if(!a.ok){if(a.status>=500){const o=new Error(`Failed to resolve linked portal wallet: ${a.status}`);throw o.status=a.status,o}return null}return(await a.json()).portalWalletAddress?.toLowerCase()??null}async function Vt(t,e,r){const a=new URLSearchParams({walletAddress:e,campaignId:r.campaignId,campaignGroup:r.campaignGroup,partnerId:r.partnerId}),o=await fetch(`${t}/portal/mainnet/whitelist/check?${a.toString()}`,{cache:"no-store"});if(!o.ok){const n=new Error(`Failed to check whitelist: ${o.status}`);throw n.status=o.status,n}return await o.json()}async function Xt(t,e,r,a){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:a})});if(!o.ok)throw new Error(`Failed to link wallet: ${o.status}`)}function Te({walletAddress:t,campaignId:e,campaignGroup:r,partnerId:a,apiBaseUrl:o=Jt,enabled:n=!0,staleTime:s=5*60*1e3,refetchInterval:u=!1}={}){const{isAuthenticated:h,isConnected:d}=Ie(),{externalAddress:m,embeddedAddress:i}=oe(),c=t??m,p=typeof c=="string"?c.toLowerCase():void 0,y=typeof i=="string"?i.toLowerCase():void 0,l=typeof m=="string"?m.toLowerCase():void 0,v=n&&h&&d&&!!m&&!!p&&R(p)&&!!e&&!!r&&!!a,w=L(()=>["partner-whitelist","check",p,e,r,a,se(o)],[p,e,r,a,o]),g=ut({queryKey:w,enabled:v,staleTime:s,refetchInterval:u,retry:(x,U)=>{const T=U?.status;return typeof T=="number"&&T>=400&&T<500?!1:x<3},retryDelay:x=>Math.min(1e3*2**x,15e3),queryFn:async()=>{if(!p||!R(p))throw new Error("A valid wallet address is required");if(!e||!r||!a)throw new Error("campaignId, campaignGroup, and partnerId are required");const x=se(o),U={campaignId:e,campaignGroup:r,partnerId:a},T=await Qt(x,p);return T?Vt(x,T,U):{walletAddress:p,campaignId:e,campaignGroup:r,partnerId:a,isWhitelisted:!1,isLinkedWallet:!1,whitelistedWalletAddress:null,externalWalletAddress:p}}}),f=n&&h&&d&&!!l&&R(l)&&!!y&&R(y)&&!!e&&!!r&&!!a,b=ft({mutationFn:x=>Xt(se(o),{campaignId:e,campaignGroup:r,partnerId:a},x.external,x.embedded)}),E=ce(new Set),I=b.mutate;return A(()=>{if(!f||!l||!y||!e||!r||!a)return;const x=Yt(l,y);E.current.has(x)||(E.current.add(x),I({external:l,embedded:y}))},[f,l,y,e,r,a,I]),{isWhitelisted:g.data?.isWhitelisted??!1,whitelistCheck:g.data,checkedWalletAddress:p,externalWalletAddress:m,embeddedWalletAddress:i,isExternalWalletConnected:!!m,isWhitelistCheckEnabled:v,linkWallet:b,isWalletLinked:b.isSuccess,...g}}const Kt=["__spicenet_whitelist_blocked__"],Ae="spiceflow-mode",Pe=()=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Ae);return t==="7702"?"7702":t==="non7702"?"ondemand":t==="embedded"?"7702":t==="external"?"ondemand":null}catch{return null}},Zt=t=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Ae,t==="7702"?"7702":"non7702")}catch{}},er=()=>Pe()!==null,Re=ue(null),H=ue(null),tr=({children:t,value:e,whitelist:r})=>{const a=!!r&&r.enabled!==!1,{isWhitelisted:o,isLoading:n,whitelistCheck:s}=Te(a?r:{enabled:!1}),u=a&&!o,h=L(()=>({...e,mode:u?"ondemand":e.mode,allowedTokens:u?Kt:e.allowedTokens,isUserWhitelisted:o,isWhitelistChecking:n,isWhitelistConfigured:a,isWhitelistGateActive:u,whitelistCheck:s}),[e,a,u,o,n,s]);return $(H.Provider,{value:h,children:t})},rr=({children:t,provider:e="privy",supportedChainIds:r,allowedTokens:a,network:o="testnet",mode:n,skipFlow:s=[],nativeChainId:u,appName:h="Spicenet",apiUrl:d,theme:m,rpcOverrides:i,swapper:c,whitelist:p})=>{A(()=>{if(!d)return;const x=P.getBaseUrl();return P.setBaseUrl(d),()=>P.setBaseUrl(x)},[d]),A(()=>(be(i),()=>be(void 0)),[i]);const y=L(()=>Ve(o),[o]),l=r??y,v=m??null,[w,g]=M(()=>n??Pe()??"7702");A(()=>{n&&g(n)},[n]);const f=De(x=>{if(n){g(n);return}g(x),Zt(x)},[n]),{embeddedAddress:b,externalAddress:E}=oe(),I=L(()=>({provider:e,supportedChainIds:l,allowedTokens:a,skipFlow:s,mode:w,setMode:f,network:o,nativeChainId:u,appName:h,apiUrl:d,rpcOverrides:i,swapper:c,embeddedWalletAddress:b,externalWalletAddress:E,isUserWhitelisted:null,isWhitelistChecking:!1,isWhitelistConfigured:!1,isWhitelistGateActive:!1}),[e,l,a,s,w,f,o,u,h,d,i,c,b,E]);return $(Re.Provider,{value:v,children:$(H.Provider,{value:I,children:$(tr,{value:I,whitelist:p,children:t})})})},ar={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:D.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"}},nr={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"},or={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"},We=(t="light")=>({mode:t,...ar,colors:t==="light"?nr:or});function J(t,e){const r=t.replace("#",""),a=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))),n=Math.max(0,Math.round(parseInt(r.substring(4,6),16)*(1-e)));return`#${a.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`}function sr(t,e){return{shell:e?.shell??"#141414",shellBorder:e?.shellBorder??J(e?.shell??"#141414",.35),shellInnerBorder:e?.shellInnerBorder??J(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 ir(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 Ue(t,e){const r=e?{...t,...e}:t,a=r.dark??!1,o=r.primaryColor,n=r.shell??(a?"#141414":"#ffffff");return{primaryColor:o,dark:a,fontFamily:r.fontFamily??'"Helvetica Neue", sans-serif',appName:r.appName??"Spicenet",logo:r.logo,borderRadius:r.borderRadius??"8px",shell:n,shellBorder:J(n,a?.35:.085),shellInnerBorder:J(n,a?.55:.165),card:r.card??(a?"#1e1e1e":"#f9fafb"),input:a?"#171717":"#ffffff",hover:a?"#2a2a2a":"#f3f4f6",text:r.text??(a?"#ffffff":"#111827"),textMuted:r.textMuted??(a?"#888888":"#6b7280"),inputText:a?"#e0e0e0":"#111827",inputPlaceholder:a?"#555555":"#9ca3af",border:r.border??(a?"rgba(255,255,255,0.08)":"#e5e7eb"),inputBorder:a?"rgba(255,255,255,0.10)":"#d1d5db",buttonBorder:a?"rgba(255,255,255,0.12)":"#0e0d0b",successBg:a?"#0a1f18":"#d1fae5",successBorder:a?"#1a4a3a":"#6ee7b7",successText:a?"#6ee7b7":"#065f46",warningBg:a?"#1f1a0d":"#fef3c7",warningBorder:a?"#4a3820":"#fde68a",warningText:a?"#fbbf24":"#92400e",errorBg:a?"#1f0d0d":"#fef2f2",errorBorder:a?"#4a2020":"#fecaca",errorText:a?"#f87171":"#dc2626",infoBg:a?"#0d1325":"#dbeafe",infoBorder:a?"#2a3a5a":"#93c5fd",infoText:a?"#60a5fa":"#1e40af"}}const lr=D.mono;function Ne(t,e){const r=de(Re)??void 0;return L(()=>{const a=r??{primaryColor:"#EA4B4B"},o={...t?.primaryColor?{primaryColor:t.primaryColor}:{},...t?.fontFamily?{fontFamily:t.fontFamily}:{},...e!==void 0?{dark:e}:{}},n=Ue(a,o),{dark:s,primaryColor:u,appName:h}=n,d=We(s?"dark":"light"),m={...d,colors:{...d.colors,primary:u,primaryHover:`${u}dd`},typography:{...d.typography,fontFamily:n.fontFamily}},i={shell:n.shell,shellBorder:n.shellBorder,shellInnerBorder:n.shellInnerBorder,cardBg:n.card,inputBg:n.input,hoverBg:n.hover,textPrimary:n.text,textSecondary:n.textMuted,inputText:n.inputText,inputPlaceholder:n.inputPlaceholder,cardBorder:n.border,inputBorder:n.inputBorder,buttonBorder:n.buttonBorder,successBg:n.successBg,successBorder:n.successBorder,successText:n.successText,warningBg:n.warningBg,warningBorder:n.warningBorder,warningText:n.warningText,errorBg:n.errorBg,errorBorder:n.errorBorder,errorText:n.errorText,infoBg:n.infoBg,infoBorder:n.infoBorder,infoText:n.infoText},c=t?.inputVariant?t.inputVariant==="dark":s;return{brand:r,theme:m,dark:s,appName:h,primaryColor:u,dk:i,palette:i,fontFamily:n.fontFamily,monoFont:lr,inputDark:c,cardBg:c?i.cardBg:"#E9E9E9",cardBorder:c?i.cardBorder:"#C6C6C6",textPrimary:i.textPrimary,textSecondary:i.textSecondary,subtitleText:c?i.textSecondary:"#979AA0"}},[r,t,e])}const dr=(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(/\.$/,""),cr=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",Fe=(t,e=6,r=4)=>t.length<=e+r?t:`${t.slice(0,e)}...${t.slice(-r)}`,ur=(t,e)=>{const r=t.replace(/[^0-9.]/g,"").split("."),a=r[0]??"",o=r.slice(1).join(""),n=typeof e=="number"?Math.max(0,Math.min(e,18)):null;return r.length===1?a:`${a}.${n===null?o:o.slice(0,n)}`},fr=(t,e=6)=>!Number.isFinite(t)||t<=0?"0":t.toFixed(Math.min(Math.max(e,0),18)).replace(/\.?0+$/,""),pr=async t=>{try{return await navigator.clipboard.writeText(t),!0}catch(e){return console.error("Failed to copy to clipboard:",e),!1}},Le="spiceflow-spinner-keyframes";function mr(){if(typeof document>"u"||document.getElementById(Le))return;const t=document.createElement("style");t.id=Le,t.textContent="@keyframes spiceflow-spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}",document.head.appendChild(t)}const ie=({size:t=16,borderWidth:e=2,color:r="currentColor",style:a})=>{const o=ce(!1);return A(()=>{o.current||(mr(),o.current=!0)},[]),$("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,...a}})},O=({variant:t="primary",size:e="md",loading:r=!1,fullWidth:a=!1,disabled:o,children:n,className:s="",style:u,theme:h,styles:d,dark:m,...i})=>{const{theme:c,dark:p,palette:y}=Ne(d,m),l=h||c,v=m??p,[w,g]=M(!1),[f,b]=M(!1),E=v?y.shell:"white",I=()=>{switch(t){case"primary":return{backgroundColor:d?.button?.backgroundColor||l.colors.primary,color:d?.button?.color||"#ffffff",border:`1px solid ${d?.button?.backgroundColor||l.colors.primary}`};case"secondary":return{backgroundColor:l.colors.secondary,color:l.colors.text,border:`1px solid ${l.colors.border}`};case"success":return{backgroundColor:l.colors.success,color:l.colors.text,border:`1px solid ${l.colors.success}`};case"error":return{backgroundColor:l.colors.error,color:l.colors.text,border:`1px solid ${l.colors.error}`};case"ghost":return{backgroundColor:"transparent",color:l.colors.textSecondary,border:`1px solid ${l.colors.border}`};case"outline":{const C=d?.button?.backgroundColor||l.colors.primary,le=d?.button?.color||(v?"#ffffff":"#0e0d0b"),N=d?.button?.borderColor||(v?`${l.colors.primary}88`:"#0e0d0b"),F=o||r,Me=v?"1px":"1.5px",qe=d?.button?.disabledBackgroundColor||`${C}88`,Oe=d?.button?.disabledColor||le;return{height:"56px",backgroundColor:F?qe:f?`${C}cc`:w?`${C}ee`:C,color:F?Oe:le,border:`${Me} solid ${N}`,borderRadius:d?.button?.borderRadius||"12px",fontSize:"22px",fontWeight:500,fontFamily:D.mono,opacity:F?.78:1,transform:F?"none":f?"scale(0.98)":w?"translateY(-2px)":"none",boxShadow:F?`3px 3px 0px ${E}, 4px 4px 0px ${N}`:f?`2px 2px 0px ${N}`:w?`5px 5px 0px ${E}, 6px 6px 0px ${N}`:`3px 3px 0px ${E}, 4px 4px 0px ${N}`,transition:"transform 150ms ease, box-shadow 150ms ease, background-color 150ms ease, border-color 150ms ease, color 150ms ease"}}default:return{}}},x=()=>{if(t==="outline")return{};switch(e){case"sm":return{padding:`${l.spacing.sm} ${l.spacing.md}`,fontSize:l.typography.fontSize.sm};case"md":return{padding:`${l.spacing.md} ${l.spacing.lg}`,fontSize:l.typography.fontSize.base};case"lg":return{padding:`${l.spacing.lg} ${l.spacing.xl}`,fontSize:l.typography.fontSize.lg};default:return{}}},U={borderRadius:d?.button?.borderRadius||l.borderRadius.md,fontWeight:d?.button?.fontWeight||l.typography.fontWeight.medium,fontFamily:d?.button?.fontFamily||l.typography.fontFamily,fontSize:d?.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:a?"100%":"auto",display:"flex",alignItems:"center",justifyContent:"center",gap:l.spacing.sm,...I(),...x(),...d?.button?.fontSize&&{fontSize:d.button.fontSize}},T=o||r;return Y("button",{type:i.type??"button","data-spiceflow-focus":!0,"aria-busy":r||void 0,"aria-disabled":T||void 0,style:{...U,...u},className:s,disabled:T,onMouseEnter:C=>{g(!0),i.onMouseEnter?.(C)},onMouseLeave:C=>{g(!1),b(!1),i.onMouseLeave?.(C)},onMouseDown:C=>{b(!0),i.onMouseDown?.(C)},onMouseUp:C=>{b(!1),i.onMouseUp?.(C)},...i,children:[r&&$(ie,{size:16}),n]})},hr=({onAuthSuccess:t,onAuthError:e,theme:r="light",className:a="",buttonText:o="Login with Privy",autoTrigger:n=!1})=>{const s=We(r),[u,h]=M(!1),[d,m]=M(!1),{ready:i,authenticated:c,user:p}=X(),{login:y}=dt(),{logout:l}=ct();A(()=>{h(!0)},[]),A(()=>{n&&i&&!c&&u&&!d&&(m(!0),v())},[n,i,c,u,d]),A(()=>{if(i&&c&&p&&t){const g=p.wallet?.address||p.email?.address;g&&t(g)}},[i,c,p,t]),A(()=>{},[i,c,e]);const v=()=>{try{y()}catch(g){const f=`Login failed: ${String(g)}`;e?e(f):console.error(f)}},w=()=>{try{l()}catch(g){const f=`Logout failed: ${String(g)}`;e?e(f):console.error(f)}};if(!u)return $("div",{className:a,children:$(O,{variant:"primary",disabled:!0,theme:s,children:o})});if(!i)return $("div",{className:a,children:$(O,{variant:"primary",disabled:!0,theme:s,children:"Loading..."})});if(c&&p){const g=p.wallet?.address||p.email?.address,f=g?Fe(g):"Connected";return $("div",{className:a,children:Y(O,{variant:"primary",onClick:w,theme:s,children:["Logout (",f,")"]})})}return n?$("div",{className:a,children:Y("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px",flexDirection:"column",gap:"12px"},children:[$(ie,{size:40,borderWidth:3,color:"#3b82f6"}),$("p",{style:{color:"#6b7280",fontSize:"14px"},children:"Opening login..."})]})}):$("div",{className:a,children:$(O,{variant:"primary",onClick:v,theme:s,children:o})})};export{Et as A,O as B,vt as C,Ct as D,_t as E,St as F,oe as G,kt as H,Tt as I,_ as J,pr as K,er as L,ke as M,rr as N,Te as O,hr as P,Ue as Q,Ee as R,H as S,sr as T,ir as U,te as V,W as a,we as b,ee as c,dr as d,fr as e,D as f,Bt as g,k as h,B as i,cr as j,ie as k,Fe as l,Ut as m,ve as n,j as o,ur as p,S as q,mt as r,At as s,ht as t,Ne as u,P as v,$t as w,Ie as x,Ot as y,pt as z};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
"use strict";var Re=Object.create;var oe=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Ne=Object.getPrototypeOf,Fe=Object.prototype.hasOwnProperty;var Me=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ue(t))!Fe.call(e,o)&&o!==r&&oe(e,o,{get:()=>t[o],enumerable:!(a=We(t,o))||a.enumerable});return e};var Le=(e,t,r)=>(r=e!=null?Re(Ne(e)):{},Me(t||!e||!e.__esModule?oe(r,"default",{value:e,enumerable:!0}):r,e));const $=require("react/jsx-runtime"),y=require("react"),k=require("@spicenet-io/spiceflow-core"),x=require("viem"),je=require("viem/actions"),I=require("@privy-io/react-auth"),se=require("wagmi"),ie=require("@tanstack/react-query"),qe={base:0,raised:1,sticky:10,overlay:20,popover:40,modal:1e3,dropdown:1100,toast:1200,tooltip:1300},Oe={none:"0",sm:"4px",md:"6px",card:"8px",input:"10px",shell:"9px",modal:"12px",pill:"9999px",circle:"50%"},A={out:"cubic-bezier(0.22, 1, 0.36, 1)",inOut:"cubic-bezier(0.65, 0, 0.35, 1)",linear:"linear"},T={fast:"120ms",normal:"150ms",slow:"300ms",progress:"400ms"},De={interactive:`transform ${T.normal} ${A.out}, box-shadow ${T.normal} ${A.out}, background-color ${T.normal} ${A.out}, border-color ${T.normal} ${A.out}, color ${T.normal} ${A.out}`,color:`background-color ${T.normal} ${A.out}, border-color ${T.normal} ${A.out}, color ${T.normal} ${A.out}`,popover:`opacity ${T.normal} ${A.out}, transform ${T.normal} ${A.out}`},O={ui:'"Helvetica Neue", sans-serif',mono:'"IBM Plex Mono", monospace'};function D(e,t){return!e||!t?!1:x.isAddress(e)&&x.isAddress(t)?x.getAddress(e)===x.getAddress(t):e.toLowerCase()===t.toLowerCase()}const ze="0xcA11bde05977b3631167028862bE2a173976CA11",_e={4114:"0x860aFc632a6D625B95d8B96f39ECC48E988c6962"},Ge=new Set([5115]);function He(e){const t=_e[e.id]??(Ge.has(e.id)?void 0:ze);return x.defineChain({id:e.id,name:e.name,nativeCurrency:e.nativeCurrency,rpcUrls:{default:{http:[e.rpcUrl]}},blockExplorers:{default:{name:e.displayName,url:e.blockExplorer}},testnet:e.network==="testnet",...t?{contracts:{multicall3:{address:t}}}:{}})}const Je=[1,8453,42161,4114,11155111,421614,84532,5115,123420001114,688688,688689],z=Object.fromEntries(Je.map(e=>k.getChainMeta(e)).filter(e=>e!=null).map(e=>[e.id,{...e,viemChain:He(e),supportedTokens:k.getTokensForChain(e.id)}])),Ye=z;let le={};const Y=new Map,ce=e=>{le={...e||{}},Y.clear()},Q=e=>{const t=le[e];return t&&typeof t=="string"&&t.length>0?t:z[e]?.rpcUrl},N=e=>z[e],V=e=>{const t=k.getChainMeta(e);return t?.displayName||t?.name||`Chain ${e}`},Qe=e=>{const t=k.getDelegateContract(e);if(!t)throw new Error(`Unsupported chain ID: ${e}`);return t},Ve=(e,t,r)=>{const a=N(e);return a?.blockExplorer?`${a.blockExplorer}/tx/${t}`:"#"};async function Xe(e,t){const r=`0x${t.toString(16)}`;try{await e.request({method:"wallet_switchEthereumChain",params:[{chainId:r}]});return}catch(o){if(!(o?.code===4902||typeof o?.message=="string"&&o.message.includes("Unrecognized chain ID")))throw o}const a=N(t);if(!a)throw new Error(`Cannot add unknown chain ${t} to wallet`);await e.request({method:"wallet_addEthereumChain",params:[{chainId:r,chainName:a.name||`Chain ${t}`,nativeCurrency:a.nativeCurrency||{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:[Q(t)||a.rpcUrl],blockExplorerUrls:a.blockExplorer?[a.blockExplorer]:void 0}]})}const de=e=>{const t=N(e);if(!t)throw new Error(`Unsupported chain ID: ${e}`);const r=Q(e);if(!r)throw new Error(`No RPC URL configured for chain ID: ${e}`);const a=`${e}:${r}`,o=Y.get(a);if(o)return o;const n=x.createPublicClient({chain:t.viemChain,transport:x.http(r,{timeout:15e3,retryCount:2,retryDelay:300}),batch:{multicall:{wait:16}}});return Y.set(a,n),n},Ke=()=>{const e={};return Object.values(z).forEach(t=>{e[t.id]={name:t.name,moralisName:t.moralisId||"",chain:t.viemChain,rpcUrl:Q(t.id)||t.rpcUrl}}),e},Ze=(e,t=[])=>{const r=N(e);if(!r)return[];const a=[];if(![11155111,421614,84532,688689].includes(e)){const n=t.find(s=>s.chainId===e&&s.isNative);n?a.push(n):a.push({address:k.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:e})}if(!r.supportedTokens)return a;const o=a.some(n=>n.isNative);return r.supportedTokens.forEach(n=>{if(o&&k.isNativeToken(n.address))return;const s=t.find(u=>u.chainId===e&&D(u.address,n.address));s?a.push(s):a.push({address:n.address,name:n.name,symbol:n.symbol,decimals:n.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:n.logo,isNative:!1,chainId:e})}),a},et=async(e,t)=>{const r=N(e);if(!r)throw new Error(`Unsupported chain ID: ${e}`);const a=t.toLowerCase();if(k.isNativeToken(a)){if(!r.nativeCurrency?.decimals)throw new Error(`Native currency decimals not configured for chain ${e}`);return r.nativeCurrency.decimals}if(r.supportedTokens){const o=r.supportedTokens.find(n=>D(n.address,a));if(o)return o.decimals}try{if(!x.isAddress(t,{strict:!1}))throw new Error(`Invalid token address: ${t}`);const o=x.getAddress(t),n=de(e),s=await je.readContract(n,{address:o,abi:x.erc20Abi,functionName:"decimals"});return Number(s)}catch{throw new Error(`Could not determine decimals for token ${t} on chain ${e}`)}};class P extends Error{constructor(t,r,a={}){super(r),this.code=t,this.context=a,this.name="SpiceflowError",Error.captureStackTrace&&Error.captureStackTrace(this,P)}}function X(e){return e instanceof P}const tt=["user rejected","user denied","user cancelled","rejected the request","action_rejected","4001"];function ue(e){if(!e)return"";if(typeof e=="string")return e;const t=e,r=t.message||t.reason||"",a=t.details||"";return`${r} ${a}`.trim()}const fe=e=>{if(X(e))return e.code==="WALLET_REJECTED";const t=ue(e).toLowerCase();return tt.some(r=>t.includes(r))};let K=null;function rt(e){return K?.message===e?K.detail:void 0}const at=(e,t="Something went wrong. Please try again.")=>{if(fe(e))return"Transaction was rejected.";if(X(e)){const r=e.message||t,{requestId:a,httpStatus:o,responseBody:n,endpoint:s}=e.context;return(a||o||s)&&(K={message:r,detail:{requestId:a,httpStatus:o,responseBody:n,endpoint:s}}),r}return ue(e)||t},nt=[...k.DELEGATE_ABI,...k.ERC20_ABI,...k.spicenetEscrowAbi,...k.uniV3SwapRouterAbi];function Z(e,t=0){return t>4||e==null?[]:typeof e=="string"?e.match(/0x[0-9a-fA-F]{8,}/g)??[]:Array.isArray(e)?e.flatMap(r=>Z(r,t+1)):typeof e=="object"?Object.values(e).flatMap(r=>Z(r,t+1)):[]}function pe(e){try{const t=x.decodeErrorResult({abi:nt,data:e});if(t.errorName==="Error")return String(t.args?.[0]??"");if(t.errorName==="Panic")return`Panic(${t.args?.[0]})`;if(t.errorName==="CallReverted"){const r=t.args?.[4],a=r&&r!=="0x"?pe(r):void 0;return a?`Call reverted: ${a}`:"Call reverted (no reason returned)"}return t.errorName}catch{try{const t=x.hexToString(e).replace(/\x00+$/g,"").trim();return/^[\x20-\x7e]+$/.test(t)&&t.length>1?t:void 0}catch{return}}}function ot(e){for(const t of Z(e)){if(!x.isHex(t))continue;const r=pe(t);if(r)return r}}function st(e,t){const r=t.match(/Output amount (\d+) is insufficient after fees (\d+) on chain (\d+)/);if(!r)return t;const[,a,o,n]=r,s=Number(n),u=BigInt(a),h=BigInt(o);let c;for(const v of e.intents){const g=v.chainBatches.find(f=>f.chainId===s);if(g){c=g;break}}const m=c?.tokenTransfers.find(v=>v.from==="escrow"&&D(v.to,e.user)&&!k.isNativeToken(v.token)),i=V(s);if(!m)return`Amount is too small to cover the estimated fee on ${i}.`;const d=k.getTokenByAddress(m.token,s),p=d?.decimals??18,w=d?.symbol??"tokens",l=x.formatUnits(u,p),C=x.formatUnits(h,p);return`Amount is too small to cover the estimated fee on ${i}. Amount: ${l} ${w}. Estimated fee: ${C} ${w}.`}function it(e){return e?.code===4902||e?.name==="ChainNotConfiguredError"?"This network is not configured in your wallet. Please add it manually to continue.":e?.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 lt="https://tx-submission-api.spicenet.io",me=lt;function ct(e,t){return typeof t=="bigint"?t.toString():t}async function _(e,t){const r={...t?.headers},a=r["x-request-id"]??crypto.randomUUID();r["x-request-id"]=a;const o=await fetch(e,{...t,headers:r}),n=o.headers.get("x-request-id")??"";return Object.assign(o,{requestId:n})}function j(e,t){if(!e)return t;const r=e.error,a=(typeof e.message=="string"?e.message:"")||(r&&typeof r=="object"&&"message"in r&&typeof r.message=="string"?r.message:"")||(typeof r=="string"?r:"")||t,o=ot(e);return o&&!a.includes(o)?`${a} \u2014 ${o}`:a}async function dt(e){try{return await e.json()}catch{return null}}function ut(e){return(Array.isArray(e?.balances)?e.balances:[]).flatMap(t=>{if(!t||typeof t!="object")return[];const r=t;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(a=>typeof a=="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 ft{constructor(){this.baseUrl=me}setBaseUrl(t){this.baseUrl=t}getBaseUrl(){return this.baseUrl}async requestJson(t,r){const a=`${this.baseUrl}${t}`,o=await _(a,r.method&&r.method!=="GET"?{method:r.method,headers:{"Content-Type":"application/json"},body:JSON.stringify(r.body,ct)}:void 0),n=await o.json();if(!o.ok||n.success===!1||r.ok&&!r.ok(n)){const s=j(n,r.fallbackError(o.status));throw new P(r.code??"RELAYER_ERROR",r.mapError?r.mapError(s):s,{httpStatus:o.status,requestId:o.requestId,responseBody:JSON.stringify(n),endpoint:t,...r.context})}return n}async createAction(t){return this.requestJson("/actions",{method:"POST",body:t,fallbackError:r=>`Relayer API error: ${r}`})}async estimateActionFees(t){return(await this.requestJson("/actions/fees/estimate",{method:"POST",body:t,fallbackError:r=>`Relayer fee estimate error: ${r}`,ok:r=>!!r.success&&!!r.data?.feeEstimate,mapError:r=>st(t,r)})).data.feeEstimate}async estimateBatchGas(t){const r=await this.requestJson("/actions/gas/estimate",{method:"POST",body:t,fallbackError:a=>`Relayer gas estimate error: ${a}`,ok:a=>!!a.success&&!!a.data?.gasFee});return{gasFee:BigInt(r.data.gasFee),gasQuoteSource:r.data.gasQuoteSource}}async executeStep(t,r,a,o){const n=`${this.baseUrl}/actions/${t}/intents/${r}/steps/${a}`,s=`/actions/${t}/intents/${r}/steps/${a}`,u=crypto.randomUUID(),h=3e4,c=new Promise((d,p)=>setTimeout(()=>p(new P("RELAYER_EXECUTE_ERROR",`Execute step request timed out after ${h/1e3}s`,{actionId:t,intentIndex:r,stepIndex:a,endpoint:s,requestId:u})),h)),m=await Promise.race([_(n,{method:"POST",headers:{"Content-Type":"application/json","x-request-id":u},body:JSON.stringify(o)}),c]),i=await m.json();if(!m.ok||i.success===!1)throw new P("RELAYER_EXECUTE_ERROR",j(i,`Execute step error: ${m.status}`),{httpStatus:m.status,requestId:m.requestId,responseBody:JSON.stringify(i),endpoint:s,actionId:t});if(i?.status==="error"||i?.status==="reverted"){const d=j(i,""),p=d?`: ${d}`:"";throw new P("RELAYER_EXECUTE_ERROR",`Step ${a} previously ${i.status}${p}`,{httpStatus:m.status,requestId:m.requestId,responseBody:JSON.stringify(i),endpoint:s,actionId:t,intentIndex:r,stepIndex:a,stepStatus:i.status})}return{success:!0,transactionHash:i.transactionHash}}async checkStepStatus(t,r){const a=t.split("/"),o=a[0],n=a.length>=2?a[1]:"0",s=await this.requestJson(`/actions/${o}/intents/${n}/steps/${r}`,{fallbackError:u=>`Intent step status check failed: ${u}`,code:"RELAYER_STATUS_ERROR",context:{intentId:t}});return{success:!0,data:{status:s.status==="error"?"reverted":s.status,transactionHash:s.txid,error:j(s,"")}}}async createWallet(t,r){return this.requestJson(`/wallets/${t}`,{method:"PUT",body:r,fallbackError:a=>`Create wallet error: ${a}`})}async getWallet(t){return this.requestJson(`/wallets/${t}`,{fallbackError:r=>`Get wallet error: ${r}`})}async createWithdrawal(t){return this.requestJson("/withdrawals",{method:"POST",body:t,fallbackError:r=>`Create withdrawal error: ${r}`})}async getWithdrawal(t){return this.requestJson(`/withdrawals/${t}`,{fallbackError:r=>`Get withdrawal error: ${r}`})}async getRollupTimestamp(){return this.requestJson("/time",{fallbackError:t=>`Get rollup timestamp error: ${t}`})}}const U=new ft;async function pt(e){const t=`${U.getBaseUrl()}/wallets/${e}/balance`,r=await _(t,{cache:"no-store"}),a=await dt(r);if(!r.ok||a?.success===!1)throw new P("RELAYER_ERROR",j(a,`Unable to verify Spice balance: ${r.status}`),{httpStatus:r.status,requestId:r.requestId,responseBody:JSON.stringify(a),endpoint:`/wallets/${e}/balance`});return ut(a)}const ee=new Map,mt="spiceflow.smartWallet.";function he(e){return`${mt}${e.toLowerCase()}`}function ht(e){try{return typeof localStorage<"u"&&localStorage.getItem(he(e))==="1"}catch{return!1}}function ge(e){try{typeof localStorage<"u"&&localStorage.setItem(he(e),"1")}catch{}}function gt(e){if(!(e instanceof P))return!1;const t=e.context.httpStatus;return t===400||t===404?`${e.message} ${String(e.context.responseBody??"")}`.toLowerCase().includes("not found"):!1}async function ye(e,t){if(ht(e))return;const r=e.toLowerCase(),a=ee.get(r);if(a)return a;const o=(async()=>{try{await U.getWallet(e),ge(e);return}catch(c){if(!gt(c))throw c}const{unix_timestamp:n}=await U.getRollupTimestamp(),s=`I am creating a new smart wallet and adding an admin wallet ethereum:0x${e.slice(2).toLowerCase()}. Nonce: ${n}`,u=await t(s),h=typeof u=="string"?u:u.signature;if(!h)throw new Error("Wallet returned no smart wallet signature");await U.createWallet(e,{timestamp:n,signature:h}),ge(e)})();ee.set(r,o);try{await o}finally{ee.delete(r)}}const yt=(e,t)=>{const r=o=>t?t(o):V(o),a=[];return e.forEach((o,n)=>{const s=o.calls&&o.calls.length>0,u=o.tokenTransfers&&o.tokenTransfers.length>0;!s&&!u||a.push({stepId:n,status:n===0?"processing":"pending",chainId:o.chainId,chainName:r(o.chainId),description:"Processing transaction"})}),a},wt=e=>{const t=e?.wallet;if(t?.address&&t.walletClientType==="privy"&&t.connectorType==="embedded"&&!t.imported)return t.address},we=async(e,t)=>{if(!e?.address)throw new Error("Wallet not available");if(typeof e.getWalletClient=="function"){const r=t===void 0?[void 0]:[String(t),t,void 0];let a=null;for(const o of r)try{const n=await e.getWalletClient(o);if(n)return n}catch(n){a=n}if(a)throw a}if(typeof e.getEthereumProvider=="function"){const r=await e.getEthereumProvider(),a=t?N(t)?.viemChain:void 0;return x.createWalletClient({account:e.address,chain:a,transport:x.custom(r)})}throw new Error("Wallet client not available")},bt=async(e,t)=>{if(!e?.address)throw new Error("Wallet not available");if(typeof e.getEthereumProvider=="function")return e.getEthereumProvider();const r=await we(e,t);return{request:a=>r.request(a)}},G=e=>e?.address?{address:e.address,wallet:e,getWalletClient:t=>we(e,t),getEthereumProvider:t=>bt(e,t)}:null,te=()=>{const{address:e,connector:t}=se.useAccount();let r=null,a=null;try{r=I.useWallets(),{user:a}=I.usePrivy()}catch{r=null,a=null}const o=r?.wallets||[],n=I.getEmbeddedConnectedWallet(o),s=n?.address?.toLowerCase(),u=o.find(l=>l.connectorType!=="embedded"&&l.address?.toLowerCase()!==s),h=e?.toLowerCase(),c=e&&t&&!(h&&s&&h===s)?{address:e,connector:t,getEthereumProvider:()=>t.getProvider()}:null,m=e&&t?{address:e,connector:t,getEthereumProvider:()=>t.getProvider()}:null,i=G(n),d=G(c)||G(u),p=i?.address||wt(a),w=G(m)||d;return{embeddedWallet:i,externalWallet:d,embeddedAddress:p,externalAddress:d?.address,activeWallet:w,activeAddress:w?.address}},be=()=>{const e=y.useContext(H),t=e?.mode,{isConnected:r,address:a}=se.useAccount();let o=null,n=null,s=null,u=null,h=null;try{o=I.usePrivy(),n=I.useSign7702Authorization(),s=I.useSignMessage(),u=I.useWallets()}catch(f){h=f instanceof Error?f.message:String(f)}if(h)return t==="ondemand"&&r&&a?{isReady:!0,isAuthenticated:!0,isConnected:!0,address:a,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{ready:c=!1,authenticated:m=!1}=o||{},i=e?.embeddedWalletAddress,d=I.getEmbeddedConnectedWallet(u?.wallets||[]),p=i||d?.address,w=!!p&&!!d,l={isReady:t==="ondemand"?!0:c,isAuthenticated:t==="ondemand"?!0:m||w,isConnected:t==="ondemand"?r&&!!a||c&&(m||w)&&w:c&&w,address:t==="ondemand"&&r?a:p,provider:"privy"},C=async f=>{if(!d)throw new Error("Embedded wallet not available");const b=await d.getEthereumProvider(),{createWalletClient:B,custom:R}=await import("viem");return{signature:await B({account:d.address,transport:R(b)}).signMessage({account:d.address,message:f})}},v=async f=>{if(s)try{return{signature:(await s.signMessage({message:f})).signature}}catch(b){if(!d)throw b}if(!d)throw new Error("Privy sign message not available");return C(f)},g=async()=>{if(!p)throw new Error("Embedded wallet not available for smart wallet setup");await ye(p,v)};return{...l,actions:{signAuthorization:async f=>{if(!n)throw new Error("Privy sign authorization not available");try{await g();const b=await n.signAuthorization({contractAddress:f.contractAddress,chainId:f.chainId,nonce:f.nonce},{address:p});return delete b.v,b}catch(b){const B=typeof b?.message=="string"?b.message:String(b?.message??b??"");throw B.includes("not configured")||B.includes("chain")?new Error(`Chain ${f.chainId} is not configured in PrivyProvider. Add this chain to your Privy dashboard or supportedChainIds.`):b}},signMessage:async f=>{if(typeof f=="object"&&"raw"in f){if(await g(),!d)throw new Error("Embedded wallet not available for raw signing");return C(f)}return v(f)},getEthereumProvider:async()=>{if(!d)throw new Error("Embedded wallet not available");return d.getEthereumProvider()}}}},xt="https://portal-api.spicenet.io/api/v1",re=e=>e.replace(/\/+$/,""),vt=(e,t)=>`${e}:${t}`;async function Et(e,t){const r=new URLSearchParams({walletAddress:t,campaignId:"spicenet-portal",campaignGroup:"1"}),a=await fetch(`${e}/portal/mainnet/linked-portal-wallet?${r.toString()}`,{cache:"no-store"});if(!a.ok){if(a.status>=500){const o=new Error(`Failed to resolve linked portal wallet: ${a.status}`);throw o.status=a.status,o}return null}return(await a.json()).portalWalletAddress?.toLowerCase()??null}async function $t(e,t,r){const a=new URLSearchParams({walletAddress:t,campaignId:r.campaignId,campaignGroup:r.campaignGroup,partnerId:r.partnerId}),o=await fetch(`${e}/portal/mainnet/whitelist/check?${a.toString()}`,{cache:"no-store"});if(!o.ok){const n=new Error(`Failed to check whitelist: ${o.status}`);throw n.status=o.status,n}return await o.json()}async function Ct(e,t,r,a){const o=await fetch(`${e}/portal/mainnet/link-wallet`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({campaignId:t.campaignId,campaignGroup:t.campaignGroup,partnerId:t.partnerId,externalWalletAddress:r,embeddedWalletAddress:a})});if(!o.ok)throw new Error(`Failed to link wallet: ${o.status}`)}function xe({walletAddress:e,campaignId:t,campaignGroup:r,partnerId:a,apiBaseUrl:o=xt,enabled:n=!0,staleTime:s=5*60*1e3,refetchInterval:u=!1}={}){const{isAuthenticated:h,isConnected:c}=be(),{externalAddress:m,embeddedAddress:i}=te(),d=e??m,p=typeof d=="string"?d.toLowerCase():void 0,w=typeof i=="string"?i.toLowerCase():void 0,l=typeof m=="string"?m.toLowerCase():void 0,C=n&&h&&c&&!!m&&!!p&&x.isAddress(p)&&!!t&&!!r&&!!a,v=y.useMemo(()=>["partner-whitelist","check",p,t,r,a,re(o)],[p,t,r,a,o]),g=ie.useQuery({queryKey:v,enabled:C,staleTime:s,refetchInterval:u,retry:(E,F)=>{const W=F?.status;return typeof W=="number"&&W>=400&&W<500?!1:E<3},retryDelay:E=>Math.min(1e3*2**E,15e3),queryFn:async()=>{if(!p||!x.isAddress(p))throw new Error("A valid wallet address is required");if(!t||!r||!a)throw new Error("campaignId, campaignGroup, and partnerId are required");const E=re(o),F={campaignId:t,campaignGroup:r,partnerId:a},W=await Et(E,p);return W?$t(E,W,F):{walletAddress:p,campaignId:t,campaignGroup:r,partnerId:a,isWhitelisted:!1,isLinkedWallet:!1,whitelistedWalletAddress:null,externalWalletAddress:p}}}),f=n&&h&&c&&!!l&&x.isAddress(l)&&!!w&&x.isAddress(w)&&!!t&&!!r&&!!a,b=ie.useMutation({mutationFn:E=>Ct(re(o),{campaignId:t,campaignGroup:r,partnerId:a},E.external,E.embedded)}),B=y.useRef(new Set),R=b.mutate;return y.useEffect(()=>{if(!f||!l||!w||!t||!r||!a)return;const E=vt(l,w);B.current.has(E)||(B.current.add(E),R({external:l,embedded:w}))},[f,l,w,t,r,a,R]),{isWhitelisted:g.data?.isWhitelisted??!1,whitelistCheck:g.data,checkedWalletAddress:p,externalWalletAddress:m,embeddedWalletAddress:i,isExternalWalletConnected:!!m,isWhitelistCheckEnabled:C,linkWallet:b,isWalletLinked:b.isSuccess,...g}}const Bt=["__spicenet_whitelist_blocked__"],ve="spiceflow-mode",Ee=()=>{if(typeof window>"u")return null;try{const e=window.localStorage.getItem(ve);return e==="7702"?"7702":e==="non7702"?"ondemand":e==="embedded"?"7702":e==="external"?"ondemand":null}catch{return null}},kt=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(ve,e==="7702"?"7702":"non7702")}catch{}},St=()=>Ee()!==null,$e=y.createContext(null),H=y.createContext(null),It=({children:e,value:t,whitelist:r})=>{const a=!!r&&r.enabled!==!1,{isWhitelisted:o,isLoading:n,whitelistCheck:s}=xe(a?r:{enabled:!1}),u=a&&!o,h=y.useMemo(()=>({...t,mode:u?"ondemand":t.mode,allowedTokens:u?Bt:t.allowedTokens,isUserWhitelisted:o,isWhitelistChecking:n,isWhitelistConfigured:a,isWhitelistGateActive:u,whitelistCheck:s}),[t,a,u,o,n,s]);return $.jsx(H.Provider,{value:h,children:e})},At=({children:e,provider:t="privy",supportedChainIds:r,allowedTokens:a,network:o="testnet",mode:n,skipFlow:s=[],nativeChainId:u,appName:h="Spicenet",apiUrl:c,theme:m,rpcOverrides:i,swapper:d,whitelist:p})=>{y.useEffect(()=>{if(!c)return;const E=U.getBaseUrl();return U.setBaseUrl(c),()=>U.setBaseUrl(E)},[c]),y.useEffect(()=>(ce(i),()=>ce(void 0)),[i]);const w=y.useMemo(()=>k.getChainIdsByNetwork(o),[o]),l=r??w,C=m??null,[v,g]=y.useState(()=>n??Ee()??"7702");y.useEffect(()=>{n&&g(n)},[n]);const f=y.useCallback(E=>{if(n){g(n);return}g(E),kt(E)},[n]),{embeddedAddress:b,externalAddress:B}=te(),R=y.useMemo(()=>({provider:t,supportedChainIds:l,allowedTokens:a,skipFlow:s,mode:v,setMode:f,network:o,nativeChainId:u,appName:h,apiUrl:c,rpcOverrides:i,swapper:d,embeddedWalletAddress:b,externalWalletAddress:B,isUserWhitelisted:null,isWhitelistChecking:!1,isWhitelistConfigured:!1,isWhitelistGateActive:!1}),[t,l,a,s,v,f,o,u,h,c,i,d,b,B]);return $.jsx($e.Provider,{value:C,children:$.jsx(H.Provider,{value:R,children:$.jsx(It,{value:R,whitelist:p,children:e})})})},Tt={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:O.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"}},Pt={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"},Rt={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"},Ce=(e="light")=>({mode:e,...Tt,colors:e==="light"?Pt:Rt});function J(e,t){const r=e.replace("#",""),a=Math.max(0,Math.round(parseInt(r.substring(0,2),16)*(1-t))),o=Math.max(0,Math.round(parseInt(r.substring(2,4),16)*(1-t))),n=Math.max(0,Math.round(parseInt(r.substring(4,6),16)*(1-t)));return`#${a.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`}function Wt(e,t){return{shell:t?.shell??"#141414",shellBorder:t?.shellBorder??J(t?.shell??"#141414",.35),shellInnerBorder:t?.shellInnerBorder??J(t?.shell??"#141414",.55),cardBg:t?.cardBg??"#1e1e1e",inputBg:t?.inputBg??"#171717",hoverBg:t?.hoverBg??"#2a2a2a",textPrimary:t?.textPrimary??"#ffffff",textSecondary:t?.textSecondary??"#888888",inputText:t?.inputText??"#e0e0e0",inputPlaceholder:t?.inputPlaceholder??"#555555",cardBorder:t?.cardBorder??"rgba(255,255,255,0.08)",inputBorder:t?.inputBorder??"rgba(255,255,255,0.10)",buttonBorder:t?.buttonBorder??"rgba(255,255,255,0.12)",successBg:t?.successBg??"#0a1f18",successBorder:t?.successBorder??"#1a4a3a",successText:t?.successText??"#6ee7b7",warningBg:t?.warningBg??"#1f1a0d",warningBorder:t?.warningBorder??"#4a3820",warningText:t?.warningText??"#fbbf24",errorBg:t?.errorBg??"#1f0d0d",errorBorder:t?.errorBorder??"#4a2020",errorText:t?.errorText??"#f87171",infoBg:t?.infoBg??"#0d1325",infoBorder:t?.infoBorder??"#2a3a5a",infoText:t?.infoText??"#60a5fa"}}function Ut(e){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 Be(e,t){const r=t?{...e,...t}:e,a=r.dark??!1,o=r.primaryColor,n=r.shell??(a?"#141414":"#ffffff");return{primaryColor:o,dark:a,fontFamily:r.fontFamily??'"Helvetica Neue", sans-serif',appName:r.appName??"Spicenet",logo:r.logo,borderRadius:r.borderRadius??"8px",shell:n,shellBorder:J(n,a?.35:.085),shellInnerBorder:J(n,a?.55:.165),card:r.card??(a?"#1e1e1e":"#f9fafb"),input:a?"#171717":"#ffffff",hover:a?"#2a2a2a":"#f3f4f6",text:r.text??(a?"#ffffff":"#111827"),textMuted:r.textMuted??(a?"#888888":"#6b7280"),inputText:a?"#e0e0e0":"#111827",inputPlaceholder:a?"#555555":"#9ca3af",border:r.border??(a?"rgba(255,255,255,0.08)":"#e5e7eb"),inputBorder:a?"rgba(255,255,255,0.10)":"#d1d5db",buttonBorder:a?"rgba(255,255,255,0.12)":"#0e0d0b",successBg:a?"#0a1f18":"#d1fae5",successBorder:a?"#1a4a3a":"#6ee7b7",successText:a?"#6ee7b7":"#065f46",warningBg:a?"#1f1a0d":"#fef3c7",warningBorder:a?"#4a3820":"#fde68a",warningText:a?"#fbbf24":"#92400e",errorBg:a?"#1f0d0d":"#fef2f2",errorBorder:a?"#4a2020":"#fecaca",errorText:a?"#f87171":"#dc2626",infoBg:a?"#0d1325":"#dbeafe",infoBorder:a?"#2a3a5a":"#93c5fd",infoText:a?"#60a5fa":"#1e40af"}}const Nt=O.mono;function ke(e,t){const r=y.useContext($e)??void 0;return y.useMemo(()=>{const a=r??{primaryColor:"#EA4B4B"},o={...e?.primaryColor?{primaryColor:e.primaryColor}:{},...e?.fontFamily?{fontFamily:e.fontFamily}:{},...t!==void 0?{dark:t}:{}},n=Be(a,o),{dark:s,primaryColor:u,appName:h}=n,c=Ce(s?"dark":"light"),m={...c,colors:{...c.colors,primary:u,primaryHover:`${u}dd`},typography:{...c.typography,fontFamily:n.fontFamily}},i={shell:n.shell,shellBorder:n.shellBorder,shellInnerBorder:n.shellInnerBorder,cardBg:n.card,inputBg:n.input,hoverBg:n.hover,textPrimary:n.text,textSecondary:n.textMuted,inputText:n.inputText,inputPlaceholder:n.inputPlaceholder,cardBorder:n.border,inputBorder:n.inputBorder,buttonBorder:n.buttonBorder,successBg:n.successBg,successBorder:n.successBorder,successText:n.successText,warningBg:n.warningBg,warningBorder:n.warningBorder,warningText:n.warningText,errorBg:n.errorBg,errorBorder:n.errorBorder,errorText:n.errorText,infoBg:n.infoBg,infoBorder:n.infoBorder,infoText:n.infoText},d=e?.inputVariant?e.inputVariant==="dark":s;return{brand:r,theme:m,dark:s,appName:h,primaryColor:u,dk:i,palette:i,fontFamily:n.fontFamily,monoFont:Nt,inputDark:d,cardBg:d?i.cardBg:"#E9E9E9",cardBorder:d?i.cardBorder:"#C6C6C6",textPrimary:i.textPrimary,textSecondary:i.textSecondary,subtitleText:d?i.textSecondary:"#979AA0"}},[r,e,t])}const Ft=(e,t=4)=>!isFinite(e)||e===0?"0":e>0&&e<1e-6?e.toFixed(12).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""):e<1e-4?e.toFixed(8).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""):e.toFixed(t).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""),Mt=e=>isFinite(e)?e>0&&e<.01?"<$0.01":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(e):"$0.00",Se=(e,t=6,r=4)=>e.length<=t+r?e:`${e.slice(0,t)}...${e.slice(-r)}`,Lt=(e,t)=>{const r=e.replace(/[^0-9.]/g,"").split("."),a=r[0]??"",o=r.slice(1).join(""),n=typeof t=="number"?Math.max(0,Math.min(t,18)):null;return r.length===1?a:`${a}.${n===null?o:o.slice(0,n)}`},jt=(e,t=6)=>!Number.isFinite(e)||e<=0?"0":e.toFixed(Math.min(Math.max(t,0),18)).replace(/\.?0+$/,""),qt=async e=>{try{return await navigator.clipboard.writeText(e),!0}catch(t){return console.error("Failed to copy to clipboard:",t),!1}},Ie="spiceflow-spinner-keyframes";function Ot(){if(typeof document>"u"||document.getElementById(Ie))return;const e=document.createElement("style");e.id=Ie,e.textContent="@keyframes spiceflow-spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}",document.head.appendChild(e)}const ae=({size:e=16,borderWidth:t=2,color:r="currentColor",style:a})=>{const o=y.useRef(!1);return y.useEffect(()=>{o.current||(Ot(),o.current=!0)},[]),$.jsx("div",{role:"status","aria-label":"Loading",style:{width:`${e}px`,height:`${e}px`,border:`${t}px solid ${r}`,borderTop:`${t}px solid transparent`,borderRadius:"50%",animation:"spiceflow-spin 1s linear infinite",flexShrink:0,...a}})},q=({variant:e="primary",size:t="md",loading:r=!1,fullWidth:a=!1,disabled:o,children:n,className:s="",style:u,theme:h,styles:c,dark:m,...i})=>{const{theme:d,dark:p,palette:w}=ke(c,m),l=h||d,C=m??p,[v,g]=y.useState(!1),[f,b]=y.useState(!1),B=C?w.shell:"white",R=()=>{switch(e){case"primary":return{backgroundColor:c?.button?.backgroundColor||l.colors.primary,color:c?.button?.color||"#ffffff",border:`1px solid ${c?.button?.backgroundColor||l.colors.primary}`};case"secondary":return{backgroundColor:l.colors.secondary,color:l.colors.text,border:`1px solid ${l.colors.border}`};case"success":return{backgroundColor:l.colors.success,color:l.colors.text,border:`1px solid ${l.colors.success}`};case"error":return{backgroundColor:l.colors.error,color:l.colors.text,border:`1px solid ${l.colors.error}`};case"ghost":return{backgroundColor:"transparent",color:l.colors.textSecondary,border:`1px solid ${l.colors.border}`};case"outline":{const S=c?.button?.backgroundColor||l.colors.primary,ne=c?.button?.color||(C?"#ffffff":"#0e0d0b"),M=c?.button?.borderColor||(C?`${l.colors.primary}88`:"#0e0d0b"),L=o||r,Ae=C?"1px":"1.5px",Te=c?.button?.disabledBackgroundColor||`${S}88`,Pe=c?.button?.disabledColor||ne;return{height:"56px",backgroundColor:L?Te:f?`${S}cc`:v?`${S}ee`:S,color:L?Pe:ne,border:`${Ae} solid ${M}`,borderRadius:c?.button?.borderRadius||"12px",fontSize:"22px",fontWeight:500,fontFamily:O.mono,opacity:L?.78:1,transform:L?"none":f?"scale(0.98)":v?"translateY(-2px)":"none",boxShadow:L?`3px 3px 0px ${B}, 4px 4px 0px ${M}`:f?`2px 2px 0px ${M}`:v?`5px 5px 0px ${B}, 6px 6px 0px ${M}`:`3px 3px 0px ${B}, 4px 4px 0px ${M}`,transition:"transform 150ms ease, box-shadow 150ms ease, background-color 150ms ease, border-color 150ms ease, color 150ms ease"}}default:return{}}},E=()=>{if(e==="outline")return{};switch(t){case"sm":return{padding:`${l.spacing.sm} ${l.spacing.md}`,fontSize:l.typography.fontSize.sm};case"md":return{padding:`${l.spacing.md} ${l.spacing.lg}`,fontSize:l.typography.fontSize.base};case"lg":return{padding:`${l.spacing.lg} ${l.spacing.xl}`,fontSize:l.typography.fontSize.lg};default:return{}}},F={borderRadius:c?.button?.borderRadius||l.borderRadius.md,fontWeight:c?.button?.fontWeight||l.typography.fontWeight.medium,fontFamily:c?.button?.fontFamily||l.typography.fontFamily,fontSize:c?.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)&&e!=="outline"?.6:1,width:a?"100%":"auto",display:"flex",alignItems:"center",justifyContent:"center",gap:l.spacing.sm,...R(),...E(),...c?.button?.fontSize&&{fontSize:c.button.fontSize}},W=o||r;return $.jsxs("button",{type:i.type??"button","data-spiceflow-focus":!0,"aria-busy":r||void 0,"aria-disabled":W||void 0,style:{...F,...u},className:s,disabled:W,onMouseEnter:S=>{g(!0),i.onMouseEnter?.(S)},onMouseLeave:S=>{g(!1),b(!1),i.onMouseLeave?.(S)},onMouseDown:S=>{b(!0),i.onMouseDown?.(S)},onMouseUp:S=>{b(!1),i.onMouseUp?.(S)},...i,children:[r&&$.jsx(ae,{size:16}),n]})},Dt=({onAuthSuccess:e,onAuthError:t,theme:r="light",className:a="",buttonText:o="Login with Privy",autoTrigger:n=!1})=>{const s=Ce(r),[u,h]=y.useState(!1),[c,m]=y.useState(!1),{ready:i,authenticated:d,user:p}=I.usePrivy(),{login:w}=I.useLogin(),{logout:l}=I.useLogout();y.useEffect(()=>{h(!0)},[]),y.useEffect(()=>{n&&i&&!d&&u&&!c&&(m(!0),C())},[n,i,d,u,c]),y.useEffect(()=>{if(i&&d&&p&&e){const g=p.wallet?.address||p.email?.address;g&&e(g)}},[i,d,p,e]),y.useEffect(()=>{},[i,d,t]);const C=()=>{try{w()}catch(g){const f=`Login failed: ${String(g)}`;t?t(f):console.error(f)}},v=()=>{try{l()}catch(g){const f=`Logout failed: ${String(g)}`;t?t(f):console.error(f)}};if(!u)return $.jsx("div",{className:a,children:$.jsx(q,{variant:"primary",disabled:!0,theme:s,children:o})});if(!i)return $.jsx("div",{className:a,children:$.jsx(q,{variant:"primary",disabled:!0,theme:s,children:"Loading..."})});if(d&&p){const g=p.wallet?.address||p.email?.address,f=g?Se(g):"Connected";return $.jsx("div",{className:a,children:$.jsxs(q,{variant:"primary",onClick:v,theme:s,children:["Logout (",f,")"]})})}return n?$.jsx("div",{className:a,children:$.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px",flexDirection:"column",gap:"12px"},children:[$.jsx(ae,{size:40,borderWidth:3,color:"#3b82f6"}),$.jsx("p",{style:{color:"#6b7280",fontSize:"14px"},children:"Opening login..."})]})}):$.jsx("div",{className:a,children:$.jsx(q,{variant:"primary",onClick:C,theme:s,children:o})})};exports.Button=q,exports.CHAIN_CONFIGS=Ye,exports.PrivyLogin=Dt,exports.RELAYER_API_URL=me,exports.SpiceFlowProvider=At,exports.SpiceFlowProviderContext=H,exports.SpiceflowError=P,exports.Spinner=ae,exports.addressesEqual=D,exports.buildDarkPalette=Wt,exports.buildLightPalette=Ut,exports.copyToClipboard=qt,exports.createInitialSteps=yt,exports.describeChainSwitchError=it,exports.duration=T,exports.easing=A,exports.ensureSmartWallet=ye,exports.ensureWalletOnChain=Xe,exports.font=O,exports.formatBalance=Ft,exports.formatDecimalInput=jt,exports.formatUsd=Mt,exports.getAllAssetsForChain=Ze,exports.getChainConfig=N,exports.getChainName=V,exports.getChainsForAssets=Ke,exports.getClientForChain=de,exports.getDelegateContractAddress=Qe,exports.getExplorerUrl=Ve,exports.getRelayerErrorDetail=rt,exports.getTokenDecimals=et,exports.getWalletBalanceEntries=pt,exports.hasStoredSpiceFlowMode=St,exports.isSpiceflowError=X,exports.isUserRejection=fe,exports.parseNumericInput=Lt,exports.radius=Oe,exports.relayerFetch=_,exports.relayerService=U,exports.resolveTheme=Be,exports.sanitizeError=at,exports.transition=De,exports.truncateAddress=Se,exports.useIsUserWhitelisted=xe,exports.useProviderWallets=te,exports.useSpiceBrand=ke,exports.useWallet=be,exports.z=qe;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import React from "react";
|
|
2
2
|
import type { Address } from "viem";
|
|
3
3
|
import type { SpiceTheme } from "../types/theme";
|
|
4
|
+
import type { SpiceSwapperConfig } from "../types/deposit";
|
|
4
5
|
import { type PartnerWhitelistCheckResponse, type UseIsUserWhitelistedOptions } from "../hooks/useIsUserWhitelisted";
|
|
5
6
|
export type WalletProvider = "privy";
|
|
6
7
|
export type SpiceFlowMode = "7702" | "presign" | "ondemand";
|
|
@@ -25,6 +26,7 @@ export interface SpiceFlowProviderContextValue {
|
|
|
25
26
|
appName?: string;
|
|
26
27
|
apiUrl?: string;
|
|
27
28
|
rpcOverrides?: Record<number, string>;
|
|
29
|
+
swapper?: SpiceSwapperConfig;
|
|
28
30
|
embeddedWalletAddress?: Address;
|
|
29
31
|
externalWalletAddress?: Address;
|
|
30
32
|
isUserWhitelisted: boolean | null;
|
|
@@ -51,6 +53,7 @@ export interface SpiceFlowProviderProps {
|
|
|
51
53
|
apiUrl?: string;
|
|
52
54
|
theme?: SpiceTheme;
|
|
53
55
|
rpcOverrides?: Record<number, string>;
|
|
56
|
+
swapper?: SpiceSwapperConfig;
|
|
54
57
|
whitelist?: SpiceFlowWhitelistOptions | false;
|
|
55
58
|
}
|
|
56
59
|
export declare const SpiceFlowProvider: React.FC<SpiceFlowProviderProps>;
|
package/dist/types/deposit.d.ts
CHANGED
|
@@ -7,6 +7,7 @@ import type { RelayerErrorDetail } from "../utils/errors";
|
|
|
7
7
|
import type { IntentStatus } from "./status";
|
|
8
8
|
import type { Network } from "@spicenet-io/spiceflow-core";
|
|
9
9
|
import type { VerifiedPendingDeposit } from "../hooks/usePendingDeposit";
|
|
10
|
+
import type { SwapperIframeOptions } from "@swapper-finance/deposit-sdk";
|
|
10
11
|
export interface PostDepositContext {
|
|
11
12
|
sourceChainId: number;
|
|
12
13
|
depositTokenAddress: Address;
|
|
@@ -135,6 +136,47 @@ export interface StatusToastProps {
|
|
|
135
136
|
directDepositChainId?: number | null;
|
|
136
137
|
styles?: CustomStyles;
|
|
137
138
|
}
|
|
139
|
+
export interface SwapperIframeLike {
|
|
140
|
+
mount(container: HTMLElement | string): void;
|
|
141
|
+
on(eventType: string, handler: (event: {
|
|
142
|
+
type: string;
|
|
143
|
+
data?: unknown;
|
|
144
|
+
}) => void): void;
|
|
145
|
+
destroy(): void;
|
|
146
|
+
}
|
|
147
|
+
export type SwapperIframeFactory = (options: SwapperIframeOptions) => SwapperIframeLike | Promise<SwapperIframeLike>;
|
|
148
|
+
export interface SpiceSwapperConfig {
|
|
149
|
+
enabled?: boolean;
|
|
150
|
+
integratorId?: string;
|
|
151
|
+
iframeFactory?: SwapperIframeFactory;
|
|
152
|
+
}
|
|
153
|
+
export type DepositSource = "wallet" | "card" | "exchange";
|
|
154
|
+
export interface SwapperTransactionSuccessEvent {
|
|
155
|
+
type: string;
|
|
156
|
+
data?: unknown;
|
|
157
|
+
}
|
|
158
|
+
export interface SelectSourceModalProps {
|
|
159
|
+
isOpen: boolean;
|
|
160
|
+
onClose: () => void;
|
|
161
|
+
closeOnBackdropClick?: boolean;
|
|
162
|
+
onSelect: (source: DepositSource) => void;
|
|
163
|
+
styles?: CustomStyles;
|
|
164
|
+
}
|
|
165
|
+
export interface SwapperDepositModalProps {
|
|
166
|
+
isOpen: boolean;
|
|
167
|
+
onClose: () => void;
|
|
168
|
+
onBack: () => void;
|
|
169
|
+
closeOnBackdropClick?: boolean;
|
|
170
|
+
source: Exclude<DepositSource, "wallet">;
|
|
171
|
+
integratorId: string;
|
|
172
|
+
depositWalletAddress: Address;
|
|
173
|
+
onTransactionSuccess: (event?: SwapperTransactionSuccessEvent) => void;
|
|
174
|
+
verifying: boolean;
|
|
175
|
+
verifyError: string | null;
|
|
176
|
+
onRetryVerify: () => void;
|
|
177
|
+
iframeFactory?: SwapperIframeFactory;
|
|
178
|
+
styles?: CustomStyles;
|
|
179
|
+
}
|
|
138
180
|
export interface DepositRecoveryPromptProps {
|
|
139
181
|
isOpen: boolean;
|
|
140
182
|
onClose: () => void;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@spicenet-io/spiceflow-ui",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.2.0-next.0",
|
|
4
4
|
"description": "Spiceflow UI SDK",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"packageManager": "bun@1.3.13",
|
|
@@ -54,6 +54,7 @@
|
|
|
54
54
|
"license": "MIT",
|
|
55
55
|
"dependencies": {
|
|
56
56
|
"@spicenet-io/spiceflow-core": "^0.3.14",
|
|
57
|
+
"@swapper-finance/deposit-sdk": "0.2.15",
|
|
57
58
|
"tslib": "2.8.1"
|
|
58
59
|
},
|
|
59
60
|
"peerDependencies": {
|
package/dist/privy-Dcad3cmM.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use client";
|
|
2
|
-
import{jsx as v,jsxs as V}from"react/jsx-runtime";import{useContext as de,useMemo as L,useRef as ue,useEffect as A,createContext as fe,useState as M,useCallback as je}from"react";import{getChainMeta as pe,getTokensForChain as ze,ZERO_ADDRESS as _e,isNativeToken as Q,getDelegateContract as Ge,getTokenByAddress as He,DELEGATE_ABI as Je,ERC20_ABI as Ye,spicenetEscrowAbi as Ve,uniV3SwapRouterAbi as Qe,getChainIdsByNetwork as Xe}from"@spicenet-io/spiceflow-core";import{isAddress as R,getAddress as X,defineChain as Ke,createPublicClient as Ze,http as et,erc20Abi as tt,formatUnits as me,isHex as rt,decodeErrorResult as at,hexToString as ot,createWalletClient as nt,custom as st}from"viem";import{readContract as it}from"viem/actions";import{useWallets as he,usePrivy as K,getEmbeddedConnectedWallet as ge,useSign7702Authorization as lt,useSignMessage as ct,useLogin as dt,useLogout as ut}from"@privy-io/react-auth";import{useAccount as ye}from"wagmi";import{useQuery as ft,useMutation as pt}from"@tanstack/react-query";const mt={base:0,raised:1,sticky:10,overlay:20,popover:40,modal:1e3,dropdown:1100,toast:1200,tooltip:1300},ht={none:"0",sm:"4px",md:"6px",card:"8px",input:"10px",shell:"9px",modal:"12px",pill:"9999px",circle:"50%"},k={out:"cubic-bezier(0.22, 1, 0.36, 1)",inOut:"cubic-bezier(0.65, 0, 0.35, 1)",linear:"linear"},S={fast:"120ms",normal:"150ms",slow:"300ms",progress:"400ms"},gt={interactive:`transform ${S.normal} ${k.out}, box-shadow ${S.normal} ${k.out}, background-color ${S.normal} ${k.out}, border-color ${S.normal} ${k.out}, color ${S.normal} ${k.out}`,color:`background-color ${S.normal} ${k.out}, border-color ${S.normal} ${k.out}, color ${S.normal} ${k.out}`,popover:`opacity ${S.normal} ${k.out}, transform ${S.normal} ${k.out}`},j={ui:'"Helvetica Neue", sans-serif',mono:'"IBM Plex Mono", monospace'};function z(t,e){return!t||!e?!1:R(t)&&R(e)?X(t)===X(e):t.toLowerCase()===e.toLowerCase()}const yt="0xcA11bde05977b3631167028862bE2a173976CA11",bt={4114:"0x860aFc632a6D625B95d8B96f39ECC48E988c6962"},wt=new Set([5115]);function xt(t){const e=bt[t.id]??(wt.has(t.id)?void 0:yt);return Ke({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 vt=[1,8453,42161,4114,11155111,421614,84532,5115,123420001114,688688,688689],_=Object.fromEntries(vt.map(t=>pe(t)).filter(t=>t!=null).map(t=>[t.id,{...t,viemChain:xt(t),supportedTokens:ze(t.id)}])),$t=_;let be={};const Z=new Map,we=t=>{be={...t||{}},Z.clear()},ee=t=>{const e=be[t];return e&&typeof e=="string"&&e.length>0?e:_[t]?.rpcUrl},W=t=>_[t],te=t=>{const e=pe(t);return e?.displayName||e?.name||`Chain ${t}`},Et=t=>{const e=Ge(t);if(!e)throw new Error(`Unsupported chain ID: ${t}`);return e},Ct=(t,e,r)=>{const a=W(t);return a?.blockExplorer?`${a.blockExplorer}/tx/${e}`:"#"};async function Bt(t,e){const r=`0x${e.toString(16)}`;try{await t.request({method:"wallet_switchEthereumChain",params:[{chainId:r}]});return}catch(n){if(!(n?.code===4902||typeof n?.message=="string"&&n.message.includes("Unrecognized chain ID")))throw n}const a=W(e);if(!a)throw new Error(`Cannot add unknown chain ${e} to wallet`);await t.request({method:"wallet_addEthereumChain",params:[{chainId:r,chainName:a.name||`Chain ${e}`,nativeCurrency:a.nativeCurrency||{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:[ee(e)||a.rpcUrl],blockExplorerUrls:a.blockExplorer?[a.blockExplorer]:void 0}]})}const xe=t=>{const e=W(t);if(!e)throw new Error(`Unsupported chain ID: ${t}`);const r=ee(t);if(!r)throw new Error(`No RPC URL configured for chain ID: ${t}`);const a=`${t}:${r}`,n=Z.get(a);if(n)return n;const o=Ze({chain:e.viemChain,transport:et(r,{timeout:15e3,retryCount:2,retryDelay:300}),batch:{multicall:{wait:16}}});return Z.set(a,o),o},kt=()=>{const t={};return Object.values(_).forEach(e=>{t[e.id]={name:e.name,moralisName:e.moralisId||"",chain:e.viemChain,rpcUrl:ee(e.id)||e.rpcUrl}}),t},St=(t,e=[])=>{const r=W(t);if(!r)return[];const a=[];if(![11155111,421614,84532,688689].includes(t)){const o=e.find(s=>s.chainId===t&&s.isNative);o?a.push(o):a.push({address:_e,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 a;const n=a.some(o=>o.isNative);return r.supportedTokens.forEach(o=>{if(n&&Q(o.address))return;const s=e.find(u=>u.chainId===t&&z(u.address,o.address));s?a.push(s):a.push({address:o.address,name:o.name,symbol:o.symbol,decimals:o.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:o.logo,isNative:!1,chainId:t})}),a},It=async(t,e)=>{const r=W(t);if(!r)throw new Error(`Unsupported chain ID: ${t}`);const a=e.toLowerCase();if(Q(a)){if(!r.nativeCurrency?.decimals)throw new Error(`Native currency decimals not configured for chain ${t}`);return r.nativeCurrency.decimals}if(r.supportedTokens){const n=r.supportedTokens.find(o=>z(o.address,a));if(n)return n.decimals}try{if(!R(e,{strict:!1}))throw new Error(`Invalid token address: ${e}`);const n=X(e),o=xe(t),s=await it(o,{address:n,abi:tt,functionName:"decimals"});return Number(s)}catch{throw new Error(`Could not determine decimals for token ${e} on chain ${t}`)}};class I extends Error{constructor(e,r,a={}){super(r),this.code=e,this.context=a,this.name="SpiceflowError",Error.captureStackTrace&&Error.captureStackTrace(this,I)}}function re(t){return t instanceof I}const Tt=["user rejected","user denied","user cancelled","rejected the request","action_rejected","4001"];function ve(t){if(!t)return"";if(typeof t=="string")return t;const e=t,r=e.message||e.reason||"",a=e.details||"";return`${r} ${a}`.trim()}const $e=t=>{if(re(t))return t.code==="WALLET_REJECTED";const e=ve(t).toLowerCase();return Tt.some(r=>e.includes(r))};let ae=null;function At(t){return ae?.message===t?ae.detail:void 0}const Pt=(t,e="Something went wrong. Please try again.")=>{if($e(t))return"Transaction was rejected.";if(re(t)){const r=t.message||e,{requestId:a,httpStatus:n,responseBody:o,endpoint:s}=t.context;return(a||n||s)&&(ae={message:r,detail:{requestId:a,httpStatus:n,responseBody:o,endpoint:s}}),r}return ve(t)||e},Rt=[...Je,...Ye,...Ve,...Qe];function oe(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=>oe(r,e+1)):typeof t=="object"?Object.values(t).flatMap(r=>oe(r,e+1)):[]}function Ee(t){try{const e=at({abi:Rt,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],a=r&&r!=="0x"?Ee(r):void 0;return a?`Call reverted: ${a}`:"Call reverted (no reason returned)"}return e.errorName}catch{try{const e=ot(t).replace(/\x00+$/g,"").trim();return/^[\x20-\x7e]+$/.test(e)&&e.length>1?e:void 0}catch{return}}}function Wt(t){for(const e of oe(t)){if(!rt(e))continue;const r=Ee(e);if(r)return r}}function Nt(t,e){const r=e.match(/Output amount (\d+) is insufficient after fees (\d+) on chain (\d+)/);if(!r)return e;const[,a,n,o]=r,s=Number(o),u=BigInt(a),h=BigInt(n);let l;for(const w of t.intents){const g=w.chainBatches.find(f=>f.chainId===s);if(g){l=g;break}}const m=l?.tokenTransfers.find(w=>w.from==="escrow"&&z(w.to,t.user)&&!Q(w.token)),i=te(s);if(!m)return`Amount is too small to cover the estimated fee on ${i}.`;const d=He(m.token,s),p=d?.decimals??18,y=d?.symbol??"tokens",c=me(u,p),x=me(h,p);return`Amount is too small to cover the estimated fee on ${i}. Amount: ${c} ${y}. Estimated fee: ${x} ${y}.`}function Ut(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 Ft="https://tx-submission-api.spicenet.io",Ce=Ft;function Lt(t,e){return typeof e=="bigint"?e.toString():e}function q(t,e=""){if(Array.isArray(t))t.forEach((r,a)=>q(r,`${e}[${a}]`));else if(t&&typeof t=="object")for(const[r,a]of Object.entries(t)){const n=e?`${e}.${r}`:r;if(!a&&(r==="user"||r==="to"||r==="from"||r==="address"))throw new I("INVALID_PARAMS",`Wallet not ready: ${n} is missing from the request. Wait a moment and retry, or log in again.`,{path:n});q(a,n)}}async function G(t,e){const r={...e?.headers},a=r["x-request-id"]??crypto.randomUUID();r["x-request-id"]=a;const n=await fetch(t,{...e,headers:r}),o=n.headers.get("x-request-id")??"";return Object.assign(n,{requestId:o})}function O(t,e){if(!t)return e;const r=t.error,a=(typeof t.message=="string"?t.message:"")||(r&&typeof r=="object"&&"message"in r&&typeof r.message=="string"?r.message:"")||(typeof r=="string"?r:"")||e,n=Wt(t);return n&&!a.includes(n)?`${a} \u2014 ${n}`:a}async function Mt(t){try{return await t.json()}catch{return null}}function qt(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(a=>typeof a=="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 Ot{constructor(){this.baseUrl=Ce}setBaseUrl(e){this.baseUrl=e}getBaseUrl(){return this.baseUrl}async requestJson(e,r){const a=`${this.baseUrl}${e}`,n=await G(a,r.method&&r.method!=="GET"?{method:r.method,headers:{"Content-Type":"application/json"},body:JSON.stringify(r.body,Lt)}:void 0),o=await n.json();if(!n.ok||o.success===!1||r.ok&&!r.ok(o)){const s=O(o,r.fallbackError(n.status));throw new I(r.code??"RELAYER_ERROR",r.mapError?r.mapError(s):s,{httpStatus:n.status,requestId:n.requestId,responseBody:JSON.stringify(o),endpoint:e,...r.context})}return o}async createAction(e){return q(e),this.requestJson("/actions",{method:"POST",body:e,fallbackError:r=>`Relayer API error: ${r}`})}async estimateActionFees(e){return q(e),(await this.requestJson("/actions/fees/estimate",{method:"POST",body:e,fallbackError:r=>`Relayer fee estimate error: ${r}`,ok:r=>!!r.success&&!!r.data?.feeEstimate,mapError:r=>Nt(e,r)})).data.feeEstimate}async estimateBatchGas(e){q(e);const r=await this.requestJson("/actions/gas/estimate",{method:"POST",body:e,fallbackError:a=>`Relayer gas estimate error: ${a}`,ok:a=>!!a.success&&!!a.data?.gasFee});return{gasFee:BigInt(r.data.gasFee),gasQuoteSource:r.data.gasQuoteSource}}async executeStep(e,r,a,n){const o=`${this.baseUrl}/actions/${e}/intents/${r}/steps/${a}`,s=`/actions/${e}/intents/${r}/steps/${a}`,u=crypto.randomUUID(),h=3e4,l=new Promise((d,p)=>setTimeout(()=>p(new I("RELAYER_EXECUTE_ERROR",`Execute step request timed out after ${h/1e3}s`,{actionId:e,intentIndex:r,stepIndex:a,endpoint:s,requestId:u})),h)),m=await Promise.race([G(o,{method:"POST",headers:{"Content-Type":"application/json","x-request-id":u},body:JSON.stringify(n)}),l]),i=await m.json();if(!m.ok||i.success===!1)throw new I("RELAYER_EXECUTE_ERROR",O(i,`Execute step error: ${m.status}`),{httpStatus:m.status,requestId:m.requestId,responseBody:JSON.stringify(i),endpoint:s,actionId:e});if(i?.status==="error"||i?.status==="reverted"){const d=O(i,""),p=d?`: ${d}`:"";throw new I("RELAYER_EXECUTE_ERROR",`Step ${a} previously ${i.status}${p}`,{httpStatus:m.status,requestId:m.requestId,responseBody:JSON.stringify(i),endpoint:s,actionId:e,intentIndex:r,stepIndex:a,stepStatus:i.status})}return{success:!0,transactionHash:i.transactionHash}}async checkStepStatus(e,r){const a=e.split("/"),n=a[0],o=a.length>=2?a[1]:"0",s=await this.requestJson(`/actions/${n}/intents/${o}/steps/${r}`,{fallbackError:u=>`Intent step status check failed: ${u}`,code:"RELAYER_STATUS_ERROR",context:{intentId:e}});return{success:!0,data:{status:s.status==="error"?"reverted":s.status,transactionHash:s.txid,error:O(s,"")}}}async createWallet(e,r){return this.requestJson(`/wallets/${e}`,{method:"PUT",body:r,fallbackError:a=>`Create wallet error: ${a}`})}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 P=new Ot;async function Dt(t){const e=`${P.getBaseUrl()}/wallets/${t}/balance`,r=await G(e,{cache:"no-store"}),a=await Mt(r);if(!r.ok||a?.success===!1)throw new I("RELAYER_ERROR",O(a,`Unable to verify Spice balance: ${r.status}`),{httpStatus:r.status,requestId:r.requestId,responseBody:JSON.stringify(a),endpoint:`/wallets/${t}/balance`});return qt(a)}const ne=new Map,jt="spiceflow.smartWallet.";function Be(t){return`${jt}${t.toLowerCase()}`}function zt(t){try{return typeof localStorage<"u"&&localStorage.getItem(Be(t))==="1"}catch{return!1}}function ke(t){try{typeof localStorage<"u"&&localStorage.setItem(Be(t),"1")}catch{}}function _t(t){if(!(t instanceof I))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,e){if(zt(t))return;const r=t.toLowerCase(),a=ne.get(r);if(a)return a;const n=(async()=>{try{await P.getWallet(t),ke(t);return}catch(l){if(!_t(l))throw l}const{unix_timestamp:o}=await P.getRollupTimestamp(),s=`I am creating a new smart wallet and adding an admin wallet ethereum:0x${t.slice(2).toLowerCase()}. Nonce: ${o}`,u=await e(s),h=typeof u=="string"?u:u.signature;if(!h)throw new Error("Wallet returned no smart wallet signature");await P.createWallet(t,{timestamp:o,signature:h}),ke(t)})();ne.set(r,n);try{await n}finally{ne.delete(r)}}const Gt=(t,e)=>{const r=n=>e?e(n):te(n),a=[];return t.forEach((n,o)=>{const s=n.calls&&n.calls.length>0,u=n.tokenTransfers&&n.tokenTransfers.length>0;!s&&!u||a.push({stepId:o,status:o===0?"processing":"pending",chainId:n.chainId,chainName:r(n.chainId),description:"Processing transaction"})}),a},Ht=t=>{const e=t?.wallet;if(e?.address&&e.walletClientType==="privy"&&e.connectorType==="embedded"&&!e.imported)return e.address},Ie=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 a=null;for(const n of r)try{const o=await t.getWalletClient(n);if(o)return o}catch(o){a=o}if(a)throw a}if(typeof t.getEthereumProvider=="function"){const r=await t.getEthereumProvider(),a=e?W(e)?.viemChain:void 0;return nt({account:t.address,chain:a,transport:st(r)})}throw new Error("Wallet client not available")},Jt=async(t,e)=>{if(!t?.address)throw new Error("Wallet not available");if(typeof t.getEthereumProvider=="function")return t.getEthereumProvider();const r=await Ie(t,e);return{request:a=>r.request(a)}},H=t=>t?.address?{address:t.address,wallet:t,getWalletClient:e=>Ie(t,e),getEthereumProvider:e=>Jt(t,e)}:null,se=()=>{const{address:t,connector:e}=ye();let r=null,a=null;try{r=he(),{user:a}=K()}catch{r=null,a=null}const n=r?.wallets||[],o=ge(n),s=o?.address?.toLowerCase(),u=n.find(c=>c.connectorType!=="embedded"&&c.address?.toLowerCase()!==s),h=t?.toLowerCase(),l=t&&e&&!(h&&s&&h===s)?{address:t,connector:e,getEthereumProvider:()=>e.getProvider()}:null,m=t&&e?{address:t,connector:e,getEthereumProvider:()=>e.getProvider()}:null,i=H(o),d=H(l)||H(u),p=i?.address||Ht(a),y=H(m)||d;return{embeddedWallet:i,externalWallet:d,embeddedAddress:p,externalAddress:d?.address,activeWallet:y,activeAddress:y?.address}},Te=()=>{const t=de(J),e=t?.mode,{isConnected:r,address:a}=ye();let n=null,o=null,s=null,u=null,h=null;try{n=K(),o=lt(),s=ct(),u=he()}catch(f){h=f instanceof Error?f.message:String(f)}if(h)return e==="ondemand"&&r&&a?{isReady:!0,isAuthenticated:!0,isConnected:!0,address:a,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{ready:l=!1,authenticated:m=!1}=n||{},i=t?.embeddedWalletAddress,d=ge(u?.wallets||[]),p=i||d?.address,y=!!p&&!!d,c={isReady:e==="ondemand"?!0:l,isAuthenticated:e==="ondemand"?!0:m||y,isConnected:e==="ondemand"?r&&!!a||l&&(m||y)&&y:l&&y,address:e==="ondemand"&&r?a:p,provider:"privy"},x=async f=>{if(!d)throw new Error("Embedded wallet not available");const b=await d.getEthereumProvider(),{createWalletClient:$,custom:B}=await import("viem");return{signature:await $({account:d.address,transport:B(b)}).signMessage({account:d.address,message:f})}},w=async f=>{if(s)try{return{signature:(await s.signMessage({message:f})).signature}}catch(b){if(!d)throw b}if(!d)throw new Error("Privy sign message not available");return x(f)},g=async()=>{if(!p)throw new Error("Embedded wallet not available for smart wallet setup");await Se(p,w)};return{...c,actions:{signAuthorization:async f=>{if(!o)throw new Error("Privy sign authorization not available");try{await g();const b=await o.signAuthorization({contractAddress:f.contractAddress,chainId:f.chainId,nonce:f.nonce},{address:p});return delete b.v,b}catch(b){const $=typeof b?.message=="string"?b.message:String(b?.message??b??"");throw $.includes("not configured")||$.includes("chain")?new Error(`Chain ${f.chainId} is not configured in PrivyProvider. Add this chain to your Privy dashboard or supportedChainIds.`):b}},signMessage:async f=>{if(typeof f=="object"&&"raw"in f){if(await g(),!d)throw new Error("Embedded wallet not available for raw signing");return x(f)}return w(f)},getEthereumProvider:async()=>{if(!d)throw new Error("Embedded wallet not available");return d.getEthereumProvider()}}}},Yt="https://portal-api.spicenet.io/api/v1",ie=t=>t.replace(/\/+$/,""),Vt=(t,e)=>`${t}:${e}`;async function Qt(t,e){const r=new URLSearchParams({walletAddress:e,campaignId:"spicenet-portal",campaignGroup:"1"}),a=await fetch(`${t}/portal/mainnet/linked-portal-wallet?${r.toString()}`,{cache:"no-store"});if(!a.ok){if(a.status>=500){const n=new Error(`Failed to resolve linked portal wallet: ${a.status}`);throw n.status=a.status,n}return null}return(await a.json()).portalWalletAddress?.toLowerCase()??null}async function Xt(t,e,r){const a=new URLSearchParams({walletAddress:e,campaignId:r.campaignId,campaignGroup:r.campaignGroup,partnerId:r.partnerId}),n=await fetch(`${t}/portal/mainnet/whitelist/check?${a.toString()}`,{cache:"no-store"});if(!n.ok){const o=new Error(`Failed to check whitelist: ${n.status}`);throw o.status=n.status,o}return await n.json()}async function Kt(t,e,r,a){const n=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:a})});if(!n.ok)throw new Error(`Failed to link wallet: ${n.status}`)}function Ae({walletAddress:t,campaignId:e,campaignGroup:r,partnerId:a,apiBaseUrl:n=Yt,enabled:o=!0,staleTime:s=5*60*1e3,refetchInterval:u=!1}={}){const{isAuthenticated:h,isConnected:l}=Te(),{externalAddress:m,embeddedAddress:i}=se(),d=t??m,p=typeof d=="string"?d.toLowerCase():void 0,y=typeof i=="string"?i.toLowerCase():void 0,c=typeof m=="string"?m.toLowerCase():void 0,x=o&&h&&l&&!!m&&!!p&&R(p)&&!!e&&!!r&&!!a,w=L(()=>["partner-whitelist","check",p,e,r,a,ie(n)],[p,e,r,a,n]),g=ft({queryKey:w,enabled:x,staleTime:s,refetchInterval:u,retry:(E,N)=>{const T=N?.status;return typeof T=="number"&&T>=400&&T<500?!1:E<3},retryDelay:E=>Math.min(1e3*2**E,15e3),queryFn:async()=>{if(!p||!R(p))throw new Error("A valid wallet address is required");if(!e||!r||!a)throw new Error("campaignId, campaignGroup, and partnerId are required");const E=ie(n),N={campaignId:e,campaignGroup:r,partnerId:a},T=await Qt(E,p);return T?Xt(E,T,N):{walletAddress:p,campaignId:e,campaignGroup:r,partnerId:a,isWhitelisted:!1,isLinkedWallet:!1,whitelistedWalletAddress:null,externalWalletAddress:p}}}),f=o&&h&&l&&!!c&&R(c)&&!!y&&R(y)&&!!e&&!!r&&!!a,b=pt({mutationFn:E=>Kt(ie(n),{campaignId:e,campaignGroup:r,partnerId:a},E.external,E.embedded)}),$=ue(new Set),B=b.mutate;return A(()=>{if(!f||!c||!y||!e||!r||!a)return;const E=Vt(c,y);$.current.has(E)||($.current.add(E),B({external:c,embedded:y}))},[f,c,y,e,r,a,B]),{isWhitelisted:g.data?.isWhitelisted??!1,whitelistCheck:g.data,checkedWalletAddress:p,externalWalletAddress:m,embeddedWalletAddress:i,isExternalWalletConnected:!!m,isWhitelistCheckEnabled:x,linkWallet:b,isWalletLinked:b.isSuccess,...g}}const Zt=["__spicenet_whitelist_blocked__"],Pe="spiceflow-mode",Re=()=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Pe);return t==="7702"?"7702":t==="non7702"?"ondemand":t==="embedded"?"7702":t==="external"?"ondemand":null}catch{return null}},er=t=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Pe,t==="7702"?"7702":"non7702")}catch{}},tr=()=>Re()!==null,We=fe(null),J=fe(null),rr=({children:t,value:e,whitelist:r})=>{const a=!!r&&r.enabled!==!1,{isWhitelisted:n,isLoading:o,whitelistCheck:s}=Ae(a?r:{enabled:!1}),u=a&&!n,h=L(()=>({...e,mode:u?"ondemand":e.mode,allowedTokens:u?Zt:e.allowedTokens,isUserWhitelisted:n,isWhitelistChecking:o,isWhitelistConfigured:a,isWhitelistGateActive:u,whitelistCheck:s}),[e,a,u,n,o,s]);return v(J.Provider,{value:h,children:t})},ar=({children:t,provider:e="privy",supportedChainIds:r,allowedTokens:a,network:n="testnet",mode:o,skipFlow:s=[],nativeChainId:u,appName:h="Spicenet",apiUrl:l,theme:m,rpcOverrides:i,whitelist:d})=>{A(()=>{if(!l)return;const B=P.getBaseUrl();return P.setBaseUrl(l),()=>P.setBaseUrl(B)},[l]),A(()=>(we(i),()=>we(void 0)),[i]);const p=L(()=>Xe(n),[n]),y=r??p,c=m??null,[x,w]=M(()=>o??Re()??"7702");A(()=>{o&&w(o)},[o]);const g=je(B=>{if(o){w(o);return}w(B),er(B)},[o]),{embeddedAddress:f,externalAddress:b}=se(),$=L(()=>({provider:e,supportedChainIds:y,allowedTokens:a,skipFlow:s,mode:x,setMode:g,network:n,nativeChainId:u,appName:h,apiUrl:l,rpcOverrides:i,embeddedWalletAddress:f,externalWalletAddress:b,isUserWhitelisted:null,isWhitelistChecking:!1,isWhitelistConfigured:!1,isWhitelistGateActive:!1}),[e,y,a,s,x,g,n,u,h,l,i,f,b]);return v(We.Provider,{value:c,children:v(J.Provider,{value:$,children:v(rr,{value:$,whitelist:d,children:t})})})},or={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:j.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"}},nr={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"},sr={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"},Ne=(t="light")=>({mode:t,...or,colors:t==="light"?nr:sr});function Y(t,e){const r=t.replace("#",""),a=Math.max(0,Math.round(parseInt(r.substring(0,2),16)*(1-e))),n=Math.max(0,Math.round(parseInt(r.substring(2,4),16)*(1-e))),o=Math.max(0,Math.round(parseInt(r.substring(4,6),16)*(1-e)));return`#${a.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`}function ir(t,e){return{shell:e?.shell??"#141414",shellBorder:e?.shellBorder??Y(e?.shell??"#141414",.35),shellInnerBorder:e?.shellInnerBorder??Y(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 lr(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 Ue(t,e){const r=e?{...t,...e}:t,a=r.dark??!1,n=r.primaryColor,o=r.shell??(a?"#141414":"#ffffff");return{primaryColor:n,dark:a,fontFamily:r.fontFamily??'"Helvetica Neue", sans-serif',appName:r.appName??"Spicenet",logo:r.logo,borderRadius:r.borderRadius??"8px",shell:o,shellBorder:Y(o,a?.35:.085),shellInnerBorder:Y(o,a?.55:.165),card:r.card??(a?"#1e1e1e":"#f9fafb"),input:a?"#171717":"#ffffff",hover:a?"#2a2a2a":"#f3f4f6",text:r.text??(a?"#ffffff":"#111827"),textMuted:r.textMuted??(a?"#888888":"#6b7280"),inputText:a?"#e0e0e0":"#111827",inputPlaceholder:a?"#555555":"#9ca3af",border:r.border??(a?"rgba(255,255,255,0.08)":"#e5e7eb"),inputBorder:a?"rgba(255,255,255,0.10)":"#d1d5db",buttonBorder:a?"rgba(255,255,255,0.12)":"#0e0d0b",successBg:a?"#0a1f18":"#d1fae5",successBorder:a?"#1a4a3a":"#6ee7b7",successText:a?"#6ee7b7":"#065f46",warningBg:a?"#1f1a0d":"#fef3c7",warningBorder:a?"#4a3820":"#fde68a",warningText:a?"#fbbf24":"#92400e",errorBg:a?"#1f0d0d":"#fef2f2",errorBorder:a?"#4a2020":"#fecaca",errorText:a?"#f87171":"#dc2626",infoBg:a?"#0d1325":"#dbeafe",infoBorder:a?"#2a3a5a":"#93c5fd",infoText:a?"#60a5fa":"#1e40af"}}const cr=j.mono;function Fe(t,e){const r=de(We)??void 0;return L(()=>{const a=r??{primaryColor:"#EA4B4B"},n={...t?.primaryColor?{primaryColor:t.primaryColor}:{},...t?.fontFamily?{fontFamily:t.fontFamily}:{},...e!==void 0?{dark:e}:{}},o=Ue(a,n),{dark:s,primaryColor:u,appName:h}=o,l=Ne(s?"dark":"light"),m={...l,colors:{...l.colors,primary:u,primaryHover:`${u}dd`},typography:{...l.typography,fontFamily:o.fontFamily}},i={shell:o.shell,shellBorder:o.shellBorder,shellInnerBorder:o.shellInnerBorder,cardBg:o.card,inputBg:o.input,hoverBg:o.hover,textPrimary:o.text,textSecondary:o.textMuted,inputText:o.inputText,inputPlaceholder:o.inputPlaceholder,cardBorder:o.border,inputBorder:o.inputBorder,buttonBorder:o.buttonBorder,successBg:o.successBg,successBorder:o.successBorder,successText:o.successText,warningBg:o.warningBg,warningBorder:o.warningBorder,warningText:o.warningText,errorBg:o.errorBg,errorBorder:o.errorBorder,errorText:o.errorText,infoBg:o.infoBg,infoBorder:o.infoBorder,infoText:o.infoText},d=t?.inputVariant?t.inputVariant==="dark":s;return{brand:r,theme:m,dark:s,appName:h,primaryColor:u,dk:i,palette:i,fontFamily:o.fontFamily,monoFont:cr,inputDark:d,cardBg:d?i.cardBg:"#E9E9E9",cardBorder:d?i.cardBorder:"#C6C6C6",textPrimary:i.textPrimary,textSecondary:i.textSecondary,subtitleText:d?i.textSecondary:"#979AA0"}},[r,t,e])}const dr=(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(/\.$/,""),ur=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)}`,fr=(t,e)=>{const r=t.replace(/[^0-9.]/g,"").split("."),a=r[0]??"",n=r.slice(1).join(""),o=typeof e=="number"?Math.max(0,Math.min(e,18)):null;return r.length===1?a:`${a}.${o===null?n:n.slice(0,o)}`},pr=(t,e=6)=>!Number.isFinite(t)||t<=0?"0":t.toFixed(Math.min(Math.max(e,0),18)).replace(/\.?0+$/,""),mr=async t=>{try{return await navigator.clipboard.writeText(t),!0}catch(e){return console.error("Failed to copy to clipboard:",e),!1}},Me="spiceflow-spinner-keyframes";function hr(){if(typeof document>"u"||document.getElementById(Me))return;const t=document.createElement("style");t.id=Me,t.textContent="@keyframes spiceflow-spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}",document.head.appendChild(t)}const le=({size:t=16,borderWidth:e=2,color:r="currentColor",style:a})=>{const n=ue(!1);return A(()=>{n.current||(hr(),n.current=!0)},[]),v("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,...a}})},D=({variant:t="primary",size:e="md",loading:r=!1,fullWidth:a=!1,disabled:n,children:o,className:s="",style:u,theme:h,styles:l,dark:m,...i})=>{const{theme:d,dark:p,palette:y}=Fe(l,m),c=h||d,x=m??p,[w,g]=M(!1),[f,b]=M(!1),$=x?y.shell:"white",B=()=>{switch(t){case"primary":return{backgroundColor:l?.button?.backgroundColor||c.colors.primary,color:l?.button?.color||"#ffffff",border:`1px solid ${l?.button?.backgroundColor||c.colors.primary}`};case"secondary":return{backgroundColor:c.colors.secondary,color:c.colors.text,border:`1px solid ${c.colors.border}`};case"success":return{backgroundColor:c.colors.success,color:c.colors.text,border:`1px solid ${c.colors.success}`};case"error":return{backgroundColor:c.colors.error,color:c.colors.text,border:`1px solid ${c.colors.error}`};case"ghost":return{backgroundColor:"transparent",color:c.colors.textSecondary,border:`1px solid ${c.colors.border}`};case"outline":{const C=l?.button?.backgroundColor||c.colors.primary,ce=l?.button?.color||(x?"#ffffff":"#0e0d0b"),U=l?.button?.borderColor||(x?`${c.colors.primary}88`:"#0e0d0b"),F=n||r,qe=x?"1px":"1.5px",Oe=l?.button?.disabledBackgroundColor||`${C}88`,De=l?.button?.disabledColor||ce;return{height:"56px",backgroundColor:F?Oe:f?`${C}cc`:w?`${C}ee`:C,color:F?De:ce,border:`${qe} solid ${U}`,borderRadius:l?.button?.borderRadius||"12px",fontSize:"22px",fontWeight:500,fontFamily:j.mono,opacity:F?.78:1,transform:F?"none":f?"scale(0.98)":w?"translateY(-2px)":"none",boxShadow:F?`3px 3px 0px ${$}, 4px 4px 0px ${U}`:f?`2px 2px 0px ${U}`:w?`5px 5px 0px ${$}, 6px 6px 0px ${U}`:`3px 3px 0px ${$}, 4px 4px 0px ${U}`,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:`${c.spacing.sm} ${c.spacing.md}`,fontSize:c.typography.fontSize.sm};case"md":return{padding:`${c.spacing.md} ${c.spacing.lg}`,fontSize:c.typography.fontSize.base};case"lg":return{padding:`${c.spacing.lg} ${c.spacing.xl}`,fontSize:c.typography.fontSize.lg};default:return{}}},N={borderRadius:l?.button?.borderRadius||c.borderRadius.md,fontWeight:l?.button?.fontWeight||c.typography.fontWeight.medium,fontFamily:l?.button?.fontFamily||c.typography.fontFamily,fontSize:l?.button?.fontSize||void 0,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease, opacity 150ms ease",cursor:n||r?"not-allowed":"pointer",opacity:(n||r)&&t!=="outline"?.6:1,width:a?"100%":"auto",display:"flex",alignItems:"center",justifyContent:"center",gap:c.spacing.sm,...B(),...E(),...l?.button?.fontSize&&{fontSize:l.button.fontSize}},T=n||r;return V("button",{type:i.type??"button","data-spiceflow-focus":!0,"aria-busy":r||void 0,"aria-disabled":T||void 0,style:{...N,...u},className:s,disabled:T,onMouseEnter:C=>{g(!0),i.onMouseEnter?.(C)},onMouseLeave:C=>{g(!1),b(!1),i.onMouseLeave?.(C)},onMouseDown:C=>{b(!0),i.onMouseDown?.(C)},onMouseUp:C=>{b(!1),i.onMouseUp?.(C)},...i,children:[r&&v(le,{size:16}),o]})},gr=({onAuthSuccess:t,onAuthError:e,theme:r="light",className:a="",buttonText:n="Login with Privy",autoTrigger:o=!1})=>{const s=Ne(r),[u,h]=M(!1),[l,m]=M(!1),{ready:i,authenticated:d,user:p}=K(),{login:y}=dt(),{logout:c}=ut();A(()=>{h(!0)},[]),A(()=>{o&&i&&!d&&u&&!l&&(m(!0),x())},[o,i,d,u,l]),A(()=>{if(i&&d&&p&&t){const g=p.wallet?.address||p.email?.address;g&&t(g)}},[i,d,p,t]),A(()=>{},[i,d,e]);const x=()=>{try{y()}catch(g){const f=`Login failed: ${String(g)}`;e?e(f):console.error(f)}},w=()=>{try{c()}catch(g){const f=`Logout failed: ${String(g)}`;e?e(f):console.error(f)}};if(!u)return v("div",{className:a,children:v(D,{variant:"primary",disabled:!0,theme:s,children:n})});if(!i)return v("div",{className:a,children:v(D,{variant:"primary",disabled:!0,theme:s,children:"Loading..."})});if(d&&p){const g=p.wallet?.address||p.email?.address,f=g?Le(g):"Connected";return v("div",{className:a,children:V(D,{variant:"primary",onClick:w,theme:s,children:["Logout (",f,")"]})})}return o?v("div",{className:a,children:V("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px",flexDirection:"column",gap:"12px"},children:[v(le,{size:40,borderWidth:3,color:"#3b82f6"}),v("p",{style:{color:"#6b7280",fontSize:"14px"},children:"Opening login..."})]})}):v("div",{className:a,children:v(D,{variant:"primary",onClick:x,theme:s,children:n})})};export{Ct as A,D as B,$t as C,Bt as D,Gt as E,It as F,se as G,St as H,At as I,G as J,mr as K,tr as L,Se as M,ar as N,Ae as O,gr as P,Ue as Q,Ce as R,J as S,ir as T,lr as U,re as V,W as a,xe as b,te as c,dr as d,pr as e,j as f,kt as g,S as h,k as i,ur as j,le as k,Le as l,Ut as m,$e as n,z as o,fr as p,I as q,ht as r,Pt as s,gt as t,Fe as u,P as v,Et as w,Te as x,Dt as y,mt as z};
|
package/dist/privy-KaNyb2oB.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use client";
|
|
2
|
-
"use strict";var We=Object.create;var se=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Fe=Object.getPrototypeOf,Me=Object.prototype.hasOwnProperty;var je=(t,e,r,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ue(e))!Me.call(t,o)&&o!==r&&se(t,o,{get:()=>e[o],enumerable:!(a=Ne(e,o))||a.enumerable});return t};var Le=(t,e,r)=>(r=t!=null?We(Fe(t)):{},je(e||!t||!t.__esModule?se(r,"default",{value:t,enumerable:!0}):r,t));const E=require("react/jsx-runtime"),g=require("react"),k=require("@spicenet-io/spiceflow-core"),x=require("viem"),qe=require("viem/actions"),A=require("@privy-io/react-auth"),ie=require("wagmi"),le=require("@tanstack/react-query"),Oe={base:0,raised:1,sticky:10,overlay:20,popover:40,modal:1e3,dropdown:1100,toast:1200,tooltip:1300},De={none:"0",sm:"4px",md:"6px",card:"8px",input:"10px",shell:"9px",modal:"12px",pill:"9999px",circle:"50%"},T={out:"cubic-bezier(0.22, 1, 0.36, 1)",inOut:"cubic-bezier(0.65, 0, 0.35, 1)",linear:"linear"},P={fast:"120ms",normal:"150ms",slow:"300ms",progress:"400ms"},_e={interactive:`transform ${P.normal} ${T.out}, box-shadow ${P.normal} ${T.out}, background-color ${P.normal} ${T.out}, border-color ${P.normal} ${T.out}, color ${P.normal} ${T.out}`,color:`background-color ${P.normal} ${T.out}, border-color ${P.normal} ${T.out}, color ${P.normal} ${T.out}`,popover:`opacity ${P.normal} ${T.out}, transform ${P.normal} ${T.out}`},D={ui:'"Helvetica Neue", sans-serif',mono:'"IBM Plex Mono", monospace'};function _(t,e){return!t||!e?!1:x.isAddress(t)&&x.isAddress(e)?x.getAddress(t)===x.getAddress(e):t.toLowerCase()===e.toLowerCase()}const ze="0xcA11bde05977b3631167028862bE2a173976CA11",Ge={4114:"0x860aFc632a6D625B95d8B96f39ECC48E988c6962"},He=new Set([5115]);function Je(t){const e=Ge[t.id]??(He.has(t.id)?void 0:ze);return x.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 Ye=[1,8453,42161,4114,11155111,421614,84532,5115,123420001114,688688,688689],z=Object.fromEntries(Ye.map(t=>k.getChainMeta(t)).filter(t=>t!=null).map(t=>[t.id,{...t,viemChain:Je(t),supportedTokens:k.getTokensForChain(t.id)}])),Qe=z;let ce={};const Q=new Map,de=t=>{ce={...t||{}},Q.clear()},V=t=>{const e=ce[t];return e&&typeof e=="string"&&e.length>0?e:z[t]?.rpcUrl},U=t=>z[t],X=t=>{const e=k.getChainMeta(t);return e?.displayName||e?.name||`Chain ${t}`},Ve=t=>{const e=k.getDelegateContract(t);if(!e)throw new Error(`Unsupported chain ID: ${t}`);return e},Xe=(t,e,r)=>{const a=U(t);return a?.blockExplorer?`${a.blockExplorer}/tx/${e}`:"#"};async function Ke(t,e){const r=`0x${e.toString(16)}`;try{await t.request({method:"wallet_switchEthereumChain",params:[{chainId:r}]});return}catch(o){if(!(o?.code===4902||typeof o?.message=="string"&&o.message.includes("Unrecognized chain ID")))throw o}const a=U(e);if(!a)throw new Error(`Cannot add unknown chain ${e} to wallet`);await t.request({method:"wallet_addEthereumChain",params:[{chainId:r,chainName:a.name||`Chain ${e}`,nativeCurrency:a.nativeCurrency||{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:[V(e)||a.rpcUrl],blockExplorerUrls:a.blockExplorer?[a.blockExplorer]:void 0}]})}const ue=t=>{const e=U(t);if(!e)throw new Error(`Unsupported chain ID: ${t}`);const r=V(t);if(!r)throw new Error(`No RPC URL configured for chain ID: ${t}`);const a=`${t}:${r}`,o=Q.get(a);if(o)return o;const n=x.createPublicClient({chain:e.viemChain,transport:x.http(r,{timeout:15e3,retryCount:2,retryDelay:300}),batch:{multicall:{wait:16}}});return Q.set(a,n),n},Ze=()=>{const t={};return Object.values(z).forEach(e=>{t[e.id]={name:e.name,moralisName:e.moralisId||"",chain:e.viemChain,rpcUrl:V(e.id)||e.rpcUrl}}),t},et=(t,e=[])=>{const r=U(t);if(!r)return[];const a=[];if(![11155111,421614,84532,688689].includes(t)){const n=e.find(s=>s.chainId===t&&s.isNative);n?a.push(n):a.push({address:k.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 a;const o=a.some(n=>n.isNative);return r.supportedTokens.forEach(n=>{if(o&&k.isNativeToken(n.address))return;const s=e.find(u=>u.chainId===t&&_(u.address,n.address));s?a.push(s):a.push({address:n.address,name:n.name,symbol:n.symbol,decimals:n.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:n.logo,isNative:!1,chainId:t})}),a},tt=async(t,e)=>{const r=U(t);if(!r)throw new Error(`Unsupported chain ID: ${t}`);const a=e.toLowerCase();if(k.isNativeToken(a)){if(!r.nativeCurrency?.decimals)throw new Error(`Native currency decimals not configured for chain ${t}`);return r.nativeCurrency.decimals}if(r.supportedTokens){const o=r.supportedTokens.find(n=>_(n.address,a));if(o)return o.decimals}try{if(!x.isAddress(e,{strict:!1}))throw new Error(`Invalid token address: ${e}`);const o=x.getAddress(e),n=ue(t),s=await qe.readContract(n,{address:o,abi:x.erc20Abi,functionName:"decimals"});return Number(s)}catch{throw new Error(`Could not determine decimals for token ${e} on chain ${t}`)}};class R extends Error{constructor(e,r,a={}){super(r),this.code=e,this.context=a,this.name="SpiceflowError",Error.captureStackTrace&&Error.captureStackTrace(this,R)}}function K(t){return t instanceof R}const rt=["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||"",a=e.details||"";return`${r} ${a}`.trim()}const pe=t=>{if(K(t))return t.code==="WALLET_REJECTED";const e=fe(t).toLowerCase();return rt.some(r=>e.includes(r))};let Z=null;function at(t){return Z?.message===t?Z.detail:void 0}const nt=(t,e="Something went wrong. Please try again.")=>{if(pe(t))return"Transaction was rejected.";if(K(t)){const r=t.message||e,{requestId:a,httpStatus:o,responseBody:n,endpoint:s}=t.context;return(a||o||s)&&(Z={message:r,detail:{requestId:a,httpStatus:o,responseBody:n,endpoint:s}}),r}return fe(t)||e},ot=[...k.DELEGATE_ABI,...k.ERC20_ABI,...k.spicenetEscrowAbi,...k.uniV3SwapRouterAbi];function ee(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=>ee(r,e+1)):typeof t=="object"?Object.values(t).flatMap(r=>ee(r,e+1)):[]}function me(t){try{const e=x.decodeErrorResult({abi:ot,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],a=r&&r!=="0x"?me(r):void 0;return a?`Call reverted: ${a}`:"Call reverted (no reason returned)"}return e.errorName}catch{try{const e=x.hexToString(t).replace(/\x00+$/g,"").trim();return/^[\x20-\x7e]+$/.test(e)&&e.length>1?e:void 0}catch{return}}}function st(t){for(const e of ee(t)){if(!x.isHex(e))continue;const r=me(e);if(r)return r}}function it(t,e){const r=e.match(/Output amount (\d+) is insufficient after fees (\d+) on chain (\d+)/);if(!r)return e;const[,a,o,n]=r,s=Number(n),u=BigInt(a),h=BigInt(o);let l;for(const v of t.intents){const y=v.chainBatches.find(f=>f.chainId===s);if(y){l=y;break}}const m=l?.tokenTransfers.find(v=>v.from==="escrow"&&_(v.to,t.user)&&!k.isNativeToken(v.token)),i=X(s);if(!m)return`Amount is too small to cover the estimated fee on ${i}.`;const d=k.getTokenByAddress(m.token,s),p=d?.decimals??18,w=d?.symbol??"tokens",c=x.formatUnits(u,p),$=x.formatUnits(h,p);return`Amount is too small to cover the estimated fee on ${i}. Amount: ${c} ${w}. Estimated fee: ${$} ${w}.`}function lt(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 ct="https://tx-submission-api.spicenet.io",he=ct;function dt(t,e){return typeof e=="bigint"?e.toString():e}function L(t,e=""){if(Array.isArray(t))t.forEach((r,a)=>L(r,`${e}[${a}]`));else if(t&&typeof t=="object")for(const[r,a]of Object.entries(t)){const o=e?`${e}.${r}`:r;if(!a&&(r==="user"||r==="to"||r==="from"||r==="address"))throw new R("INVALID_PARAMS",`Wallet not ready: ${o} is missing from the request. Wait a moment and retry, or log in again.`,{path:o});L(a,o)}}async function G(t,e){const r={...e?.headers},a=r["x-request-id"]??crypto.randomUUID();r["x-request-id"]=a;const o=await fetch(t,{...e,headers:r}),n=o.headers.get("x-request-id")??"";return Object.assign(o,{requestId:n})}function q(t,e){if(!t)return e;const r=t.error,a=(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=st(t);return o&&!a.includes(o)?`${a} \u2014 ${o}`:a}async function ut(t){try{return await t.json()}catch{return null}}function ft(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(a=>typeof a=="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 pt{constructor(){this.baseUrl=he}setBaseUrl(e){this.baseUrl=e}getBaseUrl(){return this.baseUrl}async requestJson(e,r){const a=`${this.baseUrl}${e}`,o=await G(a,r.method&&r.method!=="GET"?{method:r.method,headers:{"Content-Type":"application/json"},body:JSON.stringify(r.body,dt)}:void 0),n=await o.json();if(!o.ok||n.success===!1||r.ok&&!r.ok(n)){const s=q(n,r.fallbackError(o.status));throw new R(r.code??"RELAYER_ERROR",r.mapError?r.mapError(s):s,{httpStatus:o.status,requestId:o.requestId,responseBody:JSON.stringify(n),endpoint:e,...r.context})}return n}async createAction(e){return L(e),this.requestJson("/actions",{method:"POST",body:e,fallbackError:r=>`Relayer API error: ${r}`})}async estimateActionFees(e){return L(e),(await this.requestJson("/actions/fees/estimate",{method:"POST",body:e,fallbackError:r=>`Relayer fee estimate error: ${r}`,ok:r=>!!r.success&&!!r.data?.feeEstimate,mapError:r=>it(e,r)})).data.feeEstimate}async estimateBatchGas(e){L(e);const r=await this.requestJson("/actions/gas/estimate",{method:"POST",body:e,fallbackError:a=>`Relayer gas estimate error: ${a}`,ok:a=>!!a.success&&!!a.data?.gasFee});return{gasFee:BigInt(r.data.gasFee),gasQuoteSource:r.data.gasQuoteSource}}async executeStep(e,r,a,o){const n=`${this.baseUrl}/actions/${e}/intents/${r}/steps/${a}`,s=`/actions/${e}/intents/${r}/steps/${a}`,u=crypto.randomUUID(),h=3e4,l=new Promise((d,p)=>setTimeout(()=>p(new R("RELAYER_EXECUTE_ERROR",`Execute step request timed out after ${h/1e3}s`,{actionId:e,intentIndex:r,stepIndex:a,endpoint:s,requestId:u})),h)),m=await Promise.race([G(n,{method:"POST",headers:{"Content-Type":"application/json","x-request-id":u},body:JSON.stringify(o)}),l]),i=await m.json();if(!m.ok||i.success===!1)throw new R("RELAYER_EXECUTE_ERROR",q(i,`Execute step error: ${m.status}`),{httpStatus:m.status,requestId:m.requestId,responseBody:JSON.stringify(i),endpoint:s,actionId:e});if(i?.status==="error"||i?.status==="reverted"){const d=q(i,""),p=d?`: ${d}`:"";throw new R("RELAYER_EXECUTE_ERROR",`Step ${a} previously ${i.status}${p}`,{httpStatus:m.status,requestId:m.requestId,responseBody:JSON.stringify(i),endpoint:s,actionId:e,intentIndex:r,stepIndex:a,stepStatus:i.status})}return{success:!0,transactionHash:i.transactionHash}}async checkStepStatus(e,r){const a=e.split("/"),o=a[0],n=a.length>=2?a[1]:"0",s=await this.requestJson(`/actions/${o}/intents/${n}/steps/${r}`,{fallbackError:u=>`Intent step status check failed: ${u}`,code:"RELAYER_STATUS_ERROR",context:{intentId:e}});return{success:!0,data:{status:s.status==="error"?"reverted":s.status,transactionHash:s.txid,error:q(s,"")}}}async createWallet(e,r){return this.requestJson(`/wallets/${e}`,{method:"PUT",body:r,fallbackError:a=>`Create wallet error: ${a}`})}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 N=new pt;async function mt(t){const e=`${N.getBaseUrl()}/wallets/${t}/balance`,r=await G(e,{cache:"no-store"}),a=await ut(r);if(!r.ok||a?.success===!1)throw new R("RELAYER_ERROR",q(a,`Unable to verify Spice balance: ${r.status}`),{httpStatus:r.status,requestId:r.requestId,responseBody:JSON.stringify(a),endpoint:`/wallets/${t}/balance`});return ft(a)}const te=new Map,ht="spiceflow.smartWallet.";function ge(t){return`${ht}${t.toLowerCase()}`}function gt(t){try{return typeof localStorage<"u"&&localStorage.getItem(ge(t))==="1"}catch{return!1}}function ye(t){try{typeof localStorage<"u"&&localStorage.setItem(ge(t),"1")}catch{}}function yt(t){if(!(t instanceof R))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 we(t,e){if(gt(t))return;const r=t.toLowerCase(),a=te.get(r);if(a)return a;const o=(async()=>{try{await N.getWallet(t),ye(t);return}catch(l){if(!yt(l))throw l}const{unix_timestamp:n}=await N.getRollupTimestamp(),s=`I am creating a new smart wallet and adding an admin wallet ethereum:0x${t.slice(2).toLowerCase()}. Nonce: ${n}`,u=await e(s),h=typeof u=="string"?u:u.signature;if(!h)throw new Error("Wallet returned no smart wallet signature");await N.createWallet(t,{timestamp:n,signature:h}),ye(t)})();te.set(r,o);try{await o}finally{te.delete(r)}}const wt=(t,e)=>{const r=o=>e?e(o):X(o),a=[];return t.forEach((o,n)=>{const s=o.calls&&o.calls.length>0,u=o.tokenTransfers&&o.tokenTransfers.length>0;!s&&!u||a.push({stepId:n,status:n===0?"processing":"pending",chainId:o.chainId,chainName:r(o.chainId),description:"Processing transaction"})}),a},bt=t=>{const e=t?.wallet;if(e?.address&&e.walletClientType==="privy"&&e.connectorType==="embedded"&&!e.imported)return e.address},be=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 a=null;for(const o of r)try{const n=await t.getWalletClient(o);if(n)return n}catch(n){a=n}if(a)throw a}if(typeof t.getEthereumProvider=="function"){const r=await t.getEthereumProvider(),a=e?U(e)?.viemChain:void 0;return x.createWalletClient({account:t.address,chain:a,transport:x.custom(r)})}throw new Error("Wallet client not available")},xt=async(t,e)=>{if(!t?.address)throw new Error("Wallet not available");if(typeof t.getEthereumProvider=="function")return t.getEthereumProvider();const r=await be(t,e);return{request:a=>r.request(a)}},H=t=>t?.address?{address:t.address,wallet:t,getWalletClient:e=>be(t,e),getEthereumProvider:e=>xt(t,e)}:null,re=()=>{const{address:t,connector:e}=ie.useAccount();let r=null,a=null;try{r=A.useWallets(),{user:a}=A.usePrivy()}catch{r=null,a=null}const o=r?.wallets||[],n=A.getEmbeddedConnectedWallet(o),s=n?.address?.toLowerCase(),u=o.find(c=>c.connectorType!=="embedded"&&c.address?.toLowerCase()!==s),h=t?.toLowerCase(),l=t&&e&&!(h&&s&&h===s)?{address:t,connector:e,getEthereumProvider:()=>e.getProvider()}:null,m=t&&e?{address:t,connector:e,getEthereumProvider:()=>e.getProvider()}:null,i=H(n),d=H(l)||H(u),p=i?.address||bt(a),w=H(m)||d;return{embeddedWallet:i,externalWallet:d,embeddedAddress:p,externalAddress:d?.address,activeWallet:w,activeAddress:w?.address}},xe=()=>{const t=g.useContext(J),e=t?.mode,{isConnected:r,address:a}=ie.useAccount();let o=null,n=null,s=null,u=null,h=null;try{o=A.usePrivy(),n=A.useSign7702Authorization(),s=A.useSignMessage(),u=A.useWallets()}catch(f){h=f instanceof Error?f.message:String(f)}if(h)return e==="ondemand"&&r&&a?{isReady:!0,isAuthenticated:!0,isConnected:!0,address:a,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{ready:l=!1,authenticated:m=!1}=o||{},i=t?.embeddedWalletAddress,d=A.getEmbeddedConnectedWallet(u?.wallets||[]),p=i||d?.address,w=!!p&&!!d,c={isReady:e==="ondemand"?!0:l,isAuthenticated:e==="ondemand"?!0:m||w,isConnected:e==="ondemand"?r&&!!a||l&&(m||w)&&w:l&&w,address:e==="ondemand"&&r?a:p,provider:"privy"},$=async f=>{if(!d)throw new Error("Embedded wallet not available");const b=await d.getEthereumProvider(),{createWalletClient:C,custom:I}=await import("viem");return{signature:await C({account:d.address,transport:I(b)}).signMessage({account:d.address,message:f})}},v=async f=>{if(s)try{return{signature:(await s.signMessage({message:f})).signature}}catch(b){if(!d)throw b}if(!d)throw new Error("Privy sign message not available");return $(f)},y=async()=>{if(!p)throw new Error("Embedded wallet not available for smart wallet setup");await we(p,v)};return{...c,actions:{signAuthorization:async f=>{if(!n)throw new Error("Privy sign authorization not available");try{await y();const b=await n.signAuthorization({contractAddress:f.contractAddress,chainId:f.chainId,nonce:f.nonce},{address:p});return delete b.v,b}catch(b){const C=typeof b?.message=="string"?b.message:String(b?.message??b??"");throw C.includes("not configured")||C.includes("chain")?new Error(`Chain ${f.chainId} is not configured in PrivyProvider. Add this chain to your Privy dashboard or supportedChainIds.`):b}},signMessage:async f=>{if(typeof f=="object"&&"raw"in f){if(await y(),!d)throw new Error("Embedded wallet not available for raw signing");return $(f)}return v(f)},getEthereumProvider:async()=>{if(!d)throw new Error("Embedded wallet not available");return d.getEthereumProvider()}}}},vt="https://portal-api.spicenet.io/api/v1",ae=t=>t.replace(/\/+$/,""),Et=(t,e)=>`${t}:${e}`;async function $t(t,e){const r=new URLSearchParams({walletAddress:e,campaignId:"spicenet-portal",campaignGroup:"1"}),a=await fetch(`${t}/portal/mainnet/linked-portal-wallet?${r.toString()}`,{cache:"no-store"});if(!a.ok){if(a.status>=500){const o=new Error(`Failed to resolve linked portal wallet: ${a.status}`);throw o.status=a.status,o}return null}return(await a.json()).portalWalletAddress?.toLowerCase()??null}async function Ct(t,e,r){const a=new URLSearchParams({walletAddress:e,campaignId:r.campaignId,campaignGroup:r.campaignGroup,partnerId:r.partnerId}),o=await fetch(`${t}/portal/mainnet/whitelist/check?${a.toString()}`,{cache:"no-store"});if(!o.ok){const n=new Error(`Failed to check whitelist: ${o.status}`);throw n.status=o.status,n}return await o.json()}async function Bt(t,e,r,a){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:a})});if(!o.ok)throw new Error(`Failed to link wallet: ${o.status}`)}function ve({walletAddress:t,campaignId:e,campaignGroup:r,partnerId:a,apiBaseUrl:o=vt,enabled:n=!0,staleTime:s=5*60*1e3,refetchInterval:u=!1}={}){const{isAuthenticated:h,isConnected:l}=xe(),{externalAddress:m,embeddedAddress:i}=re(),d=t??m,p=typeof d=="string"?d.toLowerCase():void 0,w=typeof i=="string"?i.toLowerCase():void 0,c=typeof m=="string"?m.toLowerCase():void 0,$=n&&h&&l&&!!m&&!!p&&x.isAddress(p)&&!!e&&!!r&&!!a,v=g.useMemo(()=>["partner-whitelist","check",p,e,r,a,ae(o)],[p,e,r,a,o]),y=le.useQuery({queryKey:v,enabled:$,staleTime:s,refetchInterval:u,retry:(B,F)=>{const W=F?.status;return typeof W=="number"&&W>=400&&W<500?!1:B<3},retryDelay:B=>Math.min(1e3*2**B,15e3),queryFn:async()=>{if(!p||!x.isAddress(p))throw new Error("A valid wallet address is required");if(!e||!r||!a)throw new Error("campaignId, campaignGroup, and partnerId are required");const B=ae(o),F={campaignId:e,campaignGroup:r,partnerId:a},W=await $t(B,p);return W?Ct(B,W,F):{walletAddress:p,campaignId:e,campaignGroup:r,partnerId:a,isWhitelisted:!1,isLinkedWallet:!1,whitelistedWalletAddress:null,externalWalletAddress:p}}}),f=n&&h&&l&&!!c&&x.isAddress(c)&&!!w&&x.isAddress(w)&&!!e&&!!r&&!!a,b=le.useMutation({mutationFn:B=>Bt(ae(o),{campaignId:e,campaignGroup:r,partnerId:a},B.external,B.embedded)}),C=g.useRef(new Set),I=b.mutate;return g.useEffect(()=>{if(!f||!c||!w||!e||!r||!a)return;const B=Et(c,w);C.current.has(B)||(C.current.add(B),I({external:c,embedded:w}))},[f,c,w,e,r,a,I]),{isWhitelisted:y.data?.isWhitelisted??!1,whitelistCheck:y.data,checkedWalletAddress:p,externalWalletAddress:m,embeddedWalletAddress:i,isExternalWalletConnected:!!m,isWhitelistCheckEnabled:$,linkWallet:b,isWalletLinked:b.isSuccess,...y}}const kt=["__spicenet_whitelist_blocked__"],Ee="spiceflow-mode",$e=()=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Ee);return t==="7702"?"7702":t==="non7702"?"ondemand":t==="embedded"?"7702":t==="external"?"ondemand":null}catch{return null}},St=t=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Ee,t==="7702"?"7702":"non7702")}catch{}},It=()=>$e()!==null,Ce=g.createContext(null),J=g.createContext(null),At=({children:t,value:e,whitelist:r})=>{const a=!!r&&r.enabled!==!1,{isWhitelisted:o,isLoading:n,whitelistCheck:s}=ve(a?r:{enabled:!1}),u=a&&!o,h=g.useMemo(()=>({...e,mode:u?"ondemand":e.mode,allowedTokens:u?kt:e.allowedTokens,isUserWhitelisted:o,isWhitelistChecking:n,isWhitelistConfigured:a,isWhitelistGateActive:u,whitelistCheck:s}),[e,a,u,o,n,s]);return E.jsx(J.Provider,{value:h,children:t})},Tt=({children:t,provider:e="privy",supportedChainIds:r,allowedTokens:a,network:o="testnet",mode:n,skipFlow:s=[],nativeChainId:u,appName:h="Spicenet",apiUrl:l,theme:m,rpcOverrides:i,whitelist:d})=>{g.useEffect(()=>{if(!l)return;const I=N.getBaseUrl();return N.setBaseUrl(l),()=>N.setBaseUrl(I)},[l]),g.useEffect(()=>(de(i),()=>de(void 0)),[i]);const p=g.useMemo(()=>k.getChainIdsByNetwork(o),[o]),w=r??p,c=m??null,[$,v]=g.useState(()=>n??$e()??"7702");g.useEffect(()=>{n&&v(n)},[n]);const y=g.useCallback(I=>{if(n){v(n);return}v(I),St(I)},[n]),{embeddedAddress:f,externalAddress:b}=re(),C=g.useMemo(()=>({provider:e,supportedChainIds:w,allowedTokens:a,skipFlow:s,mode:$,setMode:y,network:o,nativeChainId:u,appName:h,apiUrl:l,rpcOverrides:i,embeddedWalletAddress:f,externalWalletAddress:b,isUserWhitelisted:null,isWhitelistChecking:!1,isWhitelistConfigured:!1,isWhitelistGateActive:!1}),[e,w,a,s,$,y,o,u,h,l,i,f,b]);return E.jsx(Ce.Provider,{value:c,children:E.jsx(J.Provider,{value:C,children:E.jsx(At,{value:C,whitelist:d,children:t})})})},Pt={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:D.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"}},Rt={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"},Wt={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"},Be=(t="light")=>({mode:t,...Pt,colors:t==="light"?Rt:Wt});function Y(t,e){const r=t.replace("#",""),a=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))),n=Math.max(0,Math.round(parseInt(r.substring(4,6),16)*(1-e)));return`#${a.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`}function Nt(t,e){return{shell:e?.shell??"#141414",shellBorder:e?.shellBorder??Y(e?.shell??"#141414",.35),shellInnerBorder:e?.shellInnerBorder??Y(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 Ut(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 ke(t,e){const r=e?{...t,...e}:t,a=r.dark??!1,o=r.primaryColor,n=r.shell??(a?"#141414":"#ffffff");return{primaryColor:o,dark:a,fontFamily:r.fontFamily??'"Helvetica Neue", sans-serif',appName:r.appName??"Spicenet",logo:r.logo,borderRadius:r.borderRadius??"8px",shell:n,shellBorder:Y(n,a?.35:.085),shellInnerBorder:Y(n,a?.55:.165),card:r.card??(a?"#1e1e1e":"#f9fafb"),input:a?"#171717":"#ffffff",hover:a?"#2a2a2a":"#f3f4f6",text:r.text??(a?"#ffffff":"#111827"),textMuted:r.textMuted??(a?"#888888":"#6b7280"),inputText:a?"#e0e0e0":"#111827",inputPlaceholder:a?"#555555":"#9ca3af",border:r.border??(a?"rgba(255,255,255,0.08)":"#e5e7eb"),inputBorder:a?"rgba(255,255,255,0.10)":"#d1d5db",buttonBorder:a?"rgba(255,255,255,0.12)":"#0e0d0b",successBg:a?"#0a1f18":"#d1fae5",successBorder:a?"#1a4a3a":"#6ee7b7",successText:a?"#6ee7b7":"#065f46",warningBg:a?"#1f1a0d":"#fef3c7",warningBorder:a?"#4a3820":"#fde68a",warningText:a?"#fbbf24":"#92400e",errorBg:a?"#1f0d0d":"#fef2f2",errorBorder:a?"#4a2020":"#fecaca",errorText:a?"#f87171":"#dc2626",infoBg:a?"#0d1325":"#dbeafe",infoBorder:a?"#2a3a5a":"#93c5fd",infoText:a?"#60a5fa":"#1e40af"}}const Ft=D.mono;function Se(t,e){const r=g.useContext(Ce)??void 0;return g.useMemo(()=>{const a=r??{primaryColor:"#EA4B4B"},o={...t?.primaryColor?{primaryColor:t.primaryColor}:{},...t?.fontFamily?{fontFamily:t.fontFamily}:{},...e!==void 0?{dark:e}:{}},n=ke(a,o),{dark:s,primaryColor:u,appName:h}=n,l=Be(s?"dark":"light"),m={...l,colors:{...l.colors,primary:u,primaryHover:`${u}dd`},typography:{...l.typography,fontFamily:n.fontFamily}},i={shell:n.shell,shellBorder:n.shellBorder,shellInnerBorder:n.shellInnerBorder,cardBg:n.card,inputBg:n.input,hoverBg:n.hover,textPrimary:n.text,textSecondary:n.textMuted,inputText:n.inputText,inputPlaceholder:n.inputPlaceholder,cardBorder:n.border,inputBorder:n.inputBorder,buttonBorder:n.buttonBorder,successBg:n.successBg,successBorder:n.successBorder,successText:n.successText,warningBg:n.warningBg,warningBorder:n.warningBorder,warningText:n.warningText,errorBg:n.errorBg,errorBorder:n.errorBorder,errorText:n.errorText,infoBg:n.infoBg,infoBorder:n.infoBorder,infoText:n.infoText},d=t?.inputVariant?t.inputVariant==="dark":s;return{brand:r,theme:m,dark:s,appName:h,primaryColor:u,dk:i,palette:i,fontFamily:n.fontFamily,monoFont:Ft,inputDark:d,cardBg:d?i.cardBg:"#E9E9E9",cardBorder:d?i.cardBorder:"#C6C6C6",textPrimary:i.textPrimary,textSecondary:i.textSecondary,subtitleText:d?i.textSecondary:"#979AA0"}},[r,t,e])}const Mt=(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(/\.$/,""),jt=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",Ie=(t,e=6,r=4)=>t.length<=e+r?t:`${t.slice(0,e)}...${t.slice(-r)}`,Lt=(t,e)=>{const r=t.replace(/[^0-9.]/g,"").split("."),a=r[0]??"",o=r.slice(1).join(""),n=typeof e=="number"?Math.max(0,Math.min(e,18)):null;return r.length===1?a:`${a}.${n===null?o:o.slice(0,n)}`},qt=(t,e=6)=>!Number.isFinite(t)||t<=0?"0":t.toFixed(Math.min(Math.max(e,0),18)).replace(/\.?0+$/,""),Ot=async t=>{try{return await navigator.clipboard.writeText(t),!0}catch(e){return console.error("Failed to copy to clipboard:",e),!1}},Ae="spiceflow-spinner-keyframes";function Dt(){if(typeof document>"u"||document.getElementById(Ae))return;const t=document.createElement("style");t.id=Ae,t.textContent="@keyframes spiceflow-spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}",document.head.appendChild(t)}const ne=({size:t=16,borderWidth:e=2,color:r="currentColor",style:a})=>{const o=g.useRef(!1);return g.useEffect(()=>{o.current||(Dt(),o.current=!0)},[]),E.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,...a}})},O=({variant:t="primary",size:e="md",loading:r=!1,fullWidth:a=!1,disabled:o,children:n,className:s="",style:u,theme:h,styles:l,dark:m,...i})=>{const{theme:d,dark:p,palette:w}=Se(l,m),c=h||d,$=m??p,[v,y]=g.useState(!1),[f,b]=g.useState(!1),C=$?w.shell:"white",I=()=>{switch(t){case"primary":return{backgroundColor:l?.button?.backgroundColor||c.colors.primary,color:l?.button?.color||"#ffffff",border:`1px solid ${l?.button?.backgroundColor||c.colors.primary}`};case"secondary":return{backgroundColor:c.colors.secondary,color:c.colors.text,border:`1px solid ${c.colors.border}`};case"success":return{backgroundColor:c.colors.success,color:c.colors.text,border:`1px solid ${c.colors.success}`};case"error":return{backgroundColor:c.colors.error,color:c.colors.text,border:`1px solid ${c.colors.error}`};case"ghost":return{backgroundColor:"transparent",color:c.colors.textSecondary,border:`1px solid ${c.colors.border}`};case"outline":{const S=l?.button?.backgroundColor||c.colors.primary,oe=l?.button?.color||($?"#ffffff":"#0e0d0b"),M=l?.button?.borderColor||($?`${c.colors.primary}88`:"#0e0d0b"),j=o||r,Te=$?"1px":"1.5px",Pe=l?.button?.disabledBackgroundColor||`${S}88`,Re=l?.button?.disabledColor||oe;return{height:"56px",backgroundColor:j?Pe:f?`${S}cc`:v?`${S}ee`:S,color:j?Re:oe,border:`${Te} solid ${M}`,borderRadius:l?.button?.borderRadius||"12px",fontSize:"22px",fontWeight:500,fontFamily:D.mono,opacity:j?.78:1,transform:j?"none":f?"scale(0.98)":v?"translateY(-2px)":"none",boxShadow:j?`3px 3px 0px ${C}, 4px 4px 0px ${M}`:f?`2px 2px 0px ${M}`:v?`5px 5px 0px ${C}, 6px 6px 0px ${M}`:`3px 3px 0px ${C}, 4px 4px 0px ${M}`,transition:"transform 150ms ease, box-shadow 150ms ease, background-color 150ms ease, border-color 150ms ease, color 150ms ease"}}default:return{}}},B=()=>{if(t==="outline")return{};switch(e){case"sm":return{padding:`${c.spacing.sm} ${c.spacing.md}`,fontSize:c.typography.fontSize.sm};case"md":return{padding:`${c.spacing.md} ${c.spacing.lg}`,fontSize:c.typography.fontSize.base};case"lg":return{padding:`${c.spacing.lg} ${c.spacing.xl}`,fontSize:c.typography.fontSize.lg};default:return{}}},F={borderRadius:l?.button?.borderRadius||c.borderRadius.md,fontWeight:l?.button?.fontWeight||c.typography.fontWeight.medium,fontFamily:l?.button?.fontFamily||c.typography.fontFamily,fontSize:l?.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:a?"100%":"auto",display:"flex",alignItems:"center",justifyContent:"center",gap:c.spacing.sm,...I(),...B(),...l?.button?.fontSize&&{fontSize:l.button.fontSize}},W=o||r;return E.jsxs("button",{type:i.type??"button","data-spiceflow-focus":!0,"aria-busy":r||void 0,"aria-disabled":W||void 0,style:{...F,...u},className:s,disabled:W,onMouseEnter:S=>{y(!0),i.onMouseEnter?.(S)},onMouseLeave:S=>{y(!1),b(!1),i.onMouseLeave?.(S)},onMouseDown:S=>{b(!0),i.onMouseDown?.(S)},onMouseUp:S=>{b(!1),i.onMouseUp?.(S)},...i,children:[r&&E.jsx(ne,{size:16}),n]})},_t=({onAuthSuccess:t,onAuthError:e,theme:r="light",className:a="",buttonText:o="Login with Privy",autoTrigger:n=!1})=>{const s=Be(r),[u,h]=g.useState(!1),[l,m]=g.useState(!1),{ready:i,authenticated:d,user:p}=A.usePrivy(),{login:w}=A.useLogin(),{logout:c}=A.useLogout();g.useEffect(()=>{h(!0)},[]),g.useEffect(()=>{n&&i&&!d&&u&&!l&&(m(!0),$())},[n,i,d,u,l]),g.useEffect(()=>{if(i&&d&&p&&t){const y=p.wallet?.address||p.email?.address;y&&t(y)}},[i,d,p,t]),g.useEffect(()=>{},[i,d,e]);const $=()=>{try{w()}catch(y){const f=`Login failed: ${String(y)}`;e?e(f):console.error(f)}},v=()=>{try{c()}catch(y){const f=`Logout failed: ${String(y)}`;e?e(f):console.error(f)}};if(!u)return E.jsx("div",{className:a,children:E.jsx(O,{variant:"primary",disabled:!0,theme:s,children:o})});if(!i)return E.jsx("div",{className:a,children:E.jsx(O,{variant:"primary",disabled:!0,theme:s,children:"Loading..."})});if(d&&p){const y=p.wallet?.address||p.email?.address,f=y?Ie(y):"Connected";return E.jsx("div",{className:a,children:E.jsxs(O,{variant:"primary",onClick:v,theme:s,children:["Logout (",f,")"]})})}return n?E.jsx("div",{className:a,children:E.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px",flexDirection:"column",gap:"12px"},children:[E.jsx(ne,{size:40,borderWidth:3,color:"#3b82f6"}),E.jsx("p",{style:{color:"#6b7280",fontSize:"14px"},children:"Opening login..."})]})}):E.jsx("div",{className:a,children:E.jsx(O,{variant:"primary",onClick:$,theme:s,children:o})})};exports.Button=O,exports.CHAIN_CONFIGS=Qe,exports.PrivyLogin=_t,exports.RELAYER_API_URL=he,exports.SpiceFlowProvider=Tt,exports.SpiceFlowProviderContext=J,exports.SpiceflowError=R,exports.Spinner=ne,exports.addressesEqual=_,exports.buildDarkPalette=Nt,exports.buildLightPalette=Ut,exports.copyToClipboard=Ot,exports.createInitialSteps=wt,exports.describeChainSwitchError=lt,exports.duration=P,exports.easing=T,exports.ensureSmartWallet=we,exports.ensureWalletOnChain=Ke,exports.font=D,exports.formatBalance=Mt,exports.formatDecimalInput=qt,exports.formatUsd=jt,exports.getAllAssetsForChain=et,exports.getChainConfig=U,exports.getChainName=X,exports.getChainsForAssets=Ze,exports.getClientForChain=ue,exports.getDelegateContractAddress=Ve,exports.getExplorerUrl=Xe,exports.getRelayerErrorDetail=at,exports.getTokenDecimals=tt,exports.getWalletBalanceEntries=mt,exports.hasStoredSpiceFlowMode=It,exports.isSpiceflowError=K,exports.isUserRejection=pe,exports.parseNumericInput=Lt,exports.radius=De,exports.relayerFetch=G,exports.relayerService=N,exports.resolveTheme=ke,exports.sanitizeError=nt,exports.transition=_e,exports.truncateAddress=Ie,exports.useIsUserWhitelisted=ve,exports.useProviderWallets=re,exports.useSpiceBrand=Se,exports.useWallet=xe,exports.z=Oe;
|