@spicenet-io/spiceflow-ui 3.3.50 → 3.3.52

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spicenet-io/spiceflow-ui",
3
- "version": "3.3.50",
3
+ "version": "3.3.52",
4
4
  "description": "Spiceflow UI SDK",
5
5
  "type": "module",
6
6
  "packageManager": "bun@1.3.13",
@@ -1,2 +0,0 @@
1
- "use client";
2
- import{jsx as A,jsxs as Me}from"react/jsx-runtime";import{useContext as P,useState as _,useEffect as N,useMemo as U,createContext as oe,useCallback as Oe,useRef as Fe}from"react";import{getChainMeta as ie,getTokensForChain as Le,getDelegateContract as _e,ZERO_ADDRESS as je,isNativeToken as Y,getTokenByAddress as De,getChainIdsByNetwork as ze}from"@spicenet-io/spiceflow-core";import{isAddress as M,getAddress as q,defineChain as Ge,createPublicClient as Je,http as He,formatUnits as le,createWalletClient as Ye,custom as qe}from"viem";import{readContract as Qe}from"viem/actions";import{useQuery as Xe}from"@tanstack/react-query";import{useWallets as Q,usePrivy as X,getEmbeddedConnectedWallet as K,useSign7702Authorization as Ke,useSignMessage as Ve}from"@privy-io/react-auth";import{useDynamicContext as V}from"@dynamic-labs/sdk-react-core";import{useAccount as ce}from"wagmi";function j(t,e){return!t||!e?!1:M(t)&&M(e)?q(t)===q(e):t.toLowerCase()===e.toLowerCase()}const de=[{constant:!0,inputs:[],name:"name",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_spender",type:"address"},{name:"_value",type:"uint256"}],name:"approve",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transferFrom",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transfer",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"},{name:"_spender",type:"address"}],name:"allowance",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{payable:!0,stateMutability:"payable",type:"fallback"},{anonymous:!1,inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Transfer",type:"event"}],Ze="0xcA11bde05977b3631167028862bE2a173976CA11",et={4114:"0x860aFc632a6D625B95d8B96f39ECC48E988c6962"},tt=new Set([5115]);function rt(t){const e=et[t.id]??(tt.has(t.id)?void 0:Ze);return Ge({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 at=[1,8453,42161,4114,11155111,421614,84532,5115,123420001114,688688,688689],D=Object.fromEntries(at.map(t=>ie(t)).filter(t=>t!=null).map(t=>[t.id,{...t,viemChain:rt(t),supportedTokens:Le(t.id)}])),nt=D;let ue={};const Z=new Map,pe=t=>{ue={...t||{}},Z.clear()},ee=t=>{const e=ue[t];return e&&typeof e=="string"&&e.length>0?e:D[t]?.rpcUrl},S=t=>D[t],te=t=>{const e=ie(t);return e?.displayName||e?.name||`Chain ${t}`},st=t=>{const e=_e(t);if(!e)throw new Error(`Unsupported chain ID: ${t}`);return e},ot=(t,e,r)=>{const a=S(t);return a?.blockExplorer?`${a.blockExplorer}/tx/${e}`:"#"};async function it(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=S(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 fe=t=>{const e=S(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 s=Je({chain:e.viemChain,transport:He(r,{timeout:15e3,retryCount:2,retryDelay:300}),batch:{multicall:{wait:16}}});return Z.set(a,s),s},lt=()=>{const t={};return Object.values(D).forEach(e=>{t[e.id]={name:e.name,moralisName:e.moralisId||"",chain:e.viemChain,rpcUrl:ee(e.id)||e.rpcUrl}}),t},ct=(t,e=[])=>{const r=S(t);if(!r)return[];const a=[];if(![11155111,421614,84532,688689].includes(t)){const s=e.find(l=>l.chainId===t&&l.isNative);s?a.push(s):a.push({address:je,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(s=>s.isNative);return r.supportedTokens.forEach(s=>{if(n&&Y(s.address))return;const l=e.find(i=>i.chainId===t&&j(i.address,s.address));l?a.push(l):a.push({address:s.address,name:s.name,symbol:s.symbol,decimals:s.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:s.logo,isNative:!1,chainId:t})}),a},dt=async(t,e)=>{const r=S(t);if(!r)throw new Error(`Unsupported chain ID: ${t}`);const a=e.toLowerCase();if(Y(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(s=>j(s.address,a));if(n)return n.decimals}try{if(!M(e,{strict:!1}))throw new Error(`Invalid token address: ${e}`);const n=q(e),s=fe(t),l=await Qe(s,{address:n,abi:de,functionName:"decimals"});return Number(l)}catch{throw new Error(`Could not determine decimals for token ${e} on chain ${t}`)}};class v extends Error{constructor(e,r,a={}){super(r),this.code=e,this.context=a,this.name="SpiceflowError",Error.captureStackTrace&&Error.captureStackTrace(this,v)}}function re(t){return t instanceof v}const ut=["user rejected","user denied","user cancelled","rejected the request","action_rejected","4001"];function me(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 he=t=>{if(re(t))return t.code==="WALLET_REJECTED";const e=me(t).toLowerCase();return ut.some(r=>e.includes(r))},pt=(t,e="Something went wrong. Please try again.")=>he(t)?"Transaction was rejected.":re(t)?t.message||e:me(t)||e;function ft(t,e){const r=e.match(/Output amount (\d+) is insufficient after fees (\d+) on chain (\d+)/);if(!r)return e;const[,a,n,s]=r,l=Number(s),i=BigInt(a),m=BigInt(n);let d;for(const f of t.intents){const y=f.chainBatches.find(g=>g.chainId===l);if(y){d=y;break}}const h=d?.tokenTransfers.find(f=>f.from==="escrow"&&j(f.to,t.user)&&!Y(f.token)),c=te(l);if(!h)return`Amount is too small to cover the estimated fee on ${c}.`;const p=De(h.token,l),u=p?.decimals??18,b=p?.symbol??"tokens",o=le(i,u),w=le(m,u);return`Amount is too small to cover the estimated fee on ${c}. Amount: ${o} ${b}. Estimated fee: ${w} ${b}.`}const mt="https://tx-submission-api.spicenet.io",ye=mt;function z(t,e){return typeof e=="bigint"?e.toString():e}function C(t,e){if(!t)return e;const r=t.error;return(typeof t.message=="string"?t.message:"")||(r&&typeof r=="object"&&"message"in r&&typeof r.message=="string"?r.message:"")||(typeof r=="string"?r:"")||e}async function ht(t){try{return await t.json()}catch{return null}}function yt(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 wt{constructor(){this.baseUrl=ye}setBaseUrl(e){this.baseUrl=e}getBaseUrl(){return this.baseUrl}async createAction(e){const r=`${this.baseUrl}/actions`,a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e,z)}),n=await a.json();if(!a.ok||n.success===!1)throw new v("RELAYER_ERROR",C(n,`Relayer API error: ${a.status}`),{httpStatus:a.status,responseBody:JSON.stringify(n),endpoint:"/actions"});return n}async estimateActionFees(e){const r=`${this.baseUrl}/actions/fees/estimate`,a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e,z)}),n=await a.json();if(!a.ok||!n.success||!n.data?.feeEstimate){const s=C(n,`Relayer fee estimate error: ${a.status}`);throw new v("RELAYER_ERROR",ft(e,s),{httpStatus:a.status,responseBody:JSON.stringify(n),endpoint:"/actions/fees/estimate"})}return n.data.feeEstimate}async estimateBatchGas(e){const r=`${this.baseUrl}/actions/gas/estimate`,a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e,z)}),n=await a.json();if(!a.ok||!n.success||!n.data?.gasFee)throw new v("RELAYER_ERROR",C(n,`Relayer gas estimate error: ${a.status}`),{httpStatus:a.status,responseBody:JSON.stringify(n),endpoint:"/actions/gas/estimate"});return{gasFee:BigInt(n.data.gasFee),gasQuoteSource:n.data.gasQuoteSource}}async executeStep(e,r,a,n){const s=`${this.baseUrl}/actions/${e}/intents/${r}/steps/${a}`,l=`/actions/${e}/intents/${r}/steps/${a}`,i=3e4,m=new Promise((c,p)=>setTimeout(()=>p(new v("RELAYER_EXECUTE_ERROR",`Execute step request timed out after ${i/1e3}s`,{actionId:e,intentIndex:r,stepIndex:a,endpoint:l})),i)),d=await Promise.race([fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),m]),h=await d.json();if(!d.ok||h.success===!1)throw new v("RELAYER_EXECUTE_ERROR",C(h,`Execute step error: ${d.status}`),{httpStatus:d.status,responseBody:JSON.stringify(h),endpoint:l,actionId:e});if(h?.status==="error"||h?.status==="reverted"){const c=C(h,""),p=c?`: ${c}`:"";throw new v("RELAYER_EXECUTE_ERROR",`Step ${a} previously ${h.status}${p}`,{httpStatus:d.status,responseBody:JSON.stringify(h),endpoint:l,actionId:e,intentIndex:r,stepIndex:a,stepStatus:h.status})}return{success:!0,transactionHash:h.transactionHash}}async checkStepStatus(e,r){const a=e.split("/"),n=a[0],s=a.length>=2?a[1]:"0",l=`${this.baseUrl}/actions/${n}/intents/${s}/steps/${r}`,i=await fetch(l),m=await i.json();if(!i.ok||m.success===!1)throw new v("RELAYER_STATUS_ERROR",C(m,`Intent step status check failed: ${i.status}`),{httpStatus:i.status,responseBody:JSON.stringify(m),endpoint:l,intentId:e});return{success:!0,data:{status:m.status==="error"?"reverted":m.status,transactionHash:m.txid,error:C(m,"")}}}async createWallet(e,r){const a=`${this.baseUrl}/wallets/${e}`,n=await fetch(a,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),s=await n.json();if(!n.ok||s.success===!1)throw new v("RELAYER_ERROR",C(s,`Create wallet error: ${n.status}`),{httpStatus:n.status,responseBody:JSON.stringify(s),endpoint:`/wallets/${e}`});return s}async getWallet(e){const r=`${this.baseUrl}/wallets/${e}`,a=await fetch(r),n=await a.json();if(!a.ok||n.success===!1)throw new v("RELAYER_ERROR",C(n,`Get wallet error: ${a.status}`),{httpStatus:a.status,responseBody:JSON.stringify(n),endpoint:`/wallets/${e}`});return n}async createWithdrawal(e){const r=`${this.baseUrl}/withdrawals`,a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e,z)}),n=await a.json();if(!a.ok||n.success===!1)throw new v("RELAYER_ERROR",C(n,`Create withdrawal error: ${a.status}`),{httpStatus:a.status,responseBody:JSON.stringify(n),endpoint:"/withdrawals"});return n}async getWithdrawal(e){const r=`${this.baseUrl}/withdrawals/${e}`,a=await fetch(r),n=await a.json();if(!a.ok||n.success===!1)throw new v("RELAYER_ERROR",C(n,`Get withdrawal error: ${a.status}`),{httpStatus:a.status,responseBody:JSON.stringify(n),endpoint:`/withdrawals/${e}`});return n}async getRollupTimestamp(){const e=`${this.baseUrl}/time`,r=await fetch(e),a=await r.json();if(!r.ok||a.success===!1)throw new v("RELAYER_ERROR",C(a,`Get rollup timestamp error: ${r.status}`),{httpStatus:r.status,responseBody:JSON.stringify(a),endpoint:"/time"});return a}}const k=new wt;async function gt(t){const e=`${k.getBaseUrl()}/wallets/${t}/balance`,r=await fetch(e,{cache:"no-store"}),a=await ht(r);if(!r.ok||a?.success===!1)throw new v("RELAYER_ERROR",C(a,`Unable to verify Spice balance: ${r.status}`),{httpStatus:r.status,responseBody:JSON.stringify(a),endpoint:`/wallets/${t}/balance`});return yt(a)}const ae=new Map;async function ne(t,e){const r=t.toLowerCase(),a=ae.get(r);if(a)return a;const n=(async()=>{try{await k.getWallet(t);return}catch{}const{unix_timestamp:s}=await k.getRollupTimestamp(),l=`I am creating a new smart wallet and adding an admin wallet ethereum:0x${t.slice(2).toLowerCase()}. Nonce: ${s}`,i=await e(l),m=typeof i=="string"?i:i.signature;if(!m)throw new Error("Wallet returned no smart wallet signature");await k.createWallet(t,{timestamp:s,signature:m})})();ae.set(r,n);try{await n}finally{ae.delete(r)}}const bt=(t,e)=>{const r=n=>e?e(n):te(n),a=[];return t.forEach((n,s)=>{const l=n.calls&&n.calls.length>0,i=n.tokenTransfers&&n.tokenTransfers.length>0;!l&&!i||a.push({stepId:s,status:s===0?"processing":"pending",chainId:n.chainId,chainName:r(n.chainId),description:"Processing transaction"})}),a},se=t=>{if(!t)return!1;const e=t.connector;if(!e)return!1;if(e.isEmbeddedWallet===!0)return!0;const r=(e.key||e.connectorKey||"").toLowerCase();if(r.includes("embedded")||r.includes("turnkey"))return!0;const a=(e.name||t.walletName||"").toLowerCase();return!!(a.includes("embedded")||a.includes("turnkey"))},G=t=>(t?.connectedWallets||[]).find(e=>se(e))||(se(t?.primaryWallet)?t.primaryWallet:null),Et=t=>(t?.connectedWallets||[]).find(e=>e?.address&&e?.connector&&!se(e))||null,we=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 s=await t.getWalletClient(n);if(s)return s}catch(s){a=s}if(a)throw a}if(typeof t.getEthereumProvider=="function"){const r=await t.getEthereumProvider(),a=e?S(e)?.viemChain:void 0;return Ye({account:t.address,chain:a,transport:qe(r)})}throw new Error("Wallet client not available")},ge=async(t,e)=>{if(!t?.address)throw new Error("Wallet not available");if(typeof t.getEthereumProvider=="function")return t.getEthereumProvider();const r=await we(t,e);return{request:a=>r.request(a)}},vt=(t,e)=>({address:t?.address||e.address,chainId:Number(t?.chainId??e.chainId),contractAddress:t?.contractAddress||t?.delegate||e.contractAddress,nonce:BigInt(t?.nonce??e.nonce),r:t?.r,s:t?.s,yParity:(()=>{if(typeof t?.yParity=="number")return t.yParity;const r=Number(t?.v??27);return Number.isFinite(r)?r>=27?r-27:r:0})()}),be=t=>{const e=t?.wallet;if(e?.address&&e.walletClientType==="privy"&&e.connectorType==="embedded"&&!e.imported)return e.address},$=t=>t?.address?{address:t.address,wallet:t,getWalletClient:e=>we(t,e),getEthereumProvider:e=>ge(t,e)}:null,Ee=()=>{const t=P(R),{address:e,connector:r}=ce();let a=null,n=null;try{a=Q(),{user:n}=X()}catch{a=null,n=null}let s=null;try{s=V()}catch{s=null}const l=a?.wallets||[],i=K(l),m=i?.address?.toLowerCase(),d=l.find(B=>B.connectorType!=="embedded"&&B.address?.toLowerCase()!==m),h=G(s),c=Et(s),p=h?.address?.toLowerCase(),u=e?.toLowerCase(),b=e&&r&&!(u&&(m&&u===m||p&&u===p))?{address:e,connector:r,getEthereumProvider:()=>r.getProvider()}:null,o=t?.provider,w=$(i)||$(h),f=$(b)||$(d)||$(c)||null,y=o==="dynamic"?$(h):o==="privy"?$(i):w,g=o==="dynamic"?$(b)||$(c):o==="privy"?$(b)||$(d):f,E=o==="dynamic"?y?.address:o==="privy"?y?.address||be(n):w?.address||be(n);return{embeddedWallet:y,externalWallet:g,embeddedAddress:E,externalAddress:g?.address}},xt=()=>{const[t,e]=_(!1);let r=null,a=null;try{r=V()}catch(u){a=u instanceof Error?u.message:String(u)}if(N(()=>{e(!0)},[]),a)return{isReady:!1,isAuthenticated:!1,isConnected:!1,provider:"dynamic",actions:{signAuthorization:async()=>{throw new Error("Dynamic context not available")},signMessage:async()=>{throw new Error("Dynamic context not available")},getEthereumProvider:async()=>{throw new Error("Dynamic context not available")}}};const{user:n,primaryWallet:s,connectedWallets:l}=r||{},i=G({connectedWallets:l,primaryWallet:s})||s,m=!!n,d=i?.address,h={isReady:t&&!!r,isAuthenticated:m,isConnected:m&&!!d,address:d,provider:"dynamic"},c=async u=>{if(!i)throw new Error("Dynamic embedded wallet not available");const{isEthereumWallet:b}=await import("@dynamic-labs/ethereum");if(!b(i))throw new Error("Embedded wallet is not an Ethereum wallet");const o=await i.getWalletClient();if(!o)throw new Error("Dynamic wallet client not available");return{signature:await o.signMessage({message:u,account:i.address})}},p=async()=>{if(!d)throw new Error("Dynamic embedded wallet not available");await ne(d,c)};return{...h,actions:{signAuthorization:async u=>{if(!i)throw new Error("Dynamic embedded wallet not available");await p();const{isEthereumWallet:b}=await import("@dynamic-labs/ethereum");if(!b(i))throw new Error("Embedded wallet is not an Ethereum wallet");const o=i.connector,w={address:i.address,chainId:u.chainId,contractAddress:u.contractAddress,nonce:u.nonce},f={address:u.contractAddress,chainId:u.chainId,nonce:u.nonce},y=typeof o?.getWaasWalletClient=="function"?await o.getWaasWalletClient():null;if(y&&typeof y.signRawMessage=="function"){const{hashAuthorization:g}=await import("viem/experimental"),{parseSignature:E}=await import("viem"),B={address:u.contractAddress,chainId:u.chainId,nonce:u.nonce},O=o.getSignedSessionId,H=typeof O=="function"?await O.call(o):void 0,F=o.getAuthToken,L=typeof F=="function"?F.call(o):void 0,x=await y.signRawMessage({accountAddress:i.address,authToken:L,context:{eip7702Auth:B},message:g(B).slice(2),signedSessionId:H}),I=E(x);return{address:w.contractAddress,chainId:w.chainId,contractAddress:w.contractAddress,nonce:BigInt(w.nonce),r:I.r,s:I.s,yParity:Number(I.yParity)}}if(typeof o?.signAuthorization=="function"){typeof o.switchNetwork=="function"&&await o.switchNetwork({networkChainId:u.chainId});const g=await o.signAuthorization(f);return vt(g,w)}throw new Error("Dynamic embedded wallet does not support EIP-7702 authorization. Ensure @dynamic-labs packages are v4.15+.")},signMessage:async u=>{if(!(typeof u=="object"&&"raw"in u))return c(u);if(await p(),!i)throw new Error("Dynamic embedded wallet not available");const b=await i.getWalletClient();if(!b)throw new Error("Dynamic wallet client not available");return{signature:await b.signMessage({message:{raw:u.raw},account:i.address})}},getEthereumProvider:async()=>{if(!i)throw new Error("Dynamic embedded wallet not available");const{isEthereumWallet:u}=await import("@dynamic-labs/ethereum");if(!u(i))throw new Error("Embedded wallet is not an Ethereum wallet");return ge(i)}}}},Ct=t=>{const e=t?.wallet;if(e?.address&&e.walletClientType==="privy"&&e.connectorType==="embedded"&&!e.imported)return e.address},ve=()=>{const t=P(R),e=t?.mode||"7702";let r=null,a=null;try{r=Q(),{user:a}=X()}catch{r=null}const n=K(r?.wallets||[])?.address,s=Ct(a);let l=null;try{l=V()}catch{l=null}const i=(G(l)||l?.primaryWallet)?.address;if(!(!t||e!=="7702"))return t.provider==="privy"?n??s:t.provider==="dynamic"?i:n??s??i},Bt=()=>{const t=P(R)?.mode,{isConnected:e,address:r}=ce();let a=null,n=null,s=null,l=null,i=null;try{a=X(),n=Ke(),s=Ve(),l=Q()}catch(f){i=f instanceof Error?f.message:String(f)}if(i)return t==="ondemand"&&e&&r?{isReady:!0,isAuthenticated:!0,isConnected:!0,address:r,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:m=!1,authenticated:d=!1}=a||{},h=ve(),c=K(l?.wallets||[]),p=h||c?.address,u=!!p&&!!c,b={isReady:t==="ondemand"?!0:m,isAuthenticated:t==="ondemand"?!0:d||u,isConnected:t==="ondemand"?e&&!!r||m&&(d||u)&&u:m&&u,address:t==="ondemand"&&!h&&e?r:p,provider:"privy"},o=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");const y=await c.getEthereumProvider(),{createWalletClient:g,custom:E}=await import("viem");return{signature:await g({account:c.address,transport:E(y)}).signMessage({account:c.address,message:f})}},w=async()=>{if(!p)throw new Error("Embedded wallet not available for smart wallet setup");await ne(p,o)};return{...b,actions:{signAuthorization:async f=>{if(!n)throw new Error("Privy sign authorization not available");try{await w();const y=await n.signAuthorization({contractAddress:f.contractAddress,chainId:f.chainId,nonce:f.nonce},{address:p});return delete y.v,y}catch(y){const g=typeof y?.message=="string"?y.message:String(y?.message??y??"");throw g.includes("not configured")||g.includes("chain")?new Error(`Chain ${f.chainId} is not configured in PrivyProvider. Add this chain to your Privy dashboard or supportedChainIds.`):y}},signMessage:async f=>{if(typeof f=="object"&&"raw"in f){if(await w(),!c)throw new Error("Embedded wallet not available for raw signing");const y=await c.getEthereumProvider(),{createWalletClient:g,custom:E}=await import("viem");return{signature:await g({account:c.address,transport:E(y)}).signMessage({account:c.address,message:f})}}return o(f)},getEthereumProvider:async()=>{if(!c)throw new Error("Embedded wallet not available");return c.getEthereumProvider()}}}},xe=()=>{const t=P(R)?.provider,e=Bt(),r=xt();return t==="privy"?e:t==="dynamic"?r:{isReady:!1,isAuthenticated:!1,isConnected:!1,provider:null,actions:{signAuthorization:async()=>{throw new Error("No wallet provider available")},signMessage:async()=>{throw new Error("No wallet provider available")},getEthereumProvider:async()=>{throw new Error("No wallet provider available")}}}},$t="https://portal-api.spicenet.io/api/v1",Ce=t=>t.replace(/\/+$/,"");async function kt(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)throw new Error(`Failed to check whitelist: ${n.status}`);return await n.json()}async function St(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"});return a.ok?(await a.json()).portalWalletAddress?.toLowerCase()??null:null}async function Rt(t,e){const r=new URLSearchParams({portalAddress:e,campaignId:"spicenet-portal",campaignGroup:"1"}),a=await fetch(`${t}/portal/mainnet/linked-wallets?${r.toString()}`,{cache:"no-store"});return a.ok?(await a.json())?.members?.map(n=>n.walletAddress.toLowerCase())??[]:[]}async function It(t,e,r){const a=await fetch(`${t}/portal/mainnet/whitelist/wallet`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({campaignId:r.campaignId,campaignGroup:r.campaignGroup,partnerId:r.partnerId,walletAddress:e})});if(!a.ok){const n=await a.text().catch(()=>"");throw new Error(`Failed to whitelist wallet: ${a.status} ${n}`.trim())}}function Be({walletAddress:t,campaignId:e,campaignGroup:r,partnerId:a,apiBaseUrl:n=$t,enabled:s=!0,staleTime:l=5*60*1e3,refetchInterval:i=!1}={}){const{isAuthenticated:m,isConnected:d}=xe(),{externalAddress:h}=Ee(),c=t??h,p=typeof c=="string"?c.toLowerCase():void 0,u=s&&m&&d&&!!h&&!!p&&M(p)&&!!e&&!!r&&!!a,b=U(()=>["partner-whitelist","check",p,e,r,a,Ce(n)],[p,e,r,a,n]),o=Xe({queryKey:b,enabled:u,staleTime:l,refetchInterval:i,queryFn:async()=>{if(!p||!M(p))throw new Error("A valid wallet address is required");if(!e||!r||!a)throw new Error("campaignId, campaignGroup, and partnerId are required");const w=Ce(n),f={campaignId:e,campaignGroup:r,partnerId:a},y=await kt(w,p,f);if(y.isWhitelisted)return y;const g=await St(w,p);if(!g||!(await Rt(w,g)).includes(p))return y;try{await It(w,p,f)}catch(E){console.warn("[useIsUserWhitelisted] auto-whitelist failed:",E)}return{...y,isWhitelisted:!0,isLinkedWallet:!0}}});return{isWhitelisted:o.data?.isWhitelisted??!1,whitelistCheck:o.data,checkedWalletAddress:p,externalWalletAddress:h,isExternalWalletConnected:!!h,isWhitelistCheckEnabled:u,...o}}const $e="spiceflow-mode",ke=()=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem($e);return t==="7702"?"7702":t==="non7702"?"ondemand":t==="embedded"?"7702":t==="external"?"ondemand":null}catch{return null}},At=t=>{if(!(typeof window>"u"))try{window.localStorage.setItem($e,t==="7702"?"7702":"non7702")}catch{}},Tt=()=>ke()!==null,Se=oe(null),Wt=["__spicenet_whitelist_blocked__"],R=oe(null),Pt=({children:t,value:e,whitelist:r})=>{const a=r!==!1&&!!r&&r.enabled!==!1,n=Be(a?r:{enabled:!1}),s=a&&n.isWhitelistCheckEnabled&&n.isSuccess,l=a&&(!s||!n.isWhitelisted),i=U(()=>({...e,allowedTokens:l?Wt:e.allowedTokens,mode:l?"ondemand":e.mode,isUserWhitelisted:s?n.isWhitelisted:null,isWhitelistChecking:a&&n.isWhitelistCheckEnabled&&(n.isLoading||n.isFetching),isWhitelistConfigured:a,isWhitelistGateActive:l,whitelistCheck:n.whitelistCheck}),[e,a,l,s,n.isWhitelisted,n.isWhitelistCheckEnabled,n.isLoading,n.isFetching,n.whitelistCheck]);return A(R.Provider,{value:i,children:t})},Nt=({children:t,provider:e,supportedChainIds:r,allowedTokens:a,network:n="testnet",mode:s,skipFlow:l=[],nativeChainId:i,appName:m="Spicenet",apiUrl:d,theme:h,rpcOverrides:c,whitelist:p})=>{N(()=>{if(!d)return;const E=k.getBaseUrl();return k.setBaseUrl(d),()=>k.setBaseUrl(E)},[d]),N(()=>(pe(c),()=>pe(void 0)),[c]);const u=U(()=>ze(n),[n]),b=r??u,o=h??null,[w,f]=_(()=>s??ke()??"7702");N(()=>{s&&f(s)},[s]);const y=Oe(E=>{if(s){f(s);return}f(E),At(E)},[s]),g=U(()=>({provider:e,supportedChainIds:b,allowedTokens:a,skipFlow:l,mode:w,setMode:y,network:n,nativeChainId:i,appName:m,apiUrl:d,rpcOverrides:c,isUserWhitelisted:null,isWhitelistChecking:!1,isWhitelistConfigured:!1,isWhitelistGateActive:!1}),[e,b,a,l,w,y,n,i,m,d,c]);return A(Se.Provider,{value:o,children:A(R.Provider,{value:g,children:A(Pt,{value:g,whitelist:p,children:t})})})},Ut={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:'"Helvetica Neue", sans-serif',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"}},Mt={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"},Ot={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"},Re=(t="light")=>({mode:t,...Ut,colors:t==="light"?Mt:Ot});function J(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))),s=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")}${s.toString(16).padStart(2,"0")}`}function Ft(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 Lt(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 Ie(t,e){const r=e?{...t,...e}:t,a=r.dark??!1,n=r.primaryColor,s=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:s,shellBorder:J(s,a?.35:.085),shellInnerBorder:J(s,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 _t='"IBM Plex Mono", monospace';function Ae(t,e){const r=P(Se)??void 0;return U(()=>{const a=r??{primaryColor:"#EA4B4B"},n={...t?.primaryColor?{primaryColor:t.primaryColor}:{},...t?.fontFamily?{fontFamily:t.fontFamily}:{},...e!==void 0?{dark:e}:{}},s=Ie(a,n),{dark:l,primaryColor:i,appName:m}=s,d=Re(l?"dark":"light"),h={...d,colors:{...d.colors,primary:i,primaryHover:`${i}dd`},typography:{...d.typography,fontFamily:s.fontFamily}},c={shell:s.shell,shellBorder:s.shellBorder,shellInnerBorder:s.shellInnerBorder,cardBg:s.card,inputBg:s.input,hoverBg:s.hover,textPrimary:s.text,textSecondary:s.textMuted,inputText:s.inputText,inputPlaceholder:s.inputPlaceholder,cardBorder:s.border,inputBorder:s.inputBorder,buttonBorder:s.buttonBorder,successBg:s.successBg,successBorder:s.successBorder,successText:s.successText,warningBg:s.warningBg,warningBorder:s.warningBorder,warningText:s.warningText,errorBg:s.errorBg,errorBorder:s.errorBorder,errorText:s.errorText,infoBg:s.infoBg,infoBorder:s.infoBorder,infoText:s.infoText},p=t?.inputVariant?t.inputVariant==="dark":l;return{brand:r,theme:h,dark:l,appName:m,primaryColor:i,dk:c,palette:c,fontFamily:s.fontFamily,monoFont:_t,inputDark:p,cardBg:p?c.cardBg:"#E9E9E9",cardBorder:p?c.cardBorder:"#C6C6C6",textPrimary:c.textPrimary,textSecondary:c.textSecondary,subtitleText:p?c.textSecondary:"#979AA0"}},[r,t,e])}const Te="spiceflow-spinner-keyframes";function jt(){if(typeof document>"u"||document.getElementById(Te))return;const t=document.createElement("style");t.id=Te,t.textContent="@keyframes spiceflow-spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}",document.head.appendChild(t)}const We=({size:t=16,borderWidth:e=2,color:r="currentColor",style:a})=>{const n=Fe(!1);return N(()=>{n.current||(jt(),n.current=!0)},[]),A("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}})},Dt=({variant:t="primary",size:e="md",loading:r=!1,fullWidth:a=!1,disabled:n,children:s,className:l="",style:i,theme:m,styles:d,dark:h,...c})=>{const{theme:p,dark:u,palette:b}=Ae(d,h),o=m||p,w=h??u,[f,y]=_(!1),[g,E]=_(!1),B=w?b.shell:"white",O=()=>{switch(t){case"primary":return{backgroundColor:d?.button?.backgroundColor||o.colors.primary,color:d?.button?.color||"#ffffff",border:`1px solid ${d?.button?.backgroundColor||o.colors.primary}`};case"secondary":return{backgroundColor:o.colors.secondary,color:o.colors.text,border:`1px solid ${o.colors.border}`};case"success":return{backgroundColor:o.colors.success,color:o.colors.text,border:`1px solid ${o.colors.success}`};case"error":return{backgroundColor:o.colors.error,color:o.colors.text,border:`1px solid ${o.colors.error}`};case"ghost":return{backgroundColor:"transparent",color:o.colors.textSecondary,border:`1px solid ${o.colors.border}`};case"outline":{const x=d?.button?.backgroundColor||o.colors.primary,I=d?.button?.color||(w?"#ffffff":"#0e0d0b"),T=d?.button?.borderColor||(w?`${o.colors.primary}88`:"#0e0d0b"),W=n||r,Pe=w?"1px":"1.5px",Ne=d?.button?.disabledBackgroundColor||`${x}88`,Ue=d?.button?.disabledColor||I;return{height:"56px",backgroundColor:W?Ne:g?`${x}cc`:f?`${x}ee`:x,color:W?Ue:I,border:`${Pe} solid ${T}`,borderRadius:d?.button?.borderRadius||"12px",fontSize:"22px",fontWeight:500,fontFamily:'"IBM Plex Mono", monospace',opacity:W?.78:1,transform:W?"none":g?"scale(0.98)":f?"translateY(-2px)":"none",boxShadow:W?`3px 3px 0px ${B}, 4px 4px 0px ${T}`:g?`2px 2px 0px ${T}`:f?`5px 5px 0px ${B}, 6px 6px 0px ${T}`:`3px 3px 0px ${B}, 4px 4px 0px ${T}`,transition:"transform 150ms ease, box-shadow 150ms ease, background-color 150ms ease, border-color 150ms ease, color 150ms ease"}}default:return{}}},H=()=>{if(t==="outline")return{};switch(e){case"sm":return{padding:`${o.spacing.sm} ${o.spacing.md}`,fontSize:o.typography.fontSize.sm};case"md":return{padding:`${o.spacing.md} ${o.spacing.lg}`,fontSize:o.typography.fontSize.base};case"lg":return{padding:`${o.spacing.lg} ${o.spacing.xl}`,fontSize:o.typography.fontSize.lg};default:return{}}},F={borderRadius:d?.button?.borderRadius||o.borderRadius.md,fontWeight:d?.button?.fontWeight||o.typography.fontWeight.medium,fontFamily:d?.button?.fontFamily||o.typography.fontFamily,fontSize:d?.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:o.spacing.sm,...O(),...H(),...d?.button?.fontSize&&{fontSize:d.button.fontSize}},L=n||r;return Me("button",{type:c.type??"button","data-spiceflow-focus":!0,"aria-busy":r||void 0,"aria-disabled":L||void 0,style:{...F,...i},className:l,disabled:L,onMouseEnter:x=>{y(!0),c.onMouseEnter?.(x)},onMouseLeave:x=>{y(!1),E(!1),c.onMouseLeave?.(x)},onMouseDown:x=>{E(!0),c.onMouseDown?.(x)},onMouseUp:x=>{E(!1),c.onMouseUp?.(x)},...c,children:[r&&A(We,{size:16}),s]})};export{Nt as A,Dt as B,nt as C,Be as D,Ie as E,Ft as F,Lt as G,ye as R,We as S,de as U,lt as a,S as b,Re as c,fe as d,te as e,R as f,G as g,ot as h,he as i,j,it as k,st as l,dt as m,bt as n,xe as o,Ee as p,ve as q,k as r,pt as s,ct as t,Ae as u,v,gt as w,Tt as x,ne as y,re as z};