@spicenet-io/spiceflow-ui 3.3.4 → 3.3.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{Button-BSdscf9Q.js → Button-BXgazUZN.js} +1 -1
- package/dist/{Button-DxtXs-vS.js → Button-d9wfO_xs.js} +1 -1
- package/dist/auth-dynamic.cjs.js +1 -1
- package/dist/auth-dynamic.js +1 -1
- package/dist/auth-privy.cjs.js +1 -1
- package/dist/auth-privy.js +1 -1
- package/dist/index.cjs.js +10 -10
- package/dist/index.js +10 -10
- package/dist/{providerWallet-BYZV-ffI.js → providerWallet-CIbQEcIP.js} +1 -1
- package/dist/{providerWallet-SDZquktT.js → providerWallet-CVHyIqiI.js} +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as v,jsxs as le}from"react/jsx-runtime";import{createContext as j,useEffect as N,useState as O,useCallback as ue,useContext as fe,useMemo as pe,useRef as me}from"react";import{getChainMeta as D,getTokensForChain as ge,getDelegateContract as he,ZERO_ADDRESS as ye,isNativeToken as _,getTokenByAddress as be,getChainIdsByNetwork as we}from"@spicenet-io/spiceflow-core";import{defineChain as xe,createPublicClient as Be,http as Ee,isAddress as $e,getAddress as Se,formatUnits as J}from"viem";import{readContract as ve}from"viem/actions";class u extends Error{constructor(e,a,t={}){super(a),this.code=e,this.context=t,this.name="SpiceflowError",Error.captureStackTrace&&Error.captureStackTrace(this,u)}}function Re(r){return r instanceof u}const W=[{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"}],Ce="0xcA11bde05977b3631167028862bE2a173976CA11",Te={4114:"0x860aFc632a6D625B95d8B96f39ECC48E988c6962"},ke=new Set([5115]);function Ie(r){const e=Te[r.id]??(ke.has(r.id)?void 0:Ce);return xe({id:r.id,name:r.name,nativeCurrency:r.nativeCurrency,rpcUrls:{default:{http:[r.rpcUrl]}},blockExplorers:{default:{name:r.displayName,url:r.blockExplorer}},testnet:r.network==="testnet",...e?{contracts:{multicall3:{address:e}}}:{}})}const Ue=[1,8453,42161,4114,11155111,421614,84532,5115,123420001114,688688,688689],R=Object.fromEntries(Ue.map(r=>D(r)).filter(r=>r!=null).map(r=>[r.id,{...r,viemChain:Ie(r),supportedTokens:ge(r.id)}])),Ne=R;let z={};const A=new Map,Y=r=>{z={...r||{}},A.clear()},M=r=>{const e=z[r];return e&&typeof e=="string"&&e.length>0?e:R[r]?.rpcUrl},$=r=>R[r],C=r=>{const e=D(r);return e?.displayName||e?.name||`Chain ${r}`},Oe=r=>{const e=he(r);if(!e)throw new Error(`Unsupported chain ID: ${r}`);return e},_e=(r,e,a)=>{const t=$(r);return t?.blockExplorer?`${t.blockExplorer}/tx/${e}`:"#"},H=r=>{const e=$(r);if(!e)throw new Error(`Unsupported chain ID: ${r}`);const a=M(r);if(!a)throw new Error(`No RPC URL configured for chain ID: ${r}`);const t=`${r}:${a}`,o=A.get(t);if(o)return o;const s=Be({chain:e.viemChain,transport:Ee(a,{timeout:15e3,retryCount:2,retryDelay:300}),batch:{multicall:{wait:16}}});return A.set(t,s),s},Ae=()=>{const r={};return Object.values(R).forEach(e=>{r[e.id]={name:e.name,moralisName:e.moralisId||"",chain:e.viemChain,rpcUrl:M(e.id)||e.rpcUrl}}),r},Me=(r,e=[])=>{const a=$(r);if(!a)return[];const t=[];if(![11155111,421614,84532,688689].includes(r)){const s=e.find(n=>n.chainId===r&&n.isNative);s?t.push(s):t.push({address:ye,name:a.nativeCurrency.name,symbol:a.nativeCurrency.symbol,decimals:a.nativeCurrency.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:void 0,isNative:!0,chainId:r})}if(!a.supportedTokens)return t;const o=t.some(s=>s.isNative);return a.supportedTokens.forEach(s=>{if(o&&_(s.address))return;const n=e.find(l=>l.chainId===r&&l.address.toLowerCase()===s.address.toLowerCase());n?t.push(n):t.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:r})}),t},Fe=async(r,e)=>{const a=$(r);if(!a)throw new Error(`Unsupported chain ID: ${r}`);const t=e.toLowerCase();if(_(t)){if(!a.nativeCurrency?.decimals)throw new Error(`Native currency decimals not configured for chain ${r}`);return a.nativeCurrency.decimals}if(a.supportedTokens){const o=a.supportedTokens.find(s=>s.address.toLowerCase()===t);if(o)return o.decimals}try{if(!$e(e,{strict:!1}))throw new Error(`Invalid token address: ${e}`);const o=Se(e),s=H(r),n=await ve(s,{address:o,abi:W,functionName:"decimals"});return Number(n)}catch{throw new Error(`Could not determine decimals for token ${e} on chain ${r}`)}},G=typeof process<"u"&&process.env?.NEXT_PUBLIC_RELAYER_API_URL||"https://tx-api-devserver.spicenet.io",X="__SPICEFLOW_RELAYER_API_URL__";function Pe(r,e){const a=e.match(/Output amount (\d+) is insufficient after fees (\d+) on chain (\d+)/);if(!a)return e;const[,t,o,s]=a,n=Number(s),l=BigInt(t),c=BigInt(o);let d;for(const f of r.intents){const w=f.chainBatches.find(S=>S.chainId===n);if(w){d=w;break}}const m=d?.tokenTransfers.find(f=>f.from==="escrow"&&f.to.toLowerCase()===r.user.toLowerCase()&&!_(f.token));if(!m)return`Amount is too small to cover the estimated fee on ${C(n)}.`;const p=be(m.token,n),y=p?.decimals??18,b=p?.symbol??"tokens",x=J(l,y),i=J(c,y);return`Amount is too small to cover the estimated fee on ${C(n)}. Amount: ${x} ${b}. Estimated fee: ${i} ${b}.`}function Le(r){return!1}function je(){if(typeof globalThis>"u")return;const r=globalThis[X];return typeof r=="string"&&r.length>0?r:void 0}class De{constructor(){this.baseUrl=G}setBaseUrl(e){this.baseUrl=e,typeof globalThis<"u"&&(globalThis[X]=e)}getBaseUrl(){return this.getEffectiveBaseUrl()}getEffectiveBaseUrl(){return je()||this.baseUrl}async createAction(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/actions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e,(o,s)=>typeof s=="bigint"?s.toString():s)}),t=await a.json();if(!a.ok||t.success===!1)throw new u("RELAYER_ERROR",t.error?.message||`Relayer API error: ${a.status}`,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:"/actions"});return t}async estimateActionFees(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/actions/fees/estimate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e,(o,s)=>typeof s=="bigint"?s.toString():s)}),t=await a.json();if(!a.ok||!t.success||!t.data?.feeEstimate){const o=t.error?.message||`Relayer fee estimate error: ${a.status}`,s=Pe(e,o);throw new u("RELAYER_ERROR",s,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:"/actions/fees/estimate"})}return t.data.feeEstimate}async estimateBatchGas(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/actions/gas/estimate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e,(o,s)=>typeof s=="bigint"?s.toString():s)}),t=await a.json();if(!a.ok||!t.success||!t.data?.gasFee){const o=t.error?.message||`Relayer gas estimate error: ${a.status}`;throw new u("RELAYER_ERROR",o,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:"/actions/gas/estimate"})}return{gasFee:BigInt(t.data.gasFee),gasQuoteSource:t.data.gasQuoteSource}}async executeStep(e,a,t,o){const s=`${this.getEffectiveBaseUrl()}/actions/${e}/intents/${a}/steps/${t}`,n=fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});let l;try{l=await Promise.race([n,new Promise((d,m)=>setTimeout(()=>m(new u("RELAYER_EXECUTE_ERROR",`Execute step request timed out after ${1e4/1e3}s`,{actionId:e,intentIndex:a,stepIndex:t,endpoint:`/actions/${e}/intents/${a}/steps/${t}`})),1e4))])}catch(d){throw d}const c=await l.json();if(!l.ok||c.success===!1)throw new u("RELAYER_EXECUTE_ERROR",c.error?.message||`Execute step error: ${l.status}`,{httpStatus:l.status,responseBody:JSON.stringify(c),endpoint:`/actions/${e}/intents/${a}/steps/${t}`,actionId:e});if(c?.status==="error"||c?.status==="reverted")throw new u("RELAYER_EXECUTE_ERROR",`Step ${t} previously ${c.status}${c?.error?`: ${c.error}`:""}`,{httpStatus:l.status,responseBody:JSON.stringify(c),endpoint:`/actions/${e}/intents/${a}/steps/${t}`,actionId:e,intentIndex:a,stepIndex:t,stepStatus:c.status});return{success:!0,transactionHash:c.transactionHash}}async checkStepStatus(e,a){const t=e.split("/");let o="";if(t.length>=2){const l=t[0],c=t[1];o=`${this.getEffectiveBaseUrl()}/actions/${l}/intents/${c}/steps/${a}`}else o=`${this.getEffectiveBaseUrl()}/actions/${e}/intents/0/steps/${a}`;const s=await fetch(o),n=await s.json();if(!s.ok||n.success===!1)throw new u("RELAYER_STATUS_ERROR",n.error?.message||`Intent step status check failed: ${s.status}`,{httpStatus:s.status,responseBody:JSON.stringify(n),endpoint:o,intentId:e});return{success:!0,data:{status:n.status==="error"?"reverted":n.status,transactionHash:n.txid}}}async createWallet(e,a){const t=await fetch(`${this.getEffectiveBaseUrl()}/wallets/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),o=await t.json();if(!t.ok||o.success===!1)throw new u("RELAYER_ERROR",o.error?.message||`Create wallet error: ${t.status}`,{httpStatus:t.status,responseBody:JSON.stringify(o),endpoint:`/wallets/${e}`});return o}async getWallet(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/wallets/${e}`),t=await a.json();if(!a.ok||t.success===!1)throw new u("RELAYER_ERROR",t.error?.message||`Get wallet error: ${a.status}`,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:`/wallets/${e}`});return t}async createWithdrawal(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/withdrawals`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e,(o,s)=>typeof s=="bigint"?s.toString():s)}),t=await a.json();if(!a.ok||t.success===!1)throw new u("RELAYER_ERROR",t.error?.message||`Create withdrawal error: ${a.status}`,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:"/withdrawals"});return t}async getWithdrawal(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/withdrawals/${e}`),t=await a.json();if(!a.ok||t.success===!1)throw new u("RELAYER_ERROR",t.error?.message||`Get withdrawal error: ${a.status}`,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:`/withdrawals/${e}`});return t}async getRollupTimestamp(){const e=await fetch(`${this.getEffectiveBaseUrl()}/time`),a=await e.json();if(!e.ok||a.success===!1)throw new u("RELAYER_ERROR",a.error?.message||`Get rollup timestamp error: ${e.status}`,{httpStatus:e.status,responseBody:JSON.stringify(a),endpoint:"/time"});return a}}const h=new De,F=new Map;async function Je(r,e){const a=r.toLowerCase(),t=F.get(a);if(t)return t;const o=(async()=>{try{await h.getWallet(r);return}catch{}const{unix_timestamp:s}=await h.getRollupTimestamp(),n=`I am creating a new smart wallet and adding an admin wallet ethereum:0x${r.slice(2).toLowerCase()}. Nonce: ${s}`,l=await e(n),c=typeof l=="string"?l:l.signature;if(!c)throw new Error("Wallet returned no smart wallet signature");await h.createWallet(r,{timestamp:s,signature:c})})();F.set(a,o);try{await o}finally{F.delete(a)}}const We=(r,e)=>{const a=o=>e?e(o):C(o),t=[];return r.forEach((o,s)=>{const n=o.calls&&o.calls.length>0,l=o.tokenTransfers&&o.tokenTransfers.length>0;if(n||l){const c={stepId:s,status:s===0?"processing":"pending",chainId:o.chainId,chainName:a(o.chainId),description:"Processing transaction"};t.push(c)}}),t},q="spiceflow-mode",Q=()=>{if(typeof window>"u")return null;try{const r=window.localStorage.getItem(q);return r==="embedded"?"7702":r==="external"?"ondemand":null}catch{return null}},ze=r=>{if(!(typeof window>"u"))try{window.localStorage.setItem(q,r==="7702"?"embedded":"external")}catch{}},Ye=()=>Q()!==null,Z=j(null),K=j(null),He=({children:r,provider:e,supportedChainIds:a,network:t="testnet",mode:o="7702",skipFlow:s=[],nativeChainId:n,appName:l="Spicenet",apiUrl:c,theme:d,rpcOverrides:m})=>{N(()=>{if(!c)return;const f=h.getBaseUrl();return h.setBaseUrl(c),()=>h.setBaseUrl(f)},[c]),N(()=>(Y(m),()=>Y(void 0)),[m]);const p=a??we(t),y=d??null,[b,x]=O(()=>Q()??o),i=ue(f=>{x(f),ze(f)},[]);return v(Z.Provider,{value:y,children:v(K.Provider,{value:{provider:e,supportedChainIds:p,skipFlow:s,mode:b,setMode:i,network:t,nativeChainId:n,appName:l,apiUrl:c,rpcOverrides:m},children:r})})},Ge={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"}},Xe={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"},qe={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"},V=(r="light")=>({mode:r,...Ge,colors:r==="light"?Xe:qe});function T(r,e){const a=r.replace("#",""),t=Math.max(0,Math.round(parseInt(a.substring(0,2),16)*(1-e))),o=Math.max(0,Math.round(parseInt(a.substring(2,4),16)*(1-e))),s=Math.max(0,Math.round(parseInt(a.substring(4,6),16)*(1-e)));return`#${t.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`}function Qe(r,e){return{shell:e?.shell??"#141414",shellBorder:e?.shellBorder??T(e?.shell??"#141414",.35),shellInnerBorder:e?.shellInnerBorder??T(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 Ze(r){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 ee(r,e){const a=e?{...r,...e}:r,t=a.dark??!1,o=a.primaryColor,s=a.shell??(t?"#141414":"#ffffff");return{primaryColor:o,dark:t,fontFamily:a.fontFamily??'"Helvetica Neue", sans-serif',appName:a.appName??"Spicenet",logo:a.logo,borderRadius:a.borderRadius??"8px",shell:s,shellBorder:T(s,t?.35:.085),shellInnerBorder:T(s,t?.55:.165),card:a.card??(t?"#1e1e1e":"#f9fafb"),input:t?"#171717":"#ffffff",hover:t?"#2a2a2a":"#f3f4f6",text:a.text??(t?"#ffffff":"#111827"),textMuted:a.textMuted??(t?"#888888":"#6b7280"),inputText:t?"#e0e0e0":"#111827",inputPlaceholder:t?"#555555":"#9ca3af",border:a.border??(t?"rgba(255,255,255,0.08)":"#e5e7eb"),inputBorder:t?"rgba(255,255,255,0.10)":"#d1d5db",buttonBorder:t?"rgba(255,255,255,0.12)":"#0e0d0b",successBg:t?"#0a1f18":"#d1fae5",successBorder:t?"#1a4a3a":"#6ee7b7",successText:t?"#6ee7b7":"#065f46",warningBg:t?"#1f1a0d":"#fef3c7",warningBorder:t?"#4a3820":"#fde68a",warningText:t?"#fbbf24":"#92400e",errorBg:t?"#1f0d0d":"#fef2f2",errorBorder:t?"#4a2020":"#fecaca",errorText:t?"#f87171":"#dc2626",infoBg:t?"#0d1325":"#dbeafe",infoBorder:t?"#2a3a5a":"#93c5fd",infoText:t?"#60a5fa":"#1e40af"}}function te(r,e){const a=fe(Z)??void 0;return pe(()=>{const t=a??{primaryColor:"#EA4B4B"},o={...r?.primaryColor?{primaryColor:r.primaryColor}:{},...r?.fontFamily?{fontFamily:r.fontFamily}:{},...e!==void 0?{dark:e}:{}},s=ee(t,o),{dark:n,primaryColor:l,appName:c}=s,d=V(n?"dark":"light"),m={...d,colors:{...d.colors,primary:l,primaryHover:`${l}dd`},typography:{...d.typography,fontFamily:s.fontFamily}},p={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};return{brand:a,theme:m,dark:n,appName:c,primaryColor:l,dk:p,palette:p}},[a,r,e])}const re="spiceflow-spinner-keyframes";function Ke(){if(typeof document>"u"||document.getElementById(re))return;const r=document.createElement("style");r.id=re,r.textContent="@keyframes spiceflow-spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}",document.head.appendChild(r)}const ae=({size:r=16,borderWidth:e=2,color:a="currentColor",style:t})=>{const o=me(!1);return N(()=>{o.current||(Ke(),o.current=!0)},[]),v("div",{role:"status","aria-label":"Loading",style:{width:`${r}px`,height:`${r}px`,border:`${e}px solid ${a}`,borderTop:`${e}px solid transparent`,borderRadius:"50%",animation:"spiceflow-spin 1s linear infinite",flexShrink:0,...t}})},Ve=({variant:r="primary",size:e="md",loading:a=!1,fullWidth:t=!1,disabled:o,children:s,className:n="",style:l,theme:c,styles:d,dark:m,...p})=>{const{theme:y,dark:b,palette:x}=te(d,m),i=c||y,f=m??b,[w,S]=O(!1),[k,I]=O(!1),U=f?x.shell:"white",se=()=>{switch(r){case"primary":return{backgroundColor:d?.button?.backgroundColor||i.colors.primary,color:d?.button?.color||"#ffffff",border:`1px solid ${d?.button?.backgroundColor||i.colors.primary}`};case"secondary":return{backgroundColor:i.colors.secondary,color:i.colors.text,border:`1px solid ${i.colors.border}`};case"success":return{backgroundColor:i.colors.success,color:i.colors.text,border:`1px solid ${i.colors.success}`};case"error":return{backgroundColor:i.colors.error,color:i.colors.text,border:`1px solid ${i.colors.error}`};case"ghost":return{backgroundColor:"transparent",color:i.colors.textSecondary,border:`1px solid ${i.colors.border}`};case"outline":{const g=d?.button?.backgroundColor||i.colors.primary,L=d?.button?.color||(f?"#ffffff":"#0e0d0b"),B=d?.button?.borderColor||(f?`${i.colors.primary}88`:"#0e0d0b"),E=o||a,ie=f?"1px":"1.5px",ce=d?.button?.disabledBackgroundColor||`${g}88`,de=d?.button?.disabledColor||L;return{height:"56px",backgroundColor:E?ce:k?`${g}cc`:w?`${g}ee`:g,color:E?de:L,border:`${ie} solid ${B}`,borderRadius:d?.button?.borderRadius||"12px",fontSize:"22px",fontWeight:500,fontFamily:'"IBM Plex Mono", monospace',opacity:E?.78:1,transform:E?"none":k?"scale(0.98)":w?"translateY(-2px)":"none",boxShadow:E?`3px 3px 0px ${U}, 4px 4px 0px ${B}`:k?`2px 2px 0px ${B}`:w?`5px 5px 0px ${U}, 6px 6px 0px ${B}`:`3px 3px 0px ${U}, 4px 4px 0px ${B}`,transition:"transform 150ms ease, box-shadow 150ms ease, background-color 150ms ease, border-color 150ms ease, color 150ms ease"}}default:return{}}},oe=()=>{if(r==="outline")return{};switch(e){case"sm":return{padding:`${i.spacing.sm} ${i.spacing.md}`,fontSize:i.typography.fontSize.sm};case"md":return{padding:`${i.spacing.md} ${i.spacing.lg}`,fontSize:i.typography.fontSize.base};case"lg":return{padding:`${i.spacing.lg} ${i.spacing.xl}`,fontSize:i.typography.fontSize.lg};default:return{}}},ne={borderRadius:d?.button?.borderRadius||i.borderRadius.md,fontWeight:d?.button?.fontWeight||i.typography.fontWeight.medium,fontFamily:d?.button?.fontFamily||i.typography.fontFamily,fontSize:d?.button?.fontSize||void 0,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease, opacity 150ms ease",cursor:o||a?"not-allowed":"pointer",opacity:(o||a)&&r!=="outline"?.6:1,width:t?"100%":"auto",display:"flex",alignItems:"center",justifyContent:"center",gap:i.spacing.sm,...se(),...oe(),...d?.button?.fontSize&&{fontSize:d.button.fontSize}},P=o||a;return le("button",{type:p.type??"button","data-spiceflow-focus":!0,"aria-busy":a||void 0,"aria-disabled":P||void 0,style:{...ne,...l},className:n,disabled:P,onMouseEnter:g=>{S(!0),p.onMouseEnter?.(g)},onMouseLeave:g=>{S(!1),I(!1),p.onMouseLeave?.(g)},onMouseDown:g=>{I(!0),p.onMouseDown?.(g)},onMouseUp:g=>{I(!1),p.onMouseUp?.(g)},...p,children:[a&&v(ae,{size:16}),s]})};export{Ve as B,Ne as C,W as H,G as R,ae as S,Ae as a,H as b,V as c,K as d,Je as e,C as f,$ as g,_e as h,Re as i,Me as j,M as k,Oe as l,Fe as m,We as n,u as o,Le as p,Ye as q,h as r,He as s,ee as t,te as u,Qe as v,Ze as w};
|
|
2
|
+
import{jsx as v,jsxs as le}from"react/jsx-runtime";import{createContext as j,useEffect as N,useState as O,useCallback as ue,useContext as fe,useMemo as pe,useRef as me}from"react";import{getChainMeta as D,getTokensForChain as ge,getDelegateContract as he,ZERO_ADDRESS as ye,isNativeToken as _,getTokenByAddress as be,getChainIdsByNetwork as we}from"@spicenet-io/spiceflow-core";import{defineChain as xe,createPublicClient as Be,http as Ee,isAddress as $e,getAddress as Se,formatUnits as J}from"viem";import{readContract as ve}from"viem/actions";class u extends Error{constructor(e,a,t={}){super(a),this.code=e,this.context=t,this.name="SpiceflowError",Error.captureStackTrace&&Error.captureStackTrace(this,u)}}function Re(r){return r instanceof u}const W=[{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"}],Ce="0xcA11bde05977b3631167028862bE2a173976CA11",Te={4114:"0x860aFc632a6D625B95d8B96f39ECC48E988c6962"},ke=new Set([5115]);function Ie(r){const e=Te[r.id]??(ke.has(r.id)?void 0:Ce);return xe({id:r.id,name:r.name,nativeCurrency:r.nativeCurrency,rpcUrls:{default:{http:[r.rpcUrl]}},blockExplorers:{default:{name:r.displayName,url:r.blockExplorer}},testnet:r.network==="testnet",...e?{contracts:{multicall3:{address:e}}}:{}})}const Ue=[1,8453,42161,4114,11155111,421614,84532,5115,123420001114,688688,688689],R=Object.fromEntries(Ue.map(r=>D(r)).filter(r=>r!=null).map(r=>[r.id,{...r,viemChain:Ie(r),supportedTokens:ge(r.id)}])),Ne=R;let z={};const A=new Map,Y=r=>{z={...r||{}},A.clear()},M=r=>{const e=z[r];return e&&typeof e=="string"&&e.length>0?e:R[r]?.rpcUrl},$=r=>R[r],C=r=>{const e=D(r);return e?.displayName||e?.name||`Chain ${r}`},Oe=r=>{const e=he(r);if(!e)throw new Error(`Unsupported chain ID: ${r}`);return e},_e=(r,e,a)=>{const t=$(r);return t?.blockExplorer?`${t.blockExplorer}/tx/${e}`:"#"},H=r=>{const e=$(r);if(!e)throw new Error(`Unsupported chain ID: ${r}`);const a=M(r);if(!a)throw new Error(`No RPC URL configured for chain ID: ${r}`);const t=`${r}:${a}`,o=A.get(t);if(o)return o;const s=Be({chain:e.viemChain,transport:Ee(a,{timeout:15e3,retryCount:2,retryDelay:300}),batch:{multicall:{wait:16}}});return A.set(t,s),s},Ae=()=>{const r={};return Object.values(R).forEach(e=>{r[e.id]={name:e.name,moralisName:e.moralisId||"",chain:e.viemChain,rpcUrl:M(e.id)||e.rpcUrl}}),r},Me=(r,e=[])=>{const a=$(r);if(!a)return[];const t=[];if(![11155111,421614,84532,688689].includes(r)){const s=e.find(n=>n.chainId===r&&n.isNative);s?t.push(s):t.push({address:ye,name:a.nativeCurrency.name,symbol:a.nativeCurrency.symbol,decimals:a.nativeCurrency.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:void 0,isNative:!0,chainId:r})}if(!a.supportedTokens)return t;const o=t.some(s=>s.isNative);return a.supportedTokens.forEach(s=>{if(o&&_(s.address))return;const n=e.find(l=>l.chainId===r&&l.address.toLowerCase()===s.address.toLowerCase());n?t.push(n):t.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:r})}),t},Fe=async(r,e)=>{const a=$(r);if(!a)throw new Error(`Unsupported chain ID: ${r}`);const t=e.toLowerCase();if(_(t)){if(!a.nativeCurrency?.decimals)throw new Error(`Native currency decimals not configured for chain ${r}`);return a.nativeCurrency.decimals}if(a.supportedTokens){const o=a.supportedTokens.find(s=>s.address.toLowerCase()===t);if(o)return o.decimals}try{if(!$e(e,{strict:!1}))throw new Error(`Invalid token address: ${e}`);const o=Se(e),s=H(r),n=await ve(s,{address:o,abi:W,functionName:"decimals"});return Number(n)}catch{throw new Error(`Could not determine decimals for token ${e} on chain ${r}`)}},G=typeof process<"u"&&process.env?.NEXT_PUBLIC_RELAYER_API_URL||"https://tx-api-devserver.spicenet.io",X="__SPICEFLOW_RELAYER_API_URL__";function Pe(r,e){const a=e.match(/Output amount (\d+) is insufficient after fees (\d+) on chain (\d+)/);if(!a)return e;const[,t,o,s]=a,n=Number(s),l=BigInt(t),c=BigInt(o);let d;for(const f of r.intents){const w=f.chainBatches.find(S=>S.chainId===n);if(w){d=w;break}}const m=d?.tokenTransfers.find(f=>f.from==="escrow"&&f.to.toLowerCase()===r.user.toLowerCase()&&!_(f.token));if(!m)return`Amount is too small to cover the estimated fee on ${C(n)}.`;const p=be(m.token,n),y=p?.decimals??18,b=p?.symbol??"tokens",x=J(l,y),i=J(c,y);return`Amount is too small to cover the estimated fee on ${C(n)}. Amount: ${x} ${b}. Estimated fee: ${i} ${b}.`}function Le(r){return!1}function je(){if(typeof globalThis>"u")return;const r=globalThis[X];return typeof r=="string"&&r.length>0?r:void 0}class De{constructor(){this.baseUrl=G}setBaseUrl(e){this.baseUrl=e,typeof globalThis<"u"&&(globalThis[X]=e)}getBaseUrl(){return this.getEffectiveBaseUrl()}getEffectiveBaseUrl(){return je()||this.baseUrl}async createAction(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/actions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e,(o,s)=>typeof s=="bigint"?s.toString():s)}),t=await a.json();if(!a.ok||t.success===!1)throw new u("RELAYER_ERROR",t.error?.message||`Relayer API error: ${a.status}`,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:"/actions"});return t}async estimateActionFees(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/actions/fees/estimate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e,(o,s)=>typeof s=="bigint"?s.toString():s)}),t=await a.json();if(!a.ok||!t.success||!t.data?.feeEstimate){const o=t.error?.message||`Relayer fee estimate error: ${a.status}`,s=Pe(e,o);throw new u("RELAYER_ERROR",s,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:"/actions/fees/estimate"})}return t.data.feeEstimate}async estimateBatchGas(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/actions/gas/estimate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e,(o,s)=>typeof s=="bigint"?s.toString():s)}),t=await a.json();if(!a.ok||!t.success||!t.data?.gasFee){const o=t.error?.message||`Relayer gas estimate error: ${a.status}`;throw new u("RELAYER_ERROR",o,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:"/actions/gas/estimate"})}return{gasFee:BigInt(t.data.gasFee),gasQuoteSource:t.data.gasQuoteSource}}async executeStep(e,a,t,o){const s=`${this.getEffectiveBaseUrl()}/actions/${e}/intents/${a}/steps/${t}`,n=fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});let l;try{l=await Promise.race([n,new Promise((d,m)=>setTimeout(()=>m(new u("RELAYER_EXECUTE_ERROR",`Execute step request timed out after ${1e4/1e3}s`,{actionId:e,intentIndex:a,stepIndex:t,endpoint:`/actions/${e}/intents/${a}/steps/${t}`})),1e4))])}catch(d){throw d}const c=await l.json();if(!l.ok||c.success===!1)throw new u("RELAYER_EXECUTE_ERROR",c.error?.message||`Execute step error: ${l.status}`,{httpStatus:l.status,responseBody:JSON.stringify(c),endpoint:`/actions/${e}/intents/${a}/steps/${t}`,actionId:e});if(c?.status==="error"||c?.status==="reverted")throw new u("RELAYER_EXECUTE_ERROR",`Step ${t} previously ${c.status}${c?.error?`: ${c.error}`:""}`,{httpStatus:l.status,responseBody:JSON.stringify(c),endpoint:`/actions/${e}/intents/${a}/steps/${t}`,actionId:e,intentIndex:a,stepIndex:t,stepStatus:c.status});return{success:!0,transactionHash:c.transactionHash}}async checkStepStatus(e,a){const t=e.split("/");let o="";if(t.length>=2){const l=t[0],c=t[1];o=`${this.getEffectiveBaseUrl()}/actions/${l}/intents/${c}/steps/${a}`}else o=`${this.getEffectiveBaseUrl()}/actions/${e}/intents/0/steps/${a}`;const s=await fetch(o),n=await s.json();if(!s.ok||n.success===!1)throw new u("RELAYER_STATUS_ERROR",n.error?.message||`Intent step status check failed: ${s.status}`,{httpStatus:s.status,responseBody:JSON.stringify(n),endpoint:o,intentId:e});return{success:!0,data:{status:n.status==="error"?"reverted":n.status,transactionHash:n.txid}}}async createWallet(e,a){const t=await fetch(`${this.getEffectiveBaseUrl()}/wallets/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),o=await t.json();if(!t.ok||o.success===!1)throw new u("RELAYER_ERROR",o.error?.message||`Create wallet error: ${t.status}`,{httpStatus:t.status,responseBody:JSON.stringify(o),endpoint:`/wallets/${e}`});return o}async getWallet(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/wallets/${e}`),t=await a.json();if(!a.ok||t.success===!1)throw new u("RELAYER_ERROR",t.error?.message||`Get wallet error: ${a.status}`,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:`/wallets/${e}`});return t}async createWithdrawal(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/withdrawals`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e,(o,s)=>typeof s=="bigint"?s.toString():s)}),t=await a.json();if(!a.ok||t.success===!1)throw new u("RELAYER_ERROR",t.error?.message||`Create withdrawal error: ${a.status}`,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:"/withdrawals"});return t}async getWithdrawal(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/withdrawals/${e}`),t=await a.json();if(!a.ok||t.success===!1)throw new u("RELAYER_ERROR",t.error?.message||`Get withdrawal error: ${a.status}`,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:`/withdrawals/${e}`});return t}async getRollupTimestamp(){const e=await fetch(`${this.getEffectiveBaseUrl()}/time`),a=await e.json();if(!e.ok||a.success===!1)throw new u("RELAYER_ERROR",a.error?.message||`Get rollup timestamp error: ${e.status}`,{httpStatus:e.status,responseBody:JSON.stringify(a),endpoint:"/time"});return a}}const h=new De,F=new Map;async function Je(r,e){const a=r.toLowerCase(),t=F.get(a);if(t)return t;const o=(async()=>{try{await h.getWallet(r);return}catch{}const{unix_timestamp:s}=await h.getRollupTimestamp(),n=`I am creating a new smart wallet and adding an admin wallet ethereum:0x${r.slice(2).toLowerCase()}. Nonce: ${s}`,l=await e(n),c=typeof l=="string"?l:l.signature;if(!c)throw new Error("Wallet returned no smart wallet signature");await h.createWallet(r,{timestamp:s,signature:c})})();F.set(a,o);try{await o}finally{F.delete(a)}}const We=(r,e)=>{const a=o=>e?e(o):C(o),t=[];return r.forEach((o,s)=>{const n=o.calls&&o.calls.length>0,l=o.tokenTransfers&&o.tokenTransfers.length>0;if(n||l){const c={stepId:s,status:s===0?"processing":"pending",chainId:o.chainId,chainName:a(o.chainId),description:"Processing transaction"};t.push(c)}}),t},q="spiceflow-mode",Q=()=>{if(typeof window>"u")return null;try{const r=window.localStorage.getItem(q);return r==="embedded"?"7702":r==="external"?"ondemand":null}catch{return null}},ze=r=>{if(!(typeof window>"u"))try{window.localStorage.setItem(q,r==="7702"?"embedded":"external")}catch{}},Ye=()=>Q()!==null,Z=j(null),K=j(null),He=({children:r,provider:e,supportedChainIds:a,network:t="testnet",mode:o="7702",skipFlow:s=[],nativeChainId:n,appName:l="Spicenet",apiUrl:c,theme:d,rpcOverrides:m})=>{N(()=>{if(!c)return;const f=h.getBaseUrl();return h.setBaseUrl(c),()=>h.setBaseUrl(f)},[c]),N(()=>(Y(m),()=>Y(void 0)),[m]);const p=a??we(t),y=d??null,[b,x]=O(()=>Q()??o),i=ue(f=>{x(f),ze(f)},[]);return v(Z.Provider,{value:y,children:v(K.Provider,{value:{provider:e,supportedChainIds:p,skipFlow:s,mode:b,setMode:i,network:t,nativeChainId:n,appName:l,apiUrl:c,rpcOverrides:m},children:r})})},Ge={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"}},Xe={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"},qe={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"},V=(r="light")=>({mode:r,...Ge,colors:r==="light"?Xe:qe});function T(r,e){const a=r.replace("#",""),t=Math.max(0,Math.round(parseInt(a.substring(0,2),16)*(1-e))),o=Math.max(0,Math.round(parseInt(a.substring(2,4),16)*(1-e))),s=Math.max(0,Math.round(parseInt(a.substring(4,6),16)*(1-e)));return`#${t.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`}function Qe(r,e){return{shell:e?.shell??"#141414",shellBorder:e?.shellBorder??T(e?.shell??"#141414",.35),shellInnerBorder:e?.shellInnerBorder??T(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 Ze(r){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 ee(r,e){const a=e?{...r,...e}:r,t=a.dark??!1,o=a.primaryColor,s=a.shell??(t?"#141414":"#ffffff");return{primaryColor:o,dark:t,fontFamily:a.fontFamily??'"Helvetica Neue", sans-serif',appName:a.appName??"Spicenet",logo:a.logo,borderRadius:a.borderRadius??"8px",shell:s,shellBorder:T(s,t?.35:.085),shellInnerBorder:T(s,t?.55:.165),card:a.card??(t?"#1e1e1e":"#f9fafb"),input:t?"#171717":"#ffffff",hover:t?"#2a2a2a":"#f3f4f6",text:a.text??(t?"#ffffff":"#111827"),textMuted:a.textMuted??(t?"#888888":"#6b7280"),inputText:t?"#e0e0e0":"#111827",inputPlaceholder:t?"#555555":"#9ca3af",border:a.border??(t?"rgba(255,255,255,0.08)":"#e5e7eb"),inputBorder:t?"rgba(255,255,255,0.10)":"#d1d5db",buttonBorder:t?"rgba(255,255,255,0.12)":"#0e0d0b",successBg:t?"#0a1f18":"#d1fae5",successBorder:t?"#1a4a3a":"#6ee7b7",successText:t?"#6ee7b7":"#065f46",warningBg:t?"#1f1a0d":"#fef3c7",warningBorder:t?"#4a3820":"#fde68a",warningText:t?"#fbbf24":"#92400e",errorBg:t?"#1f0d0d":"#fef2f2",errorBorder:t?"#4a2020":"#fecaca",errorText:t?"#f87171":"#dc2626",infoBg:t?"#0d1325":"#dbeafe",infoBorder:t?"#2a3a5a":"#93c5fd",infoText:t?"#60a5fa":"#1e40af"}}function te(r,e){const a=fe(Z)??void 0;return pe(()=>{const t=a??{primaryColor:"#EA4B4B"},o={...r?.primaryColor?{primaryColor:r.primaryColor}:{},...r?.fontFamily?{fontFamily:r.fontFamily}:{},...e!==void 0?{dark:e}:{}},s=ee(t,o),{dark:n,primaryColor:l,appName:c}=s,d=V(n?"dark":"light"),m={...d,colors:{...d.colors,primary:l,primaryHover:`${l}dd`},typography:{...d.typography,fontFamily:s.fontFamily}},p={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};return{brand:a,theme:m,dark:n,appName:c,primaryColor:l,dk:p,palette:p}},[a,r,e])}const re="spiceflow-spinner-keyframes";function Ke(){if(typeof document>"u"||document.getElementById(re))return;const r=document.createElement("style");r.id=re,r.textContent="@keyframes spiceflow-spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}",document.head.appendChild(r)}const ae=({size:r=16,borderWidth:e=2,color:a="currentColor",style:t})=>{const o=me(!1);return N(()=>{o.current||(Ke(),o.current=!0)},[]),v("div",{role:"status","aria-label":"Loading",style:{width:`${r}px`,height:`${r}px`,border:`${e}px solid ${a}`,borderTop:`${e}px solid transparent`,borderRadius:"50%",animation:"spiceflow-spin 1s linear infinite",flexShrink:0,...t}})},Ve=({variant:r="primary",size:e="md",loading:a=!1,fullWidth:t=!1,disabled:o,children:s,className:n="",style:l,theme:c,styles:d,dark:m,...p})=>{const{theme:y,dark:b,palette:x}=te(d,m),i=c||y,f=m??b,[w,S]=O(!1),[k,I]=O(!1),U=f?x.shell:"white",se=()=>{switch(r){case"primary":return{backgroundColor:d?.button?.backgroundColor||i.colors.primary,color:d?.button?.color||"#ffffff",border:`1px solid ${d?.button?.backgroundColor||i.colors.primary}`};case"secondary":return{backgroundColor:i.colors.secondary,color:i.colors.text,border:`1px solid ${i.colors.border}`};case"success":return{backgroundColor:i.colors.success,color:i.colors.text,border:`1px solid ${i.colors.success}`};case"error":return{backgroundColor:i.colors.error,color:i.colors.text,border:`1px solid ${i.colors.error}`};case"ghost":return{backgroundColor:"transparent",color:i.colors.textSecondary,border:`1px solid ${i.colors.border}`};case"outline":{const g=d?.button?.backgroundColor||i.colors.primary,L=d?.button?.color||(f?"#ffffff":"#0e0d0b"),B=d?.button?.borderColor||(f?`${i.colors.primary}88`:"#0e0d0b"),E=o||a,ie=f?"1px":"1.5px",ce=d?.button?.disabledBackgroundColor||`${g}88`,de=d?.button?.disabledColor||L;return{height:"56px",backgroundColor:E?ce:k?`${g}cc`:w?`${g}ee`:g,color:E?de:L,border:`${ie} solid ${B}`,borderRadius:d?.button?.borderRadius||"12px",fontSize:"22px",fontWeight:500,fontFamily:'"IBM Plex Mono", monospace',opacity:E?.78:1,transform:E?"none":k?"scale(0.98)":w?"translateY(-2px)":"none",boxShadow:E?`3px 3px 0px ${U}, 4px 4px 0px ${B}`:k?`2px 2px 0px ${B}`:w?`5px 5px 0px ${U}, 6px 6px 0px ${B}`:`3px 3px 0px ${U}, 4px 4px 0px ${B}`,transition:"transform 150ms ease, box-shadow 150ms ease, background-color 150ms ease, border-color 150ms ease, color 150ms ease"}}default:return{}}},oe=()=>{if(r==="outline")return{};switch(e){case"sm":return{padding:`${i.spacing.sm} ${i.spacing.md}`,fontSize:i.typography.fontSize.sm};case"md":return{padding:`${i.spacing.md} ${i.spacing.lg}`,fontSize:i.typography.fontSize.base};case"lg":return{padding:`${i.spacing.lg} ${i.spacing.xl}`,fontSize:i.typography.fontSize.lg};default:return{}}},ne={borderRadius:d?.button?.borderRadius||i.borderRadius.md,fontWeight:d?.button?.fontWeight||i.typography.fontWeight.medium,fontFamily:d?.button?.fontFamily||i.typography.fontFamily,fontSize:d?.button?.fontSize||void 0,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease, opacity 150ms ease",cursor:o||a?"not-allowed":"pointer",opacity:(o||a)&&r!=="outline"?.6:1,width:t?"100%":"auto",display:"flex",alignItems:"center",justifyContent:"center",gap:i.spacing.sm,...se(),...oe(),...d?.button?.fontSize&&{fontSize:d.button.fontSize}},P=o||a;return le("button",{type:p.type??"button","data-spiceflow-focus":!0,"aria-busy":a||void 0,"aria-disabled":P||void 0,style:{...ne,...l},className:n,disabled:P,onMouseEnter:g=>{S(!0),p.onMouseEnter?.(g)},onMouseLeave:g=>{S(!1),I(!1),p.onMouseLeave?.(g)},onMouseDown:g=>{I(!0),p.onMouseDown?.(g)},onMouseUp:g=>{I(!1),p.onMouseUp?.(g)},...p,children:[a&&v(ae,{size:16}),s]})};export{Ve as B,Ne as C,W as G,G as R,ae as S,Ae as a,H as b,V as c,K as d,Je as e,C as f,$ as g,_e as h,Re as i,Me as j,M as k,Oe as l,Fe as m,We as n,u as o,Le as p,Ye as q,h as r,He as s,ee as t,te as u,Qe as v,Ze as w};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";const v=require("react/jsx-runtime"),h=require("react"),y=require("@spicenet-io/spiceflow-core"),b=require("viem"),ie=require("viem/actions");class u extends Error{constructor(e,a,t={}){super(a),this.code=e,this.context=t,this.name="SpiceflowError",Error.captureStackTrace&&Error.captureStackTrace(this,u)}}function ce(r){return r instanceof u}const j=[{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"}],le="0xcA11bde05977b3631167028862bE2a173976CA11",de={4114:"0x860aFc632a6D625B95d8B96f39ECC48E988c6962"},ue=new Set([5115]);function fe(r){const e=de[r.id]??(ue.has(r.id)?void 0:le);return b.defineChain({id:r.id,name:r.name,nativeCurrency:r.nativeCurrency,rpcUrls:{default:{http:[r.rpcUrl]}},blockExplorers:{default:{name:r.displayName,url:r.blockExplorer}},testnet:r.network==="testnet",...e?{contracts:{multicall3:{address:e}}}:{}})}const pe=[1,8453,42161,4114,11155111,421614,84532,5115,123420001114,688688,688689],k=Object.fromEntries(pe.map(r=>y.getChainMeta(r)).filter(r=>r!=null).map(r=>[r.id,{...r,viemChain:fe(r),supportedTokens:y.getTokensForChain(r.id)}])),me=k;let D={};const _=new Map,W=r=>{D={...r||{}},_.clear()},F=r=>{const e=D[r];return e&&typeof e=="string"&&e.length>0?e:k[r]?.rpcUrl},R=r=>k[r],I=r=>{const e=y.getChainMeta(r);return e?.displayName||e?.name||`Chain ${r}`},ge=r=>{const e=y.getDelegateContract(r);if(!e)throw new Error(`Unsupported chain ID: ${r}`);return e},he=(r,e,a)=>{const t=R(r);return t?.blockExplorer?`${t.blockExplorer}/tx/${e}`:"#"},H=r=>{const e=R(r);if(!e)throw new Error(`Unsupported chain ID: ${r}`);const a=F(r);if(!a)throw new Error(`No RPC URL configured for chain ID: ${r}`);const t=`${r}:${a}`,o=_.get(t);if(o)return o;const s=b.createPublicClient({chain:e.viemChain,transport:b.http(a,{timeout:15e3,retryCount:2,retryDelay:300}),batch:{multicall:{wait:16}}});return _.set(t,s),s},ye=()=>{const r={};return Object.values(k).forEach(e=>{r[e.id]={name:e.name,moralisName:e.moralisId||"",chain:e.viemChain,rpcUrl:F(e.id)||e.rpcUrl}}),r},be=(r,e=[])=>{const a=R(r);if(!a)return[];const t=[];if(![11155111,421614,84532,688689].includes(r)){const s=e.find(n=>n.chainId===r&&n.isNative);s?t.push(s):t.push({address:y.ZERO_ADDRESS,name:a.nativeCurrency.name,symbol:a.nativeCurrency.symbol,decimals:a.nativeCurrency.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:void 0,isNative:!0,chainId:r})}if(!a.supportedTokens)return t;const o=t.some(s=>s.isNative);return a.supportedTokens.forEach(s=>{if(o&&y.isNativeToken(s.address))return;const n=e.find(d=>d.chainId===r&&d.address.toLowerCase()===s.address.toLowerCase());n?t.push(n):t.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:r})}),t},we=async(r,e)=>{const a=R(r);if(!a)throw new Error(`Unsupported chain ID: ${r}`);const t=e.toLowerCase();if(y.isNativeToken(t)){if(!a.nativeCurrency?.decimals)throw new Error(`Native currency decimals not configured for chain ${r}`);return a.nativeCurrency.decimals}if(a.supportedTokens){const o=a.supportedTokens.find(s=>s.address.toLowerCase()===t);if(o)return o.decimals}try{if(!b.isAddress(e,{strict:!1}))throw new Error(`Invalid token address: ${e}`);const o=b.getAddress(e),s=H(r),n=await ie.readContract(s,{address:o,abi:j,functionName:"decimals"});return Number(n)}catch{throw new Error(`Could not determine decimals for token ${e} on chain ${r}`)}},J=typeof process<"u"&&process.env?.NEXT_PUBLIC_RELAYER_API_URL||"https://tx-api-devserver.spicenet.io",Y="__SPICEFLOW_RELAYER_API_URL__";function xe(r,e){const a=e.match(/Output amount (\d+) is insufficient after fees (\d+) on chain (\d+)/);if(!a)return e;const[,t,o,s]=a,n=Number(s),d=BigInt(t),c=BigInt(o);let l;for(const f of r.intents){const E=f.chainBatches.find(T=>T.chainId===n);if(E){l=E;break}}const m=l?.tokenTransfers.find(f=>f.from==="escrow"&&f.to.toLowerCase()===r.user.toLowerCase()&&!y.isNativeToken(f.token));if(!m)return`Amount is too small to cover the estimated fee on ${I(n)}.`;const p=y.getTokenByAddress(m.token,n),x=p?.decimals??18,B=p?.symbol??"tokens",S=b.formatUnits(d,x),i=b.formatUnits(c,x);return`Amount is too small to cover the estimated fee on ${I(n)}. Amount: ${S} ${B}. Estimated fee: ${i} ${B}.`}function Be(r){return!1}function Ee(){if(typeof globalThis>"u")return;const r=globalThis[Y];return typeof r=="string"&&r.length>0?r:void 0}class Se{constructor(){this.baseUrl=J}setBaseUrl(e){this.baseUrl=e,typeof globalThis<"u"&&(globalThis[Y]=e)}getBaseUrl(){return this.getEffectiveBaseUrl()}getEffectiveBaseUrl(){return Ee()||this.baseUrl}async createAction(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/actions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e,(o,s)=>typeof s=="bigint"?s.toString():s)}),t=await a.json();if(!a.ok||t.success===!1)throw new u("RELAYER_ERROR",t.error?.message||`Relayer API error: ${a.status}`,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:"/actions"});return t}async estimateActionFees(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/actions/fees/estimate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e,(o,s)=>typeof s=="bigint"?s.toString():s)}),t=await a.json();if(!a.ok||!t.success||!t.data?.feeEstimate){const o=t.error?.message||`Relayer fee estimate error: ${a.status}`,s=xe(e,o);throw new u("RELAYER_ERROR",s,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:"/actions/fees/estimate"})}return t.data.feeEstimate}async estimateBatchGas(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/actions/gas/estimate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e,(o,s)=>typeof s=="bigint"?s.toString():s)}),t=await a.json();if(!a.ok||!t.success||!t.data?.gasFee){const o=t.error?.message||`Relayer gas estimate error: ${a.status}`;throw new u("RELAYER_ERROR",o,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:"/actions/gas/estimate"})}return{gasFee:BigInt(t.data.gasFee),gasQuoteSource:t.data.gasQuoteSource}}async executeStep(e,a,t,o){const s=`${this.getEffectiveBaseUrl()}/actions/${e}/intents/${a}/steps/${t}`,n=fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});let d;try{d=await Promise.race([n,new Promise((l,m)=>setTimeout(()=>m(new u("RELAYER_EXECUTE_ERROR",`Execute step request timed out after ${1e4/1e3}s`,{actionId:e,intentIndex:a,stepIndex:t,endpoint:`/actions/${e}/intents/${a}/steps/${t}`})),1e4))])}catch(l){throw l}const c=await d.json();if(!d.ok||c.success===!1)throw new u("RELAYER_EXECUTE_ERROR",c.error?.message||`Execute step error: ${d.status}`,{httpStatus:d.status,responseBody:JSON.stringify(c),endpoint:`/actions/${e}/intents/${a}/steps/${t}`,actionId:e});if(c?.status==="error"||c?.status==="reverted")throw new u("RELAYER_EXECUTE_ERROR",`Step ${t} previously ${c.status}${c?.error?`: ${c.error}`:""}`,{httpStatus:d.status,responseBody:JSON.stringify(c),endpoint:`/actions/${e}/intents/${a}/steps/${t}`,actionId:e,intentIndex:a,stepIndex:t,stepStatus:c.status});return{success:!0,transactionHash:c.transactionHash}}async checkStepStatus(e,a){const t=e.split("/");let o="";if(t.length>=2){const d=t[0],c=t[1];o=`${this.getEffectiveBaseUrl()}/actions/${d}/intents/${c}/steps/${a}`}else o=`${this.getEffectiveBaseUrl()}/actions/${e}/intents/0/steps/${a}`;const s=await fetch(o),n=await s.json();if(!s.ok||n.success===!1)throw new u("RELAYER_STATUS_ERROR",n.error?.message||`Intent step status check failed: ${s.status}`,{httpStatus:s.status,responseBody:JSON.stringify(n),endpoint:o,intentId:e});return{success:!0,data:{status:n.status==="error"?"reverted":n.status,transactionHash:n.txid}}}async createWallet(e,a){const t=await fetch(`${this.getEffectiveBaseUrl()}/wallets/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),o=await t.json();if(!t.ok||o.success===!1)throw new u("RELAYER_ERROR",o.error?.message||`Create wallet error: ${t.status}`,{httpStatus:t.status,responseBody:JSON.stringify(o),endpoint:`/wallets/${e}`});return o}async getWallet(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/wallets/${e}`),t=await a.json();if(!a.ok||t.success===!1)throw new u("RELAYER_ERROR",t.error?.message||`Get wallet error: ${a.status}`,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:`/wallets/${e}`});return t}async createWithdrawal(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/withdrawals`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e,(o,s)=>typeof s=="bigint"?s.toString():s)}),t=await a.json();if(!a.ok||t.success===!1)throw new u("RELAYER_ERROR",t.error?.message||`Create withdrawal error: ${a.status}`,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:"/withdrawals"});return t}async getWithdrawal(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/withdrawals/${e}`),t=await a.json();if(!a.ok||t.success===!1)throw new u("RELAYER_ERROR",t.error?.message||`Get withdrawal error: ${a.status}`,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:`/withdrawals/${e}`});return t}async getRollupTimestamp(){const e=await fetch(`${this.getEffectiveBaseUrl()}/time`),a=await e.json();if(!e.ok||a.success===!1)throw new u("RELAYER_ERROR",a.error?.message||`Get rollup timestamp error: ${e.status}`,{httpStatus:e.status,responseBody:JSON.stringify(a),endpoint:"/time"});return a}}const w=new Se,M=new Map;async function $e(r,e){const a=r.toLowerCase(),t=M.get(a);if(t)return t;const o=(async()=>{try{await w.getWallet(r);return}catch{}const{unix_timestamp:s}=await w.getRollupTimestamp(),n=`I am creating a new smart wallet and adding an admin wallet ethereum:0x${r.slice(2).toLowerCase()}. Nonce: ${s}`,d=await e(n),c=typeof d=="string"?d:d.signature;if(!c)throw new Error("Wallet returned no smart wallet signature");await w.createWallet(r,{timestamp:s,signature:c})})();M.set(a,o);try{await o}finally{M.delete(a)}}const Ce=(r,e)=>{const a=o=>e?e(o):I(o),t=[];return r.forEach((o,s)=>{const n=o.calls&&o.calls.length>0,d=o.tokenTransfers&&o.tokenTransfers.length>0;if(n||d){const c={stepId:s,status:s===0?"processing":"pending",chainId:o.chainId,chainName:a(o.chainId),description:"Processing transaction"};t.push(c)}}),t},z="spiceflow-mode",G=()=>{if(typeof window>"u")return null;try{const r=window.localStorage.getItem(z);return r==="embedded"?"7702":r==="external"?"ondemand":null}catch{return null}},ve=r=>{if(!(typeof window>"u"))try{window.localStorage.setItem(z,r==="7702"?"embedded":"external")}catch{}},Re=()=>G()!==null,q=h.createContext(null),X=h.createContext(null),Te=({children:r,provider:e,supportedChainIds:a,network:t="testnet",mode:o="7702",skipFlow:s=[],nativeChainId:n,appName:d="Spicenet",apiUrl:c,theme:l,rpcOverrides:m})=>{h.useEffect(()=>{if(!c)return;const f=w.getBaseUrl();return w.setBaseUrl(c),()=>w.setBaseUrl(f)},[c]),h.useEffect(()=>(W(m),()=>W(void 0)),[m]);const p=a??y.getChainIdsByNetwork(t),x=l??null,[B,S]=h.useState(()=>G()??o),i=h.useCallback(f=>{S(f),ve(f)},[]);return v.jsx(q.Provider,{value:x,children:v.jsx(X.Provider,{value:{provider:e,supportedChainIds:p,skipFlow:s,mode:B,setMode:i,network:t,nativeChainId:n,appName:d,apiUrl:c,rpcOverrides:m},children:r})})},ke={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"}},Ie={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"},Ne={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"},Q=(r="light")=>({mode:r,...ke,colors:r==="light"?Ie:Ne});function N(r,e){const a=r.replace("#",""),t=Math.max(0,Math.round(parseInt(a.substring(0,2),16)*(1-e))),o=Math.max(0,Math.round(parseInt(a.substring(2,4),16)*(1-e))),s=Math.max(0,Math.round(parseInt(a.substring(4,6),16)*(1-e)));return`#${t.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`}function Ue(r,e){return{shell:e?.shell??"#141414",shellBorder:e?.shellBorder??N(e?.shell??"#141414",.35),shellInnerBorder:e?.shellInnerBorder??N(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 Oe(r){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 Z(r,e){const a=e?{...r,...e}:r,t=a.dark??!1,o=a.primaryColor,s=a.shell??(t?"#141414":"#ffffff");return{primaryColor:o,dark:t,fontFamily:a.fontFamily??'"Helvetica Neue", sans-serif',appName:a.appName??"Spicenet",logo:a.logo,borderRadius:a.borderRadius??"8px",shell:s,shellBorder:N(s,t?.35:.085),shellInnerBorder:N(s,t?.55:.165),card:a.card??(t?"#1e1e1e":"#f9fafb"),input:t?"#171717":"#ffffff",hover:t?"#2a2a2a":"#f3f4f6",text:a.text??(t?"#ffffff":"#111827"),textMuted:a.textMuted??(t?"#888888":"#6b7280"),inputText:t?"#e0e0e0":"#111827",inputPlaceholder:t?"#555555":"#9ca3af",border:a.border??(t?"rgba(255,255,255,0.08)":"#e5e7eb"),inputBorder:t?"rgba(255,255,255,0.10)":"#d1d5db",buttonBorder:t?"rgba(255,255,255,0.12)":"#0e0d0b",successBg:t?"#0a1f18":"#d1fae5",successBorder:t?"#1a4a3a":"#6ee7b7",successText:t?"#6ee7b7":"#065f46",warningBg:t?"#1f1a0d":"#fef3c7",warningBorder:t?"#4a3820":"#fde68a",warningText:t?"#fbbf24":"#92400e",errorBg:t?"#1f0d0d":"#fef2f2",errorBorder:t?"#4a2020":"#fecaca",errorText:t?"#f87171":"#dc2626",infoBg:t?"#0d1325":"#dbeafe",infoBorder:t?"#2a3a5a":"#93c5fd",infoText:t?"#60a5fa":"#1e40af"}}function K(r,e){const a=h.useContext(q)??void 0;return h.useMemo(()=>{const t=a??{primaryColor:"#EA4B4B"},o={...r?.primaryColor?{primaryColor:r.primaryColor}:{},...r?.fontFamily?{fontFamily:r.fontFamily}:{},...e!==void 0?{dark:e}:{}},s=Z(t,o),{dark:n,primaryColor:d,appName:c}=s,l=Q(n?"dark":"light"),m={...l,colors:{...l.colors,primary:d,primaryHover:`${d}dd`},typography:{...l.typography,fontFamily:s.fontFamily}},p={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};return{brand:a,theme:m,dark:n,appName:c,primaryColor:d,dk:p,palette:p}},[a,r,e])}const V="spiceflow-spinner-keyframes";function Ae(){if(typeof document>"u"||document.getElementById(V))return;const r=document.createElement("style");r.id=V,r.textContent="@keyframes spiceflow-spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}",document.head.appendChild(r)}const ee=({size:r=16,borderWidth:e=2,color:a="currentColor",style:t})=>{const o=h.useRef(!1);return h.useEffect(()=>{o.current||(Ae(),o.current=!0)},[]),v.jsx("div",{role:"status","aria-label":"Loading",style:{width:`${r}px`,height:`${r}px`,border:`${e}px solid ${a}`,borderTop:`${e}px solid transparent`,borderRadius:"50%",animation:"spiceflow-spin 1s linear infinite",flexShrink:0,...t}})},_e=({variant:r="primary",size:e="md",loading:a=!1,fullWidth:t=!1,disabled:o,children:s,className:n="",style:d,theme:c,styles:l,dark:m,...p})=>{const{theme:x,dark:B,palette:S}=K(l,m),i=c||x,f=m??B,[E,T]=h.useState(!1),[U,O]=h.useState(!1),A=f?S.shell:"white",te=()=>{switch(r){case"primary":return{backgroundColor:l?.button?.backgroundColor||i.colors.primary,color:l?.button?.color||"#ffffff",border:`1px solid ${l?.button?.backgroundColor||i.colors.primary}`};case"secondary":return{backgroundColor:i.colors.secondary,color:i.colors.text,border:`1px solid ${i.colors.border}`};case"success":return{backgroundColor:i.colors.success,color:i.colors.text,border:`1px solid ${i.colors.success}`};case"error":return{backgroundColor:i.colors.error,color:i.colors.text,border:`1px solid ${i.colors.error}`};case"ghost":return{backgroundColor:"transparent",color:i.colors.textSecondary,border:`1px solid ${i.colors.border}`};case"outline":{const g=l?.button?.backgroundColor||i.colors.primary,L=l?.button?.color||(f?"#ffffff":"#0e0d0b"),$=l?.button?.borderColor||(f?`${i.colors.primary}88`:"#0e0d0b"),C=o||a,se=f?"1px":"1.5px",oe=l?.button?.disabledBackgroundColor||`${g}88`,ne=l?.button?.disabledColor||L;return{height:"56px",backgroundColor:C?oe:U?`${g}cc`:E?`${g}ee`:g,color:C?ne:L,border:`${se} solid ${$}`,borderRadius:l?.button?.borderRadius||"12px",fontSize:"22px",fontWeight:500,fontFamily:'"IBM Plex Mono", monospace',opacity:C?.78:1,transform:C?"none":U?"scale(0.98)":E?"translateY(-2px)":"none",boxShadow:C?`3px 3px 0px ${A}, 4px 4px 0px ${$}`:U?`2px 2px 0px ${$}`:E?`5px 5px 0px ${A}, 6px 6px 0px ${$}`:`3px 3px 0px ${A}, 4px 4px 0px ${$}`,transition:"transform 150ms ease, box-shadow 150ms ease, background-color 150ms ease, border-color 150ms ease, color 150ms ease"}}default:return{}}},re=()=>{if(r==="outline")return{};switch(e){case"sm":return{padding:`${i.spacing.sm} ${i.spacing.md}`,fontSize:i.typography.fontSize.sm};case"md":return{padding:`${i.spacing.md} ${i.spacing.lg}`,fontSize:i.typography.fontSize.base};case"lg":return{padding:`${i.spacing.lg} ${i.spacing.xl}`,fontSize:i.typography.fontSize.lg};default:return{}}},ae={borderRadius:l?.button?.borderRadius||i.borderRadius.md,fontWeight:l?.button?.fontWeight||i.typography.fontWeight.medium,fontFamily:l?.button?.fontFamily||i.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||a?"not-allowed":"pointer",opacity:(o||a)&&r!=="outline"?.6:1,width:t?"100%":"auto",display:"flex",alignItems:"center",justifyContent:"center",gap:i.spacing.sm,...te(),...re(),...l?.button?.fontSize&&{fontSize:l.button.fontSize}},P=o||a;return v.jsxs("button",{type:p.type??"button","data-spiceflow-focus":!0,"aria-busy":a||void 0,"aria-disabled":P||void 0,style:{...ae,...d},className:n,disabled:P,onMouseEnter:g=>{T(!0),p.onMouseEnter?.(g)},onMouseLeave:g=>{T(!1),O(!1),p.onMouseLeave?.(g)},onMouseDown:g=>{O(!0),p.onMouseDown?.(g)},onMouseUp:g=>{O(!1),p.onMouseUp?.(g)},...p,children:[a&&v.jsx(ee,{size:16}),s]})};exports.Button=_e,exports.CHAIN_CONFIGS=me,exports.H=j,exports.RELAYER_API_URL=J,exports.SpiceFlowProvider=Te,exports.SpiceFlowProviderContext=X,exports.SpiceflowError=u,exports.Spinner=ee,exports.buildDarkPalette=Ue,exports.buildLightPalette=Oe,exports.createInitialSteps=Ce,exports.createTheme=Q,exports.ensureSmartWallet=$e,exports.getAllAssetsForChain=be,exports.getChainConfig=R,exports.getChainName=I,exports.getChainsForAssets=ye,exports.getClientForChain=H,exports.getDelegateContractAddress=ge,exports.getExplorerUrl=he,exports.getRpcUrlForChain=F,exports.getTokenDecimals=we,exports.hasReducedFeeOutput=Be,exports.hasStoredSpiceFlowMode=Re,exports.isSpiceflowError=ce,exports.relayerService=w,exports.resolveTheme=Z,exports.useSpiceBrand=K;
|
|
2
|
+
"use strict";const v=require("react/jsx-runtime"),h=require("react"),y=require("@spicenet-io/spiceflow-core"),b=require("viem"),ie=require("viem/actions");class u extends Error{constructor(e,a,t={}){super(a),this.code=e,this.context=t,this.name="SpiceflowError",Error.captureStackTrace&&Error.captureStackTrace(this,u)}}function ce(r){return r instanceof u}const j=[{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"}],le="0xcA11bde05977b3631167028862bE2a173976CA11",de={4114:"0x860aFc632a6D625B95d8B96f39ECC48E988c6962"},ue=new Set([5115]);function fe(r){const e=de[r.id]??(ue.has(r.id)?void 0:le);return b.defineChain({id:r.id,name:r.name,nativeCurrency:r.nativeCurrency,rpcUrls:{default:{http:[r.rpcUrl]}},blockExplorers:{default:{name:r.displayName,url:r.blockExplorer}},testnet:r.network==="testnet",...e?{contracts:{multicall3:{address:e}}}:{}})}const pe=[1,8453,42161,4114,11155111,421614,84532,5115,123420001114,688688,688689],k=Object.fromEntries(pe.map(r=>y.getChainMeta(r)).filter(r=>r!=null).map(r=>[r.id,{...r,viemChain:fe(r),supportedTokens:y.getTokensForChain(r.id)}])),me=k;let D={};const _=new Map,W=r=>{D={...r||{}},_.clear()},F=r=>{const e=D[r];return e&&typeof e=="string"&&e.length>0?e:k[r]?.rpcUrl},R=r=>k[r],I=r=>{const e=y.getChainMeta(r);return e?.displayName||e?.name||`Chain ${r}`},ge=r=>{const e=y.getDelegateContract(r);if(!e)throw new Error(`Unsupported chain ID: ${r}`);return e},he=(r,e,a)=>{const t=R(r);return t?.blockExplorer?`${t.blockExplorer}/tx/${e}`:"#"},Y=r=>{const e=R(r);if(!e)throw new Error(`Unsupported chain ID: ${r}`);const a=F(r);if(!a)throw new Error(`No RPC URL configured for chain ID: ${r}`);const t=`${r}:${a}`,o=_.get(t);if(o)return o;const s=b.createPublicClient({chain:e.viemChain,transport:b.http(a,{timeout:15e3,retryCount:2,retryDelay:300}),batch:{multicall:{wait:16}}});return _.set(t,s),s},ye=()=>{const r={};return Object.values(k).forEach(e=>{r[e.id]={name:e.name,moralisName:e.moralisId||"",chain:e.viemChain,rpcUrl:F(e.id)||e.rpcUrl}}),r},be=(r,e=[])=>{const a=R(r);if(!a)return[];const t=[];if(![11155111,421614,84532,688689].includes(r)){const s=e.find(n=>n.chainId===r&&n.isNative);s?t.push(s):t.push({address:y.ZERO_ADDRESS,name:a.nativeCurrency.name,symbol:a.nativeCurrency.symbol,decimals:a.nativeCurrency.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:void 0,isNative:!0,chainId:r})}if(!a.supportedTokens)return t;const o=t.some(s=>s.isNative);return a.supportedTokens.forEach(s=>{if(o&&y.isNativeToken(s.address))return;const n=e.find(d=>d.chainId===r&&d.address.toLowerCase()===s.address.toLowerCase());n?t.push(n):t.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:r})}),t},we=async(r,e)=>{const a=R(r);if(!a)throw new Error(`Unsupported chain ID: ${r}`);const t=e.toLowerCase();if(y.isNativeToken(t)){if(!a.nativeCurrency?.decimals)throw new Error(`Native currency decimals not configured for chain ${r}`);return a.nativeCurrency.decimals}if(a.supportedTokens){const o=a.supportedTokens.find(s=>s.address.toLowerCase()===t);if(o)return o.decimals}try{if(!b.isAddress(e,{strict:!1}))throw new Error(`Invalid token address: ${e}`);const o=b.getAddress(e),s=Y(r),n=await ie.readContract(s,{address:o,abi:j,functionName:"decimals"});return Number(n)}catch{throw new Error(`Could not determine decimals for token ${e} on chain ${r}`)}},J=typeof process<"u"&&process.env?.NEXT_PUBLIC_RELAYER_API_URL||"https://tx-api-devserver.spicenet.io",z="__SPICEFLOW_RELAYER_API_URL__";function xe(r,e){const a=e.match(/Output amount (\d+) is insufficient after fees (\d+) on chain (\d+)/);if(!a)return e;const[,t,o,s]=a,n=Number(s),d=BigInt(t),c=BigInt(o);let l;for(const f of r.intents){const E=f.chainBatches.find(T=>T.chainId===n);if(E){l=E;break}}const m=l?.tokenTransfers.find(f=>f.from==="escrow"&&f.to.toLowerCase()===r.user.toLowerCase()&&!y.isNativeToken(f.token));if(!m)return`Amount is too small to cover the estimated fee on ${I(n)}.`;const p=y.getTokenByAddress(m.token,n),x=p?.decimals??18,B=p?.symbol??"tokens",S=b.formatUnits(d,x),i=b.formatUnits(c,x);return`Amount is too small to cover the estimated fee on ${I(n)}. Amount: ${S} ${B}. Estimated fee: ${i} ${B}.`}function Be(r){return!1}function Ee(){if(typeof globalThis>"u")return;const r=globalThis[z];return typeof r=="string"&&r.length>0?r:void 0}class Se{constructor(){this.baseUrl=J}setBaseUrl(e){this.baseUrl=e,typeof globalThis<"u"&&(globalThis[z]=e)}getBaseUrl(){return this.getEffectiveBaseUrl()}getEffectiveBaseUrl(){return Ee()||this.baseUrl}async createAction(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/actions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e,(o,s)=>typeof s=="bigint"?s.toString():s)}),t=await a.json();if(!a.ok||t.success===!1)throw new u("RELAYER_ERROR",t.error?.message||`Relayer API error: ${a.status}`,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:"/actions"});return t}async estimateActionFees(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/actions/fees/estimate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e,(o,s)=>typeof s=="bigint"?s.toString():s)}),t=await a.json();if(!a.ok||!t.success||!t.data?.feeEstimate){const o=t.error?.message||`Relayer fee estimate error: ${a.status}`,s=xe(e,o);throw new u("RELAYER_ERROR",s,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:"/actions/fees/estimate"})}return t.data.feeEstimate}async estimateBatchGas(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/actions/gas/estimate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e,(o,s)=>typeof s=="bigint"?s.toString():s)}),t=await a.json();if(!a.ok||!t.success||!t.data?.gasFee){const o=t.error?.message||`Relayer gas estimate error: ${a.status}`;throw new u("RELAYER_ERROR",o,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:"/actions/gas/estimate"})}return{gasFee:BigInt(t.data.gasFee),gasQuoteSource:t.data.gasQuoteSource}}async executeStep(e,a,t,o){const s=`${this.getEffectiveBaseUrl()}/actions/${e}/intents/${a}/steps/${t}`,n=fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});let d;try{d=await Promise.race([n,new Promise((l,m)=>setTimeout(()=>m(new u("RELAYER_EXECUTE_ERROR",`Execute step request timed out after ${1e4/1e3}s`,{actionId:e,intentIndex:a,stepIndex:t,endpoint:`/actions/${e}/intents/${a}/steps/${t}`})),1e4))])}catch(l){throw l}const c=await d.json();if(!d.ok||c.success===!1)throw new u("RELAYER_EXECUTE_ERROR",c.error?.message||`Execute step error: ${d.status}`,{httpStatus:d.status,responseBody:JSON.stringify(c),endpoint:`/actions/${e}/intents/${a}/steps/${t}`,actionId:e});if(c?.status==="error"||c?.status==="reverted")throw new u("RELAYER_EXECUTE_ERROR",`Step ${t} previously ${c.status}${c?.error?`: ${c.error}`:""}`,{httpStatus:d.status,responseBody:JSON.stringify(c),endpoint:`/actions/${e}/intents/${a}/steps/${t}`,actionId:e,intentIndex:a,stepIndex:t,stepStatus:c.status});return{success:!0,transactionHash:c.transactionHash}}async checkStepStatus(e,a){const t=e.split("/");let o="";if(t.length>=2){const d=t[0],c=t[1];o=`${this.getEffectiveBaseUrl()}/actions/${d}/intents/${c}/steps/${a}`}else o=`${this.getEffectiveBaseUrl()}/actions/${e}/intents/0/steps/${a}`;const s=await fetch(o),n=await s.json();if(!s.ok||n.success===!1)throw new u("RELAYER_STATUS_ERROR",n.error?.message||`Intent step status check failed: ${s.status}`,{httpStatus:s.status,responseBody:JSON.stringify(n),endpoint:o,intentId:e});return{success:!0,data:{status:n.status==="error"?"reverted":n.status,transactionHash:n.txid}}}async createWallet(e,a){const t=await fetch(`${this.getEffectiveBaseUrl()}/wallets/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),o=await t.json();if(!t.ok||o.success===!1)throw new u("RELAYER_ERROR",o.error?.message||`Create wallet error: ${t.status}`,{httpStatus:t.status,responseBody:JSON.stringify(o),endpoint:`/wallets/${e}`});return o}async getWallet(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/wallets/${e}`),t=await a.json();if(!a.ok||t.success===!1)throw new u("RELAYER_ERROR",t.error?.message||`Get wallet error: ${a.status}`,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:`/wallets/${e}`});return t}async createWithdrawal(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/withdrawals`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e,(o,s)=>typeof s=="bigint"?s.toString():s)}),t=await a.json();if(!a.ok||t.success===!1)throw new u("RELAYER_ERROR",t.error?.message||`Create withdrawal error: ${a.status}`,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:"/withdrawals"});return t}async getWithdrawal(e){const a=await fetch(`${this.getEffectiveBaseUrl()}/withdrawals/${e}`),t=await a.json();if(!a.ok||t.success===!1)throw new u("RELAYER_ERROR",t.error?.message||`Get withdrawal error: ${a.status}`,{httpStatus:a.status,responseBody:JSON.stringify(t),endpoint:`/withdrawals/${e}`});return t}async getRollupTimestamp(){const e=await fetch(`${this.getEffectiveBaseUrl()}/time`),a=await e.json();if(!e.ok||a.success===!1)throw new u("RELAYER_ERROR",a.error?.message||`Get rollup timestamp error: ${e.status}`,{httpStatus:e.status,responseBody:JSON.stringify(a),endpoint:"/time"});return a}}const w=new Se,M=new Map;async function $e(r,e){const a=r.toLowerCase(),t=M.get(a);if(t)return t;const o=(async()=>{try{await w.getWallet(r);return}catch{}const{unix_timestamp:s}=await w.getRollupTimestamp(),n=`I am creating a new smart wallet and adding an admin wallet ethereum:0x${r.slice(2).toLowerCase()}. Nonce: ${s}`,d=await e(n),c=typeof d=="string"?d:d.signature;if(!c)throw new Error("Wallet returned no smart wallet signature");await w.createWallet(r,{timestamp:s,signature:c})})();M.set(a,o);try{await o}finally{M.delete(a)}}const Ce=(r,e)=>{const a=o=>e?e(o):I(o),t=[];return r.forEach((o,s)=>{const n=o.calls&&o.calls.length>0,d=o.tokenTransfers&&o.tokenTransfers.length>0;if(n||d){const c={stepId:s,status:s===0?"processing":"pending",chainId:o.chainId,chainName:a(o.chainId),description:"Processing transaction"};t.push(c)}}),t},H="spiceflow-mode",G=()=>{if(typeof window>"u")return null;try{const r=window.localStorage.getItem(H);return r==="embedded"?"7702":r==="external"?"ondemand":null}catch{return null}},ve=r=>{if(!(typeof window>"u"))try{window.localStorage.setItem(H,r==="7702"?"embedded":"external")}catch{}},Re=()=>G()!==null,q=h.createContext(null),X=h.createContext(null),Te=({children:r,provider:e,supportedChainIds:a,network:t="testnet",mode:o="7702",skipFlow:s=[],nativeChainId:n,appName:d="Spicenet",apiUrl:c,theme:l,rpcOverrides:m})=>{h.useEffect(()=>{if(!c)return;const f=w.getBaseUrl();return w.setBaseUrl(c),()=>w.setBaseUrl(f)},[c]),h.useEffect(()=>(W(m),()=>W(void 0)),[m]);const p=a??y.getChainIdsByNetwork(t),x=l??null,[B,S]=h.useState(()=>G()??o),i=h.useCallback(f=>{S(f),ve(f)},[]);return v.jsx(q.Provider,{value:x,children:v.jsx(X.Provider,{value:{provider:e,supportedChainIds:p,skipFlow:s,mode:B,setMode:i,network:t,nativeChainId:n,appName:d,apiUrl:c,rpcOverrides:m},children:r})})},ke={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"}},Ie={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"},Ne={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"},Q=(r="light")=>({mode:r,...ke,colors:r==="light"?Ie:Ne});function N(r,e){const a=r.replace("#",""),t=Math.max(0,Math.round(parseInt(a.substring(0,2),16)*(1-e))),o=Math.max(0,Math.round(parseInt(a.substring(2,4),16)*(1-e))),s=Math.max(0,Math.round(parseInt(a.substring(4,6),16)*(1-e)));return`#${t.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`}function Ue(r,e){return{shell:e?.shell??"#141414",shellBorder:e?.shellBorder??N(e?.shell??"#141414",.35),shellInnerBorder:e?.shellInnerBorder??N(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 Ae(r){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 Z(r,e){const a=e?{...r,...e}:r,t=a.dark??!1,o=a.primaryColor,s=a.shell??(t?"#141414":"#ffffff");return{primaryColor:o,dark:t,fontFamily:a.fontFamily??'"Helvetica Neue", sans-serif',appName:a.appName??"Spicenet",logo:a.logo,borderRadius:a.borderRadius??"8px",shell:s,shellBorder:N(s,t?.35:.085),shellInnerBorder:N(s,t?.55:.165),card:a.card??(t?"#1e1e1e":"#f9fafb"),input:t?"#171717":"#ffffff",hover:t?"#2a2a2a":"#f3f4f6",text:a.text??(t?"#ffffff":"#111827"),textMuted:a.textMuted??(t?"#888888":"#6b7280"),inputText:t?"#e0e0e0":"#111827",inputPlaceholder:t?"#555555":"#9ca3af",border:a.border??(t?"rgba(255,255,255,0.08)":"#e5e7eb"),inputBorder:t?"rgba(255,255,255,0.10)":"#d1d5db",buttonBorder:t?"rgba(255,255,255,0.12)":"#0e0d0b",successBg:t?"#0a1f18":"#d1fae5",successBorder:t?"#1a4a3a":"#6ee7b7",successText:t?"#6ee7b7":"#065f46",warningBg:t?"#1f1a0d":"#fef3c7",warningBorder:t?"#4a3820":"#fde68a",warningText:t?"#fbbf24":"#92400e",errorBg:t?"#1f0d0d":"#fef2f2",errorBorder:t?"#4a2020":"#fecaca",errorText:t?"#f87171":"#dc2626",infoBg:t?"#0d1325":"#dbeafe",infoBorder:t?"#2a3a5a":"#93c5fd",infoText:t?"#60a5fa":"#1e40af"}}function K(r,e){const a=h.useContext(q)??void 0;return h.useMemo(()=>{const t=a??{primaryColor:"#EA4B4B"},o={...r?.primaryColor?{primaryColor:r.primaryColor}:{},...r?.fontFamily?{fontFamily:r.fontFamily}:{},...e!==void 0?{dark:e}:{}},s=Z(t,o),{dark:n,primaryColor:d,appName:c}=s,l=Q(n?"dark":"light"),m={...l,colors:{...l.colors,primary:d,primaryHover:`${d}dd`},typography:{...l.typography,fontFamily:s.fontFamily}},p={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};return{brand:a,theme:m,dark:n,appName:c,primaryColor:d,dk:p,palette:p}},[a,r,e])}const V="spiceflow-spinner-keyframes";function Oe(){if(typeof document>"u"||document.getElementById(V))return;const r=document.createElement("style");r.id=V,r.textContent="@keyframes spiceflow-spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}",document.head.appendChild(r)}const ee=({size:r=16,borderWidth:e=2,color:a="currentColor",style:t})=>{const o=h.useRef(!1);return h.useEffect(()=>{o.current||(Oe(),o.current=!0)},[]),v.jsx("div",{role:"status","aria-label":"Loading",style:{width:`${r}px`,height:`${r}px`,border:`${e}px solid ${a}`,borderTop:`${e}px solid transparent`,borderRadius:"50%",animation:"spiceflow-spin 1s linear infinite",flexShrink:0,...t}})},_e=({variant:r="primary",size:e="md",loading:a=!1,fullWidth:t=!1,disabled:o,children:s,className:n="",style:d,theme:c,styles:l,dark:m,...p})=>{const{theme:x,dark:B,palette:S}=K(l,m),i=c||x,f=m??B,[E,T]=h.useState(!1),[U,A]=h.useState(!1),O=f?S.shell:"white",te=()=>{switch(r){case"primary":return{backgroundColor:l?.button?.backgroundColor||i.colors.primary,color:l?.button?.color||"#ffffff",border:`1px solid ${l?.button?.backgroundColor||i.colors.primary}`};case"secondary":return{backgroundColor:i.colors.secondary,color:i.colors.text,border:`1px solid ${i.colors.border}`};case"success":return{backgroundColor:i.colors.success,color:i.colors.text,border:`1px solid ${i.colors.success}`};case"error":return{backgroundColor:i.colors.error,color:i.colors.text,border:`1px solid ${i.colors.error}`};case"ghost":return{backgroundColor:"transparent",color:i.colors.textSecondary,border:`1px solid ${i.colors.border}`};case"outline":{const g=l?.button?.backgroundColor||i.colors.primary,L=l?.button?.color||(f?"#ffffff":"#0e0d0b"),$=l?.button?.borderColor||(f?`${i.colors.primary}88`:"#0e0d0b"),C=o||a,se=f?"1px":"1.5px",oe=l?.button?.disabledBackgroundColor||`${g}88`,ne=l?.button?.disabledColor||L;return{height:"56px",backgroundColor:C?oe:U?`${g}cc`:E?`${g}ee`:g,color:C?ne:L,border:`${se} solid ${$}`,borderRadius:l?.button?.borderRadius||"12px",fontSize:"22px",fontWeight:500,fontFamily:'"IBM Plex Mono", monospace',opacity:C?.78:1,transform:C?"none":U?"scale(0.98)":E?"translateY(-2px)":"none",boxShadow:C?`3px 3px 0px ${O}, 4px 4px 0px ${$}`:U?`2px 2px 0px ${$}`:E?`5px 5px 0px ${O}, 6px 6px 0px ${$}`:`3px 3px 0px ${O}, 4px 4px 0px ${$}`,transition:"transform 150ms ease, box-shadow 150ms ease, background-color 150ms ease, border-color 150ms ease, color 150ms ease"}}default:return{}}},re=()=>{if(r==="outline")return{};switch(e){case"sm":return{padding:`${i.spacing.sm} ${i.spacing.md}`,fontSize:i.typography.fontSize.sm};case"md":return{padding:`${i.spacing.md} ${i.spacing.lg}`,fontSize:i.typography.fontSize.base};case"lg":return{padding:`${i.spacing.lg} ${i.spacing.xl}`,fontSize:i.typography.fontSize.lg};default:return{}}},ae={borderRadius:l?.button?.borderRadius||i.borderRadius.md,fontWeight:l?.button?.fontWeight||i.typography.fontWeight.medium,fontFamily:l?.button?.fontFamily||i.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||a?"not-allowed":"pointer",opacity:(o||a)&&r!=="outline"?.6:1,width:t?"100%":"auto",display:"flex",alignItems:"center",justifyContent:"center",gap:i.spacing.sm,...te(),...re(),...l?.button?.fontSize&&{fontSize:l.button.fontSize}},P=o||a;return v.jsxs("button",{type:p.type??"button","data-spiceflow-focus":!0,"aria-busy":a||void 0,"aria-disabled":P||void 0,style:{...ae,...d},className:n,disabled:P,onMouseEnter:g=>{T(!0),p.onMouseEnter?.(g)},onMouseLeave:g=>{T(!1),A(!1),p.onMouseLeave?.(g)},onMouseDown:g=>{A(!0),p.onMouseDown?.(g)},onMouseUp:g=>{A(!1),p.onMouseUp?.(g)},...p,children:[a&&v.jsx(ee,{size:16}),s]})};exports.Button=_e,exports.CHAIN_CONFIGS=me,exports.G=j,exports.RELAYER_API_URL=J,exports.SpiceFlowProvider=Te,exports.SpiceFlowProviderContext=X,exports.SpiceflowError=u,exports.Spinner=ee,exports.buildDarkPalette=Ue,exports.buildLightPalette=Ae,exports.createInitialSteps=Ce,exports.createTheme=Q,exports.ensureSmartWallet=$e,exports.getAllAssetsForChain=be,exports.getChainConfig=R,exports.getChainName=I,exports.getChainsForAssets=ye,exports.getClientForChain=Y,exports.getDelegateContractAddress=ge,exports.getExplorerUrl=he,exports.getRpcUrlForChain=F,exports.getTokenDecimals=we,exports.hasReducedFeeOutput=Be,exports.hasStoredSpiceFlowMode=Re,exports.isSpiceflowError=ce,exports.relayerService=w,exports.resolveTheme=Z,exports.useSpiceBrand=K;
|
package/dist/auth-dynamic.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";const e=require("react/jsx-runtime"),c=require("react"),t=require("./Button-
|
|
2
|
+
"use strict";const e=require("react/jsx-runtime"),c=require("react"),t=require("./Button-d9wfO_xs.js"),W=require("@dynamic-labs/sdk-react-core"),k=require("./providerWallet-CIbQEcIP.js");require("@spicenet-io/spiceflow-core"),require("viem"),require("viem/actions");const q=({onAuthSuccess:a,onAuthError:r,theme:h="light",className:i="",buttonText:o="Login with Dynamic",autoTrigger:l=!1})=>{const s=t.createTheme(h),[m,D]=c.useState(!1),[g,S]=c.useState(!1),w=W.useDynamicContext(),{user:E,primaryWallet:f,connectedWallets:b,handleLogOut:C,setShowAuthFlow:x,sdkHasLoaded:p,showAuthFlow:j}=w,n=(k.getDynamicEmbeddedWallet({connectedWallets:b,primaryWallet:f})||f)?.address,v=!!E,d=v&&!!n;c.useEffect(()=>{D(!0)},[]),c.useEffect(()=>{d&&n&&a&&a(n)},[d,n,a]),c.useEffect(()=>{l&&p&&m&&!d&&!j&&!g&&(S(!0),x(!0))},[l,p,m,d,j,g,x]);const N=()=>{try{x(!0)}catch(y){const u=`Dynamic login failed: ${String(y)}`;r?r(u):console.error(u)}},L=async()=>{try{await C()}catch(y){const u=`Dynamic logout failed: ${String(y)}`;r?r(u):console.error(u)}};return m?p?v&&!n?e.jsx("div",{className:i,children:e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px",flexDirection:"column",gap:"12px"},children:[e.jsx(t.Spinner,{size:40,borderWidth:3,color:s.colors.primary}),e.jsx("p",{style:{color:s.colors.textMuted,fontSize:"14px"},children:"Finishing wallet setup..."})]})}):d&&n?e.jsx("div",{className:i,children:e.jsxs(t.Button,{variant:"primary",onClick:L,theme:s,children:["Logout (",n.slice(0,6),"...",n.slice(-4),")"]})}):l?e.jsx("div",{className:i,children:e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px",flexDirection:"column",gap:"12px"},children:[e.jsx(t.Spinner,{size:40,borderWidth:3,color:s.colors.primary}),e.jsx("p",{style:{color:s.colors.textMuted,fontSize:"14px"},children:"Opening login..."})]})}):e.jsx("div",{className:i,children:e.jsx(t.Button,{variant:"primary",onClick:N,theme:s,children:o})}):e.jsx("div",{className:i,children:e.jsx(t.Button,{variant:"primary",disabled:!0,theme:s,children:"Loading..."})}):e.jsx("div",{className:i,children:e.jsx(t.Button,{variant:"primary",disabled:!0,theme:s,children:o})})};class B extends c.Component{constructor(r){super(r),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}render(){return this.state.hasError?this.props.fallback:this.props.children}}const F=a=>{const{theme:r="light",className:h="",buttonText:i="Login with Dynamic",onAuthError:o}=a,l=t.createTheme(r);return e.jsx(B,{fallback:e.jsx("div",{className:h,children:e.jsx(t.Button,{variant:"primary",onClick:()=>{o&&o('DynamicLogin must be used within SpiceFlowProvider provider="dynamic" and a mounted DynamicContextProvider.')},theme:l,children:i})}),children:e.jsx(q,{...a})})};exports.DynamicLogin=F;
|
package/dist/auth-dynamic.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as e,jsxs as g}from"react/jsx-runtime";import A,{useState as N,useEffect as f}from"react";import{B as d,c as S,S as b}from"./Button-
|
|
2
|
+
import{jsx as e,jsxs as g}from"react/jsx-runtime";import A,{useState as N,useEffect as f}from"react";import{B as d,c as S,S as b}from"./Button-BXgazUZN.js";import{useDynamicContext as j}from"@dynamic-labs/sdk-react-core";import{g as z}from"./providerWallet-CVHyIqiI.js";import"@spicenet-io/spiceflow-core";import"viem";import"viem/actions";const M=({onAuthSuccess:a,onAuthError:r,theme:m="light",className:t="",buttonText:o="Login with Dynamic",autoTrigger:s=!1})=>{const i=S(m),[h,C]=N(!1),[x,E]=N(!1),L=j(),{user:W,primaryWallet:v,connectedWallets:k,handleLogOut:F,setShowAuthFlow:p,sdkHasLoaded:u,showAuthFlow:D}=L,n=(z({connectedWallets:k,primaryWallet:v})||v)?.address,w=!!W,l=w&&!!n;return f(()=>{C(!0)},[]),f(()=>{l&&n&&a&&a(n)},[l,n,a]),f(()=>{s&&u&&h&&!l&&!D&&!x&&(E(!0),p(!0))},[s,u,h,l,D,x,p]),h?u?w&&!n?e("div",{className:t,children:g("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px",flexDirection:"column",gap:"12px"},children:[e(b,{size:40,borderWidth:3,color:i.colors.primary}),e("p",{style:{color:i.colors.textMuted,fontSize:"14px"},children:"Finishing wallet setup..."})]})}):l&&n?e("div",{className:t,children:g(d,{variant:"primary",onClick:async()=>{try{await F()}catch(y){const c=`Dynamic logout failed: ${String(y)}`;r?r(c):console.error(c)}},theme:i,children:["Logout (",n.slice(0,6),"...",n.slice(-4),")"]})}):s?e("div",{className:t,children:g("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px",flexDirection:"column",gap:"12px"},children:[e(b,{size:40,borderWidth:3,color:i.colors.primary}),e("p",{style:{color:i.colors.textMuted,fontSize:"14px"},children:"Opening login..."})]})}):e("div",{className:t,children:e(d,{variant:"primary",onClick:()=>{try{p(!0)}catch(y){const c=`Dynamic login failed: ${String(y)}`;r?r(c):console.error(c)}},theme:i,children:o})}):e("div",{className:t,children:e(d,{variant:"primary",disabled:!0,theme:i,children:"Loading..."})}):e("div",{className:t,children:e(d,{variant:"primary",disabled:!0,theme:i,children:o})})};class T extends A.Component{constructor(r){super(r),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}render(){return this.state.hasError?this.props.fallback:this.props.children}}const B=a=>{const{theme:r="light",className:m="",buttonText:t="Login with Dynamic",onAuthError:o}=a,s=S(r);return e(T,{fallback:e("div",{className:m,children:e(d,{variant:"primary",onClick:()=>{o&&o('DynamicLogin must be used within SpiceFlowProvider provider="dynamic" and a mounted DynamicContextProvider.')},theme:s,children:t})}),children:e(M,{...a})})};export{B as DynamicLogin};
|
package/dist/auth-privy.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";const e=require("react/jsx-runtime"),o=require("react"),c=require("./Button-
|
|
2
|
+
"use strict";const e=require("react/jsx-runtime"),o=require("react"),c=require("./Button-d9wfO_xs.js"),f=require("@privy-io/react-auth");require("@spicenet-io/spiceflow-core"),require("viem"),require("viem/actions");const S=({onAuthSuccess:d,onAuthError:a,theme:v="light",className:l="",buttonText:g="Login with Privy",autoTrigger:h=!1})=>{const u=c.createTheme(v),[m,j]=o.useState(!1),[x,p]=o.useState(!1),{ready:i,authenticated:n,user:r}=f.usePrivy(),{login:L}=f.useLogin(),{logout:b}=f.useLogout();o.useEffect(()=>{j(!0)},[]),o.useEffect(()=>{h&&i&&!n&&m&&!x&&(p(!0),y())},[h,i,n,m,x]),o.useEffect(()=>{if(i&&n&&r&&d){const t=r.wallet?.address||r.email?.address;t&&d(t)}},[i,n,r,d]),o.useEffect(()=>{},[i,n,a]);const y=()=>{try{L()}catch(t){const s=`Login failed: ${String(t)}`;a?a(s):console.error(s)}},q=()=>{try{b()}catch(t){const s=`Logout failed: ${String(t)}`;a?a(s):console.error(s)}};if(!m)return e.jsx("div",{className:l,children:e.jsx(c.Button,{variant:"primary",disabled:!0,theme:u,children:g})});if(!i)return e.jsx("div",{className:l,children:e.jsx(c.Button,{variant:"primary",disabled:!0,theme:u,children:"Loading..."})});if(n&&r){const t=r.wallet?.address||r.email?.address,s=t?`${t.slice(0,6)}...${t.slice(-4)}`:"Connected";return e.jsx("div",{className:l,children:e.jsxs(c.Button,{variant:"primary",onClick:q,theme:u,children:["Logout (",s,")"]})})}return h?e.jsx("div",{className:l,children:e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px",flexDirection:"column",gap:"12px"},children:[e.jsx(c.Spinner,{size:40,borderWidth:3,color:"#3b82f6"}),e.jsx("p",{style:{color:"#6b7280",fontSize:"14px"},children:"Opening login..."})]})}):e.jsx("div",{className:l,children:e.jsx(c.Button,{variant:"primary",onClick:y,theme:u,children:g})})};exports.PrivyLogin=S;
|
package/dist/auth-privy.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as r,jsxs as y}from"react/jsx-runtime";import{useState as v,useEffect as c}from"react";import{B as d,c as P,S as $}from"./Button-
|
|
2
|
+
import{jsx as r,jsxs as y}from"react/jsx-runtime";import{useState as v,useEffect as c}from"react";import{B as d,c as P,S as $}from"./Button-BXgazUZN.js";import{usePrivy as j,useLogin as w,useLogout as B}from"@privy-io/react-auth";import"@spicenet-io/spiceflow-core";import"viem";import"viem/actions";const T=({onAuthSuccess:m,onAuthError:n,theme:x="light",className:a="",buttonText:g="Login with Privy",autoTrigger:u=!1})=>{const l=P(x),[h,L]=v(!1),[p,b]=v(!1),{ready:o,authenticated:s,user:t}=j(),{login:S}=w(),{logout:N}=B();c(()=>{L(!0)},[]),c(()=>{u&&o&&!s&&h&&!p&&(b(!0),f())},[u,o,s,h,p]),c(()=>{if(o&&s&&t&&m){const e=t.wallet?.address||t.email?.address;e&&m(e)}},[o,s,t,m]),c(()=>{},[o,s,n]);const f=()=>{try{S()}catch(e){const i=`Login failed: ${String(e)}`;n?n(i):console.error(i)}},C=()=>{try{N()}catch(e){const i=`Logout failed: ${String(e)}`;n?n(i):console.error(i)}};if(!h)return r("div",{className:a,children:r(d,{variant:"primary",disabled:!0,theme:l,children:g})});if(!o)return r("div",{className:a,children:r(d,{variant:"primary",disabled:!0,theme:l,children:"Loading..."})});if(s&&t){const e=t.wallet?.address||t.email?.address,i=e?`${e.slice(0,6)}...${e.slice(-4)}`:"Connected";return r("div",{className:a,children:y(d,{variant:"primary",onClick:C,theme:l,children:["Logout (",i,")"]})})}return u?r("div",{className:a,children:y("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px",flexDirection:"column",gap:"12px"},children:[r($,{size:40,borderWidth:3,color:"#3b82f6"}),r("p",{style:{color:"#6b7280",fontSize:"14px"},children:"Opening login..."})]})}):r("div",{className:a,children:r(d,{variant:"primary",onClick:f,theme:l,children:g})})};export{T as PrivyLogin};
|