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