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