@naculus/connect-appkit-react 0.2.3 → 0.2.4
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/README.md +20 -2
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +35 -23
- package/dist/index.d.ts +35 -23
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{formatSol as fh,getLatestBlockhash as gh,getSignatureStatus as hh,getSolanaBalance as Ch,LAMPORTS_PER_SOL as yh,PassphraseCancelledError as wh,PassphraseGate as Sh,parseSol as Eh,SolanaRpcError as kh}from"@naculus/connect-core";import{useCallback as cn,useEffect as un,useRef as pn,useState as st}from"react";function Nr(e){return e?Object.keys(e).sort().map(t=>{let r=e[t];return`${t}=${typeof r=="object"&&r!==null?"[object]":String(r)}`}).join("&"):""}function dn(e,t){let{operation:r,chains:s,options:n}=e,[i,a]=st([]),[g,u]=st(!1),[c,h]=st(null),o=pn(!0),l=pn(0),d=`${r}|${(s??[]).join(",")}|${Nr(n)}`,f=cn(async()=>{if(!s||s.length===0){a([]);return}if(!t)return;let y=++l.current;u(!0),h(null);try{let C=await t(r,s,n);o.current&&y===l.current&&a(C)}catch(C){o.current&&y===l.current&&(h(C instanceof Error?C:new Error(String(C))),a([]))}finally{o.current&&y===l.current&&u(!1)}},[d,t]);un(()=>{f()},[f]),un(()=>(o.current=!0,()=>{o.current=!1}),[]);let m=cn(async()=>{await f()},[f]);return{comparisons:i,loading:g,error:c,refresh:m}}import{isValidAddress as Dr}from"@naculus/connect-core";import{useCallback as mn,useEffect as Mr,useRef as fn,useState as at}from"react";function gn(e){let[t,r]=at(!1),[s,n]=at(null),[i,a]=at(null),g=fn(!0),u=fn(!1);Mr(()=>(g.current=!0,()=>{g.current=!1}),[]);let c=mn(async(o,l,d)=>{if(!e)return a({code:"no_executor",message:"No executeRoute function provided"}),n(null),null;if(typeof l!="string"||l.trim()==="")return a({code:"invalid_recipient",message:"A recipient address is required"}),n(null),null;let f=o?.toChain?.split(":")[0];if(f&&!Dr(l,f))return a({code:"invalid_recipient",message:`"${l}" is not a valid ${f} address for the destination chain ${o.toChain}`}),n(null),null;if(u.current)return a({code:"execution_in_progress",message:"A route execution is already in progress"}),null;u.current=!0,r(!0),a(null),n(null);try{let m=await e(o,l,d);return g.current&&n(m),m}catch(m){let y=m;return g.current&&a({code:y.code??"execution_failed",message:y.message,details:y.details}),null}finally{u.current=!1,g.current&&r(!1)}},[e]),h=mn(()=>{n(null),a(null),r(!1)},[]);return{execute:c,executing:t,result:s,error:i,reset:h}}import{useCallback as it,useEffect as hn,useRef as Cn,useState as lt}from"react";function yn(e,t){let{fromChain:r,toChain:s,fromToken:n,toToken:i,amount:a,options:g}=e,[u,c]=lt([]),[h,o]=lt(!1),[l,d]=lt(null),f=Cn(null),m=Cn(!0),y=it(async()=>{let E=/^(?:0|[1-9][0-9]*)$/.test(a)&&BigInt(a)>0n;if(!r||!s||!n||!E){c([]);return}if(t){o(!0),d(null);try{let T=await t(r,s,n,a,g,i);m.current&&c(T)}catch(T){m.current&&(d(T instanceof Error?T:new Error(String(T))),c([]))}finally{m.current&&o(!1)}}},[r,s,n,i,a,g,t]);hn(()=>{if(f.current&&clearTimeout(f.current),!r||!s||!n||!a){c([]);return}return f.current=setTimeout(()=>{y()},300),()=>{f.current&&clearTimeout(f.current)}},[y,r,s,n,a]),hn(()=>(m.current=!0,()=>{m.current=!1}),[]);let C=it(async()=>{await y()},[y]),S=it(()=>{c([]),d(null),o(!1)},[]);return{quotes:u,loading:h,error:l,refresh:C,clear:S}}import{logger as ct,WalletError as q}from"@naculus/connect-core";import{eip6963Connector as V}from"@naculus/connector-evm-injected";import{PassphraseGate as Lr}from"@naculus/connect-core";import{createWalletConnectConnector as Br}from"@naculus/connector-walletconnect";var ut=null;function pt(e){let t=null,r=Br({projectId:e.projectId,metadata:e.metadata}),s=null,n=null,i=null,a=null,g=e.passphrasePrompt&&e.enableEmbedded&&!e.embeddedConfig?.encryptionPassphrase?new Lr:null;e.enableEmbedded&&(n=import("@naculus/connector-embedded").then(o=>{let l={...e.embeddedConfig};g&&(l.encryptionPassphrase=g.request),e.enablePasskeys&&l.encryptionPassphrase&&!l.prfUnlock&&(l.prfUnlock={async derive(f){a&&await a;let m=i;return m?.hasCredential()?m.derivePrfKey(f):null}}),s=o.createPocketConnector(l),t?._setEmbeddedConnector(s)}).catch(o=>{ct.warn("react/client","Embedded wallet connector not available:",o),s=null})),e.enablePasskeys&&(a=import("@naculus/connector-passkeys").then(o=>{i=o.createPasskeysConnector(),t?._setPasskeysConnector(i)}).catch(o=>{ct.warn("react/client","Passkeys connector not available:",o),i=null}));let u=null,c=null;e.enableSolana&&(c=import("@naculus/connector-solana").then(o=>{let l=o.solanaConnector;e.solanaDefaultChain&&"configure"in l&&l.configure({defaultChain:e.solanaDefaultChain}),u=l,typeof window<"u"&&"startDiscovery"in l&&l.startDiscovery(),t?._setSolanaConnector(u)}).catch(o=>{ct.warn("react/client","Solana connector not available:",o),u=null})),typeof window<"u"&&V.startDiscovery();let h={connector:r,get embeddedConnector(){return s},getEmbeddedConnector:async()=>(n&&await n,s),get passkeysConnector(){return i},passphraseGate:g,solanaRpcUrl:e.solanaRpcUrl??null,get solanaConnector(){return u},connect:()=>r.connect(),connectInjected:async o=>V.connect(o),connectEmbedded:async()=>{if(n&&await n,!s)throw new Error("Embedded wallet not enabled. Set enableEmbedded: true in config.");return s.connect()},connectPasskeys:async()=>{if(a&&await a,!i)throw new Error("Passkeys connector not enabled. Set enablePasskeys: true in config.");return i.connect()},startPairing:()=>r.startPairing(),completePairing:()=>r.completePairing(),cancelPairing:()=>r.cancelPairing?.(),signMessage:async(o,l)=>{if(o.id?.startsWith("eip6963-"))return V.signMessage(o,l);if(o.walletType==="passkeys"&&i)return i.signMessage(o,l);if(o.walletType==="embedded"){if(!s)throw new q("wallet_unavailable","Embedded wallet connector not available.");return s.signMessage(o,l)}if(o.walletType==="solana"){if(c&&await c,u)return u.signMessage(o,l);throw new q("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}return r.signMessage(o,l)},signTransaction:async(o,l)=>{if(o.id?.startsWith("eip6963-"))return V.signTransaction(o,l);if(o.walletType==="embedded"){if(!s)throw new q("wallet_unavailable","Embedded wallet connector not available.");return s.signTransaction(o,l)}if(o.walletType==="solana"){if(c&&await c,u)return u.signTransaction(o,l);throw new q("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}return r.signTransaction(o,l)},sendTransaction:async(o,l)=>{if(o.id?.startsWith("eip6963-"))return V.sendTransaction(o,l);if(o.walletType==="passkeys"&&i)return i.sendTransaction(o,l);if(o.walletType==="embedded"){if(!s)throw new q("wallet_unavailable","Embedded wallet connector not available.");return s.sendTransaction(o,l)}if(o.walletType==="solana"){if(c&&await c,u)return u.sendTransaction(o,l);throw new q("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}return r.sendTransaction(o,l)},onAccountsChanged:(o,l)=>{let d=()=>{};return o.id?.startsWith("eip6963-")?V.onAccountsChanged?.(o,l)??d:o.walletType==="embedded"?s?.onAccountsChanged?.(o,l)??d:o.walletType==="passkeys"?d:o.walletType==="solana"?u?.onAccountsChanged?.(o,l)??d:r.onAccountsChanged?.(o,l)??d},onChainChanged:(o,l)=>{let d=()=>{};return o.id?.startsWith("eip6963-")?V.onChainChanged?.(o,l)??d:o.walletType==="passkeys"||o.walletType==="embedded"?d:o.walletType==="solana"?u?.onChainChanged?.(o,l)??d:r.onChainChanged?.(o,l)??d},getCapabilities:o=>o.id?.startsWith("eip6963-")?V.getCapabilities?.(o):o.walletType==="passkeys"?i?.getCapabilities?.(o):o.walletType==="solana"?u?.getCapabilities?.(o):o.walletType==="embedded"?s?.getCapabilities?.(o):r.getCapabilities?.(o),sendCalls:async(o,l,d,f)=>{if(o.id?.startsWith("eip6963-"))return V.sendCalls(o,l,d,f);if(o.walletType==="passkeys"&&i)return i.sendCalls(o,l,d,f);if(o.walletType==="solana"){if(c&&await c,u)return u.sendCalls(o,l,d,f);throw new q("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}if(o.walletType==="embedded"){if(!s?.sendCalls)throw new q("method_not_allowed","Embedded wallet does not support sendCalls");return s.sendCalls(o,l,d,f)}if(!r.sendCalls)throw new q("method_not_allowed","sendCalls not supported by this connector");return r.sendCalls(o,l,d,f)},showCallsStatus:async(o,l)=>{if(o.id?.startsWith("eip6963-"))return V.showCallsStatus(o,l);if(o.walletType==="passkeys"||o.walletType==="embedded")throw new q("method_unsupported",`${o.walletType} wallets have no UI to display a call bundle.`);if(!r.showCallsStatus)throw new q("method_unsupported","This connector cannot display call status.");return r.showCallsStatus(o,l)},getCallsStatus:async(o,l)=>{if(o.id?.startsWith("eip6963-")&&V.getCallsStatus)return V.getCallsStatus(o,l);if(o.walletType==="passkeys"&&i?.getCallsStatus)return i.getCallsStatus(o,l);if(o.walletType==="embedded")throw new q("method_not_allowed","Embedded wallet does not support getCallsStatus");if(!r.getCallsStatus)throw new q("method_not_allowed","getCallsStatus not supported by this connector");return r.getCallsStatus(o,l)},reconnect:async o=>o.walletType==="eip6963"?V.reconnect(o):o.walletType==="embedded"?s?s.reconnect(o):o:o.walletType==="solana"?o:r.reconnect(o),disconnect:async o=>{if(o.id?.startsWith("eip6963-")||o.walletType==="eip6963")return V.disconnect(o);if(o.walletType==="embedded"&&s)return s.disconnect();if(o.walletType==="passkeys"&&i)return i.disconnect(o);if(o.walletType==="solana"){if(c&&await c,u)return u.disconnect(o);throw new q("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}return r.disconnect(o)},getAllConnectors:()=>{let o=[r];return s&&o.push(s),i&&o.push(i),u&&o.push(u),o},_setEmbeddedConnector:o=>{s=o},_setPasskeysConnector:o=>{i=o},_setSolanaConnector:o=>{u=o}};return t=h,ut=h,h}function dt(){return ut}function Hr(){ut=null}import{isEvmAddress as xn,parseCaip10 as po}from"@naculus/connect-core";import{useMemo as mo}from"react";import{createConnectorManager as Zr,createSessionManager as eo,LocalStorageSessionStorage as to,logger as ne,WalletError as no}from"@naculus/connect-core";import{eip6963Connector as De}from"@naculus/connector-evm-injected";import{createContext as ro,useCallback as K,useContext as oo,useEffect as ge,useMemo as he,useReducer as so,useRef as En}from"react";import{logger as Fr}from"@naculus/connect-core";import{issueNonce as Kr,parseSiwxMessage as $r}from"@naculus/siwx";function ue(e,t){let r=t.split(":",1)[0],n=(e.namespaces[r]?.accounts??[]).filter(i=>i.startsWith(`${r}:`)).map(i=>({namespace:r,caip10:i}))[0];if(n)return{...n,address:n.caip10.split(":").pop()??n.caip10}}function qr(e){return e.namespaces.eip155?.chains?.[0]??e.namespaces.solana?.chains?.[0]??e.namespaces.xrpl?.chains?.[0]??"eip155:1"}async function wn(e){let{session:t,siwx:r,signMessage:s}=e;if(!r||!t)return{kind:"skipped"};try{let n=qr(t),i=ue(t,n);if(!i)throw new Error("No account found in session");let{address:a}=i,g=await r.createMessage({address:a,chainId:n}),u=$r(g);if(!u?.nonce)throw new Error("SIWx message must contain a nonce");await Kr(u.nonce);let c=await s(t,{message:g,address:a,chainId:n});return await r.handleSignComplete?.({message:g,signature:c}),{kind:"authenticated",address:a,chainId:n}}catch(n){let i=n instanceof Error?n:new Error("Wallet authentication failed");return Fr.error("appkit/core","SIWx authentication failed:",n),{kind:"failed",error:i,fatal:r.required!==!1}}}import{initialWeb3State as ao,web3Reducer as io,withRetry as lo,withTimeout as kn}from"@naculus/connect-appkit-core";import{resolveChain as Vr}from"@naculus/connect-appkit-core";import{CHAINS as Ne,DEFAULT_RPC_URLS as zr,eip155Reference as jr,getRpcUrl as Gr}from"@naculus/connect-core";var Qr=[{caip2:"eip155:5",name:"Goerli",rpcUrl:"https://goerli.blockpi.network/v1/rpc/public",explorerUrl:"https://goerli.etherscan.io",token:"ETH"},{caip2:"eip155:80001",name:"Mumbai",rpcUrl:"https://rpc-mumbai.maticvigil.com",explorerUrl:"https://mumbai.polygonscan.com",token:"MATIC"},{caip2:"eip155:421613",name:"Arbitrum Goerli",rpcUrl:"https://goerli-rollup.arbitrum.io/rpc",explorerUrl:"https://goerli.arbiscan.io",token:"ETH"},{caip2:"eip155:420",name:"Optimism Goerli",rpcUrl:"https://goerli.optimism.io",explorerUrl:"https://goerli-optimism.etherscan.io",token:"ETH"}];function Xr(e){let t=Ne[e];if(!t||!t.explorerUrl)return null;let r=t.caip2Id;return{caip2:r,name:t.name,rpcUrl:Gr(r,zr[r]??""),explorerUrl:t.explorerUrl,token:t.nativeCurrency.symbol}}function Yr(){if(!Ne)return[];let e=[],t=Object.keys(Ne).map(Number).sort((r,s)=>r-s);for(let r of t){let s=Xr(r);s&&e.push(s)}for(let r of Qr){let s=jr(r.caip2);(s===null||!Ne[s])&&e.push(r)}return e}var Sn=Yr();function Jr(e,t){return Vr(e,t)??void 0}function mt(){return[...Sn]}import{jsx as uo}from"react/jsx-runtime";var ft=ro(null);function co({children:e,config:t,autoConnect:r=!0}){let[s,n]=so(io,ao),i=he(()=>t.chains??mt(),[t.chains]),a=t.connectionTimeout??3e4,g=t.maxRetries??2,u=he(()=>new to(t.storageKey??"naculus_web3_session",t.encryptionKey),[t.storageKey,t.encryptionKey]),c=he(()=>pt({projectId:t.projectId,metadata:t.metadata,enableEmbedded:t.enableEmbedded,embeddedConfig:t.embeddedConfig,enablePasskeys:t.enablePasskeys,enableSolana:t.enableSolana,solanaDefaultChain:t.solanaDefaultChain}),[t.projectId,t.metadata,t.enableEmbedded,t.embeddedConfig,t.enablePasskeys,t.enableSolana,t.solanaDefaultChain]),h=En(null),o=En(null),l=he(()=>{let p=Zr();for(let N of[De,...c.getAllConnectors()])p.register(N.id,N);let w={},x={};for(let N of i){let D=N.caip2;N.rpcUrl&&(w[D]=N.rpcUrl),N.token&&(x[D]={name:N.name,symbol:N.token,decimals:18})}let W=eo(p,{autoRefreshFeeOnSwitch:t.autoRefreshFeeOnSwitch??!0,defaultRpcUrls:w,defaultCurrencies:x,encryptionKey:t.encryptionKey});return h.current=W,W},[c,i,t.autoRefreshFeeOnSwitch,t.encryptionKey]);ge(()=>{let p=W=>{let{walletSession:N}=W.bundle;n({type:"SET_SESSION",payload:N});let D=[];Object.values(N.namespaces).forEach(F=>{D.push(...F.accounts)}),n({type:"SET_ACCOUNTS",payload:D}),n({type:"SET_CHAIN",payload:W.bundle.activeChainId}),n({type:"SET_STATUS",payload:"connected"})},w=()=>{n({type:"RESET"})},x=W=>{n({type:"SET_CHAIN",payload:W.newChainId})};return l.on("sessionConnected",p),l.on("sessionDisconnected",w),l.on("chainChanged",x),()=>{l.off("sessionConnected",p),l.off("sessionDisconnected",w),l.off("chainChanged",x)}},[l]),ge(()=>{let p=()=>{u.clear(),n({type:"RESET"})};c.connector.onSessionExpiry(p)},[c,u]);let d=K(()=>{for(let p of[De,...c.getAllConnectors()])l.registerConnector(p)},[c,l]),f=K(async p=>{d();let w=[De,...c.getAllConnectors()].find(W=>W.id===p.walletType||W.kind===p.walletType);w&&!p.connectorId&&(p.connectorId=w.id);let x=p.namespaces.eip155?.chains?.[0]??p.namespaces.solana?.chains?.[0]??p.namespaces.xrpl?.chains?.[0];x&&await l.attach(p,x)},[c,l,d]),m=K(p=>{if(n({type:"SET_SESSION",payload:p}),p){let w=[];Object.values(p.namespaces).forEach(D=>{w.push(...D.accounts)}),n({type:"SET_ACCOUNTS",payload:w});let x=p.namespaces.eip155?.chains?.[0],W=p.namespaces.solana?.chains?.[0],N=p.namespaces.xrpl?.chains?.[0];n({type:"SET_CHAIN",payload:x??W??N??null})}else n({type:"SET_ACCOUNTS",payload:[]}),n({type:"SET_CHAIN",payload:null})},[]);ge(()=>{let p=s.session,w=c;return!p||!w?.onAccountsChanged?void 0:w.onAccountsChanged(p,W=>{if(W.length===0){u.clear().finally(()=>n({type:"RESET"}));return}m(p),u.save(p)})},[s.session,c,u,m]),ge(()=>{let p=s.session,w=c;if(!(!p||!w?.onChainChanged))return w.onChainChanged(p,x=>{m(p),u.save(p);let W=l.syncExternalChain;if(!W)return;let N=W.call(l,x).catch(D=>{ne.warn("react/provider","External chain sync error:",D)});o.current=N,N.finally(()=>{o.current===N&&(o.current=null)})})},[s.session,c,u,m,l]);let y=K(async p=>{if(!t.siwx||!p)return!0;n({type:"SET_STATUS",payload:"authenticating"});let w=await wn({session:p,siwx:t.siwx,signMessage:(x,W)=>c.signMessage(x,W)});return w.kind==="failed"&&w.fatal?(await u.clear(),n({type:"RESET"}),n({type:"SET_ERROR",payload:w.error}),!1):!0},[t.siwx,c,u]),C=K(async()=>{n({type:"SET_STATUS",payload:"connecting"}),n({type:"SET_ERROR",payload:null});try{let p=await kn(c.connect(),a,"Wallet connect");await u.save(p),m(p);try{await f(p)}catch(w){ne.warn("react/provider","SessionManager sync error:",w)}if(!await y(p))return;n({type:"SET_STATUS",payload:"connected"})}catch(p){let w=p instanceof Error?p.message:"Connection failed";n({type:"SET_ERROR",payload:p instanceof Error?p:new Error(w)}),n({type:"SET_STATUS",payload:"disconnected"})}},[c,u,m,a,y,f]),S=K(async()=>{n({type:"SET_STATUS",payload:"connecting"}),n({type:"SET_ERROR",payload:null});try{let p=await c.connectEmbedded();if(await u.save(p),m(p),await f(p),!await y(p))return;n({type:"SET_STATUS",payload:"connected"})}catch(p){let w=p instanceof Error?p.message:"Embedded wallet connection failed";n({type:"SET_ERROR",payload:p instanceof Error?p:new Error(w)}),n({type:"SET_STATUS",payload:"disconnected"})}},[c,u,m,y,f]),E=K(async()=>{n({type:"SET_STATUS",payload:"connecting"}),n({type:"SET_ERROR",payload:null});try{let p=await c.connectPasskeys();if(await u.save(p),m(p),await f(p),!await y(p))return;n({type:"SET_STATUS",payload:"connected"})}catch(p){let w=p instanceof Error?p.message:"Passkeys connection failed";n({type:"SET_ERROR",payload:p instanceof Error?p:new Error(w)}),n({type:"SET_STATUS",payload:"disconnected"})}},[c,u,m,y,f]),T=K(async()=>{if(!s.session){n({type:"RESET"});return}try{await c.disconnect(s.session)}catch(p){ne.error("react/provider","Disconnect error:",p)}try{let p=h.current;p&&await p.disconnect()}catch(p){ne.warn("react/provider","SessionManager disconnect error:",p)}await u.clear(),n({type:"RESET"})},[c,s.session,u]),v=K(async p=>{n({type:"SET_STATUS",payload:"connecting"}),n({type:"SET_ERROR",payload:null});try{let w=await kn(c.connectInjected(p),a,"Injected wallet connect");await u.save(w),m(w);try{await f(w)}catch(x){ne.warn("react/provider","SessionManager sync error:",x)}if(!await y(w))return;n({type:"SET_STATUS",payload:"connected"})}catch(w){let x=w instanceof Error?w.message:"Connection failed";n({type:"SET_ERROR",payload:w instanceof Error?w:new Error(x)}),n({type:"SET_STATUS",payload:"disconnected"})}},[c,u,m,a,y,f]),I=K(async()=>c.startPairing(),[c]),A=K(()=>{c.cancelPairing?.()},[c]),U=K(async()=>{let p=await c.completePairing();return await u.save(p),m(p),await f(p),await y(p)&&n({type:"SET_STATUS",payload:"connected"}),p},[c,u,m,y,f]),k=K(async p=>{let w=t.siwx;if(!w||w.required===!1)return!0;try{if(await w.hasValidSession?.())return!0}catch(x){ne.warn("react/provider","siwx.hasValidSession failed",x)}return y(p)},[t.siwx,y]),R=K(async()=>{let p=await u.load();if(!p){n({type:"SET_STATUS",payload:"disconnected"});return}n({type:"SET_STATUS",payload:"reconnecting"});try{let w=await lo(()=>c.reconnect(p),{maxRetries:g,baseDelay:1e3,label:"reconnect"});m(w);try{let x=h.current;x&&(d(),await x.restoreFromPersistence())}catch(x){ne.warn("react/provider","SessionManager restore error:",x)}if(!await k(w))return;n({type:"SET_STATUS",payload:"connected"})}catch(w){ne.error("react/provider","Reconnect error:",w),await u.clear(),n({type:"SET_STATUS",payload:"disconnected"}),n({type:"SET_SESSION",payload:null})}},[c,u,m,g,d,k]),b=K(async p=>{o.current&&await o.current;let w=h.current;if(w?.getActiveBundle()){await w.switchChain(p),m(s.session);return}if(!s.session)throw new Error("No active session");try{s.session.walletType==="eip6963"||s.session.id?.startsWith("eip6963-")?await De.switchChain(s.session,p):s.session.walletType==="embedded"&&c.embeddedConnector?await c.embeddedConnector.switchChain?.(s.session,p):s.session.walletType==="passkeys"&&c.passkeysConnector?await c.passkeysConnector.switchChain?.(s.session,p):s.session.walletType==="solana"&&c.solanaConnector?await c.solanaConnector.switchChain?.(s.session,p):await c.connector.switchChain(s.session,p),m(s.session)}catch(x){throw new no("chain_unsupported","Failed to switch chain",x)}},[c,s.session,m]);ge(()=>{r&&R()},[r,R]);let O=K(()=>{n({type:"SET_ERROR",payload:null})},[]),_=he(()=>({...s,connect:C,connectEmbedded:S,connectPasskeys:E,disconnect:T,reconnect:R,switchChain:b,startPairing:I,completePairing:U,cancelPairing:A,connectInjected:v,clearError:O,isConnected:s.status==="connected",chains:i,client:c,sessionManager:l}),[s,C,S,E,T,R,b,I,U,v,O,i,c,l]);return uo(ft.Provider,{value:_,children:e})}function P(){let e=oo(ft);if(!e)throw new Error("useWeb3 must be used within a Web3ConnectProvider");return e}function H(){let{accounts:e,isConnected:t}=P(),r=mo(()=>!t||e.length===0?null:e.map(n=>{let i=po(n);return i?{address:n,namespace:i.namespace,isEVM:i.namespace==="eip155"&&xn(i.address)}:{address:n,namespace:null,isEVM:xn(n)}}),[e,t]),s=r?.find(n=>n.isEVM)?.address??null;return{accounts:r,evmAccount:s,primaryAccount:e[0]??null,isConnected:t,count:e.length}}import{chainNumber as fo,resolveChain as go,toViemChain as ho}from"@naculus/connect-appkit-core";import{useState as Ce,useEffect as gt,useCallback as Co,useMemo as ye,useRef as yo}from"react";import{createPublicClient as wo,http as So,formatEther as Eo}from"viem";import{getNativeTokenPriceUsd as ko}from"@naculus/connect-core";function xo(e){let{evmAccount:t,isConnected:r}=H(),{chainId:s,chains:n}=P(),[i,a]=Ce(null),[g,u]=Ce(!1),[c,h]=Ce(null),[o,l]=Ce(null),d=e?.refreshInterval,f=yo(null),m=ye(()=>go(n,s),[s,n]),y=m?fo(m):null,C=ye(()=>m?ho(m,y):null,[m,y]),S=ye(()=>m?.token??null,[m]),[E,T]=Ce(null);gt(()=>{if(!C||!m?.rpcUrl){T(null);return}let U=wo({transport:So(m.rpcUrl),chain:C});return T(U),()=>{}},[m]);let v=Co(async()=>{if(!t||!E){a(null);return}u(!0),h(null);try{let k=t.includes(":")?t.split(":").pop():t,[R,b]=await Promise.all([E.getBalance({address:k}),s?ko(s,m?.rpcUrl).catch(()=>null):Promise.resolve(null)]);a(R.toString()),l(b)}catch(U){h(U instanceof Error?U:new Error("Failed to fetch balance")),a(null),l(null)}finally{u(!1)}},[t,E,s,m?.rpcUrl]);gt(()=>{r&&t&&v()},[r,t,v]),gt(()=>(d&&d>0&&r&&t&&(f.current=setInterval(v,d)),()=>{f.current&&(clearInterval(f.current),f.current=null)}),[d,r,t,v]);let I=ye(()=>{if(i===null)return null;try{return Eo(BigInt(i))}catch{return null}},[i]),A=ye(()=>{if(o===null||I===null)return null;let U=parseFloat(I);if(isNaN(U))return null;let k=U*o;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(k)},[o,I]);return{balance:i,formatted:I,symbol:S,usdPrice:o,usdValue:A,isLoading:g,error:c,refetch:v,chain:m}}import{caip2ToHexChain as vo,readAtomicSupport as bo}from"@naculus/connect-core";import{useCallback as Ao,useEffect as To,useRef as Ro,useState as ht}from"react";function M(e){return e??dt()}function Ct(){let{client:e,session:t,chainId:r}=P(),[s,n]=ht(null),[i,a]=ht(!1),[g,u]=ht(null),c=Ro(0),h=Ao(async()=>{let d=++c.current,f=M(e);if(!f?.getCapabilities||!t){n(null),a(!1),u(null);return}a(!0),u(null);try{let m=await f.getCapabilities(t);if(d!==c.current)return;let y={};for(let[C,S]of Object.entries(m??{})){if(!S||typeof S!="object")continue;let{supported:E,maxBatchSize:T}=bo(S);y[C]={chainId:C,atomic:E?"supported":"unsupported",...T===void 0?{}:{maxBatchSize:T},raw:S}}n(y)}catch(m){if(d!==c.current)return;n(null),u(m instanceof Error?m:new Error("Capability query failed"))}finally{d===c.current&&a(!1)}},[e,t]);To(()=>{h()},[h]);let o=r?vo(r):void 0,l=(r?s?.[r]:void 0)??(o?s?.[o]:void 0)??null;return{capabilities:s,current:l,atomic:l?.atomic??"unknown",isFetching:i,error:g,refetch:h}}import{useMemo as yt}from"react";import{chainsForNamespace as Io,describeChain as Uo,resolveChain as Po}from"@naculus/connect-appkit-core";function z(){let{chainId:e,session:t,switchChain:r,chains:s}=P(),n=yt(()=>Po(s,e),[s,e]),i=yt(()=>t?Uo(s,e):null,[s,e,t]),a=yt(()=>Io(s,e),[s,e]);return{chainId:e,currentChain:n,chainInfo:i,availableChains:a,chains:a,isEvm:e?.startsWith("eip155:")??!1,switchChain:r}}import{useCallback as Wo,useState as vn}from"react";import{WalletError as _o}from"@naculus/connect-core";function Oo(){let{connect:e,status:t}=P(),[r,s]=vn(!1),[n,i]=vn(null);return{connect:Wo(async()=>{s(!0),i(null);try{await e()}catch(g){let u=g instanceof Error?g.message:"Connection failed";i(g instanceof _o?g:new Error(u))}finally{s(!1)}},[e]),isConnecting:r||t==="connecting",error:n}}import{readDelegation as Bo,UNKNOWN_DELEGATION as St}from"@naculus/connect-core";import{useCallback as Ho,useEffect as Fo,useRef as Ko,useState as Et}from"react";import{chainNumber as No,toViemChain as Do}from"@naculus/connect-appkit-core";import{useMemo as wt}from"react";import{createPublicClient as Mo,http as bn,createWalletClient as Lo}from"viem";function G(){let{evmAccount:e,isConnected:t}=H(),{currentChain:r,chains:s}=z(),n=r?No(r):null,i=wt(()=>r?Do(r,n):null,[r,n]),a=wt(()=>i?Mo({transport:bn(i.rpcUrls.default.http[0]),chain:i}):null,[r,i]),g=wt(()=>{if(!t||!e||!i)return null;let u=e.includes(":")?e.split(":").pop():e;return Lo({transport:bn(i.rpcUrls.default.http[0]),chain:i,account:u})},[t,e,r,i]);return{publicClient:a,walletClient:g,chains:s}}function we(){let{publicClient:e}=G(),{evmAccount:t}=H(),[r,s]=Et(St),[n,i]=Et(!1),[a,g]=Et(null),u=Ko(0),c=t?.includes(":")?t.split(":").pop():t,h=Ho(async()=>{let o=++u.current;if(!e||!c){s(St),i(!1),g(null);return}i(!0),g(null);try{let l=await e.getCode({address:c});if(o!==u.current)return;s(Bo(l??"0x"))}catch(l){if(o!==u.current)return;s(St),g(l instanceof Error?l:new Error("Code read failed"))}finally{o===u.current&&i(!1)}},[e,c]);return Fo(()=>{h()},[h]),{...r,isFetching:n,error:a,refetch:h}}import{WalletError as $}from"@naculus/connect-core";import{useCallback as se,useEffect as as,useState as Be}from"react";import{recoverMessageAddress as He}from"viem";import{planExecution as zo,WalletError as jo}from"@naculus/connect-core";import{useCallback as An,useState as xt}from"react";import{chooseExecutionStrategy as qo,getAccountCapabilities as Vo,WalletError as re}from"@naculus/connect-core";import{useCallback as Le,useState as Se}from"react";import{WalletError as $o}from"@naculus/connect-core";function Me(e){let t=typeof e=="string"?e:e&&typeof e=="object"&&"hash"in e?e.hash:void 0;if(typeof t=="string"&&/^0x[0-9a-fA-F]{64}$/.test(t))return t;throw new $o("tx_failed","Wallet did not return a valid 32-byte transaction hash")}function kt(){let{session:e,chainId:t,client:r}=P(),[s,n]=Se("idle"),[i,a]=Se(null),[g,u]=Se(null),[c,h]=Se(null),[o,l]=Se(null),d=Le(async(C,S)=>{if(!e){n("failed");let E=new re("wallet_unavailable","No active session");throw a(E),E}if(C.length===0){n("failed");let E=new re("invalid_input","At least one call is required");throw a(E),E}n("awaiting_approval"),a(null),u(null);try{let E=M(r);if(!E)throw new re("wallet_unavailable","Client not initialized");let T=S?.chainId??t??void 0,v=S?.strategy??qo(await Vo(E,e,T),C.length);if(l(v),v==="atomic-batch"){let A=await E.sendCalls(e,C,T,{atomicRequired:!0,...S?.paymasterService?{paymasterService:S.paymasterService}:{}});return n("submitted"),u(A),A}let I="";for(let A=0;A<C.length;A++){let U=C[A];try{I=Me(await E.sendTransaction(e,{transaction:{to:U.to,data:U.data,value:U.value},chainId:T}))}catch(k){throw new re("tx_failed",`Call ${A+1} of ${C.length} failed after ${A} already landed (sent sequentially \u2014 this wallet cannot batch atomically): ${k instanceof Error?k.message:String(k)}`)}}return n("submitted"),u(I),I}catch(E){n("failed");let T=E instanceof Error?E.message:"sendCalls failed";throw a(E instanceof Error?E:new Error(T)),E}},[e,t,r]),f=Le(async C=>{if(!e)throw new re("wallet_unavailable","No active session");let S=C??g;if(!S)throw new re("invalid_input","No bundle hash available");if(!C&&o==="sequential")throw new re("invalid_input","Calls were sent sequentially, so there is no bundle to query. Track the returned transaction hash instead.");let E=M(r);if(!E)throw new re("wallet_unavailable","Client not initialized");let T=await E.getCallsStatus(e,S);return h(T),T},[e,g,r,o]),m=Le(async C=>{if(!e)return!1;let S=C??g;if(!S||!C&&o==="sequential")return!1;let E=M(r);if(!E?.showCallsStatus)return!1;try{return await E.showCallsStatus(e,S),!0}catch{return!1}},[e,g,r,o]),y=Le(()=>{n("idle"),a(null),u(null),h(null),l(null)},[]);return{sendCalls:d,getCallsStatus:f,showCallsStatus:m,status:s,error:i,batchHash:g,callsStatus:c,execution:o,reset:y,isSending:s==="awaiting_approval"}}function vt(e={}){let{current:t,atomic:r}=Ct(),{delegated:s,delegate:n}=we(),{sendCalls:i}=kt(),[a,g]=xt(!1),[u,c]=xt(null),[h,o]=xt(null),l=e.atomicity??"preferred",d=e.sponsorship??"any",f=e.paymasterService,m=e.userOperation,y=e.userOperationSponsored??!1,C=!!(t?.raw?.paymasterService?.supported&&f),S=An((T,v=l)=>{let I=zo({atomicBatch:r==="supported",discovered:r!=="unknown",sponsoredTransactions:!1,...t?.maxBatchSize===void 0?{}:{maxBatchSize:t.maxBatchSize}},T,{atomicity:v,sponsorship:d}),A=d==="required"&&!y;if(I.strategy==="atomic-batch"&&!A)return{...I,reason:I.reason+(C?" A paymaster service will be requested, but the wallet's final fee payer must be checked after execution.":""),route:"wallet-batch"};let U=s&&r!=="supported"?` This account does delegate to ${n} under EIP-7702, so it is capable of batching even though the wallet has not offered to.`:"",k=v!=="any"&&!I.atomic||d==="required";return m&&k&&!A?{strategy:"atomic-batch",atomic:!0,sponsored:y,reason:d==="required"&&!I.sponsored?"The wallet batch is not configured for sponsored gas, so the calls are executed through the configured sponsored UserOperation route.":"This wallet cannot batch, so the calls are executed as a single UserOperation through the smart account, which lands as one transaction.",route:"user-operation"}:A?{strategy:"refuse",atomic:I.atomic,sponsored:!1,reason:"Sponsored gas was required, but there is no executable sponsored route: no paymaster is configured for a wallet batch, and capability advertising alone cannot pay for a sequential transaction.",route:null}:I.strategy==="refuse"?{...I,reason:I.reason+U,route:null}:{...I,reason:I.reason+U,route:"sequential"}},[r,t,f,C,m,y,l,d,s,n]),E=An(async(T,v=l)=>{g(!0),c(null);try{let I=S(T.length,v);if(I.route===null)throw new jo("method_not_allowed",I.reason);return o(I.route),I.route==="user-operation"?await m(T):await i(T,{strategy:I.route==="wallet-batch"?"atomic-batch":"sequential",...I.route==="wallet-batch"&&C?{paymasterService:f}:{}})}catch(I){let A=I instanceof Error?I:new Error("Execution failed");throw c(A),A}finally{g(!1)}},[S,i,m,l,f,C]);return{preview:S,execute:E,isExecuting:a,error:u,lastRoute:h,reset:()=>{c(null),o(null)}}}import{DEFAULT_SESSION_KEY_CONFIG as Go,LocalStorageAdapter as Qo,MemoryStorageAdapter as Xo,SessionKeyManager as Yo,WalletError as Tn}from"@naculus/connect-core";import{useCallback as J,useEffect as Jo,useRef as Zo,useState as Y}from"react";var Ee=null,bt=null;function es(e){return e?JSON.stringify({defaultMaxTotalValue:e.defaultMaxTotalValue?.toString(),defaultMaxTxCount:e.defaultMaxTxCount,defaultExpiryMs:e.defaultExpiryMs,requireAllowedContracts:e.requireAllowedContracts,forbiddenMethods:e.forbiddenMethods,pbkdf2Iterations:e.pbkdf2Iterations,unsafeAllowWeakKdf:e.unsafeAllowWeakKdf,storagePrefix:e.storagePrefix,encryptionKey:e.encryptionKey,encryptionSalt:e.encryptionSalt}):""}function pe(e){let t=es(e);if(!Ee){let r=e?.storagePrefix??Go.storagePrefix;return Ee=new Yo(e,typeof window<"u"?new Qo(`${r}:`):new Xo),bt=t,Ee}if(t!==""&&t!==bt)throw new Tn("invalid_input","useSessionKeys is backed by a process-wide SessionKeyManager, and a different spending configuration was supplied after it was created. The second configuration would be ignored, so the caller would be operating under limits it did not set. Use one configuration per application, or construct a SessionKeyManager directly.");return Ee}function At(e){let{session:t}=P(),[r,s]=Y([]),[n,i]=Y(!1),[a,g]=Y(null),u=Zo(!0),c=J(()=>g(null),[]),h=pe(e),o=h.isStorageAvailable(),l=J(async()=>{if(!t){s([]);return}i(!0),g(null);try{let f=await h.listSessions();u.current&&s(f)}catch(f){u.current&&g(f instanceof Error?f:new Error("Failed to load session keys"))}finally{u.current&&i(!1)}},[t,h]);Jo(()=>(u.current=!0,l(),()=>{u.current=!1}),[l]);let d=r.filter(f=>f.status==="active");return{sessions:r,activeSessions:d,loading:n,error:a,refresh:l,clearError:c,storageAvailable:o}}function ts(e){let{session:t}=P(),[r,s]=Y(null),[n,i]=Y(!1),[a,g]=Y(null),u=J(()=>g(null),[]),c=pe(e);return{createSessionKey:J(async(o,l)=>{if(!t)throw new Tn("wallet_unavailable","No active wallet session");i(!0),g(null);try{let d=l??void 0,f=await c.createSessionKey(o,d);return s(f),f}catch(d){let f=d instanceof Error?d:new Error("Failed to create session key");throw g(f),f}finally{i(!1)}},[t,c]),lastCreated:r,isCreating:n,error:a,clearError:u}}function ns(e){let[t,r]=Y(!1),[s,n]=Y(null),i=J(()=>n(null),[]),a=pe(e);return{revokeSession:J(async u=>{r(!0),n(null);try{await a.revokeSession(u)}catch(c){let h=c instanceof Error?c:new Error("Failed to revoke session key");throw n(h),h}finally{r(!1)}},[a]),isRevoking:t,error:s,clearError:i}}function rs(e){let[t,r]=Y(!1),[s,n]=Y(null),i=J(()=>n(null),[]),a=pe(e),g=J(async(c,h,o)=>{r(!0),n(null);try{return await a.signWithSessionKey(c,h,o)}catch(l){let d=l instanceof Error?l:new Error("Failed to sign with session key");throw n(d),d}finally{r(!1)}},[a]),u=J(async(c,h)=>{r(!0),n(null);try{return await a.checkSessionScope(c,h)}catch(o){let l=o instanceof Error?o:new Error("Failed to check session scope");throw n(l),l}finally{r(!1)}},[a]);return{signWithSession:g,checkScope:u,isBusy:t,error:s,clearError:i}}function os(){Ee=null,bt=null}import{useState as Rn,useCallback as ss}from"react";import{WalletError as Tt}from"@naculus/connect-core";function Rt(){let{session:e,chainId:t,client:r}=P(),[s,n]=Rn(!1),[i,a]=Rn(null);return{signMessage:ss(async u=>{if(!e){let h=new Tt("wallet_unavailable","No active session");throw a(h),h}let c=e.namespaces.eip155?.accounts[0]??Object.values(e.namespaces)[0]?.accounts[0];if(!c){let h=new Tt("wallet_unavailable","No account found");throw a(h),h}n(!0),a(null);try{let h=M(r);if(!h)throw new Tt("wallet_unavailable","Client not initialized");return await h.signMessage(e,{message:u,address:c,chainId:t??void 0})}catch(h){let o=h instanceof Error?h.message:"Signing failed",l=h instanceof Error?h:new Error(o);throw a(l),l}finally{n(!1)}},[e,t,r]),isSigning:s,error:i}}function is(e){let t=e?.includes(":")?e.split(":").pop():e;return t&&/^0x[0-9a-fA-F]{40}$/.test(t)?t:null}function In(e){return e?[...e].map(t=>t.toLowerCase()).sort():null}function ls(e,t){let r=e.to===void 0||e.to.toLowerCase()===t.to?.toLowerCase(),s=e.data===void 0||e.data.toLowerCase()===t.data?.toLowerCase();return r&&s&&((i,a)=>{if(i===void 0)return!0;if(a===void 0)return!1;try{return BigInt(i)===BigInt(a)}catch{return!1}})(e.value,t.value)&&(e.chainId===void 0||e.chainId===t.chainId)}function ke(e,t){let r=e.scope.tokenAllowances?Object.entries(e.scope.tokenAllowances).map(([n,i])=>[n.toLowerCase(),i.toString()]).sort(([n],[i])=>n.localeCompare(i)):null,s={version:1,origin:t,signer:e.signerAddress.toLowerCase(),sessionId:e.id,sessionPublicKey:e.publicKey.toLowerCase(),expiresAt:new Date(e.expiresAt).toISOString(),mode:e.scope.mode,limits:{maxTotalGas:e.scope.maxTotalGas?.toString()??null,maxGasPerTx:e.scope.maxGasPerTx?.toString()??null,maxTotalValue:e.scope.maxTotalValue?.toString()??null,maxValuePerTx:e.scope.maxValuePerTx?.toString()??null,maxTxCount:e.scope.maxTxCount??null},allowedContracts:In(e.scope.allowedContracts),allowedMethods:In(e.scope.allowedMethods),allowedChainIds:e.scope.allowedChainIds?[...e.scope.allowedChainIds].sort((n,i)=>n-i):null,tokenAllowances:r};return`Naculus Session Policy v1
|
|
2
|
-
${JSON.stringify(s)}`}function cs(e={}){let{evmAccount:t}=H(),r=is(t),s=we(),n=vt(e.execution),{signMessage:i}=Rt(),a=At(e.managerConfig),g=pe(e.managerConfig),[u,c]=Be(!1),[h,o]=Be(null),[l,d]=Be(()=>new Set),[f,m]=Be(!1),y=e.origin??(typeof window<"u"?window.location.origin:"unknown"),C=se(async k=>{if(k.status!=="active"||!k.authorized||k.scope.mode!=="offchain")return!1;let R=ke(k,y);return g.verifyOffchainAuthorization(k.id,R,async({message:b,signature:O,signerAddress:_})=>(await He({message:b,signature:O})).toLowerCase()===_.toLowerCase())},[g,y]);as(()=>{let k=!1,R=a.sessions.filter(b=>b.status==="active"&&b.authorized&&b.scope.mode==="offchain");return R.length===0?(d(new Set),m(!1),()=>{k=!0}):(m(!0),Promise.all(R.map(async b=>[b.id,await C(b)])).then(b=>{k||d(new Set(b.filter(([,O])=>O).map(([O])=>O)))}).catch(b=>{k||(d(new Set),o(b instanceof Error?b:new Error("Policy verification failed")))}).finally(()=>{k||m(!1)}),()=>{k=!0})},[a.sessions,C]);let S=se(()=>{o(null),a.clearError()},[a]),E=se(async k=>{if(!r){let b=new $("wallet_unavailable","No active EVM account");throw o(b),b}if(k.mode&&k.mode!=="offchain"){let b=new $("method_not_allowed","This flow creates signed off-chain policies only. EIP-7702 and AA-module policies require a configured on-chain execution adapter.");throw o(b),b}if(!e.managerConfig?.encryptionKey){let b=new $("method_not_allowed","Persistent delegation policies require a host-provided encryptionKey. The deterministic compatibility fallback is not a production key boundary.");throw o(b),b}if(!a.storageAvailable){let b=new $("storage_unavailable","Persistent delegation policy storage is unavailable in this browser");throw o(b),b}c(!0),o(null);let R=null;try{R=await g.createSessionKey({...k,mode:"offchain"},r);let b=ke(R,y),O=await i(b);if(!/^0x[0-9a-fA-F]{130}$/.test(O))throw new $("invalid_input","Wallet did not return a valid 65-byte EVM policy signature");if((await He({message:b,signature:O})).toLowerCase()!==r.toLowerCase())throw new $("invalid_input","Policy signature does not recover to the connected EVM account");await g.setAuthorization(R.id,{signerAddress:r,type:"offchain",rawSignature:O,message:b});let p=(await g.listSessions()).find(w=>w.id===R?.id);if(!p?.authorized)throw new $("invalid_input","Policy authorization was not persisted");if(!await C(p))throw new $("invalid_input","Persisted policy signature did not verify against its stored scope and origin");return await a.refresh(),p}catch(b){if(R)try{await g.revokeSession(R.id)}catch{}let O=b instanceof Error?b:new Error("Policy creation failed");throw o(O),O}finally{c(!1)}},[g,e.managerConfig?.encryptionKey,y,a,i,r,C]),T=se(async k=>{c(!0),o(null);try{await g.revokeSession(k),await a.refresh()}catch(R){let b=R instanceof Error?R:new Error("Policy revocation failed");throw o(b),b}finally{c(!1)}},[g,a]),v=se(async(k,R,b=1,O="preferred")=>{let _=(await g.listSessions()).find(Oe=>Oe.id===k)??null,p=await g.checkSessionScope(k,R),w=n.preview(b,O),x=_?await C(_):!1,W=!!(_&&r&&_.signerAddress.toLowerCase()===r.toLowerCase()),N=null;if(_&&e.adapter&&x&&W&&p.valid)try{N=await e.adapter.check({policy:_,transaction:R})}catch(Oe){N={ready:!1,authorizationInstalled:!1,sponsored:!1,promptless:!1,reason:Oe instanceof Error?`Execution adapter check failed: ${Oe.message}`:"Execution adapter check failed."}}let D=!!(e.adapter?.route!=="eip7702"||s.delegated===!0&&N?.executorAddress&&s.delegate?.toLowerCase()===N.executorAddress.toLowerCase()),F=!!(_?.status==="active"&&_.authorized&&x&&_.scope.mode==="offchain"&&W&&p.valid),le=!!(e.execution?.sponsorship!=="required"||N?.sponsored),ce=!!(F&&b===1&&N?.ready&&N.authorizationInstalled&&N.promptless&&le&&D),_r=!!(F&&(w.route||ce)),Or=_?_.status!=="active"?`Policy is ${_.status}.`:_.authorized?x?W?p.valid?ce?`The configured ${e.adapter?.route??"AA/7702"} adapter can submit this policy-authorized operation without another main-wallet prompt.${N?.sponsored?" Gas sponsorship is guaranteed.":""} ${N?.reason??"The on-chain execution adapter is ready."}`:e.adapter?!N?.ready||!N.authorizationInstalled?`${w.reason} ${N?.reason??"The execution adapter is not ready."}`:N.promptless?le?b!==1?`${w.reason} This policy adapter prepares one execution at a time and cannot claim a multi-call broadcast.`:D?w.route?`${w.reason} ${N.reason}`:w.reason:`${w.reason} The configured EIP-7702 executor does not match the account's on-chain delegation.`:`${w.reason} Sponsored gas is required, but the configured adapter does not guarantee sponsorship.`:`${w.reason} The configured adapter would invoke the main wallet again, so promptless broadcast is not ready.`:`${w.reason} The signed off-chain policy permits this request; an AA/7702 adapter is still required to broadcast without another wallet prompt.`:p.reason??"The transaction is outside the policy scope.":"The connected account is not the policy signer.":"The persisted policy signature no longer matches its scope, signer, or origin.":"The main wallet has not signed this policy.":"Policy not found.";return{policy:_,scope:p,execution:w,signerMatches:W,authorizationVerified:x,ready:_r,broadcastReady:ce,broadcastRoute:ce?e.adapter?.route??null:null,onchainAuthorizationVerified:!!(N?.authorizationInstalled&&D),broadcastSponsored:ce?N?.sponsored??!1:null,broadcastPromptless:!!(ce&&N?.promptless),reason:Or}},[s,n,g,e.adapter,e.execution?.sponsorship,r,C]),I=se(async(k,R,b)=>{let O=await v(k,b,1,"any");if(!O.ready)throw new $("method_not_allowed",O.reason);return g.signWithVerifiedOffchainAuthorization(k,_=>ke(_,y),async({message:_,signature:p,signerAddress:w})=>(await He({message:_,signature:p})).toLowerCase()===w.toLowerCase(),R,b)},[g,y,v]),A=se(async(k,R)=>{let b=e.adapter;if(!b)throw new $("method_not_allowed","No session-policy-aware AA/7702 execution adapter is configured.");c(!0),o(null);try{let O=await v(k,R,1,"any");if(!O.broadcastReady||!O.policy)throw new $("method_not_allowed",O.reason);let _=await b.prepare({policy:O.policy,transaction:R});if(!/^0x[0-9a-fA-F]{64}$/.test(_.digest))throw new $("invalid_input","Execution adapter returned a digest that is not 32 bytes.");if(!ls(R,_.transaction))throw new $("invalid_input","Execution adapter changed the requested target, value, data, or chain.");let p=await b.check({policy:O.policy,transaction:_.transaction}),w=b.route!=="eip7702"||s.delegated===!0&&p.executorAddress!==void 0&&s.delegate?.toLowerCase()===p.executorAddress.toLowerCase();if(!p.ready||!p.authorizationInstalled||!p.promptless||e.execution?.sponsorship==="required"&&!p.sponsored||!w)throw new $("method_not_allowed",p.reason||"The on-chain policy authorization is not ready.");let x=await g.signWithVerifiedOffchainAuthorization(k,N=>ke(N,y),async({message:N,signature:D,signerAddress:F})=>(await He({message:N,signature:D})).toLowerCase()===F.toLowerCase(),_.digest,_.transaction),W=await b.broadcast({policy:O.policy,prepared:_,signature:x});if(W.route!==b.route||W.status!=="submitted"||!/^0x[0-9a-fA-F]{64}$/.test(W.hash))throw new $("invalid_input","Execution adapter returned an invalid submission result.");return await a.refresh(),W}catch(O){let _=O instanceof Error?O:new Error("Policy execution failed");throw o(_),_}finally{c(!1)}},[s,g,e.adapter,e.execution?.sponsorship,y,v,a]),U=a.activeSessions.filter(k=>l.has(k.id));return{policies:a.sessions,activePolicies:U,storageAvailable:a.storageAvailable,loading:a.loading||f,isBusy:u,error:h??a.error,delegation:s,createPolicy:E,revokePolicy:T,previewPolicyExecution:v,signPolicyDigest:I,executePolicy:A,refresh:a.refresh,clearError:S}}import{useCallback as us,useRef as ps,useState as Un}from"react";function ds(){let{disconnect:e,status:t}=P(),[r,s]=Un(!1),[n,i]=Un(null),a=ps(!0);return{disconnect:us(async()=>{if(t!=="disconnected"){s(!0),i(null);try{await e()}catch(u){if(!a.current)return;i(u instanceof Error?u:new Error("Disconnect failed"))}finally{a.current&&s(!1)}}},[e,t]),isDisconnecting:r,error:n,cleanup:()=>{a.current=!1}}}import{WalletError as It}from"@naculus/connect-core";import{useCallback as Z,useEffect as ms,useRef as Fe,useState as Ke}from"react";function oe(e){let t=e.activeNamespace??"eip155",r=Array.isArray(e.accounts)?e.accounts.map(({namespace:s,address:n,derivationPath:i})=>({namespace:s,address:n,...i?{derivationPath:i}:{}})):e.address?[{namespace:t,address:e.address}]:[];return{accounts:r,activeNamespace:t,createdAt:e.createdAt??0,...e.chainId?{chainId:e.chainId}:{},...e.version?{version:e.version}:{},recoveryAvailable:!!e.mnemonic,address:r.find(s=>s.namespace===t)?.address??e.address}}function fs(){let{connectEmbedded:e,client:t}=P(),[r,s]=Ke(null),n=Fe(null),i=Fe(4),a=Fe(!1),g=Fe(null),[u,c]=Ke(!1),[h,o]=Ke(!1),[l,d]=Ke(null),f=()=>d(null),m=Z(()=>{let p=n.current;return n.current=null,p},[]),y=Z(()=>{let p=M(t);if(!p?.embeddedConnector)throw new It("wallet_unavailable","Embedded wallet not enabled.");return p.embeddedConnector},[t]),C=Z(()=>{try{return y().getWallet()?.privateKey??null}catch{return null}},[y]),S=Z(async()=>{let p=M(t);if(!p)throw new It("wallet_unavailable","Embedded wallet not enabled.");let w=p.getEmbeddedConnector?await p.getEmbeddedConnector():p.embeddedConnector;if(!w)throw new It("wallet_unavailable","Embedded wallet not enabled.");return w},[t]),E=Z(()=>{try{return M(t)?.passphraseGate??null}catch{return null}},[t]),T=Z(p=>{p?.code==="decryption_failed"&&E()?.forget("That passphrase did not open the wallet.")},[E]),v=Z(async()=>{a.current=!1,d(null);try{let p=await S();if(!await p.load())return!1;let x=p.getWallet();return x?(n.current=null,c(!1),s(oe(x)),!0):!1}catch(p){return a.current=!0,T(p),d(p instanceof Error?p:new Error("Failed to restore embedded wallet")),!1}},[T,S]);ms(()=>{let p=!1,w=null;return v().then(x=>{p||x||a.current||(w=setTimeout(()=>{p||v()},100))}),()=>{p=!0,w&&clearTimeout(w)}},[v]);let I=async()=>{o(!0),d(null);try{let p=await S(),w=await p.load(),x=p.getWallet();w&&x&&(s(oe(x)),n.current=x.mnemonic||null,c(!x.mnemonic)),await e();let W=p.getWallet();W&&(s(oe(W)),W.mnemonic&&!w&&(n.current=W.mnemonic,c(!0)))}catch(p){T(p),d(p instanceof Error?p:new Error("Embedded wallet connection failed"))}finally{o(!1)}},A=async()=>{o(!0),d(null);try{let p=await S();E()?.expect("create");let w=await p.generateWallet();return s(oe(w)),n.current=w.mnemonic,c(!0),w}catch(p){return d(p instanceof Error?p:new Error("Failed to generate wallet")),null}finally{o(!1)}},U=async p=>{o(!0),d(null);try{let w=await S();E()?.expect("create");let x=await w.importFromMnemonic(p);return s(oe(x)),n.current=null,c(!1),x}catch(w){return d(w instanceof Error?w:new Error("Failed to import wallet")),null}finally{o(!1)}},k=async p=>{o(!0),d(null);try{let w=await S();E()?.expect("create");let x=await w.importFromPrivateKey(p);return s(oe(x)),n.current=null,c(!1),x}catch(w){return d(w instanceof Error?w:new Error("Failed to import wallet")),null}finally{o(!1)}},R=async()=>{o(!0),d(null);try{await(await S()).wipe(),s(null),n.current=null,c(!1)}catch(p){d(p instanceof Error?p:new Error("Failed to wipe wallet"))}finally{o(!1)}},b=Z(p=>{let w=y();w.setActiveNamespace(p);let x=w.getWallet();s(x?oe(x):null)},[y]),O=Z(async()=>{let p=await S(),w=await p.backfillAccounts();if(w.length>0){let x=p.getWallet();s(x?oe(x):null)}return w.map(({namespace:x,address:W,derivationPath:N})=>({namespace:x,address:W,...N?{derivationPath:N}:{}}))},[S]),_=()=>{n.current=null,c(!1)};return{connectEmbedded:I,restoreWallet:v,generateWallet:A,importFromMnemonic:U,importFromPrivateKey:k,wipe:R,wallet:r,hasWallet:r!==null,address:r?.address??null,accounts:r?.accounts??[],activeNamespace:r?.activeNamespace??null,setActiveNamespace:b,backfillAccounts:O,seedPhrase:n.current,getSeedPhrase:m,getPrivateKey:C,backupPending:u,confirmBackup:_,isBusy:h,error:l,clearError:f,storageSecurityLevel:(()=>{try{let p=y(),w=p.getStorageSecurityLevel?.()??4;return p.getWallet()?(i.current=w,w):r?i.current:w}catch{return r?i.current:4}})(),securityReport:(()=>{let p=null;try{p=y().getStorageSecurityReport?.()??null}catch{p=null}if(!p)return g.current=null,null;let w=JSON.stringify(p);return g.current?.json===w?g.current.value:(g.current={json:w,value:p},p)})()}}import{chainNumber as Es}from"@naculus/connect-appkit-core";import{useState as ks,useCallback as xs,useEffect as _n,useRef as On,useMemo as vs}from"react";import{WalletError as gs}from"@naculus/connect-core";import{useCallback as Pn,useEffect as hs,useLayoutEffect as Cs,useMemo as ys,useRef as Wn}from"react";import{tokenChainMismatch as ws}from"@naculus/connect-appkit-core";function Ss(e){return[e.token.address.toLowerCase(),e.token.chainId??"",e.token.decimals??"",e.chainId??"",e.owner??"",e.spender??"",e.connected?"1":"0",e.publicClient?"1":"0",e.walletClient?"1":"0",e.session?.id??""].join("|")}function de(e){let{token:t,chainId:r}=e,s=t.address.toLowerCase(),n=Ss(e),i=ys(()=>({key:n}),[n]),a=Wn(n),g=Wn(!0);Cs(()=>{a.current=n},[n]),hs(()=>(g.current=!0,()=>{g.current=!1}),[]);let u=Pn(()=>g.current&&a.current===n,[n]),c=Pn(()=>{if(!u())throw new gs("session_inactive","Wallet or token context changed. Retry the operation with the current account and chain.");let h=ws({address:s,chainId:t.chainId},r);if(h)throw h},[u,s,t.chainId,r]);return{identity:i,isCurrent:u,assertCurrent:c}}import{ERC20_MIN_ABI as bs,formatUnits as As}from"@naculus/connect-core";function Ts(e){let{publicClient:t}=G(),{currentChain:r}=z(),{identity:s,isCurrent:n,assertCurrent:i}=de({token:e.token,chainId:r?Es(r)??void 0:void 0,owner:e.owner,spender:e.spender,publicClient:t}),[a,g]=ks(null),u=a?.identity===s?a.raw:null,c=a?.identity===s&&a.fetching,h=a?.identity===s?a.error:null,o=On(null),l=On(0),d=xs(async()=>{if(!n())return;let m=++l.current,y=()=>n()&&m===l.current;if(g({identity:s,raw:null,fetching:!!t,error:null}),!!t)try{i();let C=await t.readContract({address:e.token.address,abi:bs,functionName:"allowance",args:[e.owner,e.spender]});if(!y())return;g({identity:s,raw:C,fetching:!1,error:null})}catch(C){if(!y())return;g({identity:s,raw:null,fetching:!1,error:C instanceof Error?C:new Error("Failed to fetch allowance")})}},[t,e.token.address,e.token.chainId,e.owner,e.spender,s,n,i]);return _n(()=>{d().catch(m=>console.warn("useERC20Allowance: initial fetch failed:",m))},[d]),_n(()=>(e.refreshInterval&&e.refreshInterval>0&&(o.current=setInterval(d,e.refreshInterval)),()=>{o.current&&(clearInterval(o.current),o.current=null)}),[e.refreshInterval,d]),{allowance:vs(()=>{if(u===null)return null;let m=e.token.decimals;return m===void 0?null:As(u,m)},[u,e.token.decimals]),allowanceRaw:u,isFetching:c,error:h,refetch:d}}import{chainNumber as Rs}from"@naculus/connect-appkit-core";import{useState as Mn,useCallback as ve,useRef as Ln}from"react";import{WalletError as Ut}from"@naculus/connect-core";import{useCallback as Nn,useState as Dn}from"react";function xe(){let{session:e,chainId:t,client:r}=P(),[s,n]=Dn("idle"),[i,a]=Dn(null),g=Nn(async c=>{if(!e){n("failed");let o=new Ut("wallet_unavailable","No active session");throw a(o),o}let h=e.namespaces.eip155?.accounts.find(o=>/^eip155:\d+:0x[0-9a-fA-F]{40}$/.test(o)||/^0x[0-9a-fA-F]{40}$/.test(o));if(!h){n("failed");let o=new Ut("wallet_unavailable","No EVM account found");throw a(o),o}n("awaiting_approval"),a(null);try{let o={...c,from:c.from??h.split(":").pop()},l=M(r);if(!l)throw new Ut("wallet_unavailable","Client not initialized");let d=await l.sendTransaction(e,{transaction:o,chainId:t??void 0}),f=Me(d);return n("submitted"),f}catch(o){n("failed");let l=o instanceof Error?o.message:"Transaction failed";throw a(o instanceof Error?o:new Error(l)),o}},[e,t,r]),u=Nn(()=>{n("idle"),a(null)},[]);return{sendTransaction:g,status:s,error:i,reset:u,isSending:s==="awaiting_approval"}}import{WalletError as $e,ERC20_MIN_ABI as be,parseUnits as Bn,formatUnits as Is}from"@naculus/connect-core";import{encodeFunctionData as Us}from"viem";import{createDecimalsCache as Ps,readDecimals as Pt,writeDecimals as Hn}from"@naculus/connect-appkit-core";function Ws(e){return e.includes(":")?e.split(":").pop():e}function _s(e,t){return Us({abi:be,functionName:"approve",args:[e,t]})}var Os=2n**256n-1n;function Ns(e){let{publicClient:t,walletClient:r}=G(),{evmAccount:s,isConnected:n}=H(),{currentChain:i}=z(),{session:a,client:g}=P(),{sendTransaction:u,isSending:c,error:h,reset:o}=xe(),[l,d]=Mn(null),{identity:f,isCurrent:m,assertCurrent:y}=de({token:e.token,chainId:i?Rs(i)??void 0:void 0,owner:s,spender:e.spender,connected:n,publicClient:t,walletClient:r,session:a,client:g}),[C,S]=Mn(null),E=C?.identity===f?C.raw:null,T=C?.identity===f&&C.fetching,v=Ln(Ps(e.token,e.token.decimals)),I=Ln(0),A=l??h,U=s?Ws(s):null,k=ve(async()=>{if(!m())return null;let w=++I.current,x=()=>m()&&w===I.current;if(S({identity:f,raw:null,fetching:!!t&&!!U&&n}),d(null),!t||!U||!n)return null;try{y();let W=await t.readContract({address:e.token.address,abi:be,functionName:"allowance",args:[U,e.spender]});return x()?(S({identity:f,raw:W,fetching:!1}),W):null}catch(W){return x()&&(S({identity:f,raw:null,fetching:!1}),d(W instanceof Error?W:new Error("Failed to fetch allowance"))),null}},[t,U,e.token.address,e.token.chainId,e.spender,f,m,y,n]),R=(()=>{if(E===null)return null;let w=Pt(v.current,e.token,e.token.decimals);return w===void 0?null:Is(E,w)})(),b=ve(async w=>{if(d(null),o(),!n||!s){let x=new $e("wallet_unavailable","No connected account");throw d(x),x}if(!t){let x=new $e("wallet_unavailable","No public client");throw d(x),x}try{y();let x=_s(e.spender,w),W=M(g);if(a&&W){let D=await u({to:e.token.address,data:x,value:"0"});return k(),D}if(r){let{request:D}=await t.simulateContract({address:e.token.address,abi:be,functionName:"approve",args:[e.spender,w],account:U});y();let F=await r.writeContract(D);return k(),F}let N=await u({to:e.token.address,data:x,value:"0"});return k(),N}catch(x){let W=x instanceof Error?x:new Error("Approve failed");throw m()&&d(W),W}},[e,t,r,s,n,a,g,U,u,o,k,y,m]),O=ve(async w=>{try{if(y(),!t)throw new $e("wallet_unavailable","No public client");let x=Pt(v.current,e.token,e.token.decimals);x===void 0&&(x=await t.readContract({address:e.token.address,abi:be,functionName:"decimals"}),y(),Hn(v.current,e.token,x));let W=Bn(w,x);return await b(W)}catch(x){throw m()&&d(x instanceof Error?x:new Error("Approve failed")),x}},[e.token,t,b,y,m]),_=ve(async()=>b(Os),[b]),p=ve(async w=>{if(!m()||!n||!U||!t)return!1;try{y()}catch(D){return d(D instanceof Error?D:new Error("Cannot check allowance")),!1}let x=E??await k();if(x===null)return!1;let W=Pt(v.current,e.token,e.token.decimals);if(W===void 0){if(!t)throw new $e("wallet_unavailable","Cannot check allowance: no public client to read token decimals.");if(W=await t.readContract({address:e.token.address,abi:be,functionName:"decimals"}),!m())return!1;Hn(v.current,e.token,W)}let N=Bn(w,W);return m()&&x>=N},[E,k,e.token.address,e.token.chainId,e.token.decimals,t,m,y,n,U]);return{approve:O,approveMax:_,allowance:R,allowanceRaw:E,hasAllowance:p,isApproving:c,isFetchingAllowance:T,error:A,refetchAllowance:k}}import{chainNumber as Ds}from"@naculus/connect-appkit-core";import{useState as Ms,useCallback as Ls,useRef as Bs}from"react";import{WalletError as Fn,ERC20_MIN_ABI as Wt,parseUnits as Hs}from"@naculus/connect-core";import{encodeFunctionData as Fs}from"viem";import{createDecimalsCache as Ks,readDecimals as $s,writeDecimals as qs}from"@naculus/connect-appkit-core";function Vs(e){return e.includes(":")?e.split(":").pop():e}function zs(e,t){return Fs({abi:Wt,functionName:"transfer",args:[e,t]})}function js(e){let{publicClient:t,walletClient:r}=G(),{evmAccount:s,isConnected:n}=H(),{currentChain:i}=z(),{session:a,client:g}=P(),{sendTransaction:u,isSending:c,error:h,reset:o}=xe(),[l,d]=Ms(null),{isCurrent:f,assertCurrent:m}=de({token:e.token,chainId:i?Ds(i)??void 0:void 0,owner:s,connected:n,publicClient:t,walletClient:r,session:a,client:g}),y=Bs(Ks(e.token,e.token.decimals)),C=l??h;return{sendTransfer:Ls(async(E,T)=>{if(d(null),o(),!n||!s){let v=new Fn("wallet_unavailable","No connected account");throw d(v),v}if(!t){let v=new Fn("wallet_unavailable","No public client available");throw d(v),v}try{m();let v=Vs(s),I=$s(y.current,e.token,e.token.decimals);I===void 0&&(I=await t.readContract({address:e.token.address,abi:Wt,functionName:"decimals"}),m(),qs(y.current,e.token,I));let A=Hs(T,I),U=zs(E,A),k=M(g);if(a&&k)return await u({to:e.token.address,data:U,value:"0"});if(r){let{request:b}=await t.simulateContract({address:e.token.address,abi:Wt,functionName:"transfer",args:[E,A],account:v});return m(),await r.writeContract(b)}return await u({to:e.token.address,data:U,value:"0"})}catch(v){let I=v instanceof Error?v:new Error("Transfer failed");throw f()&&d(I),I}},[e.token,t,r,s,n,a,g,u,o,m,f]),isSending:c,error:C}}import{chainNumber as Zs}from"@naculus/connect-appkit-core";import{useMemo as ea}from"react";import{chainNumber as Gs}from"@naculus/connect-appkit-core";import{WalletError as Qs}from"@naculus/connect-core";import{useCallback as Kn,useEffect as Xs,useRef as Ys,useState as _t}from"react";import{resolveRevertReason as Js}from"@naculus/connect-appkit-core";function Ot(e,t){let{session:r}=P(),{evmAccount:s,isConnected:n}=H(),{currentChain:i}=z(),{publicClient:a}=G(),[g,u]=_t(void 0),[c,h]=_t(!1),[o,l]=_t(null),d=Ys(void 0),f=Kn(async()=>{if(!e){let y={status:"unavailable",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[]},provider:"eth_call",summary:"No transaction to simulate",changesDetected:!1};return u(y),y}h(!0),l(null);try{if((t??(i?Gs(i)??void 0:void 0))===void 0)throw new Qs("invalid_chain","No chain to simulate on. Connect a wallet or pass a chainId.");let C=i?.rpcUrl;if(a)try{let E=s?.includes(":")?s.split(":").pop():s,T={to:e.to,data:e.data??"0x",value:e.value?BigInt(e.value):0n};E&&(T.from=E),await a.call(T);let v={status:"success",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[]},gasInfo:e.gas?{gasLimit:BigInt(e.gas),estimatedFeeEth:"0"}:void 0,provider:"eth_call",summary:"Transaction simulation succeeded (basic revert check only)",changesDetected:!0};return u(v),v}catch(E){let T=E?.message??String(E),v=E?.data??E?.cause?.data,I=Js(v,T),A={status:"reverted",revertReason:I,coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"high",message:I?`Transaction would revert: ${I}`:"Transaction would revert"}]},provider:"eth_call",summary:I?`Transaction reverted: ${I}`:"Transaction reverted",changesDetected:!1};return u(A),A}if(C)try{let T=await(await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:"eth_call",params:[{to:e.to,from:s?.includes(":")?s.split(":").pop():s,data:e.data??"0x",value:e.value??"0x0"},"latest"]})})).json();if(T.error){let I={status:"reverted",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"high",message:`Transaction would revert: ${T.error.message}`}]},provider:"eth_call",summary:"Transaction reverted",changesDetected:!1};return u(I),I}let v={status:"success",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[]},provider:"eth_call",summary:"Transaction simulation succeeded",changesDetected:!0};return u(v),v}catch(E){let T={status:"unavailable",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"medium",message:`Network error: ${E?.message??"Unknown"}`}]},provider:"eth_call",summary:"Simulation unavailable due to network error",changesDetected:!1};return u(T),T}let S={status:"unavailable",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"low",message:"No RPC URL or public client available for simulation"}]},provider:"eth_call",summary:"Simulation unavailable: no RPC URL",changesDetected:!1};return u(S),S}catch(y){let C=y instanceof Error?y:new Error("Simulation failed");throw l(C),C}finally{h(!1)}},[e,t,i,a,s]);Xs(()=>{if(e)return d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{f().catch(()=>{})},300),()=>{d.current&&clearTimeout(d.current)}},[e,f]);let m=Kn(()=>{u(void 0),l(null),h(!1)},[]);return{result:g,isSimulating:c,error:o,simulate:f,reset:m}}var ta="0xa9059cbb";function na(e){return(e.startsWith("0x")?e.slice(2):e).padStart(64,"0")}function ra(e,t=32){return(e.startsWith("0x")?e.slice(2):e).padStart(t*2,"0")}function oa(e,t){let[r="0",s=""]=e.split("."),n=s.padEnd(t,"0").slice(0,t);return BigInt(r+n||"0")}function sa(e,t){return`${ta}${na(e)}${ra(t.toString(16))}`}function aa(e){let{evmAccount:t,isConnected:r}=H(),{currentChain:s}=z(),n=e.token.chainId??(s?Zs(s)??void 0:void 0),i=ea(()=>{if(!(!r||!t))try{let g=e.token.decimals;if(g===void 0)return;let u=oa(e.amount,g),c=sa(e.to,u);return{to:e.token.address,data:c,value:"0"}}catch{return}},[e.token.address,e.token.decimals,e.to,e.amount,t,r]),a=Ot(i,n);return{result:a.result,isSimulating:a.isSimulating,error:a.error,reSimulate:a.simulate,reset:a.reset}}import{useState as Nt,useCallback as da,useRef as Dt}from"react";import{useState as qe,useEffect as ia,useCallback as $n,useRef as la}from"react";import{createContext as ca,useContext as ua}from"react";var qn=ca(null);function Ae(){return ua(qn)}function pa(e,t,r){let s=Ae(),n=r??s,[i,a]=qe(null),[g,u]=qe(!1),[c,h]=qe(!1),[o,l]=qe(null),d=la(void 0),f=$n(async()=>{if(!(!n||!e)){u(!0),l(null);try{await n.refreshTx(e,t);let C=n.getTxStatus(e,t);C&&a(C)}catch(C){l(C instanceof Error?C:new Error(String(C)))}finally{u(!1)}}},[n,e,t]),m=$n(()=>{!n||!e||(n.stopWatching(e,t),h(!1))},[n,e,t]);ia(()=>{if(!n||!e||!t){a(null),h(!1);return}d.current&&d.current!==e&&n.stopWatching(d.current),d.current=e;let C=!1;h(!0),u(!0),l(null);let S=n.getTxStatus(e,t);S&&(a(S),u(!1)),n.watchTx(e,t,{}).then(T=>{C||(a(T),u(!1))}).catch(T=>{C||(l(T instanceof Error?T:new Error(String(T))),u(!1))});let E=T=>{C||a({...T})};return n.on("statusChange",E),()=>{C=!0,h(!1),n.off("statusChange",E)}},[n,e,t]);let y=i?.status??"idle";return{entry:i,status:y,isLoading:g,isWatching:c,error:o,refresh:f,stopWatching:m}}function ma(e){let t=Ae(),r=e??t,[s,n]=Nt(null),[i,a]=Nt(null),[g,u]=Nt(null),c=Dt(null),h=Dt(null),o=Dt(null);r&&(h.current||(h.current=d=>{a(d),(!c.current||d.createdAt>=c.current.createdAt)&&(n(d),c.current=d)},r.on("confirmed",h.current)),o.current||(o.current=d=>{u(d),(!c.current||d.createdAt>=c.current.createdAt)&&(n(d),c.current=d)},r.on("failed",o.current)));let l=da(()=>{n(null),a(null),u(null),c.current=null},[]);return{lastTx:s,lastConfirmedTx:i,lastFailedTx:g,clear:l}}import{useCallback as Ca}from"react";import{useCallback as fa,useEffect as Vn,useMemo as ga,useRef as zn,useState as Mt}from"react";import{getResolver as ha}from"@naculus/connect-appkit-core";function Ve({input:e,skip:t=!1,resolverConfig:r,scope:s,query:n}){let[i,a]=Mt(null),[g,u]=Mt(!1),[c,h]=Mt(null),o=zn(0),l=zn(!0);Vn(()=>(l.current=!0,()=>{l.current=!1}),[]);let d=ga(()=>ha(r),[r]),f=fa(()=>{let m=e.trim();if(!m||t){o.current+=1,a(null),u(!1),h(null);return}let y=++o.current;u(!0),h(null),n(d,m,s).then(C=>{!l.current||y!==o.current||(a(C),u(!1))}).catch(C=>{!l.current||y!==o.current||(h(C instanceof Error?C:new Error(String(C))),a(null),u(!1))})},[e,t,s,d,n]);return Vn(()=>{f()},[f]),{data:i,isLoading:g,error:c,refetch:f}}function ya(e,t){let r=Ca((s,n,i)=>s.lookupAddress(n,i),[]);return Ve({input:e,skip:t?.skip,resolverConfig:t?.resolverConfig,scope:t?.chainId,query:r})}import{useState as jn,useCallback as ee,useMemo as wa,useEffect as Gn,useRef as Sa}from"react";import{InAppChannel as Ea}from"@naculus/connect-core";import{createStorageAdapter as ka}from"@naculus/connect-core";var xa={telegram:!1,webpush:!1,inapp:!0,frequency:"final-only",mutedChains:[],mutedTypes:[]},Qn="naculus_notif_react_settings";function va(e){let t=Sa(null);t.current||(t.current=e?.channel??new Ea);let r=t.current,[s,n]=jn(()=>r.getHistory()),[i,a]=jn(()=>xa);Gn(()=>{(e?.storage??Xn()).getItem(Qn).then(S=>{S&&a(S)})},[]),Gn(()=>(r.onNotification=C=>{n(S=>[...S,C])},r.restore().then(()=>{n(r.getHistory())}),()=>{r.onNotification=void 0}),[]);let g=wa(()=>s.filter(C=>!C.read).length,[s]),u=ee(()=>{r.clear(),n([])},[r]),c=ee(C=>{let S=r.getHistory().filter(E=>E.id!==C);r.clear(),Promise.all(S.map(E=>r.send({id:E.id,userId:"",txHash:E.txHash,chainId:"",chainName:E.chainName,status:E.status,title:E.title,body:E.body,valueFormatted:E.valueFormatted,explorerUrl:E.explorerUrl,timestamp:E.timestamp}))).then(()=>{n(r.getHistory())})},[r]),h=ee(C=>{r.markAsRead(C),n(S=>S.map(E=>E.id===C?{...E,read:!0}:E))},[r]),o=ee(()=>{r.markAllAsRead(),n(C=>C.map(S=>({...S,read:!0})))},[r]),l=ee(C=>{let S={...C,id:`notif_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now()};r.send({id:S.id,userId:"",txHash:S.txHash,chainId:"",chainName:S.chainName,status:S.status,title:S.title,body:S.body,valueFormatted:S.valueFormatted,explorerUrl:S.explorerUrl,timestamp:S.timestamp})},[r]),d=ee(C=>{a(S=>{let E={...S,...C};return(e?.storage??Xn()).setItem(Qn,E).catch(()=>{}),E})},[e?.storage]),f=ee(C=>{let S={};C.includes("telegram")&&(S.telegram=!0),C.includes("webpush")&&(S.webpush=!0),C.includes("inapp")&&(S.inapp=!0),d(S)},[d]),m=ee(C=>{d({mutedChains:[...new Set([...i.mutedChains,C])]})},[i.mutedChains,d]),y=ee(C=>{d({mutedChains:i.mutedChains.filter(S=>S!==C)})},[i.mutedChains,d]);return{notifications:s,unreadCount:g,addNotification:l,clear:u,clearOne:c,markAsRead:h,markAllAsRead:o,settings:i,updateSettings:d,setChannels:f,muteChain:m,unmuteChain:y}}function Xn(){let e=ka("local","naculus_notif_");return{getItem:async t=>{try{return await e.get(t)}catch(r){return console.warn("useNotification: failed to read from storage:",r),null}},setItem:async(t,r)=>{try{await e.set(t,r)}catch(s){console.warn("useNotification: failed to write to storage:",s)}},removeItem:async t=>{try{await e.remove(t)}catch(r){console.warn("useNotification: failed to remove from storage:",r)}}}}import{useCallback as Lt,useSyncExternalStore as ba}from"react";var Yn=()=>null,Aa=()=>()=>{};function Ta(){let{client:e}=P(),t=M(e)?.passphraseGate??null,r=ba(t?.subscribe??Aa,t?.getSnapshot??Yn,Yn),s=Lt(a=>t?.submit(a),[t]),n=Lt(()=>t?.cancel(),[t]),i=Lt(a=>t?.forget(a),[t]);return{request:r,submit:s,cancel:n,forget:i,isUnlocked:t?.isUnlocked??!1,gate:t}}import{useCallback as Ra}from"react";function Ia(e,t){let r=Ra((s,n)=>s.resolveName(n),[]);return Ve({input:e,skip:t?.skip,resolverConfig:t?.resolverConfig,query:r})}import{AA_SUPPORTED_CHAINS as Ua,DEFAULT_ENTRY_POINT as Pa,WalletError as te}from"@naculus/connect-core";import{useCallback as Jn,useEffect as Zn,useRef as er,useState as Te}from"react";import{resolveEvmChainId as Wa}from"@naculus/connect-appkit-core";function _a(e){if(!e)return null;let t=e.includes(":")?e.split(":").pop():e;return t&&/^0x[0-9a-fA-F]{40}$/.test(t)?t:null}function Bt(e){if(typeof e!="string"||!/^0x(?:[0-9a-fA-F]{2})+$/.test(e))throw new te("signature_rejected","Wallet returned an invalid UserOperation signature.");return e}async function Oa(e,t,r,s,n){let i=M(t);if(!i)throw new te("wallet_unavailable","Client not initialized");let a=[r,s];if(e.walletType==="eip6963"||e.id?.startsWith("eip6963-")){let{eip6963Connector:g}=await import("@naculus/connector-evm-injected"),u=g.getDiscoveredWallets().find(h=>h.id===e.walletId),c=u?await u.provider.request({method:"personal_sign",params:a}):await g.request({method:"personal_sign",params:a});return Bt(c)}if(e.walletType==="walletconnect")return Bt(await i.connector.request({method:"personal_sign",params:a}));if(e.walletType==="embedded"){let g=i.embeddedConnector;if(!g?.signHash)throw new te("method_unsupported","This embedded wallet build cannot sign a raw digest. Upgrade @naculus/connector-embedded or pass an explicit signer.");return Bt(await g.signHash(e,r))}throw e.walletType==="passkeys"?new te("method_unsupported","Passkeys sign with P-256, which a SimpleAccount cannot verify. Use a smart account with a WebAuthn validator, or pass an explicit signer."):new te("method_unsupported",`Raw UserOperation signing is not available for ${e.walletType} on ${n}. Pass a signer that signs the raw 32-byte hash.`)}function Na(e){let{evmAccount:t}=H(),{session:r,chainId:s,client:n}=P(),[i,a]=Te(null),[g,u]=Te(null),[c,h]=Te(!1),[o,l]=Te(!1),[d,f]=Te(null),m=er(0),y=er(!1);Zn(()=>()=>{m.current+=1,y.current=!1},[]),Zn(()=>{m.current+=1,y.current=!1,a(null),u(null),h(!1),l(!1),f(null)},[n,s,t,e?.accountType,e?.bundlerUrl,e?.chainId,e?.entryPoint,e?.owner,e?.rpcUrl,e?.salt,e?.signerMode,r]);let C=Jn(async(E,T)=>{let v=k=>(f(k),null);if(!e?.rpcUrl)return v(new Error("RPC URL not configured"));if(!e.bundlerUrl)return v(new Error("Bundler URL not configured"));if(!E.length)return v(new Error("At least one call is required"));if(y.current)return v(new Error("A UserOperation is already in progress"));let I=_a(e.owner??t);if(!I)return v(new te("wallet_unavailable","No EVM account found"));let A=Wa(e.chainId,s);if(!A)return v(new te("invalid_chain",e.chainId||s?`Invalid EVM chain ID: ${e.chainId??s}`:"No EVM chain to send on. Connect a wallet or pass options.chainId."));if(s&&s!==A)return v(new te("chain_mismatch",`Connected chain ${s} does not match UserOperation chain ${A}.`));if(!e.signer&&!r)return v(new te("wallet_unavailable","No active session"));let U=++m.current;y.current=!0,h(!0),l(!0),f(null),a(null),u(null);try{let{SmartAccountManager:k}=await import("@naculus/connect-core"),R=e.signer??(p=>Oa(r,n,p,I,A)),b=new k({rpcUrl:e.rpcUrl,bundlerClient:{url:e.bundlerUrl},chainId:A,signer:R,signerMode:e.signer?e.signerMode??"eip191":"raw"}),O={owner:I,accountType:e.accountType??"simple",entryPoint:e.entryPoint??Ua[A]?.entryPoint??Pa,chainId:A,salt:e.salt},_=await b.sendUserOperation(O,E,T);return U!==m.current?null:(l(!1),a(_.userOpHash),b.getUserOperationReceipt(_.userOpHash).then(p=>{U===m.current&&u(p)}).catch(()=>{}),_)}catch(k){if(U!==m.current)return null;let R=k instanceof Error?k:new Error("Failed to send UserOperation");return f(R),null}finally{U===m.current&&(h(!1),l(!1),y.current=!1)}},[n,s,t,e,r]),S=Jn(()=>{m.current+=1,y.current=!1,a(null),u(null),h(!1),l(!1),f(null)},[]);return{sendUserOp:C,userOpHash:i,receipt:g,isPending:c,isEstimating:o,error:d,reset:S}}import{useSyncExternalStore as Da,useCallback as tr}from"react";function Ma(e,t){if(!e)return()=>{};let r=()=>t();return e.on("sessionConnected",r),e.on("sessionDisconnected",r),e.on("chainChanged",r),()=>{e.off("sessionConnected",r),e.off("sessionDisconnected",r),e.off("chainChanged",r)}}var Ht=Object.freeze({session:null,chainSessions:[],activeChainId:null,isConnected:!1,connectorId:null}),Ft=new WeakMap;function La(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function Ba(e){if(!e)return Ht;let t=e.getActiveBundle(),r=Ft.get(e);if(!t)return r&&r.session===null?r:(Ft.set(e,Ht),Ht);let s=Array.from(t.chainSessions.values());if(r&&r.session===t.walletSession&&r.activeChainId===t.activeChainId&&La(r.chainSessions,s))return r;let n={session:t.walletSession,chainSessions:s,activeChainId:t.activeChainId,isConnected:!0,connectorId:t.walletSession.walletType};return Ft.set(e,n),n}function Ha(e){let t=P(),r=e??t.sessionManager??null,s=tr(i=>Ma(r,i),[r]),n=tr(()=>Ba(r),[r]);return Da(s,n)}import{WalletError as ze}from"@naculus/connect-core";import{createSiwxMessage as Fa,generateNonce as Ka,getBlockchainName as $a,issueNonce as qa,nowISO as Va}from"@naculus/siwx";import{useCallback as nr,useState as rr}from"react";var za=86400;function ja(){return typeof window<"u"?window.location.host:"localhost"}function Ga(){return typeof window<"u"?window.location.origin:"http://localhost"}function Kt(){let{session:e,chainId:t,client:r}=P(),[s,n]=rr(!1),[i,a]=rr(null),g=nr(()=>a(null),[]);return{signIn:nr(async c=>{if(!e)throw new ze("wallet_unavailable","No active session");let h=c?.chainId??t;if(!h)throw new ze("invalid_chain","No chain to sign for. Connect a wallet or pass options.chainId.");let o=ue(e,h);if(!o)throw new ze("wallet_unavailable","No account found");let l=M(r);if(!l)throw new ze("wallet_unavailable","Client not initialized");let{address:d}=o,f=c?.domain??ja(),m=c?.uri??Ga();n(!0),a(null);try{let y=Ka();await qa(y);let C=Va(),S=c?.expirySeconds??za,E=new Date(Date.now()+S*1e3).toISOString(),T=Fa({domain:f,address:d,uri:m,version:1,chainId:h,nonce:y,issuedAt:C,expirationTime:E,statement:c?.statement,resources:c?.resources,requestId:c?.requestId}),v=await l.signMessage(e,{message:T,address:d,chainId:h??void 0}),I={message:{raw:T,domain:f,address:d,statement:c?.statement??null,uri:m,version:1,chainId:h,nonce:y,issuedAt:C,blockchain:$a(h),expirationTime:E,notBefore:null,resources:c?.resources??[],requestId:c?.requestId??null},signature:v};return n(!1),I}catch(y){let C=y instanceof Error?y:new Error("SIWx sign-in failed");throw a(C),n(!1),C}},[e,t,r]),isSigningIn:s,error:i,clearError:g}}import{logger as $t}from"@naculus/connect-core";import{checkSessionExpired as or,createLocalStorageSiwxSessionStorage as Qa}from"@naculus/siwx";import{useCallback as je,useEffect as sr,useRef as Xa,useState as Ge}from"react";function Ya(){let e=new Uint8Array(8);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function ar(e){return{id:`siwx_${Date.now().toString(36)}_${Ya()}`,chainId:e.message.chainId,address:e.message.address,domain:e.message.domain,message:e.message,signature:e.signature,issuedAt:e.message.issuedAt??new Date().toISOString(),expiresAt:e.message.expirationTime,refreshedAt:null}}function Ja(e){let{storagePrefix:t="naculus_",autoRestore:r=!0,defaultExpirySeconds:s=86400}=e??{},[n,i]=Ge(null),[a,g]=Ge(r),[u,c]=Ge(!1),[h,o]=Ge(null),{session:l,chainId:d}=P(),f=Kt(),m=Xa(Qa(`${t}siwx_session`)),y=je(()=>o(null),[]);sr(()=>{if(!r){g(!1);return}let A=!1;return(async()=>{try{let k=await m.current.get();if(A)return;k?($t.info("react/useSIWxSession","Restored persisted SIWx session"),i(k),o(null)):i(null)}catch(U){$t.warn("react/useSIWxSession","Failed to restore SIWx session:",U),i(null)}finally{A||g(!1)}})(),()=>{A=!0}},[r]),sr(()=>{if(!n?.expiresAt)return;let A=new Date(n.expiresAt).getTime()-Date.now();if(A<=0){i(null);return}let U=setTimeout(()=>{i(k=>k&&k.id===n.id?null:k)},A);return()=>clearTimeout(U)},[n?.id,n?.expiresAt]);let C=je(async A=>{c(!0),o(null);try{let U={expirySeconds:s,chainId:d??void 0,...A},k=await f.signIn(U),R=ar(k);return await m.current.set(R),i(R),c(!1),R}catch(U){let k=U instanceof Error?U:new Error("SIWx sign-in failed");throw o(k),c(!1),k}},[f,d,s]),S=je(async()=>{try{await m.current.remove()}catch(A){$t.warn("react/useSIWxSession","Failed to clear session:",A)}i(null),o(null)},[]),E=je(async()=>{if(!n)throw new Error("No active session to refresh");c(!0),o(null);try{let A=await f.signIn({domain:n.domain,statement:n.message.statement??void 0,uri:n.message.uri,chainId:n.chainId,expirySeconds:s,resources:n.message.resources.length>0?n.message.resources:void 0,requestId:n.message.requestId??void 0}),U={...ar(A),id:n.id,refreshedAt:new Date().toISOString()};return await m.current.set(U),i(U),c(!1),U}catch(A){let U=A instanceof Error?A:new Error("Session refresh failed");throw o(U),c(!1),U}},[n,f,s]),T=n!==null&&!or(n),v=or(n),I=n?.expiresAt?Math.max(0,new Date(n.expiresAt).getTime()-Date.now()):null;return{session:T?n:null,isAuthenticated:T,isRestoring:a,isSigningIn:u,isExpired:v,timeUntilExpiry:I,signIn:C,signOut:S,refresh:E,error:h,clearError:y}}import{WalletError as Qe}from"@naculus/connect-core";import{createSiwxMessage as Za,generateNonce as ei,getBlockchainName as ti,issueNonce as ni,nowISO as ri}from"@naculus/siwx";import{useCallback as ir,useState as qt}from"react";function oi(){return typeof window<"u"?window.location.host:"localhost"}function si(){return typeof window<"u"?window.location.origin:"http://localhost"}function Re(){let{session:e,chainId:t,client:r}=P(),[s,n]=qt(!1),[i,a]=qt(null),[g,u]=qt(null),c=ir(()=>u(null),[]);return{signIn:ir(async o=>{if(!e)throw new Qe("wallet_unavailable","No active session");let l=o?.chainId??t;if(!l)throw new Qe("invalid_chain","No chain to sign for. Connect a wallet or pass options.chainId.");let d=ue(e,l);if(!d)throw new Qe("wallet_unavailable","No account found");let f=M(r);if(!f)throw new Qe("wallet_unavailable","Client not initialized");let{address:m}=d,y=o?.domain??oi(),C=o?.uri??si();n(!0),u(null);try{let S=ei();await ni(S);let E=ri(),T=Za({domain:y,address:m,uri:C,version:1,chainId:l,nonce:S,issuedAt:E,statement:o?.statement,expirationTime:o?.expirySeconds?new Date(Date.now()+o.expirySeconds*1e3).toISOString():void 0,resources:o?.resources,requestId:o?.requestId}),v=await f.signMessage(e,{message:T,address:m,chainId:l??void 0}),I=o?.expirySeconds?new Date(Date.now()+o.expirySeconds*1e3).toISOString():null,A={message:{raw:T,domain:y,address:m,statement:o?.statement??null,uri:C,version:1,chainId:l,nonce:S,issuedAt:E,blockchain:ti(l),expirationTime:I,notBefore:null,resources:o?.resources??[],requestId:o?.requestId??null},signature:v};return a(A),A}catch(S){let E=S instanceof Error?S:new Error("SIWx sign-in failed");throw u(E),E}finally{n(!1)}},[e,t,r]),isSigningIn:s,result:i,error:g,clearError:c}}import{WalletError as Vt}from"@naculus/connect-core";import{useCallback as lr}from"react";function ai(){let{session:e,chainId:t}=P();return lr(r=>{if(!e)throw new Vt("wallet_unavailable","No active session");let s=r??t;if(s&&!s.startsWith("eip155:"))throw new Vt("namespace_mismatch",`Ethereum SIWx requires an eip155 chain, received ${s}`);let n=e.namespaces.eip155;if(!n||n.accounts.length===0)throw new Vt("namespace_mismatch","No EVM (eip155) accounts found in session")},[e,t])}function ii(){let e=ai(),t=Re();return{signIn:lr(async s=>(e(s?.chainId),t.signIn(s)),[e,t.signIn]),isSigningIn:t.isSigningIn,result:t.result,error:t.error,clearError:t.clearError}}import{WalletError as li}from"@naculus/connect-core";import{SimulationManager as ci}from"@naculus/wallet-engine";import{useCallback as cr,useRef as ui,useState as zt}from"react";function pi(e){let t=e?.rpcUrl,r=e?.chainId,s=ui(null);function n(){return s.current||(s.current=new ci({enabled:!0,rpcUrl:t,autoSimulate:!1})),s.current}let[i,a]=zt(null),[g,u]=zt(!1),[c,h]=zt(null),o=cr(async(d,f,m,y,C)=>{u(!0),h(null);try{let S=n(),E=C?.chainId??r;if(E===void 0)throw new li("invalid_chain","No chain to simulate on. Connect a wallet or pass a chainId.");let T=C?.rpcUrl??t,v=await S.simulateERC20Transfer(d,f,m,y,E,C?.decimals,T);return a(v),v}catch(S){let E=S instanceof Error?S:new Error(String(S));throw h(E),E}finally{u(!1)}},[t,r]),l=cr(()=>{a(null),h(null),u(!1)},[]);return{result:i,loading:g,error:c,simulate:o,reset:l}}import{useState as Xe,useCallback as jt,useEffect as di,useRef as mi}from"react";import{LocalStorageAdapter as fi,logger as Ye}from"@naculus/connect-core";var Je="siwx_auth";function gi(e){return new fi(e)}function hi(e,t){return e.message.expirationTime?new Date(e.message.expirationTime).getTime()<=t.getTime():!1}function Ci(e,t){return e.message.notBefore?new Date(e.message.notBefore).getTime()<=t.getTime():!0}function yi(e){let{storagePrefix:t="naculus_",autoRestore:r=!0}=e??{},[s,n]=Xe(null),[i,a]=Xe(r),[g,u]=Xe(!1),[c,h]=Xe(null),o=Re(),l=mi(gi(t)),d=jt(()=>h(null),[]);di(()=>{if(!r){a(!1);return}let y=!1;return(async()=>{try{let C=l.current,S=await C.get(Je);if(y)return;S&&!hi(S,new Date)&&Ci(S,new Date)?(Ye.info("react/useSiwxAuthSession","Restored persisted SIWx auth session"),n(S),h(null)):S&&(Ye.info("react/useSiwxAuthSession","Persisted SIWx auth expired, clearing"),await C.remove(Je))}catch(C){Ye.warn("react/useSiwxAuthSession","Failed to restore SIWx auth:",C)}finally{y||a(!1)}})(),()=>{y=!0}},[r]);let f=jt(async y=>{u(!0),h(null);try{let C=await o.signIn(y);return await l.current.set(Je,C),n(C),u(!1),C}catch(C){let S=C instanceof Error?C:new Error("SIWx sign-in failed");throw h(S),u(!1),S}},[o]),m=jt(async()=>{try{await l.current.remove(Je)}catch(y){Ye.warn("react/useSiwxAuthSession","Failed to clear SIWx auth:",y)}n(null),h(null)},[]);return{isSignedIn:s!==null,isRestoring:i,siwxResult:s,isSigningIn:g,error:c,signIn:f,signOut:m,clearError:d}}import{AA_SUPPORTED_CHAINS as wi,DEFAULT_ENTRY_POINT as Si,WalletError as mr}from"@naculus/connect-core";import{useCallback as ae,useEffect as ur,useRef as Gt,useState as Ie}from"react";import{resolveEvmChainId as pr}from"@naculus/connect-appkit-core";function Ei(e){if(!e)return null;let t=e.includes(":")?e.split(":").pop():e;return t&&/^0x[0-9a-fA-F]{40}$/.test(t)?t:null}function dr(e){return new mr("wallet_unavailable",e)}function ki(e){let{evmAccount:t}=H(),{session:r,chainId:s,client:n}=P(),[i,a]=Ie(null),[g,u]=Ie(!1),[c,h]=Ie(null),[o,l]=Ie(!1),[d,f]=Ie(null),m=Gt(null),y=Gt(0),C=Gt(!1);ur(()=>{if(m.current=null,!e?.rpcUrl)return;let k=!1;return import("@naculus/connect-core").then(({SmartAccountManager:R})=>{if(k)return;let b=pr(e.chainId,s);b&&(m.current=new R({rpcUrl:e.rpcUrl,chainId:b,bundlerClient:{url:e.bundlerUrl??""}}))}).catch(R=>{k||f(R instanceof Error?R:new Error("Failed to load account-abstraction module"))}),()=>{k=!0}},[s,e?.rpcUrl,e?.bundlerUrl,e?.chainId]),ur(()=>{y.current+=1,C.current=!1,a(null),u(!1),h(null),l(!1),f(null)},[t,s,e?.rpcUrl,e?.bundlerUrl,e?.chainId,e?.entryPoint,e?.accountType,e?.salt]);let S=ae(()=>{let k=Ei(t);if(!k||!m.current)return null;let R=pr(e?.chainId,s);return R?{owner:k,accountType:e?.accountType??"simple",entryPoint:e?.entryPoint??wi[R]?.entryPoint??Si,chainId:R,salt:e?.salt}:null},[t,s,e?.accountType,e?.chainId,e?.entryPoint,e?.salt]),E=ae(k=>(f(k),null),[]),T=ae(()=>C.current?null:(C.current=!0,y.current),[]),v=ae(k=>{y.current===k&&(C.current=!1)},[]),I=ae(async()=>{let k=S();if(!k||!m.current)return E(new Error("Smart account not configured"));let R=T();if(R===null)return E(new Error("Smart account operation already in progress"));l(!0),f(null);try{let O=await m.current.createAccount(k);return y.current!==R?null:(a(O.address),u(O.isDeployed),h(O),O)}catch(b){if(y.current!==R)return null;let O=b instanceof Error?b:new Error("Failed to create smart account");return f(O),null}finally{y.current===R&&l(!1),v(R)}},[T,E,v,S]),A=ae(async()=>{let k=S();if(!k||!m.current)return E(new Error("Smart account not configured"));if(!r)return E(dr("No active session"));let R=M(n);if(!R)return E(dr("Client not initialized"));if(s&&s!==k.chainId)return E(new mr("chain_mismatch",`Connected chain ${s} does not match smart account chain ${k.chainId}.`));let b=T();if(b===null)return E(new Error("Smart account operation already in progress"));l(!0),f(null);try{let O=m.current,_=await O.createAccount(k);if(y.current!==b)return null;if(_.isDeployed)return a(_.address),u(!0),h(_),_.address;let p=await O.getDeployCallData(k),w=await R.sendTransaction(r,{transaction:{to:p.to,data:p.data,value:p.value.toString()},chainId:k.chainId});if(y.current!==b)return null;let x=await O.createAccount(k);return a(x.address),u(x.isDeployed),h(x),w}catch(O){if(y.current!==b)return null;let _=O instanceof Error?O:new Error("Failed to deploy smart account");return f(_),null}finally{y.current===b&&l(!1),v(b)}},[n,s,T,E,v,S,r]),U=ae(async()=>{let k=S();if(!k||!m.current)return null;let R=y.current;try{let b=await m.current.getAccountAddress(k);return y.current!==R?null:(a(b),b)}catch(b){return y.current!==R||f(b instanceof Error?b:new Error("Failed to get smart account address")),null}},[S]);return{address:i,isDeployed:g,accountInfo:c,isLoading:o,error:d,createWallet:I,deployWallet:A,getAddress:U}}import{useMemo as xi}from"react";function Qt(){let{accounts:e,isConnected:t}=P();return xi(()=>{if(!t)return{address:null,caip10:null,chainId:null,isConnected:!1};let r=e.find(a=>a.startsWith("solana:"))??null;if(!r)return{address:null,caip10:null,chainId:null,isConnected:t};let s=r.split(":"),n=s.length>=3?s[s.length-1]:null,i=s.length>=3?s.slice(0,-1).join(":"):null;return{address:n,caip10:r,chainId:i,isConnected:t}},[e,t])}import{useCallback as vi,useEffect as fr,useRef as bi,useState as Xt}from"react";import{getSolanaBalance as Ai}from"@naculus/connect-core";function Ti(e={}){let{client:t}=P(),{address:r}=Qt(),s=e.address??r,n=e.rpcUrl??M(t)?.solanaRpcUrl??null,[i,a]=Xt(null),[g,u]=Xt(!1),[c,h]=Xt(null),o=bi(0),l=vi(async()=>{if(!s||!n){a(null);return}let d=++o.current;u(!0),h(null);try{let f=await Ai(n,s);if(d!==o.current)return;a(f)}catch(f){if(d!==o.current)return;a(null),h(f instanceof Error?f:new Error("Balance read failed"))}finally{d===o.current&&u(!1)}},[s,n]);return fr(()=>{l()},[l]),fr(()=>{if(!e.refreshInterval||e.refreshInterval<=0)return;let d=setInterval(()=>{l()},e.refreshInterval);return()=>clearInterval(d)},[e.refreshInterval,l]),{balance:i,isFetching:g,error:c,isConfigured:!!n,refetch:l}}import{WalletError as gr}from"@naculus/connect-core";import{useCallback as Yt,useState as Jt}from"react";import{getSignatureStatus as Ri}from"@naculus/connect-core";function Ii(){let{client:e,session:t}=P(),[r,s]=Jt(!1),[n,i]=Jt(!1),[a,g]=Jt(null),u=()=>{let l=M(e);if(!l||!t)throw new gr("wallet_unavailable","No connected wallet.");return l},c=Yt(async l=>{s(!0),g(null);try{return await u().signTransaction(t,{transaction:l})}catch(d){let f=d instanceof Error?d:new Error("Signing failed");throw g(f),f}finally{s(!1)}},[e,t]),h=Yt(async l=>{i(!0),g(null);try{return await u().sendTransaction(t,{transaction:l})}catch(d){let f=d instanceof Error?d:new Error("Send failed");throw g(f),f}finally{i(!1)}},[e,t]),o=Yt(async l=>{let d=M(e)?.solanaRpcUrl;if(!d)throw new gr("no_rpc","Set solanaRpcUrl on the client to read a signature's status.");return Ri(d,l)},[e]);return{signTransaction:c,sendTransaction:h,getStatus:o,isSigning:r,isSending:n,error:a,reset:()=>g(null)}}import{useCallback as hr,useState as Cr}from"react";import{toChainSwitchError as Ui}from"@naculus/connect-appkit-core";function Pi(){let{switchChain:e,chainId:t}=P(),[r,s]=Cr(!1),[n,i]=Cr(null),a=hr(async u=>{s(!0),i(null);try{await e(u)}catch(c){let h=Ui(c);throw i(h),h}finally{s(!1)}},[e]),g=hr(()=>{i(null)},[]);return{switchChain:a,isSwitching:r,currentChainId:t,error:n,clearError:g}}import{chainNumber as Wi,resolveChain as _i,toViemChain as Oi}from"@naculus/connect-appkit-core";import{useState as Ze,useEffect as Zt,useCallback as yr,useMemo as en,useRef as Ni}from"react";import{createPublicClient as Di,http as Mi,formatUnits as Li}from"viem";function Bi(e){let{evmAccount:t,isConnected:r}=H(),{chainId:s,chains:n}=P(),[i,a]=Ze([]),[g,u]=Ze(!1),[c,h]=Ze(null),{tokens:o,refreshInterval:l}=e,d=Ni(null),f=en(()=>o.map(A=>A.address.toLowerCase()+"|"+A.decimals+"|"+A.symbol).join(","),[o]),m=en(()=>_i(n,s),[s,n]),y=m?Wi(m):null,C=en(()=>m?Oi(m,y):null,[m,y]),[S,E]=Ze(null);Zt(()=>{if(!C||!m?.rpcUrl){E(null);return}let A=Di({transport:Mi(m.rpcUrl),chain:C});E(A)},[m,C]);let T=[{name:"balanceOf",type:"function",stateMutability:"view",inputs:[{name:"owner",type:"address"}],outputs:[{name:"balance",type:"uint256"}]}],v=yr(async()=>{if(!t||!S||o.length===0){a([]);return}u(!0),h(null);try{let A=t.includes(":")?t.split(":").pop():t,k=(await Promise.allSettled(o.map(async R=>{try{let b=await S.readContract({address:R.address,abi:T,functionName:"balanceOf",args:[A]});return{address:R.address,symbol:R.symbol,decimals:R.decimals,name:R.name,balance:b.toString(),formatted:Li(b,R.decimals)}}catch{return{address:R.address,symbol:R.symbol,decimals:R.decimals,name:R.name,balance:null,formatted:null}}}))).map(R=>R.status==="fulfilled"?R.value:{address:"",symbol:"?",decimals:0,balance:null,formatted:null});a(k)}catch(A){h(A instanceof Error?A:new Error("Failed to fetch token balances"))}finally{u(!1)}},[t,S,f]);Zt(()=>{r&&t&&o.length>0&&v()},[r,t,f,v]),Zt(()=>(l&&l>0&&r&&t&&o.length>0&&(d.current=setInterval(v,l)),()=>{d.current&&(clearInterval(d.current),d.current=null)}),[l,r,t,f,v]);let I=yr(A=>i.find(U=>U.address.toLowerCase()===A.toLowerCase()),[i]);return{tokenBalances:i,isLoading:g,error:c,refetch:v,getTokenBalance:I,chain:m}}import{useState as tn,useEffect as wr,useCallback as Hi,useRef as Fi}from"react";function Ki(e,t,r){let s=Ae(),n=r??s,[i,a]=tn([]),[g,u]=tn(!1),[c,h]=tn(null),o=Fi(0),l=Hi(async()=>{if(n){u(!0),h(null),o.current++;try{let f=await n.getTxHistory(e,t);a(f)}catch(f){h(f instanceof Error?f:new Error(String(f)))}finally{u(!1)}}},[n,e,t]);wr(()=>{l().catch(()=>{})},[l]),wr(()=>{if(!n)return;let f=()=>{l().catch(()=>{})};return n.on("statusChange",f),()=>{n.off("statusChange",f)}},[n,l]);let d={pending:i.filter(f=>f.status==="pending").length,confirmed:i.filter(f=>f.status==="confirmed").length,failed:i.filter(f=>f.status==="failed").length};return{entries:i,isLoading:g,error:c,refresh:l,summary:d}}import{useCallback as Ue,useEffect as Sr,useRef as me,useState as ie}from"react";var Q=class extends Error{constructor(t){super(t),this.name="InvalidUserOperationReceiptError"}};function Er(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function et(e){return typeof e=="string"&&/^0x[0-9a-fA-F]{40}$/.test(e)}function nn(e){return typeof e=="string"&&/^0x[0-9a-fA-F]{64}$/.test(e)}function $i(e){return typeof e=="string"&&/^0x(?:[0-9a-fA-F]{2})*$/.test(e)}function rn(e,t){if(typeof e!="string"||!/^(?:0x(?:0|[1-9a-fA-F][0-9a-fA-F]*)|(?:0|[1-9][0-9]*))$/.test(e))throw new Q(`Bundler returned an invalid ${t}.`);return BigInt(e)}function qi(e,t){if(!Er(e))throw new Q("Bundler returned an invalid UserOperation receipt.");if(!nn(e.userOpHash)||e.userOpHash.toLowerCase()!==t.toLowerCase())throw new Q("Bundler receipt does not match the requested UserOperation hash.");if(!et(e.entryPoint)||!et(e.sender))throw new Q("Bundler receipt contains an invalid account address.");if(e.paymaster!==void 0&&e.paymaster!==null&&!et(e.paymaster))throw new Q("Bundler receipt contains an invalid paymaster address.");if(typeof e.success!="boolean"||!nn(e.transactionHash))throw new Q("Bundler receipt contains an invalid execution result.");if(!Array.isArray(e.logs))throw new Q("Bundler receipt contains invalid logs.");let r=e.logs.map(s=>{if(!Er(s)||!et(s.address)||!Array.isArray(s.topics)||!s.topics.every(nn)||!$i(s.data))throw new Q("Bundler receipt contains an invalid log entry.");return{address:s.address,topics:s.topics,data:s.data}});return{userOpHash:e.userOpHash,entryPoint:e.entryPoint,sender:e.sender,nonce:rn(e.nonce,"nonce"),...e.paymaster===void 0||e.paymaster===null?{}:{paymaster:e.paymaster},actualGasUsed:rn(e.actualGasUsed,"actualGasUsed"),actualGasCost:rn(e.actualGasCost,"actualGasCost"),success:e.success,transactionHash:e.transactionHash,logs:r}}function Vi(e){let t=e?.bundlerUrl,r=e?.pollInterval??2e3,s=e?.maxRetries??30,[n,i]=ie("idle"),[a,g]=ie(null),[u,c]=ie(e?.userOpHash??null),[h,o]=ie(null),[l,d]=ie(!1),[f,m]=ie(0),y=me(0),[C,S]=ie(0),E=me(null),T=me(null),v=me(0),I=me(0),A=me(null),U=Ue(()=>{E.current&&(clearInterval(E.current),E.current=null),T.current&&(clearTimeout(T.current),T.current=null)},[]),k=Ue(async(_,p)=>{if(!t||p!==v.current)return;let w=I.current+1;I.current=w,m(w);let x=new AbortController;A.current=x;let W=D=>{p===v.current&&(i("not_found"),d(!1),U(),o(D))},N=D=>{if(p===v.current){if(w<=s){T.current=setTimeout(()=>{k(_,p)},r);return}W(D)}};try{let D=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getUserOperationReceipt",params:[_]}),signal:x.signal});if(p!==v.current)return;if(!D.ok)throw new Error(`Bundler returned HTTP ${D.status} while reading UserOperation status.`);let F=await D.json();if(p!==v.current)return;if(F.error)throw new Error(typeof F.error.message=="string"?F.error.message:"Bundler returned a JSON-RPC error.");if(F.result!==void 0&&F.result!==null){let le=qi(F.result,_);g(le),i(le.success?"confirmed":"failed"),d(!1),U();return}i("pending"),N(new Error("UserOperation not included after maximum retries"))}catch(D){if(p!==v.current||x.signal.aborted)return;let F=D instanceof Error?D:new Error("Unknown bundler response failure");if(F instanceof Q){W(F);return}N(new Error(`UserOperation status unavailable after ${w} attempt${w===1?"":"s"}: ${F.message}`))}finally{A.current===x&&(A.current=null)}},[t,r,s,U]),R=Ue(_=>{v.current+=1;let p=v.current;if(A.current?.abort(),A.current=null,U(),c(_),g(null),o(null),I.current=0,m(0),S(0),y.current=Date.now(),!t){i("not_found"),d(!1),o(new Error("Bundler URL not configured"));return}i("pending"),d(!0),E.current=setInterval(()=>{S(Date.now()-y.current)},1e3),k(_,p)},[t,U,k]),b=Ue(()=>{v.current+=1,A.current?.abort(),A.current=null,U(),d(!1)},[U]),O=Ue(()=>{v.current+=1,A.current?.abort(),A.current=null,U(),c(null),i("idle"),g(null),o(null),d(!1),I.current=0,m(0),S(0)},[U]);return Sr(()=>{e?.userOpHash&&e?.autoStart!==!1&&R(e.userOpHash)},[]),Sr(()=>()=>{v.current+=1,A.current?.abort(),A.current=null,U()},[U]),{status:n,receipt:a,userOpHash:u,error:h,isPolling:l,elapsedMs:C,attempts:f,start:R,stop:b,reset:O}}import{useMemo as Xi}from"react";var zi={"storage.critical.title":"Insecure Storage Detected","storage.critical.body":"Your browser does not support IndexedDB. Wallet data is stored in plaintext in localStorage and could be exposed to XSS attacks. We strongly recommend switching to a modern browser.","storage.warning.title":"Storage Security Warning","storage.warning.body":"Your browser does not support IndexedDB, but your wallet data is encrypted with AES-256-GCM. Consider switching browsers for better origin isolation.","address.empty":"Address is empty","address.invalid_format":"Invalid address format (expected 0x + 40 hex chars)","address.zero_address":"Address is the zero address \u2014 funds would be permanently lost","address.burn_address":"Address appears to be a burn address \u2014 funds would be permanently lost","wallet.connect":"Connect Wallet","wallet.disconnect":"Disconnect","wallet.connecting":"Connecting...","wallet.copy_address":"Copy address","wallet.copied":"Copied!","wallet.view_on_explorer":"View on Explorer","wallet.retry":"Retry","wallet.connection_failed":"Connection failed","wallet.scan_qr":"Scan with your wallet app","embedded.generate":"Create Wallet","embedded.import":"Import Wallet","embedded.backup_seed":"Back up your seed phrase","embedded.backup_warning":"Anyone with your seed phrase can access your funds. Store it securely.","embedded.backup_done":"I've saved my seed phrase","embedded.wipe":"Remove Wallet","embedded.wipe_confirm":"Are you sure? This cannot be undone."},ji={"storage.critical.title":"\u5075\u6E2C\u5230\u4E0D\u5B89\u5168\u5132\u5B58","storage.critical.body":"\u60A8\u7684\u700F\u89BD\u5668\u4E0D\u652F\u63F4 IndexedDB\u3002\u9322\u5305\u8CC7\u6599\u4EE5\u660E\u6587\u5132\u5B58\u5728 localStorage \u4E2D\uFF0C\u53EF\u80FD\u66B4\u9732\u65BC XSS \u653B\u64CA\u3002\u5F37\u70C8\u5EFA\u8B70\u66F4\u63DB\u81F3\u73FE\u4EE3\u700F\u89BD\u5668\u3002","storage.warning.title":"\u5132\u5B58\u5B89\u5168\u8B66\u544A","storage.warning.body":"\u60A8\u7684\u700F\u89BD\u5668\u4E0D\u652F\u63F4 IndexedDB\uFF0C\u4F46\u9322\u5305\u8CC7\u6599\u5DF2\u4F7F\u7528 AES-256-GCM \u52A0\u5BC6\u3002\u5EFA\u8B70\u66F4\u63DB\u700F\u89BD\u5668\u4EE5\u7372\u5F97\u66F4\u597D\u7684\u9694\u96E2\u4FDD\u8B77\u3002","address.empty":"\u5730\u5740\u70BA\u7A7A","address.invalid_format":"\u7121\u6548\u7684\u5730\u5740\u683C\u5F0F\uFF08\u61C9\u70BA 0x + 40 \u500B\u5341\u516D\u9032\u4F4D\u5B57\u5143\uFF09","address.zero_address":"\u6B64\u70BA\u96F6\u5730\u5740 \u2014 \u8CC7\u91D1\u5C07\u6C38\u4E45\u4E1F\u5931","address.burn_address":"\u6B64\u5730\u5740\u70BA\u71D2\u6BC0\u5730\u5740 \u2014 \u8CC7\u91D1\u5C07\u6C38\u4E45\u4E1F\u5931","wallet.connect":"\u9023\u63A5\u9322\u5305","wallet.disconnect":"\u65B7\u958B\u9023\u7DDA","wallet.connecting":"\u9023\u7DDA\u4E2D...","wallet.copy_address":"\u8907\u88FD\u5730\u5740","wallet.copied":"\u5DF2\u8907\u88FD\uFF01","wallet.view_on_explorer":"\u5728\u700F\u89BD\u5668\u67E5\u770B","wallet.retry":"\u91CD\u8A66","wallet.connection_failed":"\u9023\u7DDA\u5931\u6557","wallet.scan_qr":"\u4F7F\u7528\u9322\u5305 App \u6383\u63CF","embedded.generate":"\u5EFA\u7ACB\u9322\u5305","embedded.import":"\u532F\u5165\u9322\u5305","embedded.backup_seed":"\u5099\u4EFD\u52A9\u8A18\u8A5E","embedded.backup_warning":"\u4EFB\u4F55\u4EBA\u53D6\u5F97\u60A8\u7684\u52A9\u8A18\u8A5E\u90FD\u53EF\u4EE5\u5B58\u53D6\u60A8\u7684\u8CC7\u91D1\u3002\u8ACB\u5B89\u5168\u5132\u5B58\u3002","embedded.backup_done":"\u6211\u5DF2\u5132\u5B58\u52A9\u8A18\u8A5E","embedded.wipe":"\u79FB\u9664\u9322\u5305","embedded.wipe_confirm":"\u78BA\u5B9A\u8981\u79FB\u9664\u55CE\uFF1F\u6B64\u64CD\u4F5C\u7121\u6CD5\u5FA9\u539F\u3002"},kr={en:zi,zh:ji},on="en";function Gi(e){on=e}function Qi(){return on}function fe(e){return kr[on][e]??kr.en[e]??e}var xr="0x0000000000000000000000000000000000000000",Yi=new Set([xr,"0x0000000000000000000000000000000000000001","0x000000000000000000000000000000000000dead","0x000000000000000000000000000000000000dEaD"]);function Ji(e){let t=e.toLowerCase();return Yi.has(t)?!0:t.includes("dead")&&t.length>=40}function Zi(e){return e===xr}function el(e){return/^0x[0-9a-fA-F]{40}$/.test(e)}function vr(e){return e?el(e)?Zi(e)?{isValid:!1,level:"blocked",warning:fe("address.zero_address")}:Ji(e)?{isValid:!1,level:"blocked",warning:fe("address.burn_address")}:{isValid:!0,level:"ok",warning:null}:{isValid:!1,level:"blocked",warning:fe("address.invalid_format")}:{isValid:!1,level:"blocked",warning:fe("address.empty")}}function tl({address:e}){return{validation:Xi(()=>vr(e),[e])}}function nl(){let{status:e,session:t,accounts:r,chainId:s,error:n,connect:i,disconnect:a,reconnect:g,switchChain:u}=P(),c=e==="connected",h=e==="connecting",o=e==="reconnecting",l=r[0]??null;return{status:e,session:t,accounts:r,chainId:s,error:n,isConnected:c,isConnecting:h,isReconnecting:o,isDisconnected:e==="disconnected",currentAccount:l,connect:i,disconnect:a,reconnect:g,switchChain:u}}import{useCallback as an,useMemo as Tr}from"react";var br={wallet_unavailable:"Wallet Not Detected",user_rejected:"Connection Rejected",deeplink_timeout:"Wallet Connection Timed Out",session_expired:"Session Expired",intent_expired:"Connection Request Expired",namespace_mismatch:"Network Mismatch",chain_unsupported:"Unsupported Network",method_not_allowed:"Action Not Allowed",signature_rejected:"Signature Rejected",tx_failed:"Transaction Failed"},Ar={wallet_unavailable:"No wallet found. Please install a compatible wallet (e.g., MetaMask, WalletConnect) and try again.",user_rejected:"The connection request was declined in your wallet. You can try again whenever you're ready.",deeplink_timeout:"The wallet didn't respond in time. This can happen if the wallet app isn't installed or takes too long to open.",session_expired:"Your wallet session has expired. Please reconnect to continue.",intent_expired:"The connection request expired. Please try connecting again.",namespace_mismatch:"This wallet doesn't support the required network. Try using a different wallet or network.",chain_unsupported:"This network isn't supported. Please switch to a supported network in your wallet.",method_not_allowed:"This action isn't supported by your current wallet or network.",signature_rejected:"The signature request was declined in your wallet.",tx_failed:"The transaction couldn't be completed. This could be due to insufficient funds, network congestion, or a contract error."},Pe="Something went wrong",We="An unexpected error occurred. Please try again. If the problem persists, check your connection and wallet configuration.";function _e(e){if(!e)return{title:Pe,description:We};let t=e;if(t.name==="WalletError"&&t.code){let r=t.code,s=br[r]??Pe,n=Ar[r]??t.message??We;return{title:s,description:n,code:r}}if(e instanceof Error){let r=e.message;return/user rejected/i.test(r)||/rejected/.test(r)?{title:"Request Rejected",description:"The request was declined.",code:"user_rejected"}:/timeout/i.test(r)||/timed? ?out/i.test(r)?{title:"Request Timed Out",description:"The request took too long. Please try again.",code:"deeplink_timeout"}:/insufficient funds/i.test(r)?{title:"Insufficient Funds",description:"You don't have enough funds to complete this transaction.",code:"tx_failed"}:/network/i.test(r)||/chain/i.test(r)?{title:"Network Error",description:r,code:"chain_unsupported"}:{title:Pe,description:r||We}}return typeof e=="string"?{title:Pe,description:e||We}:{title:Pe,description:We}}function sn(e){if(e===null||typeof e!="object")return!1;let t=e;return t.name!=="WalletError"||!t.code?!1:["deeplink_timeout","session_expired","intent_expired","tx_failed"].includes(t.code)}function rl(){let{error:e,clearError:t}=P(),r=Tr(()=>e?_e(e):null,[e]),s=Tr(()=>e?sn(e):!1,[e]),n=an(()=>{t()},[t]),i=an(g=>_e(g),[]),a=an(g=>async()=>{try{return await g()}catch(u){let c=_e(u);if(u instanceof Error){let h=u;try{h.title=c.title,h.friendlyMessage=c.description,h.code===void 0&&c.code!==void 0&&(h.code=c.code)}catch{}throw h}throw Object.assign(new Error(c.description,{cause:u}),{title:c.title,code:c.code,friendlyMessage:c.description})}},[]);return{error:e,friendlyError:r,clearError:n,isRetryable:s,formatError:i,wrapAsync:a}}import{useState as tt,useEffect as ol,useCallback as Rr,useRef as sl}from"react";import{TokenListManager as al}from"@naculus/connect-core";import{eip155ChainIdToNumber as Ir}from"@naculus/connect-appkit-core";function nt(e,t){let r=sl(null),[s,n]=tt([]),[i,a]=tt(t?.autoLoad!==!1),[g,u]=tt(!1),[c,h]=tt(null);if(!r.current){let d={};t?.sources&&(d.sources=t.sources),r.current=new al(d)}let o=Rr(async()=>{let d=r.current;if(d){a(!0),h(null);try{await d.load();let f=e?Ir(e):void 0,m=d.getTokens(f!==void 0?{chainId:f}:void 0);n(m),u(!0)}catch(f){h(f instanceof Error?f:new Error(String(f)))}finally{a(!1)}}},[e]),l=Rr(async()=>{let d=r.current;if(d){a(!0),h(null);try{await d.refresh();let f=e?Ir(e):void 0,m=d.getTokens(f!==void 0?{chainId:f}:void 0);n(m),u(!0)}catch(f){h(f instanceof Error?f:new Error(String(f)))}finally{a(!1)}}},[e]);return ol(()=>{t?.autoLoad!==!1&&o()},[o,t?.autoLoad]),{tokens:s,isLoading:i,isLoaded:g,error:c,refetch:l}}import{useState as Pr,useEffect as dl,useRef as ml}from"react";import{TokenListManager as fl}from"@naculus/connect-core";import{ETHEREUM_MAINNET_TOKENS as il,POLYGON_TOKENS as ll,OPTIMISM_TOKENS as cl,ARBITRUM_TOKENS as ul,BASE_TOKENS as pl}from"@naculus/connect-core";function Ur(){return[{name:"built-in",tokens:[...il,...ll,...cl,...ul,...pl],enabled:!0},{name:"uniswap-default",url:"https://tokens.uniswap.org",enabled:!0,refreshInterval:1440*60*1e3}]}import{eip155ChainIdToNumber as gl}from"@naculus/connect-appkit-core";var hl=300,rt=null;function Cl(){return rt||(rt=new fl({sources:Ur()}),rt.load().catch(()=>{})),rt}function ot(e,t){let[r,s]=Pr({exact:[],fuzzy:[],hasMore:!1}),[n,i]=Pr(!1),a=ml(null),g=e.trim();return dl(()=>{if(!g){s({exact:[],fuzzy:[],hasMore:!1}),i(!1);return}return a.current&&clearTimeout(a.current),i(!0),a.current=setTimeout(()=>{let u=Cl(),c=t?gl(t):void 0,h=u.search(g,{chainId:c,limit:20});s(h),i(!1)},hl),()=>{a.current&&clearTimeout(a.current)}},[g,t]),{results:r,isSearching:n}}import ln,{useCallback as yl}from"react";import{Fragment as wl,jsx as j,jsxs as X}from"react/jsx-runtime";function Wr({chainId:e,onSelect:t,onClose:r,options:s}){let[n,i]=ln.useState(""),{tokens:a,isLoading:g,error:u}=nt(e),{results:c,isSearching:h}=ot(n,n?e:void 0),o=s?.showRecommendations??!0,l=ln.useMemo(()=>{if(n.trim()){let y=[...c.exact,...c.fuzzy].map(C=>C.token);return s?.filter?y.filter(s.filter):y}let m=a;return s?.filter?m.filter(s.filter):m},[n,c,a,s?.filter]),d=ln.useMemo(()=>!o||n.trim()?[]:a.slice(0,6),[a,o,n]),f=yl(m=>{t(m),r()},[t,r]);return X("div",{style:{background:"hsl(var(--background))",borderRadius:"12px",padding:"16px",color:"hsl(var(--foreground))",minWidth:"320px",maxWidth:"400px",fontFamily:"system-ui, sans-serif"},children:[X("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"12px"},children:[j("h3",{style:{margin:0,fontSize:"16px",fontWeight:600},children:"Select Token"}),j("button",{onClick:r,style:{background:"none",border:"none",color:"hsl(var(--muted-foreground))",cursor:"pointer",fontSize:"18px",padding:"4px 8px"},children:"\u2715"})]}),j("input",{type:"text",placeholder:"Search token name or paste address",value:n,onChange:m=>i(m.target.value),style:{width:"100%",padding:"10px 12px",borderRadius:"8px",border:"1px solid #333",background:"hsl(var(--card))",color:"hsl(var(--foreground))",fontSize:"14px",outline:"none",boxSizing:"border-box",marginBottom:"12px"},autoFocus:!0}),g&&!h&&j("div",{style:{textAlign:"center",padding:"20px",color:"hsl(var(--muted-foreground))"},children:"Loading tokens..."}),u&&X("div",{style:{textAlign:"center",padding:"12px",color:"hsl(var(--destructive))",fontSize:"13px"},children:["Error: ",u.message]}),o&&d.length>0&&!n.trim()&&X("div",{style:{marginBottom:"12px"},children:[j("div",{style:{fontSize:"11px",color:"hsl(var(--muted-foreground))",textTransform:"uppercase",letterSpacing:"0.5px",marginBottom:"8px"},children:"Popular"}),j("div",{style:{display:"flex",gap:"6px",flexWrap:"wrap"},children:d.map(m=>X("button",{onClick:()=>f(m),style:{background:"hsl(var(--card))",border:"1px solid #333",borderRadius:"20px",padding:"6px 14px",color:"hsl(var(--foreground))",cursor:"pointer",fontSize:"13px",display:"flex",alignItems:"center",gap:"4px"},children:[m.logoURI?j("img",{src:m.logoURI,alt:"",style:{width:"16px",height:"16px",borderRadius:"50%"},onError:y=>{y.target.style.display="none"}}):null,m.symbol]},`${m.chainId}:${m.address}`))})]}),n.trim()&&!g&&j("div",{style:{fontSize:"11px",color:"hsl(var(--muted-foreground))",marginBottom:"8px"},children:l.length>0?X(wl,{children:[c.exact.length," exact, ",c.fuzzy.length," fuzzy",c.hasMore?" (more available)":""]}):"No results found"}),j("div",{style:{maxHeight:"320px",overflowY:"auto",display:"flex",flexDirection:"column",gap:"2px"},children:l.map(m=>X("button",{onClick:()=>f(m),style:{display:"flex",alignItems:"center",gap:"10px",padding:"10px 8px",background:"transparent",border:"none",borderRadius:"8px",color:"hsl(var(--foreground))",cursor:"pointer",textAlign:"left",width:"100%",fontSize:"14px"},onMouseEnter:y=>{y.target.style.background="hsl(var(--card))"},onMouseLeave:y=>{y.target.style.background="transparent"},children:[j("div",{style:{width:"32px",height:"32px",borderRadius:"50%",background:"hsl(var(--border))",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:600,flexShrink:0,overflow:"hidden"},children:m.logoURI?j("img",{src:m.logoURI,alt:m.symbol,style:{width:"100%",height:"100%"},onError:y=>{let C=y.target;C.style.display="none",C.parentElement.textContent=m.symbol.slice(0,2)}}):m.symbol.slice(0,2)}),X("div",{style:{flex:1,minWidth:0},children:[j("div",{style:{fontWeight:600,fontSize:"14px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m.symbol}),j("div",{style:{fontSize:"12px",color:"hsl(var(--muted-foreground))",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m.name})]}),X("div",{style:{fontSize:"11px",color:"#666",textAlign:"right",flexShrink:0},children:[X("div",{children:[m.decimals," decimals"]}),X("div",{children:["Chain ",m.chainId]})]})]},`${m.chainId}:${m.address}`))})]})}import{createComponent as L}from"@stencil/react-output-target/runtime";import B from"react";import{AppkitAccordion as Sl,defineCustomElement as El}from"@naculus/connect-appkit-wc/dist/components/appkit-accordion.js";import{AppkitAccountButton as kl,defineCustomElement as xl}from"@naculus/connect-appkit-wc/dist/components/appkit-account-button.js";import{AppkitAlertDialog as vl,defineCustomElement as bl}from"@naculus/connect-appkit-wc/dist/components/appkit-alert-dialog.js";import{AppkitAvatar as Al,defineCustomElement as Tl}from"@naculus/connect-appkit-wc/dist/components/appkit-avatar.js";import{AppkitBadge as Rl,defineCustomElement as Il}from"@naculus/connect-appkit-wc/dist/components/appkit-badge.js";import{AppkitButton as Ul,defineCustomElement as Pl}from"@naculus/connect-appkit-wc/dist/components/appkit-button.js";import{AppkitCardContent as Wl,defineCustomElement as _l}from"@naculus/connect-appkit-wc/dist/components/appkit-card-content.js";import{AppkitCardDescription as Ol,defineCustomElement as Nl}from"@naculus/connect-appkit-wc/dist/components/appkit-card-description.js";import{AppkitCardFooter as Dl,defineCustomElement as Ml}from"@naculus/connect-appkit-wc/dist/components/appkit-card-footer.js";import{AppkitCardHeader as Ll,defineCustomElement as Bl}from"@naculus/connect-appkit-wc/dist/components/appkit-card-header.js";import{AppkitCardTitle as Hl,defineCustomElement as Fl}from"@naculus/connect-appkit-wc/dist/components/appkit-card-title.js";import{AppkitCard as Kl,defineCustomElement as $l}from"@naculus/connect-appkit-wc/dist/components/appkit-card.js";import{AppkitCheckbox as ql,defineCustomElement as Vl}from"@naculus/connect-appkit-wc/dist/components/appkit-checkbox.js";import{AppkitCollapsible as zl,defineCustomElement as jl}from"@naculus/connect-appkit-wc/dist/components/appkit-collapsible.js";import{AppkitConnectButton as Gl,defineCustomElement as Ql}from"@naculus/connect-appkit-wc/dist/components/appkit-connect-button.js";import{AppkitDialog as Xl,defineCustomElement as Yl}from"@naculus/connect-appkit-wc/dist/components/appkit-dialog.js";import{AppkitDropdownMenu as Jl,defineCustomElement as Zl}from"@naculus/connect-appkit-wc/dist/components/appkit-dropdown-menu.js";import{AppkitInput as ec,defineCustomElement as tc}from"@naculus/connect-appkit-wc/dist/components/appkit-input.js";import{AppkitPopover as nc,defineCustomElement as rc}from"@naculus/connect-appkit-wc/dist/components/appkit-popover.js";import{AppkitProgress as oc,defineCustomElement as sc}from"@naculus/connect-appkit-wc/dist/components/appkit-progress.js";import{AppkitScrollArea as ac,defineCustomElement as ic}from"@naculus/connect-appkit-wc/dist/components/appkit-scroll-area.js";import{AppkitSelect as lc,defineCustomElement as cc}from"@naculus/connect-appkit-wc/dist/components/appkit-select.js";import{AppkitSeparator as uc,defineCustomElement as pc}from"@naculus/connect-appkit-wc/dist/components/appkit-separator.js";import{AppkitSkeleton as dc,defineCustomElement as mc}from"@naculus/connect-appkit-wc/dist/components/appkit-skeleton.js";import{AppkitSwitch as fc,defineCustomElement as gc}from"@naculus/connect-appkit-wc/dist/components/appkit-switch.js";import{AppkitTabs as hc,defineCustomElement as Cc}from"@naculus/connect-appkit-wc/dist/components/appkit-tabs.js";import{AppkitToggleGroup as yc,defineCustomElement as wc}from"@naculus/connect-appkit-wc/dist/components/appkit-toggle-group.js";import{AppkitTooltip as Sc,defineCustomElement as Ec}from"@naculus/connect-appkit-wc/dist/components/appkit-tooltip.js";var kc=L({tagName:"appkit-accordion",elementClass:Sl,react:B,events:{onAppkitToggle:"appkitToggle"},defineCustomElement:El}),xc=L({tagName:"appkit-account-button",elementClass:kl,react:B,events:{},defineCustomElement:xl}),vc=L({tagName:"appkit-alert-dialog",elementClass:vl,react:B,events:{onAppkitClose:"appkitClose",onAppkitOpenChange:"appkitOpenChange"},defineCustomElement:bl}),bc=L({tagName:"appkit-avatar",elementClass:Al,react:B,events:{},defineCustomElement:Tl}),Ac=L({tagName:"appkit-badge",elementClass:Rl,react:B,events:{},defineCustomElement:Il}),Tc=L({tagName:"appkit-button",elementClass:Ul,react:B,events:{},defineCustomElement:Pl}),Rc=L({tagName:"appkit-card",elementClass:Kl,react:B,events:{},defineCustomElement:$l}),Ic=L({tagName:"appkit-card-content",elementClass:Wl,react:B,events:{},defineCustomElement:_l}),Uc=L({tagName:"appkit-card-description",elementClass:Ol,react:B,events:{},defineCustomElement:Nl}),Pc=L({tagName:"appkit-card-footer",elementClass:Dl,react:B,events:{},defineCustomElement:Ml}),Wc=L({tagName:"appkit-card-header",elementClass:Ll,react:B,events:{},defineCustomElement:Bl}),_c=L({tagName:"appkit-card-title",elementClass:Hl,react:B,events:{},defineCustomElement:Fl}),Oc=L({tagName:"appkit-checkbox",elementClass:ql,react:B,events:{onAppkitChange:"appkitChange"},defineCustomElement:Vl}),Nc=L({tagName:"appkit-collapsible",elementClass:zl,react:B,events:{onAppkitToggle:"appkitToggle"},defineCustomElement:jl}),Dc=L({tagName:"appkit-connect-button",elementClass:Gl,react:B,events:{onAppkitConnect:"appkitConnect",onAppkitDisconnect:"appkitDisconnect",onAppkitStartPairing:"appkitStartPairing",onAppkitRetry:"appkitRetry",onAppkitCancelPairing:"appkitCancelPairing",onAppkitMobileDeepLink:"appkitMobileDeepLink",onAppkitCopyAddress:"appkitCopyAddress"},defineCustomElement:Ql}),Mc=L({tagName:"appkit-dialog",elementClass:Xl,react:B,events:{onAppkitClose:"appkitClose",onAppkitOpenChange:"appkitOpenChange"},defineCustomElement:Yl}),Lc=L({tagName:"appkit-dropdown-menu",elementClass:Jl,react:B,events:{onAppkitSelect:"appkitSelect"},defineCustomElement:Zl}),Bc=L({tagName:"appkit-input",elementClass:ec,react:B,events:{onAppkitChange:"appkitChange"},defineCustomElement:tc}),Hc=L({tagName:"appkit-popover",elementClass:nc,react:B,events:{onAppkitOpenChange:"appkitOpenChange"},defineCustomElement:rc}),Fc=L({tagName:"appkit-progress",elementClass:oc,react:B,events:{},defineCustomElement:sc}),Kc=L({tagName:"appkit-scroll-area",elementClass:ac,react:B,events:{},defineCustomElement:ic}),$c=L({tagName:"appkit-select",elementClass:lc,react:B,events:{onAppkitChange:"appkitChange"},defineCustomElement:cc}),qc=L({tagName:"appkit-separator",elementClass:uc,react:B,events:{},defineCustomElement:pc}),Vc=L({tagName:"appkit-skeleton",elementClass:dc,react:B,events:{},defineCustomElement:mc}),zc=L({tagName:"appkit-switch",elementClass:fc,react:B,events:{onAppkitChange:"appkitChange"},defineCustomElement:gc}),jc=L({tagName:"appkit-tabs",elementClass:hc,react:B,events:{onAppkitTabChange:"appkitTabChange"},defineCustomElement:Cc}),Gc=L({tagName:"appkit-toggle-group",elementClass:yc,react:B,events:{onAppkitChange:"appkitChange"},defineCustomElement:wc}),Qc=L({tagName:"appkit-tooltip",elementClass:Sc,react:B,events:{},defineCustomElement:Ec});export{kc as AppkitAccordion,xc as AppkitAccountButton,vc as AppkitAlertDialog,bc as AppkitAvatar,Ac as AppkitBadge,Tc as AppkitButton,Rc as AppkitCard,Ic as AppkitCardContent,Uc as AppkitCardDescription,Pc as AppkitCardFooter,Wc as AppkitCardHeader,_c as AppkitCardTitle,Oc as AppkitCheckbox,Nc as AppkitCollapsible,Dc as AppkitConnectButton,Mc as AppkitDialog,Lc as AppkitDropdownMenu,Bc as AppkitInput,Hc as AppkitPopover,Fc as AppkitProgress,Kc as AppkitScrollArea,$c as AppkitSelect,qc as AppkitSeparator,Vc as AppkitSkeleton,zc as AppkitSwitch,jc as AppkitTabs,Gc as AppkitToggleGroup,Qc as AppkitTooltip,Sn as DEFAULT_EVM_CHAINS,yh as LAMPORTS_PER_SOL,wh as PassphraseCancelledError,Sh as PassphraseGate,kh as SolanaRpcError,Wr as TokenSelector,qn as TxMonitorContext,Ar as WALLET_ERROR_DESCRIPTIONS,br as WALLET_ERROR_TITLES,co as Web3ConnectProvider,ft as Web3Context,ke as buildDelegationPolicyMessage,Hr as clearClient,pt as createClient,fh as formatSol,Jr as getChainById,dt as getClient,mt as getDefaultChains,gh as getLatestBlockhash,Qi as getLocale,hh as getSignatureStatus,Ch as getSolanaBalance,_e as getUserFriendlyError,sn as isRetryableError,Eh as parseSol,os as resetSessionKeyManager,Gi as setLocale,fe as t,H as useAccount,xo as useBalance,Ct as useCapabilities,z as useChain,dn as useCompareCosts,Oo as useConnect,ts as useCreateSessionKey,we as useDelegation,cs as useDelegationPolicy,ds as useDisconnect,Ts as useERC20Allowance,Ns as useERC20Approve,js as useERC20Transfer,aa as useERC20TransferSimulation,fs as useEmbeddedWallet,vt as useExecuteCalls,gn as useExecuteRoute,ma as useLastTx,ya as useLookupAddress,va as useNotification,Ta as usePassphraseGate,Ia as useResolveName,ns as useRevokeSession,yn as useRouteQuote,Kt as useSIWxLogin,Ja as useSIWxSession,kt as useSendCalls,xe as useSendTransaction,Na as useSendUserOperation,rs as useSendWithSession,Ha as useSession,At as useSessionKeys,ii as useSignInWithEthereum,Re as useSignInWithX,Rt as useSignMessage,pi as useSimulateTransfer,yi as useSiwxAuthSession,ki as useSmartAccount,Qt as useSolanaAccount,Ti as useSolanaBalance,Ii as useSolanaTransaction,Pi as useSwitchChain,Bi as useTokenBalance,nt as useTokenList,ot as useTokenSearch,Ot as useTransactionSimulation,Ki as useTxHistory,pa as useTxMonitor,Vi as useUserOpStatus,tl as useValidateDestination,G as useViemClient,nl as useWallet,P as useWeb3,rl as useWeb3ErrorHandler,vr as validateDestination};
|
|
1
|
+
import{formatSol as xh,getLatestBlockhash as vh,getSignatureStatus as bh,getSolanaBalance as Ah,LAMPORTS_PER_SOL as Rh,PassphraseCancelledError as Th,PassphraseGate as Ih,parseSol as Uh,SolanaRpcError as Ph}from"@naculus/connect-core";import{useCallback as cn,useEffect as un,useRef as pn,useState as st}from"react";function Nr(e){return e?Object.keys(e).sort().map(t=>{let r=e[t];return`${t}=${typeof r=="object"&&r!==null?"[object]":String(r)}`}).join("&"):""}function dn(e,t){let{operation:r,chains:s,options:n}=e,[i,a]=st([]),[g,u]=st(!1),[c,h]=st(null),o=pn(!0),l=pn(0),d=`${r}|${(s??[]).join(",")}|${Nr(n)}`,f=cn(async()=>{if(!s||s.length===0){a([]);return}if(!t)return;let C=++l.current;u(!0),h(null);try{let y=await t(r,s,n);o.current&&C===l.current&&a(y)}catch(y){o.current&&C===l.current&&(h(y instanceof Error?y:new Error(String(y))),a([]))}finally{o.current&&C===l.current&&u(!1)}},[d,t]);un(()=>{f()},[f]),un(()=>(o.current=!0,()=>{o.current=!1}),[]);let m=cn(async()=>{await f()},[f]);return{comparisons:i,loading:g,error:c,refresh:m}}import{isValidAddress as Dr}from"@naculus/connect-core";import{useCallback as mn,useEffect as Mr,useRef as fn,useState as at}from"react";function gn(e){let[t,r]=at(!1),[s,n]=at(null),[i,a]=at(null),g=fn(!0),u=fn(!1);Mr(()=>(g.current=!0,()=>{g.current=!1}),[]);let c=mn(async(o,l,d)=>{if(!e)return a({code:"no_executor",message:"No executeRoute function provided"}),n(null),null;if(typeof l!="string"||l.trim()==="")return a({code:"invalid_recipient",message:"A recipient address is required"}),n(null),null;let f=o?.toChain?.split(":")[0];if(f&&!Dr(l,f))return a({code:"invalid_recipient",message:`"${l}" is not a valid ${f} address for the destination chain ${o.toChain}`}),n(null),null;if(u.current)return a({code:"execution_in_progress",message:"A route execution is already in progress"}),null;u.current=!0,r(!0),a(null),n(null);try{let m=await e(o,l,d);return g.current&&n(m),m}catch(m){let C=m;return g.current&&a({code:C.code??"execution_failed",message:C.message,details:C.details}),null}finally{u.current=!1,g.current&&r(!1)}},[e]),h=mn(()=>{n(null),a(null),r(!1)},[]);return{execute:c,executing:t,result:s,error:i,reset:h}}import{useCallback as it,useEffect as hn,useRef as yn,useState as lt}from"react";function Cn(e,t){let{fromChain:r,toChain:s,fromToken:n,toToken:i,amount:a,options:g}=e,[u,c]=lt([]),[h,o]=lt(!1),[l,d]=lt(null),f=yn(null),m=yn(!0),C=it(async()=>{let w=/^(?:0|[1-9][0-9]*)$/.test(a)&&BigInt(a)>0n;if(!r||!s||!n||!w){c([]);return}if(t){o(!0),d(null);try{let R=await t(r,s,n,a,g,i);m.current&&c(R)}catch(R){m.current&&(d(R instanceof Error?R:new Error(String(R))),c([]))}finally{m.current&&o(!1)}}},[r,s,n,i,a,g,t]);hn(()=>{if(f.current&&clearTimeout(f.current),!r||!s||!n||!a){c([]);return}return f.current=setTimeout(()=>{C()},300),()=>{f.current&&clearTimeout(f.current)}},[C,r,s,n,a]),hn(()=>(m.current=!0,()=>{m.current=!1}),[]);let y=it(async()=>{await C()},[C]),E=it(()=>{c([]),d(null),o(!1)},[]);return{quotes:u,loading:h,error:l,refresh:y,clear:E}}import{logger as ct,WalletError as q}from"@naculus/connect-core";import{eip6963Connector as V}from"@naculus/connector-evm-injected";import{PassphraseGate as Lr}from"@naculus/connect-core";import{createWalletConnectConnector as Br}from"@naculus/connector-walletconnect";var ut=null;function pt(e){let t=null,r=Br({projectId:e.projectId,metadata:e.metadata}),s=null,n=null,i=null,a=null,g=e.passphrasePrompt&&e.enableEmbedded&&!e.embeddedConfig?.encryptionPassphrase?new Lr:null;e.enableEmbedded&&(n=import("@naculus/connector-embedded").then(o=>{let l={...e.embeddedConfig};g&&(l.encryptionPassphrase=g.request),e.enablePasskeys&&l.encryptionPassphrase&&!l.prfUnlock&&(l.prfUnlock={async derive(f){a&&await a;let m=i;return m?.hasCredential()?m.derivePrfKey(f):null}}),s=o.createPocketConnector(l),t?._setEmbeddedConnector(s)}).catch(o=>{ct.warn("react/client","Embedded wallet connector not available:",o),s=null})),e.enablePasskeys&&(a=import("@naculus/connector-passkeys").then(o=>{i=o.createPasskeysConnector(),t?._setPasskeysConnector(i)}).catch(o=>{ct.warn("react/client","Passkeys connector not available:",o),i=null}));let u=null,c=null;e.enableSolana&&(c=import("@naculus/connector-solana").then(o=>{let l=o.solanaConnector;e.solanaDefaultChain&&"configure"in l&&l.configure({defaultChain:e.solanaDefaultChain}),u=l,typeof window<"u"&&"startDiscovery"in l&&l.startDiscovery(),t?._setSolanaConnector(u)}).catch(o=>{ct.warn("react/client","Solana connector not available:",o),u=null})),typeof window<"u"&&V.startDiscovery();let h={connector:r,get embeddedConnector(){return s},getEmbeddedConnector:async()=>(n&&await n,s),get passkeysConnector(){return i},passphraseGate:g,solanaRpcUrl:e.solanaRpcUrl??null,get solanaConnector(){return u},connect:()=>r.connect(),connectInjected:async o=>V.connect(o),connectEmbedded:async()=>{if(n&&await n,!s)throw new Error("Embedded wallet not enabled. Set enableEmbedded: true in config.");return s.connect()},connectPasskeys:async()=>{if(a&&await a,!i)throw new Error("Passkeys connector not enabled. Set enablePasskeys: true in config.");return i.connect()},startPairing:()=>r.startPairing(),completePairing:()=>r.completePairing(),cancelPairing:()=>r.cancelPairing?.(),signMessage:async(o,l)=>{if(o.id?.startsWith("eip6963-"))return V.signMessage(o,l);if(o.walletType==="passkeys"&&i)return i.signMessage(o,l);if(o.walletType==="embedded"){if(!s)throw new q("wallet_unavailable","Embedded wallet connector not available.");return s.signMessage(o,l)}if(o.walletType==="solana"){if(c&&await c,u)return u.signMessage(o,l);throw new q("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}return r.signMessage(o,l)},signTransaction:async(o,l)=>{if(o.id?.startsWith("eip6963-"))return V.signTransaction(o,l);if(o.walletType==="embedded"){if(!s)throw new q("wallet_unavailable","Embedded wallet connector not available.");return s.signTransaction(o,l)}if(o.walletType==="solana"){if(c&&await c,u)return u.signTransaction(o,l);throw new q("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}return r.signTransaction(o,l)},sendTransaction:async(o,l)=>{if(o.id?.startsWith("eip6963-"))return V.sendTransaction(o,l);if(o.walletType==="passkeys"&&i)return i.sendTransaction(o,l);if(o.walletType==="embedded"){if(!s)throw new q("wallet_unavailable","Embedded wallet connector not available.");return s.sendTransaction(o,l)}if(o.walletType==="solana"){if(c&&await c,u)return u.sendTransaction(o,l);throw new q("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}return r.sendTransaction(o,l)},onAccountsChanged:(o,l)=>{let d=()=>{};return o.id?.startsWith("eip6963-")?V.onAccountsChanged?.(o,l)??d:o.walletType==="embedded"?s?.onAccountsChanged?.(o,l)??d:o.walletType==="passkeys"?d:o.walletType==="solana"?u?.onAccountsChanged?.(o,l)??d:r.onAccountsChanged?.(o,l)??d},onChainChanged:(o,l)=>{let d=()=>{};return o.id?.startsWith("eip6963-")?V.onChainChanged?.(o,l)??d:o.walletType==="passkeys"||o.walletType==="embedded"?d:o.walletType==="solana"?u?.onChainChanged?.(o,l)??d:r.onChainChanged?.(o,l)??d},getCapabilities:o=>o.id?.startsWith("eip6963-")?V.getCapabilities?.(o):o.walletType==="passkeys"?i?.getCapabilities?.(o):o.walletType==="solana"?u?.getCapabilities?.(o):o.walletType==="embedded"?s?.getCapabilities?.(o):r.getCapabilities?.(o),sendCalls:async(o,l,d,f)=>{if(o.id?.startsWith("eip6963-"))return V.sendCalls(o,l,d,f);if(o.walletType==="passkeys"&&i)return i.sendCalls(o,l,d,f);if(o.walletType==="solana"){if(c&&await c,u)return u.sendCalls(o,l,d,f);throw new q("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}if(o.walletType==="embedded"){if(!s?.sendCalls)throw new q("method_not_allowed","Embedded wallet does not support sendCalls");return s.sendCalls(o,l,d,f)}if(!r.sendCalls)throw new q("method_not_allowed","sendCalls not supported by this connector");return r.sendCalls(o,l,d,f)},showCallsStatus:async(o,l)=>{if(o.id?.startsWith("eip6963-"))return V.showCallsStatus(o,l);if(o.walletType==="passkeys"||o.walletType==="embedded")throw new q("method_unsupported",`${o.walletType} wallets have no UI to display a call bundle.`);if(!r.showCallsStatus)throw new q("method_unsupported","This connector cannot display call status.");return r.showCallsStatus(o,l)},getCallsStatus:async(o,l)=>{if(o.id?.startsWith("eip6963-")&&V.getCallsStatus)return V.getCallsStatus(o,l);if(o.walletType==="passkeys"&&i?.getCallsStatus)return i.getCallsStatus(o,l);if(o.walletType==="embedded")throw new q("method_not_allowed","Embedded wallet does not support getCallsStatus");if(!r.getCallsStatus)throw new q("method_not_allowed","getCallsStatus not supported by this connector");return r.getCallsStatus(o,l)},reconnect:async o=>o.walletType==="eip6963"?V.reconnect(o):o.walletType==="embedded"?s?s.reconnect(o):o:o.walletType==="solana"?o:r.reconnect(o),disconnect:async o=>{if(o.id?.startsWith("eip6963-")||o.walletType==="eip6963")return V.disconnect(o);if(o.walletType==="embedded"&&s)return s.disconnect();if(o.walletType==="passkeys"&&i)return i.disconnect(o);if(o.walletType==="solana"){if(c&&await c,u)return u.disconnect(o);throw new q("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}return r.disconnect(o)},getAllConnectors:()=>{let o=[r];return s&&o.push(s),i&&o.push(i),u&&o.push(u),o},_setEmbeddedConnector:o=>{s=o},_setPasskeysConnector:o=>{i=o},_setSolanaConnector:o=>{u=o}};return t=h,ut=h,h}function dt(){return ut}function Hr(){ut=null}import{isEvmAddress as xn,parseCaip10 as po}from"@naculus/connect-core";import{useMemo as mo}from"react";import{createConnectorManager as Zr,createSessionManager as eo,LocalStorageSessionStorage as to,logger as ne,WalletError as no}from"@naculus/connect-core";import{eip6963Connector as De}from"@naculus/connector-evm-injected";import{createContext as ro,useCallback as K,useContext as oo,useEffect as ge,useMemo as he,useReducer as so,useRef as En}from"react";import{logger as Fr}from"@naculus/connect-core";import{issueNonce as Kr,parseSiwxMessage as $r}from"@naculus/siwx";function ue(e,t){let r=t.split(":",1)[0],n=(e.namespaces[r]?.accounts??[]).filter(i=>i.startsWith(`${r}:`)).map(i=>({namespace:r,caip10:i}))[0];if(n)return{...n,address:n.caip10.split(":").pop()??n.caip10}}function qr(e){return e.namespaces.eip155?.chains?.[0]??e.namespaces.solana?.chains?.[0]??e.namespaces.xrpl?.chains?.[0]??"eip155:1"}async function Sn(e){let{session:t,siwx:r,signMessage:s}=e;if(!r||!t)return{kind:"skipped"};try{let n=qr(t),i=ue(t,n);if(!i)throw new Error("No account found in session");let{address:a}=i,g=await r.createMessage({address:a,chainId:n}),u=$r(g);if(!u?.nonce)throw new Error("SIWx message must contain a nonce");await Kr(u.nonce);let c=await s(t,{message:g,address:a,chainId:n});return await r.handleSignComplete?.({message:g,signature:c}),{kind:"authenticated",address:a,chainId:n}}catch(n){let i=n instanceof Error?n:new Error("Wallet authentication failed");return Fr.error("appkit/core","SIWx authentication failed:",n),{kind:"failed",error:i,fatal:r.required!==!1}}}import{initialWeb3State as ao,web3Reducer as io,withRetry as lo,withTimeout as kn}from"@naculus/connect-appkit-core";import{resolveChain as Vr}from"@naculus/connect-appkit-core";import{CHAINS as Ne,DEFAULT_RPC_URLS as zr,eip155Reference as jr,getRpcUrl as Gr}from"@naculus/connect-core";var Qr=[{caip2:"eip155:5",name:"Goerli",rpcUrl:"https://goerli.blockpi.network/v1/rpc/public",explorerUrl:"https://goerli.etherscan.io",token:"ETH"},{caip2:"eip155:80001",name:"Mumbai",rpcUrl:"https://rpc-mumbai.maticvigil.com",explorerUrl:"https://mumbai.polygonscan.com",token:"MATIC"},{caip2:"eip155:421613",name:"Arbitrum Goerli",rpcUrl:"https://goerli-rollup.arbitrum.io/rpc",explorerUrl:"https://goerli.arbiscan.io",token:"ETH"},{caip2:"eip155:420",name:"Optimism Goerli",rpcUrl:"https://goerli.optimism.io",explorerUrl:"https://goerli-optimism.etherscan.io",token:"ETH"}];function Xr(e){let t=Ne[e];if(!t||!t.explorerUrl)return null;let r=t.caip2Id;return{caip2:r,name:t.name,rpcUrl:Gr(r,zr[r]??""),explorerUrl:t.explorerUrl,token:t.nativeCurrency.symbol}}function Yr(){if(!Ne)return[];let e=[],t=Object.keys(Ne).map(Number).sort((r,s)=>r-s);for(let r of t){let s=Xr(r);s&&e.push(s)}for(let r of Qr){let s=jr(r.caip2);(s===null||!Ne[s])&&e.push(r)}return e}var wn=Yr();function Jr(e,t){return Vr(e,t)??void 0}function mt(){return[...wn]}import{jsx as uo}from"react/jsx-runtime";var ft=ro(null);function co({children:e,config:t,autoConnect:r=!0}){let[s,n]=so(io,ao),i=he(()=>t.chains??mt(),[t.chains]),a=t.connectionTimeout??3e4,g=t.maxRetries??2,u=he(()=>new to(t.storageKey??"naculus_web3_session",t.encryptionKey),[t.storageKey,t.encryptionKey]),c=he(()=>pt({projectId:t.projectId,metadata:t.metadata,enableEmbedded:t.enableEmbedded,embeddedConfig:t.embeddedConfig,enablePasskeys:t.enablePasskeys,enableSolana:t.enableSolana,solanaDefaultChain:t.solanaDefaultChain}),[t.projectId,t.metadata,t.enableEmbedded,t.embeddedConfig,t.enablePasskeys,t.enableSolana,t.solanaDefaultChain]),h=En(null),o=En(null),l=he(()=>{let p=Zr();for(let N of[De,...c.getAllConnectors()])p.register(N.id,N);let S={},x={};for(let N of i){let M=N.caip2;N.rpcUrl&&(S[M]=N.rpcUrl),N.token&&(x[M]={name:N.name,symbol:N.token,decimals:18})}let W=eo(p,{autoRefreshFeeOnSwitch:t.autoRefreshFeeOnSwitch??!0,defaultRpcUrls:S,defaultCurrencies:x,encryptionKey:t.encryptionKey});return h.current=W,W},[c,i,t.autoRefreshFeeOnSwitch,t.encryptionKey]);ge(()=>{let p=W=>{let{walletSession:N}=W.bundle;n({type:"SET_SESSION",payload:N});let M=[];Object.values(N.namespaces).forEach(F=>{M.push(...F.accounts)}),n({type:"SET_ACCOUNTS",payload:M}),n({type:"SET_CHAIN",payload:W.bundle.activeChainId}),n({type:"SET_STATUS",payload:"connected"})},S=()=>{n({type:"RESET"})},x=W=>{n({type:"SET_CHAIN",payload:W.newChainId})};return l.on("sessionConnected",p),l.on("sessionDisconnected",S),l.on("chainChanged",x),()=>{l.off("sessionConnected",p),l.off("sessionDisconnected",S),l.off("chainChanged",x)}},[l]),ge(()=>{let p=()=>{u.clear(),n({type:"RESET"})};c.connector.onSessionExpiry(p)},[c,u]);let d=K(()=>{for(let p of[De,...c.getAllConnectors()])l.registerConnector(p)},[c,l]),f=K(async p=>{d();let S=[De,...c.getAllConnectors()].find(W=>W.id===p.walletType||W.kind===p.walletType);S&&!p.connectorId&&(p.connectorId=S.id);let x=p.namespaces.eip155?.chains?.[0]??p.namespaces.solana?.chains?.[0]??p.namespaces.xrpl?.chains?.[0];x&&await l.attach(p,x)},[c,l,d]),m=K(p=>{if(n({type:"SET_SESSION",payload:p}),p){let S=[];Object.values(p.namespaces).forEach(M=>{S.push(...M.accounts)}),n({type:"SET_ACCOUNTS",payload:S});let x=p.namespaces.eip155?.chains?.[0],W=p.namespaces.solana?.chains?.[0],N=p.namespaces.xrpl?.chains?.[0];n({type:"SET_CHAIN",payload:x??W??N??null})}else n({type:"SET_ACCOUNTS",payload:[]}),n({type:"SET_CHAIN",payload:null})},[]);ge(()=>{let p=s.session,S=c;return!p||!S?.onAccountsChanged?void 0:S.onAccountsChanged(p,W=>{if(W.length===0){u.clear().finally(()=>n({type:"RESET"}));return}m(p),u.save(p)})},[s.session,c,u,m]),ge(()=>{let p=s.session,S=c;if(!(!p||!S?.onChainChanged))return S.onChainChanged(p,x=>{m(p),u.save(p);let W=l.syncExternalChain;if(!W)return;let N=W.call(l,x).catch(M=>{ne.warn("react/provider","External chain sync error:",M)});o.current=N,N.finally(()=>{o.current===N&&(o.current=null)})})},[s.session,c,u,m,l]);let C=K(async p=>{if(!t.siwx||!p)return!0;n({type:"SET_STATUS",payload:"authenticating"});let S=await Sn({session:p,siwx:t.siwx,signMessage:(x,W)=>c.signMessage(x,W)});return S.kind==="failed"&&S.fatal?(await u.clear(),n({type:"RESET"}),n({type:"SET_ERROR",payload:S.error}),!1):!0},[t.siwx,c,u]),y=K(async()=>{n({type:"SET_STATUS",payload:"connecting"}),n({type:"SET_ERROR",payload:null});try{let p=await kn(c.connect(),a,"Wallet connect");await u.save(p),m(p);try{await f(p)}catch(S){ne.warn("react/provider","SessionManager sync error:",S)}if(!await C(p))return;n({type:"SET_STATUS",payload:"connected"})}catch(p){let S=p instanceof Error?p.message:"Connection failed";n({type:"SET_ERROR",payload:p instanceof Error?p:new Error(S)}),n({type:"SET_STATUS",payload:"disconnected"})}},[c,u,m,a,C,f]),E=K(async()=>{n({type:"SET_STATUS",payload:"connecting"}),n({type:"SET_ERROR",payload:null});try{let p=await c.connectEmbedded();if(await u.save(p),m(p),await f(p),!await C(p))return;n({type:"SET_STATUS",payload:"connected"})}catch(p){let S=p instanceof Error?p.message:"Embedded wallet connection failed";n({type:"SET_ERROR",payload:p instanceof Error?p:new Error(S)}),n({type:"SET_STATUS",payload:"disconnected"})}},[c,u,m,C,f]),w=K(async()=>{n({type:"SET_STATUS",payload:"connecting"}),n({type:"SET_ERROR",payload:null});try{let p=await c.connectPasskeys();if(await u.save(p),m(p),await f(p),!await C(p))return;n({type:"SET_STATUS",payload:"connected"})}catch(p){let S=p instanceof Error?p.message:"Passkeys connection failed";n({type:"SET_ERROR",payload:p instanceof Error?p:new Error(S)}),n({type:"SET_STATUS",payload:"disconnected"})}},[c,u,m,C,f]),R=K(async()=>{if(!s.session){n({type:"RESET"});return}try{await c.disconnect(s.session)}catch(p){ne.error("react/provider","Disconnect error:",p)}try{let p=h.current;p&&await p.disconnect()}catch(p){ne.warn("react/provider","SessionManager disconnect error:",p)}await u.clear(),n({type:"RESET"})},[c,s.session,u]),v=K(async p=>{n({type:"SET_STATUS",payload:"connecting"}),n({type:"SET_ERROR",payload:null});try{let S=await kn(c.connectInjected(p),a,"Injected wallet connect");await u.save(S),m(S);try{await f(S)}catch(x){ne.warn("react/provider","SessionManager sync error:",x)}if(!await C(S))return;n({type:"SET_STATUS",payload:"connected"})}catch(S){let x=S instanceof Error?S.message:"Connection failed";n({type:"SET_ERROR",payload:S instanceof Error?S:new Error(x)}),n({type:"SET_STATUS",payload:"disconnected"})}},[c,u,m,a,C,f]),I=K(async()=>c.startPairing(),[c]),A=K(()=>{c.cancelPairing?.()},[c]),U=K(async()=>{let p=await c.completePairing();return await u.save(p),m(p),await f(p),await C(p)&&n({type:"SET_STATUS",payload:"connected"}),p},[c,u,m,C,f]),k=K(async p=>{let S=t.siwx;if(!S||S.required===!1)return!0;try{if(await S.hasValidSession?.())return!0}catch(x){ne.warn("react/provider","siwx.hasValidSession failed",x)}return C(p)},[t.siwx,C]),T=K(async()=>{let p=await u.load();if(!p){n({type:"SET_STATUS",payload:"disconnected"});return}n({type:"SET_STATUS",payload:"reconnecting"});try{let S=await lo(()=>c.reconnect(p),{maxRetries:g,baseDelay:1e3,label:"reconnect"});m(S);try{let x=h.current;x&&(d(),await x.restoreFromPersistence())}catch(x){ne.warn("react/provider","SessionManager restore error:",x)}if(!await k(S))return;n({type:"SET_STATUS",payload:"connected"})}catch(S){ne.error("react/provider","Reconnect error:",S),await u.clear(),n({type:"SET_STATUS",payload:"disconnected"}),n({type:"SET_SESSION",payload:null})}},[c,u,m,g,d,k]),b=K(async p=>{o.current&&await o.current;let S=h.current;if(S?.getActiveBundle()){await S.switchChain(p),m(s.session);return}if(!s.session)throw new Error("No active session");try{s.session.walletType==="eip6963"||s.session.id?.startsWith("eip6963-")?await De.switchChain(s.session,p):s.session.walletType==="embedded"&&c.embeddedConnector?await c.embeddedConnector.switchChain?.(s.session,p):s.session.walletType==="passkeys"&&c.passkeysConnector?await c.passkeysConnector.switchChain?.(s.session,p):s.session.walletType==="solana"&&c.solanaConnector?await c.solanaConnector.switchChain?.(s.session,p):await c.connector.switchChain(s.session,p),m(s.session)}catch(x){throw new no("chain_unsupported","Failed to switch chain",x)}},[c,s.session,m]);ge(()=>{r&&T()},[r,T]);let O=K(()=>{n({type:"SET_ERROR",payload:null})},[]),_=he(()=>({...s,connect:y,connectEmbedded:E,connectPasskeys:w,disconnect:R,reconnect:T,switchChain:b,startPairing:I,completePairing:U,cancelPairing:A,connectInjected:v,clearError:O,isConnected:s.status==="connected",chains:i,client:c,sessionManager:l}),[s,y,E,w,R,T,b,I,U,v,O,i,c,l]);return uo(ft.Provider,{value:_,children:e})}function P(){let e=oo(ft);if(!e)throw new Error("useWeb3 must be used within a Web3ConnectProvider");return e}function H(){let{accounts:e,isConnected:t}=P(),r=mo(()=>!t||e.length===0?null:e.map(n=>{let i=po(n);return i?{address:n,namespace:i.namespace,isEVM:i.namespace==="eip155"&&xn(i.address)}:{address:n,namespace:null,isEVM:xn(n)}}),[e,t]),s=r?.find(n=>n.isEVM)?.address??null;return{accounts:r,evmAccount:s,primaryAccount:e[0]??null,isConnected:t,count:e.length}}import{chainNumber as fo,resolveChain as go,toViemChain as ho}from"@naculus/connect-appkit-core";import{useState as ye,useEffect as gt,useCallback as yo,useMemo as Ce,useRef as Co}from"react";import{createPublicClient as So,http as wo,formatEther as Eo}from"viem";import{getNativeTokenPriceUsd as ko}from"@naculus/connect-core";function xo(e){let{evmAccount:t,isConnected:r}=H(),{chainId:s,chains:n}=P(),[i,a]=ye(null),[g,u]=ye(!1),[c,h]=ye(null),[o,l]=ye(null),d=e?.refreshInterval,f=Co(null),m=Ce(()=>go(n,s),[s,n]),C=m?fo(m):null,y=Ce(()=>m?ho(m,C):null,[m,C]),E=Ce(()=>m?.token??null,[m]),[w,R]=ye(null);gt(()=>{if(!y||!m?.rpcUrl){R(null);return}let U=So({transport:wo(m.rpcUrl),chain:y});return R(U),()=>{}},[m]);let v=yo(async()=>{if(!t||!w){a(null);return}u(!0),h(null);try{let k=t.includes(":")?t.split(":").pop():t,[T,b]=await Promise.all([w.getBalance({address:k}),s?ko(s,m?.rpcUrl).catch(()=>null):Promise.resolve(null)]);a(T.toString()),l(b)}catch(U){h(U instanceof Error?U:new Error("Failed to fetch balance")),a(null),l(null)}finally{u(!1)}},[t,w,s,m?.rpcUrl]);gt(()=>{r&&t&&v()},[r,t,v]),gt(()=>(d&&d>0&&r&&t&&(f.current=setInterval(v,d)),()=>{f.current&&(clearInterval(f.current),f.current=null)}),[d,r,t,v]);let I=Ce(()=>{if(i===null)return null;try{return Eo(BigInt(i))}catch{return null}},[i]),A=Ce(()=>{if(o===null||I===null)return null;let U=parseFloat(I);if(isNaN(U))return null;let k=U*o;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(k)},[o,I]);return{balance:i,formatted:I,symbol:E,usdPrice:o,usdValue:A,isLoading:g,error:c,refetch:v,chain:m}}import{atomicSupportFor as vo,normalizeCapabilities as bo,selectChainCapabilities as Ao}from"@naculus/connect-appkit-core";import{useCallback as Ro,useEffect as To,useRef as Io,useState as ht}from"react";function D(e){return e??dt()}function yt(){let{client:e,session:t,chainId:r}=P(),[s,n]=ht(null),[i,a]=ht(!1),[g,u]=ht(null),c=Io(0),h=Ro(async()=>{let o=++c.current,l=D(e);if(!l?.getCapabilities||!t){n(null),a(!1),u(null);return}a(!0),u(null);try{let d=await l.getCapabilities(t);if(o!==c.current)return;n(bo(d))}catch(d){if(o!==c.current)return;n(null),u(d instanceof Error?d:new Error("Capability query failed"))}finally{o===c.current&&a(!1)}},[e,t]);return To(()=>{h()},[h]),{capabilities:s,current:Ao(s,r),atomic:vo(s,r),isFetching:i,error:g,refetch:h}}import{useMemo as Ct}from"react";import{chainsForNamespace as Uo,describeChain as Po,resolveChain as Wo}from"@naculus/connect-appkit-core";function z(){let{chainId:e,session:t,switchChain:r,chains:s}=P(),n=Ct(()=>Wo(s,e),[s,e]),i=Ct(()=>t?Po(s,e):null,[s,e,t]),a=Ct(()=>Uo(s,e),[s,e]);return{chainId:e,currentChain:n,chainInfo:i,availableChains:a,chains:a,isEvm:e?.startsWith("eip155:")??!1,switchChain:r}}import{useCallback as _o,useState as vn}from"react";import{WalletError as Oo}from"@naculus/connect-core";function No(){let{connect:e,status:t}=P(),[r,s]=vn(!1),[n,i]=vn(null);return{connect:_o(async()=>{s(!0),i(null);try{await e()}catch(g){let u=g instanceof Error?g.message:"Connection failed";i(g instanceof Oo?g:new Error(u))}finally{s(!1)}},[e]),isConnecting:r||t==="connecting",error:n}}import{readDelegation as Ho,UNKNOWN_DELEGATION as wt}from"@naculus/connect-core";import{useCallback as Fo,useEffect as Ko,useRef as $o,useState as Et}from"react";import{chainNumber as Do,toViemChain as Mo}from"@naculus/connect-appkit-core";import{useMemo as St}from"react";import{createPublicClient as Lo,http as bn,createWalletClient as Bo}from"viem";function G(){let{evmAccount:e,isConnected:t}=H(),{currentChain:r,chains:s}=z(),n=r?Do(r):null,i=St(()=>r?Mo(r,n):null,[r,n]),a=St(()=>i?Lo({transport:bn(i.rpcUrls.default.http[0]),chain:i}):null,[r,i]),g=St(()=>{if(!t||!e||!i)return null;let u=e.includes(":")?e.split(":").pop():e;return Bo({transport:bn(i.rpcUrls.default.http[0]),chain:i,account:u})},[t,e,r,i]);return{publicClient:a,walletClient:g,chains:s}}function Se(){let{publicClient:e}=G(),{evmAccount:t}=H(),[r,s]=Et(wt),[n,i]=Et(!1),[a,g]=Et(null),u=$o(0),c=t?.includes(":")?t.split(":").pop():t,h=Fo(async()=>{let o=++u.current;if(!e||!c){s(wt),i(!1),g(null);return}i(!0),g(null);try{let l=await e.getCode({address:c});if(o!==u.current)return;s(Ho(l??"0x"))}catch(l){if(o!==u.current)return;s(wt),g(l instanceof Error?l:new Error("Code read failed"))}finally{o===u.current&&i(!1)}},[e,c]);return Ko(()=>{h()},[h]),{...r,isFetching:n,error:a,refetch:h}}import{WalletError as $}from"@naculus/connect-core";import{useCallback as se,useEffect as is,useState as Be}from"react";import{recoverMessageAddress as He}from"viem";import{planExecution as jo,WalletError as Go}from"@naculus/connect-core";import{useCallback as An,useState as xt}from"react";import{chooseExecutionStrategy as Vo,getAccountCapabilities as zo,WalletError as re}from"@naculus/connect-core";import{useCallback as Le,useState as we}from"react";import{WalletError as qo}from"@naculus/connect-core";function Me(e){let t=typeof e=="string"?e:e&&typeof e=="object"&&"hash"in e?e.hash:void 0;if(typeof t=="string"&&/^0x[0-9a-fA-F]{64}$/.test(t))return t;throw new qo("tx_failed","Wallet did not return a valid 32-byte transaction hash")}function kt(){let{session:e,chainId:t,client:r}=P(),[s,n]=we("idle"),[i,a]=we(null),[g,u]=we(null),[c,h]=we(null),[o,l]=we(null),d=Le(async(y,E)=>{if(!e){n("failed");let w=new re("wallet_unavailable","No active session");throw a(w),w}if(y.length===0){n("failed");let w=new re("invalid_input","At least one call is required");throw a(w),w}n("awaiting_approval"),a(null),u(null);try{let w=D(r);if(!w)throw new re("wallet_unavailable","Client not initialized");let R=E?.chainId??t??void 0,v=E?.strategy??Vo(await zo(w,e,R),y.length);if(l(v),v==="atomic-batch"){let A=await w.sendCalls(e,y,R,{atomicRequired:!0,...E?.paymasterService?{paymasterService:E.paymasterService}:{}});return n("submitted"),u(A),A}let I="";for(let A=0;A<y.length;A++){let U=y[A];try{I=Me(await w.sendTransaction(e,{transaction:{to:U.to,data:U.data,value:U.value},chainId:R}))}catch(k){throw new re("tx_failed",`Call ${A+1} of ${y.length} failed after ${A} already landed (sent sequentially \u2014 this wallet cannot batch atomically): ${k instanceof Error?k.message:String(k)}`)}}return n("submitted"),u(I),I}catch(w){n("failed");let R=w instanceof Error?w.message:"sendCalls failed";throw a(w instanceof Error?w:new Error(R)),w}},[e,t,r]),f=Le(async y=>{if(!e)throw new re("wallet_unavailable","No active session");let E=y??g;if(!E)throw new re("invalid_input","No bundle hash available");if(!y&&o==="sequential")throw new re("invalid_input","Calls were sent sequentially, so there is no bundle to query. Track the returned transaction hash instead.");let w=D(r);if(!w)throw new re("wallet_unavailable","Client not initialized");let R=await w.getCallsStatus(e,E);return h(R),R},[e,g,r,o]),m=Le(async y=>{if(!e)return!1;let E=y??g;if(!E||!y&&o==="sequential")return!1;let w=D(r);if(!w?.showCallsStatus)return!1;try{return await w.showCallsStatus(e,E),!0}catch{return!1}},[e,g,r,o]),C=Le(()=>{n("idle"),a(null),u(null),h(null),l(null)},[]);return{sendCalls:d,getCallsStatus:f,showCallsStatus:m,status:s,error:i,batchHash:g,callsStatus:c,execution:o,reset:C,isSending:s==="awaiting_approval"}}function vt(e={}){let{current:t,atomic:r}=yt(),{delegated:s,delegate:n}=Se(),{sendCalls:i}=kt(),[a,g]=xt(!1),[u,c]=xt(null),[h,o]=xt(null),l=e.atomicity??"preferred",d=e.sponsorship??"any",f=e.paymasterService,m=e.userOperation,C=e.userOperationSponsored??!1,y=!!(t?.raw?.paymasterService?.supported&&f),E=An((R,v=l)=>{let I=jo({atomicBatch:r==="supported",discovered:r!=="unknown",sponsoredTransactions:!1,...t?.maxBatchSize===void 0?{}:{maxBatchSize:t.maxBatchSize}},R,{atomicity:v,sponsorship:d}),A=d==="required"&&!C;if(I.strategy==="atomic-batch"&&!A)return{...I,reason:I.reason+(y?" A paymaster service will be requested, but the wallet's final fee payer must be checked after execution.":""),route:"wallet-batch"};let U=s&&r!=="supported"?` This account does delegate to ${n} under EIP-7702, so it is capable of batching even though the wallet has not offered to.`:"",k=v!=="any"&&!I.atomic||d==="required";return m&&k&&!A?{strategy:"atomic-batch",atomic:!0,sponsored:C,reason:d==="required"&&!I.sponsored?"The wallet batch is not configured for sponsored gas, so the calls are executed through the configured sponsored UserOperation route.":"This wallet cannot batch, so the calls are executed as a single UserOperation through the smart account, which lands as one transaction.",route:"user-operation"}:A?{strategy:"refuse",atomic:I.atomic,sponsored:!1,reason:"Sponsored gas was required, but there is no executable sponsored route: no paymaster is configured for a wallet batch, and capability advertising alone cannot pay for a sequential transaction.",route:null}:I.strategy==="refuse"?{...I,reason:I.reason+U,route:null}:{...I,reason:I.reason+U,route:"sequential"}},[r,t,f,y,m,C,l,d,s,n]),w=An(async(R,v=l)=>{g(!0),c(null);try{let I=E(R.length,v);if(I.route===null)throw new Go("method_not_allowed",I.reason);return o(I.route),I.route==="user-operation"?await m(R):await i(R,{strategy:I.route==="wallet-batch"?"atomic-batch":"sequential",...I.route==="wallet-batch"&&y?{paymasterService:f}:{}})}catch(I){let A=I instanceof Error?I:new Error("Execution failed");throw c(A),A}finally{g(!1)}},[E,i,m,l,f,y]);return{preview:E,execute:w,isExecuting:a,error:u,lastRoute:h,reset:()=>{c(null),o(null)}}}import{DEFAULT_SESSION_KEY_CONFIG as Qo,LocalStorageAdapter as Xo,MemoryStorageAdapter as Yo,SessionKeyManager as Jo,WalletError as Rn}from"@naculus/connect-core";import{useCallback as J,useEffect as Zo,useRef as es,useState as Y}from"react";var Ee=null,bt=null;function ts(e){return e?JSON.stringify({defaultMaxTotalValue:e.defaultMaxTotalValue?.toString(),defaultMaxTxCount:e.defaultMaxTxCount,defaultExpiryMs:e.defaultExpiryMs,requireAllowedContracts:e.requireAllowedContracts,forbiddenMethods:e.forbiddenMethods,pbkdf2Iterations:e.pbkdf2Iterations,unsafeAllowWeakKdf:e.unsafeAllowWeakKdf,storagePrefix:e.storagePrefix,encryptionKey:e.encryptionKey,encryptionSalt:e.encryptionSalt}):""}function pe(e){let t=ts(e);if(!Ee){let r=e?.storagePrefix??Qo.storagePrefix;return Ee=new Jo(e,typeof window<"u"?new Xo(`${r}:`):new Yo),bt=t,Ee}if(t!==""&&t!==bt)throw new Rn("invalid_input","useSessionKeys is backed by a process-wide SessionKeyManager, and a different spending configuration was supplied after it was created. The second configuration would be ignored, so the caller would be operating under limits it did not set. Use one configuration per application, or construct a SessionKeyManager directly.");return Ee}function At(e){let{session:t}=P(),[r,s]=Y([]),[n,i]=Y(!1),[a,g]=Y(null),u=es(!0),c=J(()=>g(null),[]),h=pe(e),o=h.isStorageAvailable(),l=J(async()=>{if(!t){s([]);return}i(!0),g(null);try{let f=await h.listSessions();u.current&&s(f)}catch(f){u.current&&g(f instanceof Error?f:new Error("Failed to load session keys"))}finally{u.current&&i(!1)}},[t,h]);Zo(()=>(u.current=!0,l(),()=>{u.current=!1}),[l]);let d=r.filter(f=>f.status==="active");return{sessions:r,activeSessions:d,loading:n,error:a,refresh:l,clearError:c,storageAvailable:o}}function ns(e){let{session:t}=P(),[r,s]=Y(null),[n,i]=Y(!1),[a,g]=Y(null),u=J(()=>g(null),[]),c=pe(e);return{createSessionKey:J(async(o,l)=>{if(!t)throw new Rn("wallet_unavailable","No active wallet session");i(!0),g(null);try{let d=l??void 0,f=await c.createSessionKey(o,d);return s(f),f}catch(d){let f=d instanceof Error?d:new Error("Failed to create session key");throw g(f),f}finally{i(!1)}},[t,c]),lastCreated:r,isCreating:n,error:a,clearError:u}}function rs(e){let[t,r]=Y(!1),[s,n]=Y(null),i=J(()=>n(null),[]),a=pe(e);return{revokeSession:J(async u=>{r(!0),n(null);try{await a.revokeSession(u)}catch(c){let h=c instanceof Error?c:new Error("Failed to revoke session key");throw n(h),h}finally{r(!1)}},[a]),isRevoking:t,error:s,clearError:i}}function os(e){let[t,r]=Y(!1),[s,n]=Y(null),i=J(()=>n(null),[]),a=pe(e),g=J(async(c,h,o)=>{r(!0),n(null);try{return await a.signWithSessionKey(c,h,o)}catch(l){let d=l instanceof Error?l:new Error("Failed to sign with session key");throw n(d),d}finally{r(!1)}},[a]),u=J(async(c,h)=>{r(!0),n(null);try{return await a.checkSessionScope(c,h)}catch(o){let l=o instanceof Error?o:new Error("Failed to check session scope");throw n(l),l}finally{r(!1)}},[a]);return{signWithSession:g,checkScope:u,isBusy:t,error:s,clearError:i}}function ss(){Ee=null,bt=null}import{useState as Tn,useCallback as as}from"react";import{WalletError as Rt}from"@naculus/connect-core";function Tt(){let{session:e,chainId:t,client:r}=P(),[s,n]=Tn(!1),[i,a]=Tn(null);return{signMessage:as(async u=>{if(!e){let h=new Rt("wallet_unavailable","No active session");throw a(h),h}let c=e.namespaces.eip155?.accounts[0]??Object.values(e.namespaces)[0]?.accounts[0];if(!c){let h=new Rt("wallet_unavailable","No account found");throw a(h),h}n(!0),a(null);try{let h=D(r);if(!h)throw new Rt("wallet_unavailable","Client not initialized");return await h.signMessage(e,{message:u,address:c,chainId:t??void 0})}catch(h){let o=h instanceof Error?h.message:"Signing failed",l=h instanceof Error?h:new Error(o);throw a(l),l}finally{n(!1)}},[e,t,r]),isSigning:s,error:i}}function ls(e){let t=e?.includes(":")?e.split(":").pop():e;return t&&/^0x[0-9a-fA-F]{40}$/.test(t)?t:null}function In(e){return e?[...e].map(t=>t.toLowerCase()).sort():null}function cs(e,t){let r=e.to===void 0||e.to.toLowerCase()===t.to?.toLowerCase(),s=e.data===void 0||e.data.toLowerCase()===t.data?.toLowerCase();return r&&s&&((i,a)=>{if(i===void 0)return!0;if(a===void 0)return!1;try{return BigInt(i)===BigInt(a)}catch{return!1}})(e.value,t.value)&&(e.chainId===void 0||e.chainId===t.chainId)}function ke(e,t){let r=e.scope.tokenAllowances?Object.entries(e.scope.tokenAllowances).map(([n,i])=>[n.toLowerCase(),i.toString()]).sort(([n],[i])=>n.localeCompare(i)):null,s={version:1,origin:t,signer:e.signerAddress.toLowerCase(),sessionId:e.id,sessionPublicKey:e.publicKey.toLowerCase(),expiresAt:new Date(e.expiresAt).toISOString(),mode:e.scope.mode,limits:{maxTotalGas:e.scope.maxTotalGas?.toString()??null,maxGasPerTx:e.scope.maxGasPerTx?.toString()??null,maxTotalValue:e.scope.maxTotalValue?.toString()??null,maxValuePerTx:e.scope.maxValuePerTx?.toString()??null,maxTxCount:e.scope.maxTxCount??null},allowedContracts:In(e.scope.allowedContracts),allowedMethods:In(e.scope.allowedMethods),allowedChainIds:e.scope.allowedChainIds?[...e.scope.allowedChainIds].sort((n,i)=>n-i):null,tokenAllowances:r};return`Naculus Session Policy v1
|
|
2
|
+
${JSON.stringify(s)}`}function us(e={}){let{evmAccount:t}=H(),r=ls(t),s=Se(),n=vt(e.execution),{signMessage:i}=Tt(),a=At(e.managerConfig),g=pe(e.managerConfig),[u,c]=Be(!1),[h,o]=Be(null),[l,d]=Be(()=>new Set),[f,m]=Be(!1),C=e.origin??(typeof window<"u"?window.location.origin:"unknown"),y=se(async k=>{if(k.status!=="active"||!k.authorized||k.scope.mode!=="offchain")return!1;let T=ke(k,C);return g.verifyOffchainAuthorization(k.id,T,async({message:b,signature:O,signerAddress:_})=>(await He({message:b,signature:O})).toLowerCase()===_.toLowerCase())},[g,C]);is(()=>{let k=!1,T=a.sessions.filter(b=>b.status==="active"&&b.authorized&&b.scope.mode==="offchain");return T.length===0?(d(new Set),m(!1),()=>{k=!0}):(m(!0),Promise.all(T.map(async b=>[b.id,await y(b)])).then(b=>{k||d(new Set(b.filter(([,O])=>O).map(([O])=>O)))}).catch(b=>{k||(d(new Set),o(b instanceof Error?b:new Error("Policy verification failed")))}).finally(()=>{k||m(!1)}),()=>{k=!0})},[a.sessions,y]);let E=se(()=>{o(null),a.clearError()},[a]),w=se(async k=>{if(!r){let b=new $("wallet_unavailable","No active EVM account");throw o(b),b}if(k.mode&&k.mode!=="offchain"){let b=new $("method_not_allowed","This flow creates signed off-chain policies only. EIP-7702 and AA-module policies require a configured on-chain execution adapter.");throw o(b),b}if(!e.managerConfig?.encryptionKey){let b=new $("method_not_allowed","Persistent delegation policies require a host-provided encryptionKey. The deterministic compatibility fallback is not a production key boundary.");throw o(b),b}if(!a.storageAvailable){let b=new $("storage_unavailable","Persistent delegation policy storage is unavailable in this browser");throw o(b),b}c(!0),o(null);let T=null;try{T=await g.createSessionKey({...k,mode:"offchain"},r);let b=ke(T,C),O=await i(b);if(!/^0x[0-9a-fA-F]{130}$/.test(O))throw new $("invalid_input","Wallet did not return a valid 65-byte EVM policy signature");if((await He({message:b,signature:O})).toLowerCase()!==r.toLowerCase())throw new $("invalid_input","Policy signature does not recover to the connected EVM account");await g.setAuthorization(T.id,{signerAddress:r,type:"offchain",rawSignature:O,message:b});let p=(await g.listSessions()).find(S=>S.id===T?.id);if(!p?.authorized)throw new $("invalid_input","Policy authorization was not persisted");if(!await y(p))throw new $("invalid_input","Persisted policy signature did not verify against its stored scope and origin");return await a.refresh(),p}catch(b){if(T)try{await g.revokeSession(T.id)}catch{}let O=b instanceof Error?b:new Error("Policy creation failed");throw o(O),O}finally{c(!1)}},[g,e.managerConfig?.encryptionKey,C,a,i,r,y]),R=se(async k=>{c(!0),o(null);try{await g.revokeSession(k),await a.refresh()}catch(T){let b=T instanceof Error?T:new Error("Policy revocation failed");throw o(b),b}finally{c(!1)}},[g,a]),v=se(async(k,T,b=1,O="preferred")=>{let _=(await g.listSessions()).find(Oe=>Oe.id===k)??null,p=await g.checkSessionScope(k,T),S=n.preview(b,O),x=_?await y(_):!1,W=!!(_&&r&&_.signerAddress.toLowerCase()===r.toLowerCase()),N=null;if(_&&e.adapter&&x&&W&&p.valid)try{N=await e.adapter.check({policy:_,transaction:T})}catch(Oe){N={ready:!1,authorizationInstalled:!1,sponsored:!1,promptless:!1,reason:Oe instanceof Error?`Execution adapter check failed: ${Oe.message}`:"Execution adapter check failed."}}let M=!!(e.adapter?.route!=="eip7702"||s.delegated===!0&&N?.executorAddress&&s.delegate?.toLowerCase()===N.executorAddress.toLowerCase()),F=!!(_?.status==="active"&&_.authorized&&x&&_.scope.mode==="offchain"&&W&&p.valid),le=!!(e.execution?.sponsorship!=="required"||N?.sponsored),ce=!!(F&&b===1&&N?.ready&&N.authorizationInstalled&&N.promptless&&le&&M),_r=!!(F&&(S.route||ce)),Or=_?_.status!=="active"?`Policy is ${_.status}.`:_.authorized?x?W?p.valid?ce?`The configured ${e.adapter?.route??"AA/7702"} adapter can submit this policy-authorized operation without another main-wallet prompt.${N?.sponsored?" Gas sponsorship is guaranteed.":""} ${N?.reason??"The on-chain execution adapter is ready."}`:e.adapter?!N?.ready||!N.authorizationInstalled?`${S.reason} ${N?.reason??"The execution adapter is not ready."}`:N.promptless?le?b!==1?`${S.reason} This policy adapter prepares one execution at a time and cannot claim a multi-call broadcast.`:M?S.route?`${S.reason} ${N.reason}`:S.reason:`${S.reason} The configured EIP-7702 executor does not match the account's on-chain delegation.`:`${S.reason} Sponsored gas is required, but the configured adapter does not guarantee sponsorship.`:`${S.reason} The configured adapter would invoke the main wallet again, so promptless broadcast is not ready.`:`${S.reason} The signed off-chain policy permits this request; an AA/7702 adapter is still required to broadcast without another wallet prompt.`:p.reason??"The transaction is outside the policy scope.":"The connected account is not the policy signer.":"The persisted policy signature no longer matches its scope, signer, or origin.":"The main wallet has not signed this policy.":"Policy not found.";return{policy:_,scope:p,execution:S,signerMatches:W,authorizationVerified:x,ready:_r,broadcastReady:ce,broadcastRoute:ce?e.adapter?.route??null:null,onchainAuthorizationVerified:!!(N?.authorizationInstalled&&M),broadcastSponsored:ce?N?.sponsored??!1:null,broadcastPromptless:!!(ce&&N?.promptless),reason:Or}},[s,n,g,e.adapter,e.execution?.sponsorship,r,y]),I=se(async(k,T,b)=>{let O=await v(k,b,1,"any");if(!O.ready)throw new $("method_not_allowed",O.reason);return g.signWithVerifiedOffchainAuthorization(k,_=>ke(_,C),async({message:_,signature:p,signerAddress:S})=>(await He({message:_,signature:p})).toLowerCase()===S.toLowerCase(),T,b)},[g,C,v]),A=se(async(k,T)=>{let b=e.adapter;if(!b)throw new $("method_not_allowed","No session-policy-aware AA/7702 execution adapter is configured.");c(!0),o(null);try{let O=await v(k,T,1,"any");if(!O.broadcastReady||!O.policy)throw new $("method_not_allowed",O.reason);let _=await b.prepare({policy:O.policy,transaction:T});if(!/^0x[0-9a-fA-F]{64}$/.test(_.digest))throw new $("invalid_input","Execution adapter returned a digest that is not 32 bytes.");if(!cs(T,_.transaction))throw new $("invalid_input","Execution adapter changed the requested target, value, data, or chain.");let p=await b.check({policy:O.policy,transaction:_.transaction}),S=b.route!=="eip7702"||s.delegated===!0&&p.executorAddress!==void 0&&s.delegate?.toLowerCase()===p.executorAddress.toLowerCase();if(!p.ready||!p.authorizationInstalled||!p.promptless||e.execution?.sponsorship==="required"&&!p.sponsored||!S)throw new $("method_not_allowed",p.reason||"The on-chain policy authorization is not ready.");let x=await g.signWithVerifiedOffchainAuthorization(k,N=>ke(N,C),async({message:N,signature:M,signerAddress:F})=>(await He({message:N,signature:M})).toLowerCase()===F.toLowerCase(),_.digest,_.transaction),W=await b.broadcast({policy:O.policy,prepared:_,signature:x});if(W.route!==b.route||W.status!=="submitted"||!/^0x[0-9a-fA-F]{64}$/.test(W.hash))throw new $("invalid_input","Execution adapter returned an invalid submission result.");return await a.refresh(),W}catch(O){let _=O instanceof Error?O:new Error("Policy execution failed");throw o(_),_}finally{c(!1)}},[s,g,e.adapter,e.execution?.sponsorship,C,v,a]),U=a.activeSessions.filter(k=>l.has(k.id));return{policies:a.sessions,activePolicies:U,storageAvailable:a.storageAvailable,loading:a.loading||f,isBusy:u,error:h??a.error,delegation:s,createPolicy:w,revokePolicy:R,previewPolicyExecution:v,signPolicyDigest:I,executePolicy:A,refresh:a.refresh,clearError:E}}import{useCallback as ps,useRef as ds,useState as Un}from"react";function ms(){let{disconnect:e,status:t}=P(),[r,s]=Un(!1),[n,i]=Un(null),a=ds(!0);return{disconnect:ps(async()=>{if(t!=="disconnected"){s(!0),i(null);try{await e()}catch(u){if(!a.current)return;i(u instanceof Error?u:new Error("Disconnect failed"))}finally{a.current&&s(!1)}}},[e,t]),isDisconnecting:r,error:n,cleanup:()=>{a.current=!1}}}import{WalletError as It}from"@naculus/connect-core";import{useCallback as Z,useEffect as fs,useRef as Fe,useState as Ke}from"react";function oe(e){let t=e.activeNamespace??"eip155",r=Array.isArray(e.accounts)?e.accounts.map(({namespace:s,address:n,derivationPath:i})=>({namespace:s,address:n,...i?{derivationPath:i}:{}})):e.address?[{namespace:t,address:e.address}]:[];return{accounts:r,activeNamespace:t,createdAt:e.createdAt??0,...e.chainId?{chainId:e.chainId}:{},...e.version?{version:e.version}:{},recoveryAvailable:!!e.mnemonic,address:r.find(s=>s.namespace===t)?.address??e.address}}function gs(){let{connectEmbedded:e,client:t}=P(),[r,s]=Ke(null),n=Fe(null),i=Fe(4),a=Fe(!1),g=Fe(null),[u,c]=Ke(!1),[h,o]=Ke(!1),[l,d]=Ke(null),f=()=>d(null),m=Z(()=>{let p=n.current;return n.current=null,p},[]),C=Z(()=>{let p=D(t);if(!p?.embeddedConnector)throw new It("wallet_unavailable","Embedded wallet not enabled.");return p.embeddedConnector},[t]),y=Z(()=>{try{return C().getWallet()?.privateKey??null}catch{return null}},[C]),E=Z(async()=>{let p=D(t);if(!p)throw new It("wallet_unavailable","Embedded wallet not enabled.");let S=p.getEmbeddedConnector?await p.getEmbeddedConnector():p.embeddedConnector;if(!S)throw new It("wallet_unavailable","Embedded wallet not enabled.");return S},[t]),w=Z(()=>{try{return D(t)?.passphraseGate??null}catch{return null}},[t]),R=Z(p=>{p?.code==="decryption_failed"&&w()?.forget("That passphrase did not open the wallet.")},[w]),v=Z(async()=>{a.current=!1,d(null);try{let p=await E();if(!await p.load())return!1;let x=p.getWallet();return x?(n.current=null,c(!1),s(oe(x)),!0):!1}catch(p){return a.current=!0,R(p),d(p instanceof Error?p:new Error("Failed to restore embedded wallet")),!1}},[R,E]);fs(()=>{let p=!1,S=null;return v().then(x=>{p||x||a.current||(S=setTimeout(()=>{p||v()},100))}),()=>{p=!0,S&&clearTimeout(S)}},[v]);let I=async()=>{o(!0),d(null);try{let p=await E(),S=await p.load(),x=p.getWallet();S&&x&&(s(oe(x)),n.current=x.mnemonic||null,c(!x.mnemonic)),await e();let W=p.getWallet();W&&(s(oe(W)),W.mnemonic&&!S&&(n.current=W.mnemonic,c(!0)))}catch(p){R(p),d(p instanceof Error?p:new Error("Embedded wallet connection failed"))}finally{o(!1)}},A=async()=>{o(!0),d(null);try{let p=await E();w()?.expect("create");let S=await p.generateWallet();return s(oe(S)),n.current=S.mnemonic,c(!0),S}catch(p){return d(p instanceof Error?p:new Error("Failed to generate wallet")),null}finally{o(!1)}},U=async p=>{o(!0),d(null);try{let S=await E();w()?.expect("create");let x=await S.importFromMnemonic(p);return s(oe(x)),n.current=null,c(!1),x}catch(S){return d(S instanceof Error?S:new Error("Failed to import wallet")),null}finally{o(!1)}},k=async p=>{o(!0),d(null);try{let S=await E();w()?.expect("create");let x=await S.importFromPrivateKey(p);return s(oe(x)),n.current=null,c(!1),x}catch(S){return d(S instanceof Error?S:new Error("Failed to import wallet")),null}finally{o(!1)}},T=async()=>{o(!0),d(null);try{await(await E()).wipe(),s(null),n.current=null,c(!1)}catch(p){d(p instanceof Error?p:new Error("Failed to wipe wallet"))}finally{o(!1)}},b=Z(p=>{let S=C();S.setActiveNamespace(p);let x=S.getWallet();s(x?oe(x):null)},[C]),O=Z(async()=>{let p=await E(),S=await p.backfillAccounts();if(S.length>0){let x=p.getWallet();s(x?oe(x):null)}return S.map(({namespace:x,address:W,derivationPath:N})=>({namespace:x,address:W,...N?{derivationPath:N}:{}}))},[E]),_=()=>{n.current=null,c(!1)};return{connectEmbedded:I,restoreWallet:v,generateWallet:A,importFromMnemonic:U,importFromPrivateKey:k,wipe:T,wallet:r,hasWallet:r!==null,address:r?.address??null,accounts:r?.accounts??[],activeNamespace:r?.activeNamespace??null,setActiveNamespace:b,backfillAccounts:O,seedPhrase:n.current,getSeedPhrase:m,getPrivateKey:y,backupPending:u,confirmBackup:_,isBusy:h,error:l,clearError:f,storageSecurityLevel:(()=>{try{let p=C(),S=p.getStorageSecurityLevel?.()??4;return p.getWallet()?(i.current=S,S):r?i.current:S}catch{return r?i.current:4}})(),securityReport:(()=>{let p=null;try{p=C().getStorageSecurityReport?.()??null}catch{p=null}if(!p)return g.current=null,null;let S=JSON.stringify(p);return g.current?.json===S?g.current.value:(g.current={json:S,value:p},p)})()}}import{chainNumber as ks}from"@naculus/connect-appkit-core";import{useState as xs,useCallback as vs,useEffect as _n,useRef as On,useMemo as bs}from"react";import{WalletError as hs}from"@naculus/connect-core";import{useCallback as Pn,useEffect as ys,useLayoutEffect as Cs,useMemo as Ss,useRef as Wn}from"react";import{tokenChainMismatch as ws}from"@naculus/connect-appkit-core";function Es(e){return[e.token.address.toLowerCase(),e.token.chainId??"",e.token.decimals??"",e.chainId??"",e.owner??"",e.spender??"",e.connected?"1":"0",e.publicClient?"1":"0",e.walletClient?"1":"0",e.session?.id??""].join("|")}function de(e){let{token:t,chainId:r}=e,s=t.address.toLowerCase(),n=Es(e),i=Ss(()=>({key:n}),[n]),a=Wn(n),g=Wn(!0);Cs(()=>{a.current=n},[n]),ys(()=>(g.current=!0,()=>{g.current=!1}),[]);let u=Pn(()=>g.current&&a.current===n,[n]),c=Pn(()=>{if(!u())throw new hs("session_inactive","Wallet or token context changed. Retry the operation with the current account and chain.");let h=ws({address:s,chainId:t.chainId},r);if(h)throw h},[u,s,t.chainId,r]);return{identity:i,isCurrent:u,assertCurrent:c}}import{ERC20_MIN_ABI as As,formatUnits as Rs}from"@naculus/connect-core";function Ts(e){let{publicClient:t}=G(),{currentChain:r}=z(),{identity:s,isCurrent:n,assertCurrent:i}=de({token:e.token,chainId:r?ks(r)??void 0:void 0,owner:e.owner,spender:e.spender,publicClient:t}),[a,g]=xs(null),u=a?.identity===s?a.raw:null,c=a?.identity===s&&a.fetching,h=a?.identity===s?a.error:null,o=On(null),l=On(0),d=vs(async()=>{if(!n())return;let m=++l.current,C=()=>n()&&m===l.current;if(g({identity:s,raw:null,fetching:!!t,error:null}),!!t)try{i();let y=await t.readContract({address:e.token.address,abi:As,functionName:"allowance",args:[e.owner,e.spender]});if(!C())return;g({identity:s,raw:y,fetching:!1,error:null})}catch(y){if(!C())return;g({identity:s,raw:null,fetching:!1,error:y instanceof Error?y:new Error("Failed to fetch allowance")})}},[t,e.token.address,e.token.chainId,e.owner,e.spender,s,n,i]);return _n(()=>{d().catch(m=>console.warn("useERC20Allowance: initial fetch failed:",m))},[d]),_n(()=>(e.refreshInterval&&e.refreshInterval>0&&(o.current=setInterval(d,e.refreshInterval)),()=>{o.current&&(clearInterval(o.current),o.current=null)}),[e.refreshInterval,d]),{allowance:bs(()=>{if(u===null)return null;let m=e.token.decimals;return m===void 0?null:Rs(u,m)},[u,e.token.decimals]),allowanceRaw:u,isFetching:c,error:h,refetch:d}}import{chainNumber as Is}from"@naculus/connect-appkit-core";import{useState as Mn,useCallback as ve,useRef as Ln}from"react";import{WalletError as Ut}from"@naculus/connect-core";import{useCallback as Nn,useState as Dn}from"react";function xe(){let{session:e,chainId:t,client:r}=P(),[s,n]=Dn("idle"),[i,a]=Dn(null),g=Nn(async c=>{if(!e){n("failed");let o=new Ut("wallet_unavailable","No active session");throw a(o),o}let h=e.namespaces.eip155?.accounts.find(o=>/^eip155:\d+:0x[0-9a-fA-F]{40}$/.test(o)||/^0x[0-9a-fA-F]{40}$/.test(o));if(!h){n("failed");let o=new Ut("wallet_unavailable","No EVM account found");throw a(o),o}n("awaiting_approval"),a(null);try{let o={...c,from:c.from??h.split(":").pop()},l=D(r);if(!l)throw new Ut("wallet_unavailable","Client not initialized");let d=await l.sendTransaction(e,{transaction:o,chainId:t??void 0}),f=Me(d);return n("submitted"),f}catch(o){n("failed");let l=o instanceof Error?o.message:"Transaction failed";throw a(o instanceof Error?o:new Error(l)),o}},[e,t,r]),u=Nn(()=>{n("idle"),a(null)},[]);return{sendTransaction:g,status:s,error:i,reset:u,isSending:s==="awaiting_approval"}}import{WalletError as $e,ERC20_MIN_ABI as be,parseUnits as Bn,formatUnits as Us}from"@naculus/connect-core";import{encodeFunctionData as Ps}from"viem";import{createDecimalsCache as Ws,readDecimals as Pt,writeDecimals as Hn}from"@naculus/connect-appkit-core";function _s(e){return e.includes(":")?e.split(":").pop():e}function Os(e,t){return Ps({abi:be,functionName:"approve",args:[e,t]})}var Ns=2n**256n-1n;function Ds(e){let{publicClient:t,walletClient:r}=G(),{evmAccount:s,isConnected:n}=H(),{currentChain:i}=z(),{session:a,client:g}=P(),{sendTransaction:u,isSending:c,error:h,reset:o}=xe(),[l,d]=Mn(null),{identity:f,isCurrent:m,assertCurrent:C}=de({token:e.token,chainId:i?Is(i)??void 0:void 0,owner:s,spender:e.spender,connected:n,publicClient:t,walletClient:r,session:a,client:g}),[y,E]=Mn(null),w=y?.identity===f?y.raw:null,R=y?.identity===f&&y.fetching,v=Ln(Ws(e.token,e.token.decimals)),I=Ln(0),A=l??h,U=s?_s(s):null,k=ve(async()=>{if(!m())return null;let S=++I.current,x=()=>m()&&S===I.current;if(E({identity:f,raw:null,fetching:!!t&&!!U&&n}),d(null),!t||!U||!n)return null;try{C();let W=await t.readContract({address:e.token.address,abi:be,functionName:"allowance",args:[U,e.spender]});return x()?(E({identity:f,raw:W,fetching:!1}),W):null}catch(W){return x()&&(E({identity:f,raw:null,fetching:!1}),d(W instanceof Error?W:new Error("Failed to fetch allowance"))),null}},[t,U,e.token.address,e.token.chainId,e.spender,f,m,C,n]),T=(()=>{if(w===null)return null;let S=Pt(v.current,e.token,e.token.decimals);return S===void 0?null:Us(w,S)})(),b=ve(async S=>{if(d(null),o(),!n||!s){let x=new $e("wallet_unavailable","No connected account");throw d(x),x}if(!t){let x=new $e("wallet_unavailable","No public client");throw d(x),x}try{C();let x=Os(e.spender,S),W=D(g);if(a&&W){let M=await u({to:e.token.address,data:x,value:"0"});return k(),M}if(r){let{request:M}=await t.simulateContract({address:e.token.address,abi:be,functionName:"approve",args:[e.spender,S],account:U});C();let F=await r.writeContract(M);return k(),F}let N=await u({to:e.token.address,data:x,value:"0"});return k(),N}catch(x){let W=x instanceof Error?x:new Error("Approve failed");throw m()&&d(W),W}},[e,t,r,s,n,a,g,U,u,o,k,C,m]),O=ve(async S=>{try{if(C(),!t)throw new $e("wallet_unavailable","No public client");let x=Pt(v.current,e.token,e.token.decimals);x===void 0&&(x=await t.readContract({address:e.token.address,abi:be,functionName:"decimals"}),C(),Hn(v.current,e.token,x));let W=Bn(S,x);return await b(W)}catch(x){throw m()&&d(x instanceof Error?x:new Error("Approve failed")),x}},[e.token,t,b,C,m]),_=ve(async()=>b(Ns),[b]),p=ve(async S=>{if(!m()||!n||!U||!t)return!1;try{C()}catch(M){return d(M instanceof Error?M:new Error("Cannot check allowance")),!1}let x=w??await k();if(x===null)return!1;let W=Pt(v.current,e.token,e.token.decimals);if(W===void 0){if(!t)throw new $e("wallet_unavailable","Cannot check allowance: no public client to read token decimals.");if(W=await t.readContract({address:e.token.address,abi:be,functionName:"decimals"}),!m())return!1;Hn(v.current,e.token,W)}let N=Bn(S,W);return m()&&x>=N},[w,k,e.token.address,e.token.chainId,e.token.decimals,t,m,C,n,U]);return{approve:O,approveMax:_,allowance:T,allowanceRaw:w,hasAllowance:p,isApproving:c,isFetchingAllowance:R,error:A,refetchAllowance:k}}import{chainNumber as Ms}from"@naculus/connect-appkit-core";import{useState as Ls,useCallback as Bs,useRef as Hs}from"react";import{WalletError as Fn,ERC20_MIN_ABI as Wt,parseUnits as Fs}from"@naculus/connect-core";import{encodeFunctionData as Ks}from"viem";import{createDecimalsCache as $s,readDecimals as qs,writeDecimals as Vs}from"@naculus/connect-appkit-core";function zs(e){return e.includes(":")?e.split(":").pop():e}function js(e,t){return Ks({abi:Wt,functionName:"transfer",args:[e,t]})}function Gs(e){let{publicClient:t,walletClient:r}=G(),{evmAccount:s,isConnected:n}=H(),{currentChain:i}=z(),{session:a,client:g}=P(),{sendTransaction:u,isSending:c,error:h,reset:o}=xe(),[l,d]=Ls(null),{isCurrent:f,assertCurrent:m}=de({token:e.token,chainId:i?Ms(i)??void 0:void 0,owner:s,connected:n,publicClient:t,walletClient:r,session:a,client:g}),C=Hs($s(e.token,e.token.decimals)),y=l??h;return{sendTransfer:Bs(async(w,R)=>{if(d(null),o(),!n||!s){let v=new Fn("wallet_unavailable","No connected account");throw d(v),v}if(!t){let v=new Fn("wallet_unavailable","No public client available");throw d(v),v}try{m();let v=zs(s),I=qs(C.current,e.token,e.token.decimals);I===void 0&&(I=await t.readContract({address:e.token.address,abi:Wt,functionName:"decimals"}),m(),Vs(C.current,e.token,I));let A=Fs(R,I),U=js(w,A),k=D(g);if(a&&k)return await u({to:e.token.address,data:U,value:"0"});if(r){let{request:b}=await t.simulateContract({address:e.token.address,abi:Wt,functionName:"transfer",args:[w,A],account:v});return m(),await r.writeContract(b)}return await u({to:e.token.address,data:U,value:"0"})}catch(v){let I=v instanceof Error?v:new Error("Transfer failed");throw f()&&d(I),I}},[e.token,t,r,s,n,a,g,u,o,m,f]),isSending:c,error:y}}import{chainNumber as ea}from"@naculus/connect-appkit-core";import{useMemo as ta}from"react";import{chainNumber as Qs}from"@naculus/connect-appkit-core";import{WalletError as Xs}from"@naculus/connect-core";import{useCallback as Kn,useEffect as Ys,useRef as Js,useState as _t}from"react";import{resolveRevertReason as Zs}from"@naculus/connect-appkit-core";function Ot(e,t){let{session:r}=P(),{evmAccount:s,isConnected:n}=H(),{currentChain:i}=z(),{publicClient:a}=G(),[g,u]=_t(void 0),[c,h]=_t(!1),[o,l]=_t(null),d=Js(void 0),f=Kn(async()=>{if(!e){let C={status:"unavailable",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[]},provider:"eth_call",summary:"No transaction to simulate",changesDetected:!1};return u(C),C}h(!0),l(null);try{if((t??(i?Qs(i)??void 0:void 0))===void 0)throw new Xs("invalid_chain","No chain to simulate on. Connect a wallet or pass a chainId.");let y=i?.rpcUrl;if(a)try{let w=s?.includes(":")?s.split(":").pop():s,R={to:e.to,data:e.data??"0x",value:e.value?BigInt(e.value):0n};w&&(R.from=w),await a.call(R);let v={status:"success",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[]},gasInfo:e.gas?{gasLimit:BigInt(e.gas),estimatedFeeEth:"0"}:void 0,provider:"eth_call",summary:"Transaction simulation succeeded (basic revert check only)",changesDetected:!0};return u(v),v}catch(w){let R=w?.message??String(w),v=w?.data??w?.cause?.data,I=Zs(v,R),A={status:"reverted",revertReason:I,coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"high",message:I?`Transaction would revert: ${I}`:"Transaction would revert"}]},provider:"eth_call",summary:I?`Transaction reverted: ${I}`:"Transaction reverted",changesDetected:!1};return u(A),A}if(y)try{let R=await(await fetch(y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:"eth_call",params:[{to:e.to,from:s?.includes(":")?s.split(":").pop():s,data:e.data??"0x",value:e.value??"0x0"},"latest"]})})).json();if(R.error){let I={status:"reverted",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"high",message:`Transaction would revert: ${R.error.message}`}]},provider:"eth_call",summary:"Transaction reverted",changesDetected:!1};return u(I),I}let v={status:"success",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[]},provider:"eth_call",summary:"Transaction simulation succeeded",changesDetected:!0};return u(v),v}catch(w){let R={status:"unavailable",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"medium",message:`Network error: ${w?.message??"Unknown"}`}]},provider:"eth_call",summary:"Simulation unavailable due to network error",changesDetected:!1};return u(R),R}let E={status:"unavailable",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"low",message:"No RPC URL or public client available for simulation"}]},provider:"eth_call",summary:"Simulation unavailable: no RPC URL",changesDetected:!1};return u(E),E}catch(C){let y=C instanceof Error?C:new Error("Simulation failed");throw l(y),y}finally{h(!1)}},[e,t,i,a,s]);Ys(()=>{if(e)return d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{f().catch(()=>{})},300),()=>{d.current&&clearTimeout(d.current)}},[e,f]);let m=Kn(()=>{u(void 0),l(null),h(!1)},[]);return{result:g,isSimulating:c,error:o,simulate:f,reset:m}}var na="0xa9059cbb";function ra(e){return(e.startsWith("0x")?e.slice(2):e).padStart(64,"0")}function oa(e,t=32){return(e.startsWith("0x")?e.slice(2):e).padStart(t*2,"0")}function sa(e,t){let[r="0",s=""]=e.split("."),n=s.padEnd(t,"0").slice(0,t);return BigInt(r+n||"0")}function aa(e,t){return`${na}${ra(e)}${oa(t.toString(16))}`}function ia(e){let{evmAccount:t,isConnected:r}=H(),{currentChain:s}=z(),n=e.token.chainId??(s?ea(s)??void 0:void 0),i=ta(()=>{if(!(!r||!t))try{let g=e.token.decimals;if(g===void 0)return;let u=sa(e.amount,g),c=aa(e.to,u);return{to:e.token.address,data:c,value:"0"}}catch{return}},[e.token.address,e.token.decimals,e.to,e.amount,t,r]),a=Ot(i,n);return{result:a.result,isSimulating:a.isSimulating,error:a.error,reSimulate:a.simulate,reset:a.reset}}import{useState as Nt,useCallback as ma,useRef as Dt}from"react";import{useState as qe,useEffect as la,useCallback as $n,useRef as ca}from"react";import{createContext as ua,useContext as pa}from"react";var qn=ua(null);function Ae(){return pa(qn)}function da(e,t,r){let s=Ae(),n=r??s,[i,a]=qe(null),[g,u]=qe(!1),[c,h]=qe(!1),[o,l]=qe(null),d=ca(void 0),f=$n(async()=>{if(!(!n||!e)){u(!0),l(null);try{await n.refreshTx(e,t);let y=n.getTxStatus(e,t);y&&a(y)}catch(y){l(y instanceof Error?y:new Error(String(y)))}finally{u(!1)}}},[n,e,t]),m=$n(()=>{!n||!e||(n.stopWatching(e,t),h(!1))},[n,e,t]);la(()=>{if(!n||!e||!t){a(null),h(!1);return}d.current&&d.current!==e&&n.stopWatching(d.current),d.current=e;let y=!1;h(!0),u(!0),l(null);let E=n.getTxStatus(e,t);E&&(a(E),u(!1)),n.watchTx(e,t,{}).then(R=>{y||(a(R),u(!1))}).catch(R=>{y||(l(R instanceof Error?R:new Error(String(R))),u(!1))});let w=R=>{y||a({...R})};return n.on("statusChange",w),()=>{y=!0,h(!1),n.off("statusChange",w)}},[n,e,t]);let C=i?.status??"idle";return{entry:i,status:C,isLoading:g,isWatching:c,error:o,refresh:f,stopWatching:m}}function fa(e){let t=Ae(),r=e??t,[s,n]=Nt(null),[i,a]=Nt(null),[g,u]=Nt(null),c=Dt(null),h=Dt(null),o=Dt(null);r&&(h.current||(h.current=d=>{a(d),(!c.current||d.createdAt>=c.current.createdAt)&&(n(d),c.current=d)},r.on("confirmed",h.current)),o.current||(o.current=d=>{u(d),(!c.current||d.createdAt>=c.current.createdAt)&&(n(d),c.current=d)},r.on("failed",o.current)));let l=ma(()=>{n(null),a(null),u(null),c.current=null},[]);return{lastTx:s,lastConfirmedTx:i,lastFailedTx:g,clear:l}}import{useCallback as Ca}from"react";import{useCallback as ga,useEffect as Vn,useMemo as ha,useRef as zn,useState as Mt}from"react";import{getResolver as ya}from"@naculus/connect-appkit-core";function Ve({input:e,skip:t=!1,resolverConfig:r,scope:s,query:n}){let[i,a]=Mt(null),[g,u]=Mt(!1),[c,h]=Mt(null),o=zn(0),l=zn(!0);Vn(()=>(l.current=!0,()=>{l.current=!1}),[]);let d=ha(()=>ya(r),[r]),f=ga(()=>{let m=e.trim();if(!m||t){o.current+=1,a(null),u(!1),h(null);return}let C=++o.current;u(!0),h(null),n(d,m,s).then(y=>{!l.current||C!==o.current||(a(y),u(!1))}).catch(y=>{!l.current||C!==o.current||(h(y instanceof Error?y:new Error(String(y))),a(null),u(!1))})},[e,t,s,d,n]);return Vn(()=>{f()},[f]),{data:i,isLoading:g,error:c,refetch:f}}function Sa(e,t){let r=Ca((s,n,i)=>s.lookupAddress(n,i),[]);return Ve({input:e,skip:t?.skip,resolverConfig:t?.resolverConfig,scope:t?.chainId,query:r})}import{useState as jn,useCallback as ee,useMemo as wa,useEffect as Gn,useRef as Ea}from"react";import{InAppChannel as ka}from"@naculus/connect-core";import{createStorageAdapter as xa}from"@naculus/connect-core";var va={telegram:!1,webpush:!1,inapp:!0,frequency:"final-only",mutedChains:[],mutedTypes:[]},Qn="naculus_notif_react_settings";function ba(e){let t=Ea(null);t.current||(t.current=e?.channel??new ka);let r=t.current,[s,n]=jn(()=>r.getHistory()),[i,a]=jn(()=>va);Gn(()=>{(e?.storage??Xn()).getItem(Qn).then(E=>{E&&a(E)})},[]),Gn(()=>(r.onNotification=y=>{n(E=>[...E,y])},r.restore().then(()=>{n(r.getHistory())}),()=>{r.onNotification=void 0}),[]);let g=wa(()=>s.filter(y=>!y.read).length,[s]),u=ee(()=>{r.clear(),n([])},[r]),c=ee(y=>{let E=r.getHistory().filter(w=>w.id!==y);r.clear(),Promise.all(E.map(w=>r.send({id:w.id,userId:"",txHash:w.txHash,chainId:"",chainName:w.chainName,status:w.status,title:w.title,body:w.body,valueFormatted:w.valueFormatted,explorerUrl:w.explorerUrl,timestamp:w.timestamp}))).then(()=>{n(r.getHistory())})},[r]),h=ee(y=>{r.markAsRead(y),n(E=>E.map(w=>w.id===y?{...w,read:!0}:w))},[r]),o=ee(()=>{r.markAllAsRead(),n(y=>y.map(E=>({...E,read:!0})))},[r]),l=ee(y=>{let E={...y,id:`notif_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now()};r.send({id:E.id,userId:"",txHash:E.txHash,chainId:"",chainName:E.chainName,status:E.status,title:E.title,body:E.body,valueFormatted:E.valueFormatted,explorerUrl:E.explorerUrl,timestamp:E.timestamp})},[r]),d=ee(y=>{a(E=>{let w={...E,...y};return(e?.storage??Xn()).setItem(Qn,w).catch(()=>{}),w})},[e?.storage]),f=ee(y=>{let E={};y.includes("telegram")&&(E.telegram=!0),y.includes("webpush")&&(E.webpush=!0),y.includes("inapp")&&(E.inapp=!0),d(E)},[d]),m=ee(y=>{d({mutedChains:[...new Set([...i.mutedChains,y])]})},[i.mutedChains,d]),C=ee(y=>{d({mutedChains:i.mutedChains.filter(E=>E!==y)})},[i.mutedChains,d]);return{notifications:s,unreadCount:g,addNotification:l,clear:u,clearOne:c,markAsRead:h,markAllAsRead:o,settings:i,updateSettings:d,setChannels:f,muteChain:m,unmuteChain:C}}function Xn(){let e=xa("local","naculus_notif_");return{getItem:async t=>{try{return await e.get(t)}catch(r){return console.warn("useNotification: failed to read from storage:",r),null}},setItem:async(t,r)=>{try{await e.set(t,r)}catch(s){console.warn("useNotification: failed to write to storage:",s)}},removeItem:async t=>{try{await e.remove(t)}catch(r){console.warn("useNotification: failed to remove from storage:",r)}}}}import{useCallback as Lt,useSyncExternalStore as Aa}from"react";var Yn=()=>null,Ra=()=>()=>{};function Ta(){let{client:e}=P(),t=D(e)?.passphraseGate??null,r=Aa(t?.subscribe??Ra,t?.getSnapshot??Yn,Yn),s=Lt(a=>t?.submit(a),[t]),n=Lt(()=>t?.cancel(),[t]),i=Lt(a=>t?.forget(a),[t]);return{request:r,submit:s,cancel:n,forget:i,isUnlocked:t?.isUnlocked??!1,gate:t}}import{useCallback as Ia}from"react";function Ua(e,t){let r=Ia((s,n)=>s.resolveName(n),[]);return Ve({input:e,skip:t?.skip,resolverConfig:t?.resolverConfig,query:r})}import{AA_SUPPORTED_CHAINS as Pa,DEFAULT_ENTRY_POINT as Wa,WalletError as te}from"@naculus/connect-core";import{useCallback as Jn,useEffect as Zn,useRef as er,useState as Re}from"react";import{resolveEvmChainId as _a}from"@naculus/connect-appkit-core";function Oa(e){if(!e)return null;let t=e.includes(":")?e.split(":").pop():e;return t&&/^0x[0-9a-fA-F]{40}$/.test(t)?t:null}function Bt(e){if(typeof e!="string"||!/^0x(?:[0-9a-fA-F]{2})+$/.test(e))throw new te("signature_rejected","Wallet returned an invalid UserOperation signature.");return e}async function Na(e,t,r,s,n){let i=D(t);if(!i)throw new te("wallet_unavailable","Client not initialized");let a=[r,s];if(e.walletType==="eip6963"||e.id?.startsWith("eip6963-")){let{eip6963Connector:g}=await import("@naculus/connector-evm-injected"),u=g.getDiscoveredWallets().find(h=>h.id===e.walletId),c=u?await u.provider.request({method:"personal_sign",params:a}):await g.request({method:"personal_sign",params:a});return Bt(c)}if(e.walletType==="walletconnect")return Bt(await i.connector.request({method:"personal_sign",params:a}));if(e.walletType==="embedded"){let g=i.embeddedConnector;if(!g?.signHash)throw new te("method_unsupported","This embedded wallet build cannot sign a raw digest. Upgrade @naculus/connector-embedded or pass an explicit signer.");return Bt(await g.signHash(e,r))}throw e.walletType==="passkeys"?new te("method_unsupported","Passkeys sign with P-256, which a SimpleAccount cannot verify. Use a smart account with a WebAuthn validator, or pass an explicit signer."):new te("method_unsupported",`Raw UserOperation signing is not available for ${e.walletType} on ${n}. Pass a signer that signs the raw 32-byte hash.`)}function Da(e){let{evmAccount:t}=H(),{session:r,chainId:s,client:n}=P(),[i,a]=Re(null),[g,u]=Re(null),[c,h]=Re(!1),[o,l]=Re(!1),[d,f]=Re(null),m=er(0),C=er(!1);Zn(()=>()=>{m.current+=1,C.current=!1},[]),Zn(()=>{m.current+=1,C.current=!1,a(null),u(null),h(!1),l(!1),f(null)},[n,s,t,e?.accountType,e?.bundlerUrl,e?.chainId,e?.entryPoint,e?.owner,e?.rpcUrl,e?.salt,e?.signerMode,r]);let y=Jn(async(w,R)=>{let v=k=>(f(k),null);if(!e?.rpcUrl)return v(new Error("RPC URL not configured"));if(!e.bundlerUrl)return v(new Error("Bundler URL not configured"));if(!w.length)return v(new Error("At least one call is required"));if(C.current)return v(new Error("A UserOperation is already in progress"));let I=Oa(e.owner??t);if(!I)return v(new te("wallet_unavailable","No EVM account found"));let A=_a(e.chainId,s);if(!A)return v(new te("invalid_chain",e.chainId||s?`Invalid EVM chain ID: ${e.chainId??s}`:"No EVM chain to send on. Connect a wallet or pass options.chainId."));if(s&&s!==A)return v(new te("chain_mismatch",`Connected chain ${s} does not match UserOperation chain ${A}.`));if(!e.signer&&!r)return v(new te("wallet_unavailable","No active session"));let U=++m.current;C.current=!0,h(!0),l(!0),f(null),a(null),u(null);try{let{SmartAccountManager:k}=await import("@naculus/connect-core"),T=e.signer??(p=>Na(r,n,p,I,A)),b=new k({rpcUrl:e.rpcUrl,bundlerClient:{url:e.bundlerUrl},chainId:A,signer:T,signerMode:e.signer?e.signerMode??"eip191":"raw"}),O={owner:I,accountType:e.accountType??"simple",entryPoint:e.entryPoint??Pa[A]?.entryPoint??Wa,chainId:A,salt:e.salt},_=await b.sendUserOperation(O,w,R);return U!==m.current?null:(l(!1),a(_.userOpHash),b.getUserOperationReceipt(_.userOpHash).then(p=>{U===m.current&&u(p)}).catch(()=>{}),_)}catch(k){if(U!==m.current)return null;let T=k instanceof Error?k:new Error("Failed to send UserOperation");return f(T),null}finally{U===m.current&&(h(!1),l(!1),C.current=!1)}},[n,s,t,e,r]),E=Jn(()=>{m.current+=1,C.current=!1,a(null),u(null),h(!1),l(!1),f(null)},[]);return{sendUserOp:y,userOpHash:i,receipt:g,isPending:c,isEstimating:o,error:d,reset:E}}import{useSyncExternalStore as Ma,useCallback as tr}from"react";function La(e,t){if(!e)return()=>{};let r=()=>t();return e.on("sessionConnected",r),e.on("sessionDisconnected",r),e.on("chainChanged",r),()=>{e.off("sessionConnected",r),e.off("sessionDisconnected",r),e.off("chainChanged",r)}}var Ht=Object.freeze({session:null,chainSessions:[],activeChainId:null,isConnected:!1,connectorId:null}),Ft=new WeakMap;function Ba(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function Ha(e){if(!e)return Ht;let t=e.getActiveBundle(),r=Ft.get(e);if(!t)return r&&r.session===null?r:(Ft.set(e,Ht),Ht);let s=Array.from(t.chainSessions.values());if(r&&r.session===t.walletSession&&r.activeChainId===t.activeChainId&&Ba(r.chainSessions,s))return r;let n={session:t.walletSession,chainSessions:s,activeChainId:t.activeChainId,isConnected:!0,connectorId:t.walletSession.walletType};return Ft.set(e,n),n}function Fa(e){let t=P(),r=e??t.sessionManager??null,s=tr(i=>La(r,i),[r]),n=tr(()=>Ha(r),[r]);return Ma(s,n)}import{WalletError as ze}from"@naculus/connect-core";import{createSiwxMessage as Ka,generateNonce as $a,getBlockchainName as qa,issueNonce as Va,nowISO as za}from"@naculus/siwx";import{useCallback as nr,useState as rr}from"react";var ja=86400;function Ga(){return typeof window<"u"?window.location.host:"localhost"}function Qa(){return typeof window<"u"?window.location.origin:"http://localhost"}function Kt(){let{session:e,chainId:t,client:r}=P(),[s,n]=rr(!1),[i,a]=rr(null),g=nr(()=>a(null),[]);return{signIn:nr(async c=>{if(!e)throw new ze("wallet_unavailable","No active session");let h=c?.chainId??t;if(!h)throw new ze("invalid_chain","No chain to sign for. Connect a wallet or pass options.chainId.");let o=ue(e,h);if(!o)throw new ze("wallet_unavailable","No account found");let l=D(r);if(!l)throw new ze("wallet_unavailable","Client not initialized");let{address:d}=o,f=c?.domain??Ga(),m=c?.uri??Qa();n(!0),a(null);try{let C=$a();await Va(C);let y=za(),E=c?.expirySeconds??ja,w=new Date(Date.now()+E*1e3).toISOString(),R=Ka({domain:f,address:d,uri:m,version:1,chainId:h,nonce:C,issuedAt:y,expirationTime:w,statement:c?.statement,resources:c?.resources,requestId:c?.requestId}),v=await l.signMessage(e,{message:R,address:d,chainId:h??void 0}),I={message:{raw:R,domain:f,address:d,statement:c?.statement??null,uri:m,version:1,chainId:h,nonce:C,issuedAt:y,blockchain:qa(h),expirationTime:w,notBefore:null,resources:c?.resources??[],requestId:c?.requestId??null},signature:v};return n(!1),I}catch(C){let y=C instanceof Error?C:new Error("SIWx sign-in failed");throw a(y),n(!1),y}},[e,t,r]),isSigningIn:s,error:i,clearError:g}}import{logger as $t}from"@naculus/connect-core";import{checkSessionExpired as or,createLocalStorageSiwxSessionStorage as Xa}from"@naculus/siwx";import{useCallback as je,useEffect as sr,useRef as Ya,useState as Ge}from"react";function Ja(){let e=new Uint8Array(8);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function ar(e){return{id:`siwx_${Date.now().toString(36)}_${Ja()}`,chainId:e.message.chainId,address:e.message.address,domain:e.message.domain,message:e.message,signature:e.signature,issuedAt:e.message.issuedAt??new Date().toISOString(),expiresAt:e.message.expirationTime,refreshedAt:null}}function Za(e){let{storagePrefix:t="naculus_",autoRestore:r=!0,defaultExpirySeconds:s=86400}=e??{},[n,i]=Ge(null),[a,g]=Ge(r),[u,c]=Ge(!1),[h,o]=Ge(null),{session:l,chainId:d}=P(),f=Kt(),m=Ya(Xa(`${t}siwx_session`)),C=je(()=>o(null),[]);sr(()=>{if(!r){g(!1);return}let A=!1;return(async()=>{try{let k=await m.current.get();if(A)return;k?($t.info("react/useSIWxSession","Restored persisted SIWx session"),i(k),o(null)):i(null)}catch(U){$t.warn("react/useSIWxSession","Failed to restore SIWx session:",U),i(null)}finally{A||g(!1)}})(),()=>{A=!0}},[r]),sr(()=>{if(!n?.expiresAt)return;let A=new Date(n.expiresAt).getTime()-Date.now();if(A<=0){i(null);return}let U=setTimeout(()=>{i(k=>k&&k.id===n.id?null:k)},A);return()=>clearTimeout(U)},[n?.id,n?.expiresAt]);let y=je(async A=>{c(!0),o(null);try{let U={expirySeconds:s,chainId:d??void 0,...A},k=await f.signIn(U),T=ar(k);return await m.current.set(T),i(T),c(!1),T}catch(U){let k=U instanceof Error?U:new Error("SIWx sign-in failed");throw o(k),c(!1),k}},[f,d,s]),E=je(async()=>{try{await m.current.remove()}catch(A){$t.warn("react/useSIWxSession","Failed to clear session:",A)}i(null),o(null)},[]),w=je(async()=>{if(!n)throw new Error("No active session to refresh");c(!0),o(null);try{let A=await f.signIn({domain:n.domain,statement:n.message.statement??void 0,uri:n.message.uri,chainId:n.chainId,expirySeconds:s,resources:n.message.resources.length>0?n.message.resources:void 0,requestId:n.message.requestId??void 0}),U={...ar(A),id:n.id,refreshedAt:new Date().toISOString()};return await m.current.set(U),i(U),c(!1),U}catch(A){let U=A instanceof Error?A:new Error("Session refresh failed");throw o(U),c(!1),U}},[n,f,s]),R=n!==null&&!or(n),v=or(n),I=n?.expiresAt?Math.max(0,new Date(n.expiresAt).getTime()-Date.now()):null;return{session:R?n:null,isAuthenticated:R,isRestoring:a,isSigningIn:u,isExpired:v,timeUntilExpiry:I,signIn:y,signOut:E,refresh:w,error:h,clearError:C}}import{WalletError as Qe}from"@naculus/connect-core";import{createSiwxMessage as ei,generateNonce as ti,getBlockchainName as ni,issueNonce as ri,nowISO as oi}from"@naculus/siwx";import{useCallback as ir,useState as qt}from"react";function si(){return typeof window<"u"?window.location.host:"localhost"}function ai(){return typeof window<"u"?window.location.origin:"http://localhost"}function Te(){let{session:e,chainId:t,client:r}=P(),[s,n]=qt(!1),[i,a]=qt(null),[g,u]=qt(null),c=ir(()=>u(null),[]);return{signIn:ir(async o=>{if(!e)throw new Qe("wallet_unavailable","No active session");let l=o?.chainId??t;if(!l)throw new Qe("invalid_chain","No chain to sign for. Connect a wallet or pass options.chainId.");let d=ue(e,l);if(!d)throw new Qe("wallet_unavailable","No account found");let f=D(r);if(!f)throw new Qe("wallet_unavailable","Client not initialized");let{address:m}=d,C=o?.domain??si(),y=o?.uri??ai();n(!0),u(null);try{let E=ti();await ri(E);let w=oi(),R=ei({domain:C,address:m,uri:y,version:1,chainId:l,nonce:E,issuedAt:w,statement:o?.statement,expirationTime:o?.expirySeconds?new Date(Date.now()+o.expirySeconds*1e3).toISOString():void 0,resources:o?.resources,requestId:o?.requestId}),v=await f.signMessage(e,{message:R,address:m,chainId:l??void 0}),I=o?.expirySeconds?new Date(Date.now()+o.expirySeconds*1e3).toISOString():null,A={message:{raw:R,domain:C,address:m,statement:o?.statement??null,uri:y,version:1,chainId:l,nonce:E,issuedAt:w,blockchain:ni(l),expirationTime:I,notBefore:null,resources:o?.resources??[],requestId:o?.requestId??null},signature:v};return a(A),A}catch(E){let w=E instanceof Error?E:new Error("SIWx sign-in failed");throw u(w),w}finally{n(!1)}},[e,t,r]),isSigningIn:s,result:i,error:g,clearError:c}}import{WalletError as Vt}from"@naculus/connect-core";import{useCallback as lr}from"react";function ii(){let{session:e,chainId:t}=P();return lr(r=>{if(!e)throw new Vt("wallet_unavailable","No active session");let s=r??t;if(s&&!s.startsWith("eip155:"))throw new Vt("namespace_mismatch",`Ethereum SIWx requires an eip155 chain, received ${s}`);let n=e.namespaces.eip155;if(!n||n.accounts.length===0)throw new Vt("namespace_mismatch","No EVM (eip155) accounts found in session")},[e,t])}function li(){let e=ii(),t=Te();return{signIn:lr(async s=>(e(s?.chainId),t.signIn(s)),[e,t.signIn]),isSigningIn:t.isSigningIn,result:t.result,error:t.error,clearError:t.clearError}}import{WalletError as ci}from"@naculus/connect-core";import{SimulationManager as ui}from"@naculus/wallet-engine";import{useCallback as cr,useRef as pi,useState as zt}from"react";function di(e){let t=e?.rpcUrl,r=e?.chainId,s=pi(null);function n(){return s.current||(s.current=new ui({enabled:!0,rpcUrl:t,autoSimulate:!1})),s.current}let[i,a]=zt(null),[g,u]=zt(!1),[c,h]=zt(null),o=cr(async(d,f,m,C,y)=>{u(!0),h(null);try{let E=n(),w=y?.chainId??r;if(w===void 0)throw new ci("invalid_chain","No chain to simulate on. Connect a wallet or pass a chainId.");let R=y?.rpcUrl??t,v=await E.simulateERC20Transfer(d,f,m,C,w,y?.decimals,R);return a(v),v}catch(E){let w=E instanceof Error?E:new Error(String(E));throw h(w),w}finally{u(!1)}},[t,r]),l=cr(()=>{a(null),h(null),u(!1)},[]);return{result:i,loading:g,error:c,simulate:o,reset:l}}import{useState as Xe,useCallback as jt,useEffect as mi,useRef as fi}from"react";import{LocalStorageAdapter as gi,logger as Ye}from"@naculus/connect-core";var Je="siwx_auth";function hi(e){return new gi(e)}function yi(e,t){return e.message.expirationTime?new Date(e.message.expirationTime).getTime()<=t.getTime():!1}function Ci(e,t){return e.message.notBefore?new Date(e.message.notBefore).getTime()<=t.getTime():!0}function Si(e){let{storagePrefix:t="naculus_",autoRestore:r=!0}=e??{},[s,n]=Xe(null),[i,a]=Xe(r),[g,u]=Xe(!1),[c,h]=Xe(null),o=Te(),l=fi(hi(t)),d=jt(()=>h(null),[]);mi(()=>{if(!r){a(!1);return}let C=!1;return(async()=>{try{let y=l.current,E=await y.get(Je);if(C)return;E&&!yi(E,new Date)&&Ci(E,new Date)?(Ye.info("react/useSiwxAuthSession","Restored persisted SIWx auth session"),n(E),h(null)):E&&(Ye.info("react/useSiwxAuthSession","Persisted SIWx auth expired, clearing"),await y.remove(Je))}catch(y){Ye.warn("react/useSiwxAuthSession","Failed to restore SIWx auth:",y)}finally{C||a(!1)}})(),()=>{C=!0}},[r]);let f=jt(async C=>{u(!0),h(null);try{let y=await o.signIn(C);return await l.current.set(Je,y),n(y),u(!1),y}catch(y){let E=y instanceof Error?y:new Error("SIWx sign-in failed");throw h(E),u(!1),E}},[o]),m=jt(async()=>{try{await l.current.remove(Je)}catch(C){Ye.warn("react/useSiwxAuthSession","Failed to clear SIWx auth:",C)}n(null),h(null)},[]);return{isSignedIn:s!==null,isRestoring:i,siwxResult:s,isSigningIn:g,error:c,signIn:f,signOut:m,clearError:d}}import{AA_SUPPORTED_CHAINS as wi,DEFAULT_ENTRY_POINT as Ei,WalletError as mr}from"@naculus/connect-core";import{useCallback as ae,useEffect as ur,useRef as Gt,useState as Ie}from"react";import{resolveEvmChainId as pr}from"@naculus/connect-appkit-core";function ki(e){if(!e)return null;let t=e.includes(":")?e.split(":").pop():e;return t&&/^0x[0-9a-fA-F]{40}$/.test(t)?t:null}function dr(e){return new mr("wallet_unavailable",e)}function xi(e){let{evmAccount:t}=H(),{session:r,chainId:s,client:n}=P(),[i,a]=Ie(null),[g,u]=Ie(!1),[c,h]=Ie(null),[o,l]=Ie(!1),[d,f]=Ie(null),m=Gt(null),C=Gt(0),y=Gt(!1);ur(()=>{if(m.current=null,!e?.rpcUrl)return;let k=!1;return import("@naculus/connect-core").then(({SmartAccountManager:T})=>{if(k)return;let b=pr(e.chainId,s);b&&(m.current=new T({rpcUrl:e.rpcUrl,chainId:b,bundlerClient:{url:e.bundlerUrl??""}}))}).catch(T=>{k||f(T instanceof Error?T:new Error("Failed to load account-abstraction module"))}),()=>{k=!0}},[s,e?.rpcUrl,e?.bundlerUrl,e?.chainId]),ur(()=>{C.current+=1,y.current=!1,a(null),u(!1),h(null),l(!1),f(null)},[t,s,e?.rpcUrl,e?.bundlerUrl,e?.chainId,e?.entryPoint,e?.accountType,e?.salt]);let E=ae(()=>{let k=ki(t);if(!k||!m.current)return null;let T=pr(e?.chainId,s);return T?{owner:k,accountType:e?.accountType??"simple",entryPoint:e?.entryPoint??wi[T]?.entryPoint??Ei,chainId:T,salt:e?.salt}:null},[t,s,e?.accountType,e?.chainId,e?.entryPoint,e?.salt]),w=ae(k=>(f(k),null),[]),R=ae(()=>y.current?null:(y.current=!0,C.current),[]),v=ae(k=>{C.current===k&&(y.current=!1)},[]),I=ae(async()=>{let k=E();if(!k||!m.current)return w(new Error("Smart account not configured"));let T=R();if(T===null)return w(new Error("Smart account operation already in progress"));l(!0),f(null);try{let O=await m.current.createAccount(k);return C.current!==T?null:(a(O.address),u(O.isDeployed),h(O),O)}catch(b){if(C.current!==T)return null;let O=b instanceof Error?b:new Error("Failed to create smart account");return f(O),null}finally{C.current===T&&l(!1),v(T)}},[R,w,v,E]),A=ae(async()=>{let k=E();if(!k||!m.current)return w(new Error("Smart account not configured"));if(!r)return w(dr("No active session"));let T=D(n);if(!T)return w(dr("Client not initialized"));if(s&&s!==k.chainId)return w(new mr("chain_mismatch",`Connected chain ${s} does not match smart account chain ${k.chainId}.`));let b=R();if(b===null)return w(new Error("Smart account operation already in progress"));l(!0),f(null);try{let O=m.current,_=await O.createAccount(k);if(C.current!==b)return null;if(_.isDeployed)return a(_.address),u(!0),h(_),_.address;let p=await O.getDeployCallData(k),S=await T.sendTransaction(r,{transaction:{to:p.to,data:p.data,value:p.value.toString()},chainId:k.chainId});if(C.current!==b)return null;let x=await O.createAccount(k);return a(x.address),u(x.isDeployed),h(x),S}catch(O){if(C.current!==b)return null;let _=O instanceof Error?O:new Error("Failed to deploy smart account");return f(_),null}finally{C.current===b&&l(!1),v(b)}},[n,s,R,w,v,E,r]),U=ae(async()=>{let k=E();if(!k||!m.current)return null;let T=C.current;try{let b=await m.current.getAccountAddress(k);return C.current!==T?null:(a(b),b)}catch(b){return C.current!==T||f(b instanceof Error?b:new Error("Failed to get smart account address")),null}},[E]);return{address:i,isDeployed:g,accountInfo:c,isLoading:o,error:d,createWallet:I,deployWallet:A,getAddress:U}}import{useMemo as vi}from"react";function Qt(){let{accounts:e,isConnected:t}=P();return vi(()=>{if(!t)return{address:null,caip10:null,chainId:null,isConnected:!1};let r=e.find(a=>a.startsWith("solana:"))??null;if(!r)return{address:null,caip10:null,chainId:null,isConnected:t};let s=r.split(":"),n=s.length>=3?s[s.length-1]:null,i=s.length>=3?s.slice(0,-1).join(":"):null;return{address:n,caip10:r,chainId:i,isConnected:t}},[e,t])}import{useCallback as bi,useEffect as fr,useRef as Ai,useState as Xt}from"react";import{getSolanaBalance as Ri}from"@naculus/connect-core";function Ti(e={}){let{client:t}=P(),{address:r}=Qt(),s=e.address??r,n=e.rpcUrl??D(t)?.solanaRpcUrl??null,[i,a]=Xt(null),[g,u]=Xt(!1),[c,h]=Xt(null),o=Ai(0),l=bi(async()=>{if(!s||!n){a(null);return}let d=++o.current;u(!0),h(null);try{let f=await Ri(n,s);if(d!==o.current)return;a(f)}catch(f){if(d!==o.current)return;a(null),h(f instanceof Error?f:new Error("Balance read failed"))}finally{d===o.current&&u(!1)}},[s,n]);return fr(()=>{l()},[l]),fr(()=>{if(!e.refreshInterval||e.refreshInterval<=0)return;let d=setInterval(()=>{l()},e.refreshInterval);return()=>clearInterval(d)},[e.refreshInterval,l]),{balance:i,isFetching:g,error:c,isConfigured:!!n,refetch:l}}import{readSolanaRoles as Ii}from"@naculus/connect-appkit-core";import{useMemo as Ui}from"react";function Pi(){let{client:e,session:t,accounts:r}=P();return Ui(()=>{let s=D(e)?.solanaConnector,{roles:n,absence:i}=Ii(s,t);return{roles:n,absence:i,identity:n?.identity??null,signer:n?.signer??null,payer:n?.payer??null}},[e,t,r])}import{WalletError as gr}from"@naculus/connect-core";import{useCallback as Yt,useState as Jt}from"react";import{getSignatureStatus as Wi}from"@naculus/connect-core";function _i(){let{client:e,session:t}=P(),[r,s]=Jt(!1),[n,i]=Jt(!1),[a,g]=Jt(null),u=()=>{let l=D(e);if(!l||!t)throw new gr("wallet_unavailable","No connected wallet.");return l},c=Yt(async l=>{s(!0),g(null);try{return await u().signTransaction(t,{transaction:l})}catch(d){let f=d instanceof Error?d:new Error("Signing failed");throw g(f),f}finally{s(!1)}},[e,t]),h=Yt(async l=>{i(!0),g(null);try{return await u().sendTransaction(t,{transaction:l})}catch(d){let f=d instanceof Error?d:new Error("Send failed");throw g(f),f}finally{i(!1)}},[e,t]),o=Yt(async l=>{let d=D(e)?.solanaRpcUrl;if(!d)throw new gr("no_rpc","Set solanaRpcUrl on the client to read a signature's status.");return Wi(d,l)},[e]);return{signTransaction:c,sendTransaction:h,getStatus:o,isSigning:r,isSending:n,error:a,reset:()=>g(null)}}import{useCallback as hr,useState as yr}from"react";import{toChainSwitchError as Oi}from"@naculus/connect-appkit-core";function Ni(){let{switchChain:e,chainId:t}=P(),[r,s]=yr(!1),[n,i]=yr(null),a=hr(async u=>{s(!0),i(null);try{await e(u)}catch(c){let h=Oi(c);throw i(h),h}finally{s(!1)}},[e]),g=hr(()=>{i(null)},[]);return{switchChain:a,isSwitching:r,currentChainId:t,error:n,clearError:g}}import{chainNumber as Di,resolveChain as Mi,toViemChain as Li}from"@naculus/connect-appkit-core";import{useState as Ze,useEffect as Zt,useCallback as Cr,useMemo as en,useRef as Bi}from"react";import{createPublicClient as Hi,http as Fi,formatUnits as Ki}from"viem";function $i(e){let{evmAccount:t,isConnected:r}=H(),{chainId:s,chains:n}=P(),[i,a]=Ze([]),[g,u]=Ze(!1),[c,h]=Ze(null),{tokens:o,refreshInterval:l}=e,d=Bi(null),f=en(()=>o.map(A=>A.address.toLowerCase()+"|"+A.decimals+"|"+A.symbol).join(","),[o]),m=en(()=>Mi(n,s),[s,n]),C=m?Di(m):null,y=en(()=>m?Li(m,C):null,[m,C]),[E,w]=Ze(null);Zt(()=>{if(!y||!m?.rpcUrl){w(null);return}let A=Hi({transport:Fi(m.rpcUrl),chain:y});w(A)},[m,y]);let R=[{name:"balanceOf",type:"function",stateMutability:"view",inputs:[{name:"owner",type:"address"}],outputs:[{name:"balance",type:"uint256"}]}],v=Cr(async()=>{if(!t||!E||o.length===0){a([]);return}u(!0),h(null);try{let A=t.includes(":")?t.split(":").pop():t,k=(await Promise.allSettled(o.map(async T=>{try{let b=await E.readContract({address:T.address,abi:R,functionName:"balanceOf",args:[A]});return{address:T.address,symbol:T.symbol,decimals:T.decimals,name:T.name,balance:b.toString(),formatted:Ki(b,T.decimals)}}catch{return{address:T.address,symbol:T.symbol,decimals:T.decimals,name:T.name,balance:null,formatted:null}}}))).map(T=>T.status==="fulfilled"?T.value:{address:"",symbol:"?",decimals:0,balance:null,formatted:null});a(k)}catch(A){h(A instanceof Error?A:new Error("Failed to fetch token balances"))}finally{u(!1)}},[t,E,f]);Zt(()=>{r&&t&&o.length>0&&v()},[r,t,f,v]),Zt(()=>(l&&l>0&&r&&t&&o.length>0&&(d.current=setInterval(v,l)),()=>{d.current&&(clearInterval(d.current),d.current=null)}),[l,r,t,f,v]);let I=Cr(A=>i.find(U=>U.address.toLowerCase()===A.toLowerCase()),[i]);return{tokenBalances:i,isLoading:g,error:c,refetch:v,getTokenBalance:I,chain:m}}import{useState as tn,useEffect as Sr,useCallback as qi,useRef as Vi}from"react";function zi(e,t,r){let s=Ae(),n=r??s,[i,a]=tn([]),[g,u]=tn(!1),[c,h]=tn(null),o=Vi(0),l=qi(async()=>{if(n){u(!0),h(null),o.current++;try{let f=await n.getTxHistory(e,t);a(f)}catch(f){h(f instanceof Error?f:new Error(String(f)))}finally{u(!1)}}},[n,e,t]);Sr(()=>{l().catch(()=>{})},[l]),Sr(()=>{if(!n)return;let f=()=>{l().catch(()=>{})};return n.on("statusChange",f),()=>{n.off("statusChange",f)}},[n,l]);let d={pending:i.filter(f=>f.status==="pending").length,confirmed:i.filter(f=>f.status==="confirmed").length,failed:i.filter(f=>f.status==="failed").length};return{entries:i,isLoading:g,error:c,refresh:l,summary:d}}import{useCallback as Ue,useEffect as wr,useRef as me,useState as ie}from"react";var Q=class extends Error{constructor(t){super(t),this.name="InvalidUserOperationReceiptError"}};function Er(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function et(e){return typeof e=="string"&&/^0x[0-9a-fA-F]{40}$/.test(e)}function nn(e){return typeof e=="string"&&/^0x[0-9a-fA-F]{64}$/.test(e)}function ji(e){return typeof e=="string"&&/^0x(?:[0-9a-fA-F]{2})*$/.test(e)}function rn(e,t){if(typeof e!="string"||!/^(?:0x(?:0|[1-9a-fA-F][0-9a-fA-F]*)|(?:0|[1-9][0-9]*))$/.test(e))throw new Q(`Bundler returned an invalid ${t}.`);return BigInt(e)}function Gi(e,t){if(!Er(e))throw new Q("Bundler returned an invalid UserOperation receipt.");if(!nn(e.userOpHash)||e.userOpHash.toLowerCase()!==t.toLowerCase())throw new Q("Bundler receipt does not match the requested UserOperation hash.");if(!et(e.entryPoint)||!et(e.sender))throw new Q("Bundler receipt contains an invalid account address.");if(e.paymaster!==void 0&&e.paymaster!==null&&!et(e.paymaster))throw new Q("Bundler receipt contains an invalid paymaster address.");if(typeof e.success!="boolean"||!nn(e.transactionHash))throw new Q("Bundler receipt contains an invalid execution result.");if(!Array.isArray(e.logs))throw new Q("Bundler receipt contains invalid logs.");let r=e.logs.map(s=>{if(!Er(s)||!et(s.address)||!Array.isArray(s.topics)||!s.topics.every(nn)||!ji(s.data))throw new Q("Bundler receipt contains an invalid log entry.");return{address:s.address,topics:s.topics,data:s.data}});return{userOpHash:e.userOpHash,entryPoint:e.entryPoint,sender:e.sender,nonce:rn(e.nonce,"nonce"),...e.paymaster===void 0||e.paymaster===null?{}:{paymaster:e.paymaster},actualGasUsed:rn(e.actualGasUsed,"actualGasUsed"),actualGasCost:rn(e.actualGasCost,"actualGasCost"),success:e.success,transactionHash:e.transactionHash,logs:r}}function Qi(e){let t=e?.bundlerUrl,r=e?.pollInterval??2e3,s=e?.maxRetries??30,[n,i]=ie("idle"),[a,g]=ie(null),[u,c]=ie(e?.userOpHash??null),[h,o]=ie(null),[l,d]=ie(!1),[f,m]=ie(0),C=me(0),[y,E]=ie(0),w=me(null),R=me(null),v=me(0),I=me(0),A=me(null),U=Ue(()=>{w.current&&(clearInterval(w.current),w.current=null),R.current&&(clearTimeout(R.current),R.current=null)},[]),k=Ue(async(_,p)=>{if(!t||p!==v.current)return;let S=I.current+1;I.current=S,m(S);let x=new AbortController;A.current=x;let W=M=>{p===v.current&&(i("not_found"),d(!1),U(),o(M))},N=M=>{if(p===v.current){if(S<=s){R.current=setTimeout(()=>{k(_,p)},r);return}W(M)}};try{let M=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getUserOperationReceipt",params:[_]}),signal:x.signal});if(p!==v.current)return;if(!M.ok)throw new Error(`Bundler returned HTTP ${M.status} while reading UserOperation status.`);let F=await M.json();if(p!==v.current)return;if(F.error)throw new Error(typeof F.error.message=="string"?F.error.message:"Bundler returned a JSON-RPC error.");if(F.result!==void 0&&F.result!==null){let le=Gi(F.result,_);g(le),i(le.success?"confirmed":"failed"),d(!1),U();return}i("pending"),N(new Error("UserOperation not included after maximum retries"))}catch(M){if(p!==v.current||x.signal.aborted)return;let F=M instanceof Error?M:new Error("Unknown bundler response failure");if(F instanceof Q){W(F);return}N(new Error(`UserOperation status unavailable after ${S} attempt${S===1?"":"s"}: ${F.message}`))}finally{A.current===x&&(A.current=null)}},[t,r,s,U]),T=Ue(_=>{v.current+=1;let p=v.current;if(A.current?.abort(),A.current=null,U(),c(_),g(null),o(null),I.current=0,m(0),E(0),C.current=Date.now(),!t){i("not_found"),d(!1),o(new Error("Bundler URL not configured"));return}i("pending"),d(!0),w.current=setInterval(()=>{E(Date.now()-C.current)},1e3),k(_,p)},[t,U,k]),b=Ue(()=>{v.current+=1,A.current?.abort(),A.current=null,U(),d(!1)},[U]),O=Ue(()=>{v.current+=1,A.current?.abort(),A.current=null,U(),c(null),i("idle"),g(null),o(null),d(!1),I.current=0,m(0),E(0)},[U]);return wr(()=>{e?.userOpHash&&e?.autoStart!==!1&&T(e.userOpHash)},[]),wr(()=>()=>{v.current+=1,A.current?.abort(),A.current=null,U()},[U]),{status:n,receipt:a,userOpHash:u,error:h,isPolling:l,elapsedMs:y,attempts:f,start:T,stop:b,reset:O}}import{useMemo as el}from"react";var Xi={"storage.critical.title":"Insecure Storage Detected","storage.critical.body":"Your browser does not support IndexedDB. Wallet data is stored in plaintext in localStorage and could be exposed to XSS attacks. We strongly recommend switching to a modern browser.","storage.warning.title":"Storage Security Warning","storage.warning.body":"Your browser does not support IndexedDB, but your wallet data is encrypted with AES-256-GCM. Consider switching browsers for better origin isolation.","address.empty":"Address is empty","address.invalid_format":"Invalid address format (expected 0x + 40 hex chars)","address.zero_address":"Address is the zero address \u2014 funds would be permanently lost","address.burn_address":"Address appears to be a burn address \u2014 funds would be permanently lost","wallet.connect":"Connect Wallet","wallet.disconnect":"Disconnect","wallet.connecting":"Connecting...","wallet.copy_address":"Copy address","wallet.copied":"Copied!","wallet.view_on_explorer":"View on Explorer","wallet.retry":"Retry","wallet.connection_failed":"Connection failed","wallet.scan_qr":"Scan with your wallet app","embedded.generate":"Create Wallet","embedded.import":"Import Wallet","embedded.backup_seed":"Back up your seed phrase","embedded.backup_warning":"Anyone with your seed phrase can access your funds. Store it securely.","embedded.backup_done":"I've saved my seed phrase","embedded.wipe":"Remove Wallet","embedded.wipe_confirm":"Are you sure? This cannot be undone."},Yi={"storage.critical.title":"\u5075\u6E2C\u5230\u4E0D\u5B89\u5168\u5132\u5B58","storage.critical.body":"\u60A8\u7684\u700F\u89BD\u5668\u4E0D\u652F\u63F4 IndexedDB\u3002\u9322\u5305\u8CC7\u6599\u4EE5\u660E\u6587\u5132\u5B58\u5728 localStorage \u4E2D\uFF0C\u53EF\u80FD\u66B4\u9732\u65BC XSS \u653B\u64CA\u3002\u5F37\u70C8\u5EFA\u8B70\u66F4\u63DB\u81F3\u73FE\u4EE3\u700F\u89BD\u5668\u3002","storage.warning.title":"\u5132\u5B58\u5B89\u5168\u8B66\u544A","storage.warning.body":"\u60A8\u7684\u700F\u89BD\u5668\u4E0D\u652F\u63F4 IndexedDB\uFF0C\u4F46\u9322\u5305\u8CC7\u6599\u5DF2\u4F7F\u7528 AES-256-GCM \u52A0\u5BC6\u3002\u5EFA\u8B70\u66F4\u63DB\u700F\u89BD\u5668\u4EE5\u7372\u5F97\u66F4\u597D\u7684\u9694\u96E2\u4FDD\u8B77\u3002","address.empty":"\u5730\u5740\u70BA\u7A7A","address.invalid_format":"\u7121\u6548\u7684\u5730\u5740\u683C\u5F0F\uFF08\u61C9\u70BA 0x + 40 \u500B\u5341\u516D\u9032\u4F4D\u5B57\u5143\uFF09","address.zero_address":"\u6B64\u70BA\u96F6\u5730\u5740 \u2014 \u8CC7\u91D1\u5C07\u6C38\u4E45\u4E1F\u5931","address.burn_address":"\u6B64\u5730\u5740\u70BA\u71D2\u6BC0\u5730\u5740 \u2014 \u8CC7\u91D1\u5C07\u6C38\u4E45\u4E1F\u5931","wallet.connect":"\u9023\u63A5\u9322\u5305","wallet.disconnect":"\u65B7\u958B\u9023\u7DDA","wallet.connecting":"\u9023\u7DDA\u4E2D...","wallet.copy_address":"\u8907\u88FD\u5730\u5740","wallet.copied":"\u5DF2\u8907\u88FD\uFF01","wallet.view_on_explorer":"\u5728\u700F\u89BD\u5668\u67E5\u770B","wallet.retry":"\u91CD\u8A66","wallet.connection_failed":"\u9023\u7DDA\u5931\u6557","wallet.scan_qr":"\u4F7F\u7528\u9322\u5305 App \u6383\u63CF","embedded.generate":"\u5EFA\u7ACB\u9322\u5305","embedded.import":"\u532F\u5165\u9322\u5305","embedded.backup_seed":"\u5099\u4EFD\u52A9\u8A18\u8A5E","embedded.backup_warning":"\u4EFB\u4F55\u4EBA\u53D6\u5F97\u60A8\u7684\u52A9\u8A18\u8A5E\u90FD\u53EF\u4EE5\u5B58\u53D6\u60A8\u7684\u8CC7\u91D1\u3002\u8ACB\u5B89\u5168\u5132\u5B58\u3002","embedded.backup_done":"\u6211\u5DF2\u5132\u5B58\u52A9\u8A18\u8A5E","embedded.wipe":"\u79FB\u9664\u9322\u5305","embedded.wipe_confirm":"\u78BA\u5B9A\u8981\u79FB\u9664\u55CE\uFF1F\u6B64\u64CD\u4F5C\u7121\u6CD5\u5FA9\u539F\u3002"},kr={en:Xi,zh:Yi},on="en";function Ji(e){on=e}function Zi(){return on}function fe(e){return kr[on][e]??kr.en[e]??e}var xr="0x0000000000000000000000000000000000000000",tl=new Set([xr,"0x0000000000000000000000000000000000000001","0x000000000000000000000000000000000000dead","0x000000000000000000000000000000000000dEaD"]);function nl(e){let t=e.toLowerCase();return tl.has(t)?!0:t.includes("dead")&&t.length>=40}function rl(e){return e===xr}function ol(e){return/^0x[0-9a-fA-F]{40}$/.test(e)}function vr(e){return e?ol(e)?rl(e)?{isValid:!1,level:"blocked",warning:fe("address.zero_address")}:nl(e)?{isValid:!1,level:"blocked",warning:fe("address.burn_address")}:{isValid:!0,level:"ok",warning:null}:{isValid:!1,level:"blocked",warning:fe("address.invalid_format")}:{isValid:!1,level:"blocked",warning:fe("address.empty")}}function sl({address:e}){return{validation:el(()=>vr(e),[e])}}function al(){let{status:e,session:t,accounts:r,chainId:s,error:n,connect:i,disconnect:a,reconnect:g,switchChain:u}=P(),c=e==="connected",h=e==="connecting",o=e==="reconnecting",l=r[0]??null;return{status:e,session:t,accounts:r,chainId:s,error:n,isConnected:c,isConnecting:h,isReconnecting:o,isDisconnected:e==="disconnected",currentAccount:l,connect:i,disconnect:a,reconnect:g,switchChain:u}}import{useCallback as an,useMemo as Rr}from"react";var br={wallet_unavailable:"Wallet Not Detected",user_rejected:"Connection Rejected",deeplink_timeout:"Wallet Connection Timed Out",session_expired:"Session Expired",intent_expired:"Connection Request Expired",namespace_mismatch:"Network Mismatch",chain_unsupported:"Unsupported Network",method_not_allowed:"Action Not Allowed",signature_rejected:"Signature Rejected",tx_failed:"Transaction Failed"},Ar={wallet_unavailable:"No wallet found. Please install a compatible wallet (e.g., MetaMask, WalletConnect) and try again.",user_rejected:"The connection request was declined in your wallet. You can try again whenever you're ready.",deeplink_timeout:"The wallet didn't respond in time. This can happen if the wallet app isn't installed or takes too long to open.",session_expired:"Your wallet session has expired. Please reconnect to continue.",intent_expired:"The connection request expired. Please try connecting again.",namespace_mismatch:"This wallet doesn't support the required network. Try using a different wallet or network.",chain_unsupported:"This network isn't supported. Please switch to a supported network in your wallet.",method_not_allowed:"This action isn't supported by your current wallet or network.",signature_rejected:"The signature request was declined in your wallet.",tx_failed:"The transaction couldn't be completed. This could be due to insufficient funds, network congestion, or a contract error."},Pe="Something went wrong",We="An unexpected error occurred. Please try again. If the problem persists, check your connection and wallet configuration.";function _e(e){if(!e)return{title:Pe,description:We};let t=e;if(t.name==="WalletError"&&t.code){let r=t.code,s=br[r]??Pe,n=Ar[r]??t.message??We;return{title:s,description:n,code:r}}if(e instanceof Error){let r=e.message;return/user rejected/i.test(r)||/rejected/.test(r)?{title:"Request Rejected",description:"The request was declined.",code:"user_rejected"}:/timeout/i.test(r)||/timed? ?out/i.test(r)?{title:"Request Timed Out",description:"The request took too long. Please try again.",code:"deeplink_timeout"}:/insufficient funds/i.test(r)?{title:"Insufficient Funds",description:"You don't have enough funds to complete this transaction.",code:"tx_failed"}:/network/i.test(r)||/chain/i.test(r)?{title:"Network Error",description:r,code:"chain_unsupported"}:{title:Pe,description:r||We}}return typeof e=="string"?{title:Pe,description:e||We}:{title:Pe,description:We}}function sn(e){if(e===null||typeof e!="object")return!1;let t=e;return t.name!=="WalletError"||!t.code?!1:["deeplink_timeout","session_expired","intent_expired","tx_failed"].includes(t.code)}function il(){let{error:e,clearError:t}=P(),r=Rr(()=>e?_e(e):null,[e]),s=Rr(()=>e?sn(e):!1,[e]),n=an(()=>{t()},[t]),i=an(g=>_e(g),[]),a=an(g=>async()=>{try{return await g()}catch(u){let c=_e(u);if(u instanceof Error){let h=u;try{h.title=c.title,h.friendlyMessage=c.description,h.code===void 0&&c.code!==void 0&&(h.code=c.code)}catch{}throw h}throw Object.assign(new Error(c.description,{cause:u}),{title:c.title,code:c.code,friendlyMessage:c.description})}},[]);return{error:e,friendlyError:r,clearError:n,isRetryable:s,formatError:i,wrapAsync:a}}import{useState as tt,useEffect as ll,useCallback as Tr,useRef as cl}from"react";import{TokenListManager as ul}from"@naculus/connect-core";import{eip155ChainIdToNumber as Ir}from"@naculus/connect-appkit-core";function nt(e,t){let r=cl(null),[s,n]=tt([]),[i,a]=tt(t?.autoLoad!==!1),[g,u]=tt(!1),[c,h]=tt(null);if(!r.current){let d={};t?.sources&&(d.sources=t.sources),r.current=new ul(d)}let o=Tr(async()=>{let d=r.current;if(d){a(!0),h(null);try{await d.load();let f=e?Ir(e):void 0,m=d.getTokens(f!==void 0?{chainId:f}:void 0);n(m),u(!0)}catch(f){h(f instanceof Error?f:new Error(String(f)))}finally{a(!1)}}},[e]),l=Tr(async()=>{let d=r.current;if(d){a(!0),h(null);try{await d.refresh();let f=e?Ir(e):void 0,m=d.getTokens(f!==void 0?{chainId:f}:void 0);n(m),u(!0)}catch(f){h(f instanceof Error?f:new Error(String(f)))}finally{a(!1)}}},[e]);return ll(()=>{t?.autoLoad!==!1&&o()},[o,t?.autoLoad]),{tokens:s,isLoading:i,isLoaded:g,error:c,refetch:l}}import{useState as Pr,useEffect as hl,useRef as yl}from"react";import{TokenListManager as Cl}from"@naculus/connect-core";import{ETHEREUM_MAINNET_TOKENS as pl,POLYGON_TOKENS as dl,OPTIMISM_TOKENS as ml,ARBITRUM_TOKENS as fl,BASE_TOKENS as gl}from"@naculus/connect-core";function Ur(){return[{name:"built-in",tokens:[...pl,...dl,...ml,...fl,...gl],enabled:!0},{name:"uniswap-default",url:"https://tokens.uniswap.org",enabled:!0,refreshInterval:1440*60*1e3}]}import{eip155ChainIdToNumber as Sl}from"@naculus/connect-appkit-core";var wl=300,rt=null;function El(){return rt||(rt=new Cl({sources:Ur()}),rt.load().catch(()=>{})),rt}function ot(e,t){let[r,s]=Pr({exact:[],fuzzy:[],hasMore:!1}),[n,i]=Pr(!1),a=yl(null),g=e.trim();return hl(()=>{if(!g){s({exact:[],fuzzy:[],hasMore:!1}),i(!1);return}return a.current&&clearTimeout(a.current),i(!0),a.current=setTimeout(()=>{let u=El(),c=t?Sl(t):void 0,h=u.search(g,{chainId:c,limit:20});s(h),i(!1)},wl),()=>{a.current&&clearTimeout(a.current)}},[g,t]),{results:r,isSearching:n}}import ln,{useCallback as kl}from"react";import{Fragment as xl,jsx as j,jsxs as X}from"react/jsx-runtime";function Wr({chainId:e,onSelect:t,onClose:r,options:s}){let[n,i]=ln.useState(""),{tokens:a,isLoading:g,error:u}=nt(e),{results:c,isSearching:h}=ot(n,n?e:void 0),o=s?.showRecommendations??!0,l=ln.useMemo(()=>{if(n.trim()){let C=[...c.exact,...c.fuzzy].map(y=>y.token);return s?.filter?C.filter(s.filter):C}let m=a;return s?.filter?m.filter(s.filter):m},[n,c,a,s?.filter]),d=ln.useMemo(()=>!o||n.trim()?[]:a.slice(0,6),[a,o,n]),f=kl(m=>{t(m),r()},[t,r]);return X("div",{style:{background:"hsl(var(--background))",borderRadius:"12px",padding:"16px",color:"hsl(var(--foreground))",minWidth:"320px",maxWidth:"400px",fontFamily:"system-ui, sans-serif"},children:[X("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"12px"},children:[j("h3",{style:{margin:0,fontSize:"16px",fontWeight:600},children:"Select Token"}),j("button",{onClick:r,style:{background:"none",border:"none",color:"hsl(var(--muted-foreground))",cursor:"pointer",fontSize:"18px",padding:"4px 8px"},children:"\u2715"})]}),j("input",{type:"text",placeholder:"Search token name or paste address",value:n,onChange:m=>i(m.target.value),style:{width:"100%",padding:"10px 12px",borderRadius:"8px",border:"1px solid #333",background:"hsl(var(--card))",color:"hsl(var(--foreground))",fontSize:"14px",outline:"none",boxSizing:"border-box",marginBottom:"12px"},autoFocus:!0}),g&&!h&&j("div",{style:{textAlign:"center",padding:"20px",color:"hsl(var(--muted-foreground))"},children:"Loading tokens..."}),u&&X("div",{style:{textAlign:"center",padding:"12px",color:"hsl(var(--destructive))",fontSize:"13px"},children:["Error: ",u.message]}),o&&d.length>0&&!n.trim()&&X("div",{style:{marginBottom:"12px"},children:[j("div",{style:{fontSize:"11px",color:"hsl(var(--muted-foreground))",textTransform:"uppercase",letterSpacing:"0.5px",marginBottom:"8px"},children:"Popular"}),j("div",{style:{display:"flex",gap:"6px",flexWrap:"wrap"},children:d.map(m=>X("button",{onClick:()=>f(m),style:{background:"hsl(var(--card))",border:"1px solid #333",borderRadius:"20px",padding:"6px 14px",color:"hsl(var(--foreground))",cursor:"pointer",fontSize:"13px",display:"flex",alignItems:"center",gap:"4px"},children:[m.logoURI?j("img",{src:m.logoURI,alt:"",style:{width:"16px",height:"16px",borderRadius:"50%"},onError:C=>{C.target.style.display="none"}}):null,m.symbol]},`${m.chainId}:${m.address}`))})]}),n.trim()&&!g&&j("div",{style:{fontSize:"11px",color:"hsl(var(--muted-foreground))",marginBottom:"8px"},children:l.length>0?X(xl,{children:[c.exact.length," exact, ",c.fuzzy.length," fuzzy",c.hasMore?" (more available)":""]}):"No results found"}),j("div",{style:{maxHeight:"320px",overflowY:"auto",display:"flex",flexDirection:"column",gap:"2px"},children:l.map(m=>X("button",{onClick:()=>f(m),style:{display:"flex",alignItems:"center",gap:"10px",padding:"10px 8px",background:"transparent",border:"none",borderRadius:"8px",color:"hsl(var(--foreground))",cursor:"pointer",textAlign:"left",width:"100%",fontSize:"14px"},onMouseEnter:C=>{C.target.style.background="hsl(var(--card))"},onMouseLeave:C=>{C.target.style.background="transparent"},children:[j("div",{style:{width:"32px",height:"32px",borderRadius:"50%",background:"hsl(var(--border))",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:600,flexShrink:0,overflow:"hidden"},children:m.logoURI?j("img",{src:m.logoURI,alt:m.symbol,style:{width:"100%",height:"100%"},onError:C=>{let y=C.target;y.style.display="none",y.parentElement.textContent=m.symbol.slice(0,2)}}):m.symbol.slice(0,2)}),X("div",{style:{flex:1,minWidth:0},children:[j("div",{style:{fontWeight:600,fontSize:"14px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m.symbol}),j("div",{style:{fontSize:"12px",color:"hsl(var(--muted-foreground))",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m.name})]}),X("div",{style:{fontSize:"11px",color:"#666",textAlign:"right",flexShrink:0},children:[X("div",{children:[m.decimals," decimals"]}),X("div",{children:["Chain ",m.chainId]})]})]},`${m.chainId}:${m.address}`))})]})}import{createComponent as L}from"@stencil/react-output-target/runtime";import B from"react";import{AppkitAccordion as vl,defineCustomElement as bl}from"@naculus/connect-appkit-wc/dist/components/appkit-accordion.js";import{AppkitAccountButton as Al,defineCustomElement as Rl}from"@naculus/connect-appkit-wc/dist/components/appkit-account-button.js";import{AppkitAlertDialog as Tl,defineCustomElement as Il}from"@naculus/connect-appkit-wc/dist/components/appkit-alert-dialog.js";import{AppkitAvatar as Ul,defineCustomElement as Pl}from"@naculus/connect-appkit-wc/dist/components/appkit-avatar.js";import{AppkitBadge as Wl,defineCustomElement as _l}from"@naculus/connect-appkit-wc/dist/components/appkit-badge.js";import{AppkitButton as Ol,defineCustomElement as Nl}from"@naculus/connect-appkit-wc/dist/components/appkit-button.js";import{AppkitCardContent as Dl,defineCustomElement as Ml}from"@naculus/connect-appkit-wc/dist/components/appkit-card-content.js";import{AppkitCardDescription as Ll,defineCustomElement as Bl}from"@naculus/connect-appkit-wc/dist/components/appkit-card-description.js";import{AppkitCardFooter as Hl,defineCustomElement as Fl}from"@naculus/connect-appkit-wc/dist/components/appkit-card-footer.js";import{AppkitCardHeader as Kl,defineCustomElement as $l}from"@naculus/connect-appkit-wc/dist/components/appkit-card-header.js";import{AppkitCardTitle as ql,defineCustomElement as Vl}from"@naculus/connect-appkit-wc/dist/components/appkit-card-title.js";import{AppkitCard as zl,defineCustomElement as jl}from"@naculus/connect-appkit-wc/dist/components/appkit-card.js";import{AppkitCheckbox as Gl,defineCustomElement as Ql}from"@naculus/connect-appkit-wc/dist/components/appkit-checkbox.js";import{AppkitCollapsible as Xl,defineCustomElement as Yl}from"@naculus/connect-appkit-wc/dist/components/appkit-collapsible.js";import{AppkitConnectButton as Jl,defineCustomElement as Zl}from"@naculus/connect-appkit-wc/dist/components/appkit-connect-button.js";import{AppkitDialog as ec,defineCustomElement as tc}from"@naculus/connect-appkit-wc/dist/components/appkit-dialog.js";import{AppkitDropdownMenu as nc,defineCustomElement as rc}from"@naculus/connect-appkit-wc/dist/components/appkit-dropdown-menu.js";import{AppkitInput as oc,defineCustomElement as sc}from"@naculus/connect-appkit-wc/dist/components/appkit-input.js";import{AppkitPopover as ac,defineCustomElement as ic}from"@naculus/connect-appkit-wc/dist/components/appkit-popover.js";import{AppkitProgress as lc,defineCustomElement as cc}from"@naculus/connect-appkit-wc/dist/components/appkit-progress.js";import{AppkitScrollArea as uc,defineCustomElement as pc}from"@naculus/connect-appkit-wc/dist/components/appkit-scroll-area.js";import{AppkitSelect as dc,defineCustomElement as mc}from"@naculus/connect-appkit-wc/dist/components/appkit-select.js";import{AppkitSeparator as fc,defineCustomElement as gc}from"@naculus/connect-appkit-wc/dist/components/appkit-separator.js";import{AppkitSkeleton as hc,defineCustomElement as yc}from"@naculus/connect-appkit-wc/dist/components/appkit-skeleton.js";import{AppkitSwitch as Cc,defineCustomElement as Sc}from"@naculus/connect-appkit-wc/dist/components/appkit-switch.js";import{AppkitTabs as wc,defineCustomElement as Ec}from"@naculus/connect-appkit-wc/dist/components/appkit-tabs.js";import{AppkitToggleGroup as kc,defineCustomElement as xc}from"@naculus/connect-appkit-wc/dist/components/appkit-toggle-group.js";import{AppkitTooltip as vc,defineCustomElement as bc}from"@naculus/connect-appkit-wc/dist/components/appkit-tooltip.js";var Ac=L({tagName:"appkit-accordion",elementClass:vl,react:B,events:{onAppkitToggle:"appkitToggle"},defineCustomElement:bl}),Rc=L({tagName:"appkit-account-button",elementClass:Al,react:B,events:{},defineCustomElement:Rl}),Tc=L({tagName:"appkit-alert-dialog",elementClass:Tl,react:B,events:{onAppkitClose:"appkitClose",onAppkitOpenChange:"appkitOpenChange"},defineCustomElement:Il}),Ic=L({tagName:"appkit-avatar",elementClass:Ul,react:B,events:{},defineCustomElement:Pl}),Uc=L({tagName:"appkit-badge",elementClass:Wl,react:B,events:{},defineCustomElement:_l}),Pc=L({tagName:"appkit-button",elementClass:Ol,react:B,events:{},defineCustomElement:Nl}),Wc=L({tagName:"appkit-card",elementClass:zl,react:B,events:{},defineCustomElement:jl}),_c=L({tagName:"appkit-card-content",elementClass:Dl,react:B,events:{},defineCustomElement:Ml}),Oc=L({tagName:"appkit-card-description",elementClass:Ll,react:B,events:{},defineCustomElement:Bl}),Nc=L({tagName:"appkit-card-footer",elementClass:Hl,react:B,events:{},defineCustomElement:Fl}),Dc=L({tagName:"appkit-card-header",elementClass:Kl,react:B,events:{},defineCustomElement:$l}),Mc=L({tagName:"appkit-card-title",elementClass:ql,react:B,events:{},defineCustomElement:Vl}),Lc=L({tagName:"appkit-checkbox",elementClass:Gl,react:B,events:{onAppkitChange:"appkitChange"},defineCustomElement:Ql}),Bc=L({tagName:"appkit-collapsible",elementClass:Xl,react:B,events:{onAppkitToggle:"appkitToggle"},defineCustomElement:Yl}),Hc=L({tagName:"appkit-connect-button",elementClass:Jl,react:B,events:{onAppkitConnect:"appkitConnect",onAppkitDisconnect:"appkitDisconnect",onAppkitStartPairing:"appkitStartPairing",onAppkitRetry:"appkitRetry",onAppkitCancelPairing:"appkitCancelPairing",onAppkitMobileDeepLink:"appkitMobileDeepLink",onAppkitCopyAddress:"appkitCopyAddress"},defineCustomElement:Zl}),Fc=L({tagName:"appkit-dialog",elementClass:ec,react:B,events:{onAppkitClose:"appkitClose",onAppkitOpenChange:"appkitOpenChange"},defineCustomElement:tc}),Kc=L({tagName:"appkit-dropdown-menu",elementClass:nc,react:B,events:{onAppkitSelect:"appkitSelect"},defineCustomElement:rc}),$c=L({tagName:"appkit-input",elementClass:oc,react:B,events:{onAppkitChange:"appkitChange"},defineCustomElement:sc}),qc=L({tagName:"appkit-popover",elementClass:ac,react:B,events:{onAppkitOpenChange:"appkitOpenChange"},defineCustomElement:ic}),Vc=L({tagName:"appkit-progress",elementClass:lc,react:B,events:{},defineCustomElement:cc}),zc=L({tagName:"appkit-scroll-area",elementClass:uc,react:B,events:{},defineCustomElement:pc}),jc=L({tagName:"appkit-select",elementClass:dc,react:B,events:{onAppkitChange:"appkitChange"},defineCustomElement:mc}),Gc=L({tagName:"appkit-separator",elementClass:fc,react:B,events:{},defineCustomElement:gc}),Qc=L({tagName:"appkit-skeleton",elementClass:hc,react:B,events:{},defineCustomElement:yc}),Xc=L({tagName:"appkit-switch",elementClass:Cc,react:B,events:{onAppkitChange:"appkitChange"},defineCustomElement:Sc}),Yc=L({tagName:"appkit-tabs",elementClass:wc,react:B,events:{onAppkitTabChange:"appkitTabChange"},defineCustomElement:Ec}),Jc=L({tagName:"appkit-toggle-group",elementClass:kc,react:B,events:{onAppkitChange:"appkitChange"},defineCustomElement:xc}),Zc=L({tagName:"appkit-tooltip",elementClass:vc,react:B,events:{},defineCustomElement:bc});export{Ac as AppkitAccordion,Rc as AppkitAccountButton,Tc as AppkitAlertDialog,Ic as AppkitAvatar,Uc as AppkitBadge,Pc as AppkitButton,Wc as AppkitCard,_c as AppkitCardContent,Oc as AppkitCardDescription,Nc as AppkitCardFooter,Dc as AppkitCardHeader,Mc as AppkitCardTitle,Lc as AppkitCheckbox,Bc as AppkitCollapsible,Hc as AppkitConnectButton,Fc as AppkitDialog,Kc as AppkitDropdownMenu,$c as AppkitInput,qc as AppkitPopover,Vc as AppkitProgress,zc as AppkitScrollArea,jc as AppkitSelect,Gc as AppkitSeparator,Qc as AppkitSkeleton,Xc as AppkitSwitch,Yc as AppkitTabs,Jc as AppkitToggleGroup,Zc as AppkitTooltip,wn as DEFAULT_EVM_CHAINS,Rh as LAMPORTS_PER_SOL,Th as PassphraseCancelledError,Ih as PassphraseGate,Ph as SolanaRpcError,Wr as TokenSelector,qn as TxMonitorContext,Ar as WALLET_ERROR_DESCRIPTIONS,br as WALLET_ERROR_TITLES,co as Web3ConnectProvider,ft as Web3Context,ke as buildDelegationPolicyMessage,Hr as clearClient,pt as createClient,xh as formatSol,Jr as getChainById,dt as getClient,mt as getDefaultChains,vh as getLatestBlockhash,Zi as getLocale,bh as getSignatureStatus,Ah as getSolanaBalance,_e as getUserFriendlyError,sn as isRetryableError,Uh as parseSol,ss as resetSessionKeyManager,Ji as setLocale,fe as t,H as useAccount,xo as useBalance,yt as useCapabilities,z as useChain,dn as useCompareCosts,No as useConnect,ns as useCreateSessionKey,Se as useDelegation,us as useDelegationPolicy,ms as useDisconnect,Ts as useERC20Allowance,Ds as useERC20Approve,Gs as useERC20Transfer,ia as useERC20TransferSimulation,gs as useEmbeddedWallet,vt as useExecuteCalls,gn as useExecuteRoute,fa as useLastTx,Sa as useLookupAddress,ba as useNotification,Ta as usePassphraseGate,Ua as useResolveName,rs as useRevokeSession,Cn as useRouteQuote,Kt as useSIWxLogin,Za as useSIWxSession,kt as useSendCalls,xe as useSendTransaction,Da as useSendUserOperation,os as useSendWithSession,Fa as useSession,At as useSessionKeys,li as useSignInWithEthereum,Te as useSignInWithX,Tt as useSignMessage,di as useSimulateTransfer,Si as useSiwxAuthSession,xi as useSmartAccount,Qt as useSolanaAccount,Ti as useSolanaBalance,Pi as useSolanaRoles,_i as useSolanaTransaction,Ni as useSwitchChain,$i as useTokenBalance,nt as useTokenList,ot as useTokenSearch,Ot as useTransactionSimulation,zi as useTxHistory,da as useTxMonitor,Qi as useUserOpStatus,sl as useValidateDestination,G as useViemClient,al as useWallet,P as useWeb3,il as useWeb3ErrorHandler,vr as validateDestination};
|
|
3
3
|
//# sourceMappingURL=index.js.map
|