@naculus/connect-appkit-react 0.2.3 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -2
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +35 -23
- package/dist/index.d.ts +35 -23
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var Es=Object.create;var Ot=Object.defineProperty;var ks=Object.getOwnPropertyDescriptor;var xs=Object.getOwnPropertyNames;var vs=Object.getPrototypeOf,bs=Object.prototype.hasOwnProperty;var As=(e,t)=>{for(var r in t)Ot(e,r,{get:t[r],enumerable:!0})},lr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of xs(t))!bs.call(e,n)&&n!==r&&Ot(e,n,{get:()=>t[n],enumerable:!(o=ks(t,n))||o.enumerable});return e};var Me=(e,t,r)=>(r=e!=null?Es(vs(e)):{},lr(t||!e||!e.__esModule?Ot(r,"default",{value:e,enumerable:!0}):r,e)),Ts=e=>lr(Ot({},"__esModule",{value:!0}),e);var Ea={};As(Ea,{AppkitAccordion:()=>Vo,AppkitAccountButton:()=>zo,AppkitAlertDialog:()=>jo,AppkitAvatar:()=>Go,AppkitBadge:()=>Qo,AppkitButton:()=>Xo,AppkitCard:()=>Yo,AppkitCardContent:()=>Jo,AppkitCardDescription:()=>Zo,AppkitCardFooter:()=>es,AppkitCardHeader:()=>ts,AppkitCardTitle:()=>ns,AppkitCheckbox:()=>rs,AppkitCollapsible:()=>os,AppkitConnectButton:()=>ss,AppkitDialog:()=>as,AppkitDropdownMenu:()=>is,AppkitInput:()=>ls,AppkitPopover:()=>cs,AppkitProgress:()=>us,AppkitScrollArea:()=>ps,AppkitSelect:()=>ds,AppkitSeparator:()=>ms,AppkitSkeleton:()=>fs,AppkitSwitch:()=>gs,AppkitTabs:()=>hs,AppkitToggleGroup:()=>Cs,AppkitTooltip:()=>ys,DEFAULT_EVM_CHAINS:()=>Vn,LAMPORTS_PER_SOL:()=>J.LAMPORTS_PER_SOL,PassphraseCancelledError:()=>J.PassphraseCancelledError,PassphraseGate:()=>J.PassphraseGate,SolanaRpcError:()=>J.SolanaRpcError,TokenSelector:()=>ir,TxMonitorContext:()=>jn,WALLET_ERROR_DESCRIPTIONS:()=>sr,WALLET_ERROR_TITLES:()=>or,Web3ConnectProvider:()=>Cr,Web3Context:()=>Bt,buildDelegationPolicyMessage:()=>ot,clearClient:()=>dr,createClient:()=>Nt,formatSol:()=>J.formatSol,getChainById:()=>hr,getClient:()=>Dt,getDefaultChains:()=>Lt,getLatestBlockhash:()=>J.getLatestBlockhash,getLocale:()=>No,getSignatureStatus:()=>J.getSignatureStatus,getSolanaBalance:()=>J.getSolanaBalance,getUserFriendlyError:()=>ht,isRetryableError:()=>pn,parseSol:()=>J.parseSol,resetSessionKeyManager:()=>Rr,setLocale:()=>Oo,t:()=>ze,useAccount:()=>$,useBalance:()=>Er,useCapabilities:()=>Ft,useChain:()=>ie,useCompareCosts:()=>Fn,useConnect:()=>xr,useCreateSessionKey:()=>br,useDelegation:()=>nt,useDelegationPolicy:()=>Ur,useDisconnect:()=>Pr,useERC20Allowance:()=>Dr,useERC20Approve:()=>Br,useERC20Transfer:()=>Kr,useERC20TransferSimulation:()=>Gr,useEmbeddedWallet:()=>Wr,useExecuteCalls:()=>Gt,useExecuteRoute:()=>Kn,useLastTx:()=>Xr,useLookupAddress:()=>Zr,useNotification:()=>oo,usePassphraseGate:()=>ao,useResolveName:()=>lo,useRevokeSession:()=>Ar,useRouteQuote:()=>$n,useSIWxLogin:()=>on,useSIWxSession:()=>fo,useSendCalls:()=>zt,useSendTransaction:()=>it,useSendUserOperation:()=>uo,useSendWithSession:()=>Tr,useSession:()=>po,useSessionKeys:()=>Qt,useSignInWithEthereum:()=>go,useSignInWithX:()=>dt,useSignMessage:()=>Yt,useSimulateTransfer:()=>yo,useSiwxAuthSession:()=>wo,useSmartAccount:()=>Eo,useSolanaAccount:()=>cn,useSolanaBalance:()=>vo,useSolanaTransaction:()=>Ao,useSwitchChain:()=>Ro,useTokenBalance:()=>Io,useTokenList:()=>Pt,useTokenSearch:()=>Wt,useTransactionSimulation:()=>tn,useTxHistory:()=>Uo,useTxMonitor:()=>Qr,useUserOpStatus:()=>Wo,useValidateDestination:()=>Lo,useViemClient:()=>fe,useWallet:()=>Bo,useWeb3:()=>P,useWeb3ErrorHandler:()=>Ho,validateDestination:()=>rr});module.exports=Ts(Ea);var J=require("@naculus/connect-core");var ue=require("react");function Rs(e){return e?Object.keys(e).sort().map(t=>{let r=e[t];return`${t}=${typeof r=="object"&&r!==null?"[object]":String(r)}`}).join("&"):""}function Fn(e,t){let{operation:r,chains:o,options:n}=e,[i,a]=(0,ue.useState)([]),[g,u]=(0,ue.useState)(!1),[c,h]=(0,ue.useState)(null),s=(0,ue.useRef)(!0),l=(0,ue.useRef)(0),d=`${r}|${(o??[]).join(",")}|${Rs(n)}`,f=(0,ue.useCallback)(async()=>{if(!o||o.length===0){a([]);return}if(!t)return;let y=++l.current;u(!0),h(null);try{let C=await t(r,o,n);s.current&&y===l.current&&a(C)}catch(C){s.current&&y===l.current&&(h(C instanceof Error?C:new Error(String(C))),a([]))}finally{s.current&&y===l.current&&u(!1)}},[d,t]);(0,ue.useEffect)(()=>{f()},[f]),(0,ue.useEffect)(()=>(s.current=!0,()=>{s.current=!1}),[]);let m=(0,ue.useCallback)(async()=>{await f()},[f]);return{comparisons:i,loading:g,error:c,refresh:m}}var cr=require("@naculus/connect-core"),me=require("react");function Kn(e){let[t,r]=(0,me.useState)(!1),[o,n]=(0,me.useState)(null),[i,a]=(0,me.useState)(null),g=(0,me.useRef)(!0),u=(0,me.useRef)(!1);(0,me.useEffect)(()=>(g.current=!0,()=>{g.current=!1}),[]);let c=(0,me.useCallback)(async(s,l,d)=>{if(!e)return a({code:"no_executor",message:"No executeRoute function provided"}),n(null),null;if(typeof l!="string"||l.trim()==="")return a({code:"invalid_recipient",message:"A recipient address is required"}),n(null),null;let f=s?.toChain?.split(":")[0];if(f&&!(0,cr.isValidAddress)(l,f))return a({code:"invalid_recipient",message:`"${l}" is not a valid ${f} address for the destination chain ${s.toChain}`}),n(null),null;if(u.current)return a({code:"execution_in_progress",message:"A route execution is already in progress"}),null;u.current=!0,r(!0),a(null),n(null);try{let m=await e(s,l,d);return g.current&&n(m),m}catch(m){let y=m;return g.current&&a({code:y.code??"execution_failed",message:y.message,details:y.details}),null}finally{u.current=!1,g.current&&r(!1)}},[e]),h=(0,me.useCallback)(()=>{n(null),a(null),r(!1)},[]);return{execute:c,executing:t,result:o,error:i,reset:h}}var ae=require("react");function $n(e,t){let{fromChain:r,toChain:o,fromToken:n,toToken:i,amount:a,options:g}=e,[u,c]=(0,ae.useState)([]),[h,s]=(0,ae.useState)(!1),[l,d]=(0,ae.useState)(null),f=(0,ae.useRef)(null),m=(0,ae.useRef)(!0),y=(0,ae.useCallback)(async()=>{let E=/^(?:0|[1-9][0-9]*)$/.test(a)&&BigInt(a)>0n;if(!r||!o||!n||!E){c([]);return}if(t){s(!0),d(null);try{let T=await t(r,o,n,a,g,i);m.current&&c(T)}catch(T){m.current&&(d(T instanceof Error?T:new Error(String(T))),c([]))}finally{m.current&&s(!1)}}},[r,o,n,i,a,g,t]);(0,ae.useEffect)(()=>{if(f.current&&clearTimeout(f.current),!r||!o||!n||!a){c([]);return}return f.current=setTimeout(()=>{y()},300),()=>{f.current&&clearTimeout(f.current)}},[y,r,o,n,a]),(0,ae.useEffect)(()=>(m.current=!0,()=>{m.current=!1}),[]);let C=(0,ae.useCallback)(async()=>{await y()},[y]),S=(0,ae.useCallback)(()=>{c([]),d(null),s(!1)},[]);return{quotes:u,loading:h,error:l,refresh:C,clear:S}}var X=require("@naculus/connect-core"),ne=require("@naculus/connector-evm-injected"),ur=require("@naculus/connect-core"),pr=require("@naculus/connector-walletconnect"),qn=null;function Nt(e){let t=null,r=(0,pr.createWalletConnectConnector)({projectId:e.projectId,metadata:e.metadata}),o=null,n=null,i=null,a=null,g=e.passphrasePrompt&&e.enableEmbedded&&!e.embeddedConfig?.encryptionPassphrase?new ur.PassphraseGate:null;e.enableEmbedded&&(n=import("@naculus/connector-embedded").then(s=>{let l={...e.embeddedConfig};g&&(l.encryptionPassphrase=g.request),e.enablePasskeys&&l.encryptionPassphrase&&!l.prfUnlock&&(l.prfUnlock={async derive(f){a&&await a;let m=i;return m?.hasCredential()?m.derivePrfKey(f):null}}),o=s.createPocketConnector(l),t?._setEmbeddedConnector(o)}).catch(s=>{X.logger.warn("react/client","Embedded wallet connector not available:",s),o=null})),e.enablePasskeys&&(a=import("@naculus/connector-passkeys").then(s=>{i=s.createPasskeysConnector(),t?._setPasskeysConnector(i)}).catch(s=>{X.logger.warn("react/client","Passkeys connector not available:",s),i=null}));let u=null,c=null;e.enableSolana&&(c=import("@naculus/connector-solana").then(s=>{let l=s.solanaConnector;e.solanaDefaultChain&&"configure"in l&&l.configure({defaultChain:e.solanaDefaultChain}),u=l,typeof window<"u"&&"startDiscovery"in l&&l.startDiscovery(),t?._setSolanaConnector(u)}).catch(s=>{X.logger.warn("react/client","Solana connector not available:",s),u=null})),typeof window<"u"&&ne.eip6963Connector.startDiscovery();let h={connector:r,get embeddedConnector(){return o},getEmbeddedConnector:async()=>(n&&await n,o),get passkeysConnector(){return i},passphraseGate:g,solanaRpcUrl:e.solanaRpcUrl??null,get solanaConnector(){return u},connect:()=>r.connect(),connectInjected:async s=>ne.eip6963Connector.connect(s),connectEmbedded:async()=>{if(n&&await n,!o)throw new Error("Embedded wallet not enabled. Set enableEmbedded: true in config.");return o.connect()},connectPasskeys:async()=>{if(a&&await a,!i)throw new Error("Passkeys connector not enabled. Set enablePasskeys: true in config.");return i.connect()},startPairing:()=>r.startPairing(),completePairing:()=>r.completePairing(),cancelPairing:()=>r.cancelPairing?.(),signMessage:async(s,l)=>{if(s.id?.startsWith("eip6963-"))return ne.eip6963Connector.signMessage(s,l);if(s.walletType==="passkeys"&&i)return i.signMessage(s,l);if(s.walletType==="embedded"){if(!o)throw new X.WalletError("wallet_unavailable","Embedded wallet connector not available.");return o.signMessage(s,l)}if(s.walletType==="solana"){if(c&&await c,u)return u.signMessage(s,l);throw new X.WalletError("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}return r.signMessage(s,l)},signTransaction:async(s,l)=>{if(s.id?.startsWith("eip6963-"))return ne.eip6963Connector.signTransaction(s,l);if(s.walletType==="embedded"){if(!o)throw new X.WalletError("wallet_unavailable","Embedded wallet connector not available.");return o.signTransaction(s,l)}if(s.walletType==="solana"){if(c&&await c,u)return u.signTransaction(s,l);throw new X.WalletError("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}return r.signTransaction(s,l)},sendTransaction:async(s,l)=>{if(s.id?.startsWith("eip6963-"))return ne.eip6963Connector.sendTransaction(s,l);if(s.walletType==="passkeys"&&i)return i.sendTransaction(s,l);if(s.walletType==="embedded"){if(!o)throw new X.WalletError("wallet_unavailable","Embedded wallet connector not available.");return o.sendTransaction(s,l)}if(s.walletType==="solana"){if(c&&await c,u)return u.sendTransaction(s,l);throw new X.WalletError("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}return r.sendTransaction(s,l)},onAccountsChanged:(s,l)=>{let d=()=>{};return s.id?.startsWith("eip6963-")?ne.eip6963Connector.onAccountsChanged?.(s,l)??d:s.walletType==="embedded"?o?.onAccountsChanged?.(s,l)??d:s.walletType==="passkeys"?d:s.walletType==="solana"?u?.onAccountsChanged?.(s,l)??d:r.onAccountsChanged?.(s,l)??d},onChainChanged:(s,l)=>{let d=()=>{};return s.id?.startsWith("eip6963-")?ne.eip6963Connector.onChainChanged?.(s,l)??d:s.walletType==="passkeys"||s.walletType==="embedded"?d:s.walletType==="solana"?u?.onChainChanged?.(s,l)??d:r.onChainChanged?.(s,l)??d},getCapabilities:s=>s.id?.startsWith("eip6963-")?ne.eip6963Connector.getCapabilities?.(s):s.walletType==="passkeys"?i?.getCapabilities?.(s):s.walletType==="solana"?u?.getCapabilities?.(s):s.walletType==="embedded"?o?.getCapabilities?.(s):r.getCapabilities?.(s),sendCalls:async(s,l,d,f)=>{if(s.id?.startsWith("eip6963-"))return ne.eip6963Connector.sendCalls(s,l,d,f);if(s.walletType==="passkeys"&&i)return i.sendCalls(s,l,d,f);if(s.walletType==="solana"){if(c&&await c,u)return u.sendCalls(s,l,d,f);throw new X.WalletError("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}if(s.walletType==="embedded"){if(!o?.sendCalls)throw new X.WalletError("method_not_allowed","Embedded wallet does not support sendCalls");return o.sendCalls(s,l,d,f)}if(!r.sendCalls)throw new X.WalletError("method_not_allowed","sendCalls not supported by this connector");return r.sendCalls(s,l,d,f)},showCallsStatus:async(s,l)=>{if(s.id?.startsWith("eip6963-"))return ne.eip6963Connector.showCallsStatus(s,l);if(s.walletType==="passkeys"||s.walletType==="embedded")throw new X.WalletError("method_unsupported",`${s.walletType} wallets have no UI to display a call bundle.`);if(!r.showCallsStatus)throw new X.WalletError("method_unsupported","This connector cannot display call status.");return r.showCallsStatus(s,l)},getCallsStatus:async(s,l)=>{if(s.id?.startsWith("eip6963-")&&ne.eip6963Connector.getCallsStatus)return ne.eip6963Connector.getCallsStatus(s,l);if(s.walletType==="passkeys"&&i?.getCallsStatus)return i.getCallsStatus(s,l);if(s.walletType==="embedded")throw new X.WalletError("method_not_allowed","Embedded wallet does not support getCallsStatus");if(!r.getCallsStatus)throw new X.WalletError("method_not_allowed","getCallsStatus not supported by this connector");return r.getCallsStatus(s,l)},reconnect:async s=>s.walletType==="eip6963"?ne.eip6963Connector.reconnect(s):s.walletType==="embedded"?o?o.reconnect(s):s:s.walletType==="solana"?s:r.reconnect(s),disconnect:async s=>{if(s.id?.startsWith("eip6963-")||s.walletType==="eip6963")return ne.eip6963Connector.disconnect(s);if(s.walletType==="embedded"&&o)return o.disconnect();if(s.walletType==="passkeys"&&i)return i.disconnect(s);if(s.walletType==="solana"){if(c&&await c,u)return u.disconnect(s);throw new X.WalletError("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}return r.disconnect(s)},getAllConnectors:()=>{let s=[r];return o&&s.push(o),i&&s.push(i),u&&s.push(u),s},_setEmbeddedConnector:s=>{o=s},_setPasskeysConnector:s=>{i=s},_setSolanaConnector:s=>{u=s}};return t=h,qn=h,h}function Dt(){return qn}function dr(){qn=null}var wt=require("@naculus/connect-core"),wr=require("react");var Z=require("@naculus/connect-core"),yt=require("@naculus/connector-evm-injected"),D=require("react");var mr=require("@naculus/connect-core"),Mt=require("@naculus/siwx");function Ye(e,t){let r=t.split(":",1)[0],n=(e.namespaces[r]?.accounts??[]).filter(i=>i.startsWith(`${r}:`)).map(i=>({namespace:r,caip10:i}))[0];if(n)return{...n,address:n.caip10.split(":").pop()??n.caip10}}function Is(e){return e.namespaces.eip155?.chains?.[0]??e.namespaces.solana?.chains?.[0]??e.namespaces.xrpl?.chains?.[0]??"eip155:1"}async function fr(e){let{session:t,siwx:r,signMessage:o}=e;if(!r||!t)return{kind:"skipped"};try{let n=Is(t),i=Ye(t,n);if(!i)throw new Error("No account found in session");let{address:a}=i,g=await r.createMessage({address:a,chainId:n}),u=(0,Mt.parseSiwxMessage)(g);if(!u?.nonce)throw new Error("SIWx message must contain a nonce");await(0,Mt.issueNonce)(u.nonce);let c=await o(t,{message:g,address:a,chainId:n});return await r.handleSignComplete?.({message:g,signature:c}),{kind:"authenticated",address:a,chainId:n}}catch(n){let i=n instanceof Error?n:new Error("Wallet authentication failed");return mr.logger.error("appkit/core","SIWx authentication failed:",n),{kind:"failed",error:i,fatal:r.required!==!1}}}var _e=require("@naculus/connect-appkit-core");var gr=require("@naculus/connect-appkit-core"),Se=require("@naculus/connect-core"),Us=[{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 Ps(e){let t=Se.CHAINS[e];if(!t||!t.explorerUrl)return null;let r=t.caip2Id;return{caip2:r,name:t.name,rpcUrl:(0,Se.getRpcUrl)(r,Se.DEFAULT_RPC_URLS[r]??""),explorerUrl:t.explorerUrl,token:t.nativeCurrency.symbol}}function Ws(){if(!Se.CHAINS)return[];let e=[],t=Object.keys(Se.CHAINS).map(Number).sort((r,o)=>r-o);for(let r of t){let o=Ps(r);o&&e.push(o)}for(let r of Us){let o=(0,Se.eip155Reference)(r.caip2);(o===null||!Se.CHAINS[o])&&e.push(r)}return e}var Vn=Ws();function hr(e,t){return(0,gr.resolveChain)(e,t)??void 0}function Lt(){return[...Vn]}var yr=require("react/jsx-runtime"),Bt=(0,D.createContext)(null);function Cr({children:e,config:t,autoConnect:r=!0}){let[o,n]=(0,D.useReducer)(_e.web3Reducer,_e.initialWeb3State),i=(0,D.useMemo)(()=>t.chains??Lt(),[t.chains]),a=t.connectionTimeout??3e4,g=t.maxRetries??2,u=(0,D.useMemo)(()=>new Z.LocalStorageSessionStorage(t.storageKey??"naculus_web3_session",t.encryptionKey),[t.storageKey,t.encryptionKey]),c=(0,D.useMemo)(()=>Nt({projectId:t.projectId,metadata:t.metadata,enableEmbedded:t.enableEmbedded,embeddedConfig:t.embeddedConfig,enablePasskeys:t.enablePasskeys,enableSolana:t.enableSolana,solanaDefaultChain:t.solanaDefaultChain}),[t.projectId,t.metadata,t.enableEmbedded,t.embeddedConfig,t.enablePasskeys,t.enableSolana,t.solanaDefaultChain]),h=(0,D.useRef)(null),s=(0,D.useRef)(null),l=(0,D.useMemo)(()=>{let p=(0,Z.createConnectorManager)();for(let N of[yt.eip6963Connector,...c.getAllConnectors()])p.register(N.id,N);let w={},x={};for(let N of i){let M=N.caip2;N.rpcUrl&&(w[M]=N.rpcUrl),N.token&&(x[M]={name:N.name,symbol:N.token,decimals:18})}let W=(0,Z.createSessionManager)(p,{autoRefreshFeeOnSwitch:t.autoRefreshFeeOnSwitch??!0,defaultRpcUrls:w,defaultCurrencies:x,encryptionKey:t.encryptionKey});return h.current=W,W},[c,i,t.autoRefreshFeeOnSwitch,t.encryptionKey]);(0,D.useEffect)(()=>{let p=W=>{let{walletSession:N}=W.bundle;n({type:"SET_SESSION",payload:N});let M=[];Object.values(N.namespaces).forEach(Q=>{M.push(...Q.accounts)}),n({type:"SET_ACCOUNTS",payload:M}),n({type:"SET_CHAIN",payload:W.bundle.activeChainId}),n({type:"SET_STATUS",payload:"connected"})},w=()=>{n({type:"RESET"})},x=W=>{n({type:"SET_CHAIN",payload:W.newChainId})};return l.on("sessionConnected",p),l.on("sessionDisconnected",w),l.on("chainChanged",x),()=>{l.off("sessionConnected",p),l.off("sessionDisconnected",w),l.off("chainChanged",x)}},[l]),(0,D.useEffect)(()=>{let p=()=>{u.clear(),n({type:"RESET"})};c.connector.onSessionExpiry(p)},[c,u]);let d=(0,D.useCallback)(()=>{for(let p of[yt.eip6963Connector,...c.getAllConnectors()])l.registerConnector(p)},[c,l]),f=(0,D.useCallback)(async p=>{d();let w=[yt.eip6963Connector,...c.getAllConnectors()].find(W=>W.id===p.walletType||W.kind===p.walletType);w&&!p.connectorId&&(p.connectorId=w.id);let x=p.namespaces.eip155?.chains?.[0]??p.namespaces.solana?.chains?.[0]??p.namespaces.xrpl?.chains?.[0];x&&await l.attach(p,x)},[c,l,d]),m=(0,D.useCallback)(p=>{if(n({type:"SET_SESSION",payload:p}),p){let w=[];Object.values(p.namespaces).forEach(M=>{w.push(...M.accounts)}),n({type:"SET_ACCOUNTS",payload:w});let x=p.namespaces.eip155?.chains?.[0],W=p.namespaces.solana?.chains?.[0],N=p.namespaces.xrpl?.chains?.[0];n({type:"SET_CHAIN",payload:x??W??N??null})}else n({type:"SET_ACCOUNTS",payload:[]}),n({type:"SET_CHAIN",payload:null})},[]);(0,D.useEffect)(()=>{let p=o.session,w=c;return!p||!w?.onAccountsChanged?void 0:w.onAccountsChanged(p,W=>{if(W.length===0){u.clear().finally(()=>n({type:"RESET"}));return}m(p),u.save(p)})},[o.session,c,u,m]),(0,D.useEffect)(()=>{let p=o.session,w=c;if(!(!p||!w?.onChainChanged))return w.onChainChanged(p,x=>{m(p),u.save(p);let W=l.syncExternalChain;if(!W)return;let N=W.call(l,x).catch(M=>{Z.logger.warn("react/provider","External chain sync error:",M)});s.current=N,N.finally(()=>{s.current===N&&(s.current=null)})})},[o.session,c,u,m,l]);let y=(0,D.useCallback)(async p=>{if(!t.siwx||!p)return!0;n({type:"SET_STATUS",payload:"authenticating"});let w=await fr({session:p,siwx:t.siwx,signMessage:(x,W)=>c.signMessage(x,W)});return w.kind==="failed"&&w.fatal?(await u.clear(),n({type:"RESET"}),n({type:"SET_ERROR",payload:w.error}),!1):!0},[t.siwx,c,u]),C=(0,D.useCallback)(async()=>{n({type:"SET_STATUS",payload:"connecting"}),n({type:"SET_ERROR",payload:null});try{let p=await(0,_e.withTimeout)(c.connect(),a,"Wallet connect");await u.save(p),m(p);try{await f(p)}catch(w){Z.logger.warn("react/provider","SessionManager sync error:",w)}if(!await y(p))return;n({type:"SET_STATUS",payload:"connected"})}catch(p){let w=p instanceof Error?p.message:"Connection failed";n({type:"SET_ERROR",payload:p instanceof Error?p:new Error(w)}),n({type:"SET_STATUS",payload:"disconnected"})}},[c,u,m,a,y,f]),S=(0,D.useCallback)(async()=>{n({type:"SET_STATUS",payload:"connecting"}),n({type:"SET_ERROR",payload:null});try{let p=await c.connectEmbedded();if(await u.save(p),m(p),await f(p),!await y(p))return;n({type:"SET_STATUS",payload:"connected"})}catch(p){let w=p instanceof Error?p.message:"Embedded wallet connection failed";n({type:"SET_ERROR",payload:p instanceof Error?p:new Error(w)}),n({type:"SET_STATUS",payload:"disconnected"})}},[c,u,m,y,f]),E=(0,D.useCallback)(async()=>{n({type:"SET_STATUS",payload:"connecting"}),n({type:"SET_ERROR",payload:null});try{let p=await c.connectPasskeys();if(await u.save(p),m(p),await f(p),!await y(p))return;n({type:"SET_STATUS",payload:"connected"})}catch(p){let w=p instanceof Error?p.message:"Passkeys connection failed";n({type:"SET_ERROR",payload:p instanceof Error?p:new Error(w)}),n({type:"SET_STATUS",payload:"disconnected"})}},[c,u,m,y,f]),T=(0,D.useCallback)(async()=>{if(!o.session){n({type:"RESET"});return}try{await c.disconnect(o.session)}catch(p){Z.logger.error("react/provider","Disconnect error:",p)}try{let p=h.current;p&&await p.disconnect()}catch(p){Z.logger.warn("react/provider","SessionManager disconnect error:",p)}await u.clear(),n({type:"RESET"})},[c,o.session,u]),v=(0,D.useCallback)(async p=>{n({type:"SET_STATUS",payload:"connecting"}),n({type:"SET_ERROR",payload:null});try{let w=await(0,_e.withTimeout)(c.connectInjected(p),a,"Injected wallet connect");await u.save(w),m(w);try{await f(w)}catch(x){Z.logger.warn("react/provider","SessionManager sync error:",x)}if(!await y(w))return;n({type:"SET_STATUS",payload:"connected"})}catch(w){let x=w instanceof Error?w.message:"Connection failed";n({type:"SET_ERROR",payload:w instanceof Error?w:new Error(x)}),n({type:"SET_STATUS",payload:"disconnected"})}},[c,u,m,a,y,f]),I=(0,D.useCallback)(async()=>c.startPairing(),[c]),A=(0,D.useCallback)(()=>{c.cancelPairing?.()},[c]),U=(0,D.useCallback)(async()=>{let p=await c.completePairing();return await u.save(p),m(p),await f(p),await y(p)&&n({type:"SET_STATUS",payload:"connected"}),p},[c,u,m,y,f]),k=(0,D.useCallback)(async p=>{let w=t.siwx;if(!w||w.required===!1)return!0;try{if(await w.hasValidSession?.())return!0}catch(x){Z.logger.warn("react/provider","siwx.hasValidSession failed",x)}return y(p)},[t.siwx,y]),R=(0,D.useCallback)(async()=>{let p=await u.load();if(!p){n({type:"SET_STATUS",payload:"disconnected"});return}n({type:"SET_STATUS",payload:"reconnecting"});try{let w=await(0,_e.withRetry)(()=>c.reconnect(p),{maxRetries:g,baseDelay:1e3,label:"reconnect"});m(w);try{let x=h.current;x&&(d(),await x.restoreFromPersistence())}catch(x){Z.logger.warn("react/provider","SessionManager restore error:",x)}if(!await k(w))return;n({type:"SET_STATUS",payload:"connected"})}catch(w){Z.logger.error("react/provider","Reconnect error:",w),await u.clear(),n({type:"SET_STATUS",payload:"disconnected"}),n({type:"SET_SESSION",payload:null})}},[c,u,m,g,d,k]),b=(0,D.useCallback)(async p=>{s.current&&await s.current;let w=h.current;if(w?.getActiveBundle()){await w.switchChain(p),m(o.session);return}if(!o.session)throw new Error("No active session");try{o.session.walletType==="eip6963"||o.session.id?.startsWith("eip6963-")?await yt.eip6963Connector.switchChain(o.session,p):o.session.walletType==="embedded"&&c.embeddedConnector?await c.embeddedConnector.switchChain?.(o.session,p):o.session.walletType==="passkeys"&&c.passkeysConnector?await c.passkeysConnector.switchChain?.(o.session,p):o.session.walletType==="solana"&&c.solanaConnector?await c.solanaConnector.switchChain?.(o.session,p):await c.connector.switchChain(o.session,p),m(o.session)}catch(x){throw new Z.WalletError("chain_unsupported","Failed to switch chain",x)}},[c,o.session,m]);(0,D.useEffect)(()=>{r&&R()},[r,R]);let O=(0,D.useCallback)(()=>{n({type:"SET_ERROR",payload:null})},[]),_=(0,D.useMemo)(()=>({...o,connect:C,connectEmbedded:S,connectPasskeys:E,disconnect:T,reconnect:R,switchChain:b,startPairing:I,completePairing:U,cancelPairing:A,connectInjected:v,clearError:O,isConnected:o.status==="connected",chains:i,client:c,sessionManager:l}),[o,C,S,E,T,R,b,I,U,v,O,i,c,l]);return(0,yr.jsx)(Bt.Provider,{value:_,children:e})}function P(){let e=(0,D.useContext)(Bt);if(!e)throw new Error("useWeb3 must be used within a Web3ConnectProvider");return e}function $(){let{accounts:e,isConnected:t}=P(),r=(0,wr.useMemo)(()=>!t||e.length===0?null:e.map(n=>{let i=(0,wt.parseCaip10)(n);return i?{address:n,namespace:i.namespace,isEVM:i.namespace==="eip155"&&(0,wt.isEvmAddress)(i.address)}:{address:n,namespace:null,isEVM:(0,wt.isEvmAddress)(n)}}),[e,t]),o=r?.find(n=>n.isEVM)?.address??null;return{accounts:r,evmAccount:o,primaryAccount:e[0]??null,isConnected:t,count:e.length}}var Je=require("@naculus/connect-appkit-core"),j=require("react");var Ze=require("viem"),Sr=require("@naculus/connect-core");function Er(e){let{evmAccount:t,isConnected:r}=$(),{chainId:o,chains:n}=P(),[i,a]=(0,j.useState)(null),[g,u]=(0,j.useState)(!1),[c,h]=(0,j.useState)(null),[s,l]=(0,j.useState)(null),d=e?.refreshInterval,f=(0,j.useRef)(null),m=(0,j.useMemo)(()=>(0,Je.resolveChain)(n,o),[o,n]),y=m?(0,Je.chainNumber)(m):null,C=(0,j.useMemo)(()=>m?(0,Je.toViemChain)(m,y):null,[m,y]),S=(0,j.useMemo)(()=>m?.token??null,[m]),[E,T]=(0,j.useState)(null);(0,j.useEffect)(()=>{if(!C||!m?.rpcUrl){T(null);return}let U=(0,Ze.createPublicClient)({transport:(0,Ze.http)(m.rpcUrl),chain:C});return T(U),()=>{}},[m]);let v=(0,j.useCallback)(async()=>{if(!t||!E){a(null);return}u(!0),h(null);try{let k=t.includes(":")?t.split(":").pop():t,[R,b]=await Promise.all([E.getBalance({address:k}),o?(0,Sr.getNativeTokenPriceUsd)(o,m?.rpcUrl).catch(()=>null):Promise.resolve(null)]);a(R.toString()),l(b)}catch(U){h(U instanceof Error?U:new Error("Failed to fetch balance")),a(null),l(null)}finally{u(!1)}},[t,E,o,m?.rpcUrl]);(0,j.useEffect)(()=>{r&&t&&v()},[r,t,v]),(0,j.useEffect)(()=>(d&&d>0&&r&&t&&(f.current=setInterval(v,d)),()=>{f.current&&(clearInterval(f.current),f.current=null)}),[d,r,t,v]);let I=(0,j.useMemo)(()=>{if(i===null)return null;try{return(0,Ze.formatEther)(BigInt(i))}catch{return null}},[i]),A=(0,j.useMemo)(()=>{if(s===null||I===null)return null;let U=parseFloat(I);if(isNaN(U))return null;let k=U*s;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(k)},[s,I]);return{balance:i,formatted:I,symbol:S,usdPrice:s,usdValue:A,isLoading:g,error:c,refetch:v,chain:m}}var Ht=require("@naculus/connect-core"),Te=require("react");function L(e){return e??Dt()}function Ft(){let{client:e,session:t,chainId:r}=P(),[o,n]=(0,Te.useState)(null),[i,a]=(0,Te.useState)(!1),[g,u]=(0,Te.useState)(null),c=(0,Te.useRef)(0),h=(0,Te.useCallback)(async()=>{let d=++c.current,f=L(e);if(!f?.getCapabilities||!t){n(null),a(!1),u(null);return}a(!0),u(null);try{let m=await f.getCapabilities(t);if(d!==c.current)return;let y={};for(let[C,S]of Object.entries(m??{})){if(!S||typeof S!="object")continue;let{supported:E,maxBatchSize:T}=(0,Ht.readAtomicSupport)(S);y[C]={chainId:C,atomic:E?"supported":"unsupported",...T===void 0?{}:{maxBatchSize:T},raw:S}}n(y)}catch(m){if(d!==c.current)return;n(null),u(m instanceof Error?m:new Error("Capability query failed"))}finally{d===c.current&&a(!1)}},[e,t]);(0,Te.useEffect)(()=>{h()},[h]);let s=r?(0,Ht.caip2ToHexChain)(r):void 0,l=(r?o?.[r]:void 0)??(s?o?.[s]:void 0)??null;return{capabilities:o,current:l,atomic:l?.atomic??"unknown",isFetching:i,error:g,refetch:h}}var Kt=require("react"),et=require("@naculus/connect-appkit-core");function ie(){let{chainId:e,session:t,switchChain:r,chains:o}=P(),n=(0,Kt.useMemo)(()=>(0,et.resolveChain)(o,e),[o,e]),i=(0,Kt.useMemo)(()=>t?(0,et.describeChain)(o,e):null,[o,e,t]),a=(0,Kt.useMemo)(()=>(0,et.chainsForNamespace)(o,e),[o,e]);return{chainId:e,currentChain:n,chainInfo:i,availableChains:a,chains:a,isEvm:e?.startsWith("eip155:")??!1,switchChain:r}}var St=require("react");var kr=require("@naculus/connect-core");function xr(){let{connect:e,status:t}=P(),[r,o]=(0,St.useState)(!1),[n,i]=(0,St.useState)(null);return{connect:(0,St.useCallback)(async()=>{o(!0),i(null);try{await e()}catch(g){let u=g instanceof Error?g.message:"Connection failed";i(g instanceof kr.WalletError?g:new Error(u))}finally{o(!1)}},[e]),isConnecting:r||t==="connecting",error:n}}var tt=require("@naculus/connect-core"),Re=require("react");var qt=require("@naculus/connect-appkit-core"),$t=require("react"),He=require("viem");function fe(){let{evmAccount:e,isConnected:t}=$(),{currentChain:r,chains:o}=ie(),n=r?(0,qt.chainNumber)(r):null,i=(0,$t.useMemo)(()=>r?(0,qt.toViemChain)(r,n):null,[r,n]),a=(0,$t.useMemo)(()=>i?(0,He.createPublicClient)({transport:(0,He.http)(i.rpcUrls.default.http[0]),chain:i}):null,[r,i]),g=(0,$t.useMemo)(()=>{if(!t||!e||!i)return null;let u=e.includes(":")?e.split(":").pop():e;return(0,He.createWalletClient)({transport:(0,He.http)(i.rpcUrls.default.http[0]),chain:i,account:u})},[t,e,r,i]);return{publicClient:a,walletClient:g,chains:o}}function nt(){let{publicClient:e}=fe(),{evmAccount:t}=$(),[r,o]=(0,Re.useState)(tt.UNKNOWN_DELEGATION),[n,i]=(0,Re.useState)(!1),[a,g]=(0,Re.useState)(null),u=(0,Re.useRef)(0),c=t?.includes(":")?t.split(":").pop():t,h=(0,Re.useCallback)(async()=>{let s=++u.current;if(!e||!c){o(tt.UNKNOWN_DELEGATION),i(!1),g(null);return}i(!0),g(null);try{let l=await e.getCode({address:c});if(s!==u.current)return;o((0,tt.readDelegation)(l??"0x"))}catch(l){if(s!==u.current)return;o(tt.UNKNOWN_DELEGATION),g(l instanceof Error?l:new Error("Code read failed"))}finally{s===u.current&&i(!1)}},[e,c]);return(0,Re.useEffect)(()=>{h()},[h]),{...r,isFetching:n,error:a,refetch:h}}var ee=require("@naculus/connect-core"),re=require("react"),xt=require("viem");var jt=require("@naculus/connect-core");var Fe=require("react");var pe=require("@naculus/connect-core"),Ee=require("react");var vr=require("@naculus/connect-core");function Vt(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 vr.WalletError("tx_failed","Wallet did not return a valid 32-byte transaction hash")}function zt(){let{session:e,chainId:t,client:r}=P(),[o,n]=(0,Ee.useState)("idle"),[i,a]=(0,Ee.useState)(null),[g,u]=(0,Ee.useState)(null),[c,h]=(0,Ee.useState)(null),[s,l]=(0,Ee.useState)(null),d=(0,Ee.useCallback)(async(C,S)=>{if(!e){n("failed");let E=new pe.WalletError("wallet_unavailable","No active session");throw a(E),E}if(C.length===0){n("failed");let E=new pe.WalletError("invalid_input","At least one call is required");throw a(E),E}n("awaiting_approval"),a(null),u(null);try{let E=L(r);if(!E)throw new pe.WalletError("wallet_unavailable","Client not initialized");let T=S?.chainId??t??void 0,v=S?.strategy??(0,pe.chooseExecutionStrategy)(await(0,pe.getAccountCapabilities)(E,e,T),C.length);if(l(v),v==="atomic-batch"){let A=await E.sendCalls(e,C,T,{atomicRequired:!0,...S?.paymasterService?{paymasterService:S.paymasterService}:{}});return n("submitted"),u(A),A}let I="";for(let A=0;A<C.length;A++){let U=C[A];try{I=Vt(await E.sendTransaction(e,{transaction:{to:U.to,data:U.data,value:U.value},chainId:T}))}catch(k){throw new pe.WalletError("tx_failed",`Call ${A+1} of ${C.length} failed after ${A} already landed (sent sequentially \u2014 this wallet cannot batch atomically): ${k instanceof Error?k.message:String(k)}`)}}return n("submitted"),u(I),I}catch(E){n("failed");let T=E instanceof Error?E.message:"sendCalls failed";throw a(E instanceof Error?E:new Error(T)),E}},[e,t,r]),f=(0,Ee.useCallback)(async C=>{if(!e)throw new pe.WalletError("wallet_unavailable","No active session");let S=C??g;if(!S)throw new pe.WalletError("invalid_input","No bundle hash available");if(!C&&s==="sequential")throw new pe.WalletError("invalid_input","Calls were sent sequentially, so there is no bundle to query. Track the returned transaction hash instead.");let E=L(r);if(!E)throw new pe.WalletError("wallet_unavailable","Client not initialized");let T=await E.getCallsStatus(e,S);return h(T),T},[e,g,r,s]),m=(0,Ee.useCallback)(async C=>{if(!e)return!1;let S=C??g;if(!S||!C&&s==="sequential")return!1;let E=L(r);if(!E?.showCallsStatus)return!1;try{return await E.showCallsStatus(e,S),!0}catch{return!1}},[e,g,r,s]),y=(0,Ee.useCallback)(()=>{n("idle"),a(null),u(null),h(null),l(null)},[]);return{sendCalls:d,getCallsStatus:f,showCallsStatus:m,status:o,error:i,batchHash:g,callsStatus:c,execution:s,reset:y,isSending:o==="awaiting_approval"}}function Gt(e={}){let{current:t,atomic:r}=Ft(),{delegated:o,delegate:n}=nt(),{sendCalls:i}=zt(),[a,g]=(0,Fe.useState)(!1),[u,c]=(0,Fe.useState)(null),[h,s]=(0,Fe.useState)(null),l=e.atomicity??"preferred",d=e.sponsorship??"any",f=e.paymasterService,m=e.userOperation,y=e.userOperationSponsored??!1,C=!!(t?.raw?.paymasterService?.supported&&f),S=(0,Fe.useCallback)((T,v=l)=>{let I=(0,jt.planExecution)({atomicBatch:r==="supported",discovered:r!=="unknown",sponsoredTransactions:!1,...t?.maxBatchSize===void 0?{}:{maxBatchSize:t.maxBatchSize}},T,{atomicity:v,sponsorship:d}),A=d==="required"&&!y;if(I.strategy==="atomic-batch"&&!A)return{...I,reason:I.reason+(C?" A paymaster service will be requested, but the wallet's final fee payer must be checked after execution.":""),route:"wallet-batch"};let U=o&&r!=="supported"?` This account does delegate to ${n} under EIP-7702, so it is capable of batching even though the wallet has not offered to.`:"",k=v!=="any"&&!I.atomic||d==="required";return m&&k&&!A?{strategy:"atomic-batch",atomic:!0,sponsored:y,reason:d==="required"&&!I.sponsored?"The wallet batch is not configured for sponsored gas, so the calls are executed through the configured sponsored UserOperation route.":"This wallet cannot batch, so the calls are executed as a single UserOperation through the smart account, which lands as one transaction.",route:"user-operation"}:A?{strategy:"refuse",atomic:I.atomic,sponsored:!1,reason:"Sponsored gas was required, but there is no executable sponsored route: no paymaster is configured for a wallet batch, and capability advertising alone cannot pay for a sequential transaction.",route:null}:I.strategy==="refuse"?{...I,reason:I.reason+U,route:null}:{...I,reason:I.reason+U,route:"sequential"}},[r,t,f,C,m,y,l,d,o,n]),E=(0,Fe.useCallback)(async(T,v=l)=>{g(!0),c(null);try{let I=S(T.length,v);if(I.route===null)throw new jt.WalletError("method_not_allowed",I.reason);return s(I.route),I.route==="user-operation"?await m(T):await i(T,{strategy:I.route==="wallet-batch"?"atomic-batch":"sequential",...I.route==="wallet-batch"&&C?{paymasterService:f}:{}})}catch(I){let A=I instanceof Error?I:new Error("Execution failed");throw c(A),A}finally{g(!1)}},[S,i,m,l,f,C]);return{preview:S,execute:E,isExecuting:a,error:u,lastRoute:h,reset:()=>{c(null),s(null)}}}var ke=require("@naculus/connect-core"),K=require("react");var Et=null,zn=null;function _s(e){return e?JSON.stringify({defaultMaxTotalValue:e.defaultMaxTotalValue?.toString(),defaultMaxTxCount:e.defaultMaxTxCount,defaultExpiryMs:e.defaultExpiryMs,requireAllowedContracts:e.requireAllowedContracts,forbiddenMethods:e.forbiddenMethods,pbkdf2Iterations:e.pbkdf2Iterations,unsafeAllowWeakKdf:e.unsafeAllowWeakKdf,storagePrefix:e.storagePrefix,encryptionKey:e.encryptionKey,encryptionSalt:e.encryptionSalt}):""}function rt(e){let t=_s(e);if(!Et){let r=e?.storagePrefix??ke.DEFAULT_SESSION_KEY_CONFIG.storagePrefix;return Et=new ke.SessionKeyManager(e,typeof window<"u"?new ke.LocalStorageAdapter(`${r}:`):new ke.MemoryStorageAdapter),zn=t,Et}if(t!==""&&t!==zn)throw new ke.WalletError("invalid_input","useSessionKeys is backed by a process-wide SessionKeyManager, and a different spending configuration was supplied after it was created. The second configuration would be ignored, so the caller would be operating under limits it did not set. Use one configuration per application, or construct a SessionKeyManager directly.");return Et}function Qt(e){let{session:t}=P(),[r,o]=(0,K.useState)([]),[n,i]=(0,K.useState)(!1),[a,g]=(0,K.useState)(null),u=(0,K.useRef)(!0),c=(0,K.useCallback)(()=>g(null),[]),h=rt(e),s=h.isStorageAvailable(),l=(0,K.useCallback)(async()=>{if(!t){o([]);return}i(!0),g(null);try{let f=await h.listSessions();u.current&&o(f)}catch(f){u.current&&g(f instanceof Error?f:new Error("Failed to load session keys"))}finally{u.current&&i(!1)}},[t,h]);(0,K.useEffect)(()=>(u.current=!0,l(),()=>{u.current=!1}),[l]);let d=r.filter(f=>f.status==="active");return{sessions:r,activeSessions:d,loading:n,error:a,refresh:l,clearError:c,storageAvailable:s}}function br(e){let{session:t}=P(),[r,o]=(0,K.useState)(null),[n,i]=(0,K.useState)(!1),[a,g]=(0,K.useState)(null),u=(0,K.useCallback)(()=>g(null),[]),c=rt(e);return{createSessionKey:(0,K.useCallback)(async(s,l)=>{if(!t)throw new ke.WalletError("wallet_unavailable","No active wallet session");i(!0),g(null);try{let d=l??void 0,f=await c.createSessionKey(s,d);return o(f),f}catch(d){let f=d instanceof Error?d:new Error("Failed to create session key");throw g(f),f}finally{i(!1)}},[t,c]),lastCreated:r,isCreating:n,error:a,clearError:u}}function Ar(e){let[t,r]=(0,K.useState)(!1),[o,n]=(0,K.useState)(null),i=(0,K.useCallback)(()=>n(null),[]),a=rt(e);return{revokeSession:(0,K.useCallback)(async u=>{r(!0),n(null);try{await a.revokeSession(u)}catch(c){let h=c instanceof Error?c:new Error("Failed to revoke session key");throw n(h),h}finally{r(!1)}},[a]),isRevoking:t,error:o,clearError:i}}function Tr(e){let[t,r]=(0,K.useState)(!1),[o,n]=(0,K.useState)(null),i=(0,K.useCallback)(()=>n(null),[]),a=rt(e),g=(0,K.useCallback)(async(c,h,s)=>{r(!0),n(null);try{return await a.signWithSessionKey(c,h,s)}catch(l){let d=l instanceof Error?l:new Error("Failed to sign with session key");throw n(d),d}finally{r(!1)}},[a]),u=(0,K.useCallback)(async(c,h)=>{r(!0),n(null);try{return await a.checkSessionScope(c,h)}catch(s){let l=s instanceof Error?s:new Error("Failed to check session scope");throw n(l),l}finally{r(!1)}},[a]);return{signWithSession:g,checkScope:u,isBusy:t,error:o,clearError:i}}function Rr(){Et=null,zn=null}var kt=require("react");var Xt=require("@naculus/connect-core");function Yt(){let{session:e,chainId:t,client:r}=P(),[o,n]=(0,kt.useState)(!1),[i,a]=(0,kt.useState)(null);return{signMessage:(0,kt.useCallback)(async u=>{if(!e){let h=new Xt.WalletError("wallet_unavailable","No active session");throw a(h),h}let c=e.namespaces.eip155?.accounts[0]??Object.values(e.namespaces)[0]?.accounts[0];if(!c){let h=new Xt.WalletError("wallet_unavailable","No account found");throw a(h),h}n(!0),a(null);try{let h=L(r);if(!h)throw new Xt.WalletError("wallet_unavailable","Client not initialized");return await h.signMessage(e,{message:u,address:c,chainId:t??void 0})}catch(h){let s=h instanceof Error?h.message:"Signing failed",l=h instanceof Error?h:new Error(s);throw a(l),l}finally{n(!1)}},[e,t,r]),isSigning:o,error:i}}function Os(e){let t=e?.includes(":")?e.split(":").pop():e;return t&&/^0x[0-9a-fA-F]{40}$/.test(t)?t:null}function Ir(e){return e?[...e].map(t=>t.toLowerCase()).sort():null}function Ns(e,t){let r=e.to===void 0||e.to.toLowerCase()===t.to?.toLowerCase(),o=e.data===void 0||e.data.toLowerCase()===t.data?.toLowerCase();return r&&o&&((i,a)=>{if(i===void 0)return!0;if(a===void 0)return!1;try{return BigInt(i)===BigInt(a)}catch{return!1}})(e.value,t.value)&&(e.chainId===void 0||e.chainId===t.chainId)}function ot(e,t){let r=e.scope.tokenAllowances?Object.entries(e.scope.tokenAllowances).map(([n,i])=>[n.toLowerCase(),i.toString()]).sort(([n],[i])=>n.localeCompare(i)):null,o={version:1,origin:t,signer:e.signerAddress.toLowerCase(),sessionId:e.id,sessionPublicKey:e.publicKey.toLowerCase(),expiresAt:new Date(e.expiresAt).toISOString(),mode:e.scope.mode,limits:{maxTotalGas:e.scope.maxTotalGas?.toString()??null,maxGasPerTx:e.scope.maxGasPerTx?.toString()??null,maxTotalValue:e.scope.maxTotalValue?.toString()??null,maxValuePerTx:e.scope.maxValuePerTx?.toString()??null,maxTxCount:e.scope.maxTxCount??null},allowedContracts:Ir(e.scope.allowedContracts),allowedMethods:Ir(e.scope.allowedMethods),allowedChainIds:e.scope.allowedChainIds?[...e.scope.allowedChainIds].sort((n,i)=>n-i):null,tokenAllowances:r};return`Naculus Session Policy v1
|
|
2
|
-
${JSON.stringify(o)}`}function Ur(e={}){let{evmAccount:t}=$(),r=Os(t),o=nt(),n=Gt(e.execution),{signMessage:i}=Yt(),a=Qt(e.managerConfig),g=rt(e.managerConfig),[u,c]=(0,re.useState)(!1),[h,s]=(0,re.useState)(null),[l,d]=(0,re.useState)(()=>new Set),[f,m]=(0,re.useState)(!1),y=e.origin??(typeof window<"u"?window.location.origin:"unknown"),C=(0,re.useCallback)(async k=>{if(k.status!=="active"||!k.authorized||k.scope.mode!=="offchain")return!1;let R=ot(k,y);return g.verifyOffchainAuthorization(k.id,R,async({message:b,signature:O,signerAddress:_})=>(await(0,xt.recoverMessageAddress)({message:b,signature:O})).toLowerCase()===_.toLowerCase())},[g,y]);(0,re.useEffect)(()=>{let k=!1,R=a.sessions.filter(b=>b.status==="active"&&b.authorized&&b.scope.mode==="offchain");return R.length===0?(d(new Set),m(!1),()=>{k=!0}):(m(!0),Promise.all(R.map(async b=>[b.id,await C(b)])).then(b=>{k||d(new Set(b.filter(([,O])=>O).map(([O])=>O)))}).catch(b=>{k||(d(new Set),s(b instanceof Error?b:new Error("Policy verification failed")))}).finally(()=>{k||m(!1)}),()=>{k=!0})},[a.sessions,C]);let S=(0,re.useCallback)(()=>{s(null),a.clearError()},[a]),E=(0,re.useCallback)(async k=>{if(!r){let b=new ee.WalletError("wallet_unavailable","No active EVM account");throw s(b),b}if(k.mode&&k.mode!=="offchain"){let b=new ee.WalletError("method_not_allowed","This flow creates signed off-chain policies only. EIP-7702 and AA-module policies require a configured on-chain execution adapter.");throw s(b),b}if(!e.managerConfig?.encryptionKey){let b=new ee.WalletError("method_not_allowed","Persistent delegation policies require a host-provided encryptionKey. The deterministic compatibility fallback is not a production key boundary.");throw s(b),b}if(!a.storageAvailable){let b=new ee.WalletError("storage_unavailable","Persistent delegation policy storage is unavailable in this browser");throw s(b),b}c(!0),s(null);let R=null;try{R=await g.createSessionKey({...k,mode:"offchain"},r);let b=ot(R,y),O=await i(b);if(!/^0x[0-9a-fA-F]{130}$/.test(O))throw new ee.WalletError("invalid_input","Wallet did not return a valid 65-byte EVM policy signature");if((await(0,xt.recoverMessageAddress)({message:b,signature:O})).toLowerCase()!==r.toLowerCase())throw new ee.WalletError("invalid_input","Policy signature does not recover to the connected EVM account");await g.setAuthorization(R.id,{signerAddress:r,type:"offchain",rawSignature:O,message:b});let p=(await g.listSessions()).find(w=>w.id===R?.id);if(!p?.authorized)throw new ee.WalletError("invalid_input","Policy authorization was not persisted");if(!await C(p))throw new ee.WalletError("invalid_input","Persisted policy signature did not verify against its stored scope and origin");return await a.refresh(),p}catch(b){if(R)try{await g.revokeSession(R.id)}catch{}let O=b instanceof Error?b:new Error("Policy creation failed");throw s(O),O}finally{c(!1)}},[g,e.managerConfig?.encryptionKey,y,a,i,r,C]),T=(0,re.useCallback)(async k=>{c(!0),s(null);try{await g.revokeSession(k),await a.refresh()}catch(R){let b=R instanceof Error?R:new Error("Policy revocation failed");throw s(b),b}finally{c(!1)}},[g,a]),v=(0,re.useCallback)(async(k,R,b=1,O="preferred")=>{let _=(await g.listSessions()).find(_t=>_t.id===k)??null,p=await g.checkSessionScope(k,R),w=n.preview(b,O),x=_?await C(_):!1,W=!!(_&&r&&_.signerAddress.toLowerCase()===r.toLowerCase()),N=null;if(_&&e.adapter&&x&&W&&p.valid)try{N=await e.adapter.check({policy:_,transaction:R})}catch(_t){N={ready:!1,authorizationInstalled:!1,sponsored:!1,promptless:!1,reason:_t instanceof Error?`Execution adapter check failed: ${_t.message}`:"Execution adapter check failed."}}let M=!!(e.adapter?.route!=="eip7702"||o.delegated===!0&&N?.executorAddress&&o.delegate?.toLowerCase()===N.executorAddress.toLowerCase()),Q=!!(_?.status==="active"&&_.authorized&&x&&_.scope.mode==="offchain"&&W&&p.valid),Qe=!!(e.execution?.sponsorship!=="required"||N?.sponsored),Xe=!!(Q&&b===1&&N?.ready&&N.authorizationInstalled&&N.promptless&&Qe&&M),ws=!!(Q&&(w.route||Xe)),Ss=_?_.status!=="active"?`Policy is ${_.status}.`:_.authorized?x?W?p.valid?Xe?`The configured ${e.adapter?.route??"AA/7702"} adapter can submit this policy-authorized operation without another main-wallet prompt.${N?.sponsored?" Gas sponsorship is guaranteed.":""} ${N?.reason??"The on-chain execution adapter is ready."}`:e.adapter?!N?.ready||!N.authorizationInstalled?`${w.reason} ${N?.reason??"The execution adapter is not ready."}`:N.promptless?Qe?b!==1?`${w.reason} This policy adapter prepares one execution at a time and cannot claim a multi-call broadcast.`:M?w.route?`${w.reason} ${N.reason}`:w.reason:`${w.reason} The configured EIP-7702 executor does not match the account's on-chain delegation.`:`${w.reason} Sponsored gas is required, but the configured adapter does not guarantee sponsorship.`:`${w.reason} The configured adapter would invoke the main wallet again, so promptless broadcast is not ready.`:`${w.reason} The signed off-chain policy permits this request; an AA/7702 adapter is still required to broadcast without another wallet prompt.`:p.reason??"The transaction is outside the policy scope.":"The connected account is not the policy signer.":"The persisted policy signature no longer matches its scope, signer, or origin.":"The main wallet has not signed this policy.":"Policy not found.";return{policy:_,scope:p,execution:w,signerMatches:W,authorizationVerified:x,ready:ws,broadcastReady:Xe,broadcastRoute:Xe?e.adapter?.route??null:null,onchainAuthorizationVerified:!!(N?.authorizationInstalled&&M),broadcastSponsored:Xe?N?.sponsored??!1:null,broadcastPromptless:!!(Xe&&N?.promptless),reason:Ss}},[o,n,g,e.adapter,e.execution?.sponsorship,r,C]),I=(0,re.useCallback)(async(k,R,b)=>{let O=await v(k,b,1,"any");if(!O.ready)throw new ee.WalletError("method_not_allowed",O.reason);return g.signWithVerifiedOffchainAuthorization(k,_=>ot(_,y),async({message:_,signature:p,signerAddress:w})=>(await(0,xt.recoverMessageAddress)({message:_,signature:p})).toLowerCase()===w.toLowerCase(),R,b)},[g,y,v]),A=(0,re.useCallback)(async(k,R)=>{let b=e.adapter;if(!b)throw new ee.WalletError("method_not_allowed","No session-policy-aware AA/7702 execution adapter is configured.");c(!0),s(null);try{let O=await v(k,R,1,"any");if(!O.broadcastReady||!O.policy)throw new ee.WalletError("method_not_allowed",O.reason);let _=await b.prepare({policy:O.policy,transaction:R});if(!/^0x[0-9a-fA-F]{64}$/.test(_.digest))throw new ee.WalletError("invalid_input","Execution adapter returned a digest that is not 32 bytes.");if(!Ns(R,_.transaction))throw new ee.WalletError("invalid_input","Execution adapter changed the requested target, value, data, or chain.");let p=await b.check({policy:O.policy,transaction:_.transaction}),w=b.route!=="eip7702"||o.delegated===!0&&p.executorAddress!==void 0&&o.delegate?.toLowerCase()===p.executorAddress.toLowerCase();if(!p.ready||!p.authorizationInstalled||!p.promptless||e.execution?.sponsorship==="required"&&!p.sponsored||!w)throw new ee.WalletError("method_not_allowed",p.reason||"The on-chain policy authorization is not ready.");let x=await g.signWithVerifiedOffchainAuthorization(k,N=>ot(N,y),async({message:N,signature:M,signerAddress:Q})=>(await(0,xt.recoverMessageAddress)({message:N,signature:M})).toLowerCase()===Q.toLowerCase(),_.digest,_.transaction),W=await b.broadcast({policy:O.policy,prepared:_,signature:x});if(W.route!==b.route||W.status!=="submitted"||!/^0x[0-9a-fA-F]{64}$/.test(W.hash))throw new ee.WalletError("invalid_input","Execution adapter returned an invalid submission result.");return await a.refresh(),W}catch(O){let _=O instanceof Error?O:new Error("Policy execution failed");throw s(_),_}finally{c(!1)}},[o,g,e.adapter,e.execution?.sponsorship,y,v,a]),U=a.activeSessions.filter(k=>l.has(k.id));return{policies:a.sessions,activePolicies:U,storageAvailable:a.storageAvailable,loading:a.loading||f,isBusy:u,error:h??a.error,delegation:o,createPolicy:E,revokePolicy:T,previewPolicyExecution:v,signPolicyDigest:I,executePolicy:A,refresh:a.refresh,clearError:S}}var Ke=require("react");function Pr(){let{disconnect:e,status:t}=P(),[r,o]=(0,Ke.useState)(!1),[n,i]=(0,Ke.useState)(null),a=(0,Ke.useRef)(!0);return{disconnect:(0,Ke.useCallback)(async()=>{if(t!=="disconnected"){o(!0),i(null);try{await e()}catch(u){if(!a.current)return;i(u instanceof Error?u:new Error("Disconnect failed"))}finally{a.current&&o(!1)}}},[e,t]),isDisconnecting:r,error:n,cleanup:()=>{a.current=!1}}}var Jt=require("@naculus/connect-core"),V=require("react");function Le(e){let t=e.activeNamespace??"eip155",r=Array.isArray(e.accounts)?e.accounts.map(({namespace:o,address:n,derivationPath:i})=>({namespace:o,address:n,...i?{derivationPath:i}:{}})):e.address?[{namespace:t,address:e.address}]:[];return{accounts:r,activeNamespace:t,createdAt:e.createdAt??0,...e.chainId?{chainId:e.chainId}:{},...e.version?{version:e.version}:{},recoveryAvailable:!!e.mnemonic,address:r.find(o=>o.namespace===t)?.address??e.address}}function Wr(){let{connectEmbedded:e,client:t}=P(),[r,o]=(0,V.useState)(null),n=(0,V.useRef)(null),i=(0,V.useRef)(4),a=(0,V.useRef)(!1),g=(0,V.useRef)(null),[u,c]=(0,V.useState)(!1),[h,s]=(0,V.useState)(!1),[l,d]=(0,V.useState)(null),f=()=>d(null),m=(0,V.useCallback)(()=>{let p=n.current;return n.current=null,p},[]),y=(0,V.useCallback)(()=>{let p=L(t);if(!p?.embeddedConnector)throw new Jt.WalletError("wallet_unavailable","Embedded wallet not enabled.");return p.embeddedConnector},[t]),C=(0,V.useCallback)(()=>{try{return y().getWallet()?.privateKey??null}catch{return null}},[y]),S=(0,V.useCallback)(async()=>{let p=L(t);if(!p)throw new Jt.WalletError("wallet_unavailable","Embedded wallet not enabled.");let w=p.getEmbeddedConnector?await p.getEmbeddedConnector():p.embeddedConnector;if(!w)throw new Jt.WalletError("wallet_unavailable","Embedded wallet not enabled.");return w},[t]),E=(0,V.useCallback)(()=>{try{return L(t)?.passphraseGate??null}catch{return null}},[t]),T=(0,V.useCallback)(p=>{p?.code==="decryption_failed"&&E()?.forget("That passphrase did not open the wallet.")},[E]),v=(0,V.useCallback)(async()=>{a.current=!1,d(null);try{let p=await S();if(!await p.load())return!1;let x=p.getWallet();return x?(n.current=null,c(!1),o(Le(x)),!0):!1}catch(p){return a.current=!0,T(p),d(p instanceof Error?p:new Error("Failed to restore embedded wallet")),!1}},[T,S]);(0,V.useEffect)(()=>{let p=!1,w=null;return v().then(x=>{p||x||a.current||(w=setTimeout(()=>{p||v()},100))}),()=>{p=!0,w&&clearTimeout(w)}},[v]);let I=async()=>{s(!0),d(null);try{let p=await S(),w=await p.load(),x=p.getWallet();w&&x&&(o(Le(x)),n.current=x.mnemonic||null,c(!x.mnemonic)),await e();let W=p.getWallet();W&&(o(Le(W)),W.mnemonic&&!w&&(n.current=W.mnemonic,c(!0)))}catch(p){T(p),d(p instanceof Error?p:new Error("Embedded wallet connection failed"))}finally{s(!1)}},A=async()=>{s(!0),d(null);try{let p=await S();E()?.expect("create");let w=await p.generateWallet();return o(Le(w)),n.current=w.mnemonic,c(!0),w}catch(p){return d(p instanceof Error?p:new Error("Failed to generate wallet")),null}finally{s(!1)}},U=async p=>{s(!0),d(null);try{let w=await S();E()?.expect("create");let x=await w.importFromMnemonic(p);return o(Le(x)),n.current=null,c(!1),x}catch(w){return d(w instanceof Error?w:new Error("Failed to import wallet")),null}finally{s(!1)}},k=async p=>{s(!0),d(null);try{let w=await S();E()?.expect("create");let x=await w.importFromPrivateKey(p);return o(Le(x)),n.current=null,c(!1),x}catch(w){return d(w instanceof Error?w:new Error("Failed to import wallet")),null}finally{s(!1)}},R=async()=>{s(!0),d(null);try{await(await S()).wipe(),o(null),n.current=null,c(!1)}catch(p){d(p instanceof Error?p:new Error("Failed to wipe wallet"))}finally{s(!1)}},b=(0,V.useCallback)(p=>{let w=y();w.setActiveNamespace(p);let x=w.getWallet();o(x?Le(x):null)},[y]),O=(0,V.useCallback)(async()=>{let p=await S(),w=await p.backfillAccounts();if(w.length>0){let x=p.getWallet();o(x?Le(x):null)}return w.map(({namespace:x,address:W,derivationPath:N})=>({namespace:x,address:W,...N?{derivationPath:N}:{}}))},[S]),_=()=>{n.current=null,c(!1)};return{connectEmbedded:I,restoreWallet:v,generateWallet:A,importFromMnemonic:U,importFromPrivateKey:k,wipe:R,wallet:r,hasWallet:r!==null,address:r?.address??null,accounts:r?.accounts??[],activeNamespace:r?.activeNamespace??null,setActiveNamespace:b,backfillAccounts:O,seedPhrase:n.current,getSeedPhrase:m,getPrivateKey:C,backupPending:u,confirmBackup:_,isBusy:h,error:l,clearError:f,storageSecurityLevel:(()=>{try{let p=y(),w=p.getStorageSecurityLevel?.()??4;return p.getWallet()?(i.current=w,w):r?i.current:w}catch{return r?i.current:4}})(),securityReport:(()=>{let p=null;try{p=y().getStorageSecurityReport?.()??null}catch{p=null}if(!p)return g.current=null,null;let w=JSON.stringify(p);return g.current?.json===w?g.current.value:(g.current={json:w,value:p},p)})()}}var Nr=require("@naculus/connect-appkit-core"),he=require("react");var _r=require("@naculus/connect-core"),ge=require("react"),Or=require("@naculus/connect-appkit-core");function Ds(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 st(e){let{token:t,chainId:r}=e,o=t.address.toLowerCase(),n=Ds(e),i=(0,ge.useMemo)(()=>({key:n}),[n]),a=(0,ge.useRef)(n),g=(0,ge.useRef)(!0);(0,ge.useLayoutEffect)(()=>{a.current=n},[n]),(0,ge.useEffect)(()=>(g.current=!0,()=>{g.current=!1}),[]);let u=(0,ge.useCallback)(()=>g.current&&a.current===n,[n]),c=(0,ge.useCallback)(()=>{if(!u())throw new _r.WalletError("session_inactive","Wallet or token context changed. Retry the operation with the current account and chain.");let h=(0,Or.tokenChainMismatch)({address:o,chainId:t.chainId},r);if(h)throw h},[u,o,t.chainId,r]);return{identity:i,isCurrent:u,assertCurrent:c}}var Zt=require("@naculus/connect-core");function Dr(e){let{publicClient:t}=fe(),{currentChain:r}=ie(),{identity:o,isCurrent:n,assertCurrent:i}=st({token:e.token,chainId:r?(0,Nr.chainNumber)(r)??void 0:void 0,owner:e.owner,spender:e.spender,publicClient:t}),[a,g]=(0,he.useState)(null),u=a?.identity===o?a.raw:null,c=a?.identity===o&&a.fetching,h=a?.identity===o?a.error:null,s=(0,he.useRef)(null),l=(0,he.useRef)(0),d=(0,he.useCallback)(async()=>{if(!n())return;let m=++l.current,y=()=>n()&&m===l.current;if(g({identity:o,raw:null,fetching:!!t,error:null}),!!t)try{i();let C=await t.readContract({address:e.token.address,abi:Zt.ERC20_MIN_ABI,functionName:"allowance",args:[e.owner,e.spender]});if(!y())return;g({identity:o,raw:C,fetching:!1,error:null})}catch(C){if(!y())return;g({identity:o,raw:null,fetching:!1,error:C instanceof Error?C:new Error("Failed to fetch allowance")})}},[t,e.token.address,e.token.chainId,e.owner,e.spender,o,n,i]);return(0,he.useEffect)(()=>{d().catch(m=>console.warn("useERC20Allowance: initial fetch failed:",m))},[d]),(0,he.useEffect)(()=>(e.refreshInterval&&e.refreshInterval>0&&(s.current=setInterval(d,e.refreshInterval)),()=>{s.current&&(clearInterval(s.current),s.current=null)}),[e.refreshInterval,d]),{allowance:(0,he.useMemo)(()=>{if(u===null)return null;let m=e.token.decimals;return m===void 0?null:(0,Zt.formatUnits)(u,m)},[u,e.token.decimals]),allowanceRaw:u,isFetching:c,error:h,refetch:d}}var Mr=require("@naculus/connect-appkit-core"),Ce=require("react");var en=require("@naculus/connect-core"),at=require("react");function it(){let{session:e,chainId:t,client:r}=P(),[o,n]=(0,at.useState)("idle"),[i,a]=(0,at.useState)(null),g=(0,at.useCallback)(async c=>{if(!e){n("failed");let s=new en.WalletError("wallet_unavailable","No active session");throw a(s),s}let h=e.namespaces.eip155?.accounts.find(s=>/^eip155:\d+:0x[0-9a-fA-F]{40}$/.test(s)||/^0x[0-9a-fA-F]{40}$/.test(s));if(!h){n("failed");let s=new en.WalletError("wallet_unavailable","No EVM account found");throw a(s),s}n("awaiting_approval"),a(null);try{let s={...c,from:c.from??h.split(":").pop()},l=L(r);if(!l)throw new en.WalletError("wallet_unavailable","Client not initialized");let d=await l.sendTransaction(e,{transaction:s,chainId:t??void 0}),f=Vt(d);return n("submitted"),f}catch(s){n("failed");let l=s instanceof Error?s.message:"Transaction failed";throw a(s instanceof Error?s:new Error(l)),s}},[e,t,r]),u=(0,at.useCallback)(()=>{n("idle"),a(null)},[]);return{sendTransaction:g,status:o,error:i,reset:u,isSending:o==="awaiting_approval"}}var te=require("@naculus/connect-core"),Lr=require("viem");var Oe=require("@naculus/connect-appkit-core");function Ms(e){return e.includes(":")?e.split(":").pop():e}function Ls(e,t){return(0,Lr.encodeFunctionData)({abi:te.ERC20_MIN_ABI,functionName:"approve",args:[e,t]})}var Bs=2n**256n-1n;function Br(e){let{publicClient:t,walletClient:r}=fe(),{evmAccount:o,isConnected:n}=$(),{currentChain:i}=ie(),{session:a,client:g}=P(),{sendTransaction:u,isSending:c,error:h,reset:s}=it(),[l,d]=(0,Ce.useState)(null),{identity:f,isCurrent:m,assertCurrent:y}=st({token:e.token,chainId:i?(0,Mr.chainNumber)(i)??void 0:void 0,owner:o,spender:e.spender,connected:n,publicClient:t,walletClient:r,session:a,client:g}),[C,S]=(0,Ce.useState)(null),E=C?.identity===f?C.raw:null,T=C?.identity===f&&C.fetching,v=(0,Ce.useRef)((0,Oe.createDecimalsCache)(e.token,e.token.decimals)),I=(0,Ce.useRef)(0),A=l??h,U=o?Ms(o):null,k=(0,Ce.useCallback)(async()=>{if(!m())return null;let w=++I.current,x=()=>m()&&w===I.current;if(S({identity:f,raw:null,fetching:!!t&&!!U&&n}),d(null),!t||!U||!n)return null;try{y();let W=await t.readContract({address:e.token.address,abi:te.ERC20_MIN_ABI,functionName:"allowance",args:[U,e.spender]});return x()?(S({identity:f,raw:W,fetching:!1}),W):null}catch(W){return x()&&(S({identity:f,raw:null,fetching:!1}),d(W instanceof Error?W:new Error("Failed to fetch allowance"))),null}},[t,U,e.token.address,e.token.chainId,e.spender,f,m,y,n]),R=(()=>{if(E===null)return null;let w=(0,Oe.readDecimals)(v.current,e.token,e.token.decimals);return w===void 0?null:(0,te.formatUnits)(E,w)})(),b=(0,Ce.useCallback)(async w=>{if(d(null),s(),!n||!o){let x=new te.WalletError("wallet_unavailable","No connected account");throw d(x),x}if(!t){let x=new te.WalletError("wallet_unavailable","No public client");throw d(x),x}try{y();let x=Ls(e.spender,w),W=L(g);if(a&&W){let M=await u({to:e.token.address,data:x,value:"0"});return k(),M}if(r){let{request:M}=await t.simulateContract({address:e.token.address,abi:te.ERC20_MIN_ABI,functionName:"approve",args:[e.spender,w],account:U});y();let Q=await r.writeContract(M);return k(),Q}let N=await u({to:e.token.address,data:x,value:"0"});return k(),N}catch(x){let W=x instanceof Error?x:new Error("Approve failed");throw m()&&d(W),W}},[e,t,r,o,n,a,g,U,u,s,k,y,m]),O=(0,Ce.useCallback)(async w=>{try{if(y(),!t)throw new te.WalletError("wallet_unavailable","No public client");let x=(0,Oe.readDecimals)(v.current,e.token,e.token.decimals);x===void 0&&(x=await t.readContract({address:e.token.address,abi:te.ERC20_MIN_ABI,functionName:"decimals"}),y(),(0,Oe.writeDecimals)(v.current,e.token,x));let W=(0,te.parseUnits)(w,x);return await b(W)}catch(x){throw m()&&d(x instanceof Error?x:new Error("Approve failed")),x}},[e.token,t,b,y,m]),_=(0,Ce.useCallback)(async()=>b(Bs),[b]),p=(0,Ce.useCallback)(async w=>{if(!m()||!n||!U||!t)return!1;try{y()}catch(M){return d(M instanceof Error?M:new Error("Cannot check allowance")),!1}let x=E??await k();if(x===null)return!1;let W=(0,Oe.readDecimals)(v.current,e.token,e.token.decimals);if(W===void 0){if(!t)throw new te.WalletError("wallet_unavailable","Cannot check allowance: no public client to read token decimals.");if(W=await t.readContract({address:e.token.address,abi:te.ERC20_MIN_ABI,functionName:"decimals"}),!m())return!1;(0,Oe.writeDecimals)(v.current,e.token,W)}let N=(0,te.parseUnits)(w,W);return m()&&x>=N},[E,k,e.token.address,e.token.chainId,e.token.decimals,t,m,y,n,U]);return{approve:O,approveMax:_,allowance:R,allowanceRaw:E,hasAllowance:p,isApproving:c,isFetchingAllowance:T,error:A,refetchAllowance:k}}var Hr=require("@naculus/connect-appkit-core"),lt=require("react");var Ne=require("@naculus/connect-core"),Fr=require("viem");var ct=require("@naculus/connect-appkit-core");function Hs(e){return e.includes(":")?e.split(":").pop():e}function Fs(e,t){return(0,Fr.encodeFunctionData)({abi:Ne.ERC20_MIN_ABI,functionName:"transfer",args:[e,t]})}function Kr(e){let{publicClient:t,walletClient:r}=fe(),{evmAccount:o,isConnected:n}=$(),{currentChain:i}=ie(),{session:a,client:g}=P(),{sendTransaction:u,isSending:c,error:h,reset:s}=it(),[l,d]=(0,lt.useState)(null),{isCurrent:f,assertCurrent:m}=st({token:e.token,chainId:i?(0,Hr.chainNumber)(i)??void 0:void 0,owner:o,connected:n,publicClient:t,walletClient:r,session:a,client:g}),y=(0,lt.useRef)((0,ct.createDecimalsCache)(e.token,e.token.decimals)),C=l??h;return{sendTransfer:(0,lt.useCallback)(async(E,T)=>{if(d(null),s(),!n||!o){let v=new Ne.WalletError("wallet_unavailable","No connected account");throw d(v),v}if(!t){let v=new Ne.WalletError("wallet_unavailable","No public client available");throw d(v),v}try{m();let v=Hs(o),I=(0,ct.readDecimals)(y.current,e.token,e.token.decimals);I===void 0&&(I=await t.readContract({address:e.token.address,abi:Ne.ERC20_MIN_ABI,functionName:"decimals"}),m(),(0,ct.writeDecimals)(y.current,e.token,I));let A=(0,Ne.parseUnits)(T,I),U=Fs(E,A),k=L(g);if(a&&k)return await u({to:e.token.address,data:U,value:"0"});if(r){let{request:b}=await t.simulateContract({address:e.token.address,abi:Ne.ERC20_MIN_ABI,functionName:"transfer",args:[E,A],account:v});return m(),await r.writeContract(b)}return await u({to:e.token.address,data:U,value:"0"})}catch(v){let I=v instanceof Error?v:new Error("Transfer failed");throw f()&&d(I),I}},[e.token,t,r,o,n,a,g,u,s,m,f]),isSending:c,error:C}}var zr=require("@naculus/connect-appkit-core"),jr=require("react");var $r=require("@naculus/connect-appkit-core"),qr=require("@naculus/connect-core"),xe=require("react"),Vr=require("@naculus/connect-appkit-core");function tn(e,t){let{session:r}=P(),{evmAccount:o,isConnected:n}=$(),{currentChain:i}=ie(),{publicClient:a}=fe(),[g,u]=(0,xe.useState)(void 0),[c,h]=(0,xe.useState)(!1),[s,l]=(0,xe.useState)(null),d=(0,xe.useRef)(void 0),f=(0,xe.useCallback)(async()=>{if(!e){let y={status:"unavailable",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[]},provider:"eth_call",summary:"No transaction to simulate",changesDetected:!1};return u(y),y}h(!0),l(null);try{if((t??(i?(0,$r.chainNumber)(i)??void 0:void 0))===void 0)throw new qr.WalletError("invalid_chain","No chain to simulate on. Connect a wallet or pass a chainId.");let C=i?.rpcUrl;if(a)try{let E=o?.includes(":")?o.split(":").pop():o,T={to:e.to,data:e.data??"0x",value:e.value?BigInt(e.value):0n};E&&(T.from=E),await a.call(T);let v={status:"success",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[]},gasInfo:e.gas?{gasLimit:BigInt(e.gas),estimatedFeeEth:"0"}:void 0,provider:"eth_call",summary:"Transaction simulation succeeded (basic revert check only)",changesDetected:!0};return u(v),v}catch(E){let T=E?.message??String(E),v=E?.data??E?.cause?.data,I=(0,Vr.resolveRevertReason)(v,T),A={status:"reverted",revertReason:I,coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"high",message:I?`Transaction would revert: ${I}`:"Transaction would revert"}]},provider:"eth_call",summary:I?`Transaction reverted: ${I}`:"Transaction reverted",changesDetected:!1};return u(A),A}if(C)try{let T=await(await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:"eth_call",params:[{to:e.to,from:o?.includes(":")?o.split(":").pop():o,data:e.data??"0x",value:e.value??"0x0"},"latest"]})})).json();if(T.error){let I={status:"reverted",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"high",message:`Transaction would revert: ${T.error.message}`}]},provider:"eth_call",summary:"Transaction reverted",changesDetected:!1};return u(I),I}let v={status:"success",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[]},provider:"eth_call",summary:"Transaction simulation succeeded",changesDetected:!0};return u(v),v}catch(E){let T={status:"unavailable",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"medium",message:`Network error: ${E?.message??"Unknown"}`}]},provider:"eth_call",summary:"Simulation unavailable due to network error",changesDetected:!1};return u(T),T}let S={status:"unavailable",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"low",message:"No RPC URL or public client available for simulation"}]},provider:"eth_call",summary:"Simulation unavailable: no RPC URL",changesDetected:!1};return u(S),S}catch(y){let C=y instanceof Error?y:new Error("Simulation failed");throw l(C),C}finally{h(!1)}},[e,t,i,a,o]);(0,xe.useEffect)(()=>{if(e)return d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{f().catch(()=>{})},300),()=>{d.current&&clearTimeout(d.current)}},[e,f]);let m=(0,xe.useCallback)(()=>{u(void 0),l(null),h(!1)},[]);return{result:g,isSimulating:c,error:s,simulate:f,reset:m}}var Ks="0xa9059cbb";function $s(e){return(e.startsWith("0x")?e.slice(2):e).padStart(64,"0")}function qs(e,t=32){return(e.startsWith("0x")?e.slice(2):e).padStart(t*2,"0")}function Vs(e,t){let[r="0",o=""]=e.split("."),n=o.padEnd(t,"0").slice(0,t);return BigInt(r+n||"0")}function zs(e,t){return`${Ks}${$s(e)}${qs(t.toString(16))}`}function Gr(e){let{evmAccount:t,isConnected:r}=$(),{currentChain:o}=ie(),n=e.token.chainId??(o?(0,zr.chainNumber)(o)??void 0:void 0),i=(0,jr.useMemo)(()=>{if(!(!r||!t))try{let g=e.token.decimals;if(g===void 0)return;let u=Vs(e.amount,g),c=zs(e.to,u);return{to:e.token.address,data:c,value:"0"}}catch{return}},[e.token.address,e.token.decimals,e.to,e.amount,t,r]),a=tn(i,n);return{result:a.result,isSimulating:a.isSimulating,error:a.error,reSimulate:a.simulate,reset:a.reset}}var Ie=require("react");var ye=require("react"),nn=require("react"),jn=(0,nn.createContext)(null);function vt(){return(0,nn.useContext)(jn)}function Qr(e,t,r){let o=vt(),n=r??o,[i,a]=(0,ye.useState)(null),[g,u]=(0,ye.useState)(!1),[c,h]=(0,ye.useState)(!1),[s,l]=(0,ye.useState)(null),d=(0,ye.useRef)(void 0),f=(0,ye.useCallback)(async()=>{if(!(!n||!e)){u(!0),l(null);try{await n.refreshTx(e,t);let C=n.getTxStatus(e,t);C&&a(C)}catch(C){l(C instanceof Error?C:new Error(String(C)))}finally{u(!1)}}},[n,e,t]),m=(0,ye.useCallback)(()=>{!n||!e||(n.stopWatching(e,t),h(!1))},[n,e,t]);(0,ye.useEffect)(()=>{if(!n||!e||!t){a(null),h(!1);return}d.current&&d.current!==e&&n.stopWatching(d.current),d.current=e;let C=!1;h(!0),u(!0),l(null);let S=n.getTxStatus(e,t);S&&(a(S),u(!1)),n.watchTx(e,t,{}).then(T=>{C||(a(T),u(!1))}).catch(T=>{C||(l(T instanceof Error?T:new Error(String(T))),u(!1))});let E=T=>{C||a({...T})};return n.on("statusChange",E),()=>{C=!0,h(!1),n.off("statusChange",E)}},[n,e,t]);let y=i?.status??"idle";return{entry:i,status:y,isLoading:g,isWatching:c,error:s,refresh:f,stopWatching:m}}function Xr(e){let t=vt(),r=e??t,[o,n]=(0,Ie.useState)(null),[i,a]=(0,Ie.useState)(null),[g,u]=(0,Ie.useState)(null),c=(0,Ie.useRef)(null),h=(0,Ie.useRef)(null),s=(0,Ie.useRef)(null);r&&(h.current||(h.current=d=>{a(d),(!c.current||d.createdAt>=c.current.createdAt)&&(n(d),c.current=d)},r.on("confirmed",h.current)),s.current||(s.current=d=>{u(d),(!c.current||d.createdAt>=c.current.createdAt)&&(n(d),c.current=d)},r.on("failed",s.current)));let l=(0,Ie.useCallback)(()=>{n(null),a(null),u(null),c.current=null},[]);return{lastTx:o,lastConfirmedTx:i,lastFailedTx:g,clear:l}}var Jr=require("react");var le=require("react"),Yr=require("@naculus/connect-appkit-core");function rn({input:e,skip:t=!1,resolverConfig:r,scope:o,query:n}){let[i,a]=(0,le.useState)(null),[g,u]=(0,le.useState)(!1),[c,h]=(0,le.useState)(null),s=(0,le.useRef)(0),l=(0,le.useRef)(!0);(0,le.useEffect)(()=>(l.current=!0,()=>{l.current=!1}),[]);let d=(0,le.useMemo)(()=>(0,Yr.getResolver)(r),[r]),f=(0,le.useCallback)(()=>{let m=e.trim();if(!m||t){s.current+=1,a(null),u(!1),h(null);return}let y=++s.current;u(!0),h(null),n(d,m,o).then(C=>{!l.current||y!==s.current||(a(C),u(!1))}).catch(C=>{!l.current||y!==s.current||(h(C instanceof Error?C:new Error(String(C))),a(null),u(!1))})},[e,t,o,d,n]);return(0,le.useEffect)(()=>{f()},[f]),{data:i,isLoading:g,error:c,refetch:f}}function Zr(e,t){let r=(0,Jr.useCallback)((o,n,i)=>o.lookupAddress(n,i),[]);return rn({input:e,skip:t?.skip,resolverConfig:t?.resolverConfig,scope:t?.chainId,query:r})}var G=require("react"),no=require("@naculus/connect-core"),ro=require("@naculus/connect-core"),js={telegram:!1,webpush:!1,inapp:!0,frequency:"final-only",mutedChains:[],mutedTypes:[]},eo="naculus_notif_react_settings";function oo(e){let t=(0,G.useRef)(null);t.current||(t.current=e?.channel??new no.InAppChannel);let r=t.current,[o,n]=(0,G.useState)(()=>r.getHistory()),[i,a]=(0,G.useState)(()=>js);(0,G.useEffect)(()=>{(e?.storage??to()).getItem(eo).then(S=>{S&&a(S)})},[]),(0,G.useEffect)(()=>(r.onNotification=C=>{n(S=>[...S,C])},r.restore().then(()=>{n(r.getHistory())}),()=>{r.onNotification=void 0}),[]);let g=(0,G.useMemo)(()=>o.filter(C=>!C.read).length,[o]),u=(0,G.useCallback)(()=>{r.clear(),n([])},[r]),c=(0,G.useCallback)(C=>{let S=r.getHistory().filter(E=>E.id!==C);r.clear(),Promise.all(S.map(E=>r.send({id:E.id,userId:"",txHash:E.txHash,chainId:"",chainName:E.chainName,status:E.status,title:E.title,body:E.body,valueFormatted:E.valueFormatted,explorerUrl:E.explorerUrl,timestamp:E.timestamp}))).then(()=>{n(r.getHistory())})},[r]),h=(0,G.useCallback)(C=>{r.markAsRead(C),n(S=>S.map(E=>E.id===C?{...E,read:!0}:E))},[r]),s=(0,G.useCallback)(()=>{r.markAllAsRead(),n(C=>C.map(S=>({...S,read:!0})))},[r]),l=(0,G.useCallback)(C=>{let S={...C,id:`notif_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now()};r.send({id:S.id,userId:"",txHash:S.txHash,chainId:"",chainName:S.chainName,status:S.status,title:S.title,body:S.body,valueFormatted:S.valueFormatted,explorerUrl:S.explorerUrl,timestamp:S.timestamp})},[r]),d=(0,G.useCallback)(C=>{a(S=>{let E={...S,...C};return(e?.storage??to()).setItem(eo,E).catch(()=>{}),E})},[e?.storage]),f=(0,G.useCallback)(C=>{let S={};C.includes("telegram")&&(S.telegram=!0),C.includes("webpush")&&(S.webpush=!0),C.includes("inapp")&&(S.inapp=!0),d(S)},[d]),m=(0,G.useCallback)(C=>{d({mutedChains:[...new Set([...i.mutedChains,C])]})},[i.mutedChains,d]),y=(0,G.useCallback)(C=>{d({mutedChains:i.mutedChains.filter(S=>S!==C)})},[i.mutedChains,d]);return{notifications:o,unreadCount:g,addNotification:l,clear:u,clearOne:c,markAsRead:h,markAllAsRead:s,settings:i,updateSettings:d,setChannels:f,muteChain:m,unmuteChain:y}}function to(){let e=(0,ro.createStorageAdapter)("local","naculus_notif_");return{getItem:async t=>{try{return await e.get(t)}catch(r){return console.warn("useNotification: failed to read from storage:",r),null}},setItem:async(t,r)=>{try{await e.set(t,r)}catch(o){console.warn("useNotification: failed to write to storage:",o)}},removeItem:async t=>{try{await e.remove(t)}catch(r){console.warn("useNotification: failed to remove from storage:",r)}}}}var ut=require("react");var so=()=>null,Gs=()=>()=>{};function ao(){let{client:e}=P(),t=L(e)?.passphraseGate??null,r=(0,ut.useSyncExternalStore)(t?.subscribe??Gs,t?.getSnapshot??so,so),o=(0,ut.useCallback)(a=>t?.submit(a),[t]),n=(0,ut.useCallback)(()=>t?.cancel(),[t]),i=(0,ut.useCallback)(a=>t?.forget(a),[t]);return{request:r,submit:o,cancel:n,forget:i,isUnlocked:t?.isUnlocked??!1,gate:t}}var io=require("react");function lo(e,t){let r=(0,io.useCallback)((o,n)=>o.resolveName(n),[]);return rn({input:e,skip:t?.skip,resolverConfig:t?.resolverConfig,query:r})}var ce=require("@naculus/connect-core"),oe=require("react"),co=require("@naculus/connect-appkit-core");function Qs(e){if(!e)return null;let t=e.includes(":")?e.split(":").pop():e;return t&&/^0x[0-9a-fA-F]{40}$/.test(t)?t:null}function Gn(e){if(typeof e!="string"||!/^0x(?:[0-9a-fA-F]{2})+$/.test(e))throw new ce.WalletError("signature_rejected","Wallet returned an invalid UserOperation signature.");return e}async function Xs(e,t,r,o,n){let i=L(t);if(!i)throw new ce.WalletError("wallet_unavailable","Client not initialized");let a=[r,o];if(e.walletType==="eip6963"||e.id?.startsWith("eip6963-")){let{eip6963Connector:g}=await import("@naculus/connector-evm-injected"),u=g.getDiscoveredWallets().find(h=>h.id===e.walletId),c=u?await u.provider.request({method:"personal_sign",params:a}):await g.request({method:"personal_sign",params:a});return Gn(c)}if(e.walletType==="walletconnect")return Gn(await i.connector.request({method:"personal_sign",params:a}));if(e.walletType==="embedded"){let g=i.embeddedConnector;if(!g?.signHash)throw new ce.WalletError("method_unsupported","This embedded wallet build cannot sign a raw digest. Upgrade @naculus/connector-embedded or pass an explicit signer.");return Gn(await g.signHash(e,r))}throw e.walletType==="passkeys"?new ce.WalletError("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 ce.WalletError("method_unsupported",`Raw UserOperation signing is not available for ${e.walletType} on ${n}. Pass a signer that signs the raw 32-byte hash.`)}function uo(e){let{evmAccount:t}=$(),{session:r,chainId:o,client:n}=P(),[i,a]=(0,oe.useState)(null),[g,u]=(0,oe.useState)(null),[c,h]=(0,oe.useState)(!1),[s,l]=(0,oe.useState)(!1),[d,f]=(0,oe.useState)(null),m=(0,oe.useRef)(0),y=(0,oe.useRef)(!1);(0,oe.useEffect)(()=>()=>{m.current+=1,y.current=!1},[]),(0,oe.useEffect)(()=>{m.current+=1,y.current=!1,a(null),u(null),h(!1),l(!1),f(null)},[n,o,t,e?.accountType,e?.bundlerUrl,e?.chainId,e?.entryPoint,e?.owner,e?.rpcUrl,e?.salt,e?.signerMode,r]);let C=(0,oe.useCallback)(async(E,T)=>{let v=k=>(f(k),null);if(!e?.rpcUrl)return v(new Error("RPC URL not configured"));if(!e.bundlerUrl)return v(new Error("Bundler URL not configured"));if(!E.length)return v(new Error("At least one call is required"));if(y.current)return v(new Error("A UserOperation is already in progress"));let I=Qs(e.owner??t);if(!I)return v(new ce.WalletError("wallet_unavailable","No EVM account found"));let A=(0,co.resolveEvmChainId)(e.chainId,o);if(!A)return v(new ce.WalletError("invalid_chain",e.chainId||o?`Invalid EVM chain ID: ${e.chainId??o}`:"No EVM chain to send on. Connect a wallet or pass options.chainId."));if(o&&o!==A)return v(new ce.WalletError("chain_mismatch",`Connected chain ${o} does not match UserOperation chain ${A}.`));if(!e.signer&&!r)return v(new ce.WalletError("wallet_unavailable","No active session"));let U=++m.current;y.current=!0,h(!0),l(!0),f(null),a(null),u(null);try{let{SmartAccountManager:k}=await import("@naculus/connect-core"),R=e.signer??(p=>Xs(r,n,p,I,A)),b=new k({rpcUrl:e.rpcUrl,bundlerClient:{url:e.bundlerUrl},chainId:A,signer:R,signerMode:e.signer?e.signerMode??"eip191":"raw"}),O={owner:I,accountType:e.accountType??"simple",entryPoint:e.entryPoint??ce.AA_SUPPORTED_CHAINS[A]?.entryPoint??ce.DEFAULT_ENTRY_POINT,chainId:A,salt:e.salt},_=await b.sendUserOperation(O,E,T);return U!==m.current?null:(l(!1),a(_.userOpHash),b.getUserOperationReceipt(_.userOpHash).then(p=>{U===m.current&&u(p)}).catch(()=>{}),_)}catch(k){if(U!==m.current)return null;let R=k instanceof Error?k:new Error("Failed to send UserOperation");return f(R),null}finally{U===m.current&&(h(!1),l(!1),y.current=!1)}},[n,o,t,e,r]),S=(0,oe.useCallback)(()=>{m.current+=1,y.current=!1,a(null),u(null),h(!1),l(!1),f(null)},[]);return{sendUserOp:C,userOpHash:i,receipt:g,isPending:c,isEstimating:s,error:d,reset:S}}var bt=require("react");function Ys(e,t){if(!e)return()=>{};let r=()=>t();return e.on("sessionConnected",r),e.on("sessionDisconnected",r),e.on("chainChanged",r),()=>{e.off("sessionConnected",r),e.off("sessionDisconnected",r),e.off("chainChanged",r)}}var Qn=Object.freeze({session:null,chainSessions:[],activeChainId:null,isConnected:!1,connectorId:null}),Xn=new WeakMap;function Js(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function Zs(e){if(!e)return Qn;let t=e.getActiveBundle(),r=Xn.get(e);if(!t)return r&&r.session===null?r:(Xn.set(e,Qn),Qn);let o=Array.from(t.chainSessions.values());if(r&&r.session===t.walletSession&&r.activeChainId===t.activeChainId&&Js(r.chainSessions,o))return r;let n={session:t.walletSession,chainSessions:o,activeChainId:t.activeChainId,isConnected:!0,connectorId:t.walletSession.walletType};return Xn.set(e,n),n}function po(e){let t=P(),r=e??t.sessionManager??null,o=(0,bt.useCallback)(i=>Ys(r,i),[r]),n=(0,bt.useCallback)(()=>Zs(r),[r]);return(0,bt.useSyncExternalStore)(o,n)}var At=require("@naculus/connect-core"),Ue=require("@naculus/siwx"),pt=require("react");var ea=86400;function ta(){return typeof window<"u"?window.location.host:"localhost"}function na(){return typeof window<"u"?window.location.origin:"http://localhost"}function on(){let{session:e,chainId:t,client:r}=P(),[o,n]=(0,pt.useState)(!1),[i,a]=(0,pt.useState)(null),g=(0,pt.useCallback)(()=>a(null),[]);return{signIn:(0,pt.useCallback)(async c=>{if(!e)throw new At.WalletError("wallet_unavailable","No active session");let h=c?.chainId??t;if(!h)throw new At.WalletError("invalid_chain","No chain to sign for. Connect a wallet or pass options.chainId.");let s=Ye(e,h);if(!s)throw new At.WalletError("wallet_unavailable","No account found");let l=L(r);if(!l)throw new At.WalletError("wallet_unavailable","Client not initialized");let{address:d}=s,f=c?.domain??ta(),m=c?.uri??na();n(!0),a(null);try{let y=(0,Ue.generateNonce)();await(0,Ue.issueNonce)(y);let C=(0,Ue.nowISO)(),S=c?.expirySeconds??ea,E=new Date(Date.now()+S*1e3).toISOString(),T=(0,Ue.createSiwxMessage)({domain:f,address:d,uri:m,version:1,chainId:h,nonce:y,issuedAt:C,expirationTime:E,statement:c?.statement,resources:c?.resources,requestId:c?.requestId}),v=await l.signMessage(e,{message:T,address:d,chainId:h??void 0}),I={message:{raw:T,domain:f,address:d,statement:c?.statement??null,uri:m,version:1,chainId:h,nonce:y,issuedAt:C,blockchain:(0,Ue.getBlockchainName)(h),expirationTime:E,notBefore:null,resources:c?.resources??[],requestId:c?.requestId??null},signature:v};return n(!1),I}catch(y){let C=y instanceof Error?y:new Error("SIWx sign-in failed");throw a(C),n(!1),C}},[e,t,r]),isSigningIn:o,error:i,clearError:g}}var sn=require("@naculus/connect-core"),Tt=require("@naculus/siwx"),se=require("react");function ra(){let e=new Uint8Array(8);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function mo(e){return{id:`siwx_${Date.now().toString(36)}_${ra()}`,chainId:e.message.chainId,address:e.message.address,domain:e.message.domain,message:e.message,signature:e.signature,issuedAt:e.message.issuedAt??new Date().toISOString(),expiresAt:e.message.expirationTime,refreshedAt:null}}function fo(e){let{storagePrefix:t="naculus_",autoRestore:r=!0,defaultExpirySeconds:o=86400}=e??{},[n,i]=(0,se.useState)(null),[a,g]=(0,se.useState)(r),[u,c]=(0,se.useState)(!1),[h,s]=(0,se.useState)(null),{session:l,chainId:d}=P(),f=on(),m=(0,se.useRef)((0,Tt.createLocalStorageSiwxSessionStorage)(`${t}siwx_session`)),y=(0,se.useCallback)(()=>s(null),[]);(0,se.useEffect)(()=>{if(!r){g(!1);return}let A=!1;return(async()=>{try{let k=await m.current.get();if(A)return;k?(sn.logger.info("react/useSIWxSession","Restored persisted SIWx session"),i(k),s(null)):i(null)}catch(U){sn.logger.warn("react/useSIWxSession","Failed to restore SIWx session:",U),i(null)}finally{A||g(!1)}})(),()=>{A=!0}},[r]),(0,se.useEffect)(()=>{if(!n?.expiresAt)return;let A=new Date(n.expiresAt).getTime()-Date.now();if(A<=0){i(null);return}let U=setTimeout(()=>{i(k=>k&&k.id===n.id?null:k)},A);return()=>clearTimeout(U)},[n?.id,n?.expiresAt]);let C=(0,se.useCallback)(async A=>{c(!0),s(null);try{let U={expirySeconds:o,chainId:d??void 0,...A},k=await f.signIn(U),R=mo(k);return await m.current.set(R),i(R),c(!1),R}catch(U){let k=U instanceof Error?U:new Error("SIWx sign-in failed");throw s(k),c(!1),k}},[f,d,o]),S=(0,se.useCallback)(async()=>{try{await m.current.remove()}catch(A){sn.logger.warn("react/useSIWxSession","Failed to clear session:",A)}i(null),s(null)},[]),E=(0,se.useCallback)(async()=>{if(!n)throw new Error("No active session to refresh");c(!0),s(null);try{let A=await f.signIn({domain:n.domain,statement:n.message.statement??void 0,uri:n.message.uri,chainId:n.chainId,expirySeconds:o,resources:n.message.resources.length>0?n.message.resources:void 0,requestId:n.message.requestId??void 0}),U={...mo(A),id:n.id,refreshedAt:new Date().toISOString()};return await m.current.set(U),i(U),c(!1),U}catch(A){let U=A instanceof Error?A:new Error("Session refresh failed");throw s(U),c(!1),U}},[n,f,o]),T=n!==null&&!(0,Tt.checkSessionExpired)(n),v=(0,Tt.checkSessionExpired)(n),I=n?.expiresAt?Math.max(0,new Date(n.expiresAt).getTime()-Date.now()):null;return{session:T?n:null,isAuthenticated:T,isRestoring:a,isSigningIn:u,isExpired:v,timeUntilExpiry:I,signIn:C,signOut:S,refresh:E,error:h,clearError:y}}var Rt=require("@naculus/connect-core"),Pe=require("@naculus/siwx"),$e=require("react");function oa(){return typeof window<"u"?window.location.host:"localhost"}function sa(){return typeof window<"u"?window.location.origin:"http://localhost"}function dt(){let{session:e,chainId:t,client:r}=P(),[o,n]=(0,$e.useState)(!1),[i,a]=(0,$e.useState)(null),[g,u]=(0,$e.useState)(null),c=(0,$e.useCallback)(()=>u(null),[]);return{signIn:(0,$e.useCallback)(async s=>{if(!e)throw new Rt.WalletError("wallet_unavailable","No active session");let l=s?.chainId??t;if(!l)throw new Rt.WalletError("invalid_chain","No chain to sign for. Connect a wallet or pass options.chainId.");let d=Ye(e,l);if(!d)throw new Rt.WalletError("wallet_unavailable","No account found");let f=L(r);if(!f)throw new Rt.WalletError("wallet_unavailable","Client not initialized");let{address:m}=d,y=s?.domain??oa(),C=s?.uri??sa();n(!0),u(null);try{let S=(0,Pe.generateNonce)();await(0,Pe.issueNonce)(S);let E=(0,Pe.nowISO)(),T=(0,Pe.createSiwxMessage)({domain:y,address:m,uri:C,version:1,chainId:l,nonce:S,issuedAt:E,statement:s?.statement,expirationTime:s?.expirySeconds?new Date(Date.now()+s.expirySeconds*1e3).toISOString():void 0,resources:s?.resources,requestId:s?.requestId}),v=await f.signMessage(e,{message:T,address:m,chainId:l??void 0}),I=s?.expirySeconds?new Date(Date.now()+s.expirySeconds*1e3).toISOString():null,A={message:{raw:T,domain:y,address:m,statement:s?.statement??null,uri:C,version:1,chainId:l,nonce:S,issuedAt:E,blockchain:(0,Pe.getBlockchainName)(l),expirationTime:I,notBefore:null,resources:s?.resources??[],requestId:s?.requestId??null},signature:v};return a(A),A}catch(S){let E=S instanceof Error?S:new Error("SIWx sign-in failed");throw u(E),E}finally{n(!1)}},[e,t,r]),isSigningIn:o,result:i,error:g,clearError:c}}var an=require("@naculus/connect-core");var Yn=require("react");function aa(){let{session:e,chainId:t}=P();return(0,Yn.useCallback)(r=>{if(!e)throw new an.WalletError("wallet_unavailable","No active session");let o=r??t;if(o&&!o.startsWith("eip155:"))throw new an.WalletError("namespace_mismatch",`Ethereum SIWx requires an eip155 chain, received ${o}`);let n=e.namespaces.eip155;if(!n||n.accounts.length===0)throw new an.WalletError("namespace_mismatch","No EVM (eip155) accounts found in session")},[e,t])}function go(){let e=aa(),t=dt();return{signIn:(0,Yn.useCallback)(async o=>(e(o?.chainId),t.signIn(o)),[e,t.signIn]),isSigningIn:t.isSigningIn,result:t.result,error:t.error,clearError:t.clearError}}var ho=require("@naculus/connect-core"),Co=require("@naculus/wallet-engine"),De=require("react");function yo(e){let t=e?.rpcUrl,r=e?.chainId,o=(0,De.useRef)(null);function n(){return o.current||(o.current=new Co.SimulationManager({enabled:!0,rpcUrl:t,autoSimulate:!1})),o.current}let[i,a]=(0,De.useState)(null),[g,u]=(0,De.useState)(!1),[c,h]=(0,De.useState)(null),s=(0,De.useCallback)(async(d,f,m,y,C)=>{u(!0),h(null);try{let S=n(),E=C?.chainId??r;if(E===void 0)throw new ho.WalletError("invalid_chain","No chain to simulate on. Connect a wallet or pass a chainId.");let T=C?.rpcUrl??t,v=await S.simulateERC20Transfer(d,f,m,y,E,C?.decimals,T);return a(v),v}catch(S){let E=S instanceof Error?S:new Error(String(S));throw h(E),E}finally{u(!1)}},[t,r]),l=(0,De.useCallback)(()=>{a(null),h(null),u(!1)},[]);return{result:i,loading:g,error:c,simulate:s,reset:l}}var de=require("react");var qe=require("@naculus/connect-core"),ln="siwx_auth";function ia(e){return new qe.LocalStorageAdapter(e)}function la(e,t){return e.message.expirationTime?new Date(e.message.expirationTime).getTime()<=t.getTime():!1}function ca(e,t){return e.message.notBefore?new Date(e.message.notBefore).getTime()<=t.getTime():!0}function wo(e){let{storagePrefix:t="naculus_",autoRestore:r=!0}=e??{},[o,n]=(0,de.useState)(null),[i,a]=(0,de.useState)(r),[g,u]=(0,de.useState)(!1),[c,h]=(0,de.useState)(null),s=dt(),l=(0,de.useRef)(ia(t)),d=(0,de.useCallback)(()=>h(null),[]);(0,de.useEffect)(()=>{if(!r){a(!1);return}let y=!1;return(async()=>{try{let C=l.current,S=await C.get(ln);if(y)return;S&&!la(S,new Date)&&ca(S,new Date)?(qe.logger.info("react/useSiwxAuthSession","Restored persisted SIWx auth session"),n(S),h(null)):S&&(qe.logger.info("react/useSiwxAuthSession","Persisted SIWx auth expired, clearing"),await C.remove(ln))}catch(C){qe.logger.warn("react/useSiwxAuthSession","Failed to restore SIWx auth:",C)}finally{y||a(!1)}})(),()=>{y=!0}},[r]);let f=(0,de.useCallback)(async y=>{u(!0),h(null);try{let C=await s.signIn(y);return await l.current.set(ln,C),n(C),u(!1),C}catch(C){let S=C instanceof Error?C:new Error("SIWx sign-in failed");throw h(S),u(!1),S}},[s]),m=(0,de.useCallback)(async()=>{try{await l.current.remove(ln)}catch(y){qe.logger.warn("react/useSiwxAuthSession","Failed to clear SIWx auth:",y)}n(null),h(null)},[]);return{isSignedIn:o!==null,isRestoring:i,siwxResult:o,isSigningIn:g,error:c,signIn:f,signOut:m,clearError:d}}var Ve=require("@naculus/connect-core"),z=require("react"),Jn=require("@naculus/connect-appkit-core");function ua(e){if(!e)return null;let t=e.includes(":")?e.split(":").pop():e;return t&&/^0x[0-9a-fA-F]{40}$/.test(t)?t:null}function So(e){return new Ve.WalletError("wallet_unavailable",e)}function Eo(e){let{evmAccount:t}=$(),{session:r,chainId:o,client:n}=P(),[i,a]=(0,z.useState)(null),[g,u]=(0,z.useState)(!1),[c,h]=(0,z.useState)(null),[s,l]=(0,z.useState)(!1),[d,f]=(0,z.useState)(null),m=(0,z.useRef)(null),y=(0,z.useRef)(0),C=(0,z.useRef)(!1);(0,z.useEffect)(()=>{if(m.current=null,!e?.rpcUrl)return;let k=!1;return import("@naculus/connect-core").then(({SmartAccountManager:R})=>{if(k)return;let b=(0,Jn.resolveEvmChainId)(e.chainId,o);b&&(m.current=new R({rpcUrl:e.rpcUrl,chainId:b,bundlerClient:{url:e.bundlerUrl??""}}))}).catch(R=>{k||f(R instanceof Error?R:new Error("Failed to load account-abstraction module"))}),()=>{k=!0}},[o,e?.rpcUrl,e?.bundlerUrl,e?.chainId]),(0,z.useEffect)(()=>{y.current+=1,C.current=!1,a(null),u(!1),h(null),l(!1),f(null)},[t,o,e?.rpcUrl,e?.bundlerUrl,e?.chainId,e?.entryPoint,e?.accountType,e?.salt]);let S=(0,z.useCallback)(()=>{let k=ua(t);if(!k||!m.current)return null;let R=(0,Jn.resolveEvmChainId)(e?.chainId,o);return R?{owner:k,accountType:e?.accountType??"simple",entryPoint:e?.entryPoint??Ve.AA_SUPPORTED_CHAINS[R]?.entryPoint??Ve.DEFAULT_ENTRY_POINT,chainId:R,salt:e?.salt}:null},[t,o,e?.accountType,e?.chainId,e?.entryPoint,e?.salt]),E=(0,z.useCallback)(k=>(f(k),null),[]),T=(0,z.useCallback)(()=>C.current?null:(C.current=!0,y.current),[]),v=(0,z.useCallback)(k=>{y.current===k&&(C.current=!1)},[]),I=(0,z.useCallback)(async()=>{let k=S();if(!k||!m.current)return E(new Error("Smart account not configured"));let R=T();if(R===null)return E(new Error("Smart account operation already in progress"));l(!0),f(null);try{let O=await m.current.createAccount(k);return y.current!==R?null:(a(O.address),u(O.isDeployed),h(O),O)}catch(b){if(y.current!==R)return null;let O=b instanceof Error?b:new Error("Failed to create smart account");return f(O),null}finally{y.current===R&&l(!1),v(R)}},[T,E,v,S]),A=(0,z.useCallback)(async()=>{let k=S();if(!k||!m.current)return E(new Error("Smart account not configured"));if(!r)return E(So("No active session"));let R=L(n);if(!R)return E(So("Client not initialized"));if(o&&o!==k.chainId)return E(new Ve.WalletError("chain_mismatch",`Connected chain ${o} does not match smart account chain ${k.chainId}.`));let b=T();if(b===null)return E(new Error("Smart account operation already in progress"));l(!0),f(null);try{let O=m.current,_=await O.createAccount(k);if(y.current!==b)return null;if(_.isDeployed)return a(_.address),u(!0),h(_),_.address;let p=await O.getDeployCallData(k),w=await R.sendTransaction(r,{transaction:{to:p.to,data:p.data,value:p.value.toString()},chainId:k.chainId});if(y.current!==b)return null;let x=await O.createAccount(k);return a(x.address),u(x.isDeployed),h(x),w}catch(O){if(y.current!==b)return null;let _=O instanceof Error?O:new Error("Failed to deploy smart account");return f(_),null}finally{y.current===b&&l(!1),v(b)}},[n,o,T,E,v,S,r]),U=(0,z.useCallback)(async()=>{let k=S();if(!k||!m.current)return null;let R=y.current;try{let b=await m.current.getAccountAddress(k);return y.current!==R?null:(a(b),b)}catch(b){return y.current!==R||f(b instanceof Error?b:new Error("Failed to get smart account address")),null}},[S]);return{address:i,isDeployed:g,accountInfo:c,isLoading:s,error:d,createWallet:I,deployWallet:A,getAddress:U}}var ko=require("react");function cn(){let{accounts:e,isConnected:t}=P();return(0,ko.useMemo)(()=>{if(!t)return{address:null,caip10:null,chainId:null,isConnected:!1};let r=e.find(a=>a.startsWith("solana:"))??null;if(!r)return{address:null,caip10:null,chainId:null,isConnected:t};let o=r.split(":"),n=o.length>=3?o[o.length-1]:null,i=o.length>=3?o.slice(0,-1).join(":"):null;return{address:n,caip10:r,chainId:i,isConnected:t}},[e,t])}var ve=require("react"),xo=require("@naculus/connect-core");function vo(e={}){let{client:t}=P(),{address:r}=cn(),o=e.address??r,n=e.rpcUrl??L(t)?.solanaRpcUrl??null,[i,a]=(0,ve.useState)(null),[g,u]=(0,ve.useState)(!1),[c,h]=(0,ve.useState)(null),s=(0,ve.useRef)(0),l=(0,ve.useCallback)(async()=>{if(!o||!n){a(null);return}let d=++s.current;u(!0),h(null);try{let f=await(0,xo.getSolanaBalance)(n,o);if(d!==s.current)return;a(f)}catch(f){if(d!==s.current)return;a(null),h(f instanceof Error?f:new Error("Balance read failed"))}finally{d===s.current&&u(!1)}},[o,n]);return(0,ve.useEffect)(()=>{l()},[l]),(0,ve.useEffect)(()=>{if(!e.refreshInterval||e.refreshInterval<=0)return;let d=setInterval(()=>{l()},e.refreshInterval);return()=>clearInterval(d)},[e.refreshInterval,l]),{balance:i,isFetching:g,error:c,isConfigured:!!n,refetch:l}}var Zn=require("@naculus/connect-core"),Be=require("react"),bo=require("@naculus/connect-core");function Ao(){let{client:e,session:t}=P(),[r,o]=(0,Be.useState)(!1),[n,i]=(0,Be.useState)(!1),[a,g]=(0,Be.useState)(null),u=()=>{let l=L(e);if(!l||!t)throw new Zn.WalletError("wallet_unavailable","No connected wallet.");return l},c=(0,Be.useCallback)(async l=>{o(!0),g(null);try{return await u().signTransaction(t,{transaction:l})}catch(d){let f=d instanceof Error?d:new Error("Signing failed");throw g(f),f}finally{o(!1)}},[e,t]),h=(0,Be.useCallback)(async l=>{i(!0),g(null);try{return await u().sendTransaction(t,{transaction:l})}catch(d){let f=d instanceof Error?d:new Error("Send failed");throw g(f),f}finally{i(!1)}},[e,t]),s=(0,Be.useCallback)(async l=>{let d=L(e)?.solanaRpcUrl;if(!d)throw new Zn.WalletError("no_rpc","Set solanaRpcUrl on the client to read a signature's status.");return(0,bo.getSignatureStatus)(d,l)},[e]);return{signTransaction:c,sendTransaction:h,getStatus:s,isSigning:r,isSending:n,error:a,reset:()=>g(null)}}var mt=require("react"),To=require("@naculus/connect-appkit-core");function Ro(){let{switchChain:e,chainId:t}=P(),[r,o]=(0,mt.useState)(!1),[n,i]=(0,mt.useState)(null),a=(0,mt.useCallback)(async u=>{o(!0),i(null);try{await e(u)}catch(c){let h=(0,To.toChainSwitchError)(c);throw i(h),h}finally{o(!1)}},[e]),g=(0,mt.useCallback)(()=>{i(null)},[]);return{switchChain:a,isSwitching:r,currentChainId:t,error:n,clearError:g}}var ft=require("@naculus/connect-appkit-core"),Y=require("react");var gt=require("viem");function Io(e){let{evmAccount:t,isConnected:r}=$(),{chainId:o,chains:n}=P(),[i,a]=(0,Y.useState)([]),[g,u]=(0,Y.useState)(!1),[c,h]=(0,Y.useState)(null),{tokens:s,refreshInterval:l}=e,d=(0,Y.useRef)(null),f=(0,Y.useMemo)(()=>s.map(A=>A.address.toLowerCase()+"|"+A.decimals+"|"+A.symbol).join(","),[s]),m=(0,Y.useMemo)(()=>(0,ft.resolveChain)(n,o),[o,n]),y=m?(0,ft.chainNumber)(m):null,C=(0,Y.useMemo)(()=>m?(0,ft.toViemChain)(m,y):null,[m,y]),[S,E]=(0,Y.useState)(null);(0,Y.useEffect)(()=>{if(!C||!m?.rpcUrl){E(null);return}let A=(0,gt.createPublicClient)({transport:(0,gt.http)(m.rpcUrl),chain:C});E(A)},[m,C]);let T=[{name:"balanceOf",type:"function",stateMutability:"view",inputs:[{name:"owner",type:"address"}],outputs:[{name:"balance",type:"uint256"}]}],v=(0,Y.useCallback)(async()=>{if(!t||!S||s.length===0){a([]);return}u(!0),h(null);try{let A=t.includes(":")?t.split(":").pop():t,k=(await Promise.allSettled(s.map(async R=>{try{let b=await S.readContract({address:R.address,abi:T,functionName:"balanceOf",args:[A]});return{address:R.address,symbol:R.symbol,decimals:R.decimals,name:R.name,balance:b.toString(),formatted:(0,gt.formatUnits)(b,R.decimals)}}catch{return{address:R.address,symbol:R.symbol,decimals:R.decimals,name:R.name,balance:null,formatted:null}}}))).map(R=>R.status==="fulfilled"?R.value:{address:"",symbol:"?",decimals:0,balance:null,formatted:null});a(k)}catch(A){h(A instanceof Error?A:new Error("Failed to fetch token balances"))}finally{u(!1)}},[t,S,f]);(0,Y.useEffect)(()=>{r&&t&&s.length>0&&v()},[r,t,f,v]),(0,Y.useEffect)(()=>(l&&l>0&&r&&t&&s.length>0&&(d.current=setInterval(v,l)),()=>{d.current&&(clearInterval(d.current),d.current=null)}),[l,r,t,f,v]);let I=(0,Y.useCallback)(A=>i.find(U=>U.address.toLowerCase()===A.toLowerCase()),[i]);return{tokenBalances:i,isLoading:g,error:c,refetch:v,getTokenBalance:I,chain:m}}var be=require("react");function Uo(e,t,r){let o=vt(),n=r??o,[i,a]=(0,be.useState)([]),[g,u]=(0,be.useState)(!1),[c,h]=(0,be.useState)(null),s=(0,be.useRef)(0),l=(0,be.useCallback)(async()=>{if(n){u(!0),h(null),s.current++;try{let f=await n.getTxHistory(e,t);a(f)}catch(f){h(f instanceof Error?f:new Error(String(f)))}finally{u(!1)}}},[n,e,t]);(0,be.useEffect)(()=>{l().catch(()=>{})},[l]),(0,be.useEffect)(()=>{if(!n)return;let f=()=>{l().catch(()=>{})};return n.on("statusChange",f),()=>{n.off("statusChange",f)}},[n,l]);let d={pending:i.filter(f=>f.status==="pending").length,confirmed:i.filter(f=>f.status==="confirmed").length,failed:i.filter(f=>f.status==="failed").length};return{entries:i,isLoading:g,error:c,refresh:l,summary:d}}var q=require("react"),Ae=class extends Error{constructor(t){super(t),this.name="InvalidUserOperationReceiptError"}};function Po(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function un(e){return typeof e=="string"&&/^0x[0-9a-fA-F]{40}$/.test(e)}function er(e){return typeof e=="string"&&/^0x[0-9a-fA-F]{64}$/.test(e)}function pa(e){return typeof e=="string"&&/^0x(?:[0-9a-fA-F]{2})*$/.test(e)}function tr(e,t){if(typeof e!="string"||!/^(?:0x(?:0|[1-9a-fA-F][0-9a-fA-F]*)|(?:0|[1-9][0-9]*))$/.test(e))throw new Ae(`Bundler returned an invalid ${t}.`);return BigInt(e)}function da(e,t){if(!Po(e))throw new Ae("Bundler returned an invalid UserOperation receipt.");if(!er(e.userOpHash)||e.userOpHash.toLowerCase()!==t.toLowerCase())throw new Ae("Bundler receipt does not match the requested UserOperation hash.");if(!un(e.entryPoint)||!un(e.sender))throw new Ae("Bundler receipt contains an invalid account address.");if(e.paymaster!==void 0&&e.paymaster!==null&&!un(e.paymaster))throw new Ae("Bundler receipt contains an invalid paymaster address.");if(typeof e.success!="boolean"||!er(e.transactionHash))throw new Ae("Bundler receipt contains an invalid execution result.");if(!Array.isArray(e.logs))throw new Ae("Bundler receipt contains invalid logs.");let r=e.logs.map(o=>{if(!Po(o)||!un(o.address)||!Array.isArray(o.topics)||!o.topics.every(er)||!pa(o.data))throw new Ae("Bundler receipt contains an invalid log entry.");return{address:o.address,topics:o.topics,data:o.data}});return{userOpHash:e.userOpHash,entryPoint:e.entryPoint,sender:e.sender,nonce:tr(e.nonce,"nonce"),...e.paymaster===void 0||e.paymaster===null?{}:{paymaster:e.paymaster},actualGasUsed:tr(e.actualGasUsed,"actualGasUsed"),actualGasCost:tr(e.actualGasCost,"actualGasCost"),success:e.success,transactionHash:e.transactionHash,logs:r}}function Wo(e){let t=e?.bundlerUrl,r=e?.pollInterval??2e3,o=e?.maxRetries??30,[n,i]=(0,q.useState)("idle"),[a,g]=(0,q.useState)(null),[u,c]=(0,q.useState)(e?.userOpHash??null),[h,s]=(0,q.useState)(null),[l,d]=(0,q.useState)(!1),[f,m]=(0,q.useState)(0),y=(0,q.useRef)(0),[C,S]=(0,q.useState)(0),E=(0,q.useRef)(null),T=(0,q.useRef)(null),v=(0,q.useRef)(0),I=(0,q.useRef)(0),A=(0,q.useRef)(null),U=(0,q.useCallback)(()=>{E.current&&(clearInterval(E.current),E.current=null),T.current&&(clearTimeout(T.current),T.current=null)},[]),k=(0,q.useCallback)(async(_,p)=>{if(!t||p!==v.current)return;let w=I.current+1;I.current=w,m(w);let x=new AbortController;A.current=x;let W=M=>{p===v.current&&(i("not_found"),d(!1),U(),s(M))},N=M=>{if(p===v.current){if(w<=o){T.current=setTimeout(()=>{k(_,p)},r);return}W(M)}};try{let M=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getUserOperationReceipt",params:[_]}),signal:x.signal});if(p!==v.current)return;if(!M.ok)throw new Error(`Bundler returned HTTP ${M.status} while reading UserOperation status.`);let Q=await M.json();if(p!==v.current)return;if(Q.error)throw new Error(typeof Q.error.message=="string"?Q.error.message:"Bundler returned a JSON-RPC error.");if(Q.result!==void 0&&Q.result!==null){let Qe=da(Q.result,_);g(Qe),i(Qe.success?"confirmed":"failed"),d(!1),U();return}i("pending"),N(new Error("UserOperation not included after maximum retries"))}catch(M){if(p!==v.current||x.signal.aborted)return;let Q=M instanceof Error?M:new Error("Unknown bundler response failure");if(Q instanceof Ae){W(Q);return}N(new Error(`UserOperation status unavailable after ${w} attempt${w===1?"":"s"}: ${Q.message}`))}finally{A.current===x&&(A.current=null)}},[t,r,o,U]),R=(0,q.useCallback)(_=>{v.current+=1;let p=v.current;if(A.current?.abort(),A.current=null,U(),c(_),g(null),s(null),I.current=0,m(0),S(0),y.current=Date.now(),!t){i("not_found"),d(!1),s(new Error("Bundler URL not configured"));return}i("pending"),d(!0),E.current=setInterval(()=>{S(Date.now()-y.current)},1e3),k(_,p)},[t,U,k]),b=(0,q.useCallback)(()=>{v.current+=1,A.current?.abort(),A.current=null,U(),d(!1)},[U]),O=(0,q.useCallback)(()=>{v.current+=1,A.current?.abort(),A.current=null,U(),c(null),i("idle"),g(null),s(null),d(!1),I.current=0,m(0),S(0)},[U]);return(0,q.useEffect)(()=>{e?.userOpHash&&e?.autoStart!==!1&&R(e.userOpHash)},[]),(0,q.useEffect)(()=>()=>{v.current+=1,A.current?.abort(),A.current=null,U()},[U]),{status:n,receipt:a,userOpHash:u,error:h,isPolling:l,elapsedMs:C,attempts:f,start:R,stop:b,reset:O}}var Do=require("react");var ma={"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."},fa={"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"},_o={en:ma,zh:fa},nr="en";function Oo(e){nr=e}function No(){return nr}function ze(e){return _o[nr][e]??_o.en[e]??e}var Mo="0x0000000000000000000000000000000000000000",ga=new Set([Mo,"0x0000000000000000000000000000000000000001","0x000000000000000000000000000000000000dead","0x000000000000000000000000000000000000dEaD"]);function ha(e){let t=e.toLowerCase();return ga.has(t)?!0:t.includes("dead")&&t.length>=40}function Ca(e){return e===Mo}function ya(e){return/^0x[0-9a-fA-F]{40}$/.test(e)}function rr(e){return e?ya(e)?Ca(e)?{isValid:!1,level:"blocked",warning:ze("address.zero_address")}:ha(e)?{isValid:!1,level:"blocked",warning:ze("address.burn_address")}:{isValid:!0,level:"ok",warning:null}:{isValid:!1,level:"blocked",warning:ze("address.invalid_format")}:{isValid:!1,level:"blocked",warning:ze("address.empty")}}function Lo({address:e}){return{validation:(0,Do.useMemo)(()=>rr(e),[e])}}function Bo(){let{status:e,session:t,accounts:r,chainId:o,error:n,connect:i,disconnect:a,reconnect:g,switchChain:u}=P(),c=e==="connected",h=e==="connecting",s=e==="reconnecting",l=r[0]??null;return{status:e,session:t,accounts:r,chainId:o,error:n,isConnected:c,isConnecting:h,isReconnecting:s,isDisconnected:e==="disconnected",currentAccount:l,connect:i,disconnect:a,reconnect:g,switchChain:u}}var je=require("react");var or={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"},sr={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."},It="Something went wrong",Ut="An unexpected error occurred. Please try again. If the problem persists, check your connection and wallet configuration.";function ht(e){if(!e)return{title:It,description:Ut};let t=e;if(t.name==="WalletError"&&t.code){let r=t.code,o=or[r]??It,n=sr[r]??t.message??Ut;return{title:o,description:n,code:r}}if(e instanceof Error){let r=e.message;return/user rejected/i.test(r)||/rejected/.test(r)?{title:"Request Rejected",description:"The request was declined.",code:"user_rejected"}:/timeout/i.test(r)||/timed? ?out/i.test(r)?{title:"Request Timed Out",description:"The request took too long. Please try again.",code:"deeplink_timeout"}:/insufficient funds/i.test(r)?{title:"Insufficient Funds",description:"You don't have enough funds to complete this transaction.",code:"tx_failed"}:/network/i.test(r)||/chain/i.test(r)?{title:"Network Error",description:r,code:"chain_unsupported"}:{title:It,description:r||Ut}}return typeof e=="string"?{title:It,description:e||Ut}:{title:It,description:Ut}}function pn(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 Ho(){let{error:e,clearError:t}=P(),r=(0,je.useMemo)(()=>e?ht(e):null,[e]),o=(0,je.useMemo)(()=>e?pn(e):!1,[e]),n=(0,je.useCallback)(()=>{t()},[t]),i=(0,je.useCallback)(g=>ht(g),[]),a=(0,je.useCallback)(g=>async()=>{try{return await g()}catch(u){let c=ht(u);if(u instanceof Error){let h=u;try{h.title=c.title,h.friendlyMessage=c.description,h.code===void 0&&c.code!==void 0&&(h.code=c.code)}catch{}throw h}throw Object.assign(new Error(c.description,{cause:u}),{title:c.title,code:c.code,friendlyMessage:c.description})}},[]);return{error:e,friendlyError:r,clearError:n,isRetryable:o,formatError:i,wrapAsync:a}}var we=require("react"),Fo=require("@naculus/connect-core"),ar=require("@naculus/connect-appkit-core");function Pt(e,t){let r=(0,we.useRef)(null),[o,n]=(0,we.useState)([]),[i,a]=(0,we.useState)(t?.autoLoad!==!1),[g,u]=(0,we.useState)(!1),[c,h]=(0,we.useState)(null);if(!r.current){let d={};t?.sources&&(d.sources=t.sources),r.current=new Fo.TokenListManager(d)}let s=(0,we.useCallback)(async()=>{let d=r.current;if(d){a(!0),h(null);try{await d.load();let f=e?(0,ar.eip155ChainIdToNumber)(e):void 0,m=d.getTokens(f!==void 0?{chainId:f}:void 0);n(m),u(!0)}catch(f){h(f instanceof Error?f:new Error(String(f)))}finally{a(!1)}}},[e]),l=(0,we.useCallback)(async()=>{let d=r.current;if(d){a(!0),h(null);try{await d.refresh();let f=e?(0,ar.eip155ChainIdToNumber)(e):void 0,m=d.getTokens(f!==void 0?{chainId:f}:void 0);n(m),u(!0)}catch(f){h(f instanceof Error?f:new Error(String(f)))}finally{a(!1)}}},[e]);return(0,we.useEffect)(()=>{t?.autoLoad!==!1&&s()},[s,t?.autoLoad]),{tokens:o,isLoading:i,isLoaded:g,error:c,refetch:l}}var Ge=require("react"),$o=require("@naculus/connect-core");var We=require("@naculus/connect-core");function Ko(){return[{name:"built-in",tokens:[...We.ETHEREUM_MAINNET_TOKENS,...We.POLYGON_TOKENS,...We.OPTIMISM_TOKENS,...We.ARBITRUM_TOKENS,...We.BASE_TOKENS],enabled:!0},{name:"uniswap-default",url:"https://tokens.uniswap.org",enabled:!0,refreshInterval:1440*60*1e3}]}var qo=require("@naculus/connect-appkit-core"),wa=300,dn=null;function Sa(){return dn||(dn=new $o.TokenListManager({sources:Ko()}),dn.load().catch(()=>{})),dn}function Wt(e,t){let[r,o]=(0,Ge.useState)({exact:[],fuzzy:[],hasMore:!1}),[n,i]=(0,Ge.useState)(!1),a=(0,Ge.useRef)(null),g=e.trim();return(0,Ge.useEffect)(()=>{if(!g){o({exact:[],fuzzy:[],hasMore:!1}),i(!1);return}return a.current&&clearTimeout(a.current),i(!0),a.current=setTimeout(()=>{let u=Sa(),c=t?(0,qo.eip155ChainIdToNumber)(t):void 0,h=u.search(g,{chainId:c,limit:20});o(h),i(!1)},wa),()=>{a.current&&clearTimeout(a.current)}},[g,t]),{results:r,isSearching:n}}var Ct=Me(require("react"),1);var F=require("react/jsx-runtime");function ir({chainId:e,onSelect:t,onClose:r,options:o}){let[n,i]=Ct.default.useState(""),{tokens:a,isLoading:g,error:u}=Pt(e),{results:c,isSearching:h}=Wt(n,n?e:void 0),s=o?.showRecommendations??!0,l=Ct.default.useMemo(()=>{if(n.trim()){let y=[...c.exact,...c.fuzzy].map(C=>C.token);return o?.filter?y.filter(o.filter):y}let m=a;return o?.filter?m.filter(o.filter):m},[n,c,a,o?.filter]),d=Ct.default.useMemo(()=>!s||n.trim()?[]:a.slice(0,6),[a,s,n]),f=(0,Ct.useCallback)(m=>{t(m),r()},[t,r]);return(0,F.jsxs)("div",{style:{background:"hsl(var(--background))",borderRadius:"12px",padding:"16px",color:"hsl(var(--foreground))",minWidth:"320px",maxWidth:"400px",fontFamily:"system-ui, sans-serif"},children:[(0,F.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"12px"},children:[(0,F.jsx)("h3",{style:{margin:0,fontSize:"16px",fontWeight:600},children:"Select Token"}),(0,F.jsx)("button",{onClick:r,style:{background:"none",border:"none",color:"hsl(var(--muted-foreground))",cursor:"pointer",fontSize:"18px",padding:"4px 8px"},children:"\u2715"})]}),(0,F.jsx)("input",{type:"text",placeholder:"Search token name or paste address",value:n,onChange:m=>i(m.target.value),style:{width:"100%",padding:"10px 12px",borderRadius:"8px",border:"1px solid #333",background:"hsl(var(--card))",color:"hsl(var(--foreground))",fontSize:"14px",outline:"none",boxSizing:"border-box",marginBottom:"12px"},autoFocus:!0}),g&&!h&&(0,F.jsx)("div",{style:{textAlign:"center",padding:"20px",color:"hsl(var(--muted-foreground))"},children:"Loading tokens..."}),u&&(0,F.jsxs)("div",{style:{textAlign:"center",padding:"12px",color:"hsl(var(--destructive))",fontSize:"13px"},children:["Error: ",u.message]}),s&&d.length>0&&!n.trim()&&(0,F.jsxs)("div",{style:{marginBottom:"12px"},children:[(0,F.jsx)("div",{style:{fontSize:"11px",color:"hsl(var(--muted-foreground))",textTransform:"uppercase",letterSpacing:"0.5px",marginBottom:"8px"},children:"Popular"}),(0,F.jsx)("div",{style:{display:"flex",gap:"6px",flexWrap:"wrap"},children:d.map(m=>(0,F.jsxs)("button",{onClick:()=>f(m),style:{background:"hsl(var(--card))",border:"1px solid #333",borderRadius:"20px",padding:"6px 14px",color:"hsl(var(--foreground))",cursor:"pointer",fontSize:"13px",display:"flex",alignItems:"center",gap:"4px"},children:[m.logoURI?(0,F.jsx)("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&&(0,F.jsx)("div",{style:{fontSize:"11px",color:"hsl(var(--muted-foreground))",marginBottom:"8px"},children:l.length>0?(0,F.jsxs)(F.Fragment,{children:[c.exact.length," exact, ",c.fuzzy.length," fuzzy",c.hasMore?" (more available)":""]}):"No results found"}),(0,F.jsx)("div",{style:{maxHeight:"320px",overflowY:"auto",display:"flex",flexDirection:"column",gap:"2px"},children:l.map(m=>(0,F.jsxs)("button",{onClick:()=>f(m),style:{display:"flex",alignItems:"center",gap:"10px",padding:"10px 8px",background:"transparent",border:"none",borderRadius:"8px",color:"hsl(var(--foreground))",cursor:"pointer",textAlign:"left",width:"100%",fontSize:"14px"},onMouseEnter:y=>{y.target.style.background="hsl(var(--card))"},onMouseLeave:y=>{y.target.style.background="transparent"},children:[(0,F.jsx)("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?(0,F.jsx)("img",{src:m.logoURI,alt:m.symbol,style:{width:"100%",height:"100%"},onError:y=>{let C=y.target;C.style.display="none",C.parentElement.textContent=m.symbol.slice(0,2)}}):m.symbol.slice(0,2)}),(0,F.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,F.jsx)("div",{style:{fontWeight:600,fontSize:"14px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m.symbol}),(0,F.jsx)("div",{style:{fontSize:"12px",color:"hsl(var(--muted-foreground))",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m.name})]}),(0,F.jsxs)("div",{style:{fontSize:"11px",color:"#666",textAlign:"right",flexShrink:0},children:[(0,F.jsxs)("div",{children:[m.decimals," decimals"]}),(0,F.jsxs)("div",{children:["Chain ",m.chainId]})]})]},`${m.chainId}:${m.address}`))})]})}var B=require("@stencil/react-output-target/runtime"),H=Me(require("react"),1),mn=require("@naculus/connect-appkit-wc/dist/components/appkit-accordion.js"),fn=require("@naculus/connect-appkit-wc/dist/components/appkit-account-button.js"),gn=require("@naculus/connect-appkit-wc/dist/components/appkit-alert-dialog.js"),hn=require("@naculus/connect-appkit-wc/dist/components/appkit-avatar.js"),Cn=require("@naculus/connect-appkit-wc/dist/components/appkit-badge.js"),yn=require("@naculus/connect-appkit-wc/dist/components/appkit-button.js"),wn=require("@naculus/connect-appkit-wc/dist/components/appkit-card-content.js"),Sn=require("@naculus/connect-appkit-wc/dist/components/appkit-card-description.js"),En=require("@naculus/connect-appkit-wc/dist/components/appkit-card-footer.js"),kn=require("@naculus/connect-appkit-wc/dist/components/appkit-card-header.js"),xn=require("@naculus/connect-appkit-wc/dist/components/appkit-card-title.js"),vn=require("@naculus/connect-appkit-wc/dist/components/appkit-card.js"),bn=require("@naculus/connect-appkit-wc/dist/components/appkit-checkbox.js"),An=require("@naculus/connect-appkit-wc/dist/components/appkit-collapsible.js"),Tn=require("@naculus/connect-appkit-wc/dist/components/appkit-connect-button.js"),Rn=require("@naculus/connect-appkit-wc/dist/components/appkit-dialog.js"),In=require("@naculus/connect-appkit-wc/dist/components/appkit-dropdown-menu.js"),Un=require("@naculus/connect-appkit-wc/dist/components/appkit-input.js"),Pn=require("@naculus/connect-appkit-wc/dist/components/appkit-popover.js"),Wn=require("@naculus/connect-appkit-wc/dist/components/appkit-progress.js"),_n=require("@naculus/connect-appkit-wc/dist/components/appkit-scroll-area.js"),On=require("@naculus/connect-appkit-wc/dist/components/appkit-select.js"),Nn=require("@naculus/connect-appkit-wc/dist/components/appkit-separator.js"),Dn=require("@naculus/connect-appkit-wc/dist/components/appkit-skeleton.js"),Mn=require("@naculus/connect-appkit-wc/dist/components/appkit-switch.js"),Ln=require("@naculus/connect-appkit-wc/dist/components/appkit-tabs.js"),Bn=require("@naculus/connect-appkit-wc/dist/components/appkit-toggle-group.js"),Hn=require("@naculus/connect-appkit-wc/dist/components/appkit-tooltip.js"),Vo=(0,B.createComponent)({tagName:"appkit-accordion",elementClass:mn.AppkitAccordion,react:H.default,events:{onAppkitToggle:"appkitToggle"},defineCustomElement:mn.defineCustomElement}),zo=(0,B.createComponent)({tagName:"appkit-account-button",elementClass:fn.AppkitAccountButton,react:H.default,events:{},defineCustomElement:fn.defineCustomElement}),jo=(0,B.createComponent)({tagName:"appkit-alert-dialog",elementClass:gn.AppkitAlertDialog,react:H.default,events:{onAppkitClose:"appkitClose",onAppkitOpenChange:"appkitOpenChange"},defineCustomElement:gn.defineCustomElement}),Go=(0,B.createComponent)({tagName:"appkit-avatar",elementClass:hn.AppkitAvatar,react:H.default,events:{},defineCustomElement:hn.defineCustomElement}),Qo=(0,B.createComponent)({tagName:"appkit-badge",elementClass:Cn.AppkitBadge,react:H.default,events:{},defineCustomElement:Cn.defineCustomElement}),Xo=(0,B.createComponent)({tagName:"appkit-button",elementClass:yn.AppkitButton,react:H.default,events:{},defineCustomElement:yn.defineCustomElement}),Yo=(0,B.createComponent)({tagName:"appkit-card",elementClass:vn.AppkitCard,react:H.default,events:{},defineCustomElement:vn.defineCustomElement}),Jo=(0,B.createComponent)({tagName:"appkit-card-content",elementClass:wn.AppkitCardContent,react:H.default,events:{},defineCustomElement:wn.defineCustomElement}),Zo=(0,B.createComponent)({tagName:"appkit-card-description",elementClass:Sn.AppkitCardDescription,react:H.default,events:{},defineCustomElement:Sn.defineCustomElement}),es=(0,B.createComponent)({tagName:"appkit-card-footer",elementClass:En.AppkitCardFooter,react:H.default,events:{},defineCustomElement:En.defineCustomElement}),ts=(0,B.createComponent)({tagName:"appkit-card-header",elementClass:kn.AppkitCardHeader,react:H.default,events:{},defineCustomElement:kn.defineCustomElement}),ns=(0,B.createComponent)({tagName:"appkit-card-title",elementClass:xn.AppkitCardTitle,react:H.default,events:{},defineCustomElement:xn.defineCustomElement}),rs=(0,B.createComponent)({tagName:"appkit-checkbox",elementClass:bn.AppkitCheckbox,react:H.default,events:{onAppkitChange:"appkitChange"},defineCustomElement:bn.defineCustomElement}),os=(0,B.createComponent)({tagName:"appkit-collapsible",elementClass:An.AppkitCollapsible,react:H.default,events:{onAppkitToggle:"appkitToggle"},defineCustomElement:An.defineCustomElement}),ss=(0,B.createComponent)({tagName:"appkit-connect-button",elementClass:Tn.AppkitConnectButton,react:H.default,events:{onAppkitConnect:"appkitConnect",onAppkitDisconnect:"appkitDisconnect",onAppkitStartPairing:"appkitStartPairing",onAppkitRetry:"appkitRetry",onAppkitCancelPairing:"appkitCancelPairing",onAppkitMobileDeepLink:"appkitMobileDeepLink",onAppkitCopyAddress:"appkitCopyAddress"},defineCustomElement:Tn.defineCustomElement}),as=(0,B.createComponent)({tagName:"appkit-dialog",elementClass:Rn.AppkitDialog,react:H.default,events:{onAppkitClose:"appkitClose",onAppkitOpenChange:"appkitOpenChange"},defineCustomElement:Rn.defineCustomElement}),is=(0,B.createComponent)({tagName:"appkit-dropdown-menu",elementClass:In.AppkitDropdownMenu,react:H.default,events:{onAppkitSelect:"appkitSelect"},defineCustomElement:In.defineCustomElement}),ls=(0,B.createComponent)({tagName:"appkit-input",elementClass:Un.AppkitInput,react:H.default,events:{onAppkitChange:"appkitChange"},defineCustomElement:Un.defineCustomElement}),cs=(0,B.createComponent)({tagName:"appkit-popover",elementClass:Pn.AppkitPopover,react:H.default,events:{onAppkitOpenChange:"appkitOpenChange"},defineCustomElement:Pn.defineCustomElement}),us=(0,B.createComponent)({tagName:"appkit-progress",elementClass:Wn.AppkitProgress,react:H.default,events:{},defineCustomElement:Wn.defineCustomElement}),ps=(0,B.createComponent)({tagName:"appkit-scroll-area",elementClass:_n.AppkitScrollArea,react:H.default,events:{},defineCustomElement:_n.defineCustomElement}),ds=(0,B.createComponent)({tagName:"appkit-select",elementClass:On.AppkitSelect,react:H.default,events:{onAppkitChange:"appkitChange"},defineCustomElement:On.defineCustomElement}),ms=(0,B.createComponent)({tagName:"appkit-separator",elementClass:Nn.AppkitSeparator,react:H.default,events:{},defineCustomElement:Nn.defineCustomElement}),fs=(0,B.createComponent)({tagName:"appkit-skeleton",elementClass:Dn.AppkitSkeleton,react:H.default,events:{},defineCustomElement:Dn.defineCustomElement}),gs=(0,B.createComponent)({tagName:"appkit-switch",elementClass:Mn.AppkitSwitch,react:H.default,events:{onAppkitChange:"appkitChange"},defineCustomElement:Mn.defineCustomElement}),hs=(0,B.createComponent)({tagName:"appkit-tabs",elementClass:Ln.AppkitTabs,react:H.default,events:{onAppkitTabChange:"appkitTabChange"},defineCustomElement:Ln.defineCustomElement}),Cs=(0,B.createComponent)({tagName:"appkit-toggle-group",elementClass:Bn.AppkitToggleGroup,react:H.default,events:{onAppkitChange:"appkitChange"},defineCustomElement:Bn.defineCustomElement}),ys=(0,B.createComponent)({tagName:"appkit-tooltip",elementClass:Hn.AppkitTooltip,react:H.default,events:{},defineCustomElement:Hn.defineCustomElement});0&&(module.exports={AppkitAccordion,AppkitAccountButton,AppkitAlertDialog,AppkitAvatar,AppkitBadge,AppkitButton,AppkitCard,AppkitCardContent,AppkitCardDescription,AppkitCardFooter,AppkitCardHeader,AppkitCardTitle,AppkitCheckbox,AppkitCollapsible,AppkitConnectButton,AppkitDialog,AppkitDropdownMenu,AppkitInput,AppkitPopover,AppkitProgress,AppkitScrollArea,AppkitSelect,AppkitSeparator,AppkitSkeleton,AppkitSwitch,AppkitTabs,AppkitToggleGroup,AppkitTooltip,DEFAULT_EVM_CHAINS,LAMPORTS_PER_SOL,PassphraseCancelledError,PassphraseGate,SolanaRpcError,TokenSelector,TxMonitorContext,WALLET_ERROR_DESCRIPTIONS,WALLET_ERROR_TITLES,Web3ConnectProvider,Web3Context,buildDelegationPolicyMessage,clearClient,createClient,formatSol,getChainById,getClient,getDefaultChains,getLatestBlockhash,getLocale,getSignatureStatus,getSolanaBalance,getUserFriendlyError,isRetryableError,parseSol,resetSessionKeyManager,setLocale,t,useAccount,useBalance,useCapabilities,useChain,useCompareCosts,useConnect,useCreateSessionKey,useDelegation,useDelegationPolicy,useDisconnect,useERC20Allowance,useERC20Approve,useERC20Transfer,useERC20TransferSimulation,useEmbeddedWallet,useExecuteCalls,useExecuteRoute,useLastTx,useLookupAddress,useNotification,usePassphraseGate,useResolveName,useRevokeSession,useRouteQuote,useSIWxLogin,useSIWxSession,useSendCalls,useSendTransaction,useSendUserOperation,useSendWithSession,useSession,useSessionKeys,useSignInWithEthereum,useSignInWithX,useSignMessage,useSimulateTransfer,useSiwxAuthSession,useSmartAccount,useSolanaAccount,useSolanaBalance,useSolanaTransaction,useSwitchChain,useTokenBalance,useTokenList,useTokenSearch,useTransactionSimulation,useTxHistory,useTxMonitor,useUserOpStatus,useValidateDestination,useViemClient,useWallet,useWeb3,useWeb3ErrorHandler,validateDestination});
|
|
1
|
+
"use strict";var vs=Object.create;var Nt=Object.defineProperty;var bs=Object.getOwnPropertyDescriptor;var As=Object.getOwnPropertyNames;var Rs=Object.getPrototypeOf,Ts=Object.prototype.hasOwnProperty;var Is=(e,t)=>{for(var r in t)Nt(e,r,{get:t[r],enumerable:!0})},lr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of As(t))!Ts.call(e,n)&&n!==r&&Nt(e,n,{get:()=>t[n],enumerable:!(o=bs(t,n))||o.enumerable});return e};var Me=(e,t,r)=>(r=e!=null?vs(Rs(e)):{},lr(t||!e||!e.__esModule?Nt(r,"default",{value:e,enumerable:!0}):r,e)),Us=e=>lr(Nt({},"__esModule",{value:!0}),e);var va={};Is(va,{AppkitAccordion:()=>Go,AppkitAccountButton:()=>Qo,AppkitAlertDialog:()=>Xo,AppkitAvatar:()=>Yo,AppkitBadge:()=>Jo,AppkitButton:()=>Zo,AppkitCard:()=>es,AppkitCardContent:()=>ts,AppkitCardDescription:()=>ns,AppkitCardFooter:()=>rs,AppkitCardHeader:()=>os,AppkitCardTitle:()=>ss,AppkitCheckbox:()=>as,AppkitCollapsible:()=>is,AppkitConnectButton:()=>ls,AppkitDialog:()=>cs,AppkitDropdownMenu:()=>us,AppkitInput:()=>ps,AppkitPopover:()=>ds,AppkitProgress:()=>ms,AppkitScrollArea:()=>fs,AppkitSelect:()=>gs,AppkitSeparator:()=>hs,AppkitSkeleton:()=>ys,AppkitSwitch:()=>Cs,AppkitTabs:()=>Ss,AppkitToggleGroup:()=>ws,AppkitTooltip:()=>Es,DEFAULT_EVM_CHAINS:()=>Vn,LAMPORTS_PER_SOL:()=>J.LAMPORTS_PER_SOL,PassphraseCancelledError:()=>J.PassphraseCancelledError,PassphraseGate:()=>J.PassphraseGate,SolanaRpcError:()=>J.SolanaRpcError,TokenSelector:()=>ir,TxMonitorContext:()=>jn,WALLET_ERROR_DESCRIPTIONS:()=>sr,WALLET_ERROR_TITLES:()=>or,Web3ConnectProvider:()=>yr,Web3Context:()=>Ht,buildDelegationPolicyMessage:()=>st,clearClient:()=>dr,createClient:()=>Dt,formatSol:()=>J.formatSol,getChainById:()=>hr,getClient:()=>Mt,getDefaultChains:()=>Bt,getLatestBlockhash:()=>J.getLatestBlockhash,getLocale:()=>Lo,getSignatureStatus:()=>J.getSignatureStatus,getSolanaBalance:()=>J.getSolanaBalance,getUserFriendlyError:()=>yt,isRetryableError:()=>pn,parseSol:()=>J.parseSol,resetSessionKeyManager:()=>Tr,setLocale:()=>Mo,t:()=>ze,useAccount:()=>$,useBalance:()=>Er,useCapabilities:()=>Ft,useChain:()=>ie,useCompareCosts:()=>Fn,useConnect:()=>xr,useCreateSessionKey:()=>br,useDelegation:()=>rt,useDelegationPolicy:()=>Ur,useDisconnect:()=>Pr,useERC20Allowance:()=>Dr,useERC20Approve:()=>Br,useERC20Transfer:()=>Kr,useERC20TransferSimulation:()=>Gr,useEmbeddedWallet:()=>Wr,useExecuteCalls:()=>Gt,useExecuteRoute:()=>Kn,useLastTx:()=>Xr,useLookupAddress:()=>Zr,useNotification:()=>oo,usePassphraseGate:()=>ao,useResolveName:()=>lo,useRevokeSession:()=>Ar,useRouteQuote:()=>$n,useSIWxLogin:()=>on,useSIWxSession:()=>fo,useSendCalls:()=>zt,useSendTransaction:()=>lt,useSendUserOperation:()=>uo,useSendWithSession:()=>Rr,useSession:()=>po,useSessionKeys:()=>Qt,useSignInWithEthereum:()=>go,useSignInWithX:()=>mt,useSignMessage:()=>Yt,useSimulateTransfer:()=>Co,useSiwxAuthSession:()=>So,useSmartAccount:()=>Eo,useSolanaAccount:()=>cn,useSolanaBalance:()=>vo,useSolanaRoles:()=>Ro,useSolanaTransaction:()=>Io,useSwitchChain:()=>Po,useTokenBalance:()=>Wo,useTokenList:()=>Wt,useTokenSearch:()=>_t,useTransactionSimulation:()=>tn,useTxHistory:()=>_o,useTxMonitor:()=>Qr,useUserOpStatus:()=>No,useValidateDestination:()=>Fo,useViemClient:()=>fe,useWallet:()=>Ko,useWeb3:()=>P,useWeb3ErrorHandler:()=>$o,validateDestination:()=>rr});module.exports=Us(va);var J=require("@naculus/connect-core");var ue=require("react");function Ps(e){return e?Object.keys(e).sort().map(t=>{let r=e[t];return`${t}=${typeof r=="object"&&r!==null?"[object]":String(r)}`}).join("&"):""}function Fn(e,t){let{operation:r,chains:o,options:n}=e,[i,a]=(0,ue.useState)([]),[g,u]=(0,ue.useState)(!1),[c,h]=(0,ue.useState)(null),s=(0,ue.useRef)(!0),l=(0,ue.useRef)(0),d=`${r}|${(o??[]).join(",")}|${Ps(n)}`,f=(0,ue.useCallback)(async()=>{if(!o||o.length===0){a([]);return}if(!t)return;let C=++l.current;u(!0),h(null);try{let y=await t(r,o,n);s.current&&C===l.current&&a(y)}catch(y){s.current&&C===l.current&&(h(y instanceof Error?y:new Error(String(y))),a([]))}finally{s.current&&C===l.current&&u(!1)}},[d,t]);(0,ue.useEffect)(()=>{f()},[f]),(0,ue.useEffect)(()=>(s.current=!0,()=>{s.current=!1}),[]);let m=(0,ue.useCallback)(async()=>{await f()},[f]);return{comparisons:i,loading:g,error:c,refresh:m}}var cr=require("@naculus/connect-core"),me=require("react");function Kn(e){let[t,r]=(0,me.useState)(!1),[o,n]=(0,me.useState)(null),[i,a]=(0,me.useState)(null),g=(0,me.useRef)(!0),u=(0,me.useRef)(!1);(0,me.useEffect)(()=>(g.current=!0,()=>{g.current=!1}),[]);let c=(0,me.useCallback)(async(s,l,d)=>{if(!e)return a({code:"no_executor",message:"No executeRoute function provided"}),n(null),null;if(typeof l!="string"||l.trim()==="")return a({code:"invalid_recipient",message:"A recipient address is required"}),n(null),null;let f=s?.toChain?.split(":")[0];if(f&&!(0,cr.isValidAddress)(l,f))return a({code:"invalid_recipient",message:`"${l}" is not a valid ${f} address for the destination chain ${s.toChain}`}),n(null),null;if(u.current)return a({code:"execution_in_progress",message:"A route execution is already in progress"}),null;u.current=!0,r(!0),a(null),n(null);try{let m=await e(s,l,d);return g.current&&n(m),m}catch(m){let C=m;return g.current&&a({code:C.code??"execution_failed",message:C.message,details:C.details}),null}finally{u.current=!1,g.current&&r(!1)}},[e]),h=(0,me.useCallback)(()=>{n(null),a(null),r(!1)},[]);return{execute:c,executing:t,result:o,error:i,reset:h}}var ae=require("react");function $n(e,t){let{fromChain:r,toChain:o,fromToken:n,toToken:i,amount:a,options:g}=e,[u,c]=(0,ae.useState)([]),[h,s]=(0,ae.useState)(!1),[l,d]=(0,ae.useState)(null),f=(0,ae.useRef)(null),m=(0,ae.useRef)(!0),C=(0,ae.useCallback)(async()=>{let w=/^(?:0|[1-9][0-9]*)$/.test(a)&&BigInt(a)>0n;if(!r||!o||!n||!w){c([]);return}if(t){s(!0),d(null);try{let R=await t(r,o,n,a,g,i);m.current&&c(R)}catch(R){m.current&&(d(R instanceof Error?R:new Error(String(R))),c([]))}finally{m.current&&s(!1)}}},[r,o,n,i,a,g,t]);(0,ae.useEffect)(()=>{if(f.current&&clearTimeout(f.current),!r||!o||!n||!a){c([]);return}return f.current=setTimeout(()=>{C()},300),()=>{f.current&&clearTimeout(f.current)}},[C,r,o,n,a]),(0,ae.useEffect)(()=>(m.current=!0,()=>{m.current=!1}),[]);let y=(0,ae.useCallback)(async()=>{await C()},[C]),E=(0,ae.useCallback)(()=>{c([]),d(null),s(!1)},[]);return{quotes:u,loading:h,error:l,refresh:y,clear:E}}var X=require("@naculus/connect-core"),ne=require("@naculus/connector-evm-injected"),ur=require("@naculus/connect-core"),pr=require("@naculus/connector-walletconnect"),qn=null;function Dt(e){let t=null,r=(0,pr.createWalletConnectConnector)({projectId:e.projectId,metadata:e.metadata}),o=null,n=null,i=null,a=null,g=e.passphrasePrompt&&e.enableEmbedded&&!e.embeddedConfig?.encryptionPassphrase?new ur.PassphraseGate:null;e.enableEmbedded&&(n=import("@naculus/connector-embedded").then(s=>{let l={...e.embeddedConfig};g&&(l.encryptionPassphrase=g.request),e.enablePasskeys&&l.encryptionPassphrase&&!l.prfUnlock&&(l.prfUnlock={async derive(f){a&&await a;let m=i;return m?.hasCredential()?m.derivePrfKey(f):null}}),o=s.createPocketConnector(l),t?._setEmbeddedConnector(o)}).catch(s=>{X.logger.warn("react/client","Embedded wallet connector not available:",s),o=null})),e.enablePasskeys&&(a=import("@naculus/connector-passkeys").then(s=>{i=s.createPasskeysConnector(),t?._setPasskeysConnector(i)}).catch(s=>{X.logger.warn("react/client","Passkeys connector not available:",s),i=null}));let u=null,c=null;e.enableSolana&&(c=import("@naculus/connector-solana").then(s=>{let l=s.solanaConnector;e.solanaDefaultChain&&"configure"in l&&l.configure({defaultChain:e.solanaDefaultChain}),u=l,typeof window<"u"&&"startDiscovery"in l&&l.startDiscovery(),t?._setSolanaConnector(u)}).catch(s=>{X.logger.warn("react/client","Solana connector not available:",s),u=null})),typeof window<"u"&&ne.eip6963Connector.startDiscovery();let h={connector:r,get embeddedConnector(){return o},getEmbeddedConnector:async()=>(n&&await n,o),get passkeysConnector(){return i},passphraseGate:g,solanaRpcUrl:e.solanaRpcUrl??null,get solanaConnector(){return u},connect:()=>r.connect(),connectInjected:async s=>ne.eip6963Connector.connect(s),connectEmbedded:async()=>{if(n&&await n,!o)throw new Error("Embedded wallet not enabled. Set enableEmbedded: true in config.");return o.connect()},connectPasskeys:async()=>{if(a&&await a,!i)throw new Error("Passkeys connector not enabled. Set enablePasskeys: true in config.");return i.connect()},startPairing:()=>r.startPairing(),completePairing:()=>r.completePairing(),cancelPairing:()=>r.cancelPairing?.(),signMessage:async(s,l)=>{if(s.id?.startsWith("eip6963-"))return ne.eip6963Connector.signMessage(s,l);if(s.walletType==="passkeys"&&i)return i.signMessage(s,l);if(s.walletType==="embedded"){if(!o)throw new X.WalletError("wallet_unavailable","Embedded wallet connector not available.");return o.signMessage(s,l)}if(s.walletType==="solana"){if(c&&await c,u)return u.signMessage(s,l);throw new X.WalletError("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}return r.signMessage(s,l)},signTransaction:async(s,l)=>{if(s.id?.startsWith("eip6963-"))return ne.eip6963Connector.signTransaction(s,l);if(s.walletType==="embedded"){if(!o)throw new X.WalletError("wallet_unavailable","Embedded wallet connector not available.");return o.signTransaction(s,l)}if(s.walletType==="solana"){if(c&&await c,u)return u.signTransaction(s,l);throw new X.WalletError("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}return r.signTransaction(s,l)},sendTransaction:async(s,l)=>{if(s.id?.startsWith("eip6963-"))return ne.eip6963Connector.sendTransaction(s,l);if(s.walletType==="passkeys"&&i)return i.sendTransaction(s,l);if(s.walletType==="embedded"){if(!o)throw new X.WalletError("wallet_unavailable","Embedded wallet connector not available.");return o.sendTransaction(s,l)}if(s.walletType==="solana"){if(c&&await c,u)return u.sendTransaction(s,l);throw new X.WalletError("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}return r.sendTransaction(s,l)},onAccountsChanged:(s,l)=>{let d=()=>{};return s.id?.startsWith("eip6963-")?ne.eip6963Connector.onAccountsChanged?.(s,l)??d:s.walletType==="embedded"?o?.onAccountsChanged?.(s,l)??d:s.walletType==="passkeys"?d:s.walletType==="solana"?u?.onAccountsChanged?.(s,l)??d:r.onAccountsChanged?.(s,l)??d},onChainChanged:(s,l)=>{let d=()=>{};return s.id?.startsWith("eip6963-")?ne.eip6963Connector.onChainChanged?.(s,l)??d:s.walletType==="passkeys"||s.walletType==="embedded"?d:s.walletType==="solana"?u?.onChainChanged?.(s,l)??d:r.onChainChanged?.(s,l)??d},getCapabilities:s=>s.id?.startsWith("eip6963-")?ne.eip6963Connector.getCapabilities?.(s):s.walletType==="passkeys"?i?.getCapabilities?.(s):s.walletType==="solana"?u?.getCapabilities?.(s):s.walletType==="embedded"?o?.getCapabilities?.(s):r.getCapabilities?.(s),sendCalls:async(s,l,d,f)=>{if(s.id?.startsWith("eip6963-"))return ne.eip6963Connector.sendCalls(s,l,d,f);if(s.walletType==="passkeys"&&i)return i.sendCalls(s,l,d,f);if(s.walletType==="solana"){if(c&&await c,u)return u.sendCalls(s,l,d,f);throw new X.WalletError("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}if(s.walletType==="embedded"){if(!o?.sendCalls)throw new X.WalletError("method_not_allowed","Embedded wallet does not support sendCalls");return o.sendCalls(s,l,d,f)}if(!r.sendCalls)throw new X.WalletError("method_not_allowed","sendCalls not supported by this connector");return r.sendCalls(s,l,d,f)},showCallsStatus:async(s,l)=>{if(s.id?.startsWith("eip6963-"))return ne.eip6963Connector.showCallsStatus(s,l);if(s.walletType==="passkeys"||s.walletType==="embedded")throw new X.WalletError("method_unsupported",`${s.walletType} wallets have no UI to display a call bundle.`);if(!r.showCallsStatus)throw new X.WalletError("method_unsupported","This connector cannot display call status.");return r.showCallsStatus(s,l)},getCallsStatus:async(s,l)=>{if(s.id?.startsWith("eip6963-")&&ne.eip6963Connector.getCallsStatus)return ne.eip6963Connector.getCallsStatus(s,l);if(s.walletType==="passkeys"&&i?.getCallsStatus)return i.getCallsStatus(s,l);if(s.walletType==="embedded")throw new X.WalletError("method_not_allowed","Embedded wallet does not support getCallsStatus");if(!r.getCallsStatus)throw new X.WalletError("method_not_allowed","getCallsStatus not supported by this connector");return r.getCallsStatus(s,l)},reconnect:async s=>s.walletType==="eip6963"?ne.eip6963Connector.reconnect(s):s.walletType==="embedded"?o?o.reconnect(s):s:s.walletType==="solana"?s:r.reconnect(s),disconnect:async s=>{if(s.id?.startsWith("eip6963-")||s.walletType==="eip6963")return ne.eip6963Connector.disconnect(s);if(s.walletType==="embedded"&&o)return o.disconnect();if(s.walletType==="passkeys"&&i)return i.disconnect(s);if(s.walletType==="solana"){if(c&&await c,u)return u.disconnect(s);throw new X.WalletError("wallet_unavailable","Solana connector not available. Ensure enableSolana is true and @naculus/connector-solana is installed.")}return r.disconnect(s)},getAllConnectors:()=>{let s=[r];return o&&s.push(o),i&&s.push(i),u&&s.push(u),s},_setEmbeddedConnector:s=>{o=s},_setPasskeysConnector:s=>{i=s},_setSolanaConnector:s=>{u=s}};return t=h,qn=h,h}function Mt(){return qn}function dr(){qn=null}var wt=require("@naculus/connect-core"),Sr=require("react");var Z=require("@naculus/connect-core"),St=require("@naculus/connector-evm-injected"),D=require("react");var mr=require("@naculus/connect-core"),Lt=require("@naculus/siwx");function Ye(e,t){let r=t.split(":",1)[0],n=(e.namespaces[r]?.accounts??[]).filter(i=>i.startsWith(`${r}:`)).map(i=>({namespace:r,caip10:i}))[0];if(n)return{...n,address:n.caip10.split(":").pop()??n.caip10}}function Ws(e){return e.namespaces.eip155?.chains?.[0]??e.namespaces.solana?.chains?.[0]??e.namespaces.xrpl?.chains?.[0]??"eip155:1"}async function fr(e){let{session:t,siwx:r,signMessage:o}=e;if(!r||!t)return{kind:"skipped"};try{let n=Ws(t),i=Ye(t,n);if(!i)throw new Error("No account found in session");let{address:a}=i,g=await r.createMessage({address:a,chainId:n}),u=(0,Lt.parseSiwxMessage)(g);if(!u?.nonce)throw new Error("SIWx message must contain a nonce");await(0,Lt.issueNonce)(u.nonce);let c=await o(t,{message:g,address:a,chainId:n});return await r.handleSignComplete?.({message:g,signature:c}),{kind:"authenticated",address:a,chainId:n}}catch(n){let i=n instanceof Error?n:new Error("Wallet authentication failed");return mr.logger.error("appkit/core","SIWx authentication failed:",n),{kind:"failed",error:i,fatal:r.required!==!1}}}var _e=require("@naculus/connect-appkit-core");var gr=require("@naculus/connect-appkit-core"),we=require("@naculus/connect-core"),_s=[{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 Os(e){let t=we.CHAINS[e];if(!t||!t.explorerUrl)return null;let r=t.caip2Id;return{caip2:r,name:t.name,rpcUrl:(0,we.getRpcUrl)(r,we.DEFAULT_RPC_URLS[r]??""),explorerUrl:t.explorerUrl,token:t.nativeCurrency.symbol}}function Ns(){if(!we.CHAINS)return[];let e=[],t=Object.keys(we.CHAINS).map(Number).sort((r,o)=>r-o);for(let r of t){let o=Os(r);o&&e.push(o)}for(let r of _s){let o=(0,we.eip155Reference)(r.caip2);(o===null||!we.CHAINS[o])&&e.push(r)}return e}var Vn=Ns();function hr(e,t){return(0,gr.resolveChain)(e,t)??void 0}function Bt(){return[...Vn]}var Cr=require("react/jsx-runtime"),Ht=(0,D.createContext)(null);function yr({children:e,config:t,autoConnect:r=!0}){let[o,n]=(0,D.useReducer)(_e.web3Reducer,_e.initialWeb3State),i=(0,D.useMemo)(()=>t.chains??Bt(),[t.chains]),a=t.connectionTimeout??3e4,g=t.maxRetries??2,u=(0,D.useMemo)(()=>new Z.LocalStorageSessionStorage(t.storageKey??"naculus_web3_session",t.encryptionKey),[t.storageKey,t.encryptionKey]),c=(0,D.useMemo)(()=>Dt({projectId:t.projectId,metadata:t.metadata,enableEmbedded:t.enableEmbedded,embeddedConfig:t.embeddedConfig,enablePasskeys:t.enablePasskeys,enableSolana:t.enableSolana,solanaDefaultChain:t.solanaDefaultChain}),[t.projectId,t.metadata,t.enableEmbedded,t.embeddedConfig,t.enablePasskeys,t.enableSolana,t.solanaDefaultChain]),h=(0,D.useRef)(null),s=(0,D.useRef)(null),l=(0,D.useMemo)(()=>{let p=(0,Z.createConnectorManager)();for(let N of[St.eip6963Connector,...c.getAllConnectors()])p.register(N.id,N);let S={},x={};for(let N of i){let L=N.caip2;N.rpcUrl&&(S[L]=N.rpcUrl),N.token&&(x[L]={name:N.name,symbol:N.token,decimals:18})}let W=(0,Z.createSessionManager)(p,{autoRefreshFeeOnSwitch:t.autoRefreshFeeOnSwitch??!0,defaultRpcUrls:S,defaultCurrencies:x,encryptionKey:t.encryptionKey});return h.current=W,W},[c,i,t.autoRefreshFeeOnSwitch,t.encryptionKey]);(0,D.useEffect)(()=>{let p=W=>{let{walletSession:N}=W.bundle;n({type:"SET_SESSION",payload:N});let L=[];Object.values(N.namespaces).forEach(Q=>{L.push(...Q.accounts)}),n({type:"SET_ACCOUNTS",payload:L}),n({type:"SET_CHAIN",payload:W.bundle.activeChainId}),n({type:"SET_STATUS",payload:"connected"})},S=()=>{n({type:"RESET"})},x=W=>{n({type:"SET_CHAIN",payload:W.newChainId})};return l.on("sessionConnected",p),l.on("sessionDisconnected",S),l.on("chainChanged",x),()=>{l.off("sessionConnected",p),l.off("sessionDisconnected",S),l.off("chainChanged",x)}},[l]),(0,D.useEffect)(()=>{let p=()=>{u.clear(),n({type:"RESET"})};c.connector.onSessionExpiry(p)},[c,u]);let d=(0,D.useCallback)(()=>{for(let p of[St.eip6963Connector,...c.getAllConnectors()])l.registerConnector(p)},[c,l]),f=(0,D.useCallback)(async p=>{d();let S=[St.eip6963Connector,...c.getAllConnectors()].find(W=>W.id===p.walletType||W.kind===p.walletType);S&&!p.connectorId&&(p.connectorId=S.id);let x=p.namespaces.eip155?.chains?.[0]??p.namespaces.solana?.chains?.[0]??p.namespaces.xrpl?.chains?.[0];x&&await l.attach(p,x)},[c,l,d]),m=(0,D.useCallback)(p=>{if(n({type:"SET_SESSION",payload:p}),p){let S=[];Object.values(p.namespaces).forEach(L=>{S.push(...L.accounts)}),n({type:"SET_ACCOUNTS",payload:S});let x=p.namespaces.eip155?.chains?.[0],W=p.namespaces.solana?.chains?.[0],N=p.namespaces.xrpl?.chains?.[0];n({type:"SET_CHAIN",payload:x??W??N??null})}else n({type:"SET_ACCOUNTS",payload:[]}),n({type:"SET_CHAIN",payload:null})},[]);(0,D.useEffect)(()=>{let p=o.session,S=c;return!p||!S?.onAccountsChanged?void 0:S.onAccountsChanged(p,W=>{if(W.length===0){u.clear().finally(()=>n({type:"RESET"}));return}m(p),u.save(p)})},[o.session,c,u,m]),(0,D.useEffect)(()=>{let p=o.session,S=c;if(!(!p||!S?.onChainChanged))return S.onChainChanged(p,x=>{m(p),u.save(p);let W=l.syncExternalChain;if(!W)return;let N=W.call(l,x).catch(L=>{Z.logger.warn("react/provider","External chain sync error:",L)});s.current=N,N.finally(()=>{s.current===N&&(s.current=null)})})},[o.session,c,u,m,l]);let C=(0,D.useCallback)(async p=>{if(!t.siwx||!p)return!0;n({type:"SET_STATUS",payload:"authenticating"});let S=await fr({session:p,siwx:t.siwx,signMessage:(x,W)=>c.signMessage(x,W)});return S.kind==="failed"&&S.fatal?(await u.clear(),n({type:"RESET"}),n({type:"SET_ERROR",payload:S.error}),!1):!0},[t.siwx,c,u]),y=(0,D.useCallback)(async()=>{n({type:"SET_STATUS",payload:"connecting"}),n({type:"SET_ERROR",payload:null});try{let p=await(0,_e.withTimeout)(c.connect(),a,"Wallet connect");await u.save(p),m(p);try{await f(p)}catch(S){Z.logger.warn("react/provider","SessionManager sync error:",S)}if(!await C(p))return;n({type:"SET_STATUS",payload:"connected"})}catch(p){let S=p instanceof Error?p.message:"Connection failed";n({type:"SET_ERROR",payload:p instanceof Error?p:new Error(S)}),n({type:"SET_STATUS",payload:"disconnected"})}},[c,u,m,a,C,f]),E=(0,D.useCallback)(async()=>{n({type:"SET_STATUS",payload:"connecting"}),n({type:"SET_ERROR",payload:null});try{let p=await c.connectEmbedded();if(await u.save(p),m(p),await f(p),!await C(p))return;n({type:"SET_STATUS",payload:"connected"})}catch(p){let S=p instanceof Error?p.message:"Embedded wallet connection failed";n({type:"SET_ERROR",payload:p instanceof Error?p:new Error(S)}),n({type:"SET_STATUS",payload:"disconnected"})}},[c,u,m,C,f]),w=(0,D.useCallback)(async()=>{n({type:"SET_STATUS",payload:"connecting"}),n({type:"SET_ERROR",payload:null});try{let p=await c.connectPasskeys();if(await u.save(p),m(p),await f(p),!await C(p))return;n({type:"SET_STATUS",payload:"connected"})}catch(p){let S=p instanceof Error?p.message:"Passkeys connection failed";n({type:"SET_ERROR",payload:p instanceof Error?p:new Error(S)}),n({type:"SET_STATUS",payload:"disconnected"})}},[c,u,m,C,f]),R=(0,D.useCallback)(async()=>{if(!o.session){n({type:"RESET"});return}try{await c.disconnect(o.session)}catch(p){Z.logger.error("react/provider","Disconnect error:",p)}try{let p=h.current;p&&await p.disconnect()}catch(p){Z.logger.warn("react/provider","SessionManager disconnect error:",p)}await u.clear(),n({type:"RESET"})},[c,o.session,u]),v=(0,D.useCallback)(async p=>{n({type:"SET_STATUS",payload:"connecting"}),n({type:"SET_ERROR",payload:null});try{let S=await(0,_e.withTimeout)(c.connectInjected(p),a,"Injected wallet connect");await u.save(S),m(S);try{await f(S)}catch(x){Z.logger.warn("react/provider","SessionManager sync error:",x)}if(!await C(S))return;n({type:"SET_STATUS",payload:"connected"})}catch(S){let x=S instanceof Error?S.message:"Connection failed";n({type:"SET_ERROR",payload:S instanceof Error?S:new Error(x)}),n({type:"SET_STATUS",payload:"disconnected"})}},[c,u,m,a,C,f]),I=(0,D.useCallback)(async()=>c.startPairing(),[c]),A=(0,D.useCallback)(()=>{c.cancelPairing?.()},[c]),U=(0,D.useCallback)(async()=>{let p=await c.completePairing();return await u.save(p),m(p),await f(p),await C(p)&&n({type:"SET_STATUS",payload:"connected"}),p},[c,u,m,C,f]),k=(0,D.useCallback)(async p=>{let S=t.siwx;if(!S||S.required===!1)return!0;try{if(await S.hasValidSession?.())return!0}catch(x){Z.logger.warn("react/provider","siwx.hasValidSession failed",x)}return C(p)},[t.siwx,C]),T=(0,D.useCallback)(async()=>{let p=await u.load();if(!p){n({type:"SET_STATUS",payload:"disconnected"});return}n({type:"SET_STATUS",payload:"reconnecting"});try{let S=await(0,_e.withRetry)(()=>c.reconnect(p),{maxRetries:g,baseDelay:1e3,label:"reconnect"});m(S);try{let x=h.current;x&&(d(),await x.restoreFromPersistence())}catch(x){Z.logger.warn("react/provider","SessionManager restore error:",x)}if(!await k(S))return;n({type:"SET_STATUS",payload:"connected"})}catch(S){Z.logger.error("react/provider","Reconnect error:",S),await u.clear(),n({type:"SET_STATUS",payload:"disconnected"}),n({type:"SET_SESSION",payload:null})}},[c,u,m,g,d,k]),b=(0,D.useCallback)(async p=>{s.current&&await s.current;let S=h.current;if(S?.getActiveBundle()){await S.switchChain(p),m(o.session);return}if(!o.session)throw new Error("No active session");try{o.session.walletType==="eip6963"||o.session.id?.startsWith("eip6963-")?await St.eip6963Connector.switchChain(o.session,p):o.session.walletType==="embedded"&&c.embeddedConnector?await c.embeddedConnector.switchChain?.(o.session,p):o.session.walletType==="passkeys"&&c.passkeysConnector?await c.passkeysConnector.switchChain?.(o.session,p):o.session.walletType==="solana"&&c.solanaConnector?await c.solanaConnector.switchChain?.(o.session,p):await c.connector.switchChain(o.session,p),m(o.session)}catch(x){throw new Z.WalletError("chain_unsupported","Failed to switch chain",x)}},[c,o.session,m]);(0,D.useEffect)(()=>{r&&T()},[r,T]);let O=(0,D.useCallback)(()=>{n({type:"SET_ERROR",payload:null})},[]),_=(0,D.useMemo)(()=>({...o,connect:y,connectEmbedded:E,connectPasskeys:w,disconnect:R,reconnect:T,switchChain:b,startPairing:I,completePairing:U,cancelPairing:A,connectInjected:v,clearError:O,isConnected:o.status==="connected",chains:i,client:c,sessionManager:l}),[o,y,E,w,R,T,b,I,U,v,O,i,c,l]);return(0,Cr.jsx)(Ht.Provider,{value:_,children:e})}function P(){let e=(0,D.useContext)(Ht);if(!e)throw new Error("useWeb3 must be used within a Web3ConnectProvider");return e}function $(){let{accounts:e,isConnected:t}=P(),r=(0,Sr.useMemo)(()=>!t||e.length===0?null:e.map(n=>{let i=(0,wt.parseCaip10)(n);return i?{address:n,namespace:i.namespace,isEVM:i.namespace==="eip155"&&(0,wt.isEvmAddress)(i.address)}:{address:n,namespace:null,isEVM:(0,wt.isEvmAddress)(n)}}),[e,t]),o=r?.find(n=>n.isEVM)?.address??null;return{accounts:r,evmAccount:o,primaryAccount:e[0]??null,isConnected:t,count:e.length}}var Je=require("@naculus/connect-appkit-core"),j=require("react");var Ze=require("viem"),wr=require("@naculus/connect-core");function Er(e){let{evmAccount:t,isConnected:r}=$(),{chainId:o,chains:n}=P(),[i,a]=(0,j.useState)(null),[g,u]=(0,j.useState)(!1),[c,h]=(0,j.useState)(null),[s,l]=(0,j.useState)(null),d=e?.refreshInterval,f=(0,j.useRef)(null),m=(0,j.useMemo)(()=>(0,Je.resolveChain)(n,o),[o,n]),C=m?(0,Je.chainNumber)(m):null,y=(0,j.useMemo)(()=>m?(0,Je.toViemChain)(m,C):null,[m,C]),E=(0,j.useMemo)(()=>m?.token??null,[m]),[w,R]=(0,j.useState)(null);(0,j.useEffect)(()=>{if(!y||!m?.rpcUrl){R(null);return}let U=(0,Ze.createPublicClient)({transport:(0,Ze.http)(m.rpcUrl),chain:y});return R(U),()=>{}},[m]);let v=(0,j.useCallback)(async()=>{if(!t||!w){a(null);return}u(!0),h(null);try{let k=t.includes(":")?t.split(":").pop():t,[T,b]=await Promise.all([w.getBalance({address:k}),o?(0,wr.getNativeTokenPriceUsd)(o,m?.rpcUrl).catch(()=>null):Promise.resolve(null)]);a(T.toString()),l(b)}catch(U){h(U instanceof Error?U:new Error("Failed to fetch balance")),a(null),l(null)}finally{u(!1)}},[t,w,o,m?.rpcUrl]);(0,j.useEffect)(()=>{r&&t&&v()},[r,t,v]),(0,j.useEffect)(()=>(d&&d>0&&r&&t&&(f.current=setInterval(v,d)),()=>{f.current&&(clearInterval(f.current),f.current=null)}),[d,r,t,v]);let I=(0,j.useMemo)(()=>{if(i===null)return null;try{return(0,Ze.formatEther)(BigInt(i))}catch{return null}},[i]),A=(0,j.useMemo)(()=>{if(s===null||I===null)return null;let U=parseFloat(I);if(isNaN(U))return null;let k=U*s;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(k)},[s,I]);return{balance:i,formatted:I,symbol:E,usdPrice:s,usdValue:A,isLoading:g,error:c,refetch:v,chain:m}}var et=require("@naculus/connect-appkit-core"),Re=require("react");function M(e){return e??Mt()}function Ft(){let{client:e,session:t,chainId:r}=P(),[o,n]=(0,Re.useState)(null),[i,a]=(0,Re.useState)(!1),[g,u]=(0,Re.useState)(null),c=(0,Re.useRef)(0),h=(0,Re.useCallback)(async()=>{let s=++c.current,l=M(e);if(!l?.getCapabilities||!t){n(null),a(!1),u(null);return}a(!0),u(null);try{let d=await l.getCapabilities(t);if(s!==c.current)return;n((0,et.normalizeCapabilities)(d))}catch(d){if(s!==c.current)return;n(null),u(d instanceof Error?d:new Error("Capability query failed"))}finally{s===c.current&&a(!1)}},[e,t]);return(0,Re.useEffect)(()=>{h()},[h]),{capabilities:o,current:(0,et.selectChainCapabilities)(o,r),atomic:(0,et.atomicSupportFor)(o,r),isFetching:i,error:g,refetch:h}}var Kt=require("react"),tt=require("@naculus/connect-appkit-core");function ie(){let{chainId:e,session:t,switchChain:r,chains:o}=P(),n=(0,Kt.useMemo)(()=>(0,tt.resolveChain)(o,e),[o,e]),i=(0,Kt.useMemo)(()=>t?(0,tt.describeChain)(o,e):null,[o,e,t]),a=(0,Kt.useMemo)(()=>(0,tt.chainsForNamespace)(o,e),[o,e]);return{chainId:e,currentChain:n,chainInfo:i,availableChains:a,chains:a,isEvm:e?.startsWith("eip155:")??!1,switchChain:r}}var Et=require("react");var kr=require("@naculus/connect-core");function xr(){let{connect:e,status:t}=P(),[r,o]=(0,Et.useState)(!1),[n,i]=(0,Et.useState)(null);return{connect:(0,Et.useCallback)(async()=>{o(!0),i(null);try{await e()}catch(g){let u=g instanceof Error?g.message:"Connection failed";i(g instanceof kr.WalletError?g:new Error(u))}finally{o(!1)}},[e]),isConnecting:r||t==="connecting",error:n}}var nt=require("@naculus/connect-core"),Te=require("react");var qt=require("@naculus/connect-appkit-core"),$t=require("react"),He=require("viem");function fe(){let{evmAccount:e,isConnected:t}=$(),{currentChain:r,chains:o}=ie(),n=r?(0,qt.chainNumber)(r):null,i=(0,$t.useMemo)(()=>r?(0,qt.toViemChain)(r,n):null,[r,n]),a=(0,$t.useMemo)(()=>i?(0,He.createPublicClient)({transport:(0,He.http)(i.rpcUrls.default.http[0]),chain:i}):null,[r,i]),g=(0,$t.useMemo)(()=>{if(!t||!e||!i)return null;let u=e.includes(":")?e.split(":").pop():e;return(0,He.createWalletClient)({transport:(0,He.http)(i.rpcUrls.default.http[0]),chain:i,account:u})},[t,e,r,i]);return{publicClient:a,walletClient:g,chains:o}}function rt(){let{publicClient:e}=fe(),{evmAccount:t}=$(),[r,o]=(0,Te.useState)(nt.UNKNOWN_DELEGATION),[n,i]=(0,Te.useState)(!1),[a,g]=(0,Te.useState)(null),u=(0,Te.useRef)(0),c=t?.includes(":")?t.split(":").pop():t,h=(0,Te.useCallback)(async()=>{let s=++u.current;if(!e||!c){o(nt.UNKNOWN_DELEGATION),i(!1),g(null);return}i(!0),g(null);try{let l=await e.getCode({address:c});if(s!==u.current)return;o((0,nt.readDelegation)(l??"0x"))}catch(l){if(s!==u.current)return;o(nt.UNKNOWN_DELEGATION),g(l instanceof Error?l:new Error("Code read failed"))}finally{s===u.current&&i(!1)}},[e,c]);return(0,Te.useEffect)(()=>{h()},[h]),{...r,isFetching:n,error:a,refetch:h}}var ee=require("@naculus/connect-core"),re=require("react"),vt=require("viem");var jt=require("@naculus/connect-core");var Fe=require("react");var pe=require("@naculus/connect-core"),Ee=require("react");var vr=require("@naculus/connect-core");function Vt(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 vr.WalletError("tx_failed","Wallet did not return a valid 32-byte transaction hash")}function zt(){let{session:e,chainId:t,client:r}=P(),[o,n]=(0,Ee.useState)("idle"),[i,a]=(0,Ee.useState)(null),[g,u]=(0,Ee.useState)(null),[c,h]=(0,Ee.useState)(null),[s,l]=(0,Ee.useState)(null),d=(0,Ee.useCallback)(async(y,E)=>{if(!e){n("failed");let w=new pe.WalletError("wallet_unavailable","No active session");throw a(w),w}if(y.length===0){n("failed");let w=new pe.WalletError("invalid_input","At least one call is required");throw a(w),w}n("awaiting_approval"),a(null),u(null);try{let w=M(r);if(!w)throw new pe.WalletError("wallet_unavailable","Client not initialized");let R=E?.chainId??t??void 0,v=E?.strategy??(0,pe.chooseExecutionStrategy)(await(0,pe.getAccountCapabilities)(w,e,R),y.length);if(l(v),v==="atomic-batch"){let A=await w.sendCalls(e,y,R,{atomicRequired:!0,...E?.paymasterService?{paymasterService:E.paymasterService}:{}});return n("submitted"),u(A),A}let I="";for(let A=0;A<y.length;A++){let U=y[A];try{I=Vt(await w.sendTransaction(e,{transaction:{to:U.to,data:U.data,value:U.value},chainId:R}))}catch(k){throw new pe.WalletError("tx_failed",`Call ${A+1} of ${y.length} failed after ${A} already landed (sent sequentially \u2014 this wallet cannot batch atomically): ${k instanceof Error?k.message:String(k)}`)}}return n("submitted"),u(I),I}catch(w){n("failed");let R=w instanceof Error?w.message:"sendCalls failed";throw a(w instanceof Error?w:new Error(R)),w}},[e,t,r]),f=(0,Ee.useCallback)(async y=>{if(!e)throw new pe.WalletError("wallet_unavailable","No active session");let E=y??g;if(!E)throw new pe.WalletError("invalid_input","No bundle hash available");if(!y&&s==="sequential")throw new pe.WalletError("invalid_input","Calls were sent sequentially, so there is no bundle to query. Track the returned transaction hash instead.");let w=M(r);if(!w)throw new pe.WalletError("wallet_unavailable","Client not initialized");let R=await w.getCallsStatus(e,E);return h(R),R},[e,g,r,s]),m=(0,Ee.useCallback)(async y=>{if(!e)return!1;let E=y??g;if(!E||!y&&s==="sequential")return!1;let w=M(r);if(!w?.showCallsStatus)return!1;try{return await w.showCallsStatus(e,E),!0}catch{return!1}},[e,g,r,s]),C=(0,Ee.useCallback)(()=>{n("idle"),a(null),u(null),h(null),l(null)},[]);return{sendCalls:d,getCallsStatus:f,showCallsStatus:m,status:o,error:i,batchHash:g,callsStatus:c,execution:s,reset:C,isSending:o==="awaiting_approval"}}function Gt(e={}){let{current:t,atomic:r}=Ft(),{delegated:o,delegate:n}=rt(),{sendCalls:i}=zt(),[a,g]=(0,Fe.useState)(!1),[u,c]=(0,Fe.useState)(null),[h,s]=(0,Fe.useState)(null),l=e.atomicity??"preferred",d=e.sponsorship??"any",f=e.paymasterService,m=e.userOperation,C=e.userOperationSponsored??!1,y=!!(t?.raw?.paymasterService?.supported&&f),E=(0,Fe.useCallback)((R,v=l)=>{let I=(0,jt.planExecution)({atomicBatch:r==="supported",discovered:r!=="unknown",sponsoredTransactions:!1,...t?.maxBatchSize===void 0?{}:{maxBatchSize:t.maxBatchSize}},R,{atomicity:v,sponsorship:d}),A=d==="required"&&!C;if(I.strategy==="atomic-batch"&&!A)return{...I,reason:I.reason+(y?" A paymaster service will be requested, but the wallet's final fee payer must be checked after execution.":""),route:"wallet-batch"};let U=o&&r!=="supported"?` This account does delegate to ${n} under EIP-7702, so it is capable of batching even though the wallet has not offered to.`:"",k=v!=="any"&&!I.atomic||d==="required";return m&&k&&!A?{strategy:"atomic-batch",atomic:!0,sponsored:C,reason:d==="required"&&!I.sponsored?"The wallet batch is not configured for sponsored gas, so the calls are executed through the configured sponsored UserOperation route.":"This wallet cannot batch, so the calls are executed as a single UserOperation through the smart account, which lands as one transaction.",route:"user-operation"}:A?{strategy:"refuse",atomic:I.atomic,sponsored:!1,reason:"Sponsored gas was required, but there is no executable sponsored route: no paymaster is configured for a wallet batch, and capability advertising alone cannot pay for a sequential transaction.",route:null}:I.strategy==="refuse"?{...I,reason:I.reason+U,route:null}:{...I,reason:I.reason+U,route:"sequential"}},[r,t,f,y,m,C,l,d,o,n]),w=(0,Fe.useCallback)(async(R,v=l)=>{g(!0),c(null);try{let I=E(R.length,v);if(I.route===null)throw new jt.WalletError("method_not_allowed",I.reason);return s(I.route),I.route==="user-operation"?await m(R):await i(R,{strategy:I.route==="wallet-batch"?"atomic-batch":"sequential",...I.route==="wallet-batch"&&y?{paymasterService:f}:{}})}catch(I){let A=I instanceof Error?I:new Error("Execution failed");throw c(A),A}finally{g(!1)}},[E,i,m,l,f,y]);return{preview:E,execute:w,isExecuting:a,error:u,lastRoute:h,reset:()=>{c(null),s(null)}}}var ke=require("@naculus/connect-core"),K=require("react");var kt=null,zn=null;function Ds(e){return e?JSON.stringify({defaultMaxTotalValue:e.defaultMaxTotalValue?.toString(),defaultMaxTxCount:e.defaultMaxTxCount,defaultExpiryMs:e.defaultExpiryMs,requireAllowedContracts:e.requireAllowedContracts,forbiddenMethods:e.forbiddenMethods,pbkdf2Iterations:e.pbkdf2Iterations,unsafeAllowWeakKdf:e.unsafeAllowWeakKdf,storagePrefix:e.storagePrefix,encryptionKey:e.encryptionKey,encryptionSalt:e.encryptionSalt}):""}function ot(e){let t=Ds(e);if(!kt){let r=e?.storagePrefix??ke.DEFAULT_SESSION_KEY_CONFIG.storagePrefix;return kt=new ke.SessionKeyManager(e,typeof window<"u"?new ke.LocalStorageAdapter(`${r}:`):new ke.MemoryStorageAdapter),zn=t,kt}if(t!==""&&t!==zn)throw new ke.WalletError("invalid_input","useSessionKeys is backed by a process-wide SessionKeyManager, and a different spending configuration was supplied after it was created. The second configuration would be ignored, so the caller would be operating under limits it did not set. Use one configuration per application, or construct a SessionKeyManager directly.");return kt}function Qt(e){let{session:t}=P(),[r,o]=(0,K.useState)([]),[n,i]=(0,K.useState)(!1),[a,g]=(0,K.useState)(null),u=(0,K.useRef)(!0),c=(0,K.useCallback)(()=>g(null),[]),h=ot(e),s=h.isStorageAvailable(),l=(0,K.useCallback)(async()=>{if(!t){o([]);return}i(!0),g(null);try{let f=await h.listSessions();u.current&&o(f)}catch(f){u.current&&g(f instanceof Error?f:new Error("Failed to load session keys"))}finally{u.current&&i(!1)}},[t,h]);(0,K.useEffect)(()=>(u.current=!0,l(),()=>{u.current=!1}),[l]);let d=r.filter(f=>f.status==="active");return{sessions:r,activeSessions:d,loading:n,error:a,refresh:l,clearError:c,storageAvailable:s}}function br(e){let{session:t}=P(),[r,o]=(0,K.useState)(null),[n,i]=(0,K.useState)(!1),[a,g]=(0,K.useState)(null),u=(0,K.useCallback)(()=>g(null),[]),c=ot(e);return{createSessionKey:(0,K.useCallback)(async(s,l)=>{if(!t)throw new ke.WalletError("wallet_unavailable","No active wallet session");i(!0),g(null);try{let d=l??void 0,f=await c.createSessionKey(s,d);return o(f),f}catch(d){let f=d instanceof Error?d:new Error("Failed to create session key");throw g(f),f}finally{i(!1)}},[t,c]),lastCreated:r,isCreating:n,error:a,clearError:u}}function Ar(e){let[t,r]=(0,K.useState)(!1),[o,n]=(0,K.useState)(null),i=(0,K.useCallback)(()=>n(null),[]),a=ot(e);return{revokeSession:(0,K.useCallback)(async u=>{r(!0),n(null);try{await a.revokeSession(u)}catch(c){let h=c instanceof Error?c:new Error("Failed to revoke session key");throw n(h),h}finally{r(!1)}},[a]),isRevoking:t,error:o,clearError:i}}function Rr(e){let[t,r]=(0,K.useState)(!1),[o,n]=(0,K.useState)(null),i=(0,K.useCallback)(()=>n(null),[]),a=ot(e),g=(0,K.useCallback)(async(c,h,s)=>{r(!0),n(null);try{return await a.signWithSessionKey(c,h,s)}catch(l){let d=l instanceof Error?l:new Error("Failed to sign with session key");throw n(d),d}finally{r(!1)}},[a]),u=(0,K.useCallback)(async(c,h)=>{r(!0),n(null);try{return await a.checkSessionScope(c,h)}catch(s){let l=s instanceof Error?s:new Error("Failed to check session scope");throw n(l),l}finally{r(!1)}},[a]);return{signWithSession:g,checkScope:u,isBusy:t,error:o,clearError:i}}function Tr(){kt=null,zn=null}var xt=require("react");var Xt=require("@naculus/connect-core");function Yt(){let{session:e,chainId:t,client:r}=P(),[o,n]=(0,xt.useState)(!1),[i,a]=(0,xt.useState)(null);return{signMessage:(0,xt.useCallback)(async u=>{if(!e){let h=new Xt.WalletError("wallet_unavailable","No active session");throw a(h),h}let c=e.namespaces.eip155?.accounts[0]??Object.values(e.namespaces)[0]?.accounts[0];if(!c){let h=new Xt.WalletError("wallet_unavailable","No account found");throw a(h),h}n(!0),a(null);try{let h=M(r);if(!h)throw new Xt.WalletError("wallet_unavailable","Client not initialized");return await h.signMessage(e,{message:u,address:c,chainId:t??void 0})}catch(h){let s=h instanceof Error?h.message:"Signing failed",l=h instanceof Error?h:new Error(s);throw a(l),l}finally{n(!1)}},[e,t,r]),isSigning:o,error:i}}function Ms(e){let t=e?.includes(":")?e.split(":").pop():e;return t&&/^0x[0-9a-fA-F]{40}$/.test(t)?t:null}function Ir(e){return e?[...e].map(t=>t.toLowerCase()).sort():null}function Ls(e,t){let r=e.to===void 0||e.to.toLowerCase()===t.to?.toLowerCase(),o=e.data===void 0||e.data.toLowerCase()===t.data?.toLowerCase();return r&&o&&((i,a)=>{if(i===void 0)return!0;if(a===void 0)return!1;try{return BigInt(i)===BigInt(a)}catch{return!1}})(e.value,t.value)&&(e.chainId===void 0||e.chainId===t.chainId)}function st(e,t){let r=e.scope.tokenAllowances?Object.entries(e.scope.tokenAllowances).map(([n,i])=>[n.toLowerCase(),i.toString()]).sort(([n],[i])=>n.localeCompare(i)):null,o={version:1,origin:t,signer:e.signerAddress.toLowerCase(),sessionId:e.id,sessionPublicKey:e.publicKey.toLowerCase(),expiresAt:new Date(e.expiresAt).toISOString(),mode:e.scope.mode,limits:{maxTotalGas:e.scope.maxTotalGas?.toString()??null,maxGasPerTx:e.scope.maxGasPerTx?.toString()??null,maxTotalValue:e.scope.maxTotalValue?.toString()??null,maxValuePerTx:e.scope.maxValuePerTx?.toString()??null,maxTxCount:e.scope.maxTxCount??null},allowedContracts:Ir(e.scope.allowedContracts),allowedMethods:Ir(e.scope.allowedMethods),allowedChainIds:e.scope.allowedChainIds?[...e.scope.allowedChainIds].sort((n,i)=>n-i):null,tokenAllowances:r};return`Naculus Session Policy v1
|
|
2
|
+
${JSON.stringify(o)}`}function Ur(e={}){let{evmAccount:t}=$(),r=Ms(t),o=rt(),n=Gt(e.execution),{signMessage:i}=Yt(),a=Qt(e.managerConfig),g=ot(e.managerConfig),[u,c]=(0,re.useState)(!1),[h,s]=(0,re.useState)(null),[l,d]=(0,re.useState)(()=>new Set),[f,m]=(0,re.useState)(!1),C=e.origin??(typeof window<"u"?window.location.origin:"unknown"),y=(0,re.useCallback)(async k=>{if(k.status!=="active"||!k.authorized||k.scope.mode!=="offchain")return!1;let T=st(k,C);return g.verifyOffchainAuthorization(k.id,T,async({message:b,signature:O,signerAddress:_})=>(await(0,vt.recoverMessageAddress)({message:b,signature:O})).toLowerCase()===_.toLowerCase())},[g,C]);(0,re.useEffect)(()=>{let k=!1,T=a.sessions.filter(b=>b.status==="active"&&b.authorized&&b.scope.mode==="offchain");return T.length===0?(d(new Set),m(!1),()=>{k=!0}):(m(!0),Promise.all(T.map(async b=>[b.id,await y(b)])).then(b=>{k||d(new Set(b.filter(([,O])=>O).map(([O])=>O)))}).catch(b=>{k||(d(new Set),s(b instanceof Error?b:new Error("Policy verification failed")))}).finally(()=>{k||m(!1)}),()=>{k=!0})},[a.sessions,y]);let E=(0,re.useCallback)(()=>{s(null),a.clearError()},[a]),w=(0,re.useCallback)(async k=>{if(!r){let b=new ee.WalletError("wallet_unavailable","No active EVM account");throw s(b),b}if(k.mode&&k.mode!=="offchain"){let b=new ee.WalletError("method_not_allowed","This flow creates signed off-chain policies only. EIP-7702 and AA-module policies require a configured on-chain execution adapter.");throw s(b),b}if(!e.managerConfig?.encryptionKey){let b=new ee.WalletError("method_not_allowed","Persistent delegation policies require a host-provided encryptionKey. The deterministic compatibility fallback is not a production key boundary.");throw s(b),b}if(!a.storageAvailable){let b=new ee.WalletError("storage_unavailable","Persistent delegation policy storage is unavailable in this browser");throw s(b),b}c(!0),s(null);let T=null;try{T=await g.createSessionKey({...k,mode:"offchain"},r);let b=st(T,C),O=await i(b);if(!/^0x[0-9a-fA-F]{130}$/.test(O))throw new ee.WalletError("invalid_input","Wallet did not return a valid 65-byte EVM policy signature");if((await(0,vt.recoverMessageAddress)({message:b,signature:O})).toLowerCase()!==r.toLowerCase())throw new ee.WalletError("invalid_input","Policy signature does not recover to the connected EVM account");await g.setAuthorization(T.id,{signerAddress:r,type:"offchain",rawSignature:O,message:b});let p=(await g.listSessions()).find(S=>S.id===T?.id);if(!p?.authorized)throw new ee.WalletError("invalid_input","Policy authorization was not persisted");if(!await y(p))throw new ee.WalletError("invalid_input","Persisted policy signature did not verify against its stored scope and origin");return await a.refresh(),p}catch(b){if(T)try{await g.revokeSession(T.id)}catch{}let O=b instanceof Error?b:new Error("Policy creation failed");throw s(O),O}finally{c(!1)}},[g,e.managerConfig?.encryptionKey,C,a,i,r,y]),R=(0,re.useCallback)(async k=>{c(!0),s(null);try{await g.revokeSession(k),await a.refresh()}catch(T){let b=T instanceof Error?T:new Error("Policy revocation failed");throw s(b),b}finally{c(!1)}},[g,a]),v=(0,re.useCallback)(async(k,T,b=1,O="preferred")=>{let _=(await g.listSessions()).find(Ot=>Ot.id===k)??null,p=await g.checkSessionScope(k,T),S=n.preview(b,O),x=_?await y(_):!1,W=!!(_&&r&&_.signerAddress.toLowerCase()===r.toLowerCase()),N=null;if(_&&e.adapter&&x&&W&&p.valid)try{N=await e.adapter.check({policy:_,transaction:T})}catch(Ot){N={ready:!1,authorizationInstalled:!1,sponsored:!1,promptless:!1,reason:Ot instanceof Error?`Execution adapter check failed: ${Ot.message}`:"Execution adapter check failed."}}let L=!!(e.adapter?.route!=="eip7702"||o.delegated===!0&&N?.executorAddress&&o.delegate?.toLowerCase()===N.executorAddress.toLowerCase()),Q=!!(_?.status==="active"&&_.authorized&&x&&_.scope.mode==="offchain"&&W&&p.valid),Qe=!!(e.execution?.sponsorship!=="required"||N?.sponsored),Xe=!!(Q&&b===1&&N?.ready&&N.authorizationInstalled&&N.promptless&&Qe&&L),ks=!!(Q&&(S.route||Xe)),xs=_?_.status!=="active"?`Policy is ${_.status}.`:_.authorized?x?W?p.valid?Xe?`The configured ${e.adapter?.route??"AA/7702"} adapter can submit this policy-authorized operation without another main-wallet prompt.${N?.sponsored?" Gas sponsorship is guaranteed.":""} ${N?.reason??"The on-chain execution adapter is ready."}`:e.adapter?!N?.ready||!N.authorizationInstalled?`${S.reason} ${N?.reason??"The execution adapter is not ready."}`:N.promptless?Qe?b!==1?`${S.reason} This policy adapter prepares one execution at a time and cannot claim a multi-call broadcast.`:L?S.route?`${S.reason} ${N.reason}`:S.reason:`${S.reason} The configured EIP-7702 executor does not match the account's on-chain delegation.`:`${S.reason} Sponsored gas is required, but the configured adapter does not guarantee sponsorship.`:`${S.reason} The configured adapter would invoke the main wallet again, so promptless broadcast is not ready.`:`${S.reason} The signed off-chain policy permits this request; an AA/7702 adapter is still required to broadcast without another wallet prompt.`:p.reason??"The transaction is outside the policy scope.":"The connected account is not the policy signer.":"The persisted policy signature no longer matches its scope, signer, or origin.":"The main wallet has not signed this policy.":"Policy not found.";return{policy:_,scope:p,execution:S,signerMatches:W,authorizationVerified:x,ready:ks,broadcastReady:Xe,broadcastRoute:Xe?e.adapter?.route??null:null,onchainAuthorizationVerified:!!(N?.authorizationInstalled&&L),broadcastSponsored:Xe?N?.sponsored??!1:null,broadcastPromptless:!!(Xe&&N?.promptless),reason:xs}},[o,n,g,e.adapter,e.execution?.sponsorship,r,y]),I=(0,re.useCallback)(async(k,T,b)=>{let O=await v(k,b,1,"any");if(!O.ready)throw new ee.WalletError("method_not_allowed",O.reason);return g.signWithVerifiedOffchainAuthorization(k,_=>st(_,C),async({message:_,signature:p,signerAddress:S})=>(await(0,vt.recoverMessageAddress)({message:_,signature:p})).toLowerCase()===S.toLowerCase(),T,b)},[g,C,v]),A=(0,re.useCallback)(async(k,T)=>{let b=e.adapter;if(!b)throw new ee.WalletError("method_not_allowed","No session-policy-aware AA/7702 execution adapter is configured.");c(!0),s(null);try{let O=await v(k,T,1,"any");if(!O.broadcastReady||!O.policy)throw new ee.WalletError("method_not_allowed",O.reason);let _=await b.prepare({policy:O.policy,transaction:T});if(!/^0x[0-9a-fA-F]{64}$/.test(_.digest))throw new ee.WalletError("invalid_input","Execution adapter returned a digest that is not 32 bytes.");if(!Ls(T,_.transaction))throw new ee.WalletError("invalid_input","Execution adapter changed the requested target, value, data, or chain.");let p=await b.check({policy:O.policy,transaction:_.transaction}),S=b.route!=="eip7702"||o.delegated===!0&&p.executorAddress!==void 0&&o.delegate?.toLowerCase()===p.executorAddress.toLowerCase();if(!p.ready||!p.authorizationInstalled||!p.promptless||e.execution?.sponsorship==="required"&&!p.sponsored||!S)throw new ee.WalletError("method_not_allowed",p.reason||"The on-chain policy authorization is not ready.");let x=await g.signWithVerifiedOffchainAuthorization(k,N=>st(N,C),async({message:N,signature:L,signerAddress:Q})=>(await(0,vt.recoverMessageAddress)({message:N,signature:L})).toLowerCase()===Q.toLowerCase(),_.digest,_.transaction),W=await b.broadcast({policy:O.policy,prepared:_,signature:x});if(W.route!==b.route||W.status!=="submitted"||!/^0x[0-9a-fA-F]{64}$/.test(W.hash))throw new ee.WalletError("invalid_input","Execution adapter returned an invalid submission result.");return await a.refresh(),W}catch(O){let _=O instanceof Error?O:new Error("Policy execution failed");throw s(_),_}finally{c(!1)}},[o,g,e.adapter,e.execution?.sponsorship,C,v,a]),U=a.activeSessions.filter(k=>l.has(k.id));return{policies:a.sessions,activePolicies:U,storageAvailable:a.storageAvailable,loading:a.loading||f,isBusy:u,error:h??a.error,delegation:o,createPolicy:w,revokePolicy:R,previewPolicyExecution:v,signPolicyDigest:I,executePolicy:A,refresh:a.refresh,clearError:E}}var Ke=require("react");function Pr(){let{disconnect:e,status:t}=P(),[r,o]=(0,Ke.useState)(!1),[n,i]=(0,Ke.useState)(null),a=(0,Ke.useRef)(!0);return{disconnect:(0,Ke.useCallback)(async()=>{if(t!=="disconnected"){o(!0),i(null);try{await e()}catch(u){if(!a.current)return;i(u instanceof Error?u:new Error("Disconnect failed"))}finally{a.current&&o(!1)}}},[e,t]),isDisconnecting:r,error:n,cleanup:()=>{a.current=!1}}}var Jt=require("@naculus/connect-core"),V=require("react");function Le(e){let t=e.activeNamespace??"eip155",r=Array.isArray(e.accounts)?e.accounts.map(({namespace:o,address:n,derivationPath:i})=>({namespace:o,address:n,...i?{derivationPath:i}:{}})):e.address?[{namespace:t,address:e.address}]:[];return{accounts:r,activeNamespace:t,createdAt:e.createdAt??0,...e.chainId?{chainId:e.chainId}:{},...e.version?{version:e.version}:{},recoveryAvailable:!!e.mnemonic,address:r.find(o=>o.namespace===t)?.address??e.address}}function Wr(){let{connectEmbedded:e,client:t}=P(),[r,o]=(0,V.useState)(null),n=(0,V.useRef)(null),i=(0,V.useRef)(4),a=(0,V.useRef)(!1),g=(0,V.useRef)(null),[u,c]=(0,V.useState)(!1),[h,s]=(0,V.useState)(!1),[l,d]=(0,V.useState)(null),f=()=>d(null),m=(0,V.useCallback)(()=>{let p=n.current;return n.current=null,p},[]),C=(0,V.useCallback)(()=>{let p=M(t);if(!p?.embeddedConnector)throw new Jt.WalletError("wallet_unavailable","Embedded wallet not enabled.");return p.embeddedConnector},[t]),y=(0,V.useCallback)(()=>{try{return C().getWallet()?.privateKey??null}catch{return null}},[C]),E=(0,V.useCallback)(async()=>{let p=M(t);if(!p)throw new Jt.WalletError("wallet_unavailable","Embedded wallet not enabled.");let S=p.getEmbeddedConnector?await p.getEmbeddedConnector():p.embeddedConnector;if(!S)throw new Jt.WalletError("wallet_unavailable","Embedded wallet not enabled.");return S},[t]),w=(0,V.useCallback)(()=>{try{return M(t)?.passphraseGate??null}catch{return null}},[t]),R=(0,V.useCallback)(p=>{p?.code==="decryption_failed"&&w()?.forget("That passphrase did not open the wallet.")},[w]),v=(0,V.useCallback)(async()=>{a.current=!1,d(null);try{let p=await E();if(!await p.load())return!1;let x=p.getWallet();return x?(n.current=null,c(!1),o(Le(x)),!0):!1}catch(p){return a.current=!0,R(p),d(p instanceof Error?p:new Error("Failed to restore embedded wallet")),!1}},[R,E]);(0,V.useEffect)(()=>{let p=!1,S=null;return v().then(x=>{p||x||a.current||(S=setTimeout(()=>{p||v()},100))}),()=>{p=!0,S&&clearTimeout(S)}},[v]);let I=async()=>{s(!0),d(null);try{let p=await E(),S=await p.load(),x=p.getWallet();S&&x&&(o(Le(x)),n.current=x.mnemonic||null,c(!x.mnemonic)),await e();let W=p.getWallet();W&&(o(Le(W)),W.mnemonic&&!S&&(n.current=W.mnemonic,c(!0)))}catch(p){R(p),d(p instanceof Error?p:new Error("Embedded wallet connection failed"))}finally{s(!1)}},A=async()=>{s(!0),d(null);try{let p=await E();w()?.expect("create");let S=await p.generateWallet();return o(Le(S)),n.current=S.mnemonic,c(!0),S}catch(p){return d(p instanceof Error?p:new Error("Failed to generate wallet")),null}finally{s(!1)}},U=async p=>{s(!0),d(null);try{let S=await E();w()?.expect("create");let x=await S.importFromMnemonic(p);return o(Le(x)),n.current=null,c(!1),x}catch(S){return d(S instanceof Error?S:new Error("Failed to import wallet")),null}finally{s(!1)}},k=async p=>{s(!0),d(null);try{let S=await E();w()?.expect("create");let x=await S.importFromPrivateKey(p);return o(Le(x)),n.current=null,c(!1),x}catch(S){return d(S instanceof Error?S:new Error("Failed to import wallet")),null}finally{s(!1)}},T=async()=>{s(!0),d(null);try{await(await E()).wipe(),o(null),n.current=null,c(!1)}catch(p){d(p instanceof Error?p:new Error("Failed to wipe wallet"))}finally{s(!1)}},b=(0,V.useCallback)(p=>{let S=C();S.setActiveNamespace(p);let x=S.getWallet();o(x?Le(x):null)},[C]),O=(0,V.useCallback)(async()=>{let p=await E(),S=await p.backfillAccounts();if(S.length>0){let x=p.getWallet();o(x?Le(x):null)}return S.map(({namespace:x,address:W,derivationPath:N})=>({namespace:x,address:W,...N?{derivationPath:N}:{}}))},[E]),_=()=>{n.current=null,c(!1)};return{connectEmbedded:I,restoreWallet:v,generateWallet:A,importFromMnemonic:U,importFromPrivateKey:k,wipe:T,wallet:r,hasWallet:r!==null,address:r?.address??null,accounts:r?.accounts??[],activeNamespace:r?.activeNamespace??null,setActiveNamespace:b,backfillAccounts:O,seedPhrase:n.current,getSeedPhrase:m,getPrivateKey:y,backupPending:u,confirmBackup:_,isBusy:h,error:l,clearError:f,storageSecurityLevel:(()=>{try{let p=C(),S=p.getStorageSecurityLevel?.()??4;return p.getWallet()?(i.current=S,S):r?i.current:S}catch{return r?i.current:4}})(),securityReport:(()=>{let p=null;try{p=C().getStorageSecurityReport?.()??null}catch{p=null}if(!p)return g.current=null,null;let S=JSON.stringify(p);return g.current?.json===S?g.current.value:(g.current={json:S,value:p},p)})()}}var Nr=require("@naculus/connect-appkit-core"),he=require("react");var _r=require("@naculus/connect-core"),ge=require("react"),Or=require("@naculus/connect-appkit-core");function Bs(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 at(e){let{token:t,chainId:r}=e,o=t.address.toLowerCase(),n=Bs(e),i=(0,ge.useMemo)(()=>({key:n}),[n]),a=(0,ge.useRef)(n),g=(0,ge.useRef)(!0);(0,ge.useLayoutEffect)(()=>{a.current=n},[n]),(0,ge.useEffect)(()=>(g.current=!0,()=>{g.current=!1}),[]);let u=(0,ge.useCallback)(()=>g.current&&a.current===n,[n]),c=(0,ge.useCallback)(()=>{if(!u())throw new _r.WalletError("session_inactive","Wallet or token context changed. Retry the operation with the current account and chain.");let h=(0,Or.tokenChainMismatch)({address:o,chainId:t.chainId},r);if(h)throw h},[u,o,t.chainId,r]);return{identity:i,isCurrent:u,assertCurrent:c}}var Zt=require("@naculus/connect-core");function Dr(e){let{publicClient:t}=fe(),{currentChain:r}=ie(),{identity:o,isCurrent:n,assertCurrent:i}=at({token:e.token,chainId:r?(0,Nr.chainNumber)(r)??void 0:void 0,owner:e.owner,spender:e.spender,publicClient:t}),[a,g]=(0,he.useState)(null),u=a?.identity===o?a.raw:null,c=a?.identity===o&&a.fetching,h=a?.identity===o?a.error:null,s=(0,he.useRef)(null),l=(0,he.useRef)(0),d=(0,he.useCallback)(async()=>{if(!n())return;let m=++l.current,C=()=>n()&&m===l.current;if(g({identity:o,raw:null,fetching:!!t,error:null}),!!t)try{i();let y=await t.readContract({address:e.token.address,abi:Zt.ERC20_MIN_ABI,functionName:"allowance",args:[e.owner,e.spender]});if(!C())return;g({identity:o,raw:y,fetching:!1,error:null})}catch(y){if(!C())return;g({identity:o,raw:null,fetching:!1,error:y instanceof Error?y:new Error("Failed to fetch allowance")})}},[t,e.token.address,e.token.chainId,e.owner,e.spender,o,n,i]);return(0,he.useEffect)(()=>{d().catch(m=>console.warn("useERC20Allowance: initial fetch failed:",m))},[d]),(0,he.useEffect)(()=>(e.refreshInterval&&e.refreshInterval>0&&(s.current=setInterval(d,e.refreshInterval)),()=>{s.current&&(clearInterval(s.current),s.current=null)}),[e.refreshInterval,d]),{allowance:(0,he.useMemo)(()=>{if(u===null)return null;let m=e.token.decimals;return m===void 0?null:(0,Zt.formatUnits)(u,m)},[u,e.token.decimals]),allowanceRaw:u,isFetching:c,error:h,refetch:d}}var Mr=require("@naculus/connect-appkit-core"),ye=require("react");var en=require("@naculus/connect-core"),it=require("react");function lt(){let{session:e,chainId:t,client:r}=P(),[o,n]=(0,it.useState)("idle"),[i,a]=(0,it.useState)(null),g=(0,it.useCallback)(async c=>{if(!e){n("failed");let s=new en.WalletError("wallet_unavailable","No active session");throw a(s),s}let h=e.namespaces.eip155?.accounts.find(s=>/^eip155:\d+:0x[0-9a-fA-F]{40}$/.test(s)||/^0x[0-9a-fA-F]{40}$/.test(s));if(!h){n("failed");let s=new en.WalletError("wallet_unavailable","No EVM account found");throw a(s),s}n("awaiting_approval"),a(null);try{let s={...c,from:c.from??h.split(":").pop()},l=M(r);if(!l)throw new en.WalletError("wallet_unavailable","Client not initialized");let d=await l.sendTransaction(e,{transaction:s,chainId:t??void 0}),f=Vt(d);return n("submitted"),f}catch(s){n("failed");let l=s instanceof Error?s.message:"Transaction failed";throw a(s instanceof Error?s:new Error(l)),s}},[e,t,r]),u=(0,it.useCallback)(()=>{n("idle"),a(null)},[]);return{sendTransaction:g,status:o,error:i,reset:u,isSending:o==="awaiting_approval"}}var te=require("@naculus/connect-core"),Lr=require("viem");var Oe=require("@naculus/connect-appkit-core");function Hs(e){return e.includes(":")?e.split(":").pop():e}function Fs(e,t){return(0,Lr.encodeFunctionData)({abi:te.ERC20_MIN_ABI,functionName:"approve",args:[e,t]})}var Ks=2n**256n-1n;function Br(e){let{publicClient:t,walletClient:r}=fe(),{evmAccount:o,isConnected:n}=$(),{currentChain:i}=ie(),{session:a,client:g}=P(),{sendTransaction:u,isSending:c,error:h,reset:s}=lt(),[l,d]=(0,ye.useState)(null),{identity:f,isCurrent:m,assertCurrent:C}=at({token:e.token,chainId:i?(0,Mr.chainNumber)(i)??void 0:void 0,owner:o,spender:e.spender,connected:n,publicClient:t,walletClient:r,session:a,client:g}),[y,E]=(0,ye.useState)(null),w=y?.identity===f?y.raw:null,R=y?.identity===f&&y.fetching,v=(0,ye.useRef)((0,Oe.createDecimalsCache)(e.token,e.token.decimals)),I=(0,ye.useRef)(0),A=l??h,U=o?Hs(o):null,k=(0,ye.useCallback)(async()=>{if(!m())return null;let S=++I.current,x=()=>m()&&S===I.current;if(E({identity:f,raw:null,fetching:!!t&&!!U&&n}),d(null),!t||!U||!n)return null;try{C();let W=await t.readContract({address:e.token.address,abi:te.ERC20_MIN_ABI,functionName:"allowance",args:[U,e.spender]});return x()?(E({identity:f,raw:W,fetching:!1}),W):null}catch(W){return x()&&(E({identity:f,raw:null,fetching:!1}),d(W instanceof Error?W:new Error("Failed to fetch allowance"))),null}},[t,U,e.token.address,e.token.chainId,e.spender,f,m,C,n]),T=(()=>{if(w===null)return null;let S=(0,Oe.readDecimals)(v.current,e.token,e.token.decimals);return S===void 0?null:(0,te.formatUnits)(w,S)})(),b=(0,ye.useCallback)(async S=>{if(d(null),s(),!n||!o){let x=new te.WalletError("wallet_unavailable","No connected account");throw d(x),x}if(!t){let x=new te.WalletError("wallet_unavailable","No public client");throw d(x),x}try{C();let x=Fs(e.spender,S),W=M(g);if(a&&W){let L=await u({to:e.token.address,data:x,value:"0"});return k(),L}if(r){let{request:L}=await t.simulateContract({address:e.token.address,abi:te.ERC20_MIN_ABI,functionName:"approve",args:[e.spender,S],account:U});C();let Q=await r.writeContract(L);return k(),Q}let N=await u({to:e.token.address,data:x,value:"0"});return k(),N}catch(x){let W=x instanceof Error?x:new Error("Approve failed");throw m()&&d(W),W}},[e,t,r,o,n,a,g,U,u,s,k,C,m]),O=(0,ye.useCallback)(async S=>{try{if(C(),!t)throw new te.WalletError("wallet_unavailable","No public client");let x=(0,Oe.readDecimals)(v.current,e.token,e.token.decimals);x===void 0&&(x=await t.readContract({address:e.token.address,abi:te.ERC20_MIN_ABI,functionName:"decimals"}),C(),(0,Oe.writeDecimals)(v.current,e.token,x));let W=(0,te.parseUnits)(S,x);return await b(W)}catch(x){throw m()&&d(x instanceof Error?x:new Error("Approve failed")),x}},[e.token,t,b,C,m]),_=(0,ye.useCallback)(async()=>b(Ks),[b]),p=(0,ye.useCallback)(async S=>{if(!m()||!n||!U||!t)return!1;try{C()}catch(L){return d(L instanceof Error?L:new Error("Cannot check allowance")),!1}let x=w??await k();if(x===null)return!1;let W=(0,Oe.readDecimals)(v.current,e.token,e.token.decimals);if(W===void 0){if(!t)throw new te.WalletError("wallet_unavailable","Cannot check allowance: no public client to read token decimals.");if(W=await t.readContract({address:e.token.address,abi:te.ERC20_MIN_ABI,functionName:"decimals"}),!m())return!1;(0,Oe.writeDecimals)(v.current,e.token,W)}let N=(0,te.parseUnits)(S,W);return m()&&x>=N},[w,k,e.token.address,e.token.chainId,e.token.decimals,t,m,C,n,U]);return{approve:O,approveMax:_,allowance:T,allowanceRaw:w,hasAllowance:p,isApproving:c,isFetchingAllowance:R,error:A,refetchAllowance:k}}var Hr=require("@naculus/connect-appkit-core"),ct=require("react");var Ne=require("@naculus/connect-core"),Fr=require("viem");var ut=require("@naculus/connect-appkit-core");function $s(e){return e.includes(":")?e.split(":").pop():e}function qs(e,t){return(0,Fr.encodeFunctionData)({abi:Ne.ERC20_MIN_ABI,functionName:"transfer",args:[e,t]})}function Kr(e){let{publicClient:t,walletClient:r}=fe(),{evmAccount:o,isConnected:n}=$(),{currentChain:i}=ie(),{session:a,client:g}=P(),{sendTransaction:u,isSending:c,error:h,reset:s}=lt(),[l,d]=(0,ct.useState)(null),{isCurrent:f,assertCurrent:m}=at({token:e.token,chainId:i?(0,Hr.chainNumber)(i)??void 0:void 0,owner:o,connected:n,publicClient:t,walletClient:r,session:a,client:g}),C=(0,ct.useRef)((0,ut.createDecimalsCache)(e.token,e.token.decimals)),y=l??h;return{sendTransfer:(0,ct.useCallback)(async(w,R)=>{if(d(null),s(),!n||!o){let v=new Ne.WalletError("wallet_unavailable","No connected account");throw d(v),v}if(!t){let v=new Ne.WalletError("wallet_unavailable","No public client available");throw d(v),v}try{m();let v=$s(o),I=(0,ut.readDecimals)(C.current,e.token,e.token.decimals);I===void 0&&(I=await t.readContract({address:e.token.address,abi:Ne.ERC20_MIN_ABI,functionName:"decimals"}),m(),(0,ut.writeDecimals)(C.current,e.token,I));let A=(0,Ne.parseUnits)(R,I),U=qs(w,A),k=M(g);if(a&&k)return await u({to:e.token.address,data:U,value:"0"});if(r){let{request:b}=await t.simulateContract({address:e.token.address,abi:Ne.ERC20_MIN_ABI,functionName:"transfer",args:[w,A],account:v});return m(),await r.writeContract(b)}return await u({to:e.token.address,data:U,value:"0"})}catch(v){let I=v instanceof Error?v:new Error("Transfer failed");throw f()&&d(I),I}},[e.token,t,r,o,n,a,g,u,s,m,f]),isSending:c,error:y}}var zr=require("@naculus/connect-appkit-core"),jr=require("react");var $r=require("@naculus/connect-appkit-core"),qr=require("@naculus/connect-core"),xe=require("react"),Vr=require("@naculus/connect-appkit-core");function tn(e,t){let{session:r}=P(),{evmAccount:o,isConnected:n}=$(),{currentChain:i}=ie(),{publicClient:a}=fe(),[g,u]=(0,xe.useState)(void 0),[c,h]=(0,xe.useState)(!1),[s,l]=(0,xe.useState)(null),d=(0,xe.useRef)(void 0),f=(0,xe.useCallback)(async()=>{if(!e){let C={status:"unavailable",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[]},provider:"eth_call",summary:"No transaction to simulate",changesDetected:!1};return u(C),C}h(!0),l(null);try{if((t??(i?(0,$r.chainNumber)(i)??void 0:void 0))===void 0)throw new qr.WalletError("invalid_chain","No chain to simulate on. Connect a wallet or pass a chainId.");let y=i?.rpcUrl;if(a)try{let w=o?.includes(":")?o.split(":").pop():o,R={to:e.to,data:e.data??"0x",value:e.value?BigInt(e.value):0n};w&&(R.from=w),await a.call(R);let v={status:"success",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[]},gasInfo:e.gas?{gasLimit:BigInt(e.gas),estimatedFeeEth:"0"}:void 0,provider:"eth_call",summary:"Transaction simulation succeeded (basic revert check only)",changesDetected:!0};return u(v),v}catch(w){let R=w?.message??String(w),v=w?.data??w?.cause?.data,I=(0,Vr.resolveRevertReason)(v,R),A={status:"reverted",revertReason:I,coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"high",message:I?`Transaction would revert: ${I}`:"Transaction would revert"}]},provider:"eth_call",summary:I?`Transaction reverted: ${I}`:"Transaction reverted",changesDetected:!1};return u(A),A}if(y)try{let R=await(await fetch(y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:"eth_call",params:[{to:e.to,from:o?.includes(":")?o.split(":").pop():o,data:e.data??"0x",value:e.value??"0x0"},"latest"]})})).json();if(R.error){let I={status:"reverted",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"high",message:`Transaction would revert: ${R.error.message}`}]},provider:"eth_call",summary:"Transaction reverted",changesDetected:!1};return u(I),I}let v={status:"success",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[]},provider:"eth_call",summary:"Transaction simulation succeeded",changesDetected:!0};return u(v),v}catch(w){let R={status:"unavailable",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"medium",message:`Network error: ${w?.message??"Unknown"}`}]},provider:"eth_call",summary:"Simulation unavailable due to network error",changesDetected:!1};return u(R),R}let E={status:"unavailable",coverage:{balanceChanges:!1,approvalChanges:!1,risk:!1},balanceChanges:[],approvalChanges:[],riskAssessment:{level:"unknown",score:0,warnings:[{category:"simulation_failed",severity:"low",message:"No RPC URL or public client available for simulation"}]},provider:"eth_call",summary:"Simulation unavailable: no RPC URL",changesDetected:!1};return u(E),E}catch(C){let y=C instanceof Error?C:new Error("Simulation failed");throw l(y),y}finally{h(!1)}},[e,t,i,a,o]);(0,xe.useEffect)(()=>{if(e)return d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{f().catch(()=>{})},300),()=>{d.current&&clearTimeout(d.current)}},[e,f]);let m=(0,xe.useCallback)(()=>{u(void 0),l(null),h(!1)},[]);return{result:g,isSimulating:c,error:s,simulate:f,reset:m}}var Vs="0xa9059cbb";function zs(e){return(e.startsWith("0x")?e.slice(2):e).padStart(64,"0")}function js(e,t=32){return(e.startsWith("0x")?e.slice(2):e).padStart(t*2,"0")}function Gs(e,t){let[r="0",o=""]=e.split("."),n=o.padEnd(t,"0").slice(0,t);return BigInt(r+n||"0")}function Qs(e,t){return`${Vs}${zs(e)}${js(t.toString(16))}`}function Gr(e){let{evmAccount:t,isConnected:r}=$(),{currentChain:o}=ie(),n=e.token.chainId??(o?(0,zr.chainNumber)(o)??void 0:void 0),i=(0,jr.useMemo)(()=>{if(!(!r||!t))try{let g=e.token.decimals;if(g===void 0)return;let u=Gs(e.amount,g),c=Qs(e.to,u);return{to:e.token.address,data:c,value:"0"}}catch{return}},[e.token.address,e.token.decimals,e.to,e.amount,t,r]),a=tn(i,n);return{result:a.result,isSimulating:a.isSimulating,error:a.error,reSimulate:a.simulate,reset:a.reset}}var Ie=require("react");var Ce=require("react"),nn=require("react"),jn=(0,nn.createContext)(null);function bt(){return(0,nn.useContext)(jn)}function Qr(e,t,r){let o=bt(),n=r??o,[i,a]=(0,Ce.useState)(null),[g,u]=(0,Ce.useState)(!1),[c,h]=(0,Ce.useState)(!1),[s,l]=(0,Ce.useState)(null),d=(0,Ce.useRef)(void 0),f=(0,Ce.useCallback)(async()=>{if(!(!n||!e)){u(!0),l(null);try{await n.refreshTx(e,t);let y=n.getTxStatus(e,t);y&&a(y)}catch(y){l(y instanceof Error?y:new Error(String(y)))}finally{u(!1)}}},[n,e,t]),m=(0,Ce.useCallback)(()=>{!n||!e||(n.stopWatching(e,t),h(!1))},[n,e,t]);(0,Ce.useEffect)(()=>{if(!n||!e||!t){a(null),h(!1);return}d.current&&d.current!==e&&n.stopWatching(d.current),d.current=e;let y=!1;h(!0),u(!0),l(null);let E=n.getTxStatus(e,t);E&&(a(E),u(!1)),n.watchTx(e,t,{}).then(R=>{y||(a(R),u(!1))}).catch(R=>{y||(l(R instanceof Error?R:new Error(String(R))),u(!1))});let w=R=>{y||a({...R})};return n.on("statusChange",w),()=>{y=!0,h(!1),n.off("statusChange",w)}},[n,e,t]);let C=i?.status??"idle";return{entry:i,status:C,isLoading:g,isWatching:c,error:s,refresh:f,stopWatching:m}}function Xr(e){let t=bt(),r=e??t,[o,n]=(0,Ie.useState)(null),[i,a]=(0,Ie.useState)(null),[g,u]=(0,Ie.useState)(null),c=(0,Ie.useRef)(null),h=(0,Ie.useRef)(null),s=(0,Ie.useRef)(null);r&&(h.current||(h.current=d=>{a(d),(!c.current||d.createdAt>=c.current.createdAt)&&(n(d),c.current=d)},r.on("confirmed",h.current)),s.current||(s.current=d=>{u(d),(!c.current||d.createdAt>=c.current.createdAt)&&(n(d),c.current=d)},r.on("failed",s.current)));let l=(0,Ie.useCallback)(()=>{n(null),a(null),u(null),c.current=null},[]);return{lastTx:o,lastConfirmedTx:i,lastFailedTx:g,clear:l}}var Jr=require("react");var le=require("react"),Yr=require("@naculus/connect-appkit-core");function rn({input:e,skip:t=!1,resolverConfig:r,scope:o,query:n}){let[i,a]=(0,le.useState)(null),[g,u]=(0,le.useState)(!1),[c,h]=(0,le.useState)(null),s=(0,le.useRef)(0),l=(0,le.useRef)(!0);(0,le.useEffect)(()=>(l.current=!0,()=>{l.current=!1}),[]);let d=(0,le.useMemo)(()=>(0,Yr.getResolver)(r),[r]),f=(0,le.useCallback)(()=>{let m=e.trim();if(!m||t){s.current+=1,a(null),u(!1),h(null);return}let C=++s.current;u(!0),h(null),n(d,m,o).then(y=>{!l.current||C!==s.current||(a(y),u(!1))}).catch(y=>{!l.current||C!==s.current||(h(y instanceof Error?y:new Error(String(y))),a(null),u(!1))})},[e,t,o,d,n]);return(0,le.useEffect)(()=>{f()},[f]),{data:i,isLoading:g,error:c,refetch:f}}function Zr(e,t){let r=(0,Jr.useCallback)((o,n,i)=>o.lookupAddress(n,i),[]);return rn({input:e,skip:t?.skip,resolverConfig:t?.resolverConfig,scope:t?.chainId,query:r})}var G=require("react"),no=require("@naculus/connect-core"),ro=require("@naculus/connect-core"),Xs={telegram:!1,webpush:!1,inapp:!0,frequency:"final-only",mutedChains:[],mutedTypes:[]},eo="naculus_notif_react_settings";function oo(e){let t=(0,G.useRef)(null);t.current||(t.current=e?.channel??new no.InAppChannel);let r=t.current,[o,n]=(0,G.useState)(()=>r.getHistory()),[i,a]=(0,G.useState)(()=>Xs);(0,G.useEffect)(()=>{(e?.storage??to()).getItem(eo).then(E=>{E&&a(E)})},[]),(0,G.useEffect)(()=>(r.onNotification=y=>{n(E=>[...E,y])},r.restore().then(()=>{n(r.getHistory())}),()=>{r.onNotification=void 0}),[]);let g=(0,G.useMemo)(()=>o.filter(y=>!y.read).length,[o]),u=(0,G.useCallback)(()=>{r.clear(),n([])},[r]),c=(0,G.useCallback)(y=>{let E=r.getHistory().filter(w=>w.id!==y);r.clear(),Promise.all(E.map(w=>r.send({id:w.id,userId:"",txHash:w.txHash,chainId:"",chainName:w.chainName,status:w.status,title:w.title,body:w.body,valueFormatted:w.valueFormatted,explorerUrl:w.explorerUrl,timestamp:w.timestamp}))).then(()=>{n(r.getHistory())})},[r]),h=(0,G.useCallback)(y=>{r.markAsRead(y),n(E=>E.map(w=>w.id===y?{...w,read:!0}:w))},[r]),s=(0,G.useCallback)(()=>{r.markAllAsRead(),n(y=>y.map(E=>({...E,read:!0})))},[r]),l=(0,G.useCallback)(y=>{let E={...y,id:`notif_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now()};r.send({id:E.id,userId:"",txHash:E.txHash,chainId:"",chainName:E.chainName,status:E.status,title:E.title,body:E.body,valueFormatted:E.valueFormatted,explorerUrl:E.explorerUrl,timestamp:E.timestamp})},[r]),d=(0,G.useCallback)(y=>{a(E=>{let w={...E,...y};return(e?.storage??to()).setItem(eo,w).catch(()=>{}),w})},[e?.storage]),f=(0,G.useCallback)(y=>{let E={};y.includes("telegram")&&(E.telegram=!0),y.includes("webpush")&&(E.webpush=!0),y.includes("inapp")&&(E.inapp=!0),d(E)},[d]),m=(0,G.useCallback)(y=>{d({mutedChains:[...new Set([...i.mutedChains,y])]})},[i.mutedChains,d]),C=(0,G.useCallback)(y=>{d({mutedChains:i.mutedChains.filter(E=>E!==y)})},[i.mutedChains,d]);return{notifications:o,unreadCount:g,addNotification:l,clear:u,clearOne:c,markAsRead:h,markAllAsRead:s,settings:i,updateSettings:d,setChannels:f,muteChain:m,unmuteChain:C}}function to(){let e=(0,ro.createStorageAdapter)("local","naculus_notif_");return{getItem:async t=>{try{return await e.get(t)}catch(r){return console.warn("useNotification: failed to read from storage:",r),null}},setItem:async(t,r)=>{try{await e.set(t,r)}catch(o){console.warn("useNotification: failed to write to storage:",o)}},removeItem:async t=>{try{await e.remove(t)}catch(r){console.warn("useNotification: failed to remove from storage:",r)}}}}var pt=require("react");var so=()=>null,Ys=()=>()=>{};function ao(){let{client:e}=P(),t=M(e)?.passphraseGate??null,r=(0,pt.useSyncExternalStore)(t?.subscribe??Ys,t?.getSnapshot??so,so),o=(0,pt.useCallback)(a=>t?.submit(a),[t]),n=(0,pt.useCallback)(()=>t?.cancel(),[t]),i=(0,pt.useCallback)(a=>t?.forget(a),[t]);return{request:r,submit:o,cancel:n,forget:i,isUnlocked:t?.isUnlocked??!1,gate:t}}var io=require("react");function lo(e,t){let r=(0,io.useCallback)((o,n)=>o.resolveName(n),[]);return rn({input:e,skip:t?.skip,resolverConfig:t?.resolverConfig,query:r})}var ce=require("@naculus/connect-core"),oe=require("react"),co=require("@naculus/connect-appkit-core");function Js(e){if(!e)return null;let t=e.includes(":")?e.split(":").pop():e;return t&&/^0x[0-9a-fA-F]{40}$/.test(t)?t:null}function Gn(e){if(typeof e!="string"||!/^0x(?:[0-9a-fA-F]{2})+$/.test(e))throw new ce.WalletError("signature_rejected","Wallet returned an invalid UserOperation signature.");return e}async function Zs(e,t,r,o,n){let i=M(t);if(!i)throw new ce.WalletError("wallet_unavailable","Client not initialized");let a=[r,o];if(e.walletType==="eip6963"||e.id?.startsWith("eip6963-")){let{eip6963Connector:g}=await import("@naculus/connector-evm-injected"),u=g.getDiscoveredWallets().find(h=>h.id===e.walletId),c=u?await u.provider.request({method:"personal_sign",params:a}):await g.request({method:"personal_sign",params:a});return Gn(c)}if(e.walletType==="walletconnect")return Gn(await i.connector.request({method:"personal_sign",params:a}));if(e.walletType==="embedded"){let g=i.embeddedConnector;if(!g?.signHash)throw new ce.WalletError("method_unsupported","This embedded wallet build cannot sign a raw digest. Upgrade @naculus/connector-embedded or pass an explicit signer.");return Gn(await g.signHash(e,r))}throw e.walletType==="passkeys"?new ce.WalletError("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 ce.WalletError("method_unsupported",`Raw UserOperation signing is not available for ${e.walletType} on ${n}. Pass a signer that signs the raw 32-byte hash.`)}function uo(e){let{evmAccount:t}=$(),{session:r,chainId:o,client:n}=P(),[i,a]=(0,oe.useState)(null),[g,u]=(0,oe.useState)(null),[c,h]=(0,oe.useState)(!1),[s,l]=(0,oe.useState)(!1),[d,f]=(0,oe.useState)(null),m=(0,oe.useRef)(0),C=(0,oe.useRef)(!1);(0,oe.useEffect)(()=>()=>{m.current+=1,C.current=!1},[]),(0,oe.useEffect)(()=>{m.current+=1,C.current=!1,a(null),u(null),h(!1),l(!1),f(null)},[n,o,t,e?.accountType,e?.bundlerUrl,e?.chainId,e?.entryPoint,e?.owner,e?.rpcUrl,e?.salt,e?.signerMode,r]);let y=(0,oe.useCallback)(async(w,R)=>{let v=k=>(f(k),null);if(!e?.rpcUrl)return v(new Error("RPC URL not configured"));if(!e.bundlerUrl)return v(new Error("Bundler URL not configured"));if(!w.length)return v(new Error("At least one call is required"));if(C.current)return v(new Error("A UserOperation is already in progress"));let I=Js(e.owner??t);if(!I)return v(new ce.WalletError("wallet_unavailable","No EVM account found"));let A=(0,co.resolveEvmChainId)(e.chainId,o);if(!A)return v(new ce.WalletError("invalid_chain",e.chainId||o?`Invalid EVM chain ID: ${e.chainId??o}`:"No EVM chain to send on. Connect a wallet or pass options.chainId."));if(o&&o!==A)return v(new ce.WalletError("chain_mismatch",`Connected chain ${o} does not match UserOperation chain ${A}.`));if(!e.signer&&!r)return v(new ce.WalletError("wallet_unavailable","No active session"));let U=++m.current;C.current=!0,h(!0),l(!0),f(null),a(null),u(null);try{let{SmartAccountManager:k}=await import("@naculus/connect-core"),T=e.signer??(p=>Zs(r,n,p,I,A)),b=new k({rpcUrl:e.rpcUrl,bundlerClient:{url:e.bundlerUrl},chainId:A,signer:T,signerMode:e.signer?e.signerMode??"eip191":"raw"}),O={owner:I,accountType:e.accountType??"simple",entryPoint:e.entryPoint??ce.AA_SUPPORTED_CHAINS[A]?.entryPoint??ce.DEFAULT_ENTRY_POINT,chainId:A,salt:e.salt},_=await b.sendUserOperation(O,w,R);return U!==m.current?null:(l(!1),a(_.userOpHash),b.getUserOperationReceipt(_.userOpHash).then(p=>{U===m.current&&u(p)}).catch(()=>{}),_)}catch(k){if(U!==m.current)return null;let T=k instanceof Error?k:new Error("Failed to send UserOperation");return f(T),null}finally{U===m.current&&(h(!1),l(!1),C.current=!1)}},[n,o,t,e,r]),E=(0,oe.useCallback)(()=>{m.current+=1,C.current=!1,a(null),u(null),h(!1),l(!1),f(null)},[]);return{sendUserOp:y,userOpHash:i,receipt:g,isPending:c,isEstimating:s,error:d,reset:E}}var At=require("react");function ea(e,t){if(!e)return()=>{};let r=()=>t();return e.on("sessionConnected",r),e.on("sessionDisconnected",r),e.on("chainChanged",r),()=>{e.off("sessionConnected",r),e.off("sessionDisconnected",r),e.off("chainChanged",r)}}var Qn=Object.freeze({session:null,chainSessions:[],activeChainId:null,isConnected:!1,connectorId:null}),Xn=new WeakMap;function ta(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function na(e){if(!e)return Qn;let t=e.getActiveBundle(),r=Xn.get(e);if(!t)return r&&r.session===null?r:(Xn.set(e,Qn),Qn);let o=Array.from(t.chainSessions.values());if(r&&r.session===t.walletSession&&r.activeChainId===t.activeChainId&&ta(r.chainSessions,o))return r;let n={session:t.walletSession,chainSessions:o,activeChainId:t.activeChainId,isConnected:!0,connectorId:t.walletSession.walletType};return Xn.set(e,n),n}function po(e){let t=P(),r=e??t.sessionManager??null,o=(0,At.useCallback)(i=>ea(r,i),[r]),n=(0,At.useCallback)(()=>na(r),[r]);return(0,At.useSyncExternalStore)(o,n)}var Rt=require("@naculus/connect-core"),Ue=require("@naculus/siwx"),dt=require("react");var ra=86400;function oa(){return typeof window<"u"?window.location.host:"localhost"}function sa(){return typeof window<"u"?window.location.origin:"http://localhost"}function on(){let{session:e,chainId:t,client:r}=P(),[o,n]=(0,dt.useState)(!1),[i,a]=(0,dt.useState)(null),g=(0,dt.useCallback)(()=>a(null),[]);return{signIn:(0,dt.useCallback)(async c=>{if(!e)throw new Rt.WalletError("wallet_unavailable","No active session");let h=c?.chainId??t;if(!h)throw new Rt.WalletError("invalid_chain","No chain to sign for. Connect a wallet or pass options.chainId.");let s=Ye(e,h);if(!s)throw new Rt.WalletError("wallet_unavailable","No account found");let l=M(r);if(!l)throw new Rt.WalletError("wallet_unavailable","Client not initialized");let{address:d}=s,f=c?.domain??oa(),m=c?.uri??sa();n(!0),a(null);try{let C=(0,Ue.generateNonce)();await(0,Ue.issueNonce)(C);let y=(0,Ue.nowISO)(),E=c?.expirySeconds??ra,w=new Date(Date.now()+E*1e3).toISOString(),R=(0,Ue.createSiwxMessage)({domain:f,address:d,uri:m,version:1,chainId:h,nonce:C,issuedAt:y,expirationTime:w,statement:c?.statement,resources:c?.resources,requestId:c?.requestId}),v=await l.signMessage(e,{message:R,address:d,chainId:h??void 0}),I={message:{raw:R,domain:f,address:d,statement:c?.statement??null,uri:m,version:1,chainId:h,nonce:C,issuedAt:y,blockchain:(0,Ue.getBlockchainName)(h),expirationTime:w,notBefore:null,resources:c?.resources??[],requestId:c?.requestId??null},signature:v};return n(!1),I}catch(C){let y=C instanceof Error?C:new Error("SIWx sign-in failed");throw a(y),n(!1),y}},[e,t,r]),isSigningIn:o,error:i,clearError:g}}var sn=require("@naculus/connect-core"),Tt=require("@naculus/siwx"),se=require("react");function aa(){let e=new Uint8Array(8);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function mo(e){return{id:`siwx_${Date.now().toString(36)}_${aa()}`,chainId:e.message.chainId,address:e.message.address,domain:e.message.domain,message:e.message,signature:e.signature,issuedAt:e.message.issuedAt??new Date().toISOString(),expiresAt:e.message.expirationTime,refreshedAt:null}}function fo(e){let{storagePrefix:t="naculus_",autoRestore:r=!0,defaultExpirySeconds:o=86400}=e??{},[n,i]=(0,se.useState)(null),[a,g]=(0,se.useState)(r),[u,c]=(0,se.useState)(!1),[h,s]=(0,se.useState)(null),{session:l,chainId:d}=P(),f=on(),m=(0,se.useRef)((0,Tt.createLocalStorageSiwxSessionStorage)(`${t}siwx_session`)),C=(0,se.useCallback)(()=>s(null),[]);(0,se.useEffect)(()=>{if(!r){g(!1);return}let A=!1;return(async()=>{try{let k=await m.current.get();if(A)return;k?(sn.logger.info("react/useSIWxSession","Restored persisted SIWx session"),i(k),s(null)):i(null)}catch(U){sn.logger.warn("react/useSIWxSession","Failed to restore SIWx session:",U),i(null)}finally{A||g(!1)}})(),()=>{A=!0}},[r]),(0,se.useEffect)(()=>{if(!n?.expiresAt)return;let A=new Date(n.expiresAt).getTime()-Date.now();if(A<=0){i(null);return}let U=setTimeout(()=>{i(k=>k&&k.id===n.id?null:k)},A);return()=>clearTimeout(U)},[n?.id,n?.expiresAt]);let y=(0,se.useCallback)(async A=>{c(!0),s(null);try{let U={expirySeconds:o,chainId:d??void 0,...A},k=await f.signIn(U),T=mo(k);return await m.current.set(T),i(T),c(!1),T}catch(U){let k=U instanceof Error?U:new Error("SIWx sign-in failed");throw s(k),c(!1),k}},[f,d,o]),E=(0,se.useCallback)(async()=>{try{await m.current.remove()}catch(A){sn.logger.warn("react/useSIWxSession","Failed to clear session:",A)}i(null),s(null)},[]),w=(0,se.useCallback)(async()=>{if(!n)throw new Error("No active session to refresh");c(!0),s(null);try{let A=await f.signIn({domain:n.domain,statement:n.message.statement??void 0,uri:n.message.uri,chainId:n.chainId,expirySeconds:o,resources:n.message.resources.length>0?n.message.resources:void 0,requestId:n.message.requestId??void 0}),U={...mo(A),id:n.id,refreshedAt:new Date().toISOString()};return await m.current.set(U),i(U),c(!1),U}catch(A){let U=A instanceof Error?A:new Error("Session refresh failed");throw s(U),c(!1),U}},[n,f,o]),R=n!==null&&!(0,Tt.checkSessionExpired)(n),v=(0,Tt.checkSessionExpired)(n),I=n?.expiresAt?Math.max(0,new Date(n.expiresAt).getTime()-Date.now()):null;return{session:R?n:null,isAuthenticated:R,isRestoring:a,isSigningIn:u,isExpired:v,timeUntilExpiry:I,signIn:y,signOut:E,refresh:w,error:h,clearError:C}}var It=require("@naculus/connect-core"),Pe=require("@naculus/siwx"),$e=require("react");function ia(){return typeof window<"u"?window.location.host:"localhost"}function la(){return typeof window<"u"?window.location.origin:"http://localhost"}function mt(){let{session:e,chainId:t,client:r}=P(),[o,n]=(0,$e.useState)(!1),[i,a]=(0,$e.useState)(null),[g,u]=(0,$e.useState)(null),c=(0,$e.useCallback)(()=>u(null),[]);return{signIn:(0,$e.useCallback)(async s=>{if(!e)throw new It.WalletError("wallet_unavailable","No active session");let l=s?.chainId??t;if(!l)throw new It.WalletError("invalid_chain","No chain to sign for. Connect a wallet or pass options.chainId.");let d=Ye(e,l);if(!d)throw new It.WalletError("wallet_unavailable","No account found");let f=M(r);if(!f)throw new It.WalletError("wallet_unavailable","Client not initialized");let{address:m}=d,C=s?.domain??ia(),y=s?.uri??la();n(!0),u(null);try{let E=(0,Pe.generateNonce)();await(0,Pe.issueNonce)(E);let w=(0,Pe.nowISO)(),R=(0,Pe.createSiwxMessage)({domain:C,address:m,uri:y,version:1,chainId:l,nonce:E,issuedAt:w,statement:s?.statement,expirationTime:s?.expirySeconds?new Date(Date.now()+s.expirySeconds*1e3).toISOString():void 0,resources:s?.resources,requestId:s?.requestId}),v=await f.signMessage(e,{message:R,address:m,chainId:l??void 0}),I=s?.expirySeconds?new Date(Date.now()+s.expirySeconds*1e3).toISOString():null,A={message:{raw:R,domain:C,address:m,statement:s?.statement??null,uri:y,version:1,chainId:l,nonce:E,issuedAt:w,blockchain:(0,Pe.getBlockchainName)(l),expirationTime:I,notBefore:null,resources:s?.resources??[],requestId:s?.requestId??null},signature:v};return a(A),A}catch(E){let w=E instanceof Error?E:new Error("SIWx sign-in failed");throw u(w),w}finally{n(!1)}},[e,t,r]),isSigningIn:o,result:i,error:g,clearError:c}}var an=require("@naculus/connect-core");var Yn=require("react");function ca(){let{session:e,chainId:t}=P();return(0,Yn.useCallback)(r=>{if(!e)throw new an.WalletError("wallet_unavailable","No active session");let o=r??t;if(o&&!o.startsWith("eip155:"))throw new an.WalletError("namespace_mismatch",`Ethereum SIWx requires an eip155 chain, received ${o}`);let n=e.namespaces.eip155;if(!n||n.accounts.length===0)throw new an.WalletError("namespace_mismatch","No EVM (eip155) accounts found in session")},[e,t])}function go(){let e=ca(),t=mt();return{signIn:(0,Yn.useCallback)(async o=>(e(o?.chainId),t.signIn(o)),[e,t.signIn]),isSigningIn:t.isSigningIn,result:t.result,error:t.error,clearError:t.clearError}}var ho=require("@naculus/connect-core"),yo=require("@naculus/wallet-engine"),De=require("react");function Co(e){let t=e?.rpcUrl,r=e?.chainId,o=(0,De.useRef)(null);function n(){return o.current||(o.current=new yo.SimulationManager({enabled:!0,rpcUrl:t,autoSimulate:!1})),o.current}let[i,a]=(0,De.useState)(null),[g,u]=(0,De.useState)(!1),[c,h]=(0,De.useState)(null),s=(0,De.useCallback)(async(d,f,m,C,y)=>{u(!0),h(null);try{let E=n(),w=y?.chainId??r;if(w===void 0)throw new ho.WalletError("invalid_chain","No chain to simulate on. Connect a wallet or pass a chainId.");let R=y?.rpcUrl??t,v=await E.simulateERC20Transfer(d,f,m,C,w,y?.decimals,R);return a(v),v}catch(E){let w=E instanceof Error?E:new Error(String(E));throw h(w),w}finally{u(!1)}},[t,r]),l=(0,De.useCallback)(()=>{a(null),h(null),u(!1)},[]);return{result:i,loading:g,error:c,simulate:s,reset:l}}var de=require("react");var qe=require("@naculus/connect-core"),ln="siwx_auth";function ua(e){return new qe.LocalStorageAdapter(e)}function pa(e,t){return e.message.expirationTime?new Date(e.message.expirationTime).getTime()<=t.getTime():!1}function da(e,t){return e.message.notBefore?new Date(e.message.notBefore).getTime()<=t.getTime():!0}function So(e){let{storagePrefix:t="naculus_",autoRestore:r=!0}=e??{},[o,n]=(0,de.useState)(null),[i,a]=(0,de.useState)(r),[g,u]=(0,de.useState)(!1),[c,h]=(0,de.useState)(null),s=mt(),l=(0,de.useRef)(ua(t)),d=(0,de.useCallback)(()=>h(null),[]);(0,de.useEffect)(()=>{if(!r){a(!1);return}let C=!1;return(async()=>{try{let y=l.current,E=await y.get(ln);if(C)return;E&&!pa(E,new Date)&&da(E,new Date)?(qe.logger.info("react/useSiwxAuthSession","Restored persisted SIWx auth session"),n(E),h(null)):E&&(qe.logger.info("react/useSiwxAuthSession","Persisted SIWx auth expired, clearing"),await y.remove(ln))}catch(y){qe.logger.warn("react/useSiwxAuthSession","Failed to restore SIWx auth:",y)}finally{C||a(!1)}})(),()=>{C=!0}},[r]);let f=(0,de.useCallback)(async C=>{u(!0),h(null);try{let y=await s.signIn(C);return await l.current.set(ln,y),n(y),u(!1),y}catch(y){let E=y instanceof Error?y:new Error("SIWx sign-in failed");throw h(E),u(!1),E}},[s]),m=(0,de.useCallback)(async()=>{try{await l.current.remove(ln)}catch(C){qe.logger.warn("react/useSiwxAuthSession","Failed to clear SIWx auth:",C)}n(null),h(null)},[]);return{isSignedIn:o!==null,isRestoring:i,siwxResult:o,isSigningIn:g,error:c,signIn:f,signOut:m,clearError:d}}var Ve=require("@naculus/connect-core"),z=require("react"),Jn=require("@naculus/connect-appkit-core");function ma(e){if(!e)return null;let t=e.includes(":")?e.split(":").pop():e;return t&&/^0x[0-9a-fA-F]{40}$/.test(t)?t:null}function wo(e){return new Ve.WalletError("wallet_unavailable",e)}function Eo(e){let{evmAccount:t}=$(),{session:r,chainId:o,client:n}=P(),[i,a]=(0,z.useState)(null),[g,u]=(0,z.useState)(!1),[c,h]=(0,z.useState)(null),[s,l]=(0,z.useState)(!1),[d,f]=(0,z.useState)(null),m=(0,z.useRef)(null),C=(0,z.useRef)(0),y=(0,z.useRef)(!1);(0,z.useEffect)(()=>{if(m.current=null,!e?.rpcUrl)return;let k=!1;return import("@naculus/connect-core").then(({SmartAccountManager:T})=>{if(k)return;let b=(0,Jn.resolveEvmChainId)(e.chainId,o);b&&(m.current=new T({rpcUrl:e.rpcUrl,chainId:b,bundlerClient:{url:e.bundlerUrl??""}}))}).catch(T=>{k||f(T instanceof Error?T:new Error("Failed to load account-abstraction module"))}),()=>{k=!0}},[o,e?.rpcUrl,e?.bundlerUrl,e?.chainId]),(0,z.useEffect)(()=>{C.current+=1,y.current=!1,a(null),u(!1),h(null),l(!1),f(null)},[t,o,e?.rpcUrl,e?.bundlerUrl,e?.chainId,e?.entryPoint,e?.accountType,e?.salt]);let E=(0,z.useCallback)(()=>{let k=ma(t);if(!k||!m.current)return null;let T=(0,Jn.resolveEvmChainId)(e?.chainId,o);return T?{owner:k,accountType:e?.accountType??"simple",entryPoint:e?.entryPoint??Ve.AA_SUPPORTED_CHAINS[T]?.entryPoint??Ve.DEFAULT_ENTRY_POINT,chainId:T,salt:e?.salt}:null},[t,o,e?.accountType,e?.chainId,e?.entryPoint,e?.salt]),w=(0,z.useCallback)(k=>(f(k),null),[]),R=(0,z.useCallback)(()=>y.current?null:(y.current=!0,C.current),[]),v=(0,z.useCallback)(k=>{C.current===k&&(y.current=!1)},[]),I=(0,z.useCallback)(async()=>{let k=E();if(!k||!m.current)return w(new Error("Smart account not configured"));let T=R();if(T===null)return w(new Error("Smart account operation already in progress"));l(!0),f(null);try{let O=await m.current.createAccount(k);return C.current!==T?null:(a(O.address),u(O.isDeployed),h(O),O)}catch(b){if(C.current!==T)return null;let O=b instanceof Error?b:new Error("Failed to create smart account");return f(O),null}finally{C.current===T&&l(!1),v(T)}},[R,w,v,E]),A=(0,z.useCallback)(async()=>{let k=E();if(!k||!m.current)return w(new Error("Smart account not configured"));if(!r)return w(wo("No active session"));let T=M(n);if(!T)return w(wo("Client not initialized"));if(o&&o!==k.chainId)return w(new Ve.WalletError("chain_mismatch",`Connected chain ${o} does not match smart account chain ${k.chainId}.`));let b=R();if(b===null)return w(new Error("Smart account operation already in progress"));l(!0),f(null);try{let O=m.current,_=await O.createAccount(k);if(C.current!==b)return null;if(_.isDeployed)return a(_.address),u(!0),h(_),_.address;let p=await O.getDeployCallData(k),S=await T.sendTransaction(r,{transaction:{to:p.to,data:p.data,value:p.value.toString()},chainId:k.chainId});if(C.current!==b)return null;let x=await O.createAccount(k);return a(x.address),u(x.isDeployed),h(x),S}catch(O){if(C.current!==b)return null;let _=O instanceof Error?O:new Error("Failed to deploy smart account");return f(_),null}finally{C.current===b&&l(!1),v(b)}},[n,o,R,w,v,E,r]),U=(0,z.useCallback)(async()=>{let k=E();if(!k||!m.current)return null;let T=C.current;try{let b=await m.current.getAccountAddress(k);return C.current!==T?null:(a(b),b)}catch(b){return C.current!==T||f(b instanceof Error?b:new Error("Failed to get smart account address")),null}},[E]);return{address:i,isDeployed:g,accountInfo:c,isLoading:s,error:d,createWallet:I,deployWallet:A,getAddress:U}}var ko=require("react");function cn(){let{accounts:e,isConnected:t}=P();return(0,ko.useMemo)(()=>{if(!t)return{address:null,caip10:null,chainId:null,isConnected:!1};let r=e.find(a=>a.startsWith("solana:"))??null;if(!r)return{address:null,caip10:null,chainId:null,isConnected:t};let o=r.split(":"),n=o.length>=3?o[o.length-1]:null,i=o.length>=3?o.slice(0,-1).join(":"):null;return{address:n,caip10:r,chainId:i,isConnected:t}},[e,t])}var ve=require("react"),xo=require("@naculus/connect-core");function vo(e={}){let{client:t}=P(),{address:r}=cn(),o=e.address??r,n=e.rpcUrl??M(t)?.solanaRpcUrl??null,[i,a]=(0,ve.useState)(null),[g,u]=(0,ve.useState)(!1),[c,h]=(0,ve.useState)(null),s=(0,ve.useRef)(0),l=(0,ve.useCallback)(async()=>{if(!o||!n){a(null);return}let d=++s.current;u(!0),h(null);try{let f=await(0,xo.getSolanaBalance)(n,o);if(d!==s.current)return;a(f)}catch(f){if(d!==s.current)return;a(null),h(f instanceof Error?f:new Error("Balance read failed"))}finally{d===s.current&&u(!1)}},[o,n]);return(0,ve.useEffect)(()=>{l()},[l]),(0,ve.useEffect)(()=>{if(!e.refreshInterval||e.refreshInterval<=0)return;let d=setInterval(()=>{l()},e.refreshInterval);return()=>clearInterval(d)},[e.refreshInterval,l]),{balance:i,isFetching:g,error:c,isConfigured:!!n,refetch:l}}var bo=require("@naculus/connect-appkit-core"),Ao=require("react");function Ro(){let{client:e,session:t,accounts:r}=P();return(0,Ao.useMemo)(()=>{let o=M(e)?.solanaConnector,{roles:n,absence:i}=(0,bo.readSolanaRoles)(o,t);return{roles:n,absence:i,identity:n?.identity??null,signer:n?.signer??null,payer:n?.payer??null}},[e,t,r])}var Zn=require("@naculus/connect-core"),Be=require("react"),To=require("@naculus/connect-core");function Io(){let{client:e,session:t}=P(),[r,o]=(0,Be.useState)(!1),[n,i]=(0,Be.useState)(!1),[a,g]=(0,Be.useState)(null),u=()=>{let l=M(e);if(!l||!t)throw new Zn.WalletError("wallet_unavailable","No connected wallet.");return l},c=(0,Be.useCallback)(async l=>{o(!0),g(null);try{return await u().signTransaction(t,{transaction:l})}catch(d){let f=d instanceof Error?d:new Error("Signing failed");throw g(f),f}finally{o(!1)}},[e,t]),h=(0,Be.useCallback)(async l=>{i(!0),g(null);try{return await u().sendTransaction(t,{transaction:l})}catch(d){let f=d instanceof Error?d:new Error("Send failed");throw g(f),f}finally{i(!1)}},[e,t]),s=(0,Be.useCallback)(async l=>{let d=M(e)?.solanaRpcUrl;if(!d)throw new Zn.WalletError("no_rpc","Set solanaRpcUrl on the client to read a signature's status.");return(0,To.getSignatureStatus)(d,l)},[e]);return{signTransaction:c,sendTransaction:h,getStatus:s,isSigning:r,isSending:n,error:a,reset:()=>g(null)}}var ft=require("react"),Uo=require("@naculus/connect-appkit-core");function Po(){let{switchChain:e,chainId:t}=P(),[r,o]=(0,ft.useState)(!1),[n,i]=(0,ft.useState)(null),a=(0,ft.useCallback)(async u=>{o(!0),i(null);try{await e(u)}catch(c){let h=(0,Uo.toChainSwitchError)(c);throw i(h),h}finally{o(!1)}},[e]),g=(0,ft.useCallback)(()=>{i(null)},[]);return{switchChain:a,isSwitching:r,currentChainId:t,error:n,clearError:g}}var gt=require("@naculus/connect-appkit-core"),Y=require("react");var ht=require("viem");function Wo(e){let{evmAccount:t,isConnected:r}=$(),{chainId:o,chains:n}=P(),[i,a]=(0,Y.useState)([]),[g,u]=(0,Y.useState)(!1),[c,h]=(0,Y.useState)(null),{tokens:s,refreshInterval:l}=e,d=(0,Y.useRef)(null),f=(0,Y.useMemo)(()=>s.map(A=>A.address.toLowerCase()+"|"+A.decimals+"|"+A.symbol).join(","),[s]),m=(0,Y.useMemo)(()=>(0,gt.resolveChain)(n,o),[o,n]),C=m?(0,gt.chainNumber)(m):null,y=(0,Y.useMemo)(()=>m?(0,gt.toViemChain)(m,C):null,[m,C]),[E,w]=(0,Y.useState)(null);(0,Y.useEffect)(()=>{if(!y||!m?.rpcUrl){w(null);return}let A=(0,ht.createPublicClient)({transport:(0,ht.http)(m.rpcUrl),chain:y});w(A)},[m,y]);let R=[{name:"balanceOf",type:"function",stateMutability:"view",inputs:[{name:"owner",type:"address"}],outputs:[{name:"balance",type:"uint256"}]}],v=(0,Y.useCallback)(async()=>{if(!t||!E||s.length===0){a([]);return}u(!0),h(null);try{let A=t.includes(":")?t.split(":").pop():t,k=(await Promise.allSettled(s.map(async T=>{try{let b=await E.readContract({address:T.address,abi:R,functionName:"balanceOf",args:[A]});return{address:T.address,symbol:T.symbol,decimals:T.decimals,name:T.name,balance:b.toString(),formatted:(0,ht.formatUnits)(b,T.decimals)}}catch{return{address:T.address,symbol:T.symbol,decimals:T.decimals,name:T.name,balance:null,formatted:null}}}))).map(T=>T.status==="fulfilled"?T.value:{address:"",symbol:"?",decimals:0,balance:null,formatted:null});a(k)}catch(A){h(A instanceof Error?A:new Error("Failed to fetch token balances"))}finally{u(!1)}},[t,E,f]);(0,Y.useEffect)(()=>{r&&t&&s.length>0&&v()},[r,t,f,v]),(0,Y.useEffect)(()=>(l&&l>0&&r&&t&&s.length>0&&(d.current=setInterval(v,l)),()=>{d.current&&(clearInterval(d.current),d.current=null)}),[l,r,t,f,v]);let I=(0,Y.useCallback)(A=>i.find(U=>U.address.toLowerCase()===A.toLowerCase()),[i]);return{tokenBalances:i,isLoading:g,error:c,refetch:v,getTokenBalance:I,chain:m}}var be=require("react");function _o(e,t,r){let o=bt(),n=r??o,[i,a]=(0,be.useState)([]),[g,u]=(0,be.useState)(!1),[c,h]=(0,be.useState)(null),s=(0,be.useRef)(0),l=(0,be.useCallback)(async()=>{if(n){u(!0),h(null),s.current++;try{let f=await n.getTxHistory(e,t);a(f)}catch(f){h(f instanceof Error?f:new Error(String(f)))}finally{u(!1)}}},[n,e,t]);(0,be.useEffect)(()=>{l().catch(()=>{})},[l]),(0,be.useEffect)(()=>{if(!n)return;let f=()=>{l().catch(()=>{})};return n.on("statusChange",f),()=>{n.off("statusChange",f)}},[n,l]);let d={pending:i.filter(f=>f.status==="pending").length,confirmed:i.filter(f=>f.status==="confirmed").length,failed:i.filter(f=>f.status==="failed").length};return{entries:i,isLoading:g,error:c,refresh:l,summary:d}}var q=require("react"),Ae=class extends Error{constructor(t){super(t),this.name="InvalidUserOperationReceiptError"}};function Oo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function un(e){return typeof e=="string"&&/^0x[0-9a-fA-F]{40}$/.test(e)}function er(e){return typeof e=="string"&&/^0x[0-9a-fA-F]{64}$/.test(e)}function fa(e){return typeof e=="string"&&/^0x(?:[0-9a-fA-F]{2})*$/.test(e)}function tr(e,t){if(typeof e!="string"||!/^(?:0x(?:0|[1-9a-fA-F][0-9a-fA-F]*)|(?:0|[1-9][0-9]*))$/.test(e))throw new Ae(`Bundler returned an invalid ${t}.`);return BigInt(e)}function ga(e,t){if(!Oo(e))throw new Ae("Bundler returned an invalid UserOperation receipt.");if(!er(e.userOpHash)||e.userOpHash.toLowerCase()!==t.toLowerCase())throw new Ae("Bundler receipt does not match the requested UserOperation hash.");if(!un(e.entryPoint)||!un(e.sender))throw new Ae("Bundler receipt contains an invalid account address.");if(e.paymaster!==void 0&&e.paymaster!==null&&!un(e.paymaster))throw new Ae("Bundler receipt contains an invalid paymaster address.");if(typeof e.success!="boolean"||!er(e.transactionHash))throw new Ae("Bundler receipt contains an invalid execution result.");if(!Array.isArray(e.logs))throw new Ae("Bundler receipt contains invalid logs.");let r=e.logs.map(o=>{if(!Oo(o)||!un(o.address)||!Array.isArray(o.topics)||!o.topics.every(er)||!fa(o.data))throw new Ae("Bundler receipt contains an invalid log entry.");return{address:o.address,topics:o.topics,data:o.data}});return{userOpHash:e.userOpHash,entryPoint:e.entryPoint,sender:e.sender,nonce:tr(e.nonce,"nonce"),...e.paymaster===void 0||e.paymaster===null?{}:{paymaster:e.paymaster},actualGasUsed:tr(e.actualGasUsed,"actualGasUsed"),actualGasCost:tr(e.actualGasCost,"actualGasCost"),success:e.success,transactionHash:e.transactionHash,logs:r}}function No(e){let t=e?.bundlerUrl,r=e?.pollInterval??2e3,o=e?.maxRetries??30,[n,i]=(0,q.useState)("idle"),[a,g]=(0,q.useState)(null),[u,c]=(0,q.useState)(e?.userOpHash??null),[h,s]=(0,q.useState)(null),[l,d]=(0,q.useState)(!1),[f,m]=(0,q.useState)(0),C=(0,q.useRef)(0),[y,E]=(0,q.useState)(0),w=(0,q.useRef)(null),R=(0,q.useRef)(null),v=(0,q.useRef)(0),I=(0,q.useRef)(0),A=(0,q.useRef)(null),U=(0,q.useCallback)(()=>{w.current&&(clearInterval(w.current),w.current=null),R.current&&(clearTimeout(R.current),R.current=null)},[]),k=(0,q.useCallback)(async(_,p)=>{if(!t||p!==v.current)return;let S=I.current+1;I.current=S,m(S);let x=new AbortController;A.current=x;let W=L=>{p===v.current&&(i("not_found"),d(!1),U(),s(L))},N=L=>{if(p===v.current){if(S<=o){R.current=setTimeout(()=>{k(_,p)},r);return}W(L)}};try{let L=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getUserOperationReceipt",params:[_]}),signal:x.signal});if(p!==v.current)return;if(!L.ok)throw new Error(`Bundler returned HTTP ${L.status} while reading UserOperation status.`);let Q=await L.json();if(p!==v.current)return;if(Q.error)throw new Error(typeof Q.error.message=="string"?Q.error.message:"Bundler returned a JSON-RPC error.");if(Q.result!==void 0&&Q.result!==null){let Qe=ga(Q.result,_);g(Qe),i(Qe.success?"confirmed":"failed"),d(!1),U();return}i("pending"),N(new Error("UserOperation not included after maximum retries"))}catch(L){if(p!==v.current||x.signal.aborted)return;let Q=L instanceof Error?L:new Error("Unknown bundler response failure");if(Q instanceof Ae){W(Q);return}N(new Error(`UserOperation status unavailable after ${S} attempt${S===1?"":"s"}: ${Q.message}`))}finally{A.current===x&&(A.current=null)}},[t,r,o,U]),T=(0,q.useCallback)(_=>{v.current+=1;let p=v.current;if(A.current?.abort(),A.current=null,U(),c(_),g(null),s(null),I.current=0,m(0),E(0),C.current=Date.now(),!t){i("not_found"),d(!1),s(new Error("Bundler URL not configured"));return}i("pending"),d(!0),w.current=setInterval(()=>{E(Date.now()-C.current)},1e3),k(_,p)},[t,U,k]),b=(0,q.useCallback)(()=>{v.current+=1,A.current?.abort(),A.current=null,U(),d(!1)},[U]),O=(0,q.useCallback)(()=>{v.current+=1,A.current?.abort(),A.current=null,U(),c(null),i("idle"),g(null),s(null),d(!1),I.current=0,m(0),E(0)},[U]);return(0,q.useEffect)(()=>{e?.userOpHash&&e?.autoStart!==!1&&T(e.userOpHash)},[]),(0,q.useEffect)(()=>()=>{v.current+=1,A.current?.abort(),A.current=null,U()},[U]),{status:n,receipt:a,userOpHash:u,error:h,isPolling:l,elapsedMs:y,attempts:f,start:T,stop:b,reset:O}}var Bo=require("react");var ha={"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."},ya={"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"},Do={en:ha,zh:ya},nr="en";function Mo(e){nr=e}function Lo(){return nr}function ze(e){return Do[nr][e]??Do.en[e]??e}var Ho="0x0000000000000000000000000000000000000000",Ca=new Set([Ho,"0x0000000000000000000000000000000000000001","0x000000000000000000000000000000000000dead","0x000000000000000000000000000000000000dEaD"]);function Sa(e){let t=e.toLowerCase();return Ca.has(t)?!0:t.includes("dead")&&t.length>=40}function wa(e){return e===Ho}function Ea(e){return/^0x[0-9a-fA-F]{40}$/.test(e)}function rr(e){return e?Ea(e)?wa(e)?{isValid:!1,level:"blocked",warning:ze("address.zero_address")}:Sa(e)?{isValid:!1,level:"blocked",warning:ze("address.burn_address")}:{isValid:!0,level:"ok",warning:null}:{isValid:!1,level:"blocked",warning:ze("address.invalid_format")}:{isValid:!1,level:"blocked",warning:ze("address.empty")}}function Fo({address:e}){return{validation:(0,Bo.useMemo)(()=>rr(e),[e])}}function Ko(){let{status:e,session:t,accounts:r,chainId:o,error:n,connect:i,disconnect:a,reconnect:g,switchChain:u}=P(),c=e==="connected",h=e==="connecting",s=e==="reconnecting",l=r[0]??null;return{status:e,session:t,accounts:r,chainId:o,error:n,isConnected:c,isConnecting:h,isReconnecting:s,isDisconnected:e==="disconnected",currentAccount:l,connect:i,disconnect:a,reconnect:g,switchChain:u}}var je=require("react");var or={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"},sr={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."},Ut="Something went wrong",Pt="An unexpected error occurred. Please try again. If the problem persists, check your connection and wallet configuration.";function yt(e){if(!e)return{title:Ut,description:Pt};let t=e;if(t.name==="WalletError"&&t.code){let r=t.code,o=or[r]??Ut,n=sr[r]??t.message??Pt;return{title:o,description:n,code:r}}if(e instanceof Error){let r=e.message;return/user rejected/i.test(r)||/rejected/.test(r)?{title:"Request Rejected",description:"The request was declined.",code:"user_rejected"}:/timeout/i.test(r)||/timed? ?out/i.test(r)?{title:"Request Timed Out",description:"The request took too long. Please try again.",code:"deeplink_timeout"}:/insufficient funds/i.test(r)?{title:"Insufficient Funds",description:"You don't have enough funds to complete this transaction.",code:"tx_failed"}:/network/i.test(r)||/chain/i.test(r)?{title:"Network Error",description:r,code:"chain_unsupported"}:{title:Ut,description:r||Pt}}return typeof e=="string"?{title:Ut,description:e||Pt}:{title:Ut,description:Pt}}function pn(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 $o(){let{error:e,clearError:t}=P(),r=(0,je.useMemo)(()=>e?yt(e):null,[e]),o=(0,je.useMemo)(()=>e?pn(e):!1,[e]),n=(0,je.useCallback)(()=>{t()},[t]),i=(0,je.useCallback)(g=>yt(g),[]),a=(0,je.useCallback)(g=>async()=>{try{return await g()}catch(u){let c=yt(u);if(u instanceof Error){let h=u;try{h.title=c.title,h.friendlyMessage=c.description,h.code===void 0&&c.code!==void 0&&(h.code=c.code)}catch{}throw h}throw Object.assign(new Error(c.description,{cause:u}),{title:c.title,code:c.code,friendlyMessage:c.description})}},[]);return{error:e,friendlyError:r,clearError:n,isRetryable:o,formatError:i,wrapAsync:a}}var Se=require("react"),qo=require("@naculus/connect-core"),ar=require("@naculus/connect-appkit-core");function Wt(e,t){let r=(0,Se.useRef)(null),[o,n]=(0,Se.useState)([]),[i,a]=(0,Se.useState)(t?.autoLoad!==!1),[g,u]=(0,Se.useState)(!1),[c,h]=(0,Se.useState)(null);if(!r.current){let d={};t?.sources&&(d.sources=t.sources),r.current=new qo.TokenListManager(d)}let s=(0,Se.useCallback)(async()=>{let d=r.current;if(d){a(!0),h(null);try{await d.load();let f=e?(0,ar.eip155ChainIdToNumber)(e):void 0,m=d.getTokens(f!==void 0?{chainId:f}:void 0);n(m),u(!0)}catch(f){h(f instanceof Error?f:new Error(String(f)))}finally{a(!1)}}},[e]),l=(0,Se.useCallback)(async()=>{let d=r.current;if(d){a(!0),h(null);try{await d.refresh();let f=e?(0,ar.eip155ChainIdToNumber)(e):void 0,m=d.getTokens(f!==void 0?{chainId:f}:void 0);n(m),u(!0)}catch(f){h(f instanceof Error?f:new Error(String(f)))}finally{a(!1)}}},[e]);return(0,Se.useEffect)(()=>{t?.autoLoad!==!1&&s()},[s,t?.autoLoad]),{tokens:o,isLoading:i,isLoaded:g,error:c,refetch:l}}var Ge=require("react"),zo=require("@naculus/connect-core");var We=require("@naculus/connect-core");function Vo(){return[{name:"built-in",tokens:[...We.ETHEREUM_MAINNET_TOKENS,...We.POLYGON_TOKENS,...We.OPTIMISM_TOKENS,...We.ARBITRUM_TOKENS,...We.BASE_TOKENS],enabled:!0},{name:"uniswap-default",url:"https://tokens.uniswap.org",enabled:!0,refreshInterval:1440*60*1e3}]}var jo=require("@naculus/connect-appkit-core"),ka=300,dn=null;function xa(){return dn||(dn=new zo.TokenListManager({sources:Vo()}),dn.load().catch(()=>{})),dn}function _t(e,t){let[r,o]=(0,Ge.useState)({exact:[],fuzzy:[],hasMore:!1}),[n,i]=(0,Ge.useState)(!1),a=(0,Ge.useRef)(null),g=e.trim();return(0,Ge.useEffect)(()=>{if(!g){o({exact:[],fuzzy:[],hasMore:!1}),i(!1);return}return a.current&&clearTimeout(a.current),i(!0),a.current=setTimeout(()=>{let u=xa(),c=t?(0,jo.eip155ChainIdToNumber)(t):void 0,h=u.search(g,{chainId:c,limit:20});o(h),i(!1)},ka),()=>{a.current&&clearTimeout(a.current)}},[g,t]),{results:r,isSearching:n}}var Ct=Me(require("react"),1);var F=require("react/jsx-runtime");function ir({chainId:e,onSelect:t,onClose:r,options:o}){let[n,i]=Ct.default.useState(""),{tokens:a,isLoading:g,error:u}=Wt(e),{results:c,isSearching:h}=_t(n,n?e:void 0),s=o?.showRecommendations??!0,l=Ct.default.useMemo(()=>{if(n.trim()){let C=[...c.exact,...c.fuzzy].map(y=>y.token);return o?.filter?C.filter(o.filter):C}let m=a;return o?.filter?m.filter(o.filter):m},[n,c,a,o?.filter]),d=Ct.default.useMemo(()=>!s||n.trim()?[]:a.slice(0,6),[a,s,n]),f=(0,Ct.useCallback)(m=>{t(m),r()},[t,r]);return(0,F.jsxs)("div",{style:{background:"hsl(var(--background))",borderRadius:"12px",padding:"16px",color:"hsl(var(--foreground))",minWidth:"320px",maxWidth:"400px",fontFamily:"system-ui, sans-serif"},children:[(0,F.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"12px"},children:[(0,F.jsx)("h3",{style:{margin:0,fontSize:"16px",fontWeight:600},children:"Select Token"}),(0,F.jsx)("button",{onClick:r,style:{background:"none",border:"none",color:"hsl(var(--muted-foreground))",cursor:"pointer",fontSize:"18px",padding:"4px 8px"},children:"\u2715"})]}),(0,F.jsx)("input",{type:"text",placeholder:"Search token name or paste address",value:n,onChange:m=>i(m.target.value),style:{width:"100%",padding:"10px 12px",borderRadius:"8px",border:"1px solid #333",background:"hsl(var(--card))",color:"hsl(var(--foreground))",fontSize:"14px",outline:"none",boxSizing:"border-box",marginBottom:"12px"},autoFocus:!0}),g&&!h&&(0,F.jsx)("div",{style:{textAlign:"center",padding:"20px",color:"hsl(var(--muted-foreground))"},children:"Loading tokens..."}),u&&(0,F.jsxs)("div",{style:{textAlign:"center",padding:"12px",color:"hsl(var(--destructive))",fontSize:"13px"},children:["Error: ",u.message]}),s&&d.length>0&&!n.trim()&&(0,F.jsxs)("div",{style:{marginBottom:"12px"},children:[(0,F.jsx)("div",{style:{fontSize:"11px",color:"hsl(var(--muted-foreground))",textTransform:"uppercase",letterSpacing:"0.5px",marginBottom:"8px"},children:"Popular"}),(0,F.jsx)("div",{style:{display:"flex",gap:"6px",flexWrap:"wrap"},children:d.map(m=>(0,F.jsxs)("button",{onClick:()=>f(m),style:{background:"hsl(var(--card))",border:"1px solid #333",borderRadius:"20px",padding:"6px 14px",color:"hsl(var(--foreground))",cursor:"pointer",fontSize:"13px",display:"flex",alignItems:"center",gap:"4px"},children:[m.logoURI?(0,F.jsx)("img",{src:m.logoURI,alt:"",style:{width:"16px",height:"16px",borderRadius:"50%"},onError:C=>{C.target.style.display="none"}}):null,m.symbol]},`${m.chainId}:${m.address}`))})]}),n.trim()&&!g&&(0,F.jsx)("div",{style:{fontSize:"11px",color:"hsl(var(--muted-foreground))",marginBottom:"8px"},children:l.length>0?(0,F.jsxs)(F.Fragment,{children:[c.exact.length," exact, ",c.fuzzy.length," fuzzy",c.hasMore?" (more available)":""]}):"No results found"}),(0,F.jsx)("div",{style:{maxHeight:"320px",overflowY:"auto",display:"flex",flexDirection:"column",gap:"2px"},children:l.map(m=>(0,F.jsxs)("button",{onClick:()=>f(m),style:{display:"flex",alignItems:"center",gap:"10px",padding:"10px 8px",background:"transparent",border:"none",borderRadius:"8px",color:"hsl(var(--foreground))",cursor:"pointer",textAlign:"left",width:"100%",fontSize:"14px"},onMouseEnter:C=>{C.target.style.background="hsl(var(--card))"},onMouseLeave:C=>{C.target.style.background="transparent"},children:[(0,F.jsx)("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?(0,F.jsx)("img",{src:m.logoURI,alt:m.symbol,style:{width:"100%",height:"100%"},onError:C=>{let y=C.target;y.style.display="none",y.parentElement.textContent=m.symbol.slice(0,2)}}):m.symbol.slice(0,2)}),(0,F.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,F.jsx)("div",{style:{fontWeight:600,fontSize:"14px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m.symbol}),(0,F.jsx)("div",{style:{fontSize:"12px",color:"hsl(var(--muted-foreground))",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m.name})]}),(0,F.jsxs)("div",{style:{fontSize:"11px",color:"#666",textAlign:"right",flexShrink:0},children:[(0,F.jsxs)("div",{children:[m.decimals," decimals"]}),(0,F.jsxs)("div",{children:["Chain ",m.chainId]})]})]},`${m.chainId}:${m.address}`))})]})}var B=require("@stencil/react-output-target/runtime"),H=Me(require("react"),1),mn=require("@naculus/connect-appkit-wc/dist/components/appkit-accordion.js"),fn=require("@naculus/connect-appkit-wc/dist/components/appkit-account-button.js"),gn=require("@naculus/connect-appkit-wc/dist/components/appkit-alert-dialog.js"),hn=require("@naculus/connect-appkit-wc/dist/components/appkit-avatar.js"),yn=require("@naculus/connect-appkit-wc/dist/components/appkit-badge.js"),Cn=require("@naculus/connect-appkit-wc/dist/components/appkit-button.js"),Sn=require("@naculus/connect-appkit-wc/dist/components/appkit-card-content.js"),wn=require("@naculus/connect-appkit-wc/dist/components/appkit-card-description.js"),En=require("@naculus/connect-appkit-wc/dist/components/appkit-card-footer.js"),kn=require("@naculus/connect-appkit-wc/dist/components/appkit-card-header.js"),xn=require("@naculus/connect-appkit-wc/dist/components/appkit-card-title.js"),vn=require("@naculus/connect-appkit-wc/dist/components/appkit-card.js"),bn=require("@naculus/connect-appkit-wc/dist/components/appkit-checkbox.js"),An=require("@naculus/connect-appkit-wc/dist/components/appkit-collapsible.js"),Rn=require("@naculus/connect-appkit-wc/dist/components/appkit-connect-button.js"),Tn=require("@naculus/connect-appkit-wc/dist/components/appkit-dialog.js"),In=require("@naculus/connect-appkit-wc/dist/components/appkit-dropdown-menu.js"),Un=require("@naculus/connect-appkit-wc/dist/components/appkit-input.js"),Pn=require("@naculus/connect-appkit-wc/dist/components/appkit-popover.js"),Wn=require("@naculus/connect-appkit-wc/dist/components/appkit-progress.js"),_n=require("@naculus/connect-appkit-wc/dist/components/appkit-scroll-area.js"),On=require("@naculus/connect-appkit-wc/dist/components/appkit-select.js"),Nn=require("@naculus/connect-appkit-wc/dist/components/appkit-separator.js"),Dn=require("@naculus/connect-appkit-wc/dist/components/appkit-skeleton.js"),Mn=require("@naculus/connect-appkit-wc/dist/components/appkit-switch.js"),Ln=require("@naculus/connect-appkit-wc/dist/components/appkit-tabs.js"),Bn=require("@naculus/connect-appkit-wc/dist/components/appkit-toggle-group.js"),Hn=require("@naculus/connect-appkit-wc/dist/components/appkit-tooltip.js"),Go=(0,B.createComponent)({tagName:"appkit-accordion",elementClass:mn.AppkitAccordion,react:H.default,events:{onAppkitToggle:"appkitToggle"},defineCustomElement:mn.defineCustomElement}),Qo=(0,B.createComponent)({tagName:"appkit-account-button",elementClass:fn.AppkitAccountButton,react:H.default,events:{},defineCustomElement:fn.defineCustomElement}),Xo=(0,B.createComponent)({tagName:"appkit-alert-dialog",elementClass:gn.AppkitAlertDialog,react:H.default,events:{onAppkitClose:"appkitClose",onAppkitOpenChange:"appkitOpenChange"},defineCustomElement:gn.defineCustomElement}),Yo=(0,B.createComponent)({tagName:"appkit-avatar",elementClass:hn.AppkitAvatar,react:H.default,events:{},defineCustomElement:hn.defineCustomElement}),Jo=(0,B.createComponent)({tagName:"appkit-badge",elementClass:yn.AppkitBadge,react:H.default,events:{},defineCustomElement:yn.defineCustomElement}),Zo=(0,B.createComponent)({tagName:"appkit-button",elementClass:Cn.AppkitButton,react:H.default,events:{},defineCustomElement:Cn.defineCustomElement}),es=(0,B.createComponent)({tagName:"appkit-card",elementClass:vn.AppkitCard,react:H.default,events:{},defineCustomElement:vn.defineCustomElement}),ts=(0,B.createComponent)({tagName:"appkit-card-content",elementClass:Sn.AppkitCardContent,react:H.default,events:{},defineCustomElement:Sn.defineCustomElement}),ns=(0,B.createComponent)({tagName:"appkit-card-description",elementClass:wn.AppkitCardDescription,react:H.default,events:{},defineCustomElement:wn.defineCustomElement}),rs=(0,B.createComponent)({tagName:"appkit-card-footer",elementClass:En.AppkitCardFooter,react:H.default,events:{},defineCustomElement:En.defineCustomElement}),os=(0,B.createComponent)({tagName:"appkit-card-header",elementClass:kn.AppkitCardHeader,react:H.default,events:{},defineCustomElement:kn.defineCustomElement}),ss=(0,B.createComponent)({tagName:"appkit-card-title",elementClass:xn.AppkitCardTitle,react:H.default,events:{},defineCustomElement:xn.defineCustomElement}),as=(0,B.createComponent)({tagName:"appkit-checkbox",elementClass:bn.AppkitCheckbox,react:H.default,events:{onAppkitChange:"appkitChange"},defineCustomElement:bn.defineCustomElement}),is=(0,B.createComponent)({tagName:"appkit-collapsible",elementClass:An.AppkitCollapsible,react:H.default,events:{onAppkitToggle:"appkitToggle"},defineCustomElement:An.defineCustomElement}),ls=(0,B.createComponent)({tagName:"appkit-connect-button",elementClass:Rn.AppkitConnectButton,react:H.default,events:{onAppkitConnect:"appkitConnect",onAppkitDisconnect:"appkitDisconnect",onAppkitStartPairing:"appkitStartPairing",onAppkitRetry:"appkitRetry",onAppkitCancelPairing:"appkitCancelPairing",onAppkitMobileDeepLink:"appkitMobileDeepLink",onAppkitCopyAddress:"appkitCopyAddress"},defineCustomElement:Rn.defineCustomElement}),cs=(0,B.createComponent)({tagName:"appkit-dialog",elementClass:Tn.AppkitDialog,react:H.default,events:{onAppkitClose:"appkitClose",onAppkitOpenChange:"appkitOpenChange"},defineCustomElement:Tn.defineCustomElement}),us=(0,B.createComponent)({tagName:"appkit-dropdown-menu",elementClass:In.AppkitDropdownMenu,react:H.default,events:{onAppkitSelect:"appkitSelect"},defineCustomElement:In.defineCustomElement}),ps=(0,B.createComponent)({tagName:"appkit-input",elementClass:Un.AppkitInput,react:H.default,events:{onAppkitChange:"appkitChange"},defineCustomElement:Un.defineCustomElement}),ds=(0,B.createComponent)({tagName:"appkit-popover",elementClass:Pn.AppkitPopover,react:H.default,events:{onAppkitOpenChange:"appkitOpenChange"},defineCustomElement:Pn.defineCustomElement}),ms=(0,B.createComponent)({tagName:"appkit-progress",elementClass:Wn.AppkitProgress,react:H.default,events:{},defineCustomElement:Wn.defineCustomElement}),fs=(0,B.createComponent)({tagName:"appkit-scroll-area",elementClass:_n.AppkitScrollArea,react:H.default,events:{},defineCustomElement:_n.defineCustomElement}),gs=(0,B.createComponent)({tagName:"appkit-select",elementClass:On.AppkitSelect,react:H.default,events:{onAppkitChange:"appkitChange"},defineCustomElement:On.defineCustomElement}),hs=(0,B.createComponent)({tagName:"appkit-separator",elementClass:Nn.AppkitSeparator,react:H.default,events:{},defineCustomElement:Nn.defineCustomElement}),ys=(0,B.createComponent)({tagName:"appkit-skeleton",elementClass:Dn.AppkitSkeleton,react:H.default,events:{},defineCustomElement:Dn.defineCustomElement}),Cs=(0,B.createComponent)({tagName:"appkit-switch",elementClass:Mn.AppkitSwitch,react:H.default,events:{onAppkitChange:"appkitChange"},defineCustomElement:Mn.defineCustomElement}),Ss=(0,B.createComponent)({tagName:"appkit-tabs",elementClass:Ln.AppkitTabs,react:H.default,events:{onAppkitTabChange:"appkitTabChange"},defineCustomElement:Ln.defineCustomElement}),ws=(0,B.createComponent)({tagName:"appkit-toggle-group",elementClass:Bn.AppkitToggleGroup,react:H.default,events:{onAppkitChange:"appkitChange"},defineCustomElement:Bn.defineCustomElement}),Es=(0,B.createComponent)({tagName:"appkit-tooltip",elementClass:Hn.AppkitTooltip,react:H.default,events:{},defineCustomElement:Hn.defineCustomElement});0&&(module.exports={AppkitAccordion,AppkitAccountButton,AppkitAlertDialog,AppkitAvatar,AppkitBadge,AppkitButton,AppkitCard,AppkitCardContent,AppkitCardDescription,AppkitCardFooter,AppkitCardHeader,AppkitCardTitle,AppkitCheckbox,AppkitCollapsible,AppkitConnectButton,AppkitDialog,AppkitDropdownMenu,AppkitInput,AppkitPopover,AppkitProgress,AppkitScrollArea,AppkitSelect,AppkitSeparator,AppkitSkeleton,AppkitSwitch,AppkitTabs,AppkitToggleGroup,AppkitTooltip,DEFAULT_EVM_CHAINS,LAMPORTS_PER_SOL,PassphraseCancelledError,PassphraseGate,SolanaRpcError,TokenSelector,TxMonitorContext,WALLET_ERROR_DESCRIPTIONS,WALLET_ERROR_TITLES,Web3ConnectProvider,Web3Context,buildDelegationPolicyMessage,clearClient,createClient,formatSol,getChainById,getClient,getDefaultChains,getLatestBlockhash,getLocale,getSignatureStatus,getSolanaBalance,getUserFriendlyError,isRetryableError,parseSol,resetSessionKeyManager,setLocale,t,useAccount,useBalance,useCapabilities,useChain,useCompareCosts,useConnect,useCreateSessionKey,useDelegation,useDelegationPolicy,useDisconnect,useERC20Allowance,useERC20Approve,useERC20Transfer,useERC20TransferSimulation,useEmbeddedWallet,useExecuteCalls,useExecuteRoute,useLastTx,useLookupAddress,useNotification,usePassphraseGate,useResolveName,useRevokeSession,useRouteQuote,useSIWxLogin,useSIWxSession,useSendCalls,useSendTransaction,useSendUserOperation,useSendWithSession,useSession,useSessionKeys,useSignInWithEthereum,useSignInWithX,useSignMessage,useSimulateTransfer,useSiwxAuthSession,useSmartAccount,useSolanaAccount,useSolanaBalance,useSolanaRoles,useSolanaTransaction,useSwitchChain,useTokenBalance,useTokenList,useTokenSearch,useTransactionSimulation,useTxHistory,useTxMonitor,useUserOpStatus,useValidateDestination,useViemClient,useWallet,useWeb3,useWeb3ErrorHandler,validateDestination});
|
|
3
3
|
//# sourceMappingURL=index.cjs.map
|