@spicenet-io/spiceflow-ui 4.0.14 → 4.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth-privy.cjs.js +1 -1
- package/dist/auth-privy.js +1 -1
- package/dist/components/SpiceDeposit/lib/executors.d.ts +2 -1
- package/dist/components/SpiceLock/lib/executors.d.ts +1 -6
- package/dist/components/SpiceSupply/lib/executors.d.ts +2 -10
- package/dist/components/SpiceSupply/parts/SupplyStepStatusCard.d.ts +20 -0
- package/dist/components/SpiceWithdraw/SpiceWithdraw.d.ts +0 -1
- package/dist/components/SpiceWithdraw/parts/WithdrawBalanceCardHeader.d.ts +12 -0
- package/dist/components/SpiceWithdraw/parts/WithdrawDestinationCard.d.ts +28 -0
- package/dist/components/SpiceWithdraw/parts/WithdrawSourceCard.d.ts +34 -0
- package/dist/components/SpiceWithdraw/parts/WithdrawSubtitle.d.ts +8 -0
- package/dist/components/ui/AmountText.d.ts +0 -1
- package/dist/components/ui/PercentageDial.d.ts +8 -0
- package/dist/components/ui/WarningBanner.d.ts +16 -0
- package/dist/components/ui/icons.d.ts +3 -0
- package/dist/components/ui/index.d.ts +1 -1
- package/dist/execution/externalWalletClient.d.ts +21 -0
- package/dist/execution/fundEmbeddedWallet.d.ts +7 -0
- package/dist/execution/intentSigning.d.ts +12 -0
- package/dist/execution/intentStatus.d.ts +0 -6
- package/dist/execution/pollIntentStep.d.ts +2 -3
- package/dist/hooks/useDebouncedEstimate.d.ts +12 -0
- package/dist/hooks/useLockWalletAssets.d.ts +18 -0
- package/dist/index.cjs.js +21 -44
- package/dist/index.d.ts +7 -11
- package/dist/index.js +25 -48
- package/dist/privy-COlZvldu.js +2 -0
- package/dist/privy-JCBW-mP2.js +2 -0
- package/dist/types/deposit.d.ts +3 -2
- package/dist/types/lock.d.ts +2 -1
- package/dist/types/status.d.ts +1 -0
- package/dist/types/supply.d.ts +6 -1
- package/dist/types/withdraw.d.ts +2 -15
- package/dist/utils/actionOutputEscrowFunding.d.ts +0 -7
- package/dist/utils/amounts.d.ts +1 -0
- package/dist/utils/chains/index.d.ts +0 -1
- package/dist/utils/crossChainRouter/index.d.ts +0 -1
- package/dist/utils/crossChainRouter/liquidityVenues.d.ts +0 -2
- package/dist/utils/crossChainRouter/uniV3.d.ts +0 -4
- package/dist/utils/errors.d.ts +8 -0
- package/dist/utils/logos.d.ts +0 -4
- package/dist/utils/relayer/index.d.ts +4 -1
- package/package.json +2 -16
- package/dist/privy-BdHp5Owr.js +0 -0
- package/dist/privy-Ds5DCgFX.js +0 -0
- package/dist/utils/crossChainRouter/buildIntent.d.ts +0 -34
- package/dist/utils/crossChainRouter/executeSwapThenAction.d.ts +0 -17
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import{jsx as v,jsxs as Y}from"react/jsx-runtime";import{useContext as de,useMemo as L,useRef as ce,useEffect as A,createContext as ue,useState as M,useCallback as De}from"react";import{getChainMeta as fe,getTokensForChain as je,ZERO_ADDRESS as ze,isNativeToken as Q,getDelegateContract as _e,getTokenByAddress as Ge,DELEGATE_ABI as He,ERC20_ABI as Je,spicenetEscrowAbi as Ye,uniV3SwapRouterAbi as Qe,getChainIdsByNetwork as Ve}from"@spicenet-io/spiceflow-core";import{isAddress as R,getAddress as V,defineChain as Xe,createPublicClient as Ke,http as Ze,erc20Abi as et,formatUnits as pe,isHex as tt,decodeErrorResult as rt,hexToString as at,createWalletClient as nt,custom as ot}from"viem";import{readContract as st}from"viem/actions";import{useWallets as me,usePrivy as X,getEmbeddedConnectedWallet as he,useSign7702Authorization as it,useSignMessage as lt,useLogin as dt,useLogout as ct}from"@privy-io/react-auth";import{useAccount as ge}from"wagmi";import{useQuery as ut,useMutation as ft}from"@tanstack/react-query";const pt={base:0,raised:1,sticky:10,overlay:20,popover:40,modal:1e3,dropdown:1100,toast:1200,tooltip:1300},mt={none:"0",sm:"4px",md:"6px",card:"8px",input:"10px",shell:"9px",modal:"12px",pill:"9999px",circle:"50%"},k={out:"cubic-bezier(0.22, 1, 0.36, 1)",inOut:"cubic-bezier(0.65, 0, 0.35, 1)",linear:"linear"},S={fast:"120ms",normal:"150ms",slow:"300ms",progress:"400ms"},ht={interactive:`transform ${S.normal} ${k.out}, box-shadow ${S.normal} ${k.out}, background-color ${S.normal} ${k.out}, border-color ${S.normal} ${k.out}, color ${S.normal} ${k.out}`,color:`background-color ${S.normal} ${k.out}, border-color ${S.normal} ${k.out}, color ${S.normal} ${k.out}`,popover:`opacity ${S.normal} ${k.out}, transform ${S.normal} ${k.out}`},D={ui:'"Helvetica Neue", sans-serif',mono:'"IBM Plex Mono", monospace'};function j(t,e){return!t||!e?!1:R(t)&&R(e)?V(t)===V(e):t.toLowerCase()===e.toLowerCase()}const gt="0xcA11bde05977b3631167028862bE2a173976CA11",yt={4114:"0x860aFc632a6D625B95d8B96f39ECC48E988c6962"},bt=new Set([5115]);function wt(t){const e=yt[t.id]??(bt.has(t.id)?void 0:gt);return Xe({id:t.id,name:t.name,nativeCurrency:t.nativeCurrency,rpcUrls:{default:{http:[t.rpcUrl]}},blockExplorers:{default:{name:t.displayName,url:t.blockExplorer}},testnet:t.network==="testnet",...e?{contracts:{multicall3:{address:e}}}:{}})}const xt=[1,8453,42161,4114,11155111,421614,84532,5115,123420001114,688688,688689],z=Object.fromEntries(xt.map(t=>fe(t)).filter(t=>t!=null).map(t=>[t.id,{...t,viemChain:wt(t),supportedTokens:je(t.id)}])),vt=z;let ye={};const K=new Map,be=t=>{ye={...t||{}},K.clear()},Z=t=>{const e=ye[t];return e&&typeof e=="string"&&e.length>0?e:z[t]?.rpcUrl},W=t=>z[t],ee=t=>{const e=fe(t);return e?.displayName||e?.name||`Chain ${t}`},$t=t=>{const e=_e(t);if(!e)throw new Error(`Unsupported chain ID: ${t}`);return e},Et=(t,e,r)=>{const a=W(t);return a?.blockExplorer?`${a.blockExplorer}/tx/${e}`:"#"};async function Ct(t,e){const r=`0x${e.toString(16)}`;try{await t.request({method:"wallet_switchEthereumChain",params:[{chainId:r}]});return}catch(o){if(!(o?.code===4902||typeof o?.message=="string"&&o.message.includes("Unrecognized chain ID")))throw o}const a=W(e);if(!a)throw new Error(`Cannot add unknown chain ${e} to wallet`);await t.request({method:"wallet_addEthereumChain",params:[{chainId:r,chainName:a.name||`Chain ${e}`,nativeCurrency:a.nativeCurrency||{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:[Z(e)||a.rpcUrl],blockExplorerUrls:a.blockExplorer?[a.blockExplorer]:void 0}]})}const we=t=>{const e=W(t);if(!e)throw new Error(`Unsupported chain ID: ${t}`);const r=Z(t);if(!r)throw new Error(`No RPC URL configured for chain ID: ${t}`);const a=`${t}:${r}`,o=K.get(a);if(o)return o;const n=Ke({chain:e.viemChain,transport:Ze(r,{timeout:15e3,retryCount:2,retryDelay:300}),batch:{multicall:{wait:16}}});return K.set(a,n),n},Bt=()=>{const t={};return Object.values(z).forEach(e=>{t[e.id]={name:e.name,moralisName:e.moralisId||"",chain:e.viemChain,rpcUrl:Z(e.id)||e.rpcUrl}}),t},kt=(t,e=[])=>{const r=W(t);if(!r)return[];const a=[];if(![11155111,421614,84532,688689].includes(t)){const n=e.find(s=>s.chainId===t&&s.isNative);n?a.push(n):a.push({address:ze,name:r.nativeCurrency.name,symbol:r.nativeCurrency.symbol,decimals:r.nativeCurrency.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:void 0,isNative:!0,chainId:t})}if(!r.supportedTokens)return a;const o=a.some(n=>n.isNative);return r.supportedTokens.forEach(n=>{if(o&&Q(n.address))return;const s=e.find(u=>u.chainId===t&&j(u.address,n.address));s?a.push(s):a.push({address:n.address,name:n.name,symbol:n.symbol,decimals:n.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:n.logo,isNative:!1,chainId:t})}),a},St=async(t,e)=>{const r=W(t);if(!r)throw new Error(`Unsupported chain ID: ${t}`);const a=e.toLowerCase();if(Q(a)){if(!r.nativeCurrency?.decimals)throw new Error(`Native currency decimals not configured for chain ${t}`);return r.nativeCurrency.decimals}if(r.supportedTokens){const o=r.supportedTokens.find(n=>j(n.address,a));if(o)return o.decimals}try{if(!R(e,{strict:!1}))throw new Error(`Invalid token address: ${e}`);const o=V(e),n=we(t),s=await st(n,{address:o,abi:et,functionName:"decimals"});return Number(s)}catch{throw new Error(`Could not determine decimals for token ${e} on chain ${t}`)}};class I extends Error{constructor(e,r,a={}){super(r),this.code=e,this.context=a,this.name="SpiceflowError",Error.captureStackTrace&&Error.captureStackTrace(this,I)}}function te(t){return t instanceof I}const It=["user rejected","user denied","user cancelled","rejected the request","action_rejected","4001"];function xe(t){if(!t)return"";if(typeof t=="string")return t;const e=t,r=e.message||e.reason||"",a=e.details||"";return`${r} ${a}`.trim()}const ve=t=>{if(te(t))return t.code==="WALLET_REJECTED";const e=xe(t).toLowerCase();return It.some(r=>e.includes(r))};let re=null;function Tt(t){return re?.message===t?re.detail:void 0}const At=(t,e="Something went wrong. Please try again.")=>{if(ve(t))return"Transaction was rejected.";if(te(t)){const r=t.message||e,{requestId:a,httpStatus:o,responseBody:n,endpoint:s}=t.context;return(a||o||s)&&(re={message:r,detail:{requestId:a,httpStatus:o,responseBody:n,endpoint:s}}),r}return xe(t)||e},Pt=[...He,...Je,...Ye,...Qe];function ae(t,e=0){return e>4||t==null?[]:typeof t=="string"?t.match(/0x[0-9a-fA-F]{8,}/g)??[]:Array.isArray(t)?t.flatMap(r=>ae(r,e+1)):typeof t=="object"?Object.values(t).flatMap(r=>ae(r,e+1)):[]}function $e(t){try{const e=rt({abi:Pt,data:t});if(e.errorName==="Error")return String(e.args?.[0]??"");if(e.errorName==="Panic")return`Panic(${e.args?.[0]})`;if(e.errorName==="CallReverted"){const r=e.args?.[4],a=r&&r!=="0x"?$e(r):void 0;return a?`Call reverted: ${a}`:"Call reverted (no reason returned)"}return e.errorName}catch{try{const e=at(t).replace(/\x00+$/g,"").trim();return/^[\x20-\x7e]+$/.test(e)&&e.length>1?e:void 0}catch{return}}}function Rt(t){for(const e of ae(t)){if(!tt(e))continue;const r=$e(e);if(r)return r}}function Wt(t,e){const r=e.match(/Output amount (\d+) is insufficient after fees (\d+) on chain (\d+)/);if(!r)return e;const[,a,o,n]=r,s=Number(n),u=BigInt(a),h=BigInt(o);let l;for(const w of t.intents){const g=w.chainBatches.find(f=>f.chainId===s);if(g){l=g;break}}const m=l?.tokenTransfers.find(w=>w.from==="escrow"&&j(w.to,t.user)&&!Q(w.token)),i=ee(s);if(!m)return`Amount is too small to cover the estimated fee on ${i}.`;const c=Ge(m.token,s),p=c?.decimals??18,y=c?.symbol??"tokens",d=pe(u,p),x=pe(h,p);return`Amount is too small to cover the estimated fee on ${i}. Amount: ${d} ${y}. Estimated fee: ${x} ${y}.`}function Ut(t){return t?.code===4902||t?.name==="ChainNotConfiguredError"?"This network is not configured in your wallet. Please add it manually to continue.":t?.code===4001?"Network switch cancelled. Please switch manually in your wallet to continue.":"Unable to switch network. Please switch manually in your wallet to continue."}const Nt="https://tx-submission-api.spicenet.io",Ee=Nt;function Ft(t,e){return typeof e=="bigint"?e.toString():e}async function _(t,e){const r={...e?.headers},a=r["x-request-id"]??crypto.randomUUID();r["x-request-id"]=a;const o=await fetch(t,{...e,headers:r}),n=o.headers.get("x-request-id")??"";return Object.assign(o,{requestId:n})}function q(t,e){if(!t)return e;const r=t.error,a=(typeof t.message=="string"?t.message:"")||(r&&typeof r=="object"&&"message"in r&&typeof r.message=="string"?r.message:"")||(typeof r=="string"?r:"")||e,o=Rt(t);return o&&!a.includes(o)?`${a} \u2014 ${o}`:a}async function Lt(t){try{return await t.json()}catch{return null}}function Mt(t){return(Array.isArray(t?.balances)?t.balances:[]).flatMap(e=>{if(!e||typeof e!="object")return[];const r=e;return[{receiptToken:typeof r.receiptToken=="string"?r.receiptToken:void 0,tokenName:String(r.tokenName??""),balanceAvailable:String(r.balanceAvailable??"0"),chainTokens:Array.isArray(r.chainTokens)?r.chainTokens.filter(a=>typeof a=="string"):r.chainTokens&&typeof r.chainTokens=="object"?r.chainTokens:r.chainTokenConfig&&typeof r.chainTokenConfig=="object"?r.chainTokenConfig:void 0,decimals:typeof r.decimals=="number"?r.decimals:void 0,balanceUsd:typeof r.balanceUsd=="number"||typeof r.balanceUsd=="string"?r.balanceUsd:null}]})}class qt{constructor(){this.baseUrl=Ee}setBaseUrl(e){this.baseUrl=e}getBaseUrl(){return this.baseUrl}async requestJson(e,r){const a=`${this.baseUrl}${e}`,o=await _(a,r.method&&r.method!=="GET"?{method:r.method,headers:{"Content-Type":"application/json"},body:JSON.stringify(r.body,Ft)}:void 0),n=await o.json();if(!o.ok||n.success===!1||r.ok&&!r.ok(n)){const s=q(n,r.fallbackError(o.status));throw new I(r.code??"RELAYER_ERROR",r.mapError?r.mapError(s):s,{httpStatus:o.status,requestId:o.requestId,responseBody:JSON.stringify(n),endpoint:e,...r.context})}return n}async createAction(e){return this.requestJson("/actions",{method:"POST",body:e,fallbackError:r=>`Relayer API error: ${r}`})}async estimateActionFees(e){return(await this.requestJson("/actions/fees/estimate",{method:"POST",body:e,fallbackError:r=>`Relayer fee estimate error: ${r}`,ok:r=>!!r.success&&!!r.data?.feeEstimate,mapError:r=>Wt(e,r)})).data.feeEstimate}async estimateBatchGas(e){const r=await this.requestJson("/actions/gas/estimate",{method:"POST",body:e,fallbackError:a=>`Relayer gas estimate error: ${a}`,ok:a=>!!a.success&&!!a.data?.gasFee});return{gasFee:BigInt(r.data.gasFee),gasQuoteSource:r.data.gasQuoteSource}}async executeStep(e,r,a,o){const n=`${this.baseUrl}/actions/${e}/intents/${r}/steps/${a}`,s=`/actions/${e}/intents/${r}/steps/${a}`,u=crypto.randomUUID(),h=3e4,l=new Promise((c,p)=>setTimeout(()=>p(new I("RELAYER_EXECUTE_ERROR",`Execute step request timed out after ${h/1e3}s`,{actionId:e,intentIndex:r,stepIndex:a,endpoint:s,requestId:u})),h)),m=await Promise.race([_(n,{method:"POST",headers:{"Content-Type":"application/json","x-request-id":u},body:JSON.stringify(o)}),l]),i=await m.json();if(!m.ok||i.success===!1)throw new I("RELAYER_EXECUTE_ERROR",q(i,`Execute step error: ${m.status}`),{httpStatus:m.status,requestId:m.requestId,responseBody:JSON.stringify(i),endpoint:s,actionId:e});if(i?.status==="error"||i?.status==="reverted"){const c=q(i,""),p=c?`: ${c}`:"";throw new I("RELAYER_EXECUTE_ERROR",`Step ${a} previously ${i.status}${p}`,{httpStatus:m.status,requestId:m.requestId,responseBody:JSON.stringify(i),endpoint:s,actionId:e,intentIndex:r,stepIndex:a,stepStatus:i.status})}return{success:!0,transactionHash:i.transactionHash}}async checkStepStatus(e,r){const a=e.split("/"),o=a[0],n=a.length>=2?a[1]:"0",s=await this.requestJson(`/actions/${o}/intents/${n}/steps/${r}`,{fallbackError:u=>`Intent step status check failed: ${u}`,code:"RELAYER_STATUS_ERROR",context:{intentId:e}});return{success:!0,data:{status:s.status==="error"?"reverted":s.status,transactionHash:s.txid,error:q(s,"")}}}async createWallet(e,r){return this.requestJson(`/wallets/${e}`,{method:"PUT",body:r,fallbackError:a=>`Create wallet error: ${a}`})}async getWallet(e){return this.requestJson(`/wallets/${e}`,{fallbackError:r=>`Get wallet error: ${r}`})}async createWithdrawal(e){return this.requestJson("/withdrawals",{method:"POST",body:e,fallbackError:r=>`Create withdrawal error: ${r}`})}async getWithdrawal(e){return this.requestJson(`/withdrawals/${e}`,{fallbackError:r=>`Get withdrawal error: ${r}`})}async getRollupTimestamp(){return this.requestJson("/time",{fallbackError:e=>`Get rollup timestamp error: ${e}`})}}const P=new qt;async function Ot(t){const e=`${P.getBaseUrl()}/wallets/${t}/balance`,r=await _(e,{cache:"no-store"}),a=await Lt(r);if(!r.ok||a?.success===!1)throw new I("RELAYER_ERROR",q(a,`Unable to verify Spice balance: ${r.status}`),{httpStatus:r.status,requestId:r.requestId,responseBody:JSON.stringify(a),endpoint:`/wallets/${t}/balance`});return Mt(a)}const ne=new Map,Dt="spiceflow.smartWallet.";function Ce(t){return`${Dt}${t.toLowerCase()}`}function jt(t){try{return typeof localStorage<"u"&&localStorage.getItem(Ce(t))==="1"}catch{return!1}}function Be(t){try{typeof localStorage<"u"&&localStorage.setItem(Ce(t),"1")}catch{}}function zt(t){if(!(t instanceof I))return!1;const e=t.context.httpStatus;return e===400||e===404?`${t.message} ${String(t.context.responseBody??"")}`.toLowerCase().includes("not found"):!1}async function ke(t,e){if(jt(t))return;const r=t.toLowerCase(),a=ne.get(r);if(a)return a;const o=(async()=>{try{await P.getWallet(t),Be(t);return}catch(l){if(!zt(l))throw l}const{unix_timestamp:n}=await P.getRollupTimestamp(),s=`I am creating a new smart wallet and adding an admin wallet ethereum:0x${t.slice(2).toLowerCase()}. Nonce: ${n}`,u=await e(s),h=typeof u=="string"?u:u.signature;if(!h)throw new Error("Wallet returned no smart wallet signature");await P.createWallet(t,{timestamp:n,signature:h}),Be(t)})();ne.set(r,o);try{await o}finally{ne.delete(r)}}const _t=(t,e)=>{const r=o=>e?e(o):ee(o),a=[];return t.forEach((o,n)=>{const s=o.calls&&o.calls.length>0,u=o.tokenTransfers&&o.tokenTransfers.length>0;!s&&!u||a.push({stepId:n,status:n===0?"processing":"pending",chainId:o.chainId,chainName:r(o.chainId),description:"Processing transaction"})}),a},Gt=t=>{const e=t?.wallet;if(e?.address&&e.walletClientType==="privy"&&e.connectorType==="embedded"&&!e.imported)return e.address},Se=async(t,e)=>{if(!t?.address)throw new Error("Wallet not available");if(typeof t.getWalletClient=="function"){const r=e===void 0?[void 0]:[String(e),e,void 0];let a=null;for(const o of r)try{const n=await t.getWalletClient(o);if(n)return n}catch(n){a=n}if(a)throw a}if(typeof t.getEthereumProvider=="function"){const r=await t.getEthereumProvider(),a=e?W(e)?.viemChain:void 0;return nt({account:t.address,chain:a,transport:ot(r)})}throw new Error("Wallet client not available")},Ht=async(t,e)=>{if(!t?.address)throw new Error("Wallet not available");if(typeof t.getEthereumProvider=="function")return t.getEthereumProvider();const r=await Se(t,e);return{request:a=>r.request(a)}},G=t=>t?.address?{address:t.address,wallet:t,getWalletClient:e=>Se(t,e),getEthereumProvider:e=>Ht(t,e)}:null,oe=()=>{const{address:t,connector:e}=ge();let r=null,a=null;try{r=me(),{user:a}=X()}catch{r=null,a=null}const o=r?.wallets||[],n=he(o),s=n?.address?.toLowerCase(),u=o.find(d=>d.connectorType!=="embedded"&&d.address?.toLowerCase()!==s),h=t?.toLowerCase(),l=t&&e&&!(h&&s&&h===s)?{address:t,connector:e,getEthereumProvider:()=>e.getProvider()}:null,m=t&&e?{address:t,connector:e,getEthereumProvider:()=>e.getProvider()}:null,i=G(n),c=G(l)||G(u),p=i?.address||Gt(a),y=G(m)||c;return{embeddedWallet:i,externalWallet:c,embeddedAddress:p,externalAddress:c?.address,activeWallet:y,activeAddress:y?.address}},Ie=()=>{const t=de(H),e=t?.mode,{isConnected:r,address:a}=ge();let o=null,n=null,s=null,u=null,h=null;try{o=X(),n=it(),s=lt(),u=me()}catch(f){h=f instanceof Error?f.message:String(f)}if(h)return e==="ondemand"&&r&&a?{isReady:!0,isAuthenticated:!0,isConnected:!0,address:a,provider:"privy",actions:{signAuthorization:async()=>{throw new Error("Not available in ondemand mode")},signMessage:async()=>{throw new Error("Not available in ondemand mode")},getEthereumProvider:async()=>{throw new Error("Not available in ondemand mode")}}}:{isReady:!1,isAuthenticated:!1,isConnected:!1,provider:null,actions:{signAuthorization:async()=>{throw new Error("Privy not available")},signMessage:async()=>{throw new Error("Privy not available")},getEthereumProvider:async()=>{throw new Error("Privy not available")}}};const{ready:l=!1,authenticated:m=!1}=o||{},i=t?.embeddedWalletAddress,c=he(u?.wallets||[]),p=i||c?.address,y=!!p&&!!c,d={isReady:e==="ondemand"?!0:l,isAuthenticated:e==="ondemand"?!0:m||y,isConnected:e==="ondemand"?r&&!!a||l&&(m||y)&&y:l&&y,address:e==="ondemand"&&r?a:p,provider:"privy"},x=async f=>{if(!c)throw new Error("Embedded wallet not available");const b=await c.getEthereumProvider(),{createWalletClient:$,custom:B}=await import("viem");return{signature:await $({account:c.address,transport:B(b)}).signMessage({account:c.address,message:f})}},w=async f=>{if(s)try{return{signature:(await s.signMessage({message:f})).signature}}catch(b){if(!c)throw b}if(!c)throw new Error("Privy sign message not available");return x(f)},g=async()=>{if(!p)throw new Error("Embedded wallet not available for smart wallet setup");await ke(p,w)};return{...d,actions:{signAuthorization:async f=>{if(!n)throw new Error("Privy sign authorization not available");try{await g();const b=await n.signAuthorization({contractAddress:f.contractAddress,chainId:f.chainId,nonce:f.nonce},{address:p});return delete b.v,b}catch(b){const $=typeof b?.message=="string"?b.message:String(b?.message??b??"");throw $.includes("not configured")||$.includes("chain")?new Error(`Chain ${f.chainId} is not configured in PrivyProvider. Add this chain to your Privy dashboard or supportedChainIds.`):b}},signMessage:async f=>{if(typeof f=="object"&&"raw"in f){if(await g(),!c)throw new Error("Embedded wallet not available for raw signing");return x(f)}return w(f)},getEthereumProvider:async()=>{if(!c)throw new Error("Embedded wallet not available");return c.getEthereumProvider()}}}},Jt="https://portal-api.spicenet.io/api/v1",se=t=>t.replace(/\/+$/,""),Yt=(t,e)=>`${t}:${e}`;async function Qt(t,e){const r=new URLSearchParams({walletAddress:e,campaignId:"spicenet-portal",campaignGroup:"1"}),a=await fetch(`${t}/portal/mainnet/linked-portal-wallet?${r.toString()}`,{cache:"no-store"});if(!a.ok){if(a.status>=500){const o=new Error(`Failed to resolve linked portal wallet: ${a.status}`);throw o.status=a.status,o}return null}return(await a.json()).portalWalletAddress?.toLowerCase()??null}async function Vt(t,e,r){const a=new URLSearchParams({walletAddress:e,campaignId:r.campaignId,campaignGroup:r.campaignGroup,partnerId:r.partnerId}),o=await fetch(`${t}/portal/mainnet/whitelist/check?${a.toString()}`,{cache:"no-store"});if(!o.ok){const n=new Error(`Failed to check whitelist: ${o.status}`);throw n.status=o.status,n}return await o.json()}async function Xt(t,e,r,a){const o=await fetch(`${t}/portal/mainnet/link-wallet`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({campaignId:e.campaignId,campaignGroup:e.campaignGroup,partnerId:e.partnerId,externalWalletAddress:r,embeddedWalletAddress:a})});if(!o.ok)throw new Error(`Failed to link wallet: ${o.status}`)}function Te({walletAddress:t,campaignId:e,campaignGroup:r,partnerId:a,apiBaseUrl:o=Jt,enabled:n=!0,staleTime:s=5*60*1e3,refetchInterval:u=!1}={}){const{isAuthenticated:h,isConnected:l}=Ie(),{externalAddress:m,embeddedAddress:i}=oe(),c=t??m,p=typeof c=="string"?c.toLowerCase():void 0,y=typeof i=="string"?i.toLowerCase():void 0,d=typeof m=="string"?m.toLowerCase():void 0,x=n&&h&&l&&!!m&&!!p&&R(p)&&!!e&&!!r&&!!a,w=L(()=>["partner-whitelist","check",p,e,r,a,se(o)],[p,e,r,a,o]),g=ut({queryKey:w,enabled:x,staleTime:s,refetchInterval:u,retry:(E,U)=>{const T=U?.status;return typeof T=="number"&&T>=400&&T<500?!1:E<3},retryDelay:E=>Math.min(1e3*2**E,15e3),queryFn:async()=>{if(!p||!R(p))throw new Error("A valid wallet address is required");if(!e||!r||!a)throw new Error("campaignId, campaignGroup, and partnerId are required");const E=se(o),U={campaignId:e,campaignGroup:r,partnerId:a},T=await Qt(E,p);return T?Vt(E,T,U):{walletAddress:p,campaignId:e,campaignGroup:r,partnerId:a,isWhitelisted:!1,isLinkedWallet:!1,whitelistedWalletAddress:null,externalWalletAddress:p}}}),f=n&&h&&l&&!!d&&R(d)&&!!y&&R(y)&&!!e&&!!r&&!!a,b=ft({mutationFn:E=>Xt(se(o),{campaignId:e,campaignGroup:r,partnerId:a},E.external,E.embedded)}),$=ce(new Set),B=b.mutate;return A(()=>{if(!f||!d||!y||!e||!r||!a)return;const E=Yt(d,y);$.current.has(E)||($.current.add(E),B({external:d,embedded:y}))},[f,d,y,e,r,a,B]),{isWhitelisted:g.data?.isWhitelisted??!1,whitelistCheck:g.data,checkedWalletAddress:p,externalWalletAddress:m,embeddedWalletAddress:i,isExternalWalletConnected:!!m,isWhitelistCheckEnabled:x,linkWallet:b,isWalletLinked:b.isSuccess,...g}}const Kt=["__spicenet_whitelist_blocked__"],Ae="spiceflow-mode",Pe=()=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Ae);return t==="7702"?"7702":t==="non7702"?"ondemand":t==="embedded"?"7702":t==="external"?"ondemand":null}catch{return null}},Zt=t=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Ae,t==="7702"?"7702":"non7702")}catch{}},er=()=>Pe()!==null,Re=ue(null),H=ue(null),tr=({children:t,value:e,whitelist:r})=>{const a=!!r&&r.enabled!==!1,{isWhitelisted:o,isLoading:n,whitelistCheck:s}=Te(a?r:{enabled:!1}),u=a&&!o,h=L(()=>({...e,mode:u?"ondemand":e.mode,allowedTokens:u?Kt:e.allowedTokens,isUserWhitelisted:o,isWhitelistChecking:n,isWhitelistConfigured:a,isWhitelistGateActive:u,whitelistCheck:s}),[e,a,u,o,n,s]);return v(H.Provider,{value:h,children:t})},rr=({children:t,provider:e="privy",supportedChainIds:r,allowedTokens:a,network:o="testnet",mode:n,skipFlow:s=[],nativeChainId:u,appName:h="Spicenet",apiUrl:l,theme:m,rpcOverrides:i,whitelist:c})=>{A(()=>{if(!l)return;const B=P.getBaseUrl();return P.setBaseUrl(l),()=>P.setBaseUrl(B)},[l]),A(()=>(be(i),()=>be(void 0)),[i]);const p=L(()=>Ve(o),[o]),y=r??p,d=m??null,[x,w]=M(()=>n??Pe()??"7702");A(()=>{n&&w(n)},[n]);const g=De(B=>{if(n){w(n);return}w(B),Zt(B)},[n]),{embeddedAddress:f,externalAddress:b}=oe(),$=L(()=>({provider:e,supportedChainIds:y,allowedTokens:a,skipFlow:s,mode:x,setMode:g,network:o,nativeChainId:u,appName:h,apiUrl:l,rpcOverrides:i,embeddedWalletAddress:f,externalWalletAddress:b,isUserWhitelisted:null,isWhitelistChecking:!1,isWhitelistConfigured:!1,isWhitelistGateActive:!1}),[e,y,a,s,x,g,o,u,h,l,i,f,b]);return v(Re.Provider,{value:d,children:v(H.Provider,{value:$,children:v(tr,{value:$,whitelist:c,children:t})})})},ar={spacing:{xs:"0.25rem",sm:"0.5rem",md:"1rem",lg:"1.5rem",xl:"2rem"},borderRadius:{sm:"0.25rem",md:"0.5rem",lg:"0.75rem",full:"9999px"},typography:{fontFamily:D.ui,fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.75rem"},fontWeight:{normal:400,medium:500,semibold:600,bold:700}},shadows:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1)"},animation:{fast:"150ms ease-in-out",normal:"200ms ease-in-out",slow:"300ms ease-in-out"}},nr={primary:"#EA4B4B",primaryHover:"#E43838",secondary:"#f3f4f6",background:"#ffffff",surface:"#f9fafb",surfaceHover:"#f3f4f6",border:"#e5e7eb",borderHover:"#d1d5db",text:"#111827",textSecondary:"#374151",textMuted:"#6b7280",success:"#10b981",error:"#ef4444",warning:"#f59e0b",info:"#3b82f6"},or={primary:"#EA4B4B",primaryHover:"#E43838",secondary:"#171717",background:"#141414",surface:"#1e1e1e",surfaceHover:"#2a2a2a",border:"#2d2d2d",borderHover:"#3a3a3a",text:"#ffffff",textSecondary:"#888888",textMuted:"#666666",success:"#10b981",error:"#ef4444",warning:"#f59e0b",info:"#3b82f6"},We=(t="light")=>({mode:t,...ar,colors:t==="light"?nr:or});function J(t,e){const r=t.replace("#",""),a=Math.max(0,Math.round(parseInt(r.substring(0,2),16)*(1-e))),o=Math.max(0,Math.round(parseInt(r.substring(2,4),16)*(1-e))),n=Math.max(0,Math.round(parseInt(r.substring(4,6),16)*(1-e)));return`#${a.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`}function sr(t,e){return{shell:e?.shell??"#141414",shellBorder:e?.shellBorder??J(e?.shell??"#141414",.35),shellInnerBorder:e?.shellInnerBorder??J(e?.shell??"#141414",.55),cardBg:e?.cardBg??"#1e1e1e",inputBg:e?.inputBg??"#171717",hoverBg:e?.hoverBg??"#2a2a2a",textPrimary:e?.textPrimary??"#ffffff",textSecondary:e?.textSecondary??"#888888",inputText:e?.inputText??"#e0e0e0",inputPlaceholder:e?.inputPlaceholder??"#555555",cardBorder:e?.cardBorder??"rgba(255,255,255,0.08)",inputBorder:e?.inputBorder??"rgba(255,255,255,0.10)",buttonBorder:e?.buttonBorder??"rgba(255,255,255,0.12)",successBg:e?.successBg??"#0a1f18",successBorder:e?.successBorder??"#1a4a3a",successText:e?.successText??"#6ee7b7",warningBg:e?.warningBg??"#1f1a0d",warningBorder:e?.warningBorder??"#4a3820",warningText:e?.warningText??"#fbbf24",errorBg:e?.errorBg??"#1f0d0d",errorBorder:e?.errorBorder??"#4a2020",errorText:e?.errorText??"#f87171",infoBg:e?.infoBg??"#0d1325",infoBorder:e?.infoBorder??"#2a3a5a",infoText:e?.infoText??"#60a5fa"}}function ir(t){return{shell:"#ffffff",shellBorder:"#E9E9E9",shellInnerBorder:"#D5D5D5",cardBg:"#f9fafb",inputBg:"#ffffff",hoverBg:"#f3f4f6",textPrimary:"#111827",textSecondary:"#6b7280",inputText:"#111827",inputPlaceholder:"#9ca3af",cardBorder:"#e5e7eb",inputBorder:"#d1d5db",buttonBorder:"#0e0d0b",successBg:"#d1fae5",successBorder:"#6ee7b7",successText:"#065f46",warningBg:"#fef3c7",warningBorder:"#fde68a",warningText:"#92400e",errorBg:"#fef2f2",errorBorder:"#fecaca",errorText:"#dc2626",infoBg:"#dbeafe",infoBorder:"#93c5fd",infoText:"#1e40af"}}function Ue(t,e){const r=e?{...t,...e}:t,a=r.dark??!1,o=r.primaryColor,n=r.shell??(a?"#141414":"#ffffff");return{primaryColor:o,dark:a,fontFamily:r.fontFamily??'"Helvetica Neue", sans-serif',appName:r.appName??"Spicenet",logo:r.logo,borderRadius:r.borderRadius??"8px",shell:n,shellBorder:J(n,a?.35:.085),shellInnerBorder:J(n,a?.55:.165),card:r.card??(a?"#1e1e1e":"#f9fafb"),input:a?"#171717":"#ffffff",hover:a?"#2a2a2a":"#f3f4f6",text:r.text??(a?"#ffffff":"#111827"),textMuted:r.textMuted??(a?"#888888":"#6b7280"),inputText:a?"#e0e0e0":"#111827",inputPlaceholder:a?"#555555":"#9ca3af",border:r.border??(a?"rgba(255,255,255,0.08)":"#e5e7eb"),inputBorder:a?"rgba(255,255,255,0.10)":"#d1d5db",buttonBorder:a?"rgba(255,255,255,0.12)":"#0e0d0b",successBg:a?"#0a1f18":"#d1fae5",successBorder:a?"#1a4a3a":"#6ee7b7",successText:a?"#6ee7b7":"#065f46",warningBg:a?"#1f1a0d":"#fef3c7",warningBorder:a?"#4a3820":"#fde68a",warningText:a?"#fbbf24":"#92400e",errorBg:a?"#1f0d0d":"#fef2f2",errorBorder:a?"#4a2020":"#fecaca",errorText:a?"#f87171":"#dc2626",infoBg:a?"#0d1325":"#dbeafe",infoBorder:a?"#2a3a5a":"#93c5fd",infoText:a?"#60a5fa":"#1e40af"}}const lr=D.mono;function Ne(t,e){const r=de(Re)??void 0;return L(()=>{const a=r??{primaryColor:"#EA4B4B"},o={...t?.primaryColor?{primaryColor:t.primaryColor}:{},...t?.fontFamily?{fontFamily:t.fontFamily}:{},...e!==void 0?{dark:e}:{}},n=Ue(a,o),{dark:s,primaryColor:u,appName:h}=n,l=We(s?"dark":"light"),m={...l,colors:{...l.colors,primary:u,primaryHover:`${u}dd`},typography:{...l.typography,fontFamily:n.fontFamily}},i={shell:n.shell,shellBorder:n.shellBorder,shellInnerBorder:n.shellInnerBorder,cardBg:n.card,inputBg:n.input,hoverBg:n.hover,textPrimary:n.text,textSecondary:n.textMuted,inputText:n.inputText,inputPlaceholder:n.inputPlaceholder,cardBorder:n.border,inputBorder:n.inputBorder,buttonBorder:n.buttonBorder,successBg:n.successBg,successBorder:n.successBorder,successText:n.successText,warningBg:n.warningBg,warningBorder:n.warningBorder,warningText:n.warningText,errorBg:n.errorBg,errorBorder:n.errorBorder,errorText:n.errorText,infoBg:n.infoBg,infoBorder:n.infoBorder,infoText:n.infoText},c=t?.inputVariant?t.inputVariant==="dark":s;return{brand:r,theme:m,dark:s,appName:h,primaryColor:u,dk:i,palette:i,fontFamily:n.fontFamily,monoFont:lr,inputDark:c,cardBg:c?i.cardBg:"#E9E9E9",cardBorder:c?i.cardBorder:"#C6C6C6",textPrimary:i.textPrimary,textSecondary:i.textSecondary,subtitleText:c?i.textSecondary:"#979AA0"}},[r,t,e])}const dr=(t,e=4)=>!isFinite(t)||t===0?"0":t>0&&t<1e-6?t.toFixed(12).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""):t<1e-4?t.toFixed(8).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""):t.toFixed(e).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""),cr=t=>isFinite(t)?t>0&&t<.01?"<$0.01":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(t):"$0.00",Fe=(t,e=6,r=4)=>t.length<=e+r?t:`${t.slice(0,e)}...${t.slice(-r)}`,ur=(t,e)=>{const r=t.replace(/[^0-9.]/g,"").split("."),a=r[0]??"",o=r.slice(1).join(""),n=typeof e=="number"?Math.max(0,Math.min(e,18)):null;return r.length===1?a:`${a}.${n===null?o:o.slice(0,n)}`},fr=(t,e=6)=>!Number.isFinite(t)||t<=0?"0":t.toFixed(Math.min(Math.max(e,0),18)).replace(/\.?0+$/,""),pr=async t=>{try{return await navigator.clipboard.writeText(t),!0}catch(e){return console.error("Failed to copy to clipboard:",e),!1}},Le="spiceflow-spinner-keyframes";function mr(){if(typeof document>"u"||document.getElementById(Le))return;const t=document.createElement("style");t.id=Le,t.textContent="@keyframes spiceflow-spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}",document.head.appendChild(t)}const ie=({size:t=16,borderWidth:e=2,color:r="currentColor",style:a})=>{const o=ce(!1);return A(()=>{o.current||(mr(),o.current=!0)},[]),v("div",{role:"status","aria-label":"Loading",style:{width:`${t}px`,height:`${t}px`,border:`${e}px solid ${r}`,borderTop:`${e}px solid transparent`,borderRadius:"50%",animation:"spiceflow-spin 1s linear infinite",flexShrink:0,...a}})},O=({variant:t="primary",size:e="md",loading:r=!1,fullWidth:a=!1,disabled:o,children:n,className:s="",style:u,theme:h,styles:l,dark:m,...i})=>{const{theme:c,dark:p,palette:y}=Ne(l,m),d=h||c,x=m??p,[w,g]=M(!1),[f,b]=M(!1),$=x?y.shell:"white",B=()=>{switch(t){case"primary":return{backgroundColor:l?.button?.backgroundColor||d.colors.primary,color:l?.button?.color||"#ffffff",border:`1px solid ${l?.button?.backgroundColor||d.colors.primary}`};case"secondary":return{backgroundColor:d.colors.secondary,color:d.colors.text,border:`1px solid ${d.colors.border}`};case"success":return{backgroundColor:d.colors.success,color:d.colors.text,border:`1px solid ${d.colors.success}`};case"error":return{backgroundColor:d.colors.error,color:d.colors.text,border:`1px solid ${d.colors.error}`};case"ghost":return{backgroundColor:"transparent",color:d.colors.textSecondary,border:`1px solid ${d.colors.border}`};case"outline":{const C=l?.button?.backgroundColor||d.colors.primary,le=l?.button?.color||(x?"#ffffff":"#0e0d0b"),N=l?.button?.borderColor||(x?`${d.colors.primary}88`:"#0e0d0b"),F=o||r,Me=x?"1px":"1.5px",qe=l?.button?.disabledBackgroundColor||`${C}88`,Oe=l?.button?.disabledColor||le;return{height:"56px",backgroundColor:F?qe:f?`${C}cc`:w?`${C}ee`:C,color:F?Oe:le,border:`${Me} solid ${N}`,borderRadius:l?.button?.borderRadius||"12px",fontSize:"22px",fontWeight:500,fontFamily:D.mono,opacity:F?.78:1,transform:F?"none":f?"scale(0.98)":w?"translateY(-2px)":"none",boxShadow:F?`3px 3px 0px ${$}, 4px 4px 0px ${N}`:f?`2px 2px 0px ${N}`:w?`5px 5px 0px ${$}, 6px 6px 0px ${N}`:`3px 3px 0px ${$}, 4px 4px 0px ${N}`,transition:"transform 150ms ease, box-shadow 150ms ease, background-color 150ms ease, border-color 150ms ease, color 150ms ease"}}default:return{}}},E=()=>{if(t==="outline")return{};switch(e){case"sm":return{padding:`${d.spacing.sm} ${d.spacing.md}`,fontSize:d.typography.fontSize.sm};case"md":return{padding:`${d.spacing.md} ${d.spacing.lg}`,fontSize:d.typography.fontSize.base};case"lg":return{padding:`${d.spacing.lg} ${d.spacing.xl}`,fontSize:d.typography.fontSize.lg};default:return{}}},U={borderRadius:l?.button?.borderRadius||d.borderRadius.md,fontWeight:l?.button?.fontWeight||d.typography.fontWeight.medium,fontFamily:l?.button?.fontFamily||d.typography.fontFamily,fontSize:l?.button?.fontSize||void 0,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease, opacity 150ms ease",cursor:o||r?"not-allowed":"pointer",opacity:(o||r)&&t!=="outline"?.6:1,width:a?"100%":"auto",display:"flex",alignItems:"center",justifyContent:"center",gap:d.spacing.sm,...B(),...E(),...l?.button?.fontSize&&{fontSize:l.button.fontSize}},T=o||r;return Y("button",{type:i.type??"button","data-spiceflow-focus":!0,"aria-busy":r||void 0,"aria-disabled":T||void 0,style:{...U,...u},className:s,disabled:T,onMouseEnter:C=>{g(!0),i.onMouseEnter?.(C)},onMouseLeave:C=>{g(!1),b(!1),i.onMouseLeave?.(C)},onMouseDown:C=>{b(!0),i.onMouseDown?.(C)},onMouseUp:C=>{b(!1),i.onMouseUp?.(C)},...i,children:[r&&v(ie,{size:16}),n]})},hr=({onAuthSuccess:t,onAuthError:e,theme:r="light",className:a="",buttonText:o="Login with Privy",autoTrigger:n=!1})=>{const s=We(r),[u,h]=M(!1),[l,m]=M(!1),{ready:i,authenticated:c,user:p}=X(),{login:y}=dt(),{logout:d}=ct();A(()=>{h(!0)},[]),A(()=>{n&&i&&!c&&u&&!l&&(m(!0),x())},[n,i,c,u,l]),A(()=>{if(i&&c&&p&&t){const g=p.wallet?.address||p.email?.address;g&&t(g)}},[i,c,p,t]),A(()=>{},[i,c,e]);const x=()=>{try{y()}catch(g){const f=`Login failed: ${String(g)}`;e?e(f):console.error(f)}},w=()=>{try{d()}catch(g){const f=`Logout failed: ${String(g)}`;e?e(f):console.error(f)}};if(!u)return v("div",{className:a,children:v(O,{variant:"primary",disabled:!0,theme:s,children:o})});if(!i)return v("div",{className:a,children:v(O,{variant:"primary",disabled:!0,theme:s,children:"Loading..."})});if(c&&p){const g=p.wallet?.address||p.email?.address,f=g?Fe(g):"Connected";return v("div",{className:a,children:Y(O,{variant:"primary",onClick:w,theme:s,children:["Logout (",f,")"]})})}return n?v("div",{className:a,children:Y("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px",flexDirection:"column",gap:"12px"},children:[v(ie,{size:40,borderWidth:3,color:"#3b82f6"}),v("p",{style:{color:"#6b7280",fontSize:"14px"},children:"Opening login..."})]})}):v("div",{className:a,children:v(O,{variant:"primary",onClick:x,theme:s,children:o})})};export{Et as A,O as B,vt as C,Ct as D,_t as E,St as F,oe as G,kt as H,Tt as I,_ as J,pr as K,er as L,ke as M,rr as N,Te as O,hr as P,Ue as Q,Ee as R,H as S,sr as T,ir as U,te as V,W as a,we as b,ee as c,dr as d,fr as e,D as f,Bt as g,S as h,k as i,cr as j,ie as k,Fe as l,Ut as m,ve as n,j as o,ur as p,I as q,mt as r,At as s,ht as t,Ne as u,P as v,$t as w,Ie as x,Ot as y,pt as z};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
"use strict";var Re=Object.create;var oe=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Ne=Object.getPrototypeOf,Fe=Object.prototype.hasOwnProperty;var Me=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ue(t))!Fe.call(e,o)&&o!==r&&oe(e,o,{get:()=>t[o],enumerable:!(a=We(t,o))||a.enumerable});return e};var Le=(e,t,r)=>(r=e!=null?Re(Ne(e)):{},Me(t||!e||!e.__esModule?oe(r,"default",{value:e,enumerable:!0}):r,e));const E=require("react/jsx-runtime"),g=require("react"),k=require("@spicenet-io/spiceflow-core"),x=require("viem"),je=require("viem/actions"),A=require("@privy-io/react-auth"),se=require("wagmi"),ie=require("@tanstack/react-query"),qe={base:0,raised:1,sticky:10,overlay:20,popover:40,modal:1e3,dropdown:1100,toast:1200,tooltip:1300},Oe={none:"0",sm:"4px",md:"6px",card:"8px",input:"10px",shell:"9px",modal:"12px",pill:"9999px",circle:"50%"},T={out:"cubic-bezier(0.22, 1, 0.36, 1)",inOut:"cubic-bezier(0.65, 0, 0.35, 1)",linear:"linear"},P={fast:"120ms",normal:"150ms",slow:"300ms",progress:"400ms"},De={interactive:`transform ${P.normal} ${T.out}, box-shadow ${P.normal} ${T.out}, background-color ${P.normal} ${T.out}, border-color ${P.normal} ${T.out}, color ${P.normal} ${T.out}`,color:`background-color ${P.normal} ${T.out}, border-color ${P.normal} ${T.out}, color ${P.normal} ${T.out}`,popover:`opacity ${P.normal} ${T.out}, transform ${P.normal} ${T.out}`},O={ui:'"Helvetica Neue", sans-serif',mono:'"IBM Plex Mono", monospace'};function D(e,t){return!e||!t?!1:x.isAddress(e)&&x.isAddress(t)?x.getAddress(e)===x.getAddress(t):e.toLowerCase()===t.toLowerCase()}const ze="0xcA11bde05977b3631167028862bE2a173976CA11",_e={4114:"0x860aFc632a6D625B95d8B96f39ECC48E988c6962"},Ge=new Set([5115]);function He(e){const t=_e[e.id]??(Ge.has(e.id)?void 0:ze);return x.defineChain({id:e.id,name:e.name,nativeCurrency:e.nativeCurrency,rpcUrls:{default:{http:[e.rpcUrl]}},blockExplorers:{default:{name:e.displayName,url:e.blockExplorer}},testnet:e.network==="testnet",...t?{contracts:{multicall3:{address:t}}}:{}})}const Je=[1,8453,42161,4114,11155111,421614,84532,5115,123420001114,688688,688689],z=Object.fromEntries(Je.map(e=>k.getChainMeta(e)).filter(e=>e!=null).map(e=>[e.id,{...e,viemChain:He(e),supportedTokens:k.getTokensForChain(e.id)}])),Ye=z;let le={};const Y=new Map,ce=e=>{le={...e||{}},Y.clear()},Q=e=>{const t=le[e];return t&&typeof t=="string"&&t.length>0?t:z[e]?.rpcUrl},N=e=>z[e],V=e=>{const t=k.getChainMeta(e);return t?.displayName||t?.name||`Chain ${e}`},Qe=e=>{const t=k.getDelegateContract(e);if(!t)throw new Error(`Unsupported chain ID: ${e}`);return t},Ve=(e,t,r)=>{const a=N(e);return a?.blockExplorer?`${a.blockExplorer}/tx/${t}`:"#"};async function Xe(e,t){const r=`0x${t.toString(16)}`;try{await e.request({method:"wallet_switchEthereumChain",params:[{chainId:r}]});return}catch(o){if(!(o?.code===4902||typeof o?.message=="string"&&o.message.includes("Unrecognized chain ID")))throw o}const a=N(t);if(!a)throw new Error(`Cannot add unknown chain ${t} to wallet`);await e.request({method:"wallet_addEthereumChain",params:[{chainId:r,chainName:a.name||`Chain ${t}`,nativeCurrency:a.nativeCurrency||{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:[Q(t)||a.rpcUrl],blockExplorerUrls:a.blockExplorer?[a.blockExplorer]:void 0}]})}const de=e=>{const t=N(e);if(!t)throw new Error(`Unsupported chain ID: ${e}`);const r=Q(e);if(!r)throw new Error(`No RPC URL configured for chain ID: ${e}`);const a=`${e}:${r}`,o=Y.get(a);if(o)return o;const n=x.createPublicClient({chain:t.viemChain,transport:x.http(r,{timeout:15e3,retryCount:2,retryDelay:300}),batch:{multicall:{wait:16}}});return Y.set(a,n),n},Ke=()=>{const e={};return Object.values(z).forEach(t=>{e[t.id]={name:t.name,moralisName:t.moralisId||"",chain:t.viemChain,rpcUrl:Q(t.id)||t.rpcUrl}}),e},Ze=(e,t=[])=>{const r=N(e);if(!r)return[];const a=[];if(![11155111,421614,84532,688689].includes(e)){const n=t.find(s=>s.chainId===e&&s.isNative);n?a.push(n):a.push({address:k.ZERO_ADDRESS,name:r.nativeCurrency.name,symbol:r.nativeCurrency.symbol,decimals:r.nativeCurrency.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:void 0,isNative:!0,chainId:e})}if(!r.supportedTokens)return a;const o=a.some(n=>n.isNative);return r.supportedTokens.forEach(n=>{if(o&&k.isNativeToken(n.address))return;const s=t.find(u=>u.chainId===e&&D(u.address,n.address));s?a.push(s):a.push({address:n.address,name:n.name,symbol:n.symbol,decimals:n.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:n.logo,isNative:!1,chainId:e})}),a},et=async(e,t)=>{const r=N(e);if(!r)throw new Error(`Unsupported chain ID: ${e}`);const a=t.toLowerCase();if(k.isNativeToken(a)){if(!r.nativeCurrency?.decimals)throw new Error(`Native currency decimals not configured for chain ${e}`);return r.nativeCurrency.decimals}if(r.supportedTokens){const o=r.supportedTokens.find(n=>D(n.address,a));if(o)return o.decimals}try{if(!x.isAddress(t,{strict:!1}))throw new Error(`Invalid token address: ${t}`);const o=x.getAddress(t),n=de(e),s=await je.readContract(n,{address:o,abi:x.erc20Abi,functionName:"decimals"});return Number(s)}catch{throw new Error(`Could not determine decimals for token ${t} on chain ${e}`)}};class R extends Error{constructor(t,r,a={}){super(r),this.code=t,this.context=a,this.name="SpiceflowError",Error.captureStackTrace&&Error.captureStackTrace(this,R)}}function X(e){return e instanceof R}const tt=["user rejected","user denied","user cancelled","rejected the request","action_rejected","4001"];function ue(e){if(!e)return"";if(typeof e=="string")return e;const t=e,r=t.message||t.reason||"",a=t.details||"";return`${r} ${a}`.trim()}const fe=e=>{if(X(e))return e.code==="WALLET_REJECTED";const t=ue(e).toLowerCase();return tt.some(r=>t.includes(r))};let K=null;function rt(e){return K?.message===e?K.detail:void 0}const at=(e,t="Something went wrong. Please try again.")=>{if(fe(e))return"Transaction was rejected.";if(X(e)){const r=e.message||t,{requestId:a,httpStatus:o,responseBody:n,endpoint:s}=e.context;return(a||o||s)&&(K={message:r,detail:{requestId:a,httpStatus:o,responseBody:n,endpoint:s}}),r}return ue(e)||t},nt=[...k.DELEGATE_ABI,...k.ERC20_ABI,...k.spicenetEscrowAbi,...k.uniV3SwapRouterAbi];function Z(e,t=0){return t>4||e==null?[]:typeof e=="string"?e.match(/0x[0-9a-fA-F]{8,}/g)??[]:Array.isArray(e)?e.flatMap(r=>Z(r,t+1)):typeof e=="object"?Object.values(e).flatMap(r=>Z(r,t+1)):[]}function pe(e){try{const t=x.decodeErrorResult({abi:nt,data:e});if(t.errorName==="Error")return String(t.args?.[0]??"");if(t.errorName==="Panic")return`Panic(${t.args?.[0]})`;if(t.errorName==="CallReverted"){const r=t.args?.[4],a=r&&r!=="0x"?pe(r):void 0;return a?`Call reverted: ${a}`:"Call reverted (no reason returned)"}return t.errorName}catch{try{const t=x.hexToString(e).replace(/\x00+$/g,"").trim();return/^[\x20-\x7e]+$/.test(t)&&t.length>1?t:void 0}catch{return}}}function ot(e){for(const t of Z(e)){if(!x.isHex(t))continue;const r=pe(t);if(r)return r}}function st(e,t){const r=t.match(/Output amount (\d+) is insufficient after fees (\d+) on chain (\d+)/);if(!r)return t;const[,a,o,n]=r,s=Number(n),u=BigInt(a),h=BigInt(o);let l;for(const v of e.intents){const y=v.chainBatches.find(f=>f.chainId===s);if(y){l=y;break}}const m=l?.tokenTransfers.find(v=>v.from==="escrow"&&D(v.to,e.user)&&!k.isNativeToken(v.token)),i=V(s);if(!m)return`Amount is too small to cover the estimated fee on ${i}.`;const d=k.getTokenByAddress(m.token,s),p=d?.decimals??18,b=d?.symbol??"tokens",c=x.formatUnits(u,p),$=x.formatUnits(h,p);return`Amount is too small to cover the estimated fee on ${i}. Amount: ${c} ${b}. Estimated fee: ${$} ${b}.`}function it(e){return e?.code===4902||e?.name==="ChainNotConfiguredError"?"This network is not configured in your wallet. Please add it manually to continue.":e?.code===4001?"Network switch cancelled. Please switch manually in your wallet to continue.":"Unable to switch network. Please switch manually in your wallet to continue."}const lt="https://tx-submission-api.spicenet.io",me=lt;function ct(e,t){return typeof t=="bigint"?t.toString():t}async function _(e,t){const r={...t?.headers},a=r["x-request-id"]??crypto.randomUUID();r["x-request-id"]=a;const o=await fetch(e,{...t,headers:r}),n=o.headers.get("x-request-id")??"";return Object.assign(o,{requestId:n})}function j(e,t){if(!e)return t;const r=e.error,a=(typeof e.message=="string"?e.message:"")||(r&&typeof r=="object"&&"message"in r&&typeof r.message=="string"?r.message:"")||(typeof r=="string"?r:"")||t,o=ot(e);return o&&!a.includes(o)?`${a} \u2014 ${o}`:a}async function dt(e){try{return await e.json()}catch{return null}}function ut(e){return(Array.isArray(e?.balances)?e.balances:[]).flatMap(t=>{if(!t||typeof t!="object")return[];const r=t;return[{receiptToken:typeof r.receiptToken=="string"?r.receiptToken:void 0,tokenName:String(r.tokenName??""),balanceAvailable:String(r.balanceAvailable??"0"),chainTokens:Array.isArray(r.chainTokens)?r.chainTokens.filter(a=>typeof a=="string"):r.chainTokens&&typeof r.chainTokens=="object"?r.chainTokens:r.chainTokenConfig&&typeof r.chainTokenConfig=="object"?r.chainTokenConfig:void 0,decimals:typeof r.decimals=="number"?r.decimals:void 0,balanceUsd:typeof r.balanceUsd=="number"||typeof r.balanceUsd=="string"?r.balanceUsd:null}]})}class ft{constructor(){this.baseUrl=me}setBaseUrl(t){this.baseUrl=t}getBaseUrl(){return this.baseUrl}async requestJson(t,r){const a=`${this.baseUrl}${t}`,o=await _(a,r.method&&r.method!=="GET"?{method:r.method,headers:{"Content-Type":"application/json"},body:JSON.stringify(r.body,ct)}:void 0),n=await o.json();if(!o.ok||n.success===!1||r.ok&&!r.ok(n)){const s=j(n,r.fallbackError(o.status));throw new R(r.code??"RELAYER_ERROR",r.mapError?r.mapError(s):s,{httpStatus:o.status,requestId:o.requestId,responseBody:JSON.stringify(n),endpoint:t,...r.context})}return n}async createAction(t){return this.requestJson("/actions",{method:"POST",body:t,fallbackError:r=>`Relayer API error: ${r}`})}async estimateActionFees(t){return(await this.requestJson("/actions/fees/estimate",{method:"POST",body:t,fallbackError:r=>`Relayer fee estimate error: ${r}`,ok:r=>!!r.success&&!!r.data?.feeEstimate,mapError:r=>st(t,r)})).data.feeEstimate}async estimateBatchGas(t){const r=await this.requestJson("/actions/gas/estimate",{method:"POST",body:t,fallbackError:a=>`Relayer gas estimate error: ${a}`,ok:a=>!!a.success&&!!a.data?.gasFee});return{gasFee:BigInt(r.data.gasFee),gasQuoteSource:r.data.gasQuoteSource}}async executeStep(t,r,a,o){const n=`${this.baseUrl}/actions/${t}/intents/${r}/steps/${a}`,s=`/actions/${t}/intents/${r}/steps/${a}`,u=crypto.randomUUID(),h=3e4,l=new Promise((d,p)=>setTimeout(()=>p(new R("RELAYER_EXECUTE_ERROR",`Execute step request timed out after ${h/1e3}s`,{actionId:t,intentIndex:r,stepIndex:a,endpoint:s,requestId:u})),h)),m=await Promise.race([_(n,{method:"POST",headers:{"Content-Type":"application/json","x-request-id":u},body:JSON.stringify(o)}),l]),i=await m.json();if(!m.ok||i.success===!1)throw new R("RELAYER_EXECUTE_ERROR",j(i,`Execute step error: ${m.status}`),{httpStatus:m.status,requestId:m.requestId,responseBody:JSON.stringify(i),endpoint:s,actionId:t});if(i?.status==="error"||i?.status==="reverted"){const d=j(i,""),p=d?`: ${d}`:"";throw new R("RELAYER_EXECUTE_ERROR",`Step ${a} previously ${i.status}${p}`,{httpStatus:m.status,requestId:m.requestId,responseBody:JSON.stringify(i),endpoint:s,actionId:t,intentIndex:r,stepIndex:a,stepStatus:i.status})}return{success:!0,transactionHash:i.transactionHash}}async checkStepStatus(t,r){const a=t.split("/"),o=a[0],n=a.length>=2?a[1]:"0",s=await this.requestJson(`/actions/${o}/intents/${n}/steps/${r}`,{fallbackError:u=>`Intent step status check failed: ${u}`,code:"RELAYER_STATUS_ERROR",context:{intentId:t}});return{success:!0,data:{status:s.status==="error"?"reverted":s.status,transactionHash:s.txid,error:j(s,"")}}}async createWallet(t,r){return this.requestJson(`/wallets/${t}`,{method:"PUT",body:r,fallbackError:a=>`Create wallet error: ${a}`})}async getWallet(t){return this.requestJson(`/wallets/${t}`,{fallbackError:r=>`Get wallet error: ${r}`})}async createWithdrawal(t){return this.requestJson("/withdrawals",{method:"POST",body:t,fallbackError:r=>`Create withdrawal error: ${r}`})}async getWithdrawal(t){return this.requestJson(`/withdrawals/${t}`,{fallbackError:r=>`Get withdrawal error: ${r}`})}async getRollupTimestamp(){return this.requestJson("/time",{fallbackError:t=>`Get rollup timestamp error: ${t}`})}}const U=new ft;async function pt(e){const t=`${U.getBaseUrl()}/wallets/${e}/balance`,r=await _(t,{cache:"no-store"}),a=await dt(r);if(!r.ok||a?.success===!1)throw new R("RELAYER_ERROR",j(a,`Unable to verify Spice balance: ${r.status}`),{httpStatus:r.status,requestId:r.requestId,responseBody:JSON.stringify(a),endpoint:`/wallets/${e}/balance`});return ut(a)}const ee=new Map,mt="spiceflow.smartWallet.";function he(e){return`${mt}${e.toLowerCase()}`}function ht(e){try{return typeof localStorage<"u"&&localStorage.getItem(he(e))==="1"}catch{return!1}}function ge(e){try{typeof localStorage<"u"&&localStorage.setItem(he(e),"1")}catch{}}function gt(e){if(!(e instanceof R))return!1;const t=e.context.httpStatus;return t===400||t===404?`${e.message} ${String(e.context.responseBody??"")}`.toLowerCase().includes("not found"):!1}async function ye(e,t){if(ht(e))return;const r=e.toLowerCase(),a=ee.get(r);if(a)return a;const o=(async()=>{try{await U.getWallet(e),ge(e);return}catch(l){if(!gt(l))throw l}const{unix_timestamp:n}=await U.getRollupTimestamp(),s=`I am creating a new smart wallet and adding an admin wallet ethereum:0x${e.slice(2).toLowerCase()}. Nonce: ${n}`,u=await t(s),h=typeof u=="string"?u:u.signature;if(!h)throw new Error("Wallet returned no smart wallet signature");await U.createWallet(e,{timestamp:n,signature:h}),ge(e)})();ee.set(r,o);try{await o}finally{ee.delete(r)}}const yt=(e,t)=>{const r=o=>t?t(o):V(o),a=[];return e.forEach((o,n)=>{const s=o.calls&&o.calls.length>0,u=o.tokenTransfers&&o.tokenTransfers.length>0;!s&&!u||a.push({stepId:n,status:n===0?"processing":"pending",chainId:o.chainId,chainName:r(o.chainId),description:"Processing transaction"})}),a},bt=e=>{const t=e?.wallet;if(t?.address&&t.walletClientType==="privy"&&t.connectorType==="embedded"&&!t.imported)return t.address},be=async(e,t)=>{if(!e?.address)throw new Error("Wallet not available");if(typeof e.getWalletClient=="function"){const r=t===void 0?[void 0]:[String(t),t,void 0];let a=null;for(const o of r)try{const n=await e.getWalletClient(o);if(n)return n}catch(n){a=n}if(a)throw a}if(typeof e.getEthereumProvider=="function"){const r=await e.getEthereumProvider(),a=t?N(t)?.viemChain:void 0;return x.createWalletClient({account:e.address,chain:a,transport:x.custom(r)})}throw new Error("Wallet client not available")},wt=async(e,t)=>{if(!e?.address)throw new Error("Wallet not available");if(typeof e.getEthereumProvider=="function")return e.getEthereumProvider();const r=await be(e,t);return{request:a=>r.request(a)}},G=e=>e?.address?{address:e.address,wallet:e,getWalletClient:t=>be(e,t),getEthereumProvider:t=>wt(e,t)}:null,te=()=>{const{address:e,connector:t}=se.useAccount();let r=null,a=null;try{r=A.useWallets(),{user:a}=A.usePrivy()}catch{r=null,a=null}const o=r?.wallets||[],n=A.getEmbeddedConnectedWallet(o),s=n?.address?.toLowerCase(),u=o.find(c=>c.connectorType!=="embedded"&&c.address?.toLowerCase()!==s),h=e?.toLowerCase(),l=e&&t&&!(h&&s&&h===s)?{address:e,connector:t,getEthereumProvider:()=>t.getProvider()}:null,m=e&&t?{address:e,connector:t,getEthereumProvider:()=>t.getProvider()}:null,i=G(n),d=G(l)||G(u),p=i?.address||bt(a),b=G(m)||d;return{embeddedWallet:i,externalWallet:d,embeddedAddress:p,externalAddress:d?.address,activeWallet:b,activeAddress:b?.address}},we=()=>{const e=g.useContext(H),t=e?.mode,{isConnected:r,address:a}=se.useAccount();let o=null,n=null,s=null,u=null,h=null;try{o=A.usePrivy(),n=A.useSign7702Authorization(),s=A.useSignMessage(),u=A.useWallets()}catch(f){h=f instanceof Error?f.message:String(f)}if(h)return t==="ondemand"&&r&&a?{isReady:!0,isAuthenticated:!0,isConnected:!0,address:a,provider:"privy",actions:{signAuthorization:async()=>{throw new Error("Not available in ondemand mode")},signMessage:async()=>{throw new Error("Not available in ondemand mode")},getEthereumProvider:async()=>{throw new Error("Not available in ondemand mode")}}}:{isReady:!1,isAuthenticated:!1,isConnected:!1,provider:null,actions:{signAuthorization:async()=>{throw new Error("Privy not available")},signMessage:async()=>{throw new Error("Privy not available")},getEthereumProvider:async()=>{throw new Error("Privy not available")}}};const{ready:l=!1,authenticated:m=!1}=o||{},i=e?.embeddedWalletAddress,d=A.getEmbeddedConnectedWallet(u?.wallets||[]),p=i||d?.address,b=!!p&&!!d,c={isReady:t==="ondemand"?!0:l,isAuthenticated:t==="ondemand"?!0:m||b,isConnected:t==="ondemand"?r&&!!a||l&&(m||b)&&b:l&&b,address:t==="ondemand"&&r?a:p,provider:"privy"},$=async f=>{if(!d)throw new Error("Embedded wallet not available");const w=await d.getEthereumProvider(),{createWalletClient:C,custom:I}=await import("viem");return{signature:await C({account:d.address,transport:I(w)}).signMessage({account:d.address,message:f})}},v=async f=>{if(s)try{return{signature:(await s.signMessage({message:f})).signature}}catch(w){if(!d)throw w}if(!d)throw new Error("Privy sign message not available");return $(f)},y=async()=>{if(!p)throw new Error("Embedded wallet not available for smart wallet setup");await ye(p,v)};return{...c,actions:{signAuthorization:async f=>{if(!n)throw new Error("Privy sign authorization not available");try{await y();const w=await n.signAuthorization({contractAddress:f.contractAddress,chainId:f.chainId,nonce:f.nonce},{address:p});return delete w.v,w}catch(w){const C=typeof w?.message=="string"?w.message:String(w?.message??w??"");throw C.includes("not configured")||C.includes("chain")?new Error(`Chain ${f.chainId} is not configured in PrivyProvider. Add this chain to your Privy dashboard or supportedChainIds.`):w}},signMessage:async f=>{if(typeof f=="object"&&"raw"in f){if(await y(),!d)throw new Error("Embedded wallet not available for raw signing");return $(f)}return v(f)},getEthereumProvider:async()=>{if(!d)throw new Error("Embedded wallet not available");return d.getEthereumProvider()}}}},xt="https://portal-api.spicenet.io/api/v1",re=e=>e.replace(/\/+$/,""),vt=(e,t)=>`${e}:${t}`;async function Et(e,t){const r=new URLSearchParams({walletAddress:t,campaignId:"spicenet-portal",campaignGroup:"1"}),a=await fetch(`${e}/portal/mainnet/linked-portal-wallet?${r.toString()}`,{cache:"no-store"});if(!a.ok){if(a.status>=500){const o=new Error(`Failed to resolve linked portal wallet: ${a.status}`);throw o.status=a.status,o}return null}return(await a.json()).portalWalletAddress?.toLowerCase()??null}async function $t(e,t,r){const a=new URLSearchParams({walletAddress:t,campaignId:r.campaignId,campaignGroup:r.campaignGroup,partnerId:r.partnerId}),o=await fetch(`${e}/portal/mainnet/whitelist/check?${a.toString()}`,{cache:"no-store"});if(!o.ok){const n=new Error(`Failed to check whitelist: ${o.status}`);throw n.status=o.status,n}return await o.json()}async function Ct(e,t,r,a){const o=await fetch(`${e}/portal/mainnet/link-wallet`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({campaignId:t.campaignId,campaignGroup:t.campaignGroup,partnerId:t.partnerId,externalWalletAddress:r,embeddedWalletAddress:a})});if(!o.ok)throw new Error(`Failed to link wallet: ${o.status}`)}function xe({walletAddress:e,campaignId:t,campaignGroup:r,partnerId:a,apiBaseUrl:o=xt,enabled:n=!0,staleTime:s=5*60*1e3,refetchInterval:u=!1}={}){const{isAuthenticated:h,isConnected:l}=we(),{externalAddress:m,embeddedAddress:i}=te(),d=e??m,p=typeof d=="string"?d.toLowerCase():void 0,b=typeof i=="string"?i.toLowerCase():void 0,c=typeof m=="string"?m.toLowerCase():void 0,$=n&&h&&l&&!!m&&!!p&&x.isAddress(p)&&!!t&&!!r&&!!a,v=g.useMemo(()=>["partner-whitelist","check",p,t,r,a,re(o)],[p,t,r,a,o]),y=ie.useQuery({queryKey:v,enabled:$,staleTime:s,refetchInterval:u,retry:(B,F)=>{const W=F?.status;return typeof W=="number"&&W>=400&&W<500?!1:B<3},retryDelay:B=>Math.min(1e3*2**B,15e3),queryFn:async()=>{if(!p||!x.isAddress(p))throw new Error("A valid wallet address is required");if(!t||!r||!a)throw new Error("campaignId, campaignGroup, and partnerId are required");const B=re(o),F={campaignId:t,campaignGroup:r,partnerId:a},W=await Et(B,p);return W?$t(B,W,F):{walletAddress:p,campaignId:t,campaignGroup:r,partnerId:a,isWhitelisted:!1,isLinkedWallet:!1,whitelistedWalletAddress:null,externalWalletAddress:p}}}),f=n&&h&&l&&!!c&&x.isAddress(c)&&!!b&&x.isAddress(b)&&!!t&&!!r&&!!a,w=ie.useMutation({mutationFn:B=>Ct(re(o),{campaignId:t,campaignGroup:r,partnerId:a},B.external,B.embedded)}),C=g.useRef(new Set),I=w.mutate;return g.useEffect(()=>{if(!f||!c||!b||!t||!r||!a)return;const B=vt(c,b);C.current.has(B)||(C.current.add(B),I({external:c,embedded:b}))},[f,c,b,t,r,a,I]),{isWhitelisted:y.data?.isWhitelisted??!1,whitelistCheck:y.data,checkedWalletAddress:p,externalWalletAddress:m,embeddedWalletAddress:i,isExternalWalletConnected:!!m,isWhitelistCheckEnabled:$,linkWallet:w,isWalletLinked:w.isSuccess,...y}}const Bt=["__spicenet_whitelist_blocked__"],ve="spiceflow-mode",Ee=()=>{if(typeof window>"u")return null;try{const e=window.localStorage.getItem(ve);return e==="7702"?"7702":e==="non7702"?"ondemand":e==="embedded"?"7702":e==="external"?"ondemand":null}catch{return null}},kt=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(ve,e==="7702"?"7702":"non7702")}catch{}},St=()=>Ee()!==null,$e=g.createContext(null),H=g.createContext(null),It=({children:e,value:t,whitelist:r})=>{const a=!!r&&r.enabled!==!1,{isWhitelisted:o,isLoading:n,whitelistCheck:s}=xe(a?r:{enabled:!1}),u=a&&!o,h=g.useMemo(()=>({...t,mode:u?"ondemand":t.mode,allowedTokens:u?Bt:t.allowedTokens,isUserWhitelisted:o,isWhitelistChecking:n,isWhitelistConfigured:a,isWhitelistGateActive:u,whitelistCheck:s}),[t,a,u,o,n,s]);return E.jsx(H.Provider,{value:h,children:e})},At=({children:e,provider:t="privy",supportedChainIds:r,allowedTokens:a,network:o="testnet",mode:n,skipFlow:s=[],nativeChainId:u,appName:h="Spicenet",apiUrl:l,theme:m,rpcOverrides:i,whitelist:d})=>{g.useEffect(()=>{if(!l)return;const I=U.getBaseUrl();return U.setBaseUrl(l),()=>U.setBaseUrl(I)},[l]),g.useEffect(()=>(ce(i),()=>ce(void 0)),[i]);const p=g.useMemo(()=>k.getChainIdsByNetwork(o),[o]),b=r??p,c=m??null,[$,v]=g.useState(()=>n??Ee()??"7702");g.useEffect(()=>{n&&v(n)},[n]);const y=g.useCallback(I=>{if(n){v(n);return}v(I),kt(I)},[n]),{embeddedAddress:f,externalAddress:w}=te(),C=g.useMemo(()=>({provider:t,supportedChainIds:b,allowedTokens:a,skipFlow:s,mode:$,setMode:y,network:o,nativeChainId:u,appName:h,apiUrl:l,rpcOverrides:i,embeddedWalletAddress:f,externalWalletAddress:w,isUserWhitelisted:null,isWhitelistChecking:!1,isWhitelistConfigured:!1,isWhitelistGateActive:!1}),[t,b,a,s,$,y,o,u,h,l,i,f,w]);return E.jsx($e.Provider,{value:c,children:E.jsx(H.Provider,{value:C,children:E.jsx(It,{value:C,whitelist:d,children:e})})})},Tt={spacing:{xs:"0.25rem",sm:"0.5rem",md:"1rem",lg:"1.5rem",xl:"2rem"},borderRadius:{sm:"0.25rem",md:"0.5rem",lg:"0.75rem",full:"9999px"},typography:{fontFamily:O.ui,fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.75rem"},fontWeight:{normal:400,medium:500,semibold:600,bold:700}},shadows:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1)"},animation:{fast:"150ms ease-in-out",normal:"200ms ease-in-out",slow:"300ms ease-in-out"}},Pt={primary:"#EA4B4B",primaryHover:"#E43838",secondary:"#f3f4f6",background:"#ffffff",surface:"#f9fafb",surfaceHover:"#f3f4f6",border:"#e5e7eb",borderHover:"#d1d5db",text:"#111827",textSecondary:"#374151",textMuted:"#6b7280",success:"#10b981",error:"#ef4444",warning:"#f59e0b",info:"#3b82f6"},Rt={primary:"#EA4B4B",primaryHover:"#E43838",secondary:"#171717",background:"#141414",surface:"#1e1e1e",surfaceHover:"#2a2a2a",border:"#2d2d2d",borderHover:"#3a3a3a",text:"#ffffff",textSecondary:"#888888",textMuted:"#666666",success:"#10b981",error:"#ef4444",warning:"#f59e0b",info:"#3b82f6"},Ce=(e="light")=>({mode:e,...Tt,colors:e==="light"?Pt:Rt});function J(e,t){const r=e.replace("#",""),a=Math.max(0,Math.round(parseInt(r.substring(0,2),16)*(1-t))),o=Math.max(0,Math.round(parseInt(r.substring(2,4),16)*(1-t))),n=Math.max(0,Math.round(parseInt(r.substring(4,6),16)*(1-t)));return`#${a.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`}function Wt(e,t){return{shell:t?.shell??"#141414",shellBorder:t?.shellBorder??J(t?.shell??"#141414",.35),shellInnerBorder:t?.shellInnerBorder??J(t?.shell??"#141414",.55),cardBg:t?.cardBg??"#1e1e1e",inputBg:t?.inputBg??"#171717",hoverBg:t?.hoverBg??"#2a2a2a",textPrimary:t?.textPrimary??"#ffffff",textSecondary:t?.textSecondary??"#888888",inputText:t?.inputText??"#e0e0e0",inputPlaceholder:t?.inputPlaceholder??"#555555",cardBorder:t?.cardBorder??"rgba(255,255,255,0.08)",inputBorder:t?.inputBorder??"rgba(255,255,255,0.10)",buttonBorder:t?.buttonBorder??"rgba(255,255,255,0.12)",successBg:t?.successBg??"#0a1f18",successBorder:t?.successBorder??"#1a4a3a",successText:t?.successText??"#6ee7b7",warningBg:t?.warningBg??"#1f1a0d",warningBorder:t?.warningBorder??"#4a3820",warningText:t?.warningText??"#fbbf24",errorBg:t?.errorBg??"#1f0d0d",errorBorder:t?.errorBorder??"#4a2020",errorText:t?.errorText??"#f87171",infoBg:t?.infoBg??"#0d1325",infoBorder:t?.infoBorder??"#2a3a5a",infoText:t?.infoText??"#60a5fa"}}function Ut(e){return{shell:"#ffffff",shellBorder:"#E9E9E9",shellInnerBorder:"#D5D5D5",cardBg:"#f9fafb",inputBg:"#ffffff",hoverBg:"#f3f4f6",textPrimary:"#111827",textSecondary:"#6b7280",inputText:"#111827",inputPlaceholder:"#9ca3af",cardBorder:"#e5e7eb",inputBorder:"#d1d5db",buttonBorder:"#0e0d0b",successBg:"#d1fae5",successBorder:"#6ee7b7",successText:"#065f46",warningBg:"#fef3c7",warningBorder:"#fde68a",warningText:"#92400e",errorBg:"#fef2f2",errorBorder:"#fecaca",errorText:"#dc2626",infoBg:"#dbeafe",infoBorder:"#93c5fd",infoText:"#1e40af"}}function Be(e,t){const r=t?{...e,...t}:e,a=r.dark??!1,o=r.primaryColor,n=r.shell??(a?"#141414":"#ffffff");return{primaryColor:o,dark:a,fontFamily:r.fontFamily??'"Helvetica Neue", sans-serif',appName:r.appName??"Spicenet",logo:r.logo,borderRadius:r.borderRadius??"8px",shell:n,shellBorder:J(n,a?.35:.085),shellInnerBorder:J(n,a?.55:.165),card:r.card??(a?"#1e1e1e":"#f9fafb"),input:a?"#171717":"#ffffff",hover:a?"#2a2a2a":"#f3f4f6",text:r.text??(a?"#ffffff":"#111827"),textMuted:r.textMuted??(a?"#888888":"#6b7280"),inputText:a?"#e0e0e0":"#111827",inputPlaceholder:a?"#555555":"#9ca3af",border:r.border??(a?"rgba(255,255,255,0.08)":"#e5e7eb"),inputBorder:a?"rgba(255,255,255,0.10)":"#d1d5db",buttonBorder:a?"rgba(255,255,255,0.12)":"#0e0d0b",successBg:a?"#0a1f18":"#d1fae5",successBorder:a?"#1a4a3a":"#6ee7b7",successText:a?"#6ee7b7":"#065f46",warningBg:a?"#1f1a0d":"#fef3c7",warningBorder:a?"#4a3820":"#fde68a",warningText:a?"#fbbf24":"#92400e",errorBg:a?"#1f0d0d":"#fef2f2",errorBorder:a?"#4a2020":"#fecaca",errorText:a?"#f87171":"#dc2626",infoBg:a?"#0d1325":"#dbeafe",infoBorder:a?"#2a3a5a":"#93c5fd",infoText:a?"#60a5fa":"#1e40af"}}const Nt=O.mono;function ke(e,t){const r=g.useContext($e)??void 0;return g.useMemo(()=>{const a=r??{primaryColor:"#EA4B4B"},o={...e?.primaryColor?{primaryColor:e.primaryColor}:{},...e?.fontFamily?{fontFamily:e.fontFamily}:{},...t!==void 0?{dark:t}:{}},n=Be(a,o),{dark:s,primaryColor:u,appName:h}=n,l=Ce(s?"dark":"light"),m={...l,colors:{...l.colors,primary:u,primaryHover:`${u}dd`},typography:{...l.typography,fontFamily:n.fontFamily}},i={shell:n.shell,shellBorder:n.shellBorder,shellInnerBorder:n.shellInnerBorder,cardBg:n.card,inputBg:n.input,hoverBg:n.hover,textPrimary:n.text,textSecondary:n.textMuted,inputText:n.inputText,inputPlaceholder:n.inputPlaceholder,cardBorder:n.border,inputBorder:n.inputBorder,buttonBorder:n.buttonBorder,successBg:n.successBg,successBorder:n.successBorder,successText:n.successText,warningBg:n.warningBg,warningBorder:n.warningBorder,warningText:n.warningText,errorBg:n.errorBg,errorBorder:n.errorBorder,errorText:n.errorText,infoBg:n.infoBg,infoBorder:n.infoBorder,infoText:n.infoText},d=e?.inputVariant?e.inputVariant==="dark":s;return{brand:r,theme:m,dark:s,appName:h,primaryColor:u,dk:i,palette:i,fontFamily:n.fontFamily,monoFont:Nt,inputDark:d,cardBg:d?i.cardBg:"#E9E9E9",cardBorder:d?i.cardBorder:"#C6C6C6",textPrimary:i.textPrimary,textSecondary:i.textSecondary,subtitleText:d?i.textSecondary:"#979AA0"}},[r,e,t])}const Ft=(e,t=4)=>!isFinite(e)||e===0?"0":e>0&&e<1e-6?e.toFixed(12).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""):e<1e-4?e.toFixed(8).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""):e.toFixed(t).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""),Mt=e=>isFinite(e)?e>0&&e<.01?"<$0.01":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(e):"$0.00",Se=(e,t=6,r=4)=>e.length<=t+r?e:`${e.slice(0,t)}...${e.slice(-r)}`,Lt=(e,t)=>{const r=e.replace(/[^0-9.]/g,"").split("."),a=r[0]??"",o=r.slice(1).join(""),n=typeof t=="number"?Math.max(0,Math.min(t,18)):null;return r.length===1?a:`${a}.${n===null?o:o.slice(0,n)}`},jt=(e,t=6)=>!Number.isFinite(e)||e<=0?"0":e.toFixed(Math.min(Math.max(t,0),18)).replace(/\.?0+$/,""),qt=async e=>{try{return await navigator.clipboard.writeText(e),!0}catch(t){return console.error("Failed to copy to clipboard:",t),!1}},Ie="spiceflow-spinner-keyframes";function Ot(){if(typeof document>"u"||document.getElementById(Ie))return;const e=document.createElement("style");e.id=Ie,e.textContent="@keyframes spiceflow-spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}",document.head.appendChild(e)}const ae=({size:e=16,borderWidth:t=2,color:r="currentColor",style:a})=>{const o=g.useRef(!1);return g.useEffect(()=>{o.current||(Ot(),o.current=!0)},[]),E.jsx("div",{role:"status","aria-label":"Loading",style:{width:`${e}px`,height:`${e}px`,border:`${t}px solid ${r}`,borderTop:`${t}px solid transparent`,borderRadius:"50%",animation:"spiceflow-spin 1s linear infinite",flexShrink:0,...a}})},q=({variant:e="primary",size:t="md",loading:r=!1,fullWidth:a=!1,disabled:o,children:n,className:s="",style:u,theme:h,styles:l,dark:m,...i})=>{const{theme:d,dark:p,palette:b}=ke(l,m),c=h||d,$=m??p,[v,y]=g.useState(!1),[f,w]=g.useState(!1),C=$?b.shell:"white",I=()=>{switch(e){case"primary":return{backgroundColor:l?.button?.backgroundColor||c.colors.primary,color:l?.button?.color||"#ffffff",border:`1px solid ${l?.button?.backgroundColor||c.colors.primary}`};case"secondary":return{backgroundColor:c.colors.secondary,color:c.colors.text,border:`1px solid ${c.colors.border}`};case"success":return{backgroundColor:c.colors.success,color:c.colors.text,border:`1px solid ${c.colors.success}`};case"error":return{backgroundColor:c.colors.error,color:c.colors.text,border:`1px solid ${c.colors.error}`};case"ghost":return{backgroundColor:"transparent",color:c.colors.textSecondary,border:`1px solid ${c.colors.border}`};case"outline":{const S=l?.button?.backgroundColor||c.colors.primary,ne=l?.button?.color||($?"#ffffff":"#0e0d0b"),M=l?.button?.borderColor||($?`${c.colors.primary}88`:"#0e0d0b"),L=o||r,Ae=$?"1px":"1.5px",Te=l?.button?.disabledBackgroundColor||`${S}88`,Pe=l?.button?.disabledColor||ne;return{height:"56px",backgroundColor:L?Te:f?`${S}cc`:v?`${S}ee`:S,color:L?Pe:ne,border:`${Ae} solid ${M}`,borderRadius:l?.button?.borderRadius||"12px",fontSize:"22px",fontWeight:500,fontFamily:O.mono,opacity:L?.78:1,transform:L?"none":f?"scale(0.98)":v?"translateY(-2px)":"none",boxShadow:L?`3px 3px 0px ${C}, 4px 4px 0px ${M}`:f?`2px 2px 0px ${M}`:v?`5px 5px 0px ${C}, 6px 6px 0px ${M}`:`3px 3px 0px ${C}, 4px 4px 0px ${M}`,transition:"transform 150ms ease, box-shadow 150ms ease, background-color 150ms ease, border-color 150ms ease, color 150ms ease"}}default:return{}}},B=()=>{if(e==="outline")return{};switch(t){case"sm":return{padding:`${c.spacing.sm} ${c.spacing.md}`,fontSize:c.typography.fontSize.sm};case"md":return{padding:`${c.spacing.md} ${c.spacing.lg}`,fontSize:c.typography.fontSize.base};case"lg":return{padding:`${c.spacing.lg} ${c.spacing.xl}`,fontSize:c.typography.fontSize.lg};default:return{}}},F={borderRadius:l?.button?.borderRadius||c.borderRadius.md,fontWeight:l?.button?.fontWeight||c.typography.fontWeight.medium,fontFamily:l?.button?.fontFamily||c.typography.fontFamily,fontSize:l?.button?.fontSize||void 0,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease, opacity 150ms ease",cursor:o||r?"not-allowed":"pointer",opacity:(o||r)&&e!=="outline"?.6:1,width:a?"100%":"auto",display:"flex",alignItems:"center",justifyContent:"center",gap:c.spacing.sm,...I(),...B(),...l?.button?.fontSize&&{fontSize:l.button.fontSize}},W=o||r;return E.jsxs("button",{type:i.type??"button","data-spiceflow-focus":!0,"aria-busy":r||void 0,"aria-disabled":W||void 0,style:{...F,...u},className:s,disabled:W,onMouseEnter:S=>{y(!0),i.onMouseEnter?.(S)},onMouseLeave:S=>{y(!1),w(!1),i.onMouseLeave?.(S)},onMouseDown:S=>{w(!0),i.onMouseDown?.(S)},onMouseUp:S=>{w(!1),i.onMouseUp?.(S)},...i,children:[r&&E.jsx(ae,{size:16}),n]})},Dt=({onAuthSuccess:e,onAuthError:t,theme:r="light",className:a="",buttonText:o="Login with Privy",autoTrigger:n=!1})=>{const s=Ce(r),[u,h]=g.useState(!1),[l,m]=g.useState(!1),{ready:i,authenticated:d,user:p}=A.usePrivy(),{login:b}=A.useLogin(),{logout:c}=A.useLogout();g.useEffect(()=>{h(!0)},[]),g.useEffect(()=>{n&&i&&!d&&u&&!l&&(m(!0),$())},[n,i,d,u,l]),g.useEffect(()=>{if(i&&d&&p&&e){const y=p.wallet?.address||p.email?.address;y&&e(y)}},[i,d,p,e]),g.useEffect(()=>{},[i,d,t]);const $=()=>{try{b()}catch(y){const f=`Login failed: ${String(y)}`;t?t(f):console.error(f)}},v=()=>{try{c()}catch(y){const f=`Logout failed: ${String(y)}`;t?t(f):console.error(f)}};if(!u)return E.jsx("div",{className:a,children:E.jsx(q,{variant:"primary",disabled:!0,theme:s,children:o})});if(!i)return E.jsx("div",{className:a,children:E.jsx(q,{variant:"primary",disabled:!0,theme:s,children:"Loading..."})});if(d&&p){const y=p.wallet?.address||p.email?.address,f=y?Se(y):"Connected";return E.jsx("div",{className:a,children:E.jsxs(q,{variant:"primary",onClick:v,theme:s,children:["Logout (",f,")"]})})}return n?E.jsx("div",{className:a,children:E.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px",flexDirection:"column",gap:"12px"},children:[E.jsx(ae,{size:40,borderWidth:3,color:"#3b82f6"}),E.jsx("p",{style:{color:"#6b7280",fontSize:"14px"},children:"Opening login..."})]})}):E.jsx("div",{className:a,children:E.jsx(q,{variant:"primary",onClick:$,theme:s,children:o})})};exports.Button=q,exports.CHAIN_CONFIGS=Ye,exports.PrivyLogin=Dt,exports.RELAYER_API_URL=me,exports.SpiceFlowProvider=At,exports.SpiceFlowProviderContext=H,exports.SpiceflowError=R,exports.Spinner=ae,exports.addressesEqual=D,exports.buildDarkPalette=Wt,exports.buildLightPalette=Ut,exports.copyToClipboard=qt,exports.createInitialSteps=yt,exports.describeChainSwitchError=it,exports.duration=P,exports.easing=T,exports.ensureSmartWallet=ye,exports.ensureWalletOnChain=Xe,exports.font=O,exports.formatBalance=Ft,exports.formatDecimalInput=jt,exports.formatUsd=Mt,exports.getAllAssetsForChain=Ze,exports.getChainConfig=N,exports.getChainName=V,exports.getChainsForAssets=Ke,exports.getClientForChain=de,exports.getDelegateContractAddress=Qe,exports.getExplorerUrl=Ve,exports.getRelayerErrorDetail=rt,exports.getTokenDecimals=et,exports.getWalletBalanceEntries=pt,exports.hasStoredSpiceFlowMode=St,exports.isSpiceflowError=X,exports.isUserRejection=fe,exports.parseNumericInput=Lt,exports.radius=Oe,exports.relayerFetch=_,exports.relayerService=U,exports.resolveTheme=Be,exports.sanitizeError=at,exports.transition=De,exports.truncateAddress=Se,exports.useIsUserWhitelisted=xe,exports.useProviderWallets=te,exports.useSpiceBrand=ke,exports.useWallet=we,exports.z=qe;
|
package/dist/types/deposit.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { ChainBatch } from ".";
|
|
|
3
3
|
import { UseAssetInputReturn } from "../hooks/useAssetInput";
|
|
4
4
|
import { Asset } from "./assets";
|
|
5
5
|
import { CustomStyles, Theme } from "./theme";
|
|
6
|
+
import type { RelayerErrorDetail } from "../utils/errors";
|
|
6
7
|
import type { IntentStatus } from "./status";
|
|
7
8
|
import type { Network } from "@spicenet-io/spiceflow-core";
|
|
8
9
|
import type { VerifiedPendingDeposit } from "../hooks/usePendingDeposit";
|
|
@@ -52,7 +53,7 @@ export interface DepositModalProps {
|
|
|
52
53
|
sourceChain?: string;
|
|
53
54
|
txHash?: string;
|
|
54
55
|
}) => void;
|
|
55
|
-
onDepositError?: (error: string) => void;
|
|
56
|
+
onDepositError?: (error: string, detail?: RelayerErrorDetail) => void;
|
|
56
57
|
onViewAllAssets?: () => void;
|
|
57
58
|
}
|
|
58
59
|
export interface EscrowRecovery {
|
|
@@ -84,7 +85,7 @@ export interface SpiceDepositProps {
|
|
|
84
85
|
sourceChain?: string;
|
|
85
86
|
txHash?: string;
|
|
86
87
|
}) => void;
|
|
87
|
-
onDepositError?: (error: string) => void;
|
|
88
|
+
onDepositError?: (error: string, detail?: RelayerErrorDetail) => void;
|
|
88
89
|
skipRecovery?: boolean;
|
|
89
90
|
}
|
|
90
91
|
export interface SelectTokenModalProps {
|
package/dist/types/lock.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { CustomStyles } from "./theme";
|
|
2
|
+
import type { RelayerErrorDetail } from "../utils/errors";
|
|
2
3
|
import { Address } from "viem";
|
|
3
4
|
import { ChainBatch } from ".";
|
|
4
5
|
import { UseAssetInputReturn } from "../hooks/useAssetInput";
|
|
@@ -39,7 +40,7 @@ export interface SpiceLockModalProps {
|
|
|
39
40
|
votingPowerEstimate?: (amount: number, months: number) => number;
|
|
40
41
|
escrowAddress?: Address;
|
|
41
42
|
onLockSuccess?: (txHash?: string) => void;
|
|
42
|
-
onLockError?: (error: string) => void;
|
|
43
|
+
onLockError?: (error: string, detail?: RelayerErrorDetail) => void;
|
|
43
44
|
onLockExecute?: (ctx: LockExecuteContext) => Promise<string | void>;
|
|
44
45
|
sourceToDestinationConversionRate?: number;
|
|
45
46
|
onAddFunds?: () => void;
|
package/dist/types/status.d.ts
CHANGED
package/dist/types/supply.d.ts
CHANGED
|
@@ -3,7 +3,9 @@ import type { Address } from "viem";
|
|
|
3
3
|
import type { Asset } from "./assets";
|
|
4
4
|
import type { Call, ChainBatch } from "./authorization";
|
|
5
5
|
import type { CustomStyles } from "./theme";
|
|
6
|
+
import type { RelayerErrorDetail } from "../utils/errors";
|
|
6
7
|
import type { ExactOutputSwapIntent, ResolvedExactOutputSwap } from "../utils/swapQuotes";
|
|
8
|
+
import type { ExecutionOptions } from "../hooks/useSpiceExecution";
|
|
7
9
|
export interface DestinationTokenConfig {
|
|
8
10
|
address: Address;
|
|
9
11
|
symbol: string;
|
|
@@ -34,6 +36,9 @@ export interface SupplyBatchBuildOptions {
|
|
|
34
36
|
withdrawalAmountOverride?: bigint;
|
|
35
37
|
actionContextOverride?: Partial<BuildActionCallsContext>;
|
|
36
38
|
}
|
|
39
|
+
export type BuildPayBatchesFn = (options?: SupplyBatchBuildOptions) => Promise<ChainBatch[]>;
|
|
40
|
+
export type BuildSupplyBatchesFn = (options?: SupplyBatchBuildOptions) => Promise<ChainBatch[]>;
|
|
41
|
+
export type EstimateRequiredGrossFundingFn = (requiredNetFunding: bigint, buildBatches: (grossFundingAmount: bigint) => ChainBatch[] | Promise<ChainBatch[]>, fundingToken: Address, executionOptions?: Pick<ExecutionOptions, "useCustomTransfers" | "userOverride">) => Promise<bigint>;
|
|
37
42
|
export interface PayExecuteContext {
|
|
38
43
|
asset: Asset;
|
|
39
44
|
amount: string;
|
|
@@ -87,7 +92,7 @@ export interface SpiceSupplyProps {
|
|
|
87
92
|
subtitle?: React.ReactNode;
|
|
88
93
|
onAddFunds?: () => void;
|
|
89
94
|
onSuccess?: (txHash: string) => void;
|
|
90
|
-
onError?: (error: Error) => void;
|
|
95
|
+
onError?: (error: Error, detail?: RelayerErrorDetail) => void;
|
|
91
96
|
}
|
|
92
97
|
export interface SupplyEstimateProps {
|
|
93
98
|
isQuoting: boolean;
|
package/dist/types/withdraw.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Address } from "viem";
|
|
2
2
|
import type { CustomStyles } from "./theme";
|
|
3
3
|
import type { ChainBatch } from "./authorization";
|
|
4
|
+
import type { RelayerErrorDetail } from "../utils/errors";
|
|
4
5
|
export interface DestinationToken {
|
|
5
6
|
address: Address;
|
|
6
7
|
symbol: string;
|
|
@@ -24,7 +25,7 @@ export interface SpiceWithdrawProps {
|
|
|
24
25
|
amount: string;
|
|
25
26
|
chainId: number;
|
|
26
27
|
}) => void;
|
|
27
|
-
onWithdrawError?: (error: string) => void;
|
|
28
|
+
onWithdrawError?: (error: string, detail?: RelayerErrorDetail) => void;
|
|
28
29
|
availableTokens?: Record<number, DestinationToken[]>;
|
|
29
30
|
buildSpicenetBatch?: (params: {
|
|
30
31
|
destinationChainId: number;
|
|
@@ -41,17 +42,3 @@ export interface SelectPopoverItem {
|
|
|
41
42
|
icon?: string;
|
|
42
43
|
detail?: string;
|
|
43
44
|
}
|
|
44
|
-
export interface SpiceWithdrawRequest {
|
|
45
|
-
user: string;
|
|
46
|
-
txHash: string;
|
|
47
|
-
recipient: string;
|
|
48
|
-
tokenAddress: string;
|
|
49
|
-
chainId: number;
|
|
50
|
-
amount: string;
|
|
51
|
-
}
|
|
52
|
-
export interface SpiceWithdrawResponse {
|
|
53
|
-
success: boolean;
|
|
54
|
-
error?: {
|
|
55
|
-
message: string;
|
|
56
|
-
};
|
|
57
|
-
}
|
|
@@ -18,13 +18,6 @@ export declare function appendWalletFundedEscrowDeposit({ chainBatches, token, a
|
|
|
18
18
|
token: Address;
|
|
19
19
|
amount: bigint;
|
|
20
20
|
}): ChainBatch[];
|
|
21
|
-
export declare function buildActionOutputEscrowFundingPlan({ chainBatches, user, token, grossAmount, gasFee, }: {
|
|
22
|
-
chainBatches: ChainBatch[];
|
|
23
|
-
user: Address;
|
|
24
|
-
token: Address;
|
|
25
|
-
grossAmount: bigint;
|
|
26
|
-
gasFee: bigint;
|
|
27
|
-
}): ActionOutputEscrowFundingPlan;
|
|
28
21
|
export declare function resolveActionOutputEscrowFundingPlan({ chainBatches, user, token, grossAmount, chainAuthorizations, }: {
|
|
29
22
|
chainBatches: ChainBatch[];
|
|
30
23
|
user: Address;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function scaleAmountDecimals(amount: bigint, fromDecimals: number, toDecimals: number, rounding: "ceil" | "floor"): bigint;
|
|
@@ -6,7 +6,6 @@ export declare const CHAIN_CONFIGS: {
|
|
|
6
6
|
[chainId: number]: UIChainConfig;
|
|
7
7
|
};
|
|
8
8
|
export declare const setRpcOverrides: (overrides?: Record<number, string>) => void;
|
|
9
|
-
export declare const getRpcUrlForChain: (chainId: number) => string | undefined;
|
|
10
9
|
export declare const getChainConfig: (chainId: number) => UIChainConfig | undefined;
|
|
11
10
|
export declare const getChainName: (chainId: number) => string;
|
|
12
11
|
export declare const getDelegateContractAddress: (chainId: number) => string;
|
|
@@ -10,7 +10,6 @@ export interface ResolveRouteParams {
|
|
|
10
10
|
destinationChainId: number;
|
|
11
11
|
intermediaryCandidates?: string[];
|
|
12
12
|
}
|
|
13
|
-
export declare function findTokenOnChain(symbol: string, chainId: number): ChainToken | undefined;
|
|
14
13
|
export declare function findEquivalentOnChain(tokenAddress: string, targetChainId: number, sourceChainId?: number): ChainToken | undefined;
|
|
15
14
|
export declare function resolveRoute(params: ResolveRouteParams): RoutePlan;
|
|
16
15
|
export interface BuildRoutedBatchesParams {
|
|
@@ -2,7 +2,6 @@ import { type Address } from "viem";
|
|
|
2
2
|
import type { Call, SwapIntent, BatchEntry, ResolvedSwap } from "@spicenet-io/spiceflow-core";
|
|
3
3
|
import type { ExactOutputVenue } from "../swapQuotes";
|
|
4
4
|
export type { ResolvedSwap };
|
|
5
|
-
export declare function isSwapIntent(entry: BatchEntry): entry is SwapIntent;
|
|
6
5
|
export interface LiquidityVenue {
|
|
7
6
|
name: string;
|
|
8
7
|
chainIds: number[];
|
|
@@ -13,7 +12,6 @@ export interface OneInchVenueConfig {
|
|
|
13
12
|
baseUrl?: string;
|
|
14
13
|
chainIds?: number[];
|
|
15
14
|
}
|
|
16
|
-
export declare function create1inchVenue(config?: OneInchVenueConfig): LiquidityVenue;
|
|
17
15
|
export interface SatsumaVenueConfig {
|
|
18
16
|
swapRouter: Address;
|
|
19
17
|
quoterV2: Address;
|
|
@@ -14,15 +14,11 @@ export interface UniV3ExactOutputQuoteResult {
|
|
|
14
14
|
sqrtPriceX96After: bigint;
|
|
15
15
|
gasEstimate: bigint;
|
|
16
16
|
}
|
|
17
|
-
export declare function getUniV3Quote(params: UniV3QuoteParams): Promise<UniV3QuoteResult>;
|
|
18
17
|
export declare function getBestUniV3Quote(params: Omit<UniV3QuoteParams, "fee"> & {
|
|
19
18
|
feeTiers?: number[];
|
|
20
19
|
}): Promise<UniV3QuoteResult & {
|
|
21
20
|
fee: number;
|
|
22
21
|
}>;
|
|
23
|
-
export declare function getUniV3ExactOutputQuote(params: UniV3ExactOutputQuoteParams & {
|
|
24
|
-
fee: number;
|
|
25
|
-
}): Promise<UniV3ExactOutputQuoteResult>;
|
|
26
22
|
export declare function getBestUniV3ExactOutputQuote(params: UniV3ExactOutputQuoteParams & {
|
|
27
23
|
feeTiers?: number[];
|
|
28
24
|
}): Promise<UniV3ExactOutputQuoteResult & {
|
package/dist/utils/errors.d.ts
CHANGED
|
@@ -8,6 +8,14 @@ export declare class SpiceflowError extends Error {
|
|
|
8
8
|
}
|
|
9
9
|
export declare function isSpiceflowError(err: unknown): err is SpiceflowError;
|
|
10
10
|
export declare const isUserRejection: (error: unknown) => boolean;
|
|
11
|
+
export interface RelayerErrorDetail {
|
|
12
|
+
requestId?: string;
|
|
13
|
+
httpStatus?: number;
|
|
14
|
+
responseBody?: string;
|
|
15
|
+
endpoint?: string;
|
|
16
|
+
}
|
|
17
|
+
export declare function getRelayerErrorDetail(message: string): RelayerErrorDetail | undefined;
|
|
11
18
|
export declare const sanitizeError: (error: unknown, fallback?: string) => string;
|
|
12
19
|
export declare function decodeRevertReason(input: unknown): string | undefined;
|
|
13
20
|
export declare function formatFeeEstimateError(request: CreateActionRequest, message: string): string;
|
|
21
|
+
export declare function describeChainSwitchError(switchError: any): string;
|
package/dist/utils/logos.d.ts
CHANGED
|
@@ -1,8 +1,4 @@
|
|
|
1
|
-
import metamaskLogo from "../assets/icons/metamask.png";
|
|
2
|
-
import rabbyLogo from "../assets/icons/rabby.png";
|
|
3
|
-
import phantomLogo from "../assets/icons/phantom.png";
|
|
4
1
|
import spicenetLogo from "../assets/icons/spicenet-mark.svg";
|
|
5
|
-
export { metamaskLogo, rabbyLogo, phantomLogo };
|
|
6
2
|
export declare const ethLogo: string;
|
|
7
3
|
export declare const usdcLogo: string;
|
|
8
4
|
export { spicenetLogo };
|
|
@@ -3,11 +3,14 @@ import { SwapStep } from "../../types/status";
|
|
|
3
3
|
import { ChainBatch, ChainAuthorization } from "../../types/authorization";
|
|
4
4
|
import type { RollupBalanceEntry } from "../rollupBalances";
|
|
5
5
|
export declare const RELAYER_API_URL: string;
|
|
6
|
+
export declare function relayerFetch(endpoint: string, init?: RequestInit): Promise<Response & {
|
|
7
|
+
requestId?: string;
|
|
8
|
+
}>;
|
|
6
9
|
export declare class RelayerService {
|
|
7
10
|
private baseUrl;
|
|
8
11
|
setBaseUrl(url: string): void;
|
|
9
12
|
getBaseUrl(): string;
|
|
10
|
-
private
|
|
13
|
+
private requestJson;
|
|
11
14
|
createAction(request: CreateActionRequest): Promise<CreateActionResponse>;
|
|
12
15
|
estimateActionFees(request: CreateActionRequest): Promise<FeeEstimateSummary>;
|
|
13
16
|
estimateBatchGas(request: {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@spicenet-io/spiceflow-ui",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.1.1",
|
|
4
4
|
"description": "Spiceflow UI SDK",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"packageManager": "bun@1.3.13",
|
|
@@ -54,13 +54,11 @@
|
|
|
54
54
|
"license": "MIT",
|
|
55
55
|
"dependencies": {
|
|
56
56
|
"@spicenet-io/spiceflow-core": "^0.3.14",
|
|
57
|
-
"lucide-react": "0.562.0",
|
|
58
57
|
"tslib": "2.8.1"
|
|
59
58
|
},
|
|
60
59
|
"peerDependencies": {
|
|
61
60
|
"@privy-io/react-auth": ">=2.24.0 <4.0.0",
|
|
62
61
|
"@tanstack/react-query": ">=5.0.0",
|
|
63
|
-
"axios": ">=1.0.0",
|
|
64
62
|
"react": "^18.0.0",
|
|
65
63
|
"react-dom": "^18.0.0",
|
|
66
64
|
"viem": ">=2.21.0",
|
|
@@ -78,34 +76,22 @@
|
|
|
78
76
|
"@rollup/plugin-json": "6.1.0",
|
|
79
77
|
"@rollup/plugin-node-resolve": "16.0.3",
|
|
80
78
|
"@rollup/plugin-replace": "6.0.3",
|
|
81
|
-
"@rollup/plugin-typescript": "12.3.0",
|
|
82
79
|
"@tanstack/react-query": "5.90.10",
|
|
83
80
|
"@types/node": "24.10.1",
|
|
84
81
|
"@types/react": "18.3.27",
|
|
85
82
|
"@types/react-dom": "18.3.7",
|
|
86
|
-
"
|
|
87
|
-
"@typescript-eslint/parser": "6.21.0",
|
|
88
|
-
"axios": "1.13.5",
|
|
83
|
+
"dotenv": "16.6.1",
|
|
89
84
|
"esbuild": "0.24.2",
|
|
90
|
-
"eslint": "8.57.1",
|
|
91
|
-
"eslint-config-prettier": "10.1.8",
|
|
92
|
-
"eslint-plugin-react": "7.37.5",
|
|
93
|
-
"eslint-plugin-react-hooks": "4.6.2",
|
|
94
85
|
"husky": "9.1.7",
|
|
95
|
-
"jest": "29.7.0",
|
|
96
86
|
"lint-staged": "17.0.8",
|
|
97
87
|
"postcss": "8.5.6",
|
|
98
|
-
"postcss-import": "16.1.1",
|
|
99
88
|
"prettier": "3.9.5",
|
|
100
89
|
"react": "18.3.1",
|
|
101
90
|
"react-dom": "18.3.1",
|
|
102
91
|
"rollup": "4.53.2",
|
|
103
|
-
"rollup-plugin-copy": "3.5.0",
|
|
104
92
|
"rollup-plugin-esbuild": "6.2.1",
|
|
105
93
|
"rollup-plugin-peer-deps-external": "2.2.4",
|
|
106
94
|
"rollup-plugin-postcss": "4.0.2",
|
|
107
|
-
"sharp": "0.34.5",
|
|
108
|
-
"ts-node": "10.9.2",
|
|
109
95
|
"typescript": "5.9.3",
|
|
110
96
|
"viem": "2.38.0",
|
|
111
97
|
"wagmi": "2.19.5"
|
package/dist/privy-BdHp5Owr.js
DELETED
|
Binary file
|
package/dist/privy-Ds5DCgFX.js
DELETED
|
Binary file
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import type { Address } from "viem";
|
|
2
|
-
import type { ChainBatch } from "../../types/authorization";
|
|
3
|
-
import type { LiquidityRegistry } from "./liquidityVenues";
|
|
4
|
-
import type { ChainToken, RoutePlan, TokenRef, ResolvedSwap, Call } from "@spicenet-io/spiceflow-core";
|
|
5
|
-
export type { TokenRef };
|
|
6
|
-
export interface IntentAction {
|
|
7
|
-
chainId: number;
|
|
8
|
-
outputToken: TokenRef;
|
|
9
|
-
calls: Call[];
|
|
10
|
-
supportedInputTokens?: TokenRef[];
|
|
11
|
-
}
|
|
12
|
-
export interface BuildIntentParams {
|
|
13
|
-
action: IntentAction;
|
|
14
|
-
inputToken: TokenRef;
|
|
15
|
-
inputAmount: bigint;
|
|
16
|
-
registry: LiquidityRegistry;
|
|
17
|
-
userAddress: Address;
|
|
18
|
-
slippage?: number;
|
|
19
|
-
intermediaryCandidates?: string[];
|
|
20
|
-
}
|
|
21
|
-
export interface BuildIntentResult {
|
|
22
|
-
chainBatches: ChainBatch[];
|
|
23
|
-
route: RoutePlan;
|
|
24
|
-
resolvedSwaps: {
|
|
25
|
-
sourceSwap?: ResolvedSwap;
|
|
26
|
-
destinationSwap?: ResolvedSwap;
|
|
27
|
-
};
|
|
28
|
-
resolvedInputToken: ChainToken;
|
|
29
|
-
resolvedOutputToken: ChainToken;
|
|
30
|
-
solverFrontToken: ChainToken;
|
|
31
|
-
solverFrontAmount: bigint;
|
|
32
|
-
}
|
|
33
|
-
export declare function resolveTokenRef(ref: TokenRef): ChainToken;
|
|
34
|
-
export declare function buildIntent(params: BuildIntentParams): Promise<BuildIntentResult>;
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import type { Call, ChainBatch } from "../../types/authorization";
|
|
2
|
-
import type { ExecutionOptions, OnProgress } from "../../hooks/useSpiceExecution";
|
|
3
|
-
export type ExecuteFn = (chainBatches: ChainBatch[], tokenAddress: string, tokenTransferAmount: bigint, onProgress?: OnProgress, signal?: AbortSignal, options?: ExecutionOptions) => Promise<string>;
|
|
4
|
-
export interface SwapThenActionParams {
|
|
5
|
-
chainId: number;
|
|
6
|
-
swapCalls: Call[];
|
|
7
|
-
quoteAmountOut: bigint;
|
|
8
|
-
buildActionCalls: (adjustedAmount: bigint) => Call[];
|
|
9
|
-
tokenAddress: string;
|
|
10
|
-
tokenTransferAmount: bigint;
|
|
11
|
-
onProgress?: OnProgress;
|
|
12
|
-
signal?: AbortSignal;
|
|
13
|
-
options?: ExecutionOptions;
|
|
14
|
-
buffers?: bigint[];
|
|
15
|
-
}
|
|
16
|
-
export declare function applyBuffer(amount: bigint, buffer: bigint): bigint;
|
|
17
|
-
export declare function executeSwapThenAction(execute: ExecuteFn, params: SwapThenActionParams): Promise<string>;
|