@spicenet-io/spiceflow-ui 4.1.0 → 4.1.2

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.
Files changed (45) hide show
  1. package/dist/auth-privy.cjs.js +1 -1
  2. package/dist/auth-privy.js +1 -1
  3. package/dist/components/SpiceDeposit/lib/executors.d.ts +2 -1
  4. package/dist/components/SpiceLock/lib/executors.d.ts +1 -6
  5. package/dist/components/SpiceSupply/lib/executors.d.ts +2 -10
  6. package/dist/components/SpiceSupply/parts/SupplyStepStatusCard.d.ts +20 -0
  7. package/dist/components/SpiceWithdraw/SpiceWithdraw.d.ts +0 -1
  8. package/dist/components/SpiceWithdraw/parts/WithdrawBalanceCardHeader.d.ts +12 -0
  9. package/dist/components/SpiceWithdraw/parts/WithdrawDestinationCard.d.ts +28 -0
  10. package/dist/components/SpiceWithdraw/parts/WithdrawSourceCard.d.ts +34 -0
  11. package/dist/components/SpiceWithdraw/parts/WithdrawSubtitle.d.ts +8 -0
  12. package/dist/components/ui/AmountText.d.ts +0 -1
  13. package/dist/components/ui/PercentageDial.d.ts +8 -0
  14. package/dist/components/ui/WarningBanner.d.ts +16 -0
  15. package/dist/components/ui/icons.d.ts +3 -0
  16. package/dist/components/ui/index.d.ts +1 -1
  17. package/dist/execution/externalWalletClient.d.ts +21 -0
  18. package/dist/execution/fundEmbeddedWallet.d.ts +7 -0
  19. package/dist/execution/intentSigning.d.ts +12 -0
  20. package/dist/execution/intentStatus.d.ts +0 -6
  21. package/dist/execution/pollIntentStep.d.ts +2 -3
  22. package/dist/hooks/useDebouncedEstimate.d.ts +12 -0
  23. package/dist/hooks/useLockWalletAssets.d.ts +18 -0
  24. package/dist/index.cjs.js +21 -44
  25. package/dist/index.d.ts +6 -10
  26. package/dist/index.js +25 -48
  27. package/dist/privy-Dcad3cmM.js +2 -0
  28. package/dist/privy-KaNyb2oB.js +2 -0
  29. package/dist/types/status.d.ts +1 -0
  30. package/dist/types/supply.d.ts +4 -0
  31. package/dist/types/withdraw.d.ts +0 -14
  32. package/dist/utils/actionOutputEscrowFunding.d.ts +0 -7
  33. package/dist/utils/amounts.d.ts +1 -0
  34. package/dist/utils/chains/index.d.ts +0 -1
  35. package/dist/utils/crossChainRouter/index.d.ts +0 -1
  36. package/dist/utils/crossChainRouter/liquidityVenues.d.ts +0 -2
  37. package/dist/utils/crossChainRouter/uniV3.d.ts +0 -4
  38. package/dist/utils/errors.d.ts +1 -0
  39. package/dist/utils/logos.d.ts +0 -4
  40. package/dist/utils/relayer/index.d.ts +1 -0
  41. package/package.json +2 -16
  42. package/dist/privy-BpFzOWq5.js +0 -0
  43. package/dist/privy-DayQIFrD.js +0 -0
  44. package/dist/utils/crossChainRouter/buildIntent.d.ts +0 -34
  45. package/dist/utils/crossChainRouter/executeSwapThenAction.d.ts +0 -17
