@naculus/connect-appkit-react 0.2.4 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,2 @@
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};
1
+ import{formatSol as aC,getLatestBlockhash as iC,getSignatureStatus as lC,getSolanaBalance as cC,LAMPORTS_PER_SOL as uC,PassphraseCancelledError as pC,PassphraseGate as dC,parseSol as mC,SolanaRpcError as fC}from"@naculus/connect-core";import{compareCostsKey as hr}from"@naculus/connect-appkit-core";import{useCallback as Xt,useEffect as Yt,useRef as Jt,useState as Qe}from"react";function Zt(e,t){let{operation:o,chains:s,options:n}=e,[l,a]=Qe([]),[C,u]=Qe(!1),[c,g]=Qe(null),r=Jt(!0),i=Jt(0),p=hr(e),f=Xt(async()=>{if(!s||s.length===0){a([]);return}if(!t)return;let S=++i.current;u(!0),g(null);try{let h=await t(o,s,n);r.current&&S===i.current&&a(h)}catch(h){r.current&&S===i.current&&(g(h instanceof Error?h:new Error(String(h))),a([]))}finally{r.current&&S===i.current&&u(!1)}},[p,t]);Yt(()=>{f()},[f]),Yt(()=>(r.current=!0,()=>{r.current=!1}),[]);let d=Xt(async()=>{await f()},[f]);return{comparisons:l,loading:C,error:c,refresh:d}}import{toExecuteRouteError as yr,validateRouteRecipient as Sr}from"@naculus/connect-appkit-core";import{useCallback as en,useEffect as Er,useRef as tn,useState as Xe}from"react";function nn(e){let[t,o]=Xe(!1),[s,n]=Xe(null),[l,a]=Xe(null),C=tn(!0),u=tn(!1);Er(()=>(C.current=!0,()=>{C.current=!1}),[]);let c=en(async(r,i,p)=>{if(!e)return a({code:"no_executor",message:"No executeRoute function provided"}),n(null),null;let f=Sr(r,i);if(f)return a(f),n(null),null;if(u.current)return a({code:"execution_in_progress",message:"A route execution is already in progress"}),null;u.current=!0,o(!0),a(null),n(null);try{let d=await e(r,i,p);return C.current&&n(d),d}catch(d){return C.current&&a(yr(d)),null}finally{u.current=!1,C.current&&o(!1)}},[e]),g=en(()=>{n(null),a(null),o(!1)},[]);return{execute:c,executing:t,result:s,error:l,reset:g}}import{isQuotableInput as wr}from"@naculus/connect-appkit-core";import{useCallback as Ye,useEffect as rn,useRef as on,useState as Je}from"react";function sn(e,t){let{fromChain:o,toChain:s,fromToken:n,toToken:l,amount:a,options:C}=e,[u,c]=Je([]),[g,r]=Je(!1),[i,p]=Je(null),f=on(null),d=on(!0),S=Ye(async()=>{if(!wr({fromChain:o,toChain:s,fromToken:n,amount:a})){c([]);return}if(t){r(!0),p(null);try{let E=await t(o,s,n,a,C,l);d.current&&c(E)}catch(E){d.current&&(p(E instanceof Error?E:new Error(String(E))),c([]))}finally{d.current&&r(!1)}}},[o,s,n,l,a,C,t]);rn(()=>{if(f.current&&clearTimeout(f.current),!o||!s||!n||!a){c([]);return}return f.current=setTimeout(()=>{S()},300),()=>{f.current&&clearTimeout(f.current)}},[S,o,s,n,a]),rn(()=>(d.current=!0,()=>{d.current=!1}),[]);let h=Ye(async()=>{await S()},[S]),w=Ye(()=>{c([]),p(null),r(!1)},[]);return{quotes:u,loading:g,error:i,refresh:h,clear:w}}import{logger as Ze,WalletError as K}from"@naculus/connect-core";import{eip6963Connector as q}from"@naculus/connector-evm-injected";import{PassphraseGate as kr}from"@naculus/connect-core";import{createWalletConnectConnector as xr}from"@naculus/connector-walletconnect";var et=null;function tt(e){let t=null,o=xr({projectId:e.projectId,metadata:e.metadata}),s=null,n=null,l=null,a=null,C=e.passphrasePrompt&&e.enableEmbedded&&!e.embeddedConfig?.encryptionPassphrase?new kr:null;e.enableEmbedded&&(n=import("@naculus/connector-embedded").then(r=>{let i={...e.embeddedConfig};C&&(i.encryptionPassphrase=C.request),e.enablePasskeys&&i.encryptionPassphrase&&!i.prfUnlock&&(i.prfUnlock={async derive(f){a&&await a;let d=l;return d?.hasCredential()?d.derivePrfKey(f):null}}),s=r.createPocketConnector(i),t?._setEmbeddedConnector(s)}).catch(r=>{Ze.warn("react/client","Embedded wallet connector not available:",r),s=null})),e.enablePasskeys&&(a=import("@naculus/connector-passkeys").then(r=>{l=r.createPasskeysConnector(),t?._setPasskeysConnector(l)}).catch(r=>{Ze.warn("react/client","Passkeys connector not available:",r),l=null}));let u=null,c=null;e.enableSolana&&(c=import("@naculus/connector-solana").then(r=>{let i=r.solanaConnector;e.solanaDefaultChain&&"configure"in i&&i.configure({defaultChain:e.solanaDefaultChain}),u=i,typeof window<"u"&&"startDiscovery"in i&&i.startDiscovery(),t?._setSolanaConnector(u)}).catch(r=>{Ze.warn("react/client","Solana connector not available:",r),u=null})),typeof window<"u"&&q.startDiscovery();let g={connector:o,get embeddedConnector(){return s},getEmbeddedConnector:async()=>(n&&await n,s),get passkeysConnector(){return l},passphraseGate:C,solanaRpcUrl:e.solanaRpcUrl??null,get solanaConnector(){return u},connect:()=>o.connect(),connectInjected:async r=>q.connect(r),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,!l)throw new Error("Passkeys connector not enabled. Set enablePasskeys: true in config.");return l.connect()},startPairing:()=>o.startPairing(),completePairing:()=>o.completePairing(),cancelPairing:()=>o.cancelPairing?.(),signMessage:async(r,i)=>{if(r.id?.startsWith("eip6963-"))return q.signMessage(r,i);if(r.walletType==="passkeys"&&l)return l.signMessage(r,i);if(r.walletType==="embedded"){if(!s)throw new K("wallet_unavailable","Embedded wallet connector not available.");return s.signMessage(r,i)}if(r.walletType==="solana"){if(c&&await c,u)return u.signMessage(r,i);throw new K("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}return o.signMessage(r,i)},signTransaction:async(r,i)=>{if(r.id?.startsWith("eip6963-"))return q.signTransaction(r,i);if(r.walletType==="embedded"){if(!s)throw new K("wallet_unavailable","Embedded wallet connector not available.");return s.signTransaction(r,i)}if(r.walletType==="solana"){if(c&&await c,u)return u.signTransaction(r,i);throw new K("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}return o.signTransaction(r,i)},sendTransaction:async(r,i)=>{if(r.id?.startsWith("eip6963-"))return q.sendTransaction(r,i);if(r.walletType==="passkeys"&&l)return l.sendTransaction(r,i);if(r.walletType==="embedded"){if(!s)throw new K("wallet_unavailable","Embedded wallet connector not available.");return s.sendTransaction(r,i)}if(r.walletType==="solana"){if(c&&await c,u)return u.sendTransaction(r,i);throw new K("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}return o.sendTransaction(r,i)},onAccountsChanged:(r,i)=>{let p=()=>{};return r.id?.startsWith("eip6963-")?q.onAccountsChanged?.(r,i)??p:r.walletType==="embedded"?s?.onAccountsChanged?.(r,i)??p:r.walletType==="passkeys"?p:r.walletType==="solana"?u?.onAccountsChanged?.(r,i)??p:o.onAccountsChanged?.(r,i)??p},onChainChanged:(r,i)=>{let p=()=>{};return r.id?.startsWith("eip6963-")?q.onChainChanged?.(r,i)??p:r.walletType==="passkeys"||r.walletType==="embedded"?p:r.walletType==="solana"?u?.onChainChanged?.(r,i)??p:o.onChainChanged?.(r,i)??p},getCapabilities:r=>r.id?.startsWith("eip6963-")?q.getCapabilities?.(r):r.walletType==="passkeys"?l?.getCapabilities?.(r):r.walletType==="solana"?u?.getCapabilities?.(r):r.walletType==="embedded"?s?.getCapabilities?.(r):o.getCapabilities?.(r),sendCalls:async(r,i,p,f)=>{if(r.id?.startsWith("eip6963-"))return q.sendCalls(r,i,p,f);if(r.walletType==="passkeys"&&l)return l.sendCalls(r,i,p,f);if(r.walletType==="solana"){if(c&&await c,u)return u.sendCalls(r,i,p,f);throw new K("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}if(r.walletType==="embedded"){if(!s?.sendCalls)throw new K("method_not_allowed","Embedded wallet does not support sendCalls");return s.sendCalls(r,i,p,f)}if(!o.sendCalls)throw new K("method_not_allowed","sendCalls not supported by this connector");return o.sendCalls(r,i,p,f)},showCallsStatus:async(r,i)=>{if(r.id?.startsWith("eip6963-"))return q.showCallsStatus(r,i);if(r.walletType==="passkeys"||r.walletType==="embedded")throw new K("method_unsupported",`${r.walletType} wallets have no UI to display a call bundle.`);if(!o.showCallsStatus)throw new K("method_unsupported","This connector cannot display call status.");return o.showCallsStatus(r,i)},getCallsStatus:async(r,i)=>{if(r.id?.startsWith("eip6963-")&&q.getCallsStatus)return q.getCallsStatus(r,i);if(r.walletType==="passkeys"&&l?.getCallsStatus)return l.getCallsStatus(r,i);if(r.walletType==="embedded")throw new K("method_not_allowed","Embedded wallet does not support getCallsStatus");if(!o.getCallsStatus)throw new K("method_not_allowed","getCallsStatus not supported by this connector");return o.getCallsStatus(r,i)},reconnect:async r=>r.walletType==="eip6963"?q.reconnect(r):r.walletType==="embedded"?s?s.reconnect(r):r:r.walletType==="solana"?r:o.reconnect(r),disconnect:async r=>{if(r.id?.startsWith("eip6963-")||r.walletType==="eip6963")return q.disconnect(r);if(r.walletType==="embedded"&&s)return s.disconnect();if(r.walletType==="passkeys"&&l)return l.disconnect(r);if(r.walletType==="solana"){if(c&&await c,u)return u.disconnect(r);throw new K("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}return o.disconnect(r)},getAllConnectors:()=>{let r=[o];return s&&r.push(s),l&&r.push(l),u&&r.push(u),r},_setEmbeddedConnector:r=>{s=r},_setPasskeysConnector:r=>{l=r},_setSolanaConnector:r=>{u=r}};return t=g,et=g,g}function nt(){return et}function vr(){et=null}import{isEvmAddress as pn,parseCaip10 as Qr}from"@naculus/connect-core";import{useMemo as Xr}from"react";import{createConnectorManager as Mr,createSessionManager as Lr,LocalStorageSessionStorage as Br,logger as J,WalletError as Hr}from"@naculus/connect-core";import{eip6963Connector as Re}from"@naculus/connector-evm-injected";import{createContext as Fr,useCallback as F,useContext as Kr,useEffect as ce,useMemo as ue,useReducer as qr,useRef as cn}from"react";import{logger as Ar}from"@naculus/connect-core";import{issueNonce as br,parseSiwxMessage as Rr}from"@naculus/siwx";function oe(e,t){let o=t.split(":",1)[0],n=(e.namespaces[o]?.accounts??[]).filter(l=>l.startsWith(`${o}:`)).map(l=>({namespace:o,caip10:l}))[0];if(n)return{...n,address:n.caip10.split(":").pop()??n.caip10}}function Tr(e){return e.namespaces.eip155?.chains?.[0]??e.namespaces.solana?.chains?.[0]??e.namespaces.xrpl?.chains?.[0]??"eip155:1"}async function an(e){let{session:t,siwx:o,signMessage:s}=e;if(!o||!t)return{kind:"skipped"};try{let n=Tr(t),l=oe(t,n);if(!l)throw new Error("No account found in session");let{address:a}=l,C=await o.createMessage({address:a,chainId:n}),u=Rr(C);if(!u?.nonce)throw new Error("SIWx message must contain a nonce");await br(u.nonce);let c=await s(t,{message:C,address:a,chainId:n});return await o.handleSignComplete?.({message:C,signature:c}),{kind:"authenticated",address:a,chainId:n}}catch(n){let l=n instanceof Error?n:new Error("Wallet authentication failed");return Ar.error("appkit/core","SIWx authentication failed:",n),{kind:"failed",error:l,fatal:o.required!==!1}}}import{initialWeb3State as Vr,web3Reducer as $r,withRetry as Gr,withTimeout as un}from"@naculus/connect-appkit-core";import{resolveChain as Ir}from"@naculus/connect-appkit-core";import{CHAINS as be,DEFAULT_RPC_URLS as Ur,eip155Reference as Pr,getRpcUrl as Wr}from"@naculus/connect-core";var Or=[{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 Nr(e){let t=be[e];if(!t||!t.explorerUrl)return null;let o=t.caip2Id;return{caip2:o,name:t.name,rpcUrl:Wr(o,Ur[o]??""),explorerUrl:t.explorerUrl,token:t.nativeCurrency.symbol}}function _r(){if(!be)return[];let e=[],t=Object.keys(be).map(Number).sort((o,s)=>o-s);for(let o of t){let s=Nr(o);s&&e.push(s)}for(let o of Or){let s=Pr(o.caip2);(s===null||!be[s])&&e.push(o)}return e}var ln=_r();function Dr(e,t){return Ir(e,t)??void 0}function rt(){return[...ln]}import{jsx as zr}from"react/jsx-runtime";var ot=Fr(null);function jr({children:e,config:t,autoConnect:o=!0}){let[s,n]=qr($r,Vr),l=ue(()=>t.chains??rt(),[t.chains]),a=t.connectionTimeout??3e4,C=t.maxRetries??2,u=ue(()=>new Br(t.storageKey??"naculus_web3_session",t.encryptionKey),[t.storageKey,t.encryptionKey]),c=ue(()=>tt({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]),g=cn(null),r=cn(null),i=ue(()=>{let m=Mr();for(let O of[Re,...c.getAllConnectors()])m.register(O.id,O);let y={},k={};for(let O of l){let L=O.caip2;O.rpcUrl&&(y[L]=O.rpcUrl),O.token&&(k[L]={name:O.name,symbol:O.token,decimals:18})}let P=Lr(m,{autoRefreshFeeOnSwitch:t.autoRefreshFeeOnSwitch??!0,defaultRpcUrls:y,defaultCurrencies:k,encryptionKey:t.encryptionKey});return g.current=P,P},[c,l,t.autoRefreshFeeOnSwitch,t.encryptionKey]);ce(()=>{let m=P=>{let{walletSession:O}=P.bundle;n({type:"SET_SESSION",payload:O});let L=[];Object.values(O.namespaces).forEach(te=>{L.push(...te.accounts)}),n({type:"SET_ACCOUNTS",payload:L}),n({type:"SET_CHAIN",payload:P.bundle.activeChainId}),n({type:"SET_STATUS",payload:"connected"})},y=()=>{n({type:"RESET"})},k=P=>{n({type:"SET_CHAIN",payload:P.newChainId})};return i.on("sessionConnected",m),i.on("sessionDisconnected",y),i.on("chainChanged",k),()=>{i.off("sessionConnected",m),i.off("sessionDisconnected",y),i.off("chainChanged",k)}},[i]),ce(()=>{let m=()=>{u.clear(),n({type:"RESET"})};c.connector.onSessionExpiry(m)},[c,u]);let p=F(()=>{for(let m of[Re,...c.getAllConnectors()])i.registerConnector(m)},[c,i]),f=F(async m=>{p();let y=[Re,...c.getAllConnectors()].find(P=>P.id===m.walletType||P.kind===m.walletType);y&&!m.connectorId&&(m.connectorId=y.id);let k=m.namespaces.eip155?.chains?.[0]??m.namespaces.solana?.chains?.[0]??m.namespaces.xrpl?.chains?.[0];k&&await i.attach(m,k)},[c,i,p]),d=F(m=>{if(n({type:"SET_SESSION",payload:m}),m){let y=[];Object.values(m.namespaces).forEach(L=>{y.push(...L.accounts)}),n({type:"SET_ACCOUNTS",payload:y});let k=m.namespaces.eip155?.chains?.[0],P=m.namespaces.solana?.chains?.[0],O=m.namespaces.xrpl?.chains?.[0];n({type:"SET_CHAIN",payload:k??P??O??null})}else n({type:"SET_ACCOUNTS",payload:[]}),n({type:"SET_CHAIN",payload:null})},[]);ce(()=>{let m=s.session,y=c;return!m||!y?.onAccountsChanged?void 0:y.onAccountsChanged(m,P=>{if(P.length===0){u.clear().finally(()=>n({type:"RESET"}));return}d(m),u.save(m)})},[s.session,c,u,d]),ce(()=>{let m=s.session,y=c;if(!(!m||!y?.onChainChanged))return y.onChainChanged(m,k=>{d(m),u.save(m);let P=i.syncExternalChain;if(!P)return;let O=P.call(i,k).catch(L=>{J.warn("react/provider","External chain sync error:",L)});r.current=O,O.finally(()=>{r.current===O&&(r.current=null)})})},[s.session,c,u,d,i]);let S=F(async m=>{if(!t.siwx||!m)return!0;n({type:"SET_STATUS",payload:"authenticating"});let y=await an({session:m,siwx:t.siwx,signMessage:(k,P)=>c.signMessage(k,P)});return y.kind==="failed"&&y.fatal?(await u.clear(),n({type:"RESET"}),n({type:"SET_ERROR",payload:y.error}),!1):!0},[t.siwx,c,u]),h=F(async()=>{n({type:"SET_STATUS",payload:"connecting"}),n({type:"SET_ERROR",payload:null});try{let m=await un(c.connect(),a,"Wallet connect");await u.save(m),d(m);try{await f(m)}catch(y){J.warn("react/provider","SessionManager sync error:",y)}if(!await S(m))return;n({type:"SET_STATUS",payload:"connected"})}catch(m){let y=m instanceof Error?m.message:"Connection failed";n({type:"SET_ERROR",payload:m instanceof Error?m:new Error(y)}),n({type:"SET_STATUS",payload:"disconnected"})}},[c,u,d,a,S,f]),w=F(async()=>{n({type:"SET_STATUS",payload:"connecting"}),n({type:"SET_ERROR",payload:null});try{let m=await c.connectEmbedded();if(await u.save(m),d(m),await f(m),!await S(m))return;n({type:"SET_STATUS",payload:"connected"})}catch(m){let y=m instanceof Error?m.message:"Embedded wallet connection failed";n({type:"SET_ERROR",payload:m instanceof Error?m:new Error(y)}),n({type:"SET_STATUS",payload:"disconnected"})}},[c,u,d,S,f]),E=F(async()=>{n({type:"SET_STATUS",payload:"connecting"}),n({type:"SET_ERROR",payload:null});try{let m=await c.connectPasskeys();if(await u.save(m),d(m),await f(m),!await S(m))return;n({type:"SET_STATUS",payload:"connected"})}catch(m){let y=m instanceof Error?m.message:"Passkeys connection failed";n({type:"SET_ERROR",payload:m instanceof Error?m:new Error(y)}),n({type:"SET_STATUS",payload:"disconnected"})}},[c,u,d,S,f]),R=F(async()=>{if(!s.session){n({type:"RESET"});return}try{await c.disconnect(s.session)}catch(m){J.error("react/provider","Disconnect error:",m)}try{let m=g.current;m&&await m.disconnect()}catch(m){J.warn("react/provider","SessionManager disconnect error:",m)}await u.clear(),n({type:"RESET"})},[c,s.session,u]),A=F(async m=>{n({type:"SET_STATUS",payload:"connecting"}),n({type:"SET_ERROR",payload:null});try{let y=await un(c.connectInjected(m),a,"Injected wallet connect");await u.save(y),d(y);try{await f(y)}catch(k){J.warn("react/provider","SessionManager sync error:",k)}if(!await S(y))return;n({type:"SET_STATUS",payload:"connected"})}catch(y){let k=y instanceof Error?y.message:"Connection failed";n({type:"SET_ERROR",payload:y instanceof Error?y:new Error(k)}),n({type:"SET_STATUS",payload:"disconnected"})}},[c,u,d,a,S,f]),T=F(async()=>c.startPairing(),[c]),v=F(()=>{c.cancelPairing?.()},[c]),x=F(async()=>{let m=await c.completePairing();return await u.save(m),d(m),await f(m),await S(m)&&n({type:"SET_STATUS",payload:"connected"}),m},[c,u,d,S,f]),b=F(async m=>{let y=t.siwx;if(!y||y.required===!1)return!0;try{if(await y.hasValidSession?.())return!0}catch(k){J.warn("react/provider","siwx.hasValidSession failed",k)}return S(m)},[t.siwx,S]),I=F(async()=>{let m=await u.load();if(!m){n({type:"SET_STATUS",payload:"disconnected"});return}n({type:"SET_STATUS",payload:"reconnecting"});try{let y=await Gr(()=>c.reconnect(m),{maxRetries:C,baseDelay:1e3,label:"reconnect"});d(y);try{let k=g.current;k&&(p(),await k.restoreFromPersistence())}catch(k){J.warn("react/provider","SessionManager restore error:",k)}if(!await b(y))return;n({type:"SET_STATUS",payload:"connected"})}catch(y){J.error("react/provider","Reconnect error:",y),await u.clear(),n({type:"SET_STATUS",payload:"disconnected"}),n({type:"SET_SESSION",payload:null})}},[c,u,d,C,p,b]),W=F(async m=>{r.current&&await r.current;let y=g.current;if(y?.getActiveBundle()){await y.switchChain(m),d(s.session);return}if(!s.session)throw new Error("No active session");try{s.session.walletType==="eip6963"||s.session.id?.startsWith("eip6963-")?await Re.switchChain(s.session,m):s.session.walletType==="embedded"&&c.embeddedConnector?await c.embeddedConnector.switchChain?.(s.session,m):s.session.walletType==="passkeys"&&c.passkeysConnector?await c.passkeysConnector.switchChain?.(s.session,m):s.session.walletType==="solana"&&c.solanaConnector?await c.solanaConnector.switchChain?.(s.session,m):await c.connector.switchChain(s.session,m),d(s.session)}catch(k){throw new Hr("chain_unsupported","Failed to switch chain",k)}},[c,s.session,d]);ce(()=>{o&&I()},[o,I]);let M=F(()=>{n({type:"SET_ERROR",payload:null})},[]),B=ue(()=>({...s,connect:h,connectEmbedded:w,connectPasskeys:E,disconnect:R,reconnect:I,switchChain:W,startPairing:T,completePairing:x,cancelPairing:v,connectInjected:A,clearError:M,isConnected:s.status==="connected",chains:l,client:c,sessionManager:i}),[s,h,w,E,R,I,W,T,x,A,M,l,c,i]);return zr(ot.Provider,{value:B,children:e})}function U(){let e=Kr(ot);if(!e)throw new Error("useWeb3 must be used within a Web3ConnectProvider");return e}function H(){let{accounts:e,isConnected:t}=U(),o=Xr(()=>!t||e.length===0?null:e.map(n=>{let l=Qr(n);return l?{address:n,namespace:l.namespace,isEVM:l.namespace==="eip155"&&pn(l.address)}:{address:n,namespace:null,isEVM:pn(n)}}),[e,t]),s=o?.find(n=>n.isEVM)?.address??null;return{accounts:o,evmAccount:s,primaryAccount:e[0]??null,isConnected:t,count:e.length}}import{chainNumber as Yr,resolveChain as Jr,toViemChain as Zr}from"@naculus/connect-appkit-core";import{useState as pe,useEffect as st,useCallback as eo,useMemo as de,useRef as to}from"react";import{createPublicClient as no,http as ro,formatEther as oo}from"viem";import{getNativeTokenPriceUsd as so}from"@naculus/connect-core";function ao(e){let{evmAccount:t,isConnected:o}=H(),{chainId:s,chains:n}=U(),[l,a]=pe(null),[C,u]=pe(!1),[c,g]=pe(null),[r,i]=pe(null),p=e?.refreshInterval,f=to(null),d=de(()=>Jr(n,s),[s,n]),S=d?Yr(d):null,h=de(()=>d?Zr(d,S):null,[d,S]),w=de(()=>d?.token??null,[d]),[E,R]=pe(null);st(()=>{if(!h||!d?.rpcUrl){R(null);return}let x=no({transport:ro(d.rpcUrl),chain:h});return R(x),()=>{}},[d]);let A=eo(async()=>{if(!t||!E){a(null);return}u(!0),g(null);try{let b=t.includes(":")?t.split(":").pop():t,[I,W]=await Promise.all([E.getBalance({address:b}),s?so(s,d?.rpcUrl).catch(()=>null):Promise.resolve(null)]);a(I.toString()),i(W)}catch(x){g(x instanceof Error?x:new Error("Failed to fetch balance")),a(null),i(null)}finally{u(!1)}},[t,E,s,d?.rpcUrl]);st(()=>{o&&t&&A()},[o,t,A]),st(()=>(p&&p>0&&o&&t&&(f.current=setInterval(A,p)),()=>{f.current&&(clearInterval(f.current),f.current=null)}),[p,o,t,A]);let T=de(()=>{if(l===null)return null;try{return oo(BigInt(l))}catch{return null}},[l]),v=de(()=>{if(r===null||T===null)return null;let x=parseFloat(T);if(isNaN(x))return null;let b=x*r;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(b)},[r,T]);return{balance:l,formatted:T,symbol:w,usdPrice:r,usdValue:v,isLoading:C,error:c,refetch:A,chain:d}}import{atomicSupportFor as io,normalizeCapabilities as lo,selectChainCapabilities as co}from"@naculus/connect-appkit-core";import{useCallback as uo,useEffect as po,useRef as mo,useState as at}from"react";function N(e){return e??nt()}function it(){let{client:e,session:t,chainId:o}=U(),[s,n]=at(null),[l,a]=at(!1),[C,u]=at(null),c=mo(0),g=uo(async()=>{let r=++c.current,i=N(e);if(!i?.getCapabilities||!t){n(null),a(!1),u(null);return}a(!0),u(null);try{let p=await i.getCapabilities(t);if(r!==c.current)return;n(lo(p))}catch(p){if(r!==c.current)return;n(null),u(p instanceof Error?p:new Error("Capability query failed"))}finally{r===c.current&&a(!1)}},[e,t]);return po(()=>{g()},[g]),{capabilities:s,current:co(s,o),atomic:io(s,o),isFetching:l,error:C,refetch:g}}import{useMemo as lt}from"react";import{chainsForNamespace as fo,describeChain as go,resolveChain as Co}from"@naculus/connect-appkit-core";function V(){let{chainId:e,session:t,switchChain:o,chains:s}=U(),n=lt(()=>Co(s,e),[s,e]),l=lt(()=>t?go(s,e):null,[s,e,t]),a=lt(()=>fo(s,e),[s,e]);return{chainId:e,currentChain:n,chainInfo:l,availableChains:a,chains:a,isEvm:e?.startsWith("eip155:")??!1,switchChain:o}}import{useCallback as ho,useState as dn}from"react";import{WalletError as yo}from"@naculus/connect-core";function So(){let{connect:e,status:t}=U(),[o,s]=dn(!1),[n,l]=dn(null);return{connect:ho(async()=>{s(!0),l(null);try{await e()}catch(C){let u=C instanceof Error?C.message:"Connection failed";l(C instanceof yo?C:new Error(u))}finally{s(!1)}},[e]),isConnecting:o||t==="connecting",error:n}}import{readDelegation as vo,UNKNOWN_DELEGATION as ut}from"@naculus/connect-core";import{useCallback as Ao,useEffect as bo,useRef as Ro,useState as pt}from"react";import{chainNumber as Eo,toViemChain as wo}from"@naculus/connect-appkit-core";import{useMemo as ct}from"react";import{createPublicClient as ko,http as mn,createWalletClient as xo}from"viem";function G(){let{evmAccount:e,isConnected:t}=H(),{currentChain:o,chains:s}=V(),n=o?Eo(o):null,l=ct(()=>o?wo(o,n):null,[o,n]),a=ct(()=>l?ko({transport:mn(l.rpcUrls.default.http[0]),chain:l}):null,[o,l]),C=ct(()=>{if(!t||!e||!l)return null;let u=e.includes(":")?e.split(":").pop():e;return xo({transport:mn(l.rpcUrls.default.http[0]),chain:l,account:u})},[t,e,o,l]);return{publicClient:a,walletClient:C,chains:s}}function me(){let{publicClient:e}=G(),{evmAccount:t}=H(),[o,s]=pt(ut),[n,l]=pt(!1),[a,C]=pt(null),u=Ro(0),c=t?.includes(":")?t.split(":").pop():t,g=Ao(async()=>{let r=++u.current;if(!e||!c){s(ut),l(!1),C(null);return}l(!0),C(null);try{let i=await e.getCode({address:c});if(r!==u.current)return;s(vo(i??"0x"))}catch(i){if(r!==u.current)return;s(ut),C(i instanceof Error?i:new Error("Code read failed"))}finally{r===u.current&&l(!1)}},[e,c]);return bo(()=>{g()},[g]),{...o,isFetching:n,error:a,refetch:g}}import{bareEvmAddress as qo,createDelegationPolicyFlow as Vo,isVerifiablePolicy as $o}from"@naculus/connect-appkit-core";import{useCallback as ge,useEffect as Go,useMemo as jo,useState as Ue}from"react";import{recoverMessageAddress as zo}from"viem";import{planExecution as Po,WalletError as Wo}from"@naculus/connect-core";import{useCallback as fn,useState as mt}from"react";import{chooseExecutionStrategy as Io,getAccountCapabilities as Uo,WalletError as Z}from"@naculus/connect-core";import{useCallback as Ie,useState as fe}from"react";import{WalletError as To}from"@naculus/connect-core";function Te(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 To("tx_failed","Wallet did not return a valid 32-byte transaction hash")}function dt(){let{session:e,chainId:t,client:o}=U(),[s,n]=fe("idle"),[l,a]=fe(null),[C,u]=fe(null),[c,g]=fe(null),[r,i]=fe(null),p=Ie(async(h,w)=>{if(!e){n("failed");let E=new Z("wallet_unavailable","No active session");throw a(E),E}if(h.length===0){n("failed");let E=new Z("invalid_input","At least one call is required");throw a(E),E}n("awaiting_approval"),a(null),u(null);try{let E=N(o);if(!E)throw new Z("wallet_unavailable","Client not initialized");let R=w?.chainId??t??void 0,A=w?.strategy??Io(await Uo(E,e,R),h.length);if(i(A),A==="atomic-batch"){let v=await E.sendCalls(e,h,R,{atomicRequired:!0,...w?.paymasterService?{paymasterService:w.paymasterService}:{}});return n("submitted"),u(v),v}let T="";for(let v=0;v<h.length;v++){let x=h[v];try{T=Te(await E.sendTransaction(e,{transaction:{to:x.to,data:x.data,value:x.value},chainId:R}))}catch(b){throw new Z("tx_failed",`Call ${v+1} of ${h.length} failed after ${v} already landed (sent sequentially \u2014 this wallet cannot batch atomically): ${b instanceof Error?b.message:String(b)}`)}}return n("submitted"),u(T),T}catch(E){n("failed");let R=E instanceof Error?E.message:"sendCalls failed";throw a(E instanceof Error?E:new Error(R)),E}},[e,t,o]),f=Ie(async h=>{if(!e)throw new Z("wallet_unavailable","No active session");let w=h??C;if(!w)throw new Z("invalid_input","No bundle hash available");if(!h&&r==="sequential")throw new Z("invalid_input","Calls were sent sequentially, so there is no bundle to query. Track the returned transaction hash instead.");let E=N(o);if(!E)throw new Z("wallet_unavailable","Client not initialized");let R=await E.getCallsStatus(e,w);return g(R),R},[e,C,o,r]),d=Ie(async h=>{if(!e)return!1;let w=h??C;if(!w||!h&&r==="sequential")return!1;let E=N(o);if(!E?.showCallsStatus)return!1;try{return await E.showCallsStatus(e,w),!0}catch{return!1}},[e,C,o,r]),S=Ie(()=>{n("idle"),a(null),u(null),g(null),i(null)},[]);return{sendCalls:p,getCallsStatus:f,showCallsStatus:d,status:s,error:l,batchHash:C,callsStatus:c,execution:r,reset:S,isSending:s==="awaiting_approval"}}function ft(e={}){let{current:t,atomic:o}=it(),{delegated:s,delegate:n}=me(),{sendCalls:l}=dt(),[a,C]=mt(!1),[u,c]=mt(null),[g,r]=mt(null),i=e.atomicity??"preferred",p=e.sponsorship??"any",f=e.paymasterService,d=e.userOperation,S=e.userOperationSponsored??!1,h=!!(t?.raw?.paymasterService?.supported&&f),w=fn((R,A=i)=>{let T=Po({atomicBatch:o==="supported",discovered:o!=="unknown",sponsoredTransactions:!1,...t?.maxBatchSize===void 0?{}:{maxBatchSize:t.maxBatchSize}},R,{atomicity:A,sponsorship:p}),v=p==="required"&&!S;if(T.strategy==="atomic-batch"&&!v)return{...T,reason:T.reason+(h?" A paymaster service will be requested, but the wallet's final fee payer must be checked after execution.":""),route:"wallet-batch"};let x=s&&o!=="supported"?` This account does delegate to ${n} under EIP-7702, so it is capable of batching even though the wallet has not offered to.`:"",b=A!=="any"&&!T.atomic||p==="required";return d&&b&&!v?{strategy:"atomic-batch",atomic:!0,sponsored:S,reason:p==="required"&&!T.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"}:v?{strategy:"refuse",atomic:T.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}:T.strategy==="refuse"?{...T,reason:T.reason+x,route:null}:{...T,reason:T.reason+x,route:"sequential"}},[o,t,f,h,d,S,i,p,s,n]),E=fn(async(R,A=i)=>{C(!0),c(null);try{let T=w(R.length,A);if(T.route===null)throw new Wo("method_not_allowed",T.reason);return r(T.route),T.route==="user-operation"?await d(R):await l(R,{strategy:T.route==="wallet-batch"?"atomic-batch":"sequential",...T.route==="wallet-batch"&&h?{paymasterService:f}:{}})}catch(T){let v=T instanceof Error?T:new Error("Execution failed");throw c(v),v}finally{C(!1)}},[w,l,d,i,f,h]);return{preview:w,execute:E,isExecuting:a,error:u,lastRoute:g,reset:()=>{c(null),r(null)}}}import{getSharedSessionKeyManager as Oo,resetSharedSessionKeyManager as No}from"@naculus/connect-appkit-core";import{WalletError as _o}from"@naculus/connect-core";import{useCallback as Q,useEffect as Do,useRef as Mo,useState as z}from"react";function se(e){return Oo(e)}function gt(e){let{session:t}=U(),[o,s]=z([]),[n,l]=z(!1),[a,C]=z(null),u=Mo(!0),c=Q(()=>C(null),[]),g=se(e),r=g.isStorageAvailable(),i=Q(async()=>{if(!t){s([]);return}l(!0),C(null);try{let f=await g.listSessions();u.current&&s(f)}catch(f){u.current&&C(f instanceof Error?f:new Error("Failed to load session keys"))}finally{u.current&&l(!1)}},[t,g]);Do(()=>(u.current=!0,i(),()=>{u.current=!1}),[i]);let p=o.filter(f=>f.status==="active");return{sessions:o,activeSessions:p,loading:n,error:a,refresh:i,clearError:c,storageAvailable:r}}function Lo(e){let{session:t}=U(),[o,s]=z(null),[n,l]=z(!1),[a,C]=z(null),u=Q(()=>C(null),[]),c=se(e);return{createSessionKey:Q(async(r,i)=>{if(!t)throw new _o("wallet_unavailable","No active wallet session");l(!0),C(null);try{let p=i??void 0,f=await c.createSessionKey(r,p);return s(f),f}catch(p){let f=p instanceof Error?p:new Error("Failed to create session key");throw C(f),f}finally{l(!1)}},[t,c]),lastCreated:o,isCreating:n,error:a,clearError:u}}function Bo(e){let[t,o]=z(!1),[s,n]=z(null),l=Q(()=>n(null),[]),a=se(e);return{revokeSession:Q(async u=>{o(!0),n(null);try{await a.revokeSession(u)}catch(c){let g=c instanceof Error?c:new Error("Failed to revoke session key");throw n(g),g}finally{o(!1)}},[a]),isRevoking:t,error:s,clearError:l}}function Ho(e){let[t,o]=z(!1),[s,n]=z(null),l=Q(()=>n(null),[]),a=se(e),C=Q(async(c,g,r)=>{o(!0),n(null);try{return await a.signWithSessionKey(c,g,r)}catch(i){let p=i instanceof Error?i:new Error("Failed to sign with session key");throw n(p),p}finally{o(!1)}},[a]),u=Q(async(c,g)=>{o(!0),n(null);try{return await a.checkSessionScope(c,g)}catch(r){let i=r instanceof Error?r:new Error("Failed to check session scope");throw n(i),i}finally{o(!1)}},[a]);return{signWithSession:C,checkScope:u,isBusy:t,error:s,clearError:l}}function Fo(){No()}import{useState as gn,useCallback as Ko}from"react";import{WalletError as Ct}from"@naculus/connect-core";function ht(){let{session:e,chainId:t,client:o}=U(),[s,n]=gn(!1),[l,a]=gn(null);return{signMessage:Ko(async u=>{if(!e){let g=new Ct("wallet_unavailable","No active session");throw a(g),g}let c=e.namespaces.eip155?.accounts[0]??Object.values(e.namespaces)[0]?.accounts[0];if(!c){let g=new Ct("wallet_unavailable","No account found");throw a(g),g}n(!0),a(null);try{let g=N(o);if(!g)throw new Ct("wallet_unavailable","Client not initialized");return await g.signMessage(e,{message:u,address:c,chainId:t??void 0})}catch(g){let r=g instanceof Error?g.message:"Signing failed",i=g instanceof Error?g:new Error(r);throw a(i),i}finally{n(!1)}},[e,t,o]),isSigning:s,error:l}}import{buildDelegationPolicyMessage as Xo}from"@naculus/connect-appkit-core";function Qo(e={}){let{evmAccount:t}=H(),o=qo(t),s=me(),n=ft(e.execution),{signMessage:l}=ht(),a=gt(e.managerConfig),C=se(e.managerConfig),[u,c]=Ue(!1),[g,r]=Ue(null),[i,p]=Ue(()=>new Set),[f,d]=Ue(!1),S=e.origin??(typeof window<"u"?window.location.origin:"unknown"),h=!!e.managerConfig?.encryptionKey,w=e.execution?.sponsorship,{refresh:E,storageAvailable:R}=a,{preview:A}=n,{delegated:T,delegate:v}=s,x=jo(()=>Vo({manager:C,origin:S,signer:()=>o,signMessage:l,verifySignature:async({message:y,signature:k,signerAddress:P})=>(await zo({message:y,signature:k})).toLowerCase()===P.toLowerCase(),previewExecution:A,sponsorship:w,adapter:e.adapter,delegation:()=>({delegated:T,delegate:v}),encryptionKeyConfigured:h,storageAvailable:()=>R,refresh:E}),[C,S,o,l,A,w,e.adapter,T,v,h,R,E]);Go(()=>{let y=!1,k=a.sessions.filter($o);return k.length===0?(p(new Set),d(!1),()=>{y=!0}):(d(!0),Promise.all(k.map(async P=>[P.id,await x.verifyStoredPolicy(P)])).then(P=>{y||p(new Set(P.filter(([,O])=>O).map(([O])=>O)))}).catch(P=>{y||(p(new Set),r(P instanceof Error?P:new Error("Policy verification failed")))}).finally(()=>{y||d(!1)}),()=>{y=!0})},[a.sessions,x]);let b=ge(()=>{r(null),a.clearError()},[a]),I=ge(async(y,k)=>{c(!0),r(null);try{return await y()}catch(P){let O=P instanceof Error?P:new Error(k);throw r(O),O}finally{c(!1)}},[]),W=ge(y=>I(()=>x.createPolicy(y),"Policy creation failed"),[x,I]),M=ge(y=>I(()=>x.revokePolicy(y),"Policy revocation failed"),[x,I]),B=ge((y,k)=>I(()=>x.executePolicy(y,k),"Policy execution failed"),[x,I]),m=a.activeSessions.filter(y=>i.has(y.id));return{policies:a.sessions,activePolicies:m,storageAvailable:a.storageAvailable,loading:a.loading||f,isBusy:u,error:g??a.error,delegation:s,createPolicy:W,revokePolicy:M,previewPolicyExecution:x.previewPolicyExecution,signPolicyDigest:x.signPolicyDigest,executePolicy:B,refresh:a.refresh,clearError:b}}import{useCallback as Yo,useRef as Jo,useState as Cn}from"react";function Zo(){let{disconnect:e,status:t}=U(),[o,s]=Cn(!1),[n,l]=Cn(null),a=Jo(!0);return{disconnect:Yo(async()=>{if(t!=="disconnected"){s(!0),l(null);try{await e()}catch(u){if(!a.current)return;l(u instanceof Error?u:new Error("Disconnect failed"))}finally{a.current&&s(!1)}}},[e,t]),isDisconnecting:o,error:n,cleanup:()=>{a.current=!1}}}import{WalletError as yt}from"@naculus/connect-core";import{useCallback as X,useEffect as es,useRef as Pe,useState as We}from"react";function ee(e){let t=e.activeNamespace??"eip155",o=Array.isArray(e.accounts)?e.accounts.map(({namespace:s,address:n,derivationPath:l})=>({namespace:s,address:n,...l?{derivationPath:l}:{}})):e.address?[{namespace:t,address:e.address}]:[];return{accounts:o,activeNamespace:t,createdAt:e.createdAt??0,...e.chainId?{chainId:e.chainId}:{},...e.version?{version:e.version}:{},recoveryAvailable:!!e.mnemonic,address:o.find(s=>s.namespace===t)?.address??e.address}}function ts(){let{connectEmbedded:e,client:t}=U(),[o,s]=We(null),n=Pe(null),l=Pe(4),a=Pe(!1),C=Pe(null),[u,c]=We(!1),[g,r]=We(!1),[i,p]=We(null),f=()=>p(null),d=X(()=>{let m=n.current;return n.current=null,m},[]),S=X(()=>{let m=N(t);if(!m?.embeddedConnector)throw new yt("wallet_unavailable","Embedded wallet not enabled.");return m.embeddedConnector},[t]),h=X(()=>{try{return S().getWallet()?.privateKey??null}catch{return null}},[S]),w=X(async()=>{let m=N(t);if(!m)throw new yt("wallet_unavailable","Embedded wallet not enabled.");let y=m.getEmbeddedConnector?await m.getEmbeddedConnector():m.embeddedConnector;if(!y)throw new yt("wallet_unavailable","Embedded wallet not enabled.");return y},[t]),E=X(()=>{try{return N(t)?.passphraseGate??null}catch{return null}},[t]),R=X(m=>{m?.code==="decryption_failed"&&E()?.forget("That passphrase did not open the wallet.")},[E]),A=X(async()=>{a.current=!1,p(null);try{let m=await w();if(!await m.load())return!1;let k=m.getWallet();return k?(n.current=null,c(!1),s(ee(k)),!0):!1}catch(m){return a.current=!0,R(m),p(m instanceof Error?m:new Error("Failed to restore embedded wallet")),!1}},[R,w]);es(()=>{let m=!1,y=null;return A().then(k=>{m||k||a.current||(y=setTimeout(()=>{m||A()},100))}),()=>{m=!0,y&&clearTimeout(y)}},[A]);let T=async()=>{r(!0),p(null);try{let m=await w(),y=await m.load(),k=m.getWallet();y&&k&&(s(ee(k)),n.current=k.mnemonic||null,c(!k.mnemonic)),await e();let P=m.getWallet();P&&(s(ee(P)),P.mnemonic&&!y&&(n.current=P.mnemonic,c(!0)))}catch(m){R(m),p(m instanceof Error?m:new Error("Embedded wallet connection failed"))}finally{r(!1)}},v=async()=>{r(!0),p(null);try{let m=await w();E()?.expect("create");let y=await m.generateWallet();return s(ee(y)),n.current=y.mnemonic,c(!0),y}catch(m){return p(m instanceof Error?m:new Error("Failed to generate wallet")),null}finally{r(!1)}},x=async m=>{r(!0),p(null);try{let y=await w();E()?.expect("create");let k=await y.importFromMnemonic(m);return s(ee(k)),n.current=null,c(!1),k}catch(y){return p(y instanceof Error?y:new Error("Failed to import wallet")),null}finally{r(!1)}},b=async m=>{r(!0),p(null);try{let y=await w();E()?.expect("create");let k=await y.importFromPrivateKey(m);return s(ee(k)),n.current=null,c(!1),k}catch(y){return p(y instanceof Error?y:new Error("Failed to import wallet")),null}finally{r(!1)}},I=async()=>{r(!0),p(null);try{await(await w()).wipe(),s(null),n.current=null,c(!1)}catch(m){p(m instanceof Error?m:new Error("Failed to wipe wallet"))}finally{r(!1)}},W=X(m=>{let y=S();y.setActiveNamespace(m);let k=y.getWallet();s(k?ee(k):null)},[S]),M=X(async()=>{let m=await w(),y=await m.backfillAccounts();if(y.length>0){let k=m.getWallet();s(k?ee(k):null)}return y.map(({namespace:k,address:P,derivationPath:O})=>({namespace:k,address:P,...O?{derivationPath:O}:{}}))},[w]),B=()=>{n.current=null,c(!1)};return{connectEmbedded:T,restoreWallet:A,generateWallet:v,importFromMnemonic:x,importFromPrivateKey:b,wipe:I,wallet:o,hasWallet:o!==null,address:o?.address??null,accounts:o?.accounts??[],activeNamespace:o?.activeNamespace??null,setActiveNamespace:W,backfillAccounts:M,seedPhrase:n.current,getSeedPhrase:d,getPrivateKey:h,backupPending:u,confirmBackup:B,isBusy:g,error:i,clearError:f,storageSecurityLevel:(()=>{try{let m=S(),y=m.getStorageSecurityLevel?.()??4;return m.getWallet()?(l.current=y,y):o?l.current:y}catch{return o?l.current:4}})(),securityReport:(()=>{let m=null;try{m=S().getStorageSecurityReport?.()??null}catch{m=null}if(!m)return C.current=null,null;let y=JSON.stringify(m);return C.current?.json===y?C.current.value:(C.current={json:y,value:m},m)})()}}import{chainNumber as ls}from"@naculus/connect-appkit-core";import{useState as cs,useCallback as us,useEffect as Sn,useRef as En,useMemo as ps}from"react";import{WalletError as ns}from"@naculus/connect-core";import{useCallback as hn,useEffect as rs,useLayoutEffect as os,useMemo as ss,useRef as yn}from"react";import{tokenChainMismatch as as}from"@naculus/connect-appkit-core";function is(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 ae(e){let{token:t,chainId:o}=e,s=t.address.toLowerCase(),n=is(e),l=ss(()=>({key:n}),[n]),a=yn(n),C=yn(!0);os(()=>{a.current=n},[n]),rs(()=>(C.current=!0,()=>{C.current=!1}),[]);let u=hn(()=>C.current&&a.current===n,[n]),c=hn(()=>{if(!u())throw new ns("session_inactive","Wallet or token context changed. Retry the operation with the current account and chain.");let g=as({address:s,chainId:t.chainId},o);if(g)throw g},[u,s,t.chainId,o]);return{identity:l,isCurrent:u,assertCurrent:c}}import{ERC20_MIN_ABI as ds,formatUnits as ms}from"@naculus/connect-core";function fs(e){let{publicClient:t}=G(),{currentChain:o}=V(),{identity:s,isCurrent:n,assertCurrent:l}=ae({token:e.token,chainId:o?ls(o)??void 0:void 0,owner:e.owner,spender:e.spender,publicClient:t}),[a,C]=cs(null),u=a?.identity===s?a.raw:null,c=a?.identity===s&&a.fetching,g=a?.identity===s?a.error:null,r=En(null),i=En(0),p=us(async()=>{if(!n())return;let d=++i.current,S=()=>n()&&d===i.current;if(C({identity:s,raw:null,fetching:!!t,error:null}),!!t)try{l();let h=await t.readContract({address:e.token.address,abi:ds,functionName:"allowance",args:[e.owner,e.spender]});if(!S())return;C({identity:s,raw:h,fetching:!1,error:null})}catch(h){if(!S())return;C({identity:s,raw:null,fetching:!1,error:h instanceof Error?h:new Error("Failed to fetch allowance")})}},[t,e.token.address,e.token.chainId,e.owner,e.spender,s,n,l]);return Sn(()=>{p().catch(d=>console.warn("useERC20Allowance: initial fetch failed:",d))},[p]),Sn(()=>(e.refreshInterval&&e.refreshInterval>0&&(r.current=setInterval(p,e.refreshInterval)),()=>{r.current&&(clearInterval(r.current),r.current=null)}),[e.refreshInterval,p]),{allowance:ps(()=>{if(u===null)return null;let d=e.token.decimals;return d===void 0?null:ms(u,d)},[u,e.token.decimals]),allowanceRaw:u,isFetching:c,error:g,refetch:p}}import{chainNumber as gs,createDecimalsCache as Cs,encodeErc20Approve as hs,readDecimals as Et,writeDecimals as xn}from"@naculus/connect-appkit-core";import{ERC20_MIN_ABI as Oe,formatUnits as ys,parseUnits as vn,WalletError as Ne}from"@naculus/connect-core";import{useCallback as he,useRef as An,useState as bn}from"react";import{WalletError as St}from"@naculus/connect-core";import{useCallback as wn,useState as kn}from"react";function Ce(){let{session:e,chainId:t,client:o}=U(),[s,n]=kn("idle"),[l,a]=kn(null),C=wn(async c=>{if(!e){n("failed");let r=new St("wallet_unavailable","No active session");throw a(r),r}let g=e.namespaces.eip155?.accounts.find(r=>/^eip155:\d+:0x[0-9a-fA-F]{40}$/.test(r)||/^0x[0-9a-fA-F]{40}$/.test(r));if(!g){n("failed");let r=new St("wallet_unavailable","No EVM account found");throw a(r),r}n("awaiting_approval"),a(null);try{let r={...c,from:c.from??g.split(":").pop()},i=N(o);if(!i)throw new St("wallet_unavailable","Client not initialized");let p=await i.sendTransaction(e,{transaction:r,chainId:t??void 0}),f=Te(p);return n("submitted"),f}catch(r){n("failed");let i=r instanceof Error?r.message:"Transaction failed";throw a(r instanceof Error?r:new Error(i)),r}},[e,t,o]),u=wn(()=>{n("idle"),a(null)},[]);return{sendTransaction:C,status:s,error:l,reset:u,isSending:s==="awaiting_approval"}}function Ss(e){return e.includes(":")?e.split(":").pop():e}var Es=2n**256n-1n;function ws(e){let{publicClient:t,walletClient:o}=G(),{evmAccount:s,isConnected:n}=H(),{currentChain:l}=V(),{session:a,client:C}=U(),{sendTransaction:u,isSending:c,error:g,reset:r}=Ce(),[i,p]=bn(null),{identity:f,isCurrent:d,assertCurrent:S}=ae({token:e.token,chainId:l?gs(l)??void 0:void 0,owner:s,spender:e.spender,connected:n,publicClient:t,walletClient:o,session:a,client:C}),[h,w]=bn(null),E=h?.identity===f?h.raw:null,R=h?.identity===f&&h.fetching,A=An(Cs(e.token,e.token.decimals)),T=An(0),v=i??g,x=s?Ss(s):null,b=he(async()=>{if(!d())return null;let y=++T.current,k=()=>d()&&y===T.current;if(w({identity:f,raw:null,fetching:!!t&&!!x&&n}),p(null),!t||!x||!n)return null;try{S();let P=await t.readContract({address:e.token.address,abi:Oe,functionName:"allowance",args:[x,e.spender]});return k()?(w({identity:f,raw:P,fetching:!1}),P):null}catch(P){return k()&&(w({identity:f,raw:null,fetching:!1}),p(P instanceof Error?P:new Error("Failed to fetch allowance"))),null}},[t,x,e.token.address,e.token.chainId,e.spender,f,d,S,n]),I=(()=>{if(E===null)return null;let y=Et(A.current,e.token,e.token.decimals);return y===void 0?null:ys(E,y)})(),W=he(async y=>{if(p(null),r(),!n||!s){let k=new Ne("wallet_unavailable","No connected account");throw p(k),k}if(!t){let k=new Ne("wallet_unavailable","No public client");throw p(k),k}try{S();let k=hs(e.spender,y),P=N(C);if(a&&P){let L=await u({to:e.token.address,data:k,value:"0"});return b(),L}if(o){let{request:L}=await t.simulateContract({address:e.token.address,abi:Oe,functionName:"approve",args:[e.spender,y],account:x});S();let te=await o.writeContract(L);return b(),te}let O=await u({to:e.token.address,data:k,value:"0"});return b(),O}catch(k){let P=k instanceof Error?k:new Error("Approve failed");throw d()&&p(P),P}},[e,t,o,s,n,a,C,x,u,r,b,S,d]),M=he(async y=>{try{if(S(),!t)throw new Ne("wallet_unavailable","No public client");let k=Et(A.current,e.token,e.token.decimals);k===void 0&&(k=await t.readContract({address:e.token.address,abi:Oe,functionName:"decimals"}),S(),xn(A.current,e.token,k));let P=vn(y,k);return await W(P)}catch(k){throw d()&&p(k instanceof Error?k:new Error("Approve failed")),k}},[e.token,t,W,S,d]),B=he(async()=>W(Es),[W]),m=he(async y=>{if(!d()||!n||!x||!t)return!1;try{S()}catch(L){return p(L instanceof Error?L:new Error("Cannot check allowance")),!1}let k=E??await b();if(k===null)return!1;let P=Et(A.current,e.token,e.token.decimals);if(P===void 0){if(!t)throw new Ne("wallet_unavailable","Cannot check allowance: no public client to read token decimals.");if(P=await t.readContract({address:e.token.address,abi:Oe,functionName:"decimals"}),!d())return!1;xn(A.current,e.token,P)}let O=vn(y,P);return d()&&k>=O},[E,b,e.token.address,e.token.chainId,e.token.decimals,t,d,S,n,x]);return{approve:M,approveMax:B,allowance:I,allowanceRaw:E,hasAllowance:m,isApproving:c,isFetchingAllowance:R,error:v,refetchAllowance:b}}import{chainNumber as ks,createDecimalsCache as xs,encodeErc20Transfer as vs,readDecimals as As,writeDecimals as bs}from"@naculus/connect-appkit-core";import{ERC20_MIN_ABI as Rn,parseUnits as Rs,WalletError as Tn}from"@naculus/connect-core";import{useCallback as Ts,useRef as Is,useState as Us}from"react";function Ps(e){return e.includes(":")?e.split(":").pop():e}function Ws(e){let{publicClient:t,walletClient:o}=G(),{evmAccount:s,isConnected:n}=H(),{currentChain:l}=V(),{session:a,client:C}=U(),{sendTransaction:u,isSending:c,error:g,reset:r}=Ce(),[i,p]=Us(null),{isCurrent:f,assertCurrent:d}=ae({token:e.token,chainId:l?ks(l)??void 0:void 0,owner:s,connected:n,publicClient:t,walletClient:o,session:a,client:C}),S=Is(xs(e.token,e.token.decimals)),h=i??g;return{sendTransfer:Ts(async(E,R)=>{if(p(null),r(),!n||!s){let A=new Tn("wallet_unavailable","No connected account");throw p(A),A}if(!t){let A=new Tn("wallet_unavailable","No public client available");throw p(A),A}try{d();let A=Ps(s),T=As(S.current,e.token,e.token.decimals);T===void 0&&(T=await t.readContract({address:e.token.address,abi:Rn,functionName:"decimals"}),d(),bs(S.current,e.token,T));let v=Rs(R,T),x=vs(E,v),b=N(C);if(a&&b)return await u({to:e.token.address,data:x,value:"0"});if(o){let{request:W}=await t.simulateContract({address:e.token.address,abi:Rn,functionName:"transfer",args:[E,v],account:A});return d(),await o.writeContract(W)}return await u({to:e.token.address,data:x,value:"0"})}catch(A){let T=A instanceof Error?A:new Error("Transfer failed");throw f()&&p(T),T}},[e.token,t,o,s,n,a,C,u,r,d,f]),isSending:c,error:h}}import{chainNumber as Ds,encodeErc20Transfer as Ms}from"@naculus/connect-appkit-core";import{parseUnits as Ls}from"@naculus/connect-core";import{useMemo as Bs}from"react";import{simulateTransactionPreview as Os}from"@naculus/connect-appkit-core";import{useCallback as In,useEffect as Ns,useRef as _s,useState as wt}from"react";function kt(e,t){U();let{evmAccount:o}=H(),{currentChain:s}=V(),{publicClient:n}=G(),[l,a]=wt(void 0),[C,u]=wt(!1),[c,g]=wt(null),r=_s(void 0),i=In(async()=>{e&&(u(!0),g(null));try{let f=await Os(e,{chainId:t,currentChain:s,publicClient:n,evmAccount:o});return a(f),f}catch(f){let d=f instanceof Error?f:new Error("Simulation failed");throw g(d),d}finally{e&&u(!1)}},[e,t,s,n,o]);Ns(()=>{if(e)return r.current&&clearTimeout(r.current),r.current=setTimeout(()=>{i().catch(()=>{})},300),()=>{r.current&&clearTimeout(r.current)}},[e,i]);let p=In(()=>{a(void 0),g(null),u(!1)},[]);return{result:l,isSimulating:C,error:c,simulate:i,reset:p}}function Hs(e){let{evmAccount:t,isConnected:o}=H(),{currentChain:s}=V(),n=e.token.chainId??(s?Ds(s)??void 0:void 0),l=Bs(()=>{if(!(!o||!t))try{let C=e.token.decimals;if(C===void 0)return;let u=Ls(e.amount,C),c=Ms(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,o]),a=kt(l,n);return{result:l?a.result:void 0,isSimulating:!!l&&a.isSimulating,error:l?a.error:null,reSimulate:a.simulate,reset:a.reset}}import{useState as xt,useCallback as Gs,useRef as vt}from"react";import{useState as _e,useEffect as Fs,useCallback as Un,useRef as Ks}from"react";import{createContext as qs,useContext as Vs}from"react";var Pn=qs(null);function ye(){return Vs(Pn)}function $s(e,t,o){let s=ye(),n=o??s,[l,a]=_e(null),[C,u]=_e(!1),[c,g]=_e(!1),[r,i]=_e(null),p=Ks(void 0),f=Un(async()=>{if(!(!n||!e)){u(!0),i(null);try{await n.refreshTx(e,t);let h=n.getTxStatus(e,t);h&&a(h)}catch(h){i(h instanceof Error?h:new Error(String(h)))}finally{u(!1)}}},[n,e,t]),d=Un(()=>{!n||!e||(n.stopWatching(e,t),g(!1))},[n,e,t]);Fs(()=>{if(!n||!e||!t){a(null),g(!1);return}p.current&&p.current!==e&&n.stopWatching(p.current),p.current=e;let h=!1;g(!0),u(!0),i(null);let w=n.getTxStatus(e,t);w&&(a(w),u(!1)),n.watchTx(e,t,{}).then(R=>{h||(a(R),u(!1))}).catch(R=>{h||(i(R instanceof Error?R:new Error(String(R))),u(!1))});let E=R=>{h||a({...R})};return n.on("statusChange",E),()=>{h=!0,g(!1),n.off("statusChange",E)}},[n,e,t]);let S=l?.status??"idle";return{entry:l,status:S,isLoading:C,isWatching:c,error:r,refresh:f,stopWatching:d}}function js(e){let t=ye(),o=e??t,[s,n]=xt(null),[l,a]=xt(null),[C,u]=xt(null),c=vt(null),g=vt(null),r=vt(null);o&&(g.current||(g.current=p=>{a(p),(!c.current||p.createdAt>=c.current.createdAt)&&(n(p),c.current=p)},o.on("confirmed",g.current)),r.current||(r.current=p=>{u(p),(!c.current||p.createdAt>=c.current.createdAt)&&(n(p),c.current=p)},o.on("failed",r.current)));let i=Gs(()=>{n(null),a(null),u(null),c.current=null},[]);return{lastTx:s,lastConfirmedTx:l,lastFailedTx:C,clear:i}}import{useCallback as Ys}from"react";import{useCallback as zs,useEffect as Wn,useMemo as Qs,useRef as On,useState as At}from"react";import{getResolver as Xs}from"@naculus/connect-appkit-core";function De({input:e,skip:t=!1,resolverConfig:o,scope:s,query:n}){let[l,a]=At(null),[C,u]=At(!1),[c,g]=At(null),r=On(0),i=On(!0);Wn(()=>(i.current=!0,()=>{i.current=!1}),[]);let p=Qs(()=>Xs(o),[o]),f=zs(()=>{let d=e.trim();if(!d||t){r.current+=1,a(null),u(!1),g(null);return}let S=++r.current;u(!0),g(null),n(p,d,s).then(h=>{!i.current||S!==r.current||(a(h),u(!1))}).catch(h=>{!i.current||S!==r.current||(g(h instanceof Error?h:new Error(String(h))),a(null),u(!1))})},[e,t,s,p,n]);return Wn(()=>{f()},[f]),{data:l,isLoading:C,error:c,refetch:f}}function Js(e,t){let o=Ys((s,n,l)=>s.lookupAddress(n,l),[]);return De({input:e,skip:t?.skip,resolverConfig:t?.resolverConfig,scope:t?.chainId,query:o})}import{useState as Nn,useCallback as Y,useMemo as Zs,useEffect as _n,useRef as ea}from"react";import{addInAppNotification as ta,channelsUpdate as na,clearOneInAppNotification as ra,createNotificationSettingsStorage as Dn,DEFAULT_NOTIFICATION_SETTINGS as oa,loadNotificationSettings as sa,mutedChainSettings as Mn,saveNotificationSettings as aa,updateNotificationSettings as ia}from"@naculus/connect-appkit-core";import{InAppChannel as la}from"@naculus/connect-core";function ca(e){let t=ea(null);t.current||(t.current=e?.channel??new la);let o=t.current,[s,n]=Nn(()=>o.getHistory()),[l,a]=Nn(()=>oa);_n(()=>{let h=e?.storage??Dn();sa(h).then(w=>{w&&a(w)})},[]),_n(()=>(o.onNotification=h=>{n(w=>[...w,h])},o.restore().then(()=>{n(o.getHistory())}),()=>{o.onNotification=void 0}),[]);let C=Zs(()=>s.filter(h=>!h.read).length,[s]),u=Y(()=>{o.clear(),n([])},[o]),c=Y(h=>{ra(o,h).then(()=>{n(o.getHistory())})},[o]),g=Y(h=>{o.markAsRead(h),n(w=>w.map(E=>E.id===h?{...E,read:!0}:E))},[o]),r=Y(()=>{o.markAllAsRead(),n(h=>h.map(w=>({...w,read:!0})))},[o]),i=Y(h=>{ta(o,h)},[o]),p=Y(h=>{a(w=>{let E=ia(w,h),R=e?.storage??Dn();return aa(R,E),E})},[e?.storage]),f=Y(h=>{p(na(h))},[p]),d=Y(h=>{p(Mn(l,h,!0))},[l.mutedChains,p]),S=Y(h=>{p(Mn(l,h,!1))},[l.mutedChains,p]);return{notifications:s,unreadCount:C,addNotification:i,clear:u,clearOne:c,markAsRead:g,markAllAsRead:r,settings:l,updateSettings:p,setChannels:f,muteChain:d,unmuteChain:S}}import{useCallback as bt,useSyncExternalStore as ua}from"react";var Ln=()=>null,pa=()=>()=>{};function da(){let{client:e}=U(),t=N(e)?.passphraseGate??null,o=ua(t?.subscribe??pa,t?.getSnapshot??Ln,Ln),s=bt(a=>t?.submit(a),[t]),n=bt(()=>t?.cancel(),[t]),l=bt(a=>t?.forget(a),[t]);return{request:o,submit:s,cancel:n,forget:l,isUnlocked:t?.isUnlocked??!1,gate:t}}import{useCallback as ma}from"react";function fa(e,t){let o=ma((s,n)=>s.resolveName(n),[]);return De({input:e,skip:t?.skip,resolverConfig:t?.resolverConfig,query:o})}import{assertHexSignature as Rt,bareEvmAddress as ga,buildSmartAccountConfig as Ca,resolveUserOpChain as ha}from"@naculus/connect-appkit-core";import{WalletError as ie}from"@naculus/connect-core";import{useCallback as Bn,useEffect as Hn,useRef as Fn,useState as Se}from"react";async function ya(e,t,o,s,n){let l=N(t);if(!l)throw new ie("wallet_unavailable","Client not initialized");let a=[o,s];if(e.walletType==="eip6963"||e.id?.startsWith("eip6963-")){let{eip6963Connector:C}=await import("@naculus/connector-evm-injected"),u=C.getDiscoveredWallets().find(g=>g.id===e.walletId),c=u?await u.provider.request({method:"personal_sign",params:a}):await C.request({method:"personal_sign",params:a});return Rt(c)}if(e.walletType==="walletconnect")return Rt(await l.connector.request({method:"personal_sign",params:a}));if(e.walletType==="embedded"){let C=l.embeddedConnector;if(!C?.signHash)throw new ie("method_unsupported","This embedded wallet build cannot sign a raw digest. Upgrade @naculus/connector-embedded or pass an explicit signer.");return Rt(await C.signHash(e,o))}throw e.walletType==="passkeys"?new ie("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 ie("method_unsupported",`Raw UserOperation signing is not available for ${e.walletType} on ${n}. Pass a signer that signs the raw 32-byte hash.`)}function Sa(e){let{evmAccount:t}=H(),{session:o,chainId:s,client:n}=U(),[l,a]=Se(null),[C,u]=Se(null),[c,g]=Se(!1),[r,i]=Se(!1),[p,f]=Se(null),d=Fn(0),S=Fn(!1);Hn(()=>()=>{d.current+=1,S.current=!1},[]),Hn(()=>{d.current+=1,S.current=!1,a(null),u(null),g(!1),i(!1),f(null)},[n,s,t,e?.accountType,e?.bundlerUrl,e?.chainId,e?.entryPoint,e?.owner,e?.rpcUrl,e?.salt,e?.signerMode,o]);let h=Bn(async(E,R)=>{let A=b=>(f(b),null);if(!e?.rpcUrl)return A(new Error("RPC URL not configured"));if(!e.bundlerUrl)return A(new Error("Bundler URL not configured"));if(!E.length)return A(new Error("At least one call is required"));if(S.current)return A(new Error("A UserOperation is already in progress"));let T=ga(e.owner??t);if(!T)return A(new ie("wallet_unavailable","No EVM account found"));let v;try{v=ha(e.chainId,s)}catch(b){return A(b)}if(!e.signer&&!o)return A(new ie("wallet_unavailable","No active session"));let x=++d.current;S.current=!0,g(!0),i(!0),f(null),a(null),u(null);try{let{SmartAccountManager:b}=await import("@naculus/connect-core"),I=e.signer??(m=>ya(o,n,m,T,v)),W=new b({rpcUrl:e.rpcUrl,bundlerClient:{url:e.bundlerUrl},chainId:v,signer:I,signerMode:e.signer?e.signerMode??"eip191":"raw"}),M=Ca(T,v,e),B=await W.sendUserOperation(M,E,R);return x!==d.current?null:(i(!1),a(B.userOpHash),W.getUserOperationReceipt(B.userOpHash).then(m=>{x===d.current&&u(m)}).catch(()=>{}),B)}catch(b){if(x!==d.current)return null;let I=b instanceof Error?b:new Error("Failed to send UserOperation");return f(I),null}finally{S.current=!1,x===d.current&&(g(!1),i(!1))}},[n,s,t,e,o]),w=Bn(()=>{d.current+=1,a(null),u(null),g(!1),i(!1),f(null)},[]);return{sendUserOp:h,userOpHash:l,receipt:C,isPending:c,isEstimating:r,error:p,reset:w}}import{useSyncExternalStore as Ea,useCallback as Kn}from"react";function wa(e,t){if(!e)return()=>{};let o=()=>t();return e.on("sessionConnected",o),e.on("sessionDisconnected",o),e.on("chainChanged",o),()=>{e.off("sessionConnected",o),e.off("sessionDisconnected",o),e.off("chainChanged",o)}}var Tt=Object.freeze({session:null,chainSessions:[],activeChainId:null,isConnected:!1,connectorId:null}),It=new WeakMap;function ka(e,t){if(e.length!==t.length)return!1;for(let o=0;o<e.length;o++)if(e[o]!==t[o])return!1;return!0}function xa(e){if(!e)return Tt;let t=e.getActiveBundle(),o=It.get(e);if(!t)return o&&o.session===null?o:(It.set(e,Tt),Tt);let s=Array.from(t.chainSessions.values());if(o&&o.session===t.walletSession&&o.activeChainId===t.activeChainId&&ka(o.chainSessions,s))return o;let n={session:t.walletSession,chainSessions:s,activeChainId:t.activeChainId,isConnected:!0,connectorId:t.walletSession.walletType};return It.set(e,n),n}function va(e){let t=U(),o=e??t.sessionManager??null,s=Kn(l=>wa(o,l),[o]),n=Kn(()=>xa(o),[o]);return Ea(s,n)}import{defaultSiwxDomain as Aa,defaultSiwxUri as ba}from"@naculus/connect-appkit-core";import{WalletError as Me}from"@naculus/connect-core";import{createSiwxMessage as Ra,generateNonce as Ta,getBlockchainName as Ia,issueNonce as Ua,nowISO as Pa}from"@naculus/siwx";import{useCallback as qn,useState as Vn}from"react";var Wa=86400;function Ut(){let{session:e,chainId:t,client:o}=U(),[s,n]=Vn(!1),[l,a]=Vn(null),C=qn(()=>a(null),[]);return{signIn:qn(async c=>{if(!e)throw new Me("wallet_unavailable","No active session");let g=c?.chainId??t;if(!g)throw new Me("invalid_chain","No chain to sign for. Connect a wallet or pass options.chainId.");let r=oe(e,g);if(!r)throw new Me("wallet_unavailable","No account found");let i=N(o);if(!i)throw new Me("wallet_unavailable","Client not initialized");let{address:p}=r,f=typeof window>"u"?void 0:window.location,d=c?.domain??Aa(f),S=c?.uri??ba(f);n(!0),a(null);try{let h=Ta();await Ua(h);let w=Pa(),E=c?.expirySeconds??Wa,R=new Date(Date.now()+E*1e3).toISOString(),A=Ra({domain:d,address:p,uri:S,version:1,chainId:g,nonce:h,issuedAt:w,expirationTime:R,statement:c?.statement,resources:c?.resources,requestId:c?.requestId}),T=await i.signMessage(e,{message:A,address:p,chainId:g??void 0}),v={message:{raw:A,domain:d,address:p,statement:c?.statement??null,uri:S,version:1,chainId:g,nonce:h,issuedAt:w,blockchain:Ia(g),expirationTime:R,notBefore:null,resources:c?.resources??[],requestId:c?.requestId??null},signature:T};return n(!1),v}catch(h){let w=h instanceof Error?h:new Error("SIWx sign-in failed");throw a(w),n(!1),w}},[e,t,o]),isSigningIn:s,error:l,clearError:C}}import{siwxResultToSession as $n}from"@naculus/connect-appkit-core";import{logger as Pt}from"@naculus/connect-core";import{checkSessionExpired as Gn,createLocalStorageSiwxSessionStorage as Oa}from"@naculus/siwx";import{useCallback as Le,useEffect as jn,useRef as Na,useState as Be}from"react";function _a(e){let{storagePrefix:t="naculus_",autoRestore:o=!0,defaultExpirySeconds:s=86400}=e??{},[n,l]=Be(null),[a,C]=Be(o),[u,c]=Be(!1),[g,r]=Be(null),{session:i,chainId:p}=U(),f=Ut(),d=Na(Oa(`${t}siwx_session`)),S=Le(()=>r(null),[]);jn(()=>{if(!o){C(!1);return}let v=!1;return(async()=>{try{let b=await d.current.get();if(v)return;b?(Pt.info("react/useSIWxSession","Restored persisted SIWx session"),l(b),r(null)):l(null)}catch(x){Pt.warn("react/useSIWxSession","Failed to restore SIWx session:",x),l(null)}finally{v||C(!1)}})(),()=>{v=!0}},[o]),jn(()=>{if(!n?.expiresAt)return;let v=new Date(n.expiresAt).getTime()-Date.now();if(v<=0){l(null);return}let x=setTimeout(()=>{l(b=>b&&b.id===n.id?null:b)},v);return()=>clearTimeout(x)},[n?.id,n?.expiresAt]);let h=Le(async v=>{c(!0),r(null);try{let x={expirySeconds:s,chainId:p??void 0,...v},b=await f.signIn(x),I=$n(b);return await d.current.set(I),l(I),c(!1),I}catch(x){let b=x instanceof Error?x:new Error("SIWx sign-in failed");throw r(b),c(!1),b}},[f,p,s]),w=Le(async()=>{try{await d.current.remove()}catch(v){Pt.warn("react/useSIWxSession","Failed to clear session:",v)}l(null),r(null)},[]),E=Le(async()=>{if(!n)throw new Error("No active session to refresh");c(!0),r(null);try{let v=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}),x={...$n(v),id:n.id,refreshedAt:new Date().toISOString()};return await d.current.set(x),l(x),c(!1),x}catch(v){let x=v instanceof Error?v:new Error("Session refresh failed");throw r(x),c(!1),x}},[n,f,s]),R=n!==null&&!Gn(n),A=Gn(n),T=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:A,timeUntilExpiry:T,signIn:h,signOut:w,refresh:E,error:g,clearError:S}}import{defaultSiwxDomain as Da,defaultSiwxUri as Ma}from"@naculus/connect-appkit-core";import{WalletError as He}from"@naculus/connect-core";import{createSiwxMessage as La,generateNonce as Ba,getBlockchainName as Ha,issueNonce as Fa,nowISO as Ka}from"@naculus/siwx";import{useCallback as zn,useState as Wt}from"react";function Ee(){let{session:e,chainId:t,client:o}=U(),[s,n]=Wt(!1),[l,a]=Wt(null),[C,u]=Wt(null),c=zn(()=>u(null),[]);return{signIn:zn(async r=>{if(!e)throw new He("wallet_unavailable","No active session");let i=r?.chainId??t;if(!i)throw new He("invalid_chain","No chain to sign for. Connect a wallet or pass options.chainId.");let p=oe(e,i);if(!p)throw new He("wallet_unavailable","No account found");let f=N(o);if(!f)throw new He("wallet_unavailable","Client not initialized");let{address:d}=p,S=typeof window>"u"?void 0:window.location,h=r?.domain??Da(S),w=r?.uri??Ma(S);n(!0),u(null);try{let E=Ba();await Fa(E);let R=Ka(),A=La({domain:h,address:d,uri:w,version:1,chainId:i,nonce:E,issuedAt:R,statement:r?.statement,expirationTime:r?.expirySeconds?new Date(Date.now()+r.expirySeconds*1e3).toISOString():void 0,resources:r?.resources,requestId:r?.requestId}),T=await f.signMessage(e,{message:A,address:d,chainId:i??void 0}),v=r?.expirySeconds?new Date(Date.now()+r.expirySeconds*1e3).toISOString():null,x={message:{raw:A,domain:h,address:d,statement:r?.statement??null,uri:w,version:1,chainId:i,nonce:E,issuedAt:R,blockchain:Ha(i),expirationTime:v,notBefore:null,resources:r?.resources??[],requestId:r?.requestId??null},signature:T};return a(x),x}catch(E){let R=E instanceof Error?E:new Error("SIWx sign-in failed");throw u(R),R}finally{n(!1)}},[e,t,o]),isSigningIn:s,result:l,error:C,clearError:c}}import{WalletError as Ot}from"@naculus/connect-core";import{useCallback as Qn}from"react";function qa(){let{session:e,chainId:t}=U();return Qn(o=>{if(!e)throw new Ot("wallet_unavailable","No active session");let s=o??t;if(s&&!s.startsWith("eip155:"))throw new Ot("namespace_mismatch",`Ethereum SIWx requires an eip155 chain, received ${s}`);let n=e.namespaces.eip155;if(!n||n.accounts.length===0)throw new Ot("namespace_mismatch","No EVM (eip155) accounts found in session")},[e,t])}function Va(){let e=qa(),t=Ee();return{signIn:Qn(async s=>(e(s?.chainId),t.signIn(s)),[e,t.signIn]),isSigningIn:t.isSigningIn,result:t.result,error:t.error,clearError:t.clearError}}import{resolveSimulationEndpoint as $a}from"@naculus/connect-appkit-core";import{SimulationManager as Ga}from"@naculus/wallet-engine";import{useCallback as Nt,useRef as ja,useState as _t}from"react";function za(e){let t=e?.rpcUrl,o=e?.chainId,s=ja(null),n=Nt(()=>(s.current||(s.current=new Ga({enabled:!0,rpcUrl:t,autoSimulate:!1})),s.current),[t]),[l,a]=_t(null),[C,u]=_t(!1),[c,g]=_t(null),r=Nt(async(p,f,d,S,h)=>{u(!0),g(null);try{let w=n(),E=$a(h?.chainId,o,h?.rpcUrl,t),R=await w.simulateERC20Transfer(p,f,d,S,E.chainId,h?.decimals,E.rpcUrl);return a(R),R}catch(w){let E=w instanceof Error?w:new Error(String(w));throw g(E),E}finally{u(!1)}},[t,o,n]),i=Nt(()=>{a(null),g(null),u(!1)},[]);return{result:l,loading:C,error:c,simulate:r,reset:i}}import{isSiwxExpired as Qa,isSiwxNotBeforeValid as Xa}from"@naculus/connect-appkit-core";import{LocalStorageAdapter as Ya,logger as Fe}from"@naculus/connect-core";import{useCallback as Dt,useEffect as Ja,useRef as Za,useState as Ke}from"react";var qe="siwx_auth";function ei(e){return new Ya(e)}function ti(e){let{storagePrefix:t="naculus_",autoRestore:o=!0}=e??{},[s,n]=Ke(null),[l,a]=Ke(o),[C,u]=Ke(!1),[c,g]=Ke(null),r=Ee(),i=Za(ei(t)),p=Dt(()=>g(null),[]);Ja(()=>{if(!o){a(!1);return}let S=!1;return(async()=>{try{let h=i.current,w=await h.get(qe);if(S)return;w&&!Qa(w,new Date)&&Xa(w,new Date)?(Fe.info("react/useSiwxAuthSession","Restored persisted SIWx auth session"),n(w),g(null)):w&&(Fe.info("react/useSiwxAuthSession","Persisted SIWx auth expired, clearing"),await h.remove(qe))}catch(h){Fe.warn("react/useSiwxAuthSession","Failed to restore SIWx auth:",h)}finally{S||a(!1)}})(),()=>{S=!0}},[o]);let f=Dt(async S=>{u(!0),g(null);try{let h=await r.signIn(S);return await i.current.set(qe,h),n(h),u(!1),h}catch(h){let w=h instanceof Error?h:new Error("SIWx sign-in failed");throw g(w),u(!1),w}},[r]),d=Dt(async()=>{try{await i.current.remove(qe)}catch(S){Fe.warn("react/useSiwxAuthSession","Failed to clear SIWx auth:",S)}n(null),g(null)},[]);return{isSignedIn:s!==null,isRestoring:l,siwxResult:s,isSigningIn:C,error:c,signIn:f,signOut:d,clearError:p}}import{bareEvmAddress as ni,buildSmartAccountConfig as ri,resolveEvmChainId as Xn}from"@naculus/connect-appkit-core";import{WalletError as Zn}from"@naculus/connect-core";import{useCallback as ne,useEffect as Yn,useRef as Mt,useState as we}from"react";function Jn(e){return new Zn("wallet_unavailable",e)}function oi(e){let{evmAccount:t}=H(),{session:o,chainId:s,client:n}=U(),[l,a]=we(null),[C,u]=we(!1),[c,g]=we(null),[r,i]=we(!1),[p,f]=we(null),d=Mt(null),S=Mt(0),h=Mt(!1);Yn(()=>{if(d.current=null,!e?.rpcUrl)return;let b=!1;return import("@naculus/connect-core").then(({SmartAccountManager:I})=>{if(b)return;let W=Xn(e.chainId,s);W&&(d.current=new I({rpcUrl:e.rpcUrl,chainId:W,bundlerClient:{url:e.bundlerUrl??""}}))}).catch(I=>{b||f(I instanceof Error?I:new Error("Failed to load account-abstraction module"))}),()=>{b=!0}},[s,e?.rpcUrl,e?.bundlerUrl,e?.chainId]),Yn(()=>{S.current+=1,h.current=!1,a(null),u(!1),g(null),i(!1),f(null)},[t,s,e?.rpcUrl,e?.bundlerUrl,e?.chainId,e?.entryPoint,e?.accountType,e?.salt]);let w=ne(()=>{let b=ni(t);if(!b||!d.current)return null;let I=Xn(e?.chainId,s);return I?ri(b,I,{accountType:e?.accountType,entryPoint:e?.entryPoint,salt:e?.salt}):null},[t,s,e?.accountType,e?.chainId,e?.entryPoint,e?.salt]),E=ne(b=>(f(b),null),[]),R=ne(()=>h.current?null:(h.current=!0,S.current),[]),A=ne(b=>{S.current===b&&(h.current=!1)},[]),T=ne(async()=>{let b=w();if(!b||!d.current)return E(new Error("Smart account not configured"));let I=R();if(I===null)return E(new Error("Smart account operation already in progress"));i(!0),f(null);try{let M=await d.current.createAccount(b);return S.current!==I?null:(a(M.address),u(M.isDeployed),g(M),M)}catch(W){if(S.current!==I)return null;let M=W instanceof Error?W:new Error("Failed to create smart account");return f(M),null}finally{S.current===I&&i(!1),A(I)}},[R,E,A,w]),v=ne(async()=>{let b=w();if(!b||!d.current)return E(new Error("Smart account not configured"));if(!o)return E(Jn("No active session"));let I=N(n);if(!I)return E(Jn("Client not initialized"));if(s&&s!==b.chainId)return E(new Zn("chain_mismatch",`Connected chain ${s} does not match smart account chain ${b.chainId}.`));let W=R();if(W===null)return E(new Error("Smart account operation already in progress"));i(!0),f(null);try{let M=d.current,B=await M.createAccount(b);if(S.current!==W)return null;if(B.isDeployed)return a(B.address),u(!0),g(B),B.address;let m=await M.getDeployCallData(b),y=await I.sendTransaction(o,{transaction:{to:m.to,data:m.data,value:m.value.toString()},chainId:b.chainId});if(S.current!==W)return null;let k=await M.createAccount(b);return a(k.address),u(k.isDeployed),g(k),y}catch(M){if(S.current!==W)return null;let B=M instanceof Error?M:new Error("Failed to deploy smart account");return f(B),null}finally{S.current===W&&i(!1),A(W)}},[n,s,R,E,A,w,o]),x=ne(async()=>{let b=w();if(!b||!d.current)return null;let I=S.current;try{let W=await d.current.getAccountAddress(b);return S.current!==I?null:(a(W),W)}catch(W){return S.current!==I||f(W instanceof Error?W:new Error("Failed to get smart account address")),null}},[w]);return{address:l,isDeployed:C,accountInfo:c,isLoading:r,error:p,createWallet:T,deployWallet:v,getAddress:x}}import{useMemo as si}from"react";function Lt(){let{accounts:e,isConnected:t}=U();return si(()=>{if(!t)return{address:null,caip10:null,chainId:null,isConnected:!1};let o=e.find(a=>a.startsWith("solana:"))??null;if(!o)return{address:null,caip10:null,chainId:null,isConnected:t};let s=o.split(":"),n=s.length>=3?s[s.length-1]:null,l=s.length>=3?s.slice(0,-1).join(":"):null;return{address:n,caip10:o,chainId:l,isConnected:t}},[e,t])}import{useCallback as ai,useEffect as er,useRef as ii,useState as Bt}from"react";import{getSolanaBalance as li}from"@naculus/connect-core";function ci(e={}){let{client:t}=U(),{address:o}=Lt(),s=e.address??o,n=e.rpcUrl??N(t)?.solanaRpcUrl??null,[l,a]=Bt(null),[C,u]=Bt(!1),[c,g]=Bt(null),r=ii(0),i=ai(async()=>{if(!s||!n){a(null);return}let p=++r.current;u(!0),g(null);try{let f=await li(n,s);if(p!==r.current)return;a(f)}catch(f){if(p!==r.current)return;a(null),g(f instanceof Error?f:new Error("Balance read failed"))}finally{p===r.current&&u(!1)}},[s,n]);return er(()=>{i()},[i]),er(()=>{if(!e.refreshInterval||e.refreshInterval<=0)return;let p=setInterval(()=>{i()},e.refreshInterval);return()=>clearInterval(p)},[e.refreshInterval,i]),{balance:l,isFetching:C,error:c,isConfigured:!!n,refetch:i}}import{readSolanaRoles as ui}from"@naculus/connect-appkit-core";import{useMemo as pi}from"react";function di(){let{client:e,session:t,accounts:o}=U();return pi(()=>{let s=N(e)?.solanaConnector,{roles:n,absence:l}=ui(s,t);return{roles:n,absence:l,identity:n?.identity??null,signer:n?.signer??null,payer:n?.payer??null}},[e,t,o])}import{WalletError as tr}from"@naculus/connect-core";import{useCallback as Ht,useState as Ft}from"react";import{getSignatureStatus as mi}from"@naculus/connect-core";function fi(){let{client:e,session:t}=U(),[o,s]=Ft(!1),[n,l]=Ft(!1),[a,C]=Ft(null),u=()=>{let i=N(e);if(!i||!t)throw new tr("wallet_unavailable","No connected wallet.");return i},c=Ht(async i=>{s(!0),C(null);try{return await u().signTransaction(t,{transaction:i})}catch(p){let f=p instanceof Error?p:new Error("Signing failed");throw C(f),f}finally{s(!1)}},[e,t]),g=Ht(async i=>{l(!0),C(null);try{return await u().sendTransaction(t,{transaction:i})}catch(p){let f=p instanceof Error?p:new Error("Send failed");throw C(f),f}finally{l(!1)}},[e,t]),r=Ht(async i=>{let p=N(e)?.solanaRpcUrl;if(!p)throw new tr("no_rpc","Set solanaRpcUrl on the client to read a signature's status.");return mi(p,i)},[e]);return{signTransaction:c,sendTransaction:g,getStatus:r,isSigning:o,isSending:n,error:a,reset:()=>C(null)}}import{useCallback as nr,useState as rr}from"react";import{toChainSwitchError as gi}from"@naculus/connect-appkit-core";function Ci(){let{switchChain:e,chainId:t}=U(),[o,s]=rr(!1),[n,l]=rr(null),a=nr(async u=>{s(!0),l(null);try{await e(u)}catch(c){let g=gi(c);throw l(g),g}finally{s(!1)}},[e]),C=nr(()=>{l(null)},[]);return{switchChain:a,isSwitching:o,currentChainId:t,error:n,clearError:C}}import{chainNumber as hi,resolveChain as yi,toViemChain as Si}from"@naculus/connect-appkit-core";import{useState as Ve,useEffect as Kt,useCallback as or,useMemo as qt,useRef as Ei}from"react";import{createPublicClient as wi,http as ki,formatUnits as xi}from"viem";function vi(e){let{evmAccount:t,isConnected:o}=H(),{chainId:s,chains:n}=U(),[l,a]=Ve([]),[C,u]=Ve(!1),[c,g]=Ve(null),{tokens:r,refreshInterval:i}=e,p=Ei(null),f=qt(()=>r.map(v=>v.address.toLowerCase()+"|"+v.decimals+"|"+v.symbol).join(","),[r]),d=qt(()=>yi(n,s),[s,n]),S=d?hi(d):null,h=qt(()=>d?Si(d,S):null,[d,S]),[w,E]=Ve(null);Kt(()=>{if(!h||!d?.rpcUrl){E(null);return}let v=wi({transport:ki(d.rpcUrl),chain:h});E(v)},[d,h]);let R=[{name:"balanceOf",type:"function",stateMutability:"view",inputs:[{name:"owner",type:"address"}],outputs:[{name:"balance",type:"uint256"}]}],A=or(async()=>{if(!t||!w||r.length===0){a([]);return}u(!0),g(null);try{let v=t.includes(":")?t.split(":").pop():t,b=(await Promise.allSettled(r.map(async I=>{try{let W=await w.readContract({address:I.address,abi:R,functionName:"balanceOf",args:[v]});return{address:I.address,symbol:I.symbol,decimals:I.decimals,name:I.name,balance:W.toString(),formatted:xi(W,I.decimals)}}catch{return{address:I.address,symbol:I.symbol,decimals:I.decimals,name:I.name,balance:null,formatted:null}}}))).map(I=>I.status==="fulfilled"?I.value:{address:"",symbol:"?",decimals:0,balance:null,formatted:null});a(b)}catch(v){g(v instanceof Error?v:new Error("Failed to fetch token balances"))}finally{u(!1)}},[t,w,f]);Kt(()=>{o&&t&&r.length>0&&A()},[o,t,f,A]),Kt(()=>(i&&i>0&&o&&t&&r.length>0&&(p.current=setInterval(A,i)),()=>{p.current&&(clearInterval(p.current),p.current=null)}),[i,o,t,f,A]);let T=or(v=>l.find(x=>x.address.toLowerCase()===v.toLowerCase()),[l]);return{tokenBalances:l,isLoading:C,error:c,refetch:A,getTokenBalance:T,chain:d}}import{useState as Vt,useEffect as sr,useCallback as Ai,useRef as bi}from"react";function Ri(e,t,o){let s=ye(),n=o??s,[l,a]=Vt([]),[C,u]=Vt(!1),[c,g]=Vt(null),r=bi(0),i=Ai(async()=>{if(n){u(!0),g(null),r.current++;try{let f=await n.getTxHistory(e,t);a(f)}catch(f){g(f instanceof Error?f:new Error(String(f)))}finally{u(!1)}}},[n,e,t]);sr(()=>{i().catch(()=>{})},[i]),sr(()=>{if(!n)return;let f=()=>{i().catch(()=>{})};return n.on("statusChange",f),()=>{n.off("statusChange",f)}},[n,i]);let p={pending:l.filter(f=>f.status==="pending").length,confirmed:l.filter(f=>f.status==="confirmed").length,failed:l.filter(f=>f.status==="failed").length};return{entries:l,isLoading:C,error:c,refresh:i,summary:p}}import{fetchUserOperationReceipt as Ti,InvalidUserOperationReceiptError as Ii}from"@naculus/connect-appkit-core";import{useCallback as ke,useEffect as ar,useRef as le,useState as re}from"react";function Ui(e){let t=e?.bundlerUrl,o=e?.pollInterval??2e3,s=e?.maxRetries??30,[n,l]=re("idle"),[a,C]=re(null),[u,c]=re(e?.userOpHash??null),[g,r]=re(null),[i,p]=re(!1),[f,d]=re(0),S=le(0),[h,w]=re(0),E=le(null),R=le(null),A=le(0),T=le(0),v=le(null),x=ke(()=>{E.current&&(clearInterval(E.current),E.current=null),R.current&&(clearTimeout(R.current),R.current=null)},[]),b=ke(async(B,m)=>{if(!t||m!==A.current)return;let y=T.current+1;T.current=y,d(y);let k=new AbortController;v.current=k;let P=L=>{m===A.current&&(l("not_found"),p(!1),x(),r(L))},O=L=>{if(m===A.current){if(y<=s){R.current=setTimeout(()=>{b(B,m)},o);return}P(L)}};try{let L=await Ti(t,B,k.signal);if(m!==A.current)return;if(L){C(L),l(L.success?"confirmed":"failed"),p(!1),x();return}l("pending"),O(new Error("UserOperation not included after maximum retries"))}catch(L){if(m!==A.current||k.signal.aborted)return;let te=L instanceof Error?L:new Error("Unknown bundler response failure");if(te instanceof Ii){P(te);return}O(new Error(`UserOperation status unavailable after ${y} attempt${y===1?"":"s"}: ${te.message}`))}finally{v.current===k&&(v.current=null)}},[t,o,s,x]),I=ke(B=>{A.current+=1;let m=A.current;if(v.current?.abort(),v.current=null,x(),c(B),C(null),r(null),T.current=0,d(0),w(0),S.current=Date.now(),!t){l("not_found"),p(!1),r(new Error("Bundler URL not configured"));return}l("pending"),p(!0),E.current=setInterval(()=>{w(Date.now()-S.current)},1e3),b(B,m)},[t,x,b]),W=ke(()=>{A.current+=1,v.current?.abort(),v.current=null,x(),p(!1)},[x]),M=ke(()=>{A.current+=1,v.current?.abort(),v.current=null,x(),c(null),l("idle"),C(null),r(null),p(!1),T.current=0,d(0),w(0)},[x]);return ar(()=>{e?.userOpHash&&e?.autoStart!==!1&&I(e.userOpHash)},[]),ar(()=>()=>{A.current+=1,v.current?.abort(),v.current=null,x()},[x]),{status:n,receipt:a,userOpHash:u,error:g,isPolling:i,elapsedMs:h,attempts:f,start:I,stop:W,reset:M}}import{validateDestination as _i}from"@naculus/connect-appkit-core";import{useMemo as Di}from"react";var Pi={"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."},Wi={"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"},ir={en:Pi,zh:Wi},$t="en";function Oi(e){$t=e}function Ni(){return $t}function Gt(e){return ir[$t][e]??ir.en[e]??e}function lr(e){let{isValid:t,level:o,issue:s}=_i(e);return{isValid:t,level:o,warning:s?Gt(`address.${s}`):null}}function Mi({address:e}){return{validation:Di(()=>lr(e),[e])}}function Li(){let{status:e,session:t,accounts:o,chainId:s,error:n,connect:l,disconnect:a,reconnect:C,switchChain:u}=U(),c=e==="connected",g=e==="connecting",r=e==="reconnecting",i=o[0]??null;return{status:e,session:t,accounts:o,chainId:s,error:n,isConnected:c,isConnecting:g,isReconnecting:r,isDisconnected:e==="disconnected",currentAccount:i,connect:l,disconnect:a,reconnect:C,switchChain:u}}import{useCallback as zt,useMemo as pr}from"react";var cr={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"},ur={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."},xe="Something went wrong",ve="An unexpected error occurred. Please try again. If the problem persists, check your connection and wallet configuration.";function Ae(e){if(!e)return{title:xe,description:ve};let t=e;if(t.name==="WalletError"&&t.code){let o=t.code,s=cr[o]??xe,n=ur[o]??t.message??ve;return{title:s,description:n,code:o}}if(e instanceof Error){let o=e.message;return/user rejected/i.test(o)||/rejected/.test(o)?{title:"Request Rejected",description:"The request was declined.",code:"user_rejected"}:/timeout/i.test(o)||/timed? ?out/i.test(o)?{title:"Request Timed Out",description:"The request took too long. Please try again.",code:"deeplink_timeout"}:/insufficient funds/i.test(o)?{title:"Insufficient Funds",description:"You don't have enough funds to complete this transaction.",code:"tx_failed"}:/network/i.test(o)||/chain/i.test(o)?{title:"Network Error",description:o,code:"chain_unsupported"}:{title:xe,description:o||ve}}return typeof e=="string"?{title:xe,description:e||ve}:{title:xe,description:ve}}function jt(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 Bi(){let{error:e,clearError:t}=U(),o=pr(()=>e?Ae(e):null,[e]),s=pr(()=>e?jt(e):!1,[e]),n=zt(()=>{t()},[t]),l=zt(C=>Ae(C),[]),a=zt(C=>async()=>{try{return await C()}catch(u){let c=Ae(u);if(u instanceof Error){let g=u;try{g.title=c.title,g.friendlyMessage=c.description,g.code===void 0&&c.code!==void 0&&(g.code=c.code)}catch{}throw g}throw Object.assign(new Error(c.description,{cause:u}),{title:c.title,code:c.code,friendlyMessage:c.description})}},[]);return{error:e,friendlyError:o,clearError:n,isRetryable:s,formatError:l,wrapAsync:a}}import{useState as $e,useEffect as Hi,useCallback as dr,useRef as Fi}from"react";import{TokenListManager as Ki}from"@naculus/connect-core";import{eip155ChainIdToNumber as mr}from"@naculus/connect-appkit-core";function Ge(e,t){let o=Fi(null),[s,n]=$e([]),[l,a]=$e(t?.autoLoad!==!1),[C,u]=$e(!1),[c,g]=$e(null);if(!o.current){let p={};t?.sources&&(p.sources=t.sources),o.current=new Ki(p)}let r=dr(async()=>{let p=o.current;if(p){a(!0),g(null);try{await p.load();let f=e?mr(e):void 0,d=p.getTokens(f!==void 0?{chainId:f}:void 0);n(d),u(!0)}catch(f){g(f instanceof Error?f:new Error(String(f)))}finally{a(!1)}}},[e]),i=dr(async()=>{let p=o.current;if(p){a(!0),g(null);try{await p.refresh();let f=e?mr(e):void 0,d=p.getTokens(f!==void 0?{chainId:f}:void 0);n(d),u(!0)}catch(f){g(f instanceof Error?f:new Error(String(f)))}finally{a(!1)}}},[e]);return Hi(()=>{t?.autoLoad!==!1&&r()},[r,t?.autoLoad]),{tokens:s,isLoading:l,isLoaded:C,error:c,refetch:i}}import{useState as gr,useEffect as zi,useRef as Qi}from"react";import{TokenListManager as Xi}from"@naculus/connect-core";import{ETHEREUM_MAINNET_TOKENS as qi,POLYGON_TOKENS as Vi,OPTIMISM_TOKENS as $i,ARBITRUM_TOKENS as Gi,BASE_TOKENS as ji}from"@naculus/connect-core";function fr(){return[{name:"built-in",tokens:[...qi,...Vi,...$i,...Gi,...ji],enabled:!0},{name:"uniswap-default",url:"https://tokens.uniswap.org",enabled:!0,refreshInterval:1440*60*1e3}]}import{eip155ChainIdToNumber as Yi}from"@naculus/connect-appkit-core";var Ji=300,je=null;function Zi(){return je||(je=new Xi({sources:fr()}),je.load().catch(()=>{})),je}function ze(e,t){let[o,s]=gr({exact:[],fuzzy:[],hasMore:!1}),[n,l]=gr(!1),a=Qi(null),C=e.trim();return zi(()=>{if(!C){s({exact:[],fuzzy:[],hasMore:!1}),l(!1);return}return a.current&&clearTimeout(a.current),l(!0),a.current=setTimeout(()=>{let u=Zi(),c=t?Yi(t):void 0,g=u.search(C,{chainId:c,limit:20});s(g),l(!1)},Ji),()=>{a.current&&clearTimeout(a.current)}},[C,t]),{results:o,isSearching:n}}import Qt,{useCallback as el}from"react";import{Fragment as tl,jsx as $,jsxs as j}from"react/jsx-runtime";function Cr({chainId:e,onSelect:t,onClose:o,options:s}){let[n,l]=Qt.useState(""),{tokens:a,isLoading:C,error:u}=Ge(e),{results:c,isSearching:g}=ze(n,n?e:void 0),r=s?.showRecommendations??!0,i=Qt.useMemo(()=>{if(n.trim()){let S=[...c.exact,...c.fuzzy].map(h=>h.token);return s?.filter?S.filter(s.filter):S}let d=a;return s?.filter?d.filter(s.filter):d},[n,c,a,s?.filter]),p=Qt.useMemo(()=>!r||n.trim()?[]:a.slice(0,6),[a,r,n]),f=el(d=>{t(d),o()},[t,o]);return j("div",{style:{background:"hsl(var(--background))",borderRadius:"12px",padding:"16px",color:"hsl(var(--foreground))",minWidth:"320px",maxWidth:"400px",fontFamily:"system-ui, sans-serif"},children:[j("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"12px"},children:[$("h3",{style:{margin:0,fontSize:"16px",fontWeight:600},children:"Select Token"}),$("button",{onClick:o,style:{background:"none",border:"none",color:"hsl(var(--muted-foreground))",cursor:"pointer",fontSize:"18px",padding:"4px 8px"},children:"\u2715"})]}),$("input",{type:"text",placeholder:"Search token name or paste address",value:n,onChange:d=>l(d.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}),C&&!g&&$("div",{style:{textAlign:"center",padding:"20px",color:"hsl(var(--muted-foreground))"},children:"Loading tokens..."}),u&&j("div",{style:{textAlign:"center",padding:"12px",color:"hsl(var(--destructive))",fontSize:"13px"},children:["Error: ",u.message]}),r&&p.length>0&&!n.trim()&&j("div",{style:{marginBottom:"12px"},children:[$("div",{style:{fontSize:"11px",color:"hsl(var(--muted-foreground))",textTransform:"uppercase",letterSpacing:"0.5px",marginBottom:"8px"},children:"Popular"}),$("div",{style:{display:"flex",gap:"6px",flexWrap:"wrap"},children:p.map(d=>j("button",{onClick:()=>f(d),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:[d.logoURI?$("img",{src:d.logoURI,alt:"",style:{width:"16px",height:"16px",borderRadius:"50%"},onError:S=>{S.target.style.display="none"}}):null,d.symbol]},`${d.chainId}:${d.address}`))})]}),n.trim()&&!C&&$("div",{style:{fontSize:"11px",color:"hsl(var(--muted-foreground))",marginBottom:"8px"},children:i.length>0?j(tl,{children:[c.exact.length," exact, ",c.fuzzy.length," fuzzy",c.hasMore?" (more available)":""]}):"No results found"}),$("div",{style:{maxHeight:"320px",overflowY:"auto",display:"flex",flexDirection:"column",gap:"2px"},children:i.map(d=>j("button",{onClick:()=>f(d),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:S=>{S.target.style.background="hsl(var(--card))"},onMouseLeave:S=>{S.target.style.background="transparent"},children:[$("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:d.logoURI?$("img",{src:d.logoURI,alt:d.symbol,style:{width:"100%",height:"100%"},onError:S=>{let h=S.target;h.style.display="none",h.parentElement.textContent=d.symbol.slice(0,2)}}):d.symbol.slice(0,2)}),j("div",{style:{flex:1,minWidth:0},children:[$("div",{style:{fontWeight:600,fontSize:"14px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d.symbol}),$("div",{style:{fontSize:"12px",color:"hsl(var(--muted-foreground))",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d.name})]}),j("div",{style:{fontSize:"11px",color:"#666",textAlign:"right",flexShrink:0},children:[j("div",{children:[d.decimals," decimals"]}),j("div",{children:["Chain ",d.chainId]})]})]},`${d.chainId}:${d.address}`))})]})}import{createComponent as _}from"@stencil/react-output-target/runtime";import D from"react";import{AppkitAccordion as nl,defineCustomElement as rl}from"@naculus/connect-appkit-wc/dist/components/appkit-accordion.js";import{AppkitAccountButton as ol,defineCustomElement as sl}from"@naculus/connect-appkit-wc/dist/components/appkit-account-button.js";import{AppkitAlertDialog as al,defineCustomElement as il}from"@naculus/connect-appkit-wc/dist/components/appkit-alert-dialog.js";import{AppkitAvatar as ll,defineCustomElement as cl}from"@naculus/connect-appkit-wc/dist/components/appkit-avatar.js";import{AppkitBadge as ul,defineCustomElement as pl}from"@naculus/connect-appkit-wc/dist/components/appkit-badge.js";import{AppkitButton as dl,defineCustomElement as ml}from"@naculus/connect-appkit-wc/dist/components/appkit-button.js";import{AppkitCardContent as fl,defineCustomElement as gl}from"@naculus/connect-appkit-wc/dist/components/appkit-card-content.js";import{AppkitCardDescription as Cl,defineCustomElement as hl}from"@naculus/connect-appkit-wc/dist/components/appkit-card-description.js";import{AppkitCardFooter as yl,defineCustomElement as Sl}from"@naculus/connect-appkit-wc/dist/components/appkit-card-footer.js";import{AppkitCardHeader as El,defineCustomElement as wl}from"@naculus/connect-appkit-wc/dist/components/appkit-card-header.js";import{AppkitCardTitle as kl,defineCustomElement as xl}from"@naculus/connect-appkit-wc/dist/components/appkit-card-title.js";import{AppkitCard as vl,defineCustomElement as Al}from"@naculus/connect-appkit-wc/dist/components/appkit-card.js";import{AppkitCheckbox as bl,defineCustomElement as Rl}from"@naculus/connect-appkit-wc/dist/components/appkit-checkbox.js";import{AppkitCollapsible as Tl,defineCustomElement as Il}from"@naculus/connect-appkit-wc/dist/components/appkit-collapsible.js";import{AppkitConnectButton as Ul,defineCustomElement as Pl}from"@naculus/connect-appkit-wc/dist/components/appkit-connect-button.js";import{AppkitDialog as Wl,defineCustomElement as Ol}from"@naculus/connect-appkit-wc/dist/components/appkit-dialog.js";import{AppkitDropdownMenu as Nl,defineCustomElement as _l}from"@naculus/connect-appkit-wc/dist/components/appkit-dropdown-menu.js";import{AppkitInput as Dl,defineCustomElement as Ml}from"@naculus/connect-appkit-wc/dist/components/appkit-input.js";import{AppkitPopover as Ll,defineCustomElement as Bl}from"@naculus/connect-appkit-wc/dist/components/appkit-popover.js";import{AppkitProgress as Hl,defineCustomElement as Fl}from"@naculus/connect-appkit-wc/dist/components/appkit-progress.js";import{AppkitScrollArea as Kl,defineCustomElement as ql}from"@naculus/connect-appkit-wc/dist/components/appkit-scroll-area.js";import{AppkitSelect as Vl,defineCustomElement as $l}from"@naculus/connect-appkit-wc/dist/components/appkit-select.js";import{AppkitSeparator as Gl,defineCustomElement as jl}from"@naculus/connect-appkit-wc/dist/components/appkit-separator.js";import{AppkitSkeleton as zl,defineCustomElement as Ql}from"@naculus/connect-appkit-wc/dist/components/appkit-skeleton.js";import{AppkitSwitch as Xl,defineCustomElement as Yl}from"@naculus/connect-appkit-wc/dist/components/appkit-switch.js";import{AppkitTabs as Jl,defineCustomElement as Zl}from"@naculus/connect-appkit-wc/dist/components/appkit-tabs.js";import{AppkitToggleGroup as ec,defineCustomElement as tc}from"@naculus/connect-appkit-wc/dist/components/appkit-toggle-group.js";import{AppkitTooltip as nc,defineCustomElement as rc}from"@naculus/connect-appkit-wc/dist/components/appkit-tooltip.js";var oc=_({tagName:"appkit-accordion",elementClass:nl,react:D,events:{onAppkitToggle:"appkitToggle"},defineCustomElement:rl}),sc=_({tagName:"appkit-account-button",elementClass:ol,react:D,events:{},defineCustomElement:sl}),ac=_({tagName:"appkit-alert-dialog",elementClass:al,react:D,events:{onAppkitClose:"appkitClose",onAppkitOpenChange:"appkitOpenChange"},defineCustomElement:il}),ic=_({tagName:"appkit-avatar",elementClass:ll,react:D,events:{},defineCustomElement:cl}),lc=_({tagName:"appkit-badge",elementClass:ul,react:D,events:{},defineCustomElement:pl}),cc=_({tagName:"appkit-button",elementClass:dl,react:D,events:{},defineCustomElement:ml}),uc=_({tagName:"appkit-card",elementClass:vl,react:D,events:{},defineCustomElement:Al}),pc=_({tagName:"appkit-card-content",elementClass:fl,react:D,events:{},defineCustomElement:gl}),dc=_({tagName:"appkit-card-description",elementClass:Cl,react:D,events:{},defineCustomElement:hl}),mc=_({tagName:"appkit-card-footer",elementClass:yl,react:D,events:{},defineCustomElement:Sl}),fc=_({tagName:"appkit-card-header",elementClass:El,react:D,events:{},defineCustomElement:wl}),gc=_({tagName:"appkit-card-title",elementClass:kl,react:D,events:{},defineCustomElement:xl}),Cc=_({tagName:"appkit-checkbox",elementClass:bl,react:D,events:{onAppkitChange:"appkitChange"},defineCustomElement:Rl}),hc=_({tagName:"appkit-collapsible",elementClass:Tl,react:D,events:{onAppkitToggle:"appkitToggle"},defineCustomElement:Il}),yc=_({tagName:"appkit-connect-button",elementClass:Ul,react:D,events:{onAppkitConnect:"appkitConnect",onAppkitDisconnect:"appkitDisconnect",onAppkitStartPairing:"appkitStartPairing",onAppkitRetry:"appkitRetry",onAppkitCancelPairing:"appkitCancelPairing",onAppkitMobileDeepLink:"appkitMobileDeepLink",onAppkitCopyAddress:"appkitCopyAddress"},defineCustomElement:Pl}),Sc=_({tagName:"appkit-dialog",elementClass:Wl,react:D,events:{onAppkitClose:"appkitClose",onAppkitOpenChange:"appkitOpenChange"},defineCustomElement:Ol}),Ec=_({tagName:"appkit-dropdown-menu",elementClass:Nl,react:D,events:{onAppkitSelect:"appkitSelect"},defineCustomElement:_l}),wc=_({tagName:"appkit-input",elementClass:Dl,react:D,events:{onAppkitChange:"appkitChange"},defineCustomElement:Ml}),kc=_({tagName:"appkit-popover",elementClass:Ll,react:D,events:{onAppkitOpenChange:"appkitOpenChange"},defineCustomElement:Bl}),xc=_({tagName:"appkit-progress",elementClass:Hl,react:D,events:{},defineCustomElement:Fl}),vc=_({tagName:"appkit-scroll-area",elementClass:Kl,react:D,events:{},defineCustomElement:ql}),Ac=_({tagName:"appkit-select",elementClass:Vl,react:D,events:{onAppkitChange:"appkitChange"},defineCustomElement:$l}),bc=_({tagName:"appkit-separator",elementClass:Gl,react:D,events:{},defineCustomElement:jl}),Rc=_({tagName:"appkit-skeleton",elementClass:zl,react:D,events:{},defineCustomElement:Ql}),Tc=_({tagName:"appkit-switch",elementClass:Xl,react:D,events:{onAppkitChange:"appkitChange"},defineCustomElement:Yl}),Ic=_({tagName:"appkit-tabs",elementClass:Jl,react:D,events:{onAppkitTabChange:"appkitTabChange"},defineCustomElement:Zl}),Uc=_({tagName:"appkit-toggle-group",elementClass:ec,react:D,events:{onAppkitChange:"appkitChange"},defineCustomElement:tc}),Pc=_({tagName:"appkit-tooltip",elementClass:nc,react:D,events:{},defineCustomElement:rc});export{oc as AppkitAccordion,sc as AppkitAccountButton,ac as AppkitAlertDialog,ic as AppkitAvatar,lc as AppkitBadge,cc as AppkitButton,uc as AppkitCard,pc as AppkitCardContent,dc as AppkitCardDescription,mc as AppkitCardFooter,fc as AppkitCardHeader,gc as AppkitCardTitle,Cc as AppkitCheckbox,hc as AppkitCollapsible,yc as AppkitConnectButton,Sc as AppkitDialog,Ec as AppkitDropdownMenu,wc as AppkitInput,kc as AppkitPopover,xc as AppkitProgress,vc as AppkitScrollArea,Ac as AppkitSelect,bc as AppkitSeparator,Rc as AppkitSkeleton,Tc as AppkitSwitch,Ic as AppkitTabs,Uc as AppkitToggleGroup,Pc as AppkitTooltip,ln as DEFAULT_EVM_CHAINS,uC as LAMPORTS_PER_SOL,pC as PassphraseCancelledError,dC as PassphraseGate,fC as SolanaRpcError,Cr as TokenSelector,Pn as TxMonitorContext,ur as WALLET_ERROR_DESCRIPTIONS,cr as WALLET_ERROR_TITLES,jr as Web3ConnectProvider,ot as Web3Context,Xo as buildDelegationPolicyMessage,vr as clearClient,tt as createClient,aC as formatSol,Dr as getChainById,nt as getClient,rt as getDefaultChains,iC as getLatestBlockhash,Ni as getLocale,lC as getSignatureStatus,cC as getSolanaBalance,Ae as getUserFriendlyError,jt as isRetryableError,mC as parseSol,Fo as resetSessionKeyManager,Oi as setLocale,Gt as t,H as useAccount,ao as useBalance,it as useCapabilities,V as useChain,Zt as useCompareCosts,So as useConnect,Lo as useCreateSessionKey,me as useDelegation,Qo as useDelegationPolicy,Zo as useDisconnect,fs as useERC20Allowance,ws as useERC20Approve,Ws as useERC20Transfer,Hs as useERC20TransferSimulation,ts as useEmbeddedWallet,ft as useExecuteCalls,nn as useExecuteRoute,js as useLastTx,Js as useLookupAddress,ca as useNotification,da as usePassphraseGate,fa as useResolveName,Bo as useRevokeSession,sn as useRouteQuote,Ut as useSIWxLogin,_a as useSIWxSession,dt as useSendCalls,Ce as useSendTransaction,Sa as useSendUserOperation,Ho as useSendWithSession,va as useSession,gt as useSessionKeys,Va as useSignInWithEthereum,Ee as useSignInWithX,ht as useSignMessage,za as useSimulateTransfer,ti as useSiwxAuthSession,oi as useSmartAccount,Lt as useSolanaAccount,ci as useSolanaBalance,di as useSolanaRoles,fi as useSolanaTransaction,Ci as useSwitchChain,vi as useTokenBalance,Ge as useTokenList,ze as useTokenSearch,kt as useTransactionSimulation,Ri as useTxHistory,$s as useTxMonitor,Ui as useUserOpStatus,Mi as useValidateDestination,G as useViemClient,Li as useWallet,U as useWeb3,Bi as useWeb3ErrorHandler,lr as validateDestination};
3
2
  //# sourceMappingURL=index.js.map