@naculus/connect-appkit-react 0.5.0 → 0.6.0

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