@@ -0,0 +1,2 @@
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};
@@ -0,0 +1,2 @@
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;
@@ -52,6 +52,7 @@ export interface StatusPanelProps {
52
52
  closeOnComplete?: boolean;
53
53
  type: "deposit" | "withdraw" | "payment" | "lock";
54
54
  results?: StatusResultItem[];
55
+ chainId?: number;
55
56
  chainName?: string;
56
57
  explorerUrl?: string;
57
58
  theme?: Theme;
@@ -5,6 +5,7 @@ import type { Call, ChainBatch } from "./authorization";
5
5
  import type { CustomStyles } from "./theme";
6
6
  import type { RelayerErrorDetail } from "../utils/errors";
7
7
  import type { ExactOutputSwapIntent, ResolvedExactOutputSwap } from "../utils/swapQuotes";
8
+ import type { ExecutionOptions } from "../hooks/useSpiceExecution";
8
9
  export interface DestinationTokenConfig {
9
10
  address: Address;
10
11
  symbol: string;
@@ -35,6 +36,9 @@ export interface SupplyBatchBuildOptions {
35
36
  withdrawalAmountOverride?: bigint;
36
37
  actionContextOverride?: Partial<BuildActionCallsContext>;
37
38
  }
39
+ export type BuildPayBatchesFn = (options?: SupplyBatchBuildOptions) => Promise<ChainBatch[]>;
40
+ export type BuildSupplyBatchesFn = (options?: SupplyBatchBuildOptions) => Promise<ChainBatch[]>;
41
+ export type EstimateRequiredGrossFundingFn = (requiredNetFunding: bigint, buildBatches: (grossFundingAmount: bigint) => ChainBatch[] | Promise<ChainBatch[]>, fundingToken: Address, executionOptions?: Pick<ExecutionOptions, "useCustomTransfers" | "userOverride">) => Promise<bigint>;
38
42
  export interface PayExecuteContext {
39
43
  asset: Asset;
40
44
  amount: string;
@@ -42,17 +42,3 @@ export interface SelectPopoverItem {
42
42
  icon?: string;
43
43
  detail?: string;
44
44
  }
45
- export interface SpiceWithdrawRequest {
46
- user: string;
47
- txHash: string;
48
- recipient: string;
49
- tokenAddress: string;
50
- chainId: number;
51
- amount: string;
52
- }
53
- export interface SpiceWithdrawResponse {
54
- success: boolean;
55
- error?: {
56
- message: string;
57
- };
58
- }
@@ -18,13 +18,6 @@ export declare function appendWalletFundedEscrowDeposit({ chainBatches, token, a
18
18
  token: Address;
19
19
  amount: bigint;
20
20
  }): ChainBatch[];
21
- export declare function buildActionOutputEscrowFundingPlan({ chainBatches, user, token, grossAmount, gasFee, }: {
22
- chainBatches: ChainBatch[];
23
- user: Address;
24
- token: Address;
25
- grossAmount: bigint;
26
- gasFee: bigint;
27
- }): ActionOutputEscrowFundingPlan;
28
21
  export declare function resolveActionOutputEscrowFundingPlan({ chainBatches, user, token, grossAmount, chainAuthorizations, }: {
29
22
  chainBatches: ChainBatch[];
30
23
  user: Address;
@@ -0,0 +1 @@
1
+ export declare function scaleAmountDecimals(amount: bigint, fromDecimals: number, toDecimals: number, rounding: "ceil" | "floor"): bigint;
@@ -6,7 +6,6 @@ export declare const CHAIN_CONFIGS: {
6
6
  [chainId: number]: UIChainConfig;
7
7
  };
8
8
  export declare const setRpcOverrides: (overrides?: Record<number, string>) => void;
9
- export declare const getRpcUrlForChain: (chainId: number) => string | undefined;
10
9
  export declare const getChainConfig: (chainId: number) => UIChainConfig | undefined;
11
10
  export declare const getChainName: (chainId: number) => string;
12
11
  export declare const getDelegateContractAddress: (chainId: number) => string;
@@ -10,7 +10,6 @@ export interface ResolveRouteParams {
10
10
  destinationChainId: number;
11
11
  intermediaryCandidates?: string[];
12
12
  }
13
- export declare function findTokenOnChain(symbol: string, chainId: number): ChainToken | undefined;
14
13
  export declare function findEquivalentOnChain(tokenAddress: string, targetChainId: number, sourceChainId?: number): ChainToken | undefined;
15
14
  export declare function resolveRoute(params: ResolveRouteParams): RoutePlan;
16
15
  export interface BuildRoutedBatchesParams {
@@ -2,7 +2,6 @@ import { type Address } from "viem";
2
2
  import type { Call, SwapIntent, BatchEntry, ResolvedSwap } from "@spicenet-io/spiceflow-core";
3
3
  import type { ExactOutputVenue } from "../swapQuotes";
4
4
  export type { ResolvedSwap };
5
- export declare function isSwapIntent(entry: BatchEntry): entry is SwapIntent;
6
5
  export interface LiquidityVenue {
7
6
  name: string;
8
7
  chainIds: number[];
@@ -13,7 +12,6 @@ export interface OneInchVenueConfig {
13
12
  baseUrl?: string;
14
13
  chainIds?: number[];
15
14
  }
16
- export declare function create1inchVenue(config?: OneInchVenueConfig): LiquidityVenue;
17
15
  export interface SatsumaVenueConfig {
18
16
  swapRouter: Address;
19
17
  quoterV2: Address;
@@ -14,15 +14,11 @@ export interface UniV3ExactOutputQuoteResult {
14
14
  sqrtPriceX96After: bigint;
15
15
  gasEstimate: bigint;
16
16
  }
17
- export declare function getUniV3Quote(params: UniV3QuoteParams): Promise<UniV3QuoteResult>;
18
17
  export declare function getBestUniV3Quote(params: Omit<UniV3QuoteParams, "fee"> & {
19
18
  feeTiers?: number[];
20
19
  }): Promise<UniV3QuoteResult & {
21
20
  fee: number;
22
21
  }>;
23
- export declare function getUniV3ExactOutputQuote(params: UniV3ExactOutputQuoteParams & {
24
- fee: number;
25
- }): Promise<UniV3ExactOutputQuoteResult>;
26
22
  export declare function getBestUniV3ExactOutputQuote(params: UniV3ExactOutputQuoteParams & {
27
23
  feeTiers?: number[];
28
24
  }): Promise<UniV3ExactOutputQuoteResult & {
@@ -18,3 +18,4 @@ export declare function getRelayerErrorDetail(message: string): RelayerErrorDeta
18
18
  export declare const sanitizeError: (error: unknown, fallback?: string) => string;
19
19
  export declare function decodeRevertReason(input: unknown): string | undefined;
20
20
  export declare function formatFeeEstimateError(request: CreateActionRequest, message: string): string;
21
+ export declare function describeChainSwitchError(switchError: any): string;
@@ -1,8 +1,4 @@
1
- import metamaskLogo from "../assets/icons/metamask.png";
2
- import rabbyLogo from "../assets/icons/rabby.png";
3
- import phantomLogo from "../assets/icons/phantom.png";
4
1
  import spicenetLogo from "../assets/icons/spicenet-mark.svg";
5
- export { metamaskLogo, rabbyLogo, phantomLogo };
6
2
  export declare const ethLogo: string;
7
3
  export declare const usdcLogo: string;
8
4
  export { spicenetLogo };
@@ -10,6 +10,7 @@ export declare class RelayerService {
10
10
  private baseUrl;
11
11
  setBaseUrl(url: string): void;
12
12
  getBaseUrl(): string;
13
+ private requestJson;
13
14
  createAction(request: CreateActionRequest): Promise<CreateActionResponse>;
14
15
  estimateActionFees(request: CreateActionRequest): Promise<FeeEstimateSummary>;
15
16
  estimateBatchGas(request: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spicenet-io/spiceflow-ui",
3
- "version": "4.1.0",
3
+ "version": "4.1.2",
4
4
  "description": "Spiceflow UI SDK",
5
5
  "type": "module",
6
6
  "packageManager": "bun@1.3.13",
@@ -54,13 +54,11 @@
54
54
  "license": "MIT",
55
55
  "dependencies": {
56
56
  "@spicenet-io/spiceflow-core": "^0.3.14",
57
- "lucide-react": "0.562.0",
58
57
  "tslib": "2.8.1"
59
58
  },
60
59
  "peerDependencies": {
61
60
  "@privy-io/react-auth": ">=2.24.0 <4.0.0",
62
61
  "@tanstack/react-query": ">=5.0.0",
63
- "axios": ">=1.0.0",
64
62
  "react": "^18.0.0",
65
63
  "react-dom": "^18.0.0",
66
64
  "viem": ">=2.21.0",
@@ -78,34 +76,22 @@
78
76
  "@rollup/plugin-json": "6.1.0",
79
77
  "@rollup/plugin-node-resolve": "16.0.3",
80
78
  "@rollup/plugin-replace": "6.0.3",
81
- "@rollup/plugin-typescript": "12.3.0",
82
79
  "@tanstack/react-query": "5.90.10",
83
80
  "@types/node": "24.10.1",
84
81
  "@types/react": "18.3.27",
85
82
  "@types/react-dom": "18.3.7",
86
- "@typescript-eslint/eslint-plugin": "6.21.0",
87
- "@typescript-eslint/parser": "6.21.0",
88
- "axios": "1.13.5",
83
+ "dotenv": "16.6.1",
89
84
  "esbuild": "0.24.2",
90
- "eslint": "8.57.1",
91
- "eslint-config-prettier": "10.1.8",
92
- "eslint-plugin-react": "7.37.5",
93
- "eslint-plugin-react-hooks": "4.6.2",
94
85
  "husky": "9.1.7",
95
- "jest": "29.7.0",
96
86
  "lint-staged": "17.0.8",
97
87
  "postcss": "8.5.6",
98
- "postcss-import": "16.1.1",
99
88
  "prettier": "3.9.5",
100
89
  "react": "18.3.1",
101
90
  "react-dom": "18.3.1",
102
91
  "rollup": "4.53.2",
103
- "rollup-plugin-copy": "3.5.0",
104
92
  "rollup-plugin-esbuild": "6.2.1",
105
93
  "rollup-plugin-peer-deps-external": "2.2.4",
106
94
  "rollup-plugin-postcss": "4.0.2",
107
- "sharp": "0.34.5",
108
- "ts-node": "10.9.2",
109
95
  "typescript": "5.9.3",
110
96
  "viem": "2.38.0",
111
97
  "wagmi": "2.19.5"
Binary file
Binary file
@@ -1,34 +0,0 @@
1
- import type { Address } from "viem";
2
- import type { ChainBatch } from "../../types/authorization";
3
- import type { LiquidityRegistry } from "./liquidityVenues";
4
- import type { ChainToken, RoutePlan, TokenRef, ResolvedSwap, Call } from "@spicenet-io/spiceflow-core";
5
- export type { TokenRef };
6
- export interface IntentAction {
7
- chainId: number;
8
- outputToken: TokenRef;
9
- calls: Call[];
10
- supportedInputTokens?: TokenRef[];
11
- }
12
- export interface BuildIntentParams {
13
- action: IntentAction;
14
- inputToken: TokenRef;
15
- inputAmount: bigint;
16
- registry: LiquidityRegistry;
17
- userAddress: Address;
18
- slippage?: number;
19
- intermediaryCandidates?: string[];
20
- }
21
- export interface BuildIntentResult {
22
- chainBatches: ChainBatch[];
23
- route: RoutePlan;
24
- resolvedSwaps: {
25
- sourceSwap?: ResolvedSwap;
26
- destinationSwap?: ResolvedSwap;
27
- };
28
- resolvedInputToken: ChainToken;
29
- resolvedOutputToken: ChainToken;
30
- solverFrontToken: ChainToken;
31
- solverFrontAmount: bigint;
32
- }
33
- export declare function resolveTokenRef(ref: TokenRef): ChainToken;
34
- export declare function buildIntent(params: BuildIntentParams): Promise<BuildIntentResult>;
@@ -1,17 +0,0 @@
1
- import type { Call, ChainBatch } from "../../types/authorization";
2
- import type { ExecutionOptions, OnProgress } from "../../hooks/useSpiceExecution";
3
- export type ExecuteFn = (chainBatches: ChainBatch[], tokenAddress: string, tokenTransferAmount: bigint, onProgress?: OnProgress, signal?: AbortSignal, options?: ExecutionOptions) => Promise<string>;
4
- export interface SwapThenActionParams {
5
- chainId: number;
6
- swapCalls: Call[];
7
- quoteAmountOut: bigint;
8
- buildActionCalls: (adjustedAmount: bigint) => Call[];
9
- tokenAddress: string;
10
- tokenTransferAmount: bigint;
11
- onProgress?: OnProgress;
12
- signal?: AbortSignal;
13
- options?: ExecutionOptions;
14
- buffers?: bigint[];
15
- }
16
- export declare function applyBuffer(amount: bigint, buffer: bigint): bigint;
17
- export declare function executeSwapThenAction(execute: ExecuteFn, params: SwapThenActionParams): Promise<string>;