@ninsei-labs/sdk 0.56.1 → 0.58.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/LICENSE-POLICY.md +9 -2
- package/README.md +78 -28
- package/THIRD_PARTY_NOTICES.md +176 -2
- package/assets/vendors/MANIFEST.json +1 -13
- package/assets/vendors/sdk/sdk-browser.js +5 -4
- package/engine/atomic/dleq2.js +116 -15
- package/engine/atomic/order.js +21 -3
- package/engine/core/config.js +20 -46
- package/engine/core/deployments.generated.js +103 -0
- package/engine/core/rfqSource.js +6 -133
- package/engine/core/swap.js +8 -8
- package/engine/evm/asyncRoute.js +1 -1
- package/engine/evm/claimGas.js +2 -1
- package/engine/evm/escrow.js +13 -8
- package/engine/evm/factory.js +11 -6
- package/engine/evm/funding.js +8 -3
- package/engine/evm/index.js +5 -6
- package/engine/evm/session.js +48 -279
- package/engine/monero/address.js +15 -33
- package/engine/monero/keys.js +124 -0
- package/engine/monero/mnemonic.js +104 -0
- package/engine/monero/scan.js +121 -28
- package/engine/monero/wallet.js +31 -68
- package/engine/monero/wordlist.en.js +210 -0
- package/engine/recovery/restore.js +9 -9
- package/engine/sdk/bridge.js +9 -187
- package/engine/ui/walletModal.js +7 -27
- package/index.d.ts +234 -262
- package/package.json +7 -6
- package/src/actions.mjs +8 -5
- package/src/codes.mjs +17 -0
- package/src/config.mjs +17 -54
- package/src/engine.mjs +9 -6
- package/src/feeEstimate.mjs +11 -4
- package/src/http.mjs +4 -1
- package/src/index.mjs +24 -45
- package/src/legs/kyber.mjs +23 -0
- package/src/lock.mjs +1 -0
- package/src/order.mjs +110 -22
- package/src/primitives.mjs +4 -5
- package/src/probes.mjs +9 -3
- package/src/public/networks.d.ts +45 -0
- package/src/public/networks.mjs +10 -1
- package/src/public/recovery.d.ts +17 -1
- package/src/public/recovery.mjs +1 -0
- package/src/public/xmr.mjs +1 -1
- package/src/quotePolicy.mjs +25 -0
- package/src/quotes.mjs +109 -765
- package/src/readyWindow.mjs +76 -0
- package/src/recovery-key.mjs +71 -16
- package/src/recovery.mjs +11 -28
- package/src/relayClaim.mjs +132 -0
- package/src/relayFeatures.mjs +25 -13
- package/src/relayFirmClient.mjs +36 -7
- package/src/relayQuote.mjs +92 -11
- package/src/relayView.mjs +3 -3
- package/src/swap-flow.mjs +146 -60
- package/src/swaps.mjs +521 -357
- package/src/sweep-action.mjs +73 -0
- package/src/sweep-restore.mjs +8 -4
- package/src/sweep.mjs +12 -2
- package/src/version.mjs +1 -1
- package/src/xmr-arrival.mjs +328 -29
- package/src/xmrAmountPolicy.mjs +35 -0
- package/assets/vendors/atomic/atomic-browser.js +0 -24
- package/assets/vendors/monero/monero-js-browser.js +0 -58
- package/assets/vendors/monero-js/LICENSE +0 -9
- package/assets/vendors/walletconnect/wc-browser.js +0 -6202
- package/engine/atomic/order-client.js +0 -56
- package/engine/atomic/order-worker.js +0 -156
- package/engine/evm/asyncExec.js +0 -577
- package/engine/evm/asyncLegs.js +0 -308
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
var bx=Object.defineProperty;var re=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Be=(e,t)=>{for(var n in t)bx(e,n,{get:t[n],enumerable:!0})};var oe={};Be(oe,{ALLOWED_PROVIDERS:()=>Yf,API:()=>Zt,APP:()=>Ao,ASYNC_ROUTE_PROVIDERS:()=>zi,CHAINS:()=>Mt,DEFAULT_CHAIN:()=>Nt,DEMO:()=>Jt,DEX_ASSETS:()=>Xf,DEX_CHAINS:()=>kx,DEX_HUBS:()=>Sx,DEX_PRICE_GATE:()=>vx,DEX_ROUTES:()=>Ex,ENDPOINTS:()=>$i,EVM:()=>Yn,KNOWN_FACTORY_CODES:()=>Gf,MONERO:()=>ve,SCENARIO_LABELS:()=>Tx,SIGNING_DOMAIN:()=>xx,SIGNING_GUARDS:()=>_o,SWEEP:()=>bc,TEST_CLAIMER:()=>Nx,TIMING:()=>It,XMR_NETWORKS:()=>Qf,allowedProvidersFor:()=>gc,chainByChainId:()=>Sc,chainById:()=>Je,knownFactoryCodesFor:()=>xc,knownImplementationCodesFor:()=>kc,nativeOf:()=>qf,sweepOrigin:()=>Ix,tokenById:()=>_x,tokensOf:()=>vc,wrappedNativeOf:()=>Ax});function gc(e){let t=typeof e=="string"?e:e&&e.id,n=Yf[t];return!Array.isArray(n)||n.length===0?null:n.map(r=>String(r).toLowerCase())}function xc(e){let t=typeof e=="string"?e:e&&e.id,n=Gf[t];return!Array.isArray(n)||n.length===0?null:n.map(r=>String(r).toLowerCase())}function kc(e){let t=typeof e=="string"?e:e&&e.id,n=Mt.find(o=>o.id===t)||Je(t),r=n&&n.escrow?n.escrow.implementationCodeHash:null;return typeof r!="string"||!/^0x[0-9a-fA-F]{64}$/.test(r)?null:[r.toLowerCase()]}function Je(e){return Mt.find(t=>t.id===e)||Mt.find(t=>t.id===Nt)||Mt[0]}function Sc(e){return Mt.find(t=>t.chainId===Number(e))||null}function vc(e){let t=Je(e);return[qf(e),...t.tokens]}function qf(e){let t=Je(e);return{symbol:t.native.symbol,label:t.native.symbol,address:null,decimals:t.native.decimals,usd:t.native.usd,cls:"ar-token-eth",native:!0}}function Ax(e){return(Je(e).tokens||[]).find(n=>n&&n.peg==="native")||null}function _x(e,t){let n=e,r=t;typeof e=="string"&&e.includes(":")&&([n,r]=e.split(":"));let o=vc(n);return o.find(i=>i.symbol===String(r).toUpperCase())||o[0]}function Ix(){let e=typeof location<"u"?location.hostname:"";return/^(localhost|127\.0\.0\.1|\[::1\])$/.test(e)||/\.local$/.test(e)?bc.localOrigin:bc.origin}var Sr,vr,yc,$i,gx,xx,Ao,kx,Xf,Sx,vx,_o,Ex,zi,Mt,Nt,Yf,Gf,Nx,ve,Zt,Qf,bc,Yn,It,Jt,Tx,mt=re(()=>{Sr=typeof window<"u"&&window.NINSEI_DEPLOY?window.NINSEI_DEPLOY:null,vr=typeof process<"u"&&process.env?process.env:null,yc=Object.freeze({moneroNode:"http://127.0.0.1:38081",evmRpc:"http://127.0.0.1:8545",sweepOrigin:"http://localhost:5195"}),$i=Object.freeze({moneroNode:Sr&&Sr.moneroNode||vr&&vr.NINSEI_MONERO_NODE||yc.moneroNode,evmRpc:Sr&&Sr.evmRpc||vr&&vr.NINSEI_EVM_RPC||yc.evmRpc,sweepOrigin:Sr&&Sr.sweepOrigin||vr&&vr.NINSEI_SWEEP_ORIGIN||yc.sweepOrigin}),gx=typeof location<"u"?location.origin:"",xx=Object.freeze({name:"NinseiEscrowFactory",version:"1"}),Ao={name:"NinseiSwap",version:"0.1.0",demo:!0,storageKey:"ninsei.demo.v1"},kx=["arbitrum-sepolia","arbitrum","mainnet"],Xf=["USDT","USDC","DAI","USDS","USDe","PyUSD"],Sx=["USDC","USDT","DAI"],vx={maxDeviationPct:2,stableBandPct:1,stables:Xf},_o={minReadyLeadSec:600,minClaimWindowSec:600,maxDeadlineSec:259200,readyLeadWarnSec:600},Ex={"arbitrum-sepolia":{USDC:{steps:[{to:"WETH",fee:3e3,pool:"0x66eeab70ac52459dd74c6ad50d578ef76a441bbf",verified:{at:"2026-09-23",block:311900041}}]}},arbitrum:{USDT:{steps:[{to:"WETH",fee:500,pool:"0x641c00a822e8b671738d32a431a4fb6074e5c79d",verified:{at:"2026-09-23",block:508125577}}]},USDC:{steps:[{to:"WETH",fee:100,pool:"0x6f38e884725a116c9c7fbf208e79fe8828a2595f",verified:{at:"2026-09-23",block:508125577}}]},DAI:{steps:[{to:"WETH",fee:3e3,pool:"0xa961f0473da4864c5ed28e00fcc53a3aab056c1b",verified:{at:"2026-09-23",block:508125577}}]},USDe:{steps:[{to:"USDC",fee:100,pool:"0x3223859e24d5413947761cb79d3094f21be69bfa",verified:{at:"2026-09-23",block:508125577}},{to:"WETH",fee:100,pool:"0x6f38e884725a116c9c7fbf208e79fe8828a2595f",verified:{at:"2026-09-23",block:508125577}}]},WETH:{steps:[],unwrap:!0}},mainnet:{USDT:{steps:[{to:"WETH",fee:500,pool:"0x11b815efb8f581194ae79006d24e0d814b7697f6",verified:{at:"2026-09-23",block:26040283}}]},USDC:{steps:[{to:"WETH",fee:100,pool:"0xe0554a476a092703abdb3ef35c80e0d76d32939f",verified:{at:"2026-09-23",block:26040283}}]},DAI:{steps:[{to:"WETH",fee:500,pool:"0x60594a405d53811d3bc4766596efd80fd545a270",verified:{at:"2026-09-23",block:26040283}}]},USDe:{steps:[{to:"USDC",fee:100,pool:"0xe6d7ebb9f1a9519dc06d557e03c522d53520e76a",verified:{at:"2026-09-23",block:26040283}},{to:"WETH",fee:100,pool:"0xe0554a476a092703abdb3ef35c80e0d76d32939f",verified:{at:"2026-09-23",block:26040283}}]},USDS:{steps:[{to:"USDC",fee:3e3,pool:"0xa66a2770bc0e0c65b63b5a3bb4560e90f95d6146",verified:{at:"2026-09-23",block:26040283}},{to:"WETH",fee:100,pool:"0xe0554a476a092703abdb3ef35c80e0d76d32939f",verified:{at:"2026-09-23",block:26040283}}]},PyUSD:{steps:[{to:"USDC",fee:100,pool:"0x13394005c1012e708fce1eb974f1130fdc73a5ce",verified:{at:"2026-09-23",block:26040283}},{to:"WETH",fee:100,pool:"0xe0554a476a092703abdb3ef35c80e0d76d32939f",verified:{at:"2026-09-23",block:26040283}}]},WETH:{steps:[],unwrap:!0}}},zi={cowswap:{venue:"CoWSwap",shape:"async",settles:"native",networks:{1:{slug:"mainnet",orderbook:"https://api.cow.fi/mainnet"},100:{slug:"xdai",orderbook:"https://api.cow.fi/xdai"},42161:{slug:"arbitrum_one",orderbook:"https://api.cow.fi/arbitrum_one"},8453:{slug:"base",orderbook:"https://api.cow.fi/base"},56:{slug:"bnb",orderbook:"https://api.cow.fi/bnb"},11155111:{slug:"sepolia",orderbook:"https://api.cow.fi/sepolia"}}},kyberswap:{venue:"KyberSwap Limit Order",shape:"async",settles:"wrapped",networks:{1:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},10:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},56:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},137:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},250:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},324:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},5e3:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},8453:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},42161:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},43114:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},59144:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},534352:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},81457:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"}}},uniswapx:{venue:"UniswapX",shape:"async",settles:"native",networks:{1:{orderbook:"https://api.uniswap.org/v2",reactor:"0x00000011F84B9aa48e5f8aA8B9897600006289Be",submitter:"/api/uniswapx/order"}}},uniswaprelay:{venue:"Uniswap Relay",shape:"async",settles:"native",networks:{1:{reactor:"0x0000000000A4e21E2597DCac987455c48b12edBF",universalRouter:"0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD"}}}},Mt=[{id:"arbitrum-sepolia",name:"Arbitrum Sepolia",vm:"evm",chainId:421614,caip2:"eip155:421614",testnet:!0,native:{symbol:"ETH",decimals:18,usd:3212.4},rpcUrl:$i.evmRpc,priceFeed:{address:"0xd30e2101a97dcbAeBCBC04F14C3f624E67A35165",pair:"ETH / USD",decimals:8,min:100,max:2e4},explorerTx:"https://sepolia.arbiscan.io/tx/",explorerAddr:"https://sepolia.arbiscan.io/address/",explorerName:"arbiscan (sepolia)",gasUsd:.01,routeType:"atomic",escrow:{address:"0x6ab0ef3aa67b022d4007550e7556108537debb55",mode:"live",deploymentBlock:325677796,cashier:"0x6c6c6da6392a92b8b9c69b3ec234d524cdcfcb57",implementationCodeHash:"0x334d6802099fccaef87b9569618ab3c46f6a2f075c2934c0cdbc8d4e4042944b"},tokens:[{symbol:"USDC",address:"0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d",decimals:6,usd:1,cls:"ar-token-usdc"},{symbol:"WETH",address:"0x980B62Da83eFf3D4576C647993b0c1D7faf17c73",decimals:18,cls:"ar-token-eth",peg:"native",hidden:!0}],uniswap:{factory:"0x248ab79bbb9bc29bb72f7cd42f17e054fc40188e",quoter:"0x2779a0CC1c3e0E44D2542EC3e79e3864Ae93Ef0B",router:"0x101F443B4d1b059569D643917553c771E1b9663E",permit2:"0x000000000022D473030F116dDEE9F6B43aC78BA3",wrapped:{symbol:"WETH",name:"Wrapped Ether",address:"0x980B62Da83eFf3D4576C647993b0c1D7faf17c73",decimals:18},feeTiers:[100,500,3e3,1e4]},dexPriceGate:"tolerated"},{id:"local-anvil",name:"Local (anvil)",hidden:!0,vm:"evm",chainId:31337,caip2:"eip155:31337",testnet:!0,native:{symbol:"ETH",decimals:18,usd:3212.4},rpcUrl:"http://127.0.0.1:8545",priceFeed:null,explorerTx:"",explorerAddr:"",explorerName:"",gasUsd:1e-4,routeType:"atomic",escrow:{address:"0xcbEAF3BDe82155F56486Fb5a1072cb8baAf547cc",mode:"live",cashier:"0x1429859428C0aBc9C2C47C8Ee9FBaf82cFA0F20f",implementationCodeHash:"0xfd1ef12c1d96d3ee7060bd5901e06108723783403fad00c9630dcdeb6193674b"},tokens:[]},{id:"arbitrum",name:"Arbitrum One",vm:"evm",chainId:42161,caip2:"eip155:42161",native:{symbol:"ETH",decimals:18,usd:3212.4},rpcUrl:"https://arb1.arbitrum.io/rpc",priceFeed:{address:"0x639Fe6ab55C921f74e7fac1ee960C0B6293ba612",pair:"ETH / USD",decimals:8,min:100,max:2e4},explorerTx:"https://arbiscan.io/tx/",explorerAddr:"https://arbiscan.io/address/",explorerName:"arbiscan",gasUsd:.21,routeType:"atomic",escrow:{address:null,mode:"simulated"},tokens:[{symbol:"USDC",address:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",decimals:6,usd:1,cls:"ar-token-usdc"},{symbol:"USDT",onChainSymbol:"USD\u20AE0",address:"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",decimals:6,usd:1,cls:"ar-token-usdt"},{symbol:"DAI",address:"0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1",decimals:18,usd:1,cls:"ar-token-dai"},{symbol:"USDe",address:"0x5d3a1Ff2b6BAb83b63cd9AD0787074081a52ef34",decimals:18,usd:1,cls:"ar-token-usde"},{symbol:"WETH",address:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",decimals:18,cls:"ar-token-eth",peg:"native",hidden:!0}],uniswap:{factory:"0x1F98431c8aD98523631AE4a59f267346ea31F984",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",wrapped:{symbol:"WETH",name:"Wrapped Ether",address:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",decimals:18},feeTiers:[100,500,3e3,1e4]}},{id:"mainnet",name:"Ethereum",vm:"evm",chainId:1,caip2:"eip155:1",native:{symbol:"ETH",decimals:18,usd:3212.4},rpcUrl:"https://ethereum-rpc.publicnode.com",priceFeed:{address:"0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419",pair:"ETH / USD",decimals:8,min:100,max:2e4},explorerTx:"https://etherscan.io/tx/",explorerAddr:"https://etherscan.io/address/",explorerName:"etherscan",gasUsd:3.4,routeType:"atomic",escrow:{address:null,mode:"simulated"},tokens:[{symbol:"USDC",address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",decimals:6,usd:1,cls:"ar-token-usdc"},{symbol:"USDT",address:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,usd:1,cls:"ar-token-usdt"},{symbol:"DAI",address:"0x6B175474E89094C44Da98b954EedeAC495271d0F",decimals:18,usd:1,cls:"ar-token-dai"},{symbol:"USDe",address:"0x4c9EDD5852cd905f086C759E8383e09bff1E68B3",decimals:18,usd:1,cls:"ar-token-usde"},{symbol:"USDS",address:"0xdC035D45d973E3EC169d2276DDab16f1e407384F",decimals:18,usd:1,cls:"ar-token-usds"},{symbol:"PyUSD",address:"0x6c3ea9036406852006290770BEdFcAbA0e23A0e8",decimals:6,usd:1,cls:"ar-token-pyusd"},{symbol:"WETH",address:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",decimals:18,cls:"ar-token-eth",peg:"native",hidden:!0}],uniswap:{factory:"0x1F98431c8aD98523631AE4a59f267346ea31F984",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",wrapped:{symbol:"WETH",name:"Wrapped Ether",address:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",decimals:18},feeTiers:[100,500,3e3,1e4]}},{id:"base",name:"Base",vm:"evm",chainId:8453,caip2:"eip155:8453",native:{symbol:"ETH",decimals:18,usd:3212.4},rpcUrl:"https://mainnet.base.org",priceFeed:{address:"0x71041dddad3595F9CEd3DcCFBe3D1F4b0a16Bb70",pair:"ETH / USD",decimals:8,min:100,max:2e4},explorerTx:"https://basescan.org/tx/",explorerAddr:"https://basescan.org/address/",explorerName:"basescan",gasUsd:.08,routeType:"atomic",escrow:{address:null,mode:"simulated"},tokens:[{symbol:"USDC",address:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",decimals:6,usd:1,cls:"ar-token-usdc"},{symbol:"USDT",address:"0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2",decimals:6,usd:1,cls:"ar-token-usdt"},{symbol:"DAI",address:"0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb",decimals:18,usd:1,cls:"ar-token-dai"},{symbol:"USDe",address:"0x5d3a1Ff2b6BAb83b63cd9AD0787074081a52ef34",decimals:18,usd:1,cls:"ar-token-usde"}]},{id:"bsc",name:"BNB Chain",vm:"evm",chainId:56,caip2:"eip155:56",native:{symbol:"BNB",decimals:18,usd:612.5},rpcUrl:"https://bsc-dataseed.binance.org",explorerTx:"https://bscscan.com/tx/",explorerAddr:"https://bscscan.com/address/",explorerName:"bscscan",gasUsd:.05,routeType:"atomic",escrow:{address:null,mode:"simulated"},tokens:[{symbol:"USDT",address:"0x55d398326f99059fF775485246999027B3197955",decimals:18,usd:1,cls:"ar-token-usdt"},{symbol:"USDC",address:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",decimals:18,usd:1,cls:"ar-token-usdc"}]},{id:"bitcoin",name:"Bitcoin",vm:"bitcoin",chainId:0,caip2:"bip122:000000000019d6689c085ae165831e93",native:{symbol:"BTC",decimals:8,usd:96e3},rpcUrl:"https://blockstream.info/api",explorerTx:"https://mempool.space/tx/",explorerAddr:"https://mempool.space/address/",explorerName:"mempool.space",gasUsd:1.2,routeType:"atomic",tokens:[],escrow:null,settlement:"native-atomic-swap"},{id:"tron",name:"Tron",vm:"tron",chainId:728126428,caip2:"tron:0x2b6653dc",native:{symbol:"TRX",decimals:6,usd:.28},rpcUrl:"https://api.trongrid.io",explorerTx:"https://tronscan.org/#/transaction/",explorerAddr:"https://tronscan.org/#/address/",explorerName:"tronscan",gasUsd:.35,routeType:"atomic",escrow:null,tokens:[{symbol:"USDT",address:"TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",decimals:6,usd:1,cls:"ar-token-usdt"}]},{id:"solana",name:"Solana",vm:"solana",chainId:101,caip2:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d",native:{symbol:"SOL",decimals:9,usd:198.4},rpcUrl:"https://api.mainnet-beta.solana.com",explorerTx:"https://solscan.io/tx/",explorerAddr:"https://solscan.io/account/",explorerName:"solscan",gasUsd:.002,routeType:"atomic",escrow:null,tokens:[{symbol:"USDC",address:"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",decimals:6,usd:1,cls:"ar-token-usdc"},{symbol:"USDT",address:"Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB",decimals:6,usd:1,cls:"ar-token-usdt"}]},{id:"monad",name:"Monad",vm:"evm",unsupported:!0,chainId:143,caip2:"eip155:143",native:{symbol:"MON",decimals:18,usd:.03},rpcUrl:"https://rpc.monad.xyz",explorerTx:"https://monadscan.com/tx/",explorerAddr:"https://monadscan.com/address/",explorerName:"monadscan",gasUsd:.01,routeType:"atomic",escrow:{address:null,mode:"simulated"},tokens:[{symbol:"USDC",address:"0x754704Bc059F8C67012fEd69BC8A327a5aafb603",decimals:6,usd:1,cls:"ar-token-usdc"},{symbol:"USDT",onChainSymbol:"USDT0",address:"0xe7cd86e13AC4309349F30B3435a9d337750fC82D",decimals:6,usd:1,cls:"ar-token-usdt"}]},{id:"hyperevm",name:"Hyperliquid EVM",vm:"evm",unsupported:!0,chainId:999,caip2:"eip155:999",native:{symbol:"HYPE",decimals:18,usd:38.5},rpcUrl:"https://rpc.hyperliquid.xyz/evm",explorerTx:"https://hyperevmscan.io/tx/",explorerAddr:"https://hyperevmscan.io/address/",explorerName:"hyperevmscan",gasUsd:.01,routeType:"atomic",escrow:{address:null,mode:"simulated"},tokens:[{symbol:"USDC",address:"0xb88339CB7199b77E23DB6E890353E22632Ba630f",decimals:6,usd:1,cls:"ar-token-usdc"},{symbol:"USDT",onChainSymbol:"USD\u20AE0",address:"0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb",decimals:6,usd:1,cls:"ar-token-usdt"}]}],Nt="arbitrum-sepolia",Yf={"local-anvil":["0x60af2ad4963c738aa6ac16d6cb0af1982508ba21"]};Gf={"arbitrum-sepolia":["0x9246f3b981311c4ed988d77bb2177ef45d78182e47d77a2077d0afe3f3377cb8"]};Nx="0xc14C7841C7d6350859474dD6DF8dC9672047A6A0",ve={networkType:"stagenet",confirmTarget:10,blockTimeSim:12e4,blockTimeReal:12e4,node:$i.moneroNode,nodePollMs:3e4},Zt={base:null,xmrSource:"app",pollMs:5e3,maxProviders:5,timeoutMs:6e4},Qf={app:"stagenet",mock:"stagenet",fakechain:"fakechain"};bc={origin:$i.sweepOrigin,localOrigin:"http://localhost:5195"},Yn={projectId:"18c13c05b6c0ab011ffff7cee0700e2d",metadata:{name:"NinseiSwap",description:"Non-custodial XMR <-> EVM atomic swap. Demo build: real wallet, real balances, no real funds move.",url:gx,icons:[]}},It={quoteValid:12e3,quoteRefresh:5e3,fundingMined:6e3,makerLock:3e4,xmrConfirm:ve.blockTimeSim,readyWindow:60*6e4,makerClaim:45e3,sweep:3e4,t0Refund:20*6e4,t1Refund:40*6e4,watchtowerGrace:5*6e4,makerReclaim:10*6e4},Jt={speeds:[1,20,60,300],defaultSpeed:60,scenarios:["happy","maker_no_lock","user_no_ready","maker_stall"],defaultScenario:"happy",chainModes:["mock","live"],defaultChainMode:"live",xmrSources:["app","mock"],defaultXmrSource:"app",defaultChain:Nt},Tx={happy:"happy path",maker_no_lock:"maker never locks XMR",user_no_ready:"user never confirms",maker_stall:"maker stalls after ready"}});var pe={};Be(pe,{allowanceVerdict:()=>Rx,counterpartyVerdict:()=>Lx,deadlineVerdict:()=>Ac,escrowPointsVerdict:()=>Ec,escrowStateVerdict:()=>_c,gasReserveVerdict:()=>Px,liveOrderSlotsVerdict:()=>Fx,networkGateVerdict:()=>Hx,payBalanceVerdict:()=>Bx,quoteFreshnessVerdict:()=>Cx,rangeVerdict:()=>Ox,signingGateVerdict:()=>Dx,signingGateWords:()=>Ux});function Ox({size:e=null,unit:t=null,min:n=null,max:r=null,step:o=null,quoteUnit:i=null}={}){let s=String(t||i||"").toUpperCase(),a=String(i||"").toUpperCase();if(a&&s&&a!==s)return{ok:!1,checked:!0,blocks:!0,kind:"unit-mismatch",reason:`the size is measured in ${s} while the quote states its range in ${a} - the two cannot be compared`,size:e,min:n,max:r,step:o,unit:s,quoteUnit:a};let c=He(e);if(c===null||c<=0)return{ok:!1,checked:!1,blocks:!1,kind:"size-unstated",reason:"the size is not entered, so the provider's range cannot be checked",size:null,min:He(n),max:He(r),step:He(o),unit:s};let l=He(n),u=He(r),d=He(o);if(l===null&&u===null)return{ok:!0,checked:!1,blocks:!1,kind:"range-unstated",reason:"the provider did not state a volume range (min/max), so the size could not be checked against it",size:c,min:null,max:null,step:d,unit:s};let p={size:c,min:l,max:u,step:d,unit:s,quoteUnit:a||s};if(l!==null&&c<l)return{ok:!1,checked:!0,blocks:!0,kind:"below-min",...p,reason:`the order size ${wt(c)} ${s} is below the provider minimum ${wt(l)} ${s} - short by ${wt(l-c)} ${s}: the provider does not take this size`};if(u!==null&&c>u)return{ok:!1,checked:!0,blocks:!0,kind:"above-max",...p,reason:`the order size ${wt(c)} ${s} is above the provider maximum ${wt(u)} ${s} - over by ${wt(c-u)} ${s}: the provider does not take this size`};if(d!==null&&d>0){let m=l!==null?l:0,w=(c-m)/d;if(Math.abs(w-Math.round(w))>1e-6)return{ok:!1,checked:!0,blocks:!0,kind:"off-step",...p,reason:`the order size ${wt(c)} ${s} does not sit on the ${wt(d)} ${s} step from ${wt(m)} ${s}`}}return{ok:!0,checked:!0,blocks:!1,kind:"in-range",...p,reason:`the order size ${wt(c)} ${s} is inside the provider range ${l===null?"?":wt(l)}..${u===null?"?":wt(u)} ${s}`}}function Bx({payBalanceWei:e=null,payAmountWei:t=null,symbol:n=null,decimals:r=18}={}){let o=Gn(e),i=Gn(t);return i===null||i<=0n?{ok:!1,checked:!1,blocks:!1,kind:"amount-unstated",reason:"the amount to fund is not known, so the wallet balance cannot be checked against it"}:o===null?{ok:!1,checked:!1,blocks:!0,kind:"balance-unchecked",reason:"the wallet balance was not read, so it is unknown whether the wallet covers the order - signing is blocked"}:o<i?{ok:!1,checked:!0,blocks:!0,kind:"balance-short",haveWei:o.toString(),needWei:i.toString(),shortfallWei:(i-o).toString(),reason:`the wallet holds ${Ye(o,r)} ${n} but the order locks ${Ye(i,r)} ${n} - short by ${Ye(i-o,r)} ${n}`}:{ok:!0,checked:!0,blocks:!1,kind:"balance-enough",haveWei:o.toString(),needWei:i.toString(),reason:`the wallet holds ${Ye(o,r)} ${n} for the order's ${Ye(i,r)} ${n}`}}function Px({nativeBalanceWei:e=null,requiredNativeWei:t=null,gasReserveWei:n=null,symbol:r=null,decimals:o=18}={}){let i=Gn(t),s=Gn(n),a=Gn(e);if(s===null||s<=0n)return{ok:!0,checked:!1,blocks:!1,kind:"reserve-unstated",reason:"the gas reserve was not measured, so the gas part of the funding could not be checked (the wallet will name any shortfall)"};if(i===null)return{ok:!1,checked:!1,blocks:!1,kind:"amount-unstated",reserveWei:s.toString(),reason:"the amount to fund is not known, so the native balance cannot be checked against amount + gas"};if(a===null)return{ok:!1,checked:!1,blocks:!0,kind:"native-unchecked",needWei:i.toString(),reserveWei:s.toString(),reason:"the native balance was not read, so it is unknown whether the wallet covers amount + gas - signing is blocked"};let c=i+s;return a<c?{ok:!1,checked:!0,blocks:!0,kind:"gas-short",haveWei:a.toString(),needWei:i.toString(),reserveWei:s.toString(),requiredTotalWei:c.toString(),shortfallWei:(c-a).toString(),reason:`funding needs ${Ye(i,o)} ${r} plus ${Ye(s,o)} ${r} of gas, but the wallet holds ${Ye(a,o)} ${r} - short by ${Ye(c-a,o)} ${r}`}:{ok:!0,checked:!0,blocks:!1,kind:"gas-enough",haveWei:a.toString(),needWei:i.toString(),reserveWei:s.toString(),requiredTotalWei:c.toString(),reason:`the wallet holds ${Ye(a,o)} ${r}: ${Ye(i,o)} for the order and ${Ye(s,o)} for gas`}}function Cx({at:e=null,ttlMs:t=null,expiresAt:n=null,nowMs:r=null}={}){let o=He(r)===null?Date.now():Number(r),i=He(n);if(i!==null&&i<=o)return{ok:!1,checked:!0,blocks:!0,kind:"expired",expiresAt:i,nowMs:o,reason:`the order quote expired ${Math.round((o-i)/1e3)}s ago`};let s=He(e);if(s===null)return{ok:!1,checked:!1,blocks:!1,kind:"untimed",reason:"the quote carries no timestamp, so its age could not be checked"};let a=He(t),c=Math.max(0,o-s);return a===null||a<=0?{ok:!0,checked:!1,blocks:!1,kind:"no-ttl",at:s,ageMs:c,reason:`the provider did not state how long the quote lives, so only its age is known: said ${Math.round(c/1e3)}s ago`}:c>a?{ok:!1,checked:!0,blocks:!0,kind:"stale",at:s,ttlMs:a,ageMs:c,overMs:c-a,reason:`the quote is ${Math.round(c/1e3)}s old while it was valid for ${Math.round(a/1e3)}s - it expired ${Math.round((c-a)/1e3)}s ago`}:{ok:!0,checked:!0,blocks:!1,kind:"fresh",at:s,ttlMs:a,ageMs:c,reason:`the quote is ${Math.round(c/1e3)}s old and valid for ${Math.round(a/1e3)}s`}}function Ac({nowSec:e=null,readyBy:t=null,t1:n=null,minReadyLeadSec:r=null,minClaimWindowSec:o=null,maxDeadlineSec:i=null}={}){let s=He(e)===null?Math.floor(Date.now()/1e3):Number(e),a=He(t),c=He(n);if(a===null||c===null)return{ok:!1,checked:!1,blocks:!0,kind:"deadlines-unstated",reason:"the order's deadlines are not stated, so neither the ready window nor the claim window can be checked - signing is blocked"};if(a<=s)return{ok:!1,checked:!0,blocks:!0,kind:"ready-by-in-past",readyBy:a,nowSec:s,reason:`the order would be created already past its ready-by deadline (${a} is ${Math.round(s-a)}s ago): nothing could be claimed in it`};if(c<=a)return{ok:!1,checked:!0,blocks:!0,kind:"t1-not-after-ready-by",readyBy:a,t1:c,reason:`t1 (${c}) must be later than readyBy (${a}): an overlapping window lets claim and refund both be valid at once`};let l=He(r),u=He(o);if(l!==null&&a-s<l)return{ok:!1,checked:!0,blocks:!0,kind:"ready-window-too-short",readyBy:a,nowSec:s,minReadyLeadSec:l,reason:`the ready-by deadline is only ${Math.round(a-s)}s away while the mark-ready window needs at least ${l}s - XMR confirmations alone take minutes`};if(u!==null&&c-a<u)return{ok:!1,checked:!0,blocks:!0,kind:"claim-window-too-short",readyBy:a,t1:c,minClaimWindowSec:u,reason:`the claim window is ${Math.round(c-a)}s while at least ${u}s is needed to take the funds before the refund opens`};let d=He(i);return d!==null&&c-s>d?{ok:!1,checked:!0,blocks:!0,kind:"deadline-too-far",readyBy:a,t1:c,nowSec:s,maxDeadlineSec:d,reason:`the order's deadline is ${Math.round(c-s)}s (${Math.round((c-s)/3600)}h) away while at most ${d}s (${Math.round(d/3600)}h) is allowed: a deposit locked that long could not be refunded until t1`}:{ok:!0,checked:!0,blocks:!1,kind:"deadlines-ok",readyBy:a,t1:c,nowSec:s,reason:`ready in ${Math.round(a-s)}s, claim window ${Math.round(c-a)}s`}}function _c({status:e=null,error:t=null,address:n=null}={}){let r=n?" the escrow at "+n:" the escrow";return t?{ok:!1,checked:!1,blocks:!0,kind:"state-unchecked",error:String(t),reason:`the state of${r} could not be read (${String(t)}), so it is unknown whether this order already exists - signing is blocked`}:e?e.isClaimed?{ok:!1,checked:!0,blocks:!0,kind:"already-claimed",status:e,address:n||null,reason:`${r} is already claimed: the order is settled, a new signature would create a second order`}:e.isRefunded?{ok:!1,checked:!0,blocks:!0,kind:"already-refunded",status:e,address:n||null,reason:`${r} was already refunded: the order is closed, a new signature would create a second order`}:e.isFunded?{ok:!1,checked:!0,blocks:!0,kind:"already-funded",status:e,address:n||null,reason:`${r} is already funded: the contract refuses a second funding (AlreadyFunded) - top up that order instead of signing a new one`}:{ok:!0,checked:!0,blocks:!1,kind:"new",status:e,address:n||null,reason:`${r} exists but holds nothing: this is a new order`}:{ok:!0,checked:!0,blocks:!1,kind:"new",address:n||null,reason:n?`no escrow exists at ${n} yet: this is a new order`:"no escrow exists yet: this is a new order"}}function Rx({tokenIsNative:e=!1,allowanceWei:t=null,amountWei:n=null,consent:r=!1,symbol:o=null,decimals:i=18}={}){if(e)return{ok:!0,checked:!0,blocks:!1,kind:"not-needed",reason:"the payment is the network's own coin: no ERC-20 approval and no pool are involved"};let s=Gn(n),a=Gn(t);return r!==!0?{ok:!1,checked:!1,blocks:!0,kind:"consent-missing",needWei:s===null?null:s.toString(),reason:`swapping ${o||"the token"} needs an ERC-20 approval for you to sign, and no consent was given for it`}:a===null?{ok:!1,checked:!1,blocks:!0,kind:"allowance-unchecked",reason:`the existing allowance for ${o||"the token"} was not read, so it is unknown whether the approval is needed - signing is blocked`}:s===null||s<=0n?{ok:!1,checked:!1,blocks:!1,kind:"amount-unstated",reason:"the amount to swap is not known, so the allowance cannot be checked against it"}:a<s?{ok:!1,checked:!0,blocks:!0,kind:"allowance-short",allowanceWei:a.toString(),needWei:s.toString(),reason:`the approved amount is ${Ye(a,i)} ${o||""} but the swap spends ${Ye(s,i)} ${o||""}: the approval must be raised first`}:{ok:!0,checked:!0,blocks:!1,kind:"allowed",allowanceWei:a.toString(),needWei:s.toString(),reason:`the approved amount ${Ye(a,i)} ${o||""} covers the swap of ${Ye(s,i)} ${o||""}`}}function Hx({walletChainId:e=null,selectedChainId:t=null,settlementChainId:n=null,selectedChainName:r=null}={}){let o=He(e),i=He(t),s=He(n);return o===null?{ok:!1,checked:!1,blocks:!0,kind:"wallet-unknown",reason:"the wallet's network is unknown, so balances and the funding transaction have no network - signing is blocked"}:i===null?{ok:!1,checked:!1,blocks:!0,kind:"network-unknown",reason:"the page's settlement network is unknown, so it cannot be compared with the wallet's - signing is blocked"}:o!==i?{ok:!1,checked:!0,blocks:!0,kind:"wallet-network",walletChainId:o,selectedChainId:i,reason:`the wallet is on chain ${o} while this page settles on chain ${i}${r?" ("+r+")":""}: balances and the funding transaction would come from another network`}:s!==null&&s!==i?{ok:!1,checked:!0,blocks:!0,kind:"settlement-network",walletChainId:o,selectedChainId:i,settlementChainId:s,reason:`the escrow contract sits on chain ${s} while the page is set to chain ${i}: the money would go to a network where this order's escrow does not exist`}:{ok:!0,checked:!0,blocks:!1,kind:"network-match",chainId:i,reason:`the wallet and the page agree on chain ${i}${r?" ("+r+")":""}`}}function Lx({standIn:e=!1,liveChain:t=!1,network:n=null,chainId:r=null}={}){let o=(s,a,c)=>({ok:s,checked:!0,blocks:!s,kind:a,words:c,reason:c}),i=(n||"this network")+(r==null?"":" (chainId "+r+")");return e?t?o(!1,"standin-on-production",`${i} is a live network and the counterparty is a local stand-in: the proof would be checked against itself, so the signature stays locked until a real provider answers`):o(!0,"standin-on-testnet",`demo mode: the counterparty is a local stand-in and ${i} is a testnet (not a live network), the proof proves nothing by itself`):o(!0,"real-provider","counterparty is a real provider: the proof is checked against it")}function Ec({role:e=null,what:t=null,point:n=null,onchainPoint:r=null,commit:o=null,onchainCommit:i=null,readError:s=null}={}){let a=t||(e?"the "+e+" point":"the point");if(s)return{ok:!1,checked:!1,blocks:!0,kind:"points-unchecked",reason:`${a} of the live escrow could not be read (${String(s)}): whether the order holds the points that DLEQ proved is unknown - signing is blocked`};let c=!1;if(Xe(n)){if(c=!0,!Xe(r))return{ok:!1,checked:!1,blocks:!0,kind:"points-unchecked",reason:`the live escrow did not return ${a}: the order may hold different points than the proof proved - signing is blocked`};if(Xe(n)!==Xe(r))return{ok:!1,checked:!0,blocks:!0,kind:"point-mismatch",reason:`${a} in the escrow (0x${Xe(r)}) is NOT the point DLEQ proved (0x${Xe(n)}): the Monero address would be assembled from other halves and the XMR could not be swept after claim`}}if(Xe(o)){if(c=!0,!Xe(i))return{ok:!1,checked:!1,blocks:!0,kind:"points-unchecked",reason:`the live escrow did not return ${a}: the order may hold a different half than we do - signing is blocked`};if(Xe(o)!==Xe(i))return{ok:!1,checked:!0,blocks:!0,kind:"commit-mismatch",reason:`${a} in the escrow (0x${Xe(i)}) is NOT the one we hold (0x${Xe(o)}): the reveal would not match the order`}}return c?{ok:!0,checked:!0,blocks:!1,kind:"points-match",reason:`${a} in the escrow matches what we hold${Xe(n)&&Xe(o)?" (point and commitment)":""}`}:{ok:!1,checked:!1,blocks:!0,kind:"points-unchecked",reason:`nothing to compare for ${a}: neither a point nor a commitment was recorded - signing is blocked`}}function Fx({slots:e=null,expect:t=null,readError:n=null}={}){if(n||!e)return{ok:!1,checked:!1,blocks:!0,kind:"slots-unchecked",reason:`the live escrow slots could not be read (${String(n||"no answer")}): whether the order holds the points and halves we assembled is unknown - signing is blocked`};let r=[["edPointLocker","the locker spend point","point"],["edPointClaimer","the claimer spend point","point"],["edViewPointLocker","the locker view point","point"],["commitHalfLocker","the commitment of the locker half","commit"],["commitHalfClaimer","the commitment of the claimer half","commit"]],o=[],i=[];for(let[s,a,c]of r){if(!Xe(t&&t[s]))continue;if(!Xe(e[s])){i.push(a);continue}let l=Ec(c==="point"?{what:a,point:t[s],onchainPoint:e[s]}:{what:a,commit:t[s],onchainCommit:e[s]});if(l.blocks)return{...l,fields:o.concat([s])};o.push(s)}return o.length?i.length?{ok:!1,checked:!0,blocks:!0,kind:"slots-unchecked",reason:`the live escrow did not return ${i.join(", ")}: the order may differ from what was proved - signing is blocked`}:{ok:!0,checked:!0,blocks:!1,kind:"slots-match",fields:o,reason:`the live escrow holds exactly what we assembled: ${o.join(", ")}`}:{ok:!1,checked:!1,blocks:!0,kind:"slots-unchecked",reason:"nothing to compare: the app recorded neither a point nor a commitment for this order - signing is blocked"}}function Dx(e=[]){let t=(Array.isArray(e)?e:[]).filter(o=>o&&typeof o=="object"),n=t.filter(o=>o.blocks===!0),r=t.filter(o=>o.blocks!==!0&&o.checked===!1);return{ok:n.length===0,blocked:n.length>0,kind:n.length?n[0].kind:t.length?t[t.length-1].kind:"nothing-to-check",reason:n.length?n.map(o=>o.reason).filter(Boolean).join("; "):null,blockedBy:n.map(o=>o.kind),unchecked:r.map(o=>o.kind),checks:t}}function Ux(e){if(!e||!e.blocked)return null;let t=(e.checks||[]).find(r=>r.blocks===!0)||null;return"Signing is blocked: "+(t&&t.reason?t.reason:"the order cannot be checked")+" ("+e.kind+")"}var Gn,wt,He,Ye,Xe,Nc=re(()=>{Gn=e=>{if(e==null||e==="")return null;try{let t=BigInt(e);return t>=0n?t:null}catch{return null}},wt=e=>String(Number(Number(e).toFixed(4))),He=e=>e==null||e===""?null:Number.isFinite(Number(e))?Number(e):null,Ye=(e,t=18)=>{let n=Number(e)/10**Number(t);return Number.isFinite(n)?String(Number(n.toFixed(6))):String(e)};Xe=e=>e==null?"":String(e).replace(/^0x/i,"").toLowerCase()});function Xi(e=16){let t=new Uint8Array(e);return crypto.getRandomValues(t),en(t)}function en(e){let t=e instanceof Uint8Array?e:Uint8Array.from(e||[]);return Array.from(t,n=>n.toString(16).padStart(2,"0")).join("")}function Ic(){return Xi(8)}var Yi=re(()=>{});var mn={};Be(mn,{PREFIX_BY_NETWORK:()=>np,addressForNetwork:()=>Vx,addressFromKeys:()=>qn,addressPayload:()=>cp,checkAddress:()=>Bc,decodeMoneroBase58:()=>sp,encodeMoneroBase58:()=>ap,formatCheck:()=>Oc,isStagenetShaped:()=>Kx,networkFromShape:()=>Er,prefixFor:()=>rp});function rp(e,t="primary"){let n=np[e];if(!n)throw new Error("Unknown network: "+e);let r=n[t];if(r===void 0)throw new Error("Unknown address kind: "+t);return r}function Oc(e){let t=String(e||"").trim();return![95,106].includes(t.length)||!/^[1-9A-HJ-NP-Za-km-z]+$/.test(t)?!1:["4","5","7","8","9","A","B"].includes(t[0])}function Er(e){let t=String(e||"").trim();return Oc(t)?t[0]==="4"||t[0]==="8"?"mainnet":t[0]==="5"||t[0]==="7"?"stagenet":["9","A","B"].includes(t[0])?"testnet":null:null}function Kx(e){return Er(e)==="stagenet"}async function op(){if(Gi)return Gi;if(Jf)return null;try{let e=await import("/assets/vendors/monero/monero-js-browser.js?v=05c682ea");return Gi=e.default||e,Gi}catch{return Jf=!0,null}}function ep(e){let t=0n;for(let r of e)t=t<<8n|BigInt(r);let n="";for(;t>0n;)n=ip[Number(t%58n)]+n,t/=58n;return n}function tp(e,t){let n=0n;for(let o of e){let i=Wx.get(o);if(i===void 0)throw new Error("Invalid Monero base58 character: "+o);n=n*58n+i}let r=new Uint8Array(t);for(let o=t-1;o>=0;o--)r[o]=Number(n&0xffn),n>>=8n;if(n!==0n)throw new Error("Base58 block does not fit in "+t+" bytes");return r}function sp(e){let t=String(e),n=t.length,r=n%11,o=r===0?11:r,i=Mx[o];if(!i)throw new Error("Invalid Monero base58 length");let s=[],a=n-o;for(let u=0;u<a;u+=11)s.push(tp(t.slice(u,u+11),8));s.push(tp(t.slice(a),i));let c=new Uint8Array(s.reduce((u,d)=>u+d.length,0)),l=0;for(let u of s)c.set(u,l),l+=u.length;return c}function ap(e){let t=Array.from(e),n=t.length,r=n%8,o=r===0?8:r,i=n-o,s="";for(let c=0;c<i;c+=8){let l=ep(t.slice(c,c+8));s+="1".repeat(Math.max(0,Zf[8]-l.length))+l}let a=ep(t.slice(i));return s+="1".repeat(Math.max(0,Zf[o]-a.length))+a,s}function cp({network:e,kind:t="primary",spendPub:n,viewPub:r,paymentId:o}){let i=rp(e,t),s=Tc(n,32,"public spend key"),a=Tc(r,32,"public view key"),c=[i,...s,...a];if(t==="integrated"){let l=Tc(o,8,"payment id");c.push(...l)}return Uint8Array.from(c)}function Tc(e,t,n){let r=String(e||"").trim();if(!new RegExp("^[0-9a-fA-F]{"+t*2+"}$").test(r))throw new Error("Bad "+n+": expected "+t*2+" hex characters");let o=new Uint8Array(t);for(let i=0;i<t;i++)o[i]=parseInt(r.slice(i*2,i*2+2),16);return o}function qn({network:e,kind:t="primary",spendPub:n,viewPub:r,paymentId:o},i){if(!i?.keccak256)throw new Error("addressFromKeys needs { keccak256 }");let s=cp({network:e,kind:t,spendPub:n,viewPub:r,paymentId:o}),a=Uint8Array.from(i.keccak256(i.Buffer?i.Buffer.from(s):s)),c=new Uint8Array(s.length+4);return c.set(s,0),c.set(a.slice(0,4),s.length),ap(c)}async function Bc(e,t={}){let n=String(e||"").trim();if(!Oc(n))return{ok:!1,reason:"Not a Monero address (expected 95 or 106 base58 characters)"};let r=Er(n);if(t.expectNetwork&&r&&r!==t.expectNetwork)return{ok:!1,reason:`This is a ${r} address, but the swap runs on ${t.expectNetwork}`};let o=await op();if(!o)return{ok:!0,verified:!1,network:r,reason:"Format looks valid (checksum check unavailable: monero-js bundle is not built)"};try{let i=sp(n),s=i.length-4;if(s<65)throw new Error("Address is too short");let a=i.slice(0,s),c=i.slice(s),l=Uint8Array.from(o.keccak256(o.Buffer.from(a)));if(!(c.length===4&&c.every((m,w)=>m===l[w])))return{ok:!1,reason:"Checksum mismatch: the address has a typo, is corrupted, or is a demo mock address (mock addresses have no checksum)"};let d=a[0],p=jx[d]||{network:"unknown",kind:"unknown"};return p.network==="unknown"?{ok:!1,reason:`Unsupported address prefix ${d}`}:t.expectNetwork&&p.network!==t.expectNetwork?{ok:!1,reason:`This is a ${p.network} address, but the swap runs on ${t.expectNetwork}`}:{ok:!0,verified:!0,network:p.network,kind:p.kind,bytes:i.length}}catch(i){return{ok:!1,reason:"Address decode failed: "+i.message}}}async function Vx({network:e,kind:t="primary",spendPub:n,viewPub:r}){let o=await op();if(!o)throw new Error("monero-js bundle is not available");return qn({network:e,kind:t,spendPub:n,viewPub:r},{keccak256:o.keccak256,Buffer:o.Buffer})}var Zf,Mx,jx,np,Gi,Jf,ip,Wx,Qn=re(()=>{Zf={1:2,2:3,3:5,4:6,5:7,6:9,7:10,8:11},Mx={2:1,3:2,5:3,6:4,7:5,9:6,10:7,11:8},jx={18:{network:"mainnet",kind:"primary"},19:{network:"mainnet",kind:"integrated"},42:{network:"mainnet",kind:"subaddress"},24:{network:"stagenet",kind:"primary"},25:{network:"stagenet",kind:"integrated"},36:{network:"stagenet",kind:"subaddress"},53:{network:"testnet",kind:"primary"},54:{network:"testnet",kind:"integrated"},63:{network:"testnet",kind:"subaddress"}},np={mainnet:{primary:18,integrated:19,subaddress:42},stagenet:{primary:24,integrated:25,subaddress:36},testnet:{primary:53,integrated:54,subaddress:63}};Gi=null,Jf=!1;ip="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Wx=(()=>{let e=new Map;return[...ip].forEach((t,n)=>e.set(t,BigInt(n))),e})()});async function lp(){if(qi)return qi;if(Qi)throw new Error(Qi);try{let e=await import("/assets/vendors/monero/monero-js-browser.js?v=05c682ea");return qi=e.default||e,qi}catch(e){throw Qi="monero-js unavailable: "+e.message+" (run npm run build:vendor; for CSP see the deploy notes)",new Error(Qi)}}async function $x({mnemonic:e,network:t=ve.networkType}={}){let n=await lp();await n.wallet.initEcc();let r;if(e){if(!n.mnemonic.isValid(e))throw new Error("the mnemonic failed its checksum check (file or form corrupted?)");r=String(e).trim()}else r=n.mnemonic.generateWithChecksum();let o=n.mnemonic.toSeed(r),i=n.wallet.fromSeed(o),s=t||"mainnet",a={keccak256:n.keccak256,Buffer:n.Buffer},c=en(i.publicSpendKey),l=en(i.publicViewKey),u=i.subaddress(1,0),d=qn({network:s,kind:"primary",spendPub:c,viewPub:l},a),p=qn({network:s,kind:"subaddress",spendPub:en(u.publicSpendKey),viewPub:en(u.publicViewKey)},a);return{source:"monero-js",library:"ebellocchia/monero-js (MIT)",network:s,mnemonic:r,mnemonicWords:r.split(" ").length,seedHex:en(o),privateSpendKey:en(i.privateSpendKey),privateViewKey:en(i.privateViewKey),publicSpendKey:c,publicViewKey:l,address:d,subaddress:p,addressMainnet:i.primaryAddress().encode(),createdAt:Date.now()}}async function Zi({network:e=ve.networkType,seed:t}={}){return $x({mnemonic:t,network:e})}async function up(){try{return await(await lp()).wallet.initEcc(),{available:!0,info:"mnemonic + keys + addresses ("+ve.networkType+")"}}catch(e){return{available:!1,reason:e.message}}}function dp(e=ve.networkType){return{mainnet:"Monero mainnet",stagenet:"Monero stagenet",testnet:"Monero testnet"}[e]||e}var qi,Qi,Pc=re(()=>{mt();Yi();Qn();qi=null,Qi=null});var ut={};Be(ut,{ALG_NONE:()=>es,ENVELOPE_VERSION:()=>hp,FILE_MAGIC:()=>Lc,PAYLOAD_VERSION:()=>Yx,UNENCRYPTED_ENVELOPE_VERSION:()=>Fc,buildPayload:()=>Qx,createRecoveryFile:()=>Jx,decryptFile:()=>Uc,encryptPayload:()=>wp,envelopeAad:()=>Dc,isEncrypted:()=>Zx,recoveryFileName:()=>ek,scanStartHeight:()=>qx,validatePayload:()=>ts});function Rc(e){return btoa(String.fromCharCode(...new Uint8Array(e)))}function Hc(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))}function Dc(e){let t=e.meta||{};return JSON.stringify([e.v,e.alg,e.iter,e.salt,e.iv,t.id??null,t.side??null,t.createdAt??null,t.termsHash??null])}async function mp(e,t,n){let r=await crypto.subtle.importKey("raw",Ji.encode(e),Cc.name,!1,["deriveKey"]);return crypto.subtle.deriveKey({name:Cc.name,salt:t,iterations:n,hash:Cc.hash},r,{name:wn.name,length:wn.keyBits},!1,["encrypt","decrypt"])}function qx({escrowBirthHeight:e=null,serverRestoreHeight:t=null,nodeHeight:n=null}={}){let r=[e,t,n].map(o=>Number(o)).filter(o=>Number.isFinite(o)&&o>0);return r.length===0?null:Math.max(1,Math.min(...r)-1)}function Qx({swap:e,swapWallet:t,escrow:n,receiveAddress:r,restoreHeight:o=null}){return{magic:Lc,version:t&&t.spendHalf?3:2,swapId:e.id,termsHash:e.escrow&&e.escrow.termsHash||null,side:e.side,network:e.network,moneroNetwork:e.moneroNetwork,createdAt:e.createdAt,pay:{token:e.payToken,amount:e.payAmount},receive:{token:"XMR",amount:e.xmrAmount,address:r},rate:e.rate,maker:e.maker,quote:{signature:e.quoteSignature,nonce:e.quoteSignature?e.quoteSignature.slice(-8):null},escrow:n||e.escrow||null,moneroWallet:t?t.spendHalf?{source:"halves",library:t.library||null,network:t.network,address:t.address,subaddress:t.subaddress||null,spendHalf:t.spendHalf,viewHalf:t.viewHalf,otherSpendPoint:t.otherSpendPoint,otherViewPoint:t.otherViewPoint,otherViewHalf:t.otherViewHalf||null,escrowAddress:n&&n.address||e.escrow&&e.escrow.address||null,restoreHeight:Number.isFinite(o)?o:null}:{source:t.source,library:t.library||null,network:t.network,address:t.address,subaddress:t.subaddress||null,mnemonic:t.mnemonic||null,publicSpendKey:t.publicSpendKey,publicViewKey:t.publicViewKey,restoreHeight:Number.isFinite(o)?o:null}:null,deadlines:e.timeline,recoveryClient:"any standalone client implementing the Ninsei swap protocol (see litepaper \xA75.3)"}}function ts(e){let t=i=>{throw new Error("Corrupt recovery file: "+i)};(!e||typeof e!="object")&&t("the content is not an object"),e.magic!==Lc&&t("foreign file (no Ninsei mark)"),fp.includes(e.version)||t(`payload version ${e.version} is not supported (we support ${fp.join(", ")})`),e.swapId||t("no deal id");let n=e.moneroWallet;if((!n||typeof n!="object")&&t("no Monero wallet data"),e.version>=3){for(let i of["spendHalf","viewHalf","otherSpendPoint","otherViewPoint","otherViewHalf"])n[i]||t("the halves file has no field "+i);n.mnemonic&&t("the halves file contains a mnemonic - the wallet was not built by the scheme")}else{n.mnemonic||t("no mnemonic - there is nothing that can restore the wallet");let i=String(n.mnemonic).trim().split(/\s+/).length;i!==25&&i!==13&&i!==24&&t(`the mnemonic does not look like a Monero phrase (${i} words)`)}n.address||t("no wallet address - nothing to check the restored one against");let r=n.network||e.moneroNetwork;Gx.includes(r)||t(`unknown network "${r}"`),n.network&&e.moneroNetwork&&n.network!==e.moneroNetwork&&t(`the wallet network (${n.network}) does not match the deal network (${e.moneroNetwork})`);let o=[];return(!Number.isFinite(n.restoreHeight)||n.restoreHeight<=0)&&o.push("no restore height (restoreHeight): the wallet will scan history from zero, which is tens of hours - set the XMR lock height manually"),e.version===1&&o.push("an old-format file (v1): its keys were separate fields, the spend key is taken from the mnemonic"),{warnings:o}}async function wp(e,t){let n=()=>({id:e.swapId,side:e.side,createdAt:e.createdAt,termsHash:e.termsHash||null});if(t==="")return{v:Fc,alg:es,meta:n(),payload:e};if(typeof t!="string"||t.length<12)throw new Error("Passphrase must be at least 12 characters");let r=crypto.getRandomValues(new Uint8Array(16)),o=crypto.getRandomValues(new Uint8Array(12)),i=await mp(t,r,6e5),s={id:e.swapId,side:e.side,createdAt:e.createdAt,termsHash:e.termsHash||null},a={v:hp,alg:pp,iter:6e5,salt:Rc(r),iv:Rc(o)},c=await crypto.subtle.encrypt({name:wn.name,iv:o,tagLength:wn.tagLength,additionalData:Ji.encode(Dc({...a,meta:s}))},i,Ji.encode(JSON.stringify(e,yp)));return{...a,ciphertext:Rc(c),meta:s}}function Zx(e){return!!(e&&typeof e=="object"&&e.alg!==es)}async function Uc(e,t){if(!e||typeof e!="object")throw new Error("Not a recovery file (expecting JSON)");if(!Xx.includes(e.v))throw new Error(`Unsupported recovery file version: ${e.v}`);if(e.v===Fc){if(e.alg!==es)throw new Error(`Unknown algorithm: ${e.alg}`);if(!e.payload||typeof e.payload!="object")throw new Error('Recovery file is missing "payload"');return e.payload}if(e.alg!==pp)throw new Error(`Unknown algorithm: ${e.alg}`);for(let u of["salt","iv","ciphertext"])if(typeof e[u]!="string"||!e[u])throw new Error(`Recovery file is missing "${u}"`);let n=Number(e.iter);if(!Number.isInteger(n)||n<1e5)throw new Error(`Recovery file declares too few PBKDF2 iterations: ${e.iter} (minimum 100000)`);if(n>1e7)throw new Error(`Recovery file declares too many PBKDF2 iterations: ${n} (maximum 10000000)`);let r=Hc(e.salt),o=Hc(e.iv),i=await mp(t,r,n),s=e.v>=2?Ji.encode(Dc(e)):void 0,a=s?{name:wn.name,iv:o,tagLength:wn.tagLength,additionalData:s}:{name:wn.name,iv:o,tagLength:wn.tagLength},c;try{c=await crypto.subtle.decrypt(a,i,Hc(e.ciphertext))}catch{throw new Error("Could not decrypt the file: wrong password or the file was altered")}let l;try{l=JSON.parse(zx.decode(c))}catch{throw new Error("It decrypted, but the content is not JSON - the file is corrupt")}if(ts(l),e.meta&&e.meta.id!=null&&l.swapId!=null&&String(e.meta.id)!==String(l.swapId))throw new Error("The deal id in the header does not match the file content: the file was altered");return l}async function Jx(e,t){let n=await wp(e,t);return JSON.stringify(n,yp,2)}function ek(e){let t=String(e||"").trim();return`ninsei-${(t&&t!=="pending"?t:"pending").toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}.json.enc`}var pp,wn,Cc,Ji,zx,Lc,hp,Fc,es,Xx,Yx,fp,Gx,yp,Mc=re(()=>{pp="AES-GCM-256/PBKDF2-SHA256",wn=Object.freeze({name:"AES-GCM",tagLength:128,keyBits:256}),Cc=Object.freeze({name:"PBKDF2",hash:"SHA-256"}),Ji=new TextEncoder,zx=new TextDecoder,Lc="NINSEI-SWAP-RECOVERY",hp=2,Fc=3,es="NONE",Xx=[1,2,3],Yx=3,fp=[1,2,3],Gx=["mainnet","stagenet","testnet","fakechain"];yp=(e,t)=>typeof t=="bigint"?"0x"+t.toString(16):t});function ns({halves:e,addressFromKeys:t,deps:n,ownSpendHalf:r,ownViewHalf:o,otherSpendPoint:i,otherViewPoint:s,network:a}){if(!e||!t)throw new Error("halves and addressFromKeys are required");for(let[m,w]of Object.entries({ownSpendHalf:r,ownViewHalf:o,otherSpendPoint:i,otherViewPoint:s}))if(w==null||w==="")throw new Error("not set: "+m);let c=e.publicHalves(r).ed,l=e.publicHalves(o).ed,u=e.combinePublic(c,i),d=e.combinePublic(l,s);return{address:t({network:a,kind:"primary",spendPub:u,viewPub:d},n),spendPub:u,viewPub:d,ownSpendPub:c,ownViewPub:l}}function bp({halves:e,ownViewHalf:t,otherViewHalf:n}){return"0x"+e.combineHalves(t,BigInt(n)).toString(16).padStart(64,"0")}var jc=re(()=>{});var tn={};Be(tn,{createHalves:()=>No});function No({ed25519:e,secp256k1:t,keccak256:n,randomBytes:r}){for(let[x,I]of[["ed25519",e],["secp256k1",t],["keccak256",n],["randomBytes",r]])if(!I)throw new Error("createHalves: not passed "+x);let o=e.Point.Fn.ORDER,i=t.Point.Fn.ORDER,s=o<i?o:i;function a(){for(let x=0;x<256;x++){let I=r(32),E=0n;for(let U of I)E=E<<8n|BigInt(U);if(E>0n&&E<s)return E}throw new Error("newHalf: could not get a scalar in 256 attempts")}let c="ninsei-order-half-v1",l="ninsei-order-view-v1";function u(x,I,E=c){if(!x||x.length<16)throw new Error("halfFromSeed: secret shorter than 16 bytes");if(!I)throw new Error("halfFromSeed: order binding not set");let U=new TextEncoder().encode(E+"|"+String(I)+"|");for(let S=0;S<256;S++){let B=new Uint8Array(U.length+x.length+4);B.set(U,0),B.set(x,U.length),B[U.length+x.length]=S>>>24&255,B[U.length+x.length+1]=S>>>16&255,B[U.length+x.length+2]=S>>>8&255,B[U.length+x.length+3]=S&255;let R=n(B),A=0n;for(let N of R)A=A<<8n|BigInt(N);if(A>0n&&A<s)return A}throw new Error("halfFromSeed: could not get a scalar in 256 attempts")}function d(x,I){return x.fromHex(I.startsWith("0x")?I.slice(2):I)}function p(x){if(typeof x=="bigint")return x;if(typeof x=="string"){let I=x.trim().replace(/^0x/,"");if(!/^[0-9a-fA-F]{1,64}$/.test(I))throw new Error("half does not look like a number: "+x.slice(0,12));return BigInt("0x"+I)}if(typeof x=="number")return BigInt(x);throw new Error("half of unknown type: "+typeof x)}function m(x){return x.toHex()}function w(x){return{ed:m(e.Point.BASE.multiply(p(x))),secp:m(t.Point.BASE.multiply(p(x)))}}function y(x,I){return(p(x)+p(I))%o}function b(x,I){return m(d(e.Point,x).add(d(e.Point,I)))}return{LIMIT:s,ED_ORDER:o,SECP_ORDER:i,HALF_DOMAIN:c,VIEW_HALF_DOMAIN:l,newHalf:a,halfFromSeed:u,publicHalves:w,combineHalves:y,combinePublic:b}}var Io=re(()=>{});var rs={};Be(rs,{assertNoSecretsInShare:()=>kp,restoreFromFile:()=>tk,restoreFromHalves:()=>xp,restoreWalletFromPayload:()=>gp,watchOnlyShareFromWallet:()=>nk});async function gp(e,t={}){let{warnings:n}=ts(e),r=e.moneroWallet,o=r.network||e.moneroNetwork;if(e.version>=3)return await xp(e,n,t);let i=await Zi({seed:r.mnemonic,network:o});if(i.address!==r.address)throw new Error("the address from the file does not match the one derived from the mnemonic: the file is corrupted or altered");for(let[s,a]of[["publicSpendKey",i.publicSpendKey],["publicViewKey",i.publicViewKey]])if(r[s]&&r[s]!==a)throw new Error(`key ${s} from the file does not match the one derived from the mnemonic: the file was altered`);return{wallet:i,payload:e,restoreHeight:Number.isFinite(r.restoreHeight)&&r.restoreHeight>0?r.restoreHeight:0,warnings:n}}async function xp(e,t=[],n={}){let r=e.moneroWallet,o=r.network||e.moneroNetwork,i=n.halves&&n.addressFromKeys?{halves:n.halves,addressFromKeys:n.addressFromKeys,keccak256:n.keccak256}:await(async()=>{let l=await import("/assets/vendors/atomic/atomic-browser.js?v=2c038c56"),{createHalves:u}=await Promise.resolve().then(()=>(Io(),tn)),{addressFromKeys:d}=await Promise.resolve().then(()=>(Qn(),mn));return{halves:u({ed25519:l.ed25519,secp256k1:l.secp256k1,keccak256:l.keccak256,randomBytes:l.randomBytes}),addressFromKeys:d,keccak256:l.keccak256}})();if(!i.keccak256)throw new Error("no keccak256: the address cannot be checked without it");let s=ns({halves:i.halves,addressFromKeys:i.addressFromKeys,deps:{keccak256:i.keccak256},ownSpendHalf:r.spendHalf,ownViewHalf:r.viewHalf,otherSpendPoint:r.otherSpendPoint,otherViewPoint:r.otherViewPoint,network:o});if(s.address!==r.address)throw new Error("the address from the file does not match the one built from the halves and counterparty points: the file is corrupted or altered");let a=bp({halves:i.halves,ownViewHalf:r.viewHalf,otherViewHalf:r.otherViewHalf});return{wallet:{address:s.address,network:o,spendPub:s.spendPub,viewPub:s.viewPub,viewSeedHex:a,spendHalf:r.spendHalf,viewHalf:r.viewHalf,otherSpendPoint:r.otherSpendPoint,otherViewPoint:r.otherViewPoint,otherViewHalf:r.otherViewHalf,source:"halves",spendable:!1},payload:e,restoreHeight:Number.isFinite(r.restoreHeight)&&r.restoreHeight>0?r.restoreHeight:0,warnings:[...t,"this file describes the HALVES scheme: the view key sees arrivals, but spending needs the counterparty half, which is revealed on chain at the ETH claim"]}}async function tk(e,t,n={}){return gp(await Uc(e,t),n)}function kp(e,t){for(let r of["mnemonic","seed","seedHex","privateSpendKey","spendKey","subaddressKeys","spendHalf","viewHalf"])if(Object.hasOwn(e,r))throw new Error("the watch-only share must not contain "+r);let n=JSON.stringify(e);for(let[r,o]of[["spend key",t.privateSpendKey],["mnemonic",t.mnemonic],["seed",t.seedHex],["spend key half",t.spendHalf],["view key half",t.viewHalf]])if(o&&n.includes(o))throw new Error(`the watch-only share leaked a secret (${r})`);return e}function nk({swapId:e=null,wallet:t,restoreHeight:n=null}={}){if(!t||!t.address||!t.privateViewKey)throw new Error("a watch-only wallet needs an address and a private view key");return kp({swapId:e||null,network:t.network,address:t.address,privateViewKey:t.privateViewKey,restoreHeight:Number.isFinite(n)?n:null},t)}var Sp=re(()=>{Pc();Mc();jc()});var Jn={};Be(Jn,{bindStorage:()=>ik,createStore:()=>sk,exportState:()=>lk,loadState:()=>rt,memoryStorage:()=>vp,reset:()=>ck,saveState:()=>jt,setStorage:()=>ok,storage:()=>Vc,update:()=>ak});function vp(e=new Map){return{get:t=>e.has(t)?e.get(t):null,set:(t,n)=>e.set(t,String(n)),remove:t=>e.delete(t)}}function ok(e){return Wc(e),yn=e,os=null,yn}function ik(e){if(Wc(e),os&&os!==e)throw Zn("conflict");return os=e,yn=e,yn}function Ep(e){let t;try{t=e.get(Ao.storageKey)}catch(r){throw Zn("read",r)}if(t==null||t==="")return structuredClone(Kc);let n;try{n=JSON.parse(t)}catch(r){throw Zn("parse",r)}if(!n||typeof n!="object"||Array.isArray(n))throw Zn("parse");return{...structuredClone(Kc),...n,settings:{...Kc.settings,...n.settings||{}}}}function rt(){return Ep(yn)}function _p(e,t){let n;try{n=JSON.stringify(t,Ap)}catch(r){throw Zn("serialize",r)}try{e.set(Ao.storageKey,n)}catch(r){throw Zn("write",r)}return t}function jt(e){return _p(yn,e)}function sk(e){return Wc(e),{loadState:()=>Ep(e),saveState:t=>_p(e,t),storage:()=>e}}function ak(e){let t=rt(),n=e(t)||t;return jt(n),n}function ck(){try{yn.remove(Ao.storageKey)}catch(e){throw Zn("remove",e)}}function lk(){return JSON.stringify(rt(),Ap,2)}var Kc,rk,yn,os,Wc,Zn,Vc,Ap,is=re(()=>{mt();Kc={version:1,settings:{speed:Jt.defaultSpeed,scenario:Jt.defaultScenario,chainMode:Jt.defaultChainMode,chain:Jt.defaultChain,payToken:""},wallet:{connected:!1,address:null,balances:{}},swaps:{},activeSwapId:null};rk=e=>{let t=typeof globalThis<"u"?globalThis[e]:void 0;return!t||typeof t.getItem!="function"?null:{get:n=>t.getItem(n),set:(n,r)=>t.setItem(n,String(r)),remove:n=>t.removeItem(n)}},yn=rk("localStorage")||vp(),os=null,Wc=e=>{if(!(e&&typeof e.get=="function"&&typeof e.set=="function"&&typeof e.remove=="function"))throw new Error("storage must support get/set/remove")},Zn=(e,t)=>{let n=new Error("storage-unavailable");return n.code="storage-unavailable",n.params={step:e},t&&(n.cause=t),n};Vc=()=>yn;Ap=(e,t)=>typeof t=="bigint"?"0x"+t.toString(16):t});function $c(e){return(e&&(e.code||e.data&&e.data.originalError&&e.data.originalError.code))===4001?!0:/rejected|denied|cancell?ed|closed by user/i.test(String(e&&e.message||e||""))}function dk(e){return e?e.isMetaMask?"MetaMask":e.isRabby?"Rabby":e.isCoinbaseWallet?"Coinbase Wallet":e.isBraveWallet?"Brave Wallet":e.isFrame?"Frame":"Browser wallet":null}function To({win:e=globalThis,timeoutMs:t=250}={}){let n=[],r=new Set,o=s=>{let a=s.rdns||s.uuid||s.name;r.has(a)||(r.add(a),n.push(s))},i=s=>{let a=s&&s.detail;!a||!a.provider||!a.info||o({uuid:a.info.uuid||null,name:a.info.name||"Browser wallet",icon:a.info.icon||null,rdns:a.info.rdns||null,provider:a.provider,source:"eip6963"})};return e&&typeof e.addEventListener=="function"&&(e.addEventListener(Np,i),typeof e.dispatchEvent=="function"&&e.dispatchEvent(new Event(uk))),new Promise(s=>{let a=()=>{e&&typeof e.removeEventListener=="function"&&e.removeEventListener(Np,i);let c=e&&e.ethereum;if(!n.length&&c){let l=Array.isArray(c.providers)&&c.providers.length?c.providers:[c];for(let u of l)o({name:dk(u),icon:null,rdns:null,provider:u,source:"legacy"})}s(n)};t>0&&typeof setTimeout=="function"?setTimeout(a,t):a()})}async function Ip(e){if(!e||typeof e.request!="function")throw new Error("This wallet does not support EIP-1193 (no request)");let t=await e.request({method:"eth_requestAccounts"}),n=Array.isArray(t)?t[0]:null,r=await e.request({method:"eth_chainId"});return{address:n||null,chainId:Number(r)||null}}async function Tp(e){if(!e||typeof e.request!="function")return[];try{let t=await e.request({method:"eth_accounts"});return Array.isArray(t)?t:[]}catch{return[]}}function Op(e,t="Wallet"){let n=e&&(e.code||e.data&&e.data.originalError&&e.data.originalError.code),r=String(e&&e.message||e);return n===-32002||/already pending|already processing/i.test(r)?t+": the wallet already has a pending request, so a new window did not open. Open the extension, finish or cancel that request, then try again.":/no provider|not connected|provider is disconnected|undefined is not a function/i.test(r)?t+": the extension is not responding (the browser may have unloaded it, or the page is not where it works).":/user rejected|user denied|rejected by user/i.test(r)||n===4001?t+": the request was rejected in the wallet.":t+": "+r}var Np,uk,zc=re(()=>{Np="eip6963:announceProvider",uk="eip6963:requestProvider"});function Ae(e,t={},n=[]){let r=document.createElement(e);for(let[i,s]of Object.entries(t||{}))s==null||s===!1||(i==="class"?r.className=s:i==="html"?r.innerHTML=s:i==="text"?r.textContent=s:i==="style"?typeof s=="string"?r.style.cssText=s:Object.assign(r.style,s):i.startsWith("on")&&typeof s=="function"?r.addEventListener(i.slice(2).toLowerCase(),s):r.setAttribute(i,s===!0?"":String(s)));let o=Array.isArray(n)?n:[n];for(let i of o)i==null||i===!1||r.appendChild(typeof i=="string"||typeof i=="number"?document.createTextNode(String(i)):i);return r}function Bp(e,t=""){let n=document.getElementById("arToasts");if(!n)return;let r=Ae("div",{class:`ar-toast ${t?"ar-toast-"+t:""}`,text:e});n.appendChild(r),setTimeout(()=>{r.style.transition="opacity .25s",r.style.opacity="0",setTimeout(()=>r.remove(),260)},5200)}function Pp(e,t="Copied"){let n=()=>Bp(t,"ok");navigator.clipboard?.writeText?navigator.clipboard.writeText(e).then(n,()=>r()):r();function r(){let o=document.createElement("textarea");o.value=e,document.body.appendChild(o),o.select();try{document.execCommand("copy"),n()}catch{Bp("Copy failed","bad")}o.remove()}}var Cp=re(()=>{});function Rp({title:e="Connect a wallet",subtitle:t="",hint:n=""}={}){let r={},o=Ae("div",{class:"ar-overlay"},[Ae("div",{class:"ar-modal"},[Ae("div",{class:"ar-modal-head"},[Ae("div",{class:"ar-modal-title",text:e}),r.closeBtn=Ae("button",{class:"ar-modal-close",type:"button",title:"Close",text:"\xD7"})]),r.subtitle=Ae("div",{class:"ar-modal-sub",text:t}),r.choices=Ae("div",{class:"ar-modal-choices"}),r.qrBox=Ae("div",{class:"ar-modal-qr",hidden:!0},[r.qr=Ae("img",{alt:"WalletConnect QR code"})]),r.uri=Ae("code",{class:"ar-modal-uri"}),r.status=Ae("div",{class:"ar-modal-status"}),Ae("div",{class:"ar-modal-actions"},[r.copyBtn=Ae("button",{class:"ar-btn-ghost",type:"button",text:"Copy link"}),r.cancelBtn=Ae("button",{class:"ar-btn-ghost",type:"button",text:"Cancel"})]),r.hint=Ae("div",{class:"ar-modal-hint",text:n})])]);document.body.appendChild(o);let i={value:!1},s=null;function a(){i.value||(i.value=!0,o.remove())}function c(){i.value||(a(),s&&s())}r.closeBtn.addEventListener("click",c),r.cancelBtn.addEventListener("click",c),r.copyBtn.addEventListener("click",()=>{r.uri.textContent&&Pp(r.uri.textContent,"WalletConnect link copied")}),o.addEventListener("click",u=>{u.target===o&&c()});function l(u){r.choices.innerHTML="",r.choices.hidden=!u||!u.length;for(let d of u||[]){let p=Ae("button",{class:"ar-modal-choice",type:"button"},[d.icon?Ae("img",{class:"ar-modal-choice-icon",src:d.icon,alt:""}):Ae("span",{class:"ar-modal-choice-icon ar-modal-choice-icon-empty"}),Ae("span",{class:"ar-modal-choice-text"},[Ae("span",{class:"ar-modal-choice-name",text:d.name}),d.hint?Ae("span",{class:"ar-modal-choice-hint",text:d.hint}):null])]);p.addEventListener("click",()=>{i.value||d.onClick()}),r.choices.appendChild(p)}return r.choices}return{closed:i,setChoices:l,close:a,cancel:c,setOnCancel(u){s=u},update({qrDataUrl:u,uri:d,status:p,subtitle:m,hint:w,error:y}={}){if(i.value)return;u&&(r.qr.src=u,r.qrBox.hidden=!1),d!==void 0&&(r.uri.textContent=d||""),m!==void 0&&(r.subtitle.textContent=m||""),w!==void 0&&(r.hint.textContent=w||"");let b=y||p;b!==void 0&&(r.status.className="ar-modal-status"+(y?" ar-modal-status-error":""),r.status.textContent=b||"")}}}var Hp=re(()=>{Cp()});function Lp(e,t){return Number(e)/10**t}function fk(e){let t=String(e);return t.includes(".")?t.replace(/0+$/,"").replace(/\.$/,""):t}function pk(e,t=6){let n=Number(e);if(!Number.isFinite(n)||n<=0)return 0;let r=Math.floor(n*10**t);return r>0?r/10**t:Math.floor(n*1e18)/1e18}function Fp(e,t=6){let n=pk(e,t);if(!Number.isFinite(n)||n<=0)return"0";let r=n>=10**-t?t:18;return fk(n.toFixed(r))}var aN,Xc=re(()=>{aN=[[12345678900n,6,12345.6789],[108275582n,6,108.275582],[10n**18n,18,1],[1500000000000000000n,18,1.5],[55000000000000n,18,55e-6],[55000n,18,55e-15],[3120000000000000000000n,18,3120],[0n,18,0]]});var as={};Be(as,{CLAIM_GAS_LIMIT:()=>Yc,CLAIM_TIP_FLOOR_WEI:()=>Dp,DEFAULT_GIFT_RESERVE_BPS:()=>Mp,claimGasGiftWei:()=>Gc,claimMaxFeePerGasWei:()=>ss,claimRequiredWei:()=>Up});function ss({baseFeeWei:e,priorityFeeWei:t=0n,minTipWei:n=Dp}={}){let r=Ar(e);if(r===null||r<=0n)return null;let o=Ar(t),i=Ar(n),s=i===null||i<0n?0n:i,a=o!==null&&o>s?o:s;return r*2n+a}function Up({gasLimit:e=Yc,maxFeePerGasWei:t}={}){let n=Ar(e),r=Ar(t);return n===null||n<=0n||r===null||r<=0n?null:n*r}function Gc({baseFeeWei:e,priorityFeeWei:t,minTipWei:n,gasLimit:r=Yc,reserveBps:o=Mp}={}){let i=ss({baseFeeWei:e,priorityFeeWei:t,minTipWei:n}),s=Up({gasLimit:r,maxFeePerGasWei:i});if(s===null)return null;let a=Ar(o),c=a===null||a<0n?0n:a;return s+s*c/10000n}var Yc,Dp,Ar,Mp,cs=re(()=>{Yc=200000n,Dp=0n,Ar=e=>{if(e==null||e==="")return null;try{return BigInt(typeof e=="bigint"?e:String(e))}catch{return null}};Mp=10000n});function et(){for(let e of Jc)try{e(bn())}catch(t){console.warn("wallet listener failed",t)}}function bn(){return{...Q,balances:{...Q.balances}}}function Wp(e){return Jc.add(e),()=>Jc.delete(e)}function Vp(){return bn()}function Wt(){return Q.status==="connected"&&!!Q.address}function er(){return Q.address}function $p(){return Q.chainId}function Oo(){return ie}function zp(e,t){let n=Je(e),r=Q.balances[`${n.chainId}:${String(t).toUpperCase()}`];return r===void 0?0:r}async function Xp(){return qc||(qc=await import("/assets/vendors/walletconnect/wc-browser.js?v=13fe06e5")),qc}function mk(){let e={};for(let t of Mt)e[t.chainId]=t.rpcUrl;return e}function dt(e="idle",t=null){Q.status=e,Q.error=t,Q.kind=null,Q.label=null,Q.address=null,Q.chainId=null,Q.balances={},ie=null,et()}function tl(e){e.on("chainChanged",t=>{Q.chainId=Number(t),Q.error=null,et(),Kt()}),e.on("accountsChanged",t=>{let n=t&&t[0]||null;if(!n){ye&&ye.close(),dt("idle",null);return}Q.address=n,et(),Kt()}),e.on("disconnect",()=>{ye&&ye.close(),dt("idle",null)}),e.on("session_delete",()=>{ye&&ye.close(),dt("idle",null)})}async function wk(){if(Qc||Q.status!=="connected"||Q.kind!=="walletconnect"||!ie)return;Qc=!0;let e=ie;try{await Promise.race([e.request({method:"eth_accounts"}),new Promise((t,n)=>setTimeout(()=>n(new Error("the relay did not answer in 4 s")),4e3))]),console.log("[wc] the connection is alive after returning to the page");return}catch(t){console.log("[wc] the relay does not answer after returning ("+t.message+") - raising the session again")}finally{Qc=!1}ie=null;try{let t=Q.chainId||(Mt.find(o=>o.escrow)||{}).chainId,r=await(await nl(t)).request({method:"eth_accounts"});if(!Array.isArray(r)||!r.length){console.log("[wc] no session left in storage - a new QR is needed"),dt("idle",null);return}Q.address=r[0],et(),await Kt(),console.log("[wc] session raised again: "+Q.address)}catch(t){console.log("[wc] could not raise the session: "+t.message),dt("idle",null)}}async function nl(e){if(ie)return ie;let{EthereumProvider:t}=await Xp();return ie=await t.init({projectId:Yn.projectId,chains:[e],optionalChains:Mt.filter(n=>n.escrow).map(n=>n.chainId),showQrModal:!1,rpcMap:mk(),metadata:{...Yn.metadata,url:location.origin}}),ie.on("display_uri",n=>yk(n)),tl(ie),ie}async function yk(e){if(!(!ye||ye.closed.value))try{let{QRCode:t}=await Xp(),n=await t.toDataURL(e,{margin:1,width:440,errorCorrectionLevel:"M",color:{dark:"#0a0d13",light:"#ffffff"}});ye.update({qrDataUrl:n,uri:e,status:"Waiting for the wallet to approve..."})}catch(t){ye.update({uri:e,status:"Scan failed to render, copy the link instead",error:!0}),console.warn("qr render failed",t)}}async function Gp(){if(bk())return Zc=!0,console.log("[wc] restore skipped: wallet disconnected manually"),bn();if(Zc||Q.status==="connected")return bn();if(Zc=!0,Yn.projectId)try{let e=Je(Q.chainId||void 0),t=await nl(e.chainId),n=t&&t.accounts||[];n.length&&(Q.kind="walletconnect",Q.label="WalletConnect",Q.address=n[0],Q.chainId=Number(t.chainId)||e.chainId,Q.status="connected",Q.error=null,et(),await Kt(),console.info("WalletConnect: session restored after reload",Q.address))}catch(e){console.warn("WalletConnect: could not restore the session",e&&e.message?e.message:e)}return Wt()?bn():rl()}async function rl({wallets:e}={}){if(Wt())return bn();let t=e||await To();for(let n of t){let r=await Tp(n.provider);if(r.length){ie=n.provider,Q.kind="injected",Q.label=n.name||"Browser wallet",tl(ie),Q.address=r[0];try{Q.chainId=Number(await ie.request({method:"eth_chainId"}))||null}catch{Q.chainId=null}return Q.status="connected",Q.error=null,et(),await Kt(),console.info("Browser wallet restored without a prompt: "+Q.address),bn()}}return bn()}async function ol({wallet:e,chainSlug:t}={}){if(Yp(!1),!e||!e.provider)throw new Error("No wallet extension found in this browser");if(Wt()&&Q.kind==="injected"&&Q.label===(e.name||null))return{address:Q.address,chainId:Q.chainId};let n=Je(t||Q.chainId||void 0);ie=e.provider,Q.kind="injected",Q.label=e.name||"Browser wallet",Q.status="pairing",Q.error=null,et(),tl(ie);try{let r=await Ip(ie);if(!r.address)throw new Error("The wallet returned no address");return Q.address=r.address,Q.chainId=r.chainId||n.chainId,Q.status="connected",Q.error=null,et(),Q.chainId!==n.chainId&&await il(n),await Kt(),{address:Q.address,chainId:Q.chainId}}catch(r){let o=Q.label||e.name||"Wallet",i=Op(r,o);if($c(r))return console.info("[wallet] user refusal: "+i),dt("idle",null),null;throw console.warn("[wallet] connect did not happen: "+i,r),dt("error",i),new Error(i)}}async function qp({chainSlug:e}={}){if(Wt())return{address:Q.address,chainId:Q.chainId};let t=Je(e||Q.chainId||void 0);Q.status="pairing",Q.error=null,et();let n=await To();n.length?console.info("[wallet] found in the browser: "+n.map(s=>s.name+" ["+s.source+(s.rdns?" "+s.rdns:"")+"]").join(", ")):console.info("[wallet] no browser wallets found (WalletConnect remains)"),ye=Rp({title:"Connect a wallet",subtitle:`Requested network: ${t.name}. The QR below is a public WalletConnect link - nothing secret. This demo never moves real funds: there is no escrow contract on-chain yet.`,hint:"Browser wallets are detected in this browser (EIP-6963). WalletConnect works with mobile wallets by QR."});let r=await new Promise(s=>{ye.setOnCancel(()=>s({type:"cancel"}));let a=n.map(c=>({key:c.rdns||c.name,name:c.name,icon:c.icon,hint:c.source==="eip6963"?null:"detected via window.ethereum",onClick:()=>s({type:"injected",wallet:c})}));Yn.projectId&&a.push({key:"walletconnect",name:"WalletConnect",icon:null,hint:"QR code for a mobile wallet",onClick:()=>s({type:"walletconnect"})}),ye.setChoices(a),ye.update({status:n.length?"Choose a browser wallet above, or scan the QR code below.":"No browser wallet found in this browser - use the QR code below."})});if(r.type==="cancel")return dt("idle",null),null;if(r.type==="injected")try{let s=await ol({wallet:r.wallet,chainSlug:t.id});return ye&&ye.close(),s}catch(s){let a=String(s&&s.message||s);throw ye&&ye.update({error:a,status:"Try again, or use WalletConnect below."}),s}if(!Yn.projectId)throw ye&&ye.close(),dt("error","no-project-id"),new Error("WalletConnect projectId is not configured");ye.update({status:"Preparing the session..."});let o=null,i=new Promise((s,a)=>{o=()=>a(new Error("Connection cancelled"))});ye.setOnCancel(()=>{let s=ie;ie=null,s&&Promise.resolve(s.disconnect()).catch(()=>{}),dt("idle",null),o&&o()});try{let s=await nl(t.chainId);return await Promise.race([s.connect({chains:[t.chainId]}),i]),Q.kind="walletconnect",Q.label="WalletConnect",Q.address=s.accounts&&s.accounts[0]||null,Q.chainId=Number(s.chainId),Q.status="connected",Q.error=null,ye&&ye.close(),et(),await Kt(),{address:Q.address,chainId:Q.chainId}}catch(s){let a=s&&s.message?String(s.message):String(s);console.warn("WalletConnect connect failed:",a);let c=$c(s)||/cancell?ed/i.test(a);if(ye&&ye.close(),dt(c?"idle":"error",c?null:a),!c)throw s;return null}}async function Qp(e){if(!ie||Q.status!=="connected")throw new Error("wallet not connected: signing is impossible");let t="0x"+Array.from(new TextEncoder().encode(String(e)),n=>n.toString(16).padStart(2,"0")).join("");return await ie.request({method:"personal_sign",params:[t,Q.address]})}async function Zp(){Yp(!0);let e=ie,t=Q.kind;if(!e){dt("idle",null);return}try{t==="injected"?typeof e.revokePermissions=="function"&&await e.request({method:"wallet_revokePermissions",params:[{eth_accounts:{}}]}):await e.disconnect()}catch(n){console.warn("disconnect failed",n)}dt("idle",null)}async function il(e){let t=typeof e=="object"?e:Je(e);if(!ie||!Wt())return!1;let n=hk(t.chainId);try{await ie.request({method:"wallet_switchEthereumChain",params:[{chainId:n}]})}catch(r){if(!((r&&(r.code||r.data&&r.data.originalError&&r.data.originalError.code))===4902||/unrecognized chain|not added/i.test(String(r&&r.message))))return/rejected|denied/i.test(String(r&&r.message))||(Q.error=String(r&&r.message||r),et()),!1;try{await ie.request({method:"wallet_addEthereumChain",params:[{chainId:n,chainName:t.name,nativeCurrency:{name:t.native.symbol,symbol:t.native.symbol,decimals:t.native.decimals},rpcUrls:[t.rpcUrl],blockExplorerUrls:[t.explorerAddr]}]})}catch(s){return/rejected|denied/i.test(String(s&&s.message))||(Q.error=String(s&&s.message||s),et()),!1}}return Q.chainId=t.chainId,et(),await Kt(),!0}async function gn({to:e,data:t}={}){if(!ie)throw new Error("wallet not connected: nothing to read the contract with");if(!e)throw new Error("no contract address given");if(!t)throw new Error("no call data given");let n=await ie.request({method:"eth_call",params:[{to:e,data:t},"latest"]});if(typeof n!="string"||!n.startsWith("0x"))throw new Error("unexpected answer to a contract call: "+String(n).slice(0,60));return n}async function ls({address:e}={}){if(!ie)throw new Error("wallet not connected: nothing to read the contract code with");if(!e||!/^0x[0-9a-fA-F]{40}$/.test(String(e)))throw new Error("not an address for reading code: "+String(e));return await ie.request({method:"eth_getCode",params:[e,"latest"]})}async function sl({hash:e}={}){if(!ie)throw new Error("wallet not connected: nothing to read the receipt with");if(!e)throw new Error("no transaction hash given");let t=await ie.request({method:"eth_getTransactionReceipt",params:[e]});return!t||typeof t!="object"?null:t}async function al({to:e,data:t,value:n="0x0",gas:r}={}){if(!ie)throw new Error("wallet not connected: nothing to send with");if(!e)throw new Error("no contract address given");if(!t)throw new Error("no call data given");let o=er();if(!o)throw new Error("wallet not connected: no sender address");let i={from:o,to:e,data:t,value:typeof n=="bigint"?"0x"+n.toString(16):n};r&&(i.gas=typeof r=="bigint"?"0x"+r.toString(16):r);try{let a=await ie.request({method:"eth_getBlockByNumber",params:["latest",!1]}),c=a&&a.baseFeePerGas?BigInt(a.baseFeePerGas):0n,l=0n;try{let d=await ie.request({method:"eth_gasPrice",params:[]});if(typeof d=="string"&&/^0x[0-9a-fA-F]+$/.test(d)){let p=BigInt(d)-c;p>0n&&(l=p)}}catch{}let u=ss({baseFeeWei:c,priorityFeeWei:l});u!==null&&(i.maxPriorityFeePerGas="0x"+(u-c*2n).toString(16),i.maxFeePerGas="0x"+u.toString(16))}catch(a){console.warn("could not compute the fee, the wallet decides: "+(a&&a.message||a))}let s=await ie.request({method:"eth_sendTransaction",params:[i]});if(typeof s!="string"||!/^0x[0-9a-fA-F]{64}$/.test(s))throw new Error("the wallet returned not a transaction hash: "+String(s).slice(0,60));return s}async function Kt(){if(!Wt()||!ie)return;let e=Sc(Q.chainId);if(!e){Q.error=`Wallet is on chain ${Q.chainId}, which this demo does not support`,et();return}let t=Q.address,n={},r=[[e.native.symbol,null,e.native.decimals,"eth_getBalance"]];for(let i of e.tokens)r.push([i.symbol,i.address,i.decimals,null]);let o=await Promise.all(r.map(async([i,s,a,c])=>{try{let l;if(c==="eth_getBalance")l=await ie.request({method:c,params:[t,"latest"]});else{let u="0x70a08231"+t.replace(/^0x/,"").toLowerCase().padStart(64,"0");l=await ie.request({method:"eth_call",params:[{to:s,data:u},"latest"]})}return[i,Lp(BigInt(l),a)]}catch(l){return console.warn(`balance read failed for ${i}`,l),[i,void 0]}}));for(let[i,s]of o)s!==void 0&&(n[`${e.chainId}:${String(i).toUpperCase()}`]=s);Q.balances={...Q.balances,...n},Q.lastRefresh=Date.now(),Q.error=null,et()}var Jc,Q,ie,ye,qc,hk,Qc,jp,Kp,Zc,el,bk,Yp,us=re(()=>{mt();zc();Hp();Xc();cs();Jc=new Set,Q={status:"idle",kind:null,label:null,address:null,chainId:null,balances:{},error:null,lastRefresh:0},ie=null,ye=null,qc=null;hk=e=>"0x"+Number(e).toString(16);Qc=!1;jp=null,Kp=()=>{clearTimeout(jp),jp=setTimeout(()=>{wk()},400)};typeof window<"u"&&typeof document<"u"&&(window.addEventListener("pageshow",()=>Kp()),document.addEventListener("visibilitychange",()=>{document.hidden||Kp()}));Zc=!1,el="ninsei.wallet.optOut",bk=()=>{try{return localStorage.getItem(el)==="1"}catch{return!1}},Yp=e=>{try{e?localStorage.setItem(el,"1"):localStorage.removeItem(el)}catch{}}});function Sk(e){try{return cl.get(e)}catch{return null}}function Jp(e,t){try{t==null?cl.remove(e):cl.set(e,t)}catch{}}function ds(){return Sk(th)}async function eh(e,t={}){let n=await fetch(e,t),r=null;try{r=await n.json()}catch{}return{status:n.status,body:r}}async function nh(){if(!Wt())throw new Error("connect the wallet first");let e=await eh("/api/auth/nonce");if(e.status!==200||!e.body||!e.body.message)throw new Error("the server did not issue a message to sign (response "+e.status+")");let t=await Qp(e.body.message),n=await eh("/api/auth/verify",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({nonce:e.body.nonce,address:er(),signature:t})});if(n.status!==200||!n.body||!n.body.token){let r=n.body&&n.body.error?n.body.error:"response "+n.status;throw new Error("login not accepted: "+r)}return Jp(th,n.body.token),Jp(gk,n.body.address),n.body.address}var th,gk,xk,kk,cl,ll=re(()=>{us();th="ninsei.auth.token",gk="ninsei.auth.address",xk=()=>{let e=typeof globalThis<"u"?globalThis.sessionStorage:void 0;return!e||typeof e.getItem!="function"?null:{get:t=>e.getItem(t),set:(t,n)=>e.setItem(t,String(n)),remove:t=>e.removeItem(t)}},kk=()=>{let e=new Map;return{get:t=>e.has(t)?e.get(t):null,set:(t,n)=>e.set(t,String(n)),remove:t=>e.delete(t)}},cl=xk()||kk()});function oh({poolSeen:e,soft:t=Tt.softSec,hard:n=Tt.hardSec}={}){let r=rh(t,Tt.softSec),o=rh(n,Tt.hardSec),i=Math.min(r,o);return e?i:o}var Tt,rh,ih=re(()=>{Tt={softSec:600,hardSec:1200},rh=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?Math.floor(n):t}});function yt(){return Date.now()}function Bo(e,t=yt()){return Math.max(0,(t-e.realStart)*e.speed)}function tr(e,t){return e.simStartWall+t}var sh=re(()=>{});var Ho={};Be(Ho,{getInfo:()=>Ro,height:()=>ul,lastError:()=>ch,nodeUrl:()=>Tk,snapshot:()=>Co,startPolling:()=>Ik});async function _k(e,t={},n="/json_rpc"){let r=new AbortController,o=setTimeout(()=>r.abort(),Ek);try{let i=await fetch(ah+n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:"ninsei-demo",method:e,params:t}),signal:r.signal});if(!i.ok)throw new Error("HTTP "+i.status);let s=await i.json();if(s.error)throw new Error(s.error.message||"RPC error");return s.result}finally{clearTimeout(o)}}function Co(){return xn.data}function ch(){return xn.error}async function ul(){let e=await Ro();return e?e.height:null}async function Ro({force:e=!1}={}){return xn.data&&Date.now()-xn.at<Ak&&!e?xn.data:Po||(Po=_k("get_info").then(n=>(xn={at:Date.now(),data:Nk(n),error:null},xn.data)).catch(n=>(xn={at:Date.now(),data:null,error:n.message},null)).finally(()=>{Po=null}),Po)}function Nk(e){return{height:e.height,nettype:e.nettype||(e.mainnet?"mainnet":e.stagenet?"stagenet":"testnet"),offline:!!e.offline,busySyncing:!!e.busy_syncing,version:e.version,target:e.target,txPoolSize:e.tx_pool_size,outgoing:e.outgoing_connections_count,incoming:e.incoming_connections_count,databaseSizeGb:e.database_size?Math.round(e.database_size/1024**3):null,fetchedAt:Date.now()}}function Ik(e,t=3e4){fs&&clearInterval(fs);let n=async()=>{let r=await Ro({force:!0});e&&e(r,ch())};return n(),fs=setInterval(n,t),()=>clearInterval(fs)}var ah,Ek,Ak,xn,Po,fs,Tk,Lo=re(()=>{mt();ah=ve.node,Ek=8e3,Ak=15e3,xn={at:0,data:null,error:null},Po=null;fs=null;Tk=ah});function _r(...e){let t=e.join("|"),n=2166136261;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=n*16777619>>>0;return"0x"+n.toString(16).padStart(8,"0")+Xi(28)}function Ok(e){return"0x"+_r("escrow",e).slice(2,42)}function Bk(e){return"8"+_r("xmrlock",e).slice(2,96)}function lh({swapId:e,ethAmountUsd:t,ethUsd:n}){return{mock:!0,txHash:_r("fund",e),escrow:Ok(e),ethAmount:n>0?t/n:0,valueUsd:t,gasUsd:.21,method:"simulated funding (no real transaction)",confirmations:1}}function uh({swapId:e,xmrAmount:t}){return{mock:!0,txid:_r("xmrtx",e),address:Bk(e),amount:t,viewKeyVerified:!0,unlocked:"1 of 2 spend key shares revealed (DLEQ bound)"}}function dl({swapId:e}){return{mock:!0,txid:_r("sweep",e)}}function fl({swapId:e,by:t}){return{mock:!0,txHash:_r("refund",e,t),by:t}}function dh(e,t){let n=e.timeline.confTarget;if(e.chainMode==="live"){let i=e.xmr&&e.xmr.lockHeight,s=Co();return i&&s&&typeof s.height=="number"&&s.height>=i?Math.max(0,Math.min(n,s.height-i)):(e.xmr,0)}let r=e.timeline.lockAtSim;if(r===null||t<r)return 0;let o=Math.floor((t-r)/e.timeline.blockSim);return Math.max(0,Math.min(n,o))}var pl=re(()=>{Yi();Lo()});function Sn(e=Zt.xmrSource){return e==="app"}function Ck(e,t){let n=e.timeline&&e.timeline.confTarget||ve.confirmTarget,r=e.timeline?e.timeline.lockAtSim:0,o=r!==null&&t>=r,i=dh(e,t),s=o?i>=n?kn.READY:kn.FUNDED:kn.AWAITING,a=Number(e.xmr&&e.xmr.received),c=o?Number.isFinite(a)?a:e.xmrAmount:0;return{live:!1,status:s,received:c,unlocked:c,locked:0,lockedUntil:null,arrived:c,confirmations:i,confTarget:n,txids:e.xmr&&e.xmr.txid?[e.xmr.txid]:[],address:e.xmr&&e.xmr.address||null,sweepTxid:e.xmr&&e.xmr.sweepTxid||null,error:null}}function Rk(e){let t=e.timeline&&e.timeline.confTarget||ve.confirmTarget,n=e.xmrSession;return n?{live:!0,status:e.xmrSessionError?"error":n.status,received:Number(n.receivedXmr)||0,unlocked:Number(n.receivedXmr)||0,locked:Number(n.lockedXmr)||0,lockedUntil:n.lockedUntil||null,arrived:(Number(n.receivedXmr)||0)+(Number(n.lockedXmr)||0),confirmations:n.confirmations,confTarget:t,txids:n.fundingTxids,address:n.address||e.swapWallet&&e.swapWallet.address||null,sweepTxid:n.sweepTxid,error:e.xmrSessionError||null}:{live:!0,status:e.xmrSessionError?"error":"opening",received:0,unlocked:0,locked:0,lockedUntil:null,arrived:0,confirmations:0,confTarget:t,txids:[],address:e.swapWallet&&e.swapWallet.address||null,sweepTxid:null,error:e.xmrSessionError||null}}function fh(e,t){return Sn(e&&e.xmrSource)?Rk(e):Ck(e,t)}function ph(e,t="stagenet"){return e?`https://${t==="mainnet"?"":t+"."}xmrchain.net/tx/${e}`:null}var kn,hh=re(()=>{mt();pl();kn={AWAITING:"awaiting_funding",FUNDED:"funded",LOCKED:"xmr_locked",READY:"ready",SWEPT:"swept",CLOSED:"closed"}});var fe={};Be(fe,{STEP_LABELS:()=>yl,TERMINAL:()=>Nr,activeSwaps:()=>xl,addServerSwaps:()=>Lk,allSwaps:()=>bh,confirmReady:()=>Sl,createReverseSwap:()=>gl,createSwap:()=>bl,dealSwapIds:()=>Al,derive:()=>Do,forgetSwap:()=>Hk,getSwap:()=>Ir,halvesWalletOf:()=>ps,onNotify:()=>Mk,refundEth:()=>El,refundHalfRevealed:()=>kh,saveSwap:()=>kl,serverRestoreHeightFor:()=>_l,serverRowToSwap:()=>gh,setLiveFocus:()=>Nl,startTicker:()=>jk,subscribe:()=>Dk,sweepNow:()=>vl,tick:()=>vh,xmrAmountCheck:()=>Sh});function bl(e,t=null){let n=t?t.loadState():rt(),r=Date.now(),o={id:Ic(),side:e.side||"buy",scenario:e.scenario||"happy",speed:e.speed||60,network:e.network||Nt,moneroNetwork:e.moneroNetwork||ve.networkType,realStart:r,simStartWall:r,createdAt:new Date(r).toISOString(),payToken:e.payToken,payAmount:Number(e.payAmount),xmrAmount:Number(e.xmrAmount),rate:Number(e.rate),fee:Number(e.fee),maker:{id:e.makerId,name:e.makerName,spread:e.makerSpread},dexSpread:e.dexSpread,gasUsd:e.gasUsd,receiveAddress:e.receiveAddress,quoteSignature:e.quoteSignature,swapWallet:e.swapWallet||null,timeline:{fundAtSim:0,lockAtSim:e.scenario==="maker_no_lock"?null:It.makerLock,blockSim:ve.blockTimeSim,confTarget:ve.confirmTarget,t0Sim:It.t0Refund},chainMode:e.chainMode||Jt.defaultChainMode,xmrSource:e.xmrSource||Zt.xmrSource,xmrSession:null,xmrSessionError:null,events:[],escrow:null,xmr:null,settlement:null,log:[]};if(o.chainMode!=="live"){let i=lh({swapId:o.id,ethAmountUsd:o.payAmount,ethUsd:3212.4});o.escrow={address:i.escrow,fundTx:i.txHash,method:i.method,fundedAtSim:0,gasUsd:i.gasUsd},nn(o,0,"Escrow funded",`eth escrow ${i.escrow}`)}else o.escrow={address:null,fundTx:null,method:null,fundedAtSim:0,gasUsd:e.gasUsd??null};return n.swaps[o.id]=o,n.activeSwapId=o.id,t?t.saveState(n):jt(n),o}function gl(e={}){let t=rt(),n=Date.now(),r=Number(e.xmrAmount),o={id:Ic(),side:"reverse",scenario:"happy",speed:Number(e.speed)||60,network:e.network||Nt,moneroNetwork:e.moneroNetwork||ve.networkType,realStart:n,simStartWall:n,createdAt:new Date(n).toISOString(),payToken:"XMR",payAmount:r,xmrAmount:r,rate:Number(e.rate)||0,fee:Number(e.fee)||0,maker:{id:e.providerId||null,name:e.providerName||null,spread:null},receiveAddress:e.claimer||null,quoteSignature:null,ticket:e.ticketId||null,timeline:{fundAtSim:0,lockAtSim:0,blockSim:ve.blockTimeSim,confTarget:ve.confirmTarget,t0Sim:It.t0Refund},chainMode:e.chainMode||Jt.defaultChainMode,xmrSource:e.xmrSource||Zt.xmrSource,xmrSession:null,xmrSessionError:null,events:[],escrow:{address:e.escrowAddress||null,moneroAddress:e.moneroAddress||null,half:e.ownSpendHalf||null,viewHalf:e.ownViewHalf||null,counterViewHalf:e.counterViewHalf||null,counterViewPoint:e.counterViewPoint||null,counterSpendPoint:e.counterSpendPoint||null,moneroNetwork:e.moneroNetwork||ve.networkType,birthHeight:e.escrowBirthHeight||null,readyBy:e.readyBy||null,t1:e.t1||null,counterHalf:null},xmr:null,settlement:null,log:[]};return t.swaps[o.id]=o,t.activeSwapId=o.id,jt(t),o}function nn(e,t,n,r){e.log.push({atSim:t,wall:tr(e,t),title:n,detail:r||""}),console.log(`[swap ${e.id}] ${n}${r?" - "+r:""}`)}function ps(e){let t=e&&e.escrow||{};return!t.half||!t.viewHalf||!t.counterViewHalf||!t.moneroAddress?null:{source:"halves",library:"monero-js",network:t.moneroNetwork||ve.networkType,address:t.moneroAddress,subaddress:null,spendHalf:t.half,viewHalf:t.viewHalf,otherSpendPoint:t.counterSpendPoint||t.edPointClaimer||null,otherViewPoint:t.counterViewPoint||null,otherViewHalf:t.counterViewHalf}}function Hk(e,t=null){let n=t?t.loadState():rt();return n.swaps[e]?(delete n.swaps[e],t?t.saveState(n):jt(n),!0):!1}function Ir(e,t=null){return(t?t.loadState():rt()).swaps[e]||null}function bh(){let e=rt();return Object.values(e.swaps).sort((t,n)=>t.realStart<n.realStart?1:-1)}function gh(e){let t=String(e&&e.escrow||"").toLowerCase();return{id:String(e.id),network:e.network||null,chain:e.network||null,source:"server",status:"in_progress",escrow:{address:t,t0:e.t0!=null?Number(e.t0):null,t1:e.t1!=null?Number(e.t1):null,hashlock:e.hashlock||null,amountWei:e.amount!=null?String(e.amount):null,fromServer:!0},log:[],events:[]}}function Lk(e,t=null){if(!Array.isArray(e)||e.length===0)return 0;let n=t?t.loadState():rt(),r=0;for(let o of e)!o||!o.id||!o.escrow||n.swaps[o.id]||(n.swaps[o.id]=gh(o),r+=1);return r&&(t?t.saveState(n):jt(n)),r}function xl(){return bh().filter(e=>!e.settlement)}function kl(e,t=null){return hs(e,t)}function hs(e,t=null){let n=t?t.loadState():rt();return n.swaps[e.id]=e,t?t.saveState(n):jt(n),e}function mh(e,t,n,r={}){return e.events.push({type:t,atSim:n,...r}),e}function xh(e,t){return e.events.find(n=>n.type===t)||null}function Sl(e,t=null){let n=Ir(e,t);if(!n||n.settlement)return n;if(!Do(n).can.ready)throw new Error("ready() is not available in this phase");let o=Bo(n);return mh(n,"ready",o),nn(n,o,"ready() called by you","maker may now claim the ETH escrow"),xh(n,"funded_note")||mh(n,"funded_note",0),hs(n,t)}function kh(e){let t=e&&e.escrow||{};return t.revealedHalf||t.counterHalf||null}function vl(e,t=null){let n=Ir(e,t);if(!n||n.settlement&&!(n.settlement.kind==="refund_eth"&&n.side==="reverse"))return n;if(!Do(n).can.sweep)throw new Error("sweep is not available in this phase");let o=Bo(n),i=dl({swapId:n.id});n.xmr=n.xmr||{},n.xmr.sweepTxid=i.txid;let s=!!(n.settlement&&n.settlement.kind==="refund_eth");return n.settlement={kind:"success",phase:Nr.success.phase,atSim:o,txid:i.txid,by:"you",...s?{recovered:!0}:{}},nn(n,o,"XMR swept to your address",i.txid),hs(n,t)}function El(e,t="you",n=null){let r=Ir(e,n);if(!r||r.settlement)return r;if(!Do(r).can.refund)throw new Error("refund is not available in this phase");let i=Bo(r),s=fl({swapId:r.id,by:t});return r.settlement={kind:"refund_eth",phase:Nr.refunded_eth.phase,atSim:i,txHash:s.txHash,by:t},nn(r,i,`ETH refunded to your wallet (${t})`,s.txHash),hs(r,n)}function wh(e){return((Je(e&&e.network||Nt)||{}).escrow||{}).mode==="live"}function Sh(e,t){let n=Number(e&&e.xmrAmount),r=Number.isFinite(n)&&n>0,o=t&&t.arrived!==null&&t.arrived!==void 0?t.arrived:t?t.received:null,i=o!=null&&Number.isFinite(Number(o))?Number(o):null;return r?i===null?{ok:!1,checked:!0,expected:n,seen:null,why:"the amount of XMR on the address is not known ("+n+" XMR was quoted): ready stays closed until the sum is seen"}:i+yh<n?{ok:!1,checked:!0,expected:n,seen:i,why:"only "+i+" XMR arrived, the quote promised "+n+" XMR: ready is blocked - the escrow would pay out for less than agreed"}:i>n+yh?{ok:!1,checked:!0,expected:n,seen:i,why:i+" XMR arrived, but the record promises "+n+" XMR: the sum on the address does not match the quoted trade - ready is blocked until they agree (a node paying more than it quoted loses its spread)"}:{ok:!0,checked:!0,expected:n,seen:i,why:null}:{ok:!0,checked:!1,expected:null,seen:i,why:"the record has no quoted XMR amount, so the arrived sum cannot be compared - this is named, not assumed"}}function Do(e,t=yt()){let n=Bo(e,t),r=e.timeline,i=(P=>xh(e,P))("ready"),s=Sn(e.xmrSource),a=fh(e,n),c=Number(a.arrived!==void 0&&a.arrived!==null?a.arrived:a.received||0),l=s?c>0?0:null:r.lockAtSim,u=a.confirmations,d=s?c>0:l!==null&&n>=l,p=i?i.atSim:null,m=e.escrow&&e.escrow.readyBy?Number(e.escrow.readyBy)*1e3:null,w=e.escrow&&e.escrow.t1?Number(e.escrow.t1)*1e3:null,y=Number(a.arrived!==void 0&&a.arrived!==null?a.arrived:a.received||0)>0,b=(()=>{if(e.side!=="reverse"||m===null)return null;let P=m-Tt.hardSec*1e3,j=P+Tt.softSec*1e3,L=oh({poolSeen:y,soft:Tt.softSec,hard:Tt.hardSec}),z=!y&&yt()>=j,W=z?P+L*1e3:j;return{startMs:P,atMs:W,leftMs:W-yt(),seen:y,extended:z,softSec:Tt.softSec,hardSec:Tt.hardSec,windowSec:L}})(),x=p!==null&&e.scenario!=="maker_stall"?p+It.makerClaim:null,I=x!==null?x+It.sweep:null,E=l!==null?l+It.readyWindow:null,U=E!==null?E+It.makerReclaim:null,S=p!==null?p+It.t1Refund:null,B=p===null&&U!==null&&n>=U,R={ready:!1,sweep:!1,refund:!1},A="xmr_locked",N="Waiting",f=null,k=null;if(e.settlement){if(A=e.settlement.phase,N=Object.values(Nr).find(P=>P.phase===e.settlement.phase)?.label||"Settled",e.settlement.kind==="refund_eth"&&e.side==="reverse"){let P=kh(e),j=c>0;R.sweep=!!(P&&j&&ps(e)),k=R.sweep?"The refund published the provider's half, so your XMR can be swept back from the swap's one-time address to your own wallet.":j?"The refund is done and your XMR is on the swap's one-time address, but the provider's half of the spend key is not published yet: sweeping needs both halves, so the button waits for the chain.":"The refund is done, but no XMR is on the swap's one-time address: there is nothing of yours to sweep back."}}else if(s&&p===null&&m!==null&&yt()>=m&&(w===null||yt()<w))A="dead_zone",N="Ready deadline passed - the refund opens at T1",R.ready=!1,R.refund=!1,R.refundByAnyone=!1,k="The ready() deadline has passed without your confirmation, so the maker cannot claim - and the escrow refuses a refund before T1 while the mark is absent. Nothing can be signed now; the refund opens at T1 and returns your ETH and publishes your half. "+(w!==null?"T1: "+new Date(w).toISOString()+".":"");else if(s&&p===null)if(w!==null&&yt()>=w)A="refund_available",N="Claim deadline passed - the refund is open",R.ready=!1,R.refund=!0,R.refundByAnyone=!0,k="The claim deadline passed without the ready mark. The refund is open to anyone who can present the depositor's half - that half is yours in the recovery file. It returns your ETH and publishes your half.";else if(a.status===kn.LOCKED){A="xmr_unlock_pending",N="XMR is on your address but locked on-chain",R.ready=!1;let P=a.lockedUntil||{},j=P.untilHeight!==null&&P.untilHeight!==void 0?"block "+P.untilHeight:P.untilTime!==null&&P.untilTime!==void 0?new Date(Number(P.untilTime)*1e3).toISOString()+" UTC":"a time the sender set";k="The sender set the transaction's unlock_time: "+(a.locked||0)+" XMR is on your address but cannot be spent until "+j+". Ready stays closed until then - confirming now would let the maker take the ETH behind locked XMR."}else if(!a.received)A="maker_locking",N="Waiting for XMR to arrive",k=a.error?"Backend unavailable: "+a.error:"The backend watches your swap address with the view key only - it cannot spend your XMR.";else if(a.status===kn.READY){A="xmr_locked",N="XMR received and confirmed ("+u+"/"+r.confTarget+")";let P=Sh(e,a);R.ready=P.ok,R.readyAmount=P,k=P.ok?"Confirm that you see the XMR on your address (ready).":P.why}else a.status===kn.SWEPT?(A="success",N="XMR delivered"):(A="xmr_locked",N="XMR received, waiting for confirmations ("+u+"/"+r.confTarget+")",k="About "+Math.max(1,Math.round((r.confTarget-u)*r.blockSim/6e4))+" min left of confirmations.");else if(l===null)n>=r.t0Sim?(A="refund_available",N="Maker did not lock XMR",f=r.t0Sim,R.refund=!0,k="The maker never locked XMR. You can take your ETH back from the escrow - no permission needed."):(A="maker_locking",N="Waiting for the maker to lock XMR",k="If the maker does not lock XMR by T0, you get a refund button.");else if(!d)A="maker_locking",N="Maker is locking XMR";else if(B)A="xmr_reclaimed",N="XMR returned to the maker",f=U,R.refund=!0,k="You did not confirm (ready) in time, so the maker took the XMR back. Your ETH is still in escrow - refund it.";else if(p===null)A="xmr_locked",N=u<r.confTarget?`Waiting for Monero confirmations (${u}/${r.confTarget})`:"XMR locked and verified - waiting for you",R.ready=s?a.status===kn.READY:u>=r.confTarget,f=E,k=u<r.confTarget?`About ${Math.max(1,Math.round((r.confTarget-u)*r.blockSim/6e4))} min left of confirmations. You can close this tab.`:"Confirm that you see the lock with your view key (ready). Until you do, the maker keeps the XMR.";else if(x!==null&&n<x)A="ready_wait_claim",N="Waiting for the maker to claim ETH",k="The maker claims the escrow and reveals the secret; your swap wallet uses it to sweep the XMR.";else if(x!==null&&n>=x&&I!==null&&n>=I)A="success",N="XMR delivered",R.sweep=!0;else if(x!==null)A="claimed",N="Secret revealed - sweeping XMR",R.sweep=!0;else{A="refund_available",N="Maker did not claim in time",f=S;let P=e.escrow&&e.escrow.t0?e.escrow.t0*1e3:null,j=e.escrow&&e.escrow.t1?e.escrow.t1*1e3:null,L=yt();j!==null?P!==null?(R.refund=L>=P,R.refundByAnyone=L>=j):(R.refund=L>=j,R.refundByAnyone=R.refund):wh(e)?R.refund=!1:R.refund=n>=S,k=R.refund?R.refundByAnyone?"The claim deadline passed: the refund is open to anyone who can present the half of the depositor - that half is YOURS (it is in your recovery file), and the watchtower does not have it. Press Refund my ETH, or restore the file if you have lost this tab.":"The maker missed the claim deadline. You can take your ETH back from the escrow yourself.":P!==null?"This order predates the one-deadline rule: you could refund from T0, and from T1 anyone can.":"Waiting for T1: before it the ETH can only be claimed with the secret. From T1 the claim closes and the refund opens - and it always pays you, never the caller."}let _=u>=r.confTarget,K=x!==null&&n>=x,H=[{key:"funded",done:!0,atSim:0},{key:"maker_locking",done:d,active:!d&&!e.settlement&&l!==null,failed:l===null&&n>=r.t0Sim,atSim:l},{key:"xmr_locked",done:_&&!B,active:d&&!_,atSim:l},{key:"ready",done:p!==null,active:_&&p===null&&!B,atSim:p},{key:"claimed",done:K,active:p!==null&&!K,atSim:x},{key:"swept",done:!!e.settlement&&e.settlement.kind==="success",active:K&&!e.settlement,atSim:Fk(e)}];return{swap:e,sim:n,simWallTime:tr(e,n),phase:A,phaseLabel:N,note:k,conf:u,confTarget:r.confTarget,confProgress:r.confTarget?u/r.confTarget:0,deadlines:{t0:e.escrow&&e.escrow.t0?e.escrow.t0*1e3:e.escrow?null:tr(e,r.t0Sim),t0Sim:r.t0Sim,lockAtSim:l,readyBy:E!==null?tr(e,E):null,readyBySim:E,t1:e.escrow&&e.escrow.t1?e.escrow.t1*1e3:S!==null?tr(e,S):null,t1Sim:S,refundAfterSim:f,refundAfterWall:f!==null?tr(e,f):null},refundLeftSim:f!==null?f-n:null,xmr:{live:a.live,source:e.xmrSource,status:a.status,received:a.received,locked:a.locked||0,lockedUntil:a.lockedUntil||null,arrived:Number(a.arrived!==void 0&&a.arrived!==null?a.arrived:a.received||0),confirmations:a.confirmations,confTarget:a.confTarget,txids:a.txids,address:a.address,explorer:ph(a.txids[0],e.xmrSession&&e.xmrSession.network||"stagenet"),error:a.error,sweepTxid:a.sweepTxid},simulated:{evm:!wh(e),xmr:!a.live},can:R,readyDeadline:{atMs:m,soonMs:m!==null&&p===null?m-yt():null,soon:m!==null&&p===null&&m-yt()>0&&m-yt()<=Number(_o.readyLeadWarnSec||0)*1e3},xmrAmount:{expected:(()=>{let P=Number(e.xmrAmount);return Number.isFinite(P)&&P>0?P:null})(),seen:a.received!==null&&a.received!==void 0?Number(a.received):null},steps:H,sellWindow:b,terminal:e.settlement,xmrReclaimed:B}}function Fk(e){return e.settlement&&e.settlement.kind==="success"?e.settlement.atSim:null}function Dk(e){return ml.add(e),()=>ml.delete(e)}function Uk(){for(let e of ml)try{e()}catch(t){console.error(t)}}function Al(e){let t=new Set([String(e&&e.id||"")].filter(Boolean)),r=(()=>{try{return ps(e)||{}}catch{return{}}})().address||e&&e.escrow&&e.escrow.moneroAddress||null;if(!r)return[...t];for(let o of Object.values((rt()||{}).swaps||{})){if(!o||!o.id)continue;(()=>{try{return ps(o)||{}}catch{return{}}})().address===r&&t.add(String(o.id))}return[...t]}async function _l(){return null}function Nl(e){return new Set(Array.isArray(e)?e.map(String):[]).size}function vh(){let e=rt(),t=!1;for(let n of Object.values(e.swaps)){if(n.settlement)continue;let r=Do(n);if(!Sn(n.xmrSource)&&!n.xmr&&r.deadlines.lockAtSim!==null&&r.sim>=r.deadlines.lockAtSim){let o=uh({swapId:n.id,xmrAmount:n.xmrAmount});if(n.xmr={...o,reclaimed:!1,sweepTxid:null},n.chainMode==="live"){let s=Co();n.xmr.lockHeight=s?s.height:null,n.xmr.lockHeight||Ro({force:!0}).then(a=>{if(a&&!n.settlement){let c=rt();c.swaps[n.id]&&(c.swaps[n.id].xmr.lockHeight=a.height,jt(c))}})}nn(n,r.sim,"Maker locked XMR on the shared address",o.txid);let i=n.id+":lock";Vt.has(i)||(Vt.add(i),Fo(n.xmrAmount.toFixed(4)+" XMR locked; view key verified","ok")),t=!0}if(Sn(n.xmrSource)&&!n.xmr&&r.xmr&&r.xmr.received>0){n.xmr={mock:!1,txid:r.xmr.txids[0]||null,address:r.xmr.address,amount:r.xmr.received,confirmations:r.xmr.confirmations,status:r.xmr.status,explorer:r.xmr.explorer,reclaimed:!1,sweepTxid:null},nn(n,r.sim,"XMR received (backend, "+(n.xmrSession&&n.xmrSession.network||"stagenet")+")",n.xmr.txid||"");let o=n.id+":xmr-in";Vt.has(o)||(Vt.add(o),Fo(r.xmr.received.toFixed(6)+" XMR received; confirmations "+r.xmr.confirmations+"/"+r.xmr.confTarget,"ok")),t=!0}if(!Sn(n.xmrSource)&&r.can.sweep&&r.phase==="success"){let o=r.sim;n.xmr.sweepTxid=dl({swapId:n.id}).txid,n.settlement={kind:"success",phase:Nr.success.phase,atSim:o,txid:n.xmr.sweepTxid,by:"your swap wallet"},nn(n,o,"XMR swept to your address",n.xmr.sweepTxid);let i=n.id+":success";Vt.has(i)||(Vt.add(i),Fo("Swap "+n.id+" complete: XMR is on your address","ok")),t=!0;continue}if(!Sn(n.xmrSource)&&r.can.refund&&r.refundLeftSim!==null&&r.refundLeftSim<=-It.watchtowerGrace){let o=r.sim,i=fl({swapId:n.id,by:"watchtower"});n.settlement={kind:"refund_eth",phase:Nr.refunded_eth.phase,atSim:o,txHash:i.txHash,by:"watchtower"},nn(n,o,"Watchtower refunded your ETH",i.txHash);let s=n.id+":refund";Vt.has(s)||(Vt.add(s),Fo("Watchtower refunded the ETH escrow of swap "+n.id,"bad")),t=!0;continue}if(!Sn(n.xmrSource)&&n.xmr&&r.xmrReclaimed&&!n.xmr.reclaimed){n.xmr.reclaimed=!0,nn(n,r.sim,"Maker reclaimed the XMR",n.xmr.txid);let o=n.id+":reclaim";Vt.has(o)||(Vt.add(o),Fo("Maker took the XMR back: no ready() call in time","bad")),t=!0}}t&&jt(e)}function Mk(e){wl.fn=e}function Fo(e,t){wl.fn&&wl.fn(e,t)}function jk(e=400){hl&&clearInterval(hl),hl=setInterval(()=>{try{vh()}catch(t){console.error(t)}Uk()},e)}var yl,Nr,yh,hl,ml,Vt,wl,Uo=re(()=>{mt();ih();sh();is();Yi();pl();Lo();hh();yl=[["funded","Funded on-chain"],["maker_locking","Maker locking XMR"],["xmr_locked","XMR locked"],["ready","Verified by you"],["claimed","Claimed by maker"],["swept","Sent to your address"]],Nr={success:{phase:"success",label:"XMR delivered"},refunded_eth:{phase:"refunded_eth",label:"ETH refunded"}};yh=1e-6;hl=null,ml=new Set,Vt=new Set;wl={fn:null}});function me(e,t=32){let n=String(e).trim(),r;if(/^0x[0-9a-fA-F]*$/.test(n))r=n.slice(2).toLowerCase(),r.length===0&&(r="0");else if(/^[0-9]+$/.test(n))r=BigInt(n).toString(16);else throw new Error("not a number and not hex: "+e);if(!/^[0-9a-f]*$/.test(r))throw new Error("not hex: "+e);if(r.length>t*2)throw new Error(`value does not fit in ${t} bytes: ${e}`);return r.padStart(t*2,"0")}function Jk(e){for(let n of Tl)if(e[n]===void 0||e[n]===null||e[n]==="")throw new Error("the quote has no field: "+n);for(let n of Qk)if(!/^(0x)?[0-9a-fA-F]{40}$/.test(String(e[n]).trim()))throw new Error("quote field "+n+" is not an address");for(let n of Zk)if(!/^(0x)?[0-9a-fA-F]{64}$/.test(String(e[n]).trim()))throw new Error("quote field "+n+" is not bytes32");let t={provider:me(e.provider,32),quoteKey:me(e.quoteKey,32),registry:me(e.registry,32),cashier:me(e.cashier,32),locker:me(e.locker,32),claimer:me(e.claimer,32),amount:me(e.amount,32),readyBy:me(e.readyBy,32),t1:me(e.t1,32),salt:me(Tr(e.salt),32),commitHalfClaimer:me(Tr(e.commitHalfClaimer),32),edPointClaimer:me(Tr(e.edPointClaimer),32),chainId:me(e.chainId,32),feeBps:me(e.feeBps,32),fee:me(e.fee,32),feeRecipient:me(e.feeRecipient,32),validUntil:me(e.validUntil,32),nonce:me(e.nonce,32),xmrAmount:me(e.xmrAmount,32),claimTip:me(e.claimTip,32),commitHalfLocker:me(Tr(e.commitHalfLocker),32),edPointLocker:me(Tr(e.edPointLocker),32),edViewPointLocker:me(Tr(e.edViewPointLocker),32)};return Tl.map(n=>t[n]).join("")}function eS(e){let t=String(e||"").replace(/^0x/,"");if(!/^[0-9a-fA-F]{130}$/.test(t))throw new Error("the quote signature must be 65 bytes: "+String(e).slice(0,20));let n=t.slice(0,64),r=t.slice(64,128),o=parseInt(t.slice(128,130),16);return o<27&&(o+=27),me("0x"+n,32)+me("0x"+r,32)+me(o,32)}function Ph(e){return Jk(e)+eS(e.signature)}function Bl(e){return Ol.predict+Ph(e)}function Pl(e){return Ol.createOrderAndFund+Ph(e)}function xs(e){let t=String(e||"").replace(/^0x/,"");if(t.length<64)throw new Error("short answer: "+e);return"0x"+t.slice(24,64)}function tS(e){let t=bs[e];if(typeof t!="string"||!/^0x[0-9a-f]{8}$/.test(t))throw new Error("no such factory read: "+e);return t}function Ch(e){return xs(e)}function Rh(e){let t=String(e||"").replace(/^0x/,"");if(t.length<64)throw new Error("short answer from implementationCodeHash(): "+e);return"0x"+t.slice(0,64).toLowerCase()}function Hh({implementation:e,implementationCodeHash:t,code:n,hashCode:r,policy:o}={}){if(!e||!/^0x[0-9a-fA-F]{40}$/.test(String(e)))return{ok:!1,why:"implementation-missing"};if(!t||!/^0x[0-9a-fA-F]{64}$/.test(String(t)))return{ok:!1,why:"code-hash-missing"};if(n==null||n==="0x"||n==="0x0")return{ok:!1,why:"implementation-has-no-code"};let i=String(t).toLowerCase();if(Array.isArray(o)&&o.length&&!o.map(s=>String(s).toLowerCase()).includes(i))return{ok:!1,why:"implementation-code-unknown",codeHash:i};if(typeof r=="function"){let s=String(r(n)).toLowerCase();if(s!==i)return{ok:!1,why:"implementation-code-mismatch",got:s,want:i}}return{ok:!0,codeHash:i}}async function nS({factory:e,read:t,code:n,policy:r=null,hashCode:o=null}={}){if(!e||!/^0x[0-9a-fA-F]{40}$/.test(String(e)))return{ok:!1,why:"factory-missing"};if(typeof t!="function")return{ok:!1,why:"no-chain-read"};if(typeof n!="function")return{ok:!1,why:"no-code-read"};let i,s;try{i=await t({to:e,data:bs.implementation}),s=await t({to:e,data:bs.implementationCodeHash})}catch{return{ok:!1,why:"implementation-unreadable",factory:String(e).toLowerCase()}}let a,c;try{a=Ch(i),c=Rh(s)}catch{return{ok:!1,why:"implementation-unreadable",factory:String(e).toLowerCase()}}let l;try{l=await n(a)}catch{return{ok:!1,why:"implementation-code-unreadable",implementation:a}}return{...Hh({implementation:a,implementationCodeHash:c,code:l,hashCode:o,policy:r}),implementation:a,implementationCodeHash:c}}var Ol,gs,Bh,qk,Tl,Qk,Zk,Tr,bs,Cl=re(()=>{Ol={predict:"0x76e3fdc8",createOrderAndFund:"0x50db6721"},gs="0x09add13cca47b227c377447295bfaa00ef3169bfed0f5513d06f8be04af78aad",Bh="0xa22cdabaed3cce4f51dde71626a108ffe9c7bc4216fd14d5e719f892e2fd8ab0",qk=Object.freeze([gs,Bh]),Tl=["provider","quoteKey","registry","cashier","locker","claimer","amount","readyBy","t1","salt","commitHalfClaimer","edPointClaimer","chainId","feeBps","fee","feeRecipient","validUntil","nonce","xmrAmount","claimTip","commitHalfLocker","edPointLocker","edViewPointLocker"],Qk=["provider","quoteKey","registry","cashier","locker","claimer","feeRecipient"],Zk=["salt","commitHalfClaimer","edPointClaimer","commitHalfLocker","edPointLocker","edViewPointLocker"];Tr=e=>{let t=String(e??"").trim();return/^[0-9a-fA-F]{64}$/.test(t)?"0x"+t.toLowerCase():t};bs={implementation:"0x5c60da1b",implementationCodeHash:"0xbc0a3981"}});var Or={};Be(Or,{ESCROW_METHODS:()=>rn,decodeBytes32:()=>Wh,decodeStatus:()=>Ss,decodeUint64:()=>Vh,encodeClaim:()=>Fh,encodeMarkReady:()=>Lh,encodeRead:()=>Kh,encodeRefund:()=>Uh,encodeStatus:()=>ks,encodeT1:()=>Mh,encodeTermsHash:()=>jh,orderTerms:()=>$h});function Lh(){return rn.markReady}function Fh(e){return rn.claim+Dh(e,"secret")}function Dh(e,t){let n=String(e||"").replace(/^0x/i,"").toLowerCase();if(!/^[0-9a-f]{1,64}$/.test(n))throw new Error(t+" must be a number of up to 32 bytes: "+e);return n.padStart(64,"0")}function Uh(e){return rn.refund+Dh(e,"half")}function ks(){return rn.status}function Mh(){return rn.t1}function jh(){return rn.termsHash}function Kh(e){let t=rn[e];if(typeof t!="string"||!/^0x[0-9a-f]{8}$/.test(t))throw new Error("no such escrow method: "+e);return t}function Wh(e,t="value"){let n=String(e||"").replace(/^0x/,"");if(n.length<64)throw new Error("short answer "+t+": "+e);return"0x"+n.slice(0,64).toLowerCase()}function Vh(e,t="value"){let n=String(e||"").replace(/^0x/,"");if(n.length<64)throw new Error("short answer "+t+": "+e);let r=BigInt("0x"+n.slice(0,64));if(r>18446744073709551615n)throw new Error("answer "+t+" does not fit in uint64: "+r);return Number(r)}function Ss(e){let t=String(e||"").replace(/^0x/,"");if(t.length<256)throw new Error("short status() answer: "+e);let n=r=>t.slice(r*64,(r+1)*64);return{isFunded:BigInt("0x"+n(0))!==0n,isClaimed:BigInt("0x"+n(1))!==0n,isRefunded:BigInt("0x"+n(2))!==0n,balance:BigInt("0x"+n(3))}}function $h({locker:e,claimer:t,commitHalfLocker:n,commitHalfClaimer:r,edPointLocker:o,edPointClaimer:i,amount:s,readyBy:a,t1:c}){for(let[l,u]of Object.entries({locker:e,claimer:t,commitHalfLocker:n,commitHalfClaimer:r,edPointLocker:o,edPointClaimer:i,amount:s}))if(u==null||u==="")throw new Error("order term not set: "+l);if(Number(a)<=Math.floor(Date.now()/1e3))throw new Error("readyBy must be in the future: "+a);if(Number(c)<=Number(a))throw new Error("t1 must be later than readyBy");return{locker:e,claimer:t,commitHalfLocker:n,commitHalfClaimer:r,edPointLocker:o,edPointClaimer:i,amount:s,readyBy:a,t1:c}}var rn,vs=re(()=>{rn={markReady:"0x1ca087e7",claim:"0xbd66528a",refund:"0x7249fbb6",status:"0x200d2ed2",t1:"0xfb5343f3",readyBy:"0x53fc2f40",ready:"0x6defbf80",revealedHalf:"0x3f267bb6",edPointLocker:"0x8c03382b",edPointClaimer:"0xdd98c465",edViewPointLocker:"0x9a06a5fe",commitHalfLocker:"0x498b422e",commitHalfClaimer:"0x7d4c81f7",termsHash:"0xb311d9fd",fee:"0xddca3f43",feeBps:"0x24a9d853",feeRecipient:"0x46904840",feeOnTop:"0x2296cc23",registry:"0x7b103999",cashier:"0xed740e97",provider:"0x085d4883",quoteKey:"0x391d53ca",validUntil:"0xddac6654",nonce:"0xaffed0e0"}});function Rl(e,t){let n=BigInt(e==null||e===""?0:e),r=BigInt(Number(t)||0);if(n<0n||r<0n)throw new Error("fee: negative amount or rate");return n*r/10000n}function Xh(e){if(!e||typeof e!="object")throw new Error("no signed quote: there is nowhere to take the fee and the registry address");let t=BigInt(String(e.amount)),n=Number(e.feeBps===void 0||e.feeBps===null?0:e.feeBps);if(!Number.isFinite(n)||n<0||n>200)throw new Error("fee rate outside the ceiling: "+e.feeBps);let r=Rl(t,n);if(BigInt(String(e.fee===void 0||e.fee===null?0:e.fee))!==r)throw new Error("signed fee "+e.fee+" diverges from the formula amount * rate ("+r+") - signature not started");if(n!==0&&rS(e.feeRecipient))throw new Error("with a non-zero rate the fee recipient must be named");let o=zh(e.locker,e.provider),i=zh(e.claimer,e.provider);if(o===i)throw new Error("cannot tell who pays the fee: the provider is named neither as depositor nor as claimer");let s=i,a={bps:n,feeWei:r,totalWei:s?t+r:t,recipient:e.feeRecipient||null,feeOnTop:s,legacy:!1};return Br=a,a}function Yh(){return Br}function Gh(){return!Br||!Number.isFinite(Number(Br.bps))?null:Number(Br.bps)/1e4}async function qh(){return Br}var zh,rS,Br,Es=re(()=>{zh=(e,t)=>String(e||"").toLowerCase()===String(t||"").toLowerCase(),rS=e=>!e||/^0x0{40}$/i.test(String(e)),Br=null});function As(){let e=new Uint8Array(32);return crypto.getRandomValues(e),"0x"+Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function Qh({locker:e,claimer:t,commitHalfLocker:n,commitHalfClaimer:r,edPointLocker:o,edPointClaimer:i,edViewPointLocker:s,amountWei:a,salt:c,claimWindowSeconds:l=3600,readyWindowSeconds:u=14400,readyBy:d,t1:p}){for(let[E,U]of Object.entries({commitHalfLocker:n,commitHalfClaimer:r,edPointLocker:o,edPointClaimer:i,edViewPointLocker:s}))if(!U)throw new Error("order term not set: "+E);let m=Math.floor(Date.now()/1e3),w=d!=null&&d!=="",y=p!=null&&p!=="",b=w?Number(d):m+u,x=y?Number(p):b+l;if(!(x>b))throw new Error("the settlement deadline must be later than the readiness deadline: t1="+x+", readyBy="+b);let I=Ac({nowSec:m,readyBy:b,t1:x,..._o});if(I.blocks)throw new Error("order deadlines are not usable: "+I.reason);return{locker:e,claimer:t,commitHalfLocker:n,commitHalfClaimer:r,edPointLocker:o,edPointClaimer:i,edViewPointLocker:s,amount:String(a),readyBy:String(b),t1:String(x),salt:c}}function _s(e,t=18){let[n,r=""]=String(e).split("."),o=(r+"0".repeat(t)).slice(0,t);return BigInt(n||"0")*10n**BigInt(t)+BigInt(o||"0")}function oS({quote:e=null,nativeDecimals:t=18}={}){let n=e?e.payNative:null;if(n==null||n==="")return{ok:!1,code:"native-amount-unread",reason:"the quote carries no native amount"};let r=Number(n);if(!Number.isFinite(r)||r<=0)return{ok:!1,code:"native-amount-unread",reason:"the quote's native amount is not a positive number"};let o=Number(t);if(!Number.isInteger(o)||o<0)return{ok:!1,code:"native-amount-unread",reason:"the native decimals are not a whole number"};let i=/e/i.test(String(n))?r.toFixed(18):String(n);if(!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(i))return{ok:!1,code:"native-amount-unread",reason:"the native amount is not a decimal number"};let s;try{s=_s(i,o)}catch{return{ok:!1,code:"native-amount-unread",reason:"the native amount is not a decimal number"}}return s<=0n?{ok:!1,code:"native-amount-unread",reason:"the native amount rounds to zero wei"}:{ok:!0,wei:s.toString(),source:"native"}}function Jh(e,{factory:t=null,expectedEscrow:n=null}={}){if(!e||!Array.isArray(e.logs))return null;let r=t?String(t).toLowerCase():null,o=n?String(n).toLowerCase():null;for(let i of e.logs){if(r&&String(i&&i.address||"").toLowerCase()!==r)continue;let s=i.topics||[];if(String(s[0]).toLowerCase()!==gs||s.length<2)continue;let a="0x"+String(s[1]).slice(26).toLowerCase();if(!(!/^0x[0-9a-f]{40}$/.test(a)||/^0x0{40}$/.test(a))&&!(o&&a!==o))return a}return null}function Ns(e,{factory:t=null,expectedEscrow:n=null}={}){if(!e||typeof e!="object")return{status:"pending",reason:"no-receipt"};if(e.status===void 0||e.status===null||e.status==="")return{status:"pending",reason:"no-status"};let r=Number(e.status);if(!Number.isFinite(r))return{status:"pending",reason:"bad-status"};if(r===0)return{status:"reverted",reason:"status-0"};if(r!==1)return{status:"pending",reason:"bad-status"};let o=Jh(e,{factory:t,expectedEscrow:n});if(!o)return{status:"pending",reason:"no-order-created"};let i=Number(e.blockNumber);return{status:"funded",escrow:o,birthBlock:Number.isFinite(i)?i:null}}async function iS(e,t,{tries:n=12,delayMs:r=1500}={}){for(let o=0;o<n;o+=1){let i=await e({hash:t}).catch(()=>null);if(i)return i;await new Promise(s=>setTimeout(s,r))}return null}async function Hl({factory:e,locker:t,claimer:n,commitHalfLocker:r,commitHalfClaimer:o,edPointLocker:i,edPointClaimer:s,edViewPointLocker:a,salt:c,amountWei:l,amountLabel:u,claimWindowSeconds:d,readyWindowSeconds:p,readyBy:m,t1:w,quote:y,call:b,send:x,receipt:I,onStep:E}){if(!e)throw new Error("no escrow factory address set for this network");if(!t)throw new Error("no EVM wallet connected: there is nobody to deposit");if(!n)throw new Error("the order recipient (claimer) is not set");if(t.toLowerCase()===n.toLowerCase())throw new Error("locker and claimer must not coincide: the contract rejects such an order");if(!y||typeof y!="object")throw new Error("a signed quote is required: the factory takes a quote, not bare order terms");let U=c||As(),S=Qh({locker:t,claimer:n,commitHalfLocker:r,commitHalfClaimer:o,edPointLocker:i,edPointClaimer:s,edViewPointLocker:a,amountWei:l,salt:U,claimWindowSeconds:d,readyWindowSeconds:p,readyBy:m,t1:w});E?.("computing the escrow address");let B={...y,commitHalfLocker:S.commitHalfLocker,edPointLocker:S.edPointLocker,edViewPointLocker:S.edViewPointLocker},R=(g,T)=>String(g??"").replace(/^0x/i,"").toLowerCase()===String(T??"").replace(/^0x/i,"").toLowerCase();for(let g of["locker","claimer","amount","readyBy","t1","salt","commitHalfClaimer","edPointClaimer"])if(!R(y[g],S[g]))throw new Error("the quote and the order terms diverge on field "+g);let A=await b({to:e,data:Bl(B)}),N=xs(A);if(!/^0x[0-9a-fA-F]{40}$/.test(N)||/^0x0{40}$/i.test(N))throw new Error("the factory returned an invalid escrow address: "+String(A).slice(0,40));E?.("checking the order is not already on chain");let f=null;try{let g=await b({to:N,data:ks()});f=String(g||"").replace(/^0x/,"").length>=256?{status:Ss(g)}:{status:null}}catch(g){f={error:String(g&&g.message||g)}}let k=_c({status:f.status,error:f.error,address:N});if(k.blocks)throw new Error("signature not started: "+k.reason);E?.("reading the escrow fee from the signed quote");let _=Xh(y),K=_.totalWei,H=_.feeWei>0n?" (order "+l+" + fee "+_.feeWei+")":"";E?.("locking "+(u||"funds")+H+" in one transaction - confirm in wallet");let P=Pl(B),j=await x({to:e,data:P,value:"0x"+K.toString(16),gas:Zh}),L=null,z=null,W={status:"pending",reason:"no-receipt-reader"};if(typeof I=="function"){let g=await iS(I,j);if(W=Ns(g,{factory:e,expectedEscrow:N}),W.status==="reverted"){let T=new Error("the funding transaction reverted");throw T.code="contract-reverted",T.receiptStatus=0,T}W.status==="funded"?(L=W.escrow,z=W.birthBlock,L!==String(N).toLowerCase()&&(console.warn("[escrow] receipt address "+L+" != predicted "+N+" - using the receipt one"),E?.("receipt address differs from predicted - using the receipt one"))):E?.(g?"receipt has no matching OrderCreated - funding is pending, not funded":"no receipt yet - funding is pending, not funded")}let $=j,O={feeWei:_.feeWei,feeTotalWei:K,feeBps:_.bps,feeWasLegacyFactory:!!_.legacy,predictedEscrow:N,salt:U,terms:S,createHash:j,lockHash:$};return W.status!=="funded"?{...O,escrow:null,birthBlock:null,funded:!1,pending:!0,pendingReason:W.reason}:{...O,escrow:L,escrowMismatch:L!==String(N).toLowerCase(),birthBlock:z,funded:!0,pending:!1}}var Zh,Pr=re(()=>{Cl();vs();Es();Nc();mt();Zh=700000n});var em,Ll,Mo,En,tm,sS,aS,nm,jo,Dl,rm,om,cS,Fl,Is,Ul,lS,im,Ml,Ts=re(()=>{mt();em=["native","wrapped"],Ll="native",Mo=Object.freeze({NATIVE:"native",WRAPPED:"wrapped"}),En=[],tm=()=>En.length===0?null:En.length===1?En[0]:En,sS=(e=null)=>(Array.isArray(e)?En=e.filter(Boolean):e&&typeof e=="object"?En=[e]:En=[],tm()),aS=()=>tm(),nm=e=>En.filter(t=>t&&Number(t.chainId)===Number(e)),jo=e=>e&&zi[e]||null,Dl=()=>Object.keys(zi).sort(),rm=e=>Object.keys((jo(e)||{}).networks||{}).map(Number).filter(Number.isFinite).sort((t,n)=>t-n),om=e=>{let t=jo(e);return t?t.settles===void 0?null:t.settles:null},cS=(e,t={})=>t.settles?t.settles:om(e),Fl=(e,t,n,r={})=>{let o=jo(e)||{};return{id:e,venue:r.venue||o.venue||e,shape:r.shape||o.shape||"async",chainId:Number(t),slug:n.slug===void 0?null:n.slug,orderbook:n.orderbook===void 0?null:n.orderbook,contract:n.contract===void 0?null:n.contract,settles:cS(e,r)}},Is=e=>{let t=Number(e),n=new Map;for(let r of Dl()){let o=jo(r),i=o.networks&&o.networks[t];i&&n.set(r,Fl(r,t,i))}for(let r of nm(t))n.set(r.id,Fl(r.id,t,{slug:r.slug,orderbook:r.orderbook,contract:r.contract},{settles:r.settles,venue:r.venue,shape:r.shape}));return[...n.values()].sort((r,o)=>r.id.localeCompare(o.id))},Ul=(e,t=null)=>{let n=Number(e);if(t){let o=nm(n).find(i=>i.id===t);return o?Fl(o.id,n,{slug:o.slug,orderbook:o.orderbook,contract:o.contract},{settles:o.settles,venue:o.venue,shape:o.shape}):Is(n).find(i=>i.id===t)||null}let r=Is(n);return r.length?r[0]:null},lS=e=>rm(e||Dl()[0]||null),im=({chainId:e=null,providerId:t=null,need:n=Ll}={})=>{let r=Number(e),o=Number.isFinite(r),i=em.includes(n)?n:Ll,s=o?Is(r):[];if(!s.length)return{ok:!1,reason:"no-async-provider",chainId:o?r:null,need:i,provider:t||null,known:lS(t)};let a=null;if(t&&(a=s.find(m=>m.id===t)||null,!a))return{ok:!1,reason:"no-async-provider",chainId:r,need:i,provider:t,known:s.map(m=>m.id)};let c=a?[a]:s,l=c.filter(m=>m.settles===i);if(l.length){let m=l[0];return{ok:!0,kind:"single",...m,need:i,provider:m.id,legs:[m]}}let u=c.filter(m=>m.settles===Mo.WRAPPED),d=s.filter(m=>m.settles===Mo.NATIVE);if(i===Mo.NATIVE&&u.length&&d.length){let m=u[0],w=d[0];return{ok:!0,kind:"composition",need:i,chainId:r,provider:m.id,venue:m.venue,shape:"async",orderbook:m.orderbook,legs:[m,w]}}return{ok:!1,reason:i===Mo.NATIVE&&u.length&&!d.length?"no-native-async-provider":"no-async-provider",chainId:r,need:i,missing:i,provider:(a||u[0]||s[0]).id,known:s.map(m=>m.id)}},Ml=im});function uS({owner:e,spender:t,value:n,deadline:r,signature:o}){if(!Bs(e)||!Bs(t))throw new Error("permit: owner and spender must be addresses");let i=Cs(o);if(i.length!==130)throw new Error("permit: the signature must be 65 bytes, got "+i.length/2);let s=parseInt(i.slice(128,130),16);if(s<27&&(s+=27),s!==27&&s!==28)throw new Error("permit: v outside {27,28}: "+s);return Ko.permit.hex+Ps(e)+Ps(t)+Os(n)+Os(r)+Os(s)+i.slice(0,64)+i.slice(64,128)}function hS({code:e=null,domainSeparator:t=null,nonces:n=null,owner:r=null}={}){let o=Cs(e);if(o.length===0)return{supported:null,kind:"no-code",reason:"no code at the token address - not a token, the allowance cannot be read"};if(!Bs(r))return{supported:null,kind:"no-owner",reason:"no owner given - cannot read nonces(owner)"};let i=sm(t);if(i===null)return{supported:null,kind:"domain-unread",reason:"DOMAIN_SEPARATOR did not answer 32 bytes: could not read"};if(i!==32)return{supported:!1,kind:"domain-empty",reason:"DOMAIN_SEPARATOR returned "+i+" bytes instead of 32: no EIP-712 domain declared"};let s=sm(n);return s===null?{supported:null,kind:"nonces-unread",reason:"nonces(owner) did not answer: could not read"}:s!==32?{supported:!1,kind:"nonces-empty",reason:"nonces(owner) returned "+s+" bytes instead of 32: no EIP-2612 counter"}:o.toLowerCase().includes(Ko.permit.hex.slice(2))?{supported:!0,kind:"eip2612",reason:"the token declares an EIP-712 domain, a nonces counter and the permit selector"}:{supported:!1,kind:"permit-selector-absent",reason:"the token bytecode has no permit selector: no signature allowance"}}function mS({orchestrator:e=null,permitSupported:t=null,token:n=null,nativeBalanceWei:r=null,gasNeedWei:o=null,asyncProvider:i=null,chainId:s=null}={}){let a=am(o),c=i&&typeof i=="object"?i:s==null?null:Ml({chainId:s}),l=!!(c&&c.ok===!0),u=c&&c.ok===!1&&c.reason?String(c.reason):"no-async-provider";if(a!==null&&a>0n){let d=am(r);if(d===null)return{ok:!1,blocked:!1,checked:!1,kind:"balance-unread",path:null,gasNeedWei:a.toString(),reason:"the wallet's native balance was not read, so it is unknown which path fits - read the balance before choosing"};if(d>=a)return{ok:!0,blocked:!1,checked:!0,kind:"own-gas",path:"sync",nativeBalanceWei:d.toString(),gasNeedWei:a.toString(),reason:"the wallet's own native covers the gas this deal needs, so the ordinary synchronous path is taken"};let p={checked:!0,nativeBalanceWei:d.toString(),gasNeedWei:a.toString(),shortfallWei:(a-d).toString()};return l?{ok:!0,blocked:!1,...p,kind:"async-route",path:"async",provider:c.provider??null,venue:c.venue??null,reason:"the wallet's own native does not cover the gas this deal needs, but an asynchronous provider serves this network: the swap settles first and the escrow is funded after it, so the deposit's gas is paid later"}:{ok:!1,blocked:!0,...p,kind:"no-async-provider",path:null,reason:"the wallet's own native does not cover the gas this deal needs and no asynchronous provider serves this network ("+u+"): there is no path for a purchase without own native coin here"}}return Bs(e)?t===!1?{ok:!1,blocked:!0,kind:"token-no-permit",reason:"the token has no signature allowance (EIP-2612): the allowance must be a separate approve, i.e. a separate transaction - the path does not assemble into one transaction"}:t!==!0?{ok:!1,blocked:!0,kind:"permit-unproven",reason:'unknown whether the token supports a signature allowance: "not checked" is not "possible". The capability must be read from the chain before assembling the path'}:{ok:!0,blocked:!1,kind:"one-tx-possible",path:"sync",reason:"an executor is present and the token declares EIP-2612: the one-transaction path assembles"}:{ok:!1,blocked:!0,kind:"no-orchestrator",path:null,reason:"no executor contract: only a contract could pull a token by the user signature and deposit native into the escrow in one transaction, and this build has none"}}var cm,Ko,Cs,Bs,Ps,Os,sm,am,dS,fS,pS,lm=re(()=>{Ts();cm={approve:{hex:"0x095ea7b3",signature:"approve(address,uint256)"},allowance:{hex:"0xdd62ed3e",signature:"allowance(address,address)"},balanceOf:{hex:"0x70a08231",signature:"balanceOf(address)"}},Ko={permit:{hex:"0xd505accf",signature:"permit(address,address,uint256,uint256,uint8,bytes32,bytes32)"},nonces:{hex:"0x7ecebe00",signature:"nonces(address)"},DOMAIN_SEPARATOR:{hex:"0x3644e515",signature:"DOMAIN_SEPARATOR()"}},Cs=e=>String(e??"").replace(/^0x/,""),Bs=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),Ps=e=>Cs(e).toLowerCase().padStart(64,"0"),Os=e=>BigInt(e).toString(16).padStart(64,"0"),sm=e=>{let t=Cs(e);return t.length===0||t.length%2?null:t.length/2},am=e=>{if(e==null||e==="")return null;try{return BigInt(typeof e=="bigint"?e:String(e))}catch{return null}};dS=e=>Ko.nonces.hex+Ps(e),fS=()=>Ko.DOMAIN_SEPARATOR.hex,pS=({spender:e,amountWei:t})=>cm.approve.hex+Ps(e)+Os(t)});async function $l({fetchImpl:e,url:t,method:n="GET",body:r=null,timeoutMs:o=2e4}){let i=e||(typeof fetch=="function"?fetch:null);if(!i)return he("kyber-unreachable",{why:"no-fetch"});let s=null;try{let a={method:n,headers:r===null?void 0:{"content-type":"application/json"}};r!==null&&(a.body=JSON.stringify(r));let c=typeof AbortController=="function"?new AbortController:null;c&&(a.signal=c.signal,s=setTimeout(()=>c.abort(),o));let l=await i(t,a),u=null;try{u=await l.text()}catch{u=null}return{ok:!0,status:Number(l.status),text:u}}catch(a){return he("kyber-unreachable",{why:String(a&&a.message||a)})}finally{s&&clearTimeout(s)}}function zl(e={}){let t=e.maker,n=e.receiver===void 0||e.receiver===null?t:e.receiver,r={chainId:String(e.chainId),makerAsset:e.makerAsset,takerAsset:e.takerAsset,maker:t,receiver:n,makingAmount:String(e.makingAmount),takingAmount:String(e.takingAmount),expiredAt:e.expiredAt};e.allowedSenders!==void 0&&e.allowedSenders!==null&&(r.allowedSenders=e.allowedSenders);let o=[];return Number.isInteger(Number(r.chainId))||o.push("chainId"),Wo(t)||o.push("maker"),Wo(r.makerAsset)||o.push("makerAsset"),Wo(r.takerAsset)||o.push("takerAsset"),Wo(r.receiver)||o.push("receiver"),um(r.makingAmount)||o.push("makingAmount"),um(r.takingAmount)||o.push("takingAmount"),Number.isInteger(Number(r.expiredAt))||o.push("expiredAt"),o.length?he("kyber-bad-order",{missing:[...new Set(o)]}):{ok:!0,chainId:Number(r.chainId),params:r,expectedOutWei:String(r.takingAmount)}}async function Xl({params:e,chainId:t=null,orderbook:n=null,fetchImpl:r=null,timeoutMs:o=2e4}={}){let i=Number(t!==null?t:e&&e.chainId),s=n?String(n).replace(/\/+$/,""):Rs;if(!Number.isFinite(i))return he("kyber-unknown-network",{chainId:null});if(!e||typeof e!="object")return he("kyber-bad-order",{field:"params"});let a=await $l({fetchImpl:r,url:Vl(s,pm),method:"POST",body:e,timeoutMs:o});if(!a.ok)return a;if(a.status>=400)return he("kyber-refused",{status:a.status,stage:"sign-message",reason:null});let c=null;try{c=JSON.parse(a.text)}catch{c=null}let l=c&&c.data;if(!l||typeof l!="object")return he("kyber-bad-response",{where:"sign-message"});let u=l.domain||{},d=l.message||{},p=l.types&&Array.isArray(l.types.Order)?l.types.Order.map(b=>(b?b.name:"")+":"+(b?b.type:"")).join(","):null,m=Kl.map(([b,x])=>b+":"+x).join(",");if(!(String(u.name)===dm&&String(u.version)===fm&&Number(u.chainId)===i&&String(u.verifyingContract||"").toLowerCase()===jl.toLowerCase()))return he("kyber-bad-response",{where:"sign-message",field:"domain"});if(p!==m)return he("kyber-bad-response",{where:"sign-message",field:"types"});let y=Kl.filter(([b])=>d[b]===void 0||d[b]===null||d[b]==="");return y.length?he("kyber-bad-response",{where:"sign-message",missing:y.map(b=>b[0])}):{ok:!0,chainId:i,orderbook:s,contract:jl,salt:String(d.salt),message:d,typedData:{domain:u,types:l.types,primaryType:l.primaryType||"Order",message:d}}}async function Yl({typedData:e,wallet:t=null,address:n=null}={}){if(!e||typeof e!="object")return he("kyber-bad-order",{field:"typedData"});try{if(t&&typeof t.signTypedData=="function"){let o=await t.signTypedData(e);return Wl(o)?{ok:!0,signature:o}:he("kyber-sign-failed",{why:"bad-signature-shape"})}let r=t&&typeof t.driver=="function"?t.driver():t;if(r&&typeof r.request=="function"){let o=n||(t&&typeof t.address=="function"?await t.address():null),i=await r.request({method:"eth_signTypedData_v4",params:[o,JSON.stringify(e)]});return Wl(i)?{ok:!0,signature:i}:he("kyber-sign-failed",{why:"bad-signature-shape"})}return he("kyber-sign-failed",{why:"no-wallet"})}catch(r){return he("kyber-sign-failed",{why:String(r&&r.code||r&&r.message||r)})}}async function Gl({params:e,salt:t,signature:n,orderbook:r=null,chainId:o=null,fetchImpl:i=null,timeoutMs:s=2e4}={}){let a=r?String(r).replace(/\/+$/,""):Rs;if(!e||typeof e!="object")return he("kyber-bad-order",{field:"params"});if(!Wl(n))return he("kyber-bad-order",{field:"signature"});if(t==null||t==="")return he("kyber-bad-order",{field:"salt"});let c={...e,salt:String(t),signature:n},l=await $l({fetchImpl:i,url:Vl(a,hm),method:"POST",body:c,timeoutMs:s});if(!l.ok)return l;if(l.status>=400)return he("kyber-refused",{status:l.status,stage:"submit",reason:null});let u=null;try{u=JSON.parse(l.text)}catch{u=null}let d=u&&u.data,p=d&&d.id;return!Number.isInteger(Number(p))||Number(p)<=0?he("kyber-bad-response",{where:"submit",got:typeof p}):{ok:!0,id:Number(p),chainId:Number.isFinite(Number(o))?Number(o):null}}async function xm({id:e,chainId:t,maker:n,orderbook:r=null,fetchImpl:o=null,timeoutMs:i=2e4}={}){let s=r?String(r).replace(/\/+$/,""):Rs,a=Number(t);if(!Number.isInteger(Number(e))||Number(e)<=0)return he("kyber-bad-order",{field:"id"});if(!Wo(n))return he("kyber-bad-order",{field:"maker"});for(let c of gm){let l=mm+"?chainId="+a+"&maker="+n+"&status="+c,u=await $l({fetchImpl:o,url:Vl(s,l),timeoutMs:i});if(!u.ok)return u;if(u.status>=400)return he("kyber-refused",{status:u.status,stage:"orders"});let d=null;try{d=JSON.parse(u.text)}catch{d=null}let p=d&&d.data&&d.data.orders;if(!Array.isArray(p))return he("kyber-bad-response",{where:"orders"});let m=p.find(w=>w&&Number(w.id)===Number(e))||null;if(m){let w=m.status;return typeof w!="string"||!wm.includes(w)?he("kyber-bad-response",{where:"status",got:typeof w=="string"?w:null}):{ok:!0,status:w,order:m,bucket:c}}}return he("kyber-order-unknown",{id:Number(e),maker:n})}async function ql({id:e,chainId:t,maker:n,orderbook:r=null,fetchImpl:o=null,pollMs:i=5e3,timeoutMs:s=3e5,now:a=null,sleep:c=null,onTick:l=null}={}){if(!Number.isInteger(Number(e))||Number(e)<=0)return he("kyber-bad-order",{field:"id"});let u=typeof a=="function"?a:()=>Date.now(),d=typeof c=="function"?c:b=>new Promise(x=>setTimeout(x,b)),p=Number.isFinite(i)&&i>0?i:5e3,m=Number.isFinite(s)&&s>0?s:3e5,w=u(),y=null;for(;;){let b=await xm({id:e,chainId:t,maker:n,orderbook:r,fetchImpl:o});if(!b.ok)return b;if(y=b.status,typeof l=="function"&&l(y),ym.includes(y))return{ok:!0,done:!0,settled:y===bm,status:y,id:Number(e)};if(u()-w>=m)return{...he("kyber-not-settled",{id:Number(e),status:y,waitedMs:u()-w}),status:y,id:Number(e)};await d(p)}}var Rs,wS,dm,fm,jl,Kl,pm,hm,mm,wm,ym,bm,yS,gm,bS,he,Wo,um,Wl,Vl,gS,Ql=re(()=>{Rs="https://limit-order.kyberswap.com",wS=["KyberSwap","Limit","Order"].join(" "),dm=["Kyber","DSLO","Protocol"].join(" "),fm="1",jl="0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C",Kl=[["salt","uint256"],["makerAsset","address"],["takerAsset","address"],["maker","address"],["receiver","address"],["allowedSender","address"],["makingAmount","uint256"],["takingAmount","uint256"],["feeConfig","uint256"],["makerAssetData","bytes"],["takerAssetData","bytes"],["getMakerAmount","bytes"],["getTakerAmount","bytes"],["predicate","bytes"],["interaction","bytes"]],pm="/write/api/v1/orders/sign-message",hm="/write/api/v1/orders",mm="/read-ks/api/v1/orders",wm=["active","open","partially_filled","cancelling","closed","filled","cancelled","expired"],ym=["filled","cancelled","expired"],bm="filled",yS=["open","partially_filled","cancelling"],gm=["active","closed"],bS=["kyber-unknown-network","kyber-bad-order","kyber-sign-failed","kyber-unreachable","kyber-order-unknown","kyber-refused","kyber-bad-response","kyber-not-settled"],he=(e,t={})=>({ok:!1,code:e,params:t}),Wo=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),um=e=>{try{return BigInt(String(e))>0n}catch{return!1}},Wl=e=>/^0x[0-9a-fA-F]{130}$/.test(String(e||"")),Vl=(e,t)=>String(e||"").replace(/\/+$/,"")+t;gS=e=>{let t=e&&e.code?String(e.code):null;return{"kyber-unknown-network":"no KyberSwap liquidity provider serves this network","kyber-bad-order":"the swap intent is incomplete and was not sent","kyber-sign-failed":"the wallet did not sign the swap intent","kyber-unreachable":"the KyberSwap order book could not be reached","kyber-order-unknown":"the KyberSwap order book does not know this order","kyber-refused":"the KyberSwap order book did not accept the order","kyber-bad-response":"the KyberSwap order book answered in a shape we do not know","kyber-not-settled":"the swap did not settle in time"}[t]||t||"the liquidity leg stopped"}});function ru(e={}){let t=Number(e.chainId),n=nu(t,e.orderbook||null,e.providerId||null);if(!n)return Le("cow-unknown-network",{chainId:Number.isFinite(t)?t:null});let r=e.owner,o=e.receiver===void 0||e.receiver===null?r:e.receiver,i={sellToken:e.sellToken,buyToken:e.buyToken,receiver:o,sellAmount:Vo(e.sellAmountWei)===null?e.sellAmountWei:String(e.sellAmountWei),buyAmount:Vo(e.buyAmountWei)===null?e.buyAmountWei:String(e.buyAmountWei),validTo:e.validTo,appData:e.appData===void 0||e.appData===null?"0x"+"00".repeat(32):e.appData,feeAmount:e.feeAmountWei===void 0||e.feeAmountWei===null?"0":String(e.feeAmountWei),kind:e.kind===void 0||e.kind===null?"sell":e.kind,partiallyFillable:e.partiallyFillable===void 0||e.partiallyFillable===null?!1:e.partiallyFillable,sellTokenBalance:e.sellTokenBalance===void 0||e.sellTokenBalance===null?"erc20":e.sellTokenBalance,buyTokenBalance:e.buyTokenBalance===void 0||e.buyTokenBalance===null?"erc20":e.buyTokenBalance},s=[];for(let[a]of eu){let c=i[a];(c==null||c==="")&&s.push(a)}return Hs(r)||s.push("owner"),SS(i.appData)||s.push("appData"),(!Hs(i.sellToken)||!Hs(i.buyToken)||!Hs(i.receiver))&&s.push("token"),(Vo(i.sellAmount)===null||Vo(i.buyAmount)===null)&&s.push("amount"),Vo(i.validTo)===null&&s.push("validTo"),(!tu.length||!["sell","buy"].includes(i.kind))&&s.push("kind"),s.length?{...Le("cow-bad-order",{missing:[...new Set(s)]}),orderbook:n}:{ok:!0,chainId:Number.isFinite(t)?t:null,orderbook:n,owner:r,order:i,typedData:Om({order:i,chainId:t,settlement:e.settlement||Jl})}}async function ou({typedData:e,wallet:t=null,address:n=null}={}){if(!e||typeof e!="object")return Le("cow-bad-order",{field:"typedData"});try{if(t&&typeof t.signTypedData=="function"){let o=await t.signTypedData(e);return Zl(o)?{ok:!0,signature:o}:Le("cow-sign-failed",{why:"bad-signature-shape"})}let r=t&&typeof t.driver=="function"?t.driver():t;if(r&&typeof r.request=="function"){let o=n||(t&&typeof t.address=="function"?await t.address():null),i=await r.request({method:"eth_signTypedData_v4",params:[o,JSON.stringify(e)]});return Zl(i)?{ok:!0,signature:i}:Le("cow-sign-failed",{why:"bad-signature-shape"})}return Le("cow-sign-failed",{why:"no-wallet"})}catch(r){return Le("cow-sign-failed",{why:String(r&&r.code||r&&r.message||r)})}}async function Pm({fetchImpl:e,url:t,method:n="GET",body:r=null,timeoutMs:o=2e4}){let i=e||(typeof fetch=="function"?fetch:null);if(!i)return Le("cow-unreachable",{why:"no-fetch"});let s=null;try{let a={method:n,headers:r===null?void 0:{"content-type":"application/json"}};r!==null&&(a.body=JSON.stringify(r));let c=typeof AbortController=="function"?new AbortController:null;c&&(a.signal=c.signal,s=setTimeout(()=>c.abort(),o));let l=await i(t,a),u=null;try{u=await l.text()}catch{u=null}return{ok:!0,status:Number(l.status),text:u}}catch(a){return Le("cow-unreachable",{why:String(a&&a.message||a)})}finally{s&&clearTimeout(s)}}async function iu({orderbook:e,order:t,signature:n,owner:r,fetchImpl:o=null,timeoutMs:i=2e4,signingScheme:s="eip712",from:a=null}={}){let c=e?String(e).replace(/\/+$/,""):null;if(!c)return Le("cow-unknown-network",{});if(!Zl(n))return Le("cow-bad-order",{field:"signature"});let l=await Pm({fetchImpl:o,url:Tm(c,Sm),method:"POST",body:Bm({order:t,signature:n,owner:r,signingScheme:s,from:a}),timeoutMs:i});return l.ok?l.status>=400?Le("cow-refused",{status:l.status,reason:null}):typeof l.text!="string"||!Im(l.text.trim())?Le("cow-bad-response",{where:"submit"}):{ok:!0,uid:l.text.trim()}:l}async function Cm({orderbook:e,uid:t,fetchImpl:n=null,timeoutMs:r=2e4}={}){let o=e?String(e).replace(/\/+$/,""):null;if(!o)return Le("cow-unknown-network",{});if(!Im(t))return Le("cow-bad-order",{field:"uid"});let i=await Pm({fetchImpl:n,url:Tm(o,vm+t),timeoutMs:r});if(!i.ok)return i;if(i.status===404)return Le("cow-order-unknown",{uid:t});if(i.status>=400)return Le("cow-refused",{status:i.status});let s=null;try{s=JSON.parse(i.text)}catch{s=null}let a=s&&s.status;return typeof a!="string"||!tu.includes(a)?Le("cow-bad-response",{where:"status",got:typeof a=="string"?a:null}):{ok:!0,status:a,order:s}}async function su({orderbook:e,uid:t,fetchImpl:n=null,pollMs:r=5e3,timeoutMs:o=3e5,now:i=null,sleep:s=null,onTick:a=null}={}){let c=typeof i=="function"?i:()=>Date.now(),l=typeof s=="function"?s:w=>new Promise(y=>setTimeout(y,w)),u=Number.isFinite(r)&&r>0?r:5e3,d=Number.isFinite(o)&&o>0?o:3e5,p=c(),m=null;for(;;){let w=await Cm({orderbook:e,uid:t,fetchImpl:n});if(!w.ok)return w;if(m=w.status,typeof a=="function"&&a(m),_m.includes(m))return{ok:!0,done:!0,settled:m===Nm,status:m,uid:t};if(c()-p>=d)return{...Le("cow-not-settled",{uid:t,status:m,waitedMs:c()-p}),status:m,uid:t};await l(u)}}function au(e,t=""){let n=String(t||"").trim(),r={"async-plan":"Building the swap intent","async-sign":"Waiting for the wallet to sign the swap intent","async-submit":"Submitting the swap intent to the order book","async-wait":"Waiting for the swap to settle","async-settled":"Swap settled - now funding the escrow","async-swap":"Swapping your token for WETH","async-convert":"Converting WETH into native ETH","async-fund":"Funding the escrow with the settled native ETH"}[e]||null;return r?r+(n?": "+n:""):n||String(e||"")}function Rm({wethOutWei:e=null,leg2FeeWei:t="0",depositWei:n=null,reserveWei:r="0"}={}){let o=Ls(e),i=t==null||t===""?0n:Ls(t),s=Ls(n),a=r==null||r===""?0n:Ls(r);if(o===null||i===null||i<0n||s===null||a===null||a<0n)return{ok:!1,code:"composition-short",measured:!1,reason:"the composition's amounts or the deposit were not measured"};let c=s+a+i,l=o-i;return o<c?{ok:!1,code:"composition-short",measured:!0,wethOutWei:o.toString(),leg2FeeWei:i.toString(),depositWei:s.toString(),reserveWei:a.toString(),nativeOutWei:(l>0n?l:0n).toString(),needWei:c.toString(),shortfallWei:(c-o).toString(),reason:"the liquidity leg does not cover the escrow deposit, its reserve and the conversion fee"}:{ok:!0,measured:!0,wethOutWei:o.toString(),leg2FeeWei:i.toString(),nativeOutWei:l.toString(),needWei:c.toString(),depositWei:s.toString(),reserveWei:a.toString()}}async function Hm({route:e={},request:t={},wallet:n=null,fund:r=null,fetchImpl:o=null,pollMs:i=5e3,timeoutMs:s=3e5,now:a=null,sleep:c=null,onStep:l=null}={}){let u=(L,z)=>{typeof l=="function"&&l(L,z,au(L,z))},d=Array.isArray(e.legs)?e.legs:[],p=d.find(L=>L&&L.settles==="wrapped")||null,m=d.find(L=>L&&L.settles==="native")||null;if(!p||!m){let L={ok:!1,code:"async-bad-composition",params:{legs:d.map(z=>z&&z.settles)}};return{ok:!1,stage:"plan",...L,words:Pe(L)}}let w=e.chainId!==void 0&&e.chainId!==null?e.chainId:t.chainId,y=t.owner,b=t.wrappedToken,x=t.leg2FeeWei===void 0||t.leg2FeeWei===null?"0":t.leg2FeeWei;u("async-plan","token -> WETH -> native coin");let I=Rm({wethOutWei:t.wethOutWei,leg2FeeWei:x,depositWei:t.depositWei,reserveWei:t.reserveWei});if(!I.ok)return{ok:!1,stage:"plan",...I,words:Pe(I)};let E=I.wethOutWei,U=p.orderbook||null,S=zl({chainId:w,maker:y,receiver:y,makerAsset:t.sellToken,takerAsset:b,makingAmount:t.sellAmountWei,takingAmount:E,expiredAt:t.expiredAt});if(!S.ok)return{ok:!1,stage:"swap",leg:"liquidity",...S,words:Pe(S)};u("async-swap","building the liquidity intent");let B=await Xl({params:S.params,chainId:w,orderbook:U,fetchImpl:o});if(!B.ok)return{ok:!1,stage:"swap",leg:"liquidity",...B,words:Pe(B)};u("async-swap","waiting for the wallet to sign the swap intent");let R=await Yl({typedData:B.typedData,wallet:n,address:y});if(!R.ok)return{ok:!1,stage:"swap",leg:"liquidity",...R,words:Pe(R)};u("async-swap","submitting the liquidity order");let A=await Gl({params:S.params,salt:B.salt,signature:R.signature,orderbook:U,chainId:w,fetchImpl:o});if(!A.ok)return{ok:!1,stage:"swap",leg:"liquidity",...A,words:Pe(A)};u("async-swap","order "+A.id);let N=await ql({id:A.id,chainId:w,maker:y,orderbook:U,fetchImpl:o,pollMs:i,timeoutMs:s,now:a,sleep:c,onTick:L=>u("async-swap","status "+L)});if(!N.ok)return{ok:!1,stage:"swap",leg:"liquidity",...N,words:Pe(N)};if(!N.settled){let L={ok:!1,code:"async-order-dead",params:{leg:"liquidity",id:A.id,status:N.status}};return{ok:!1,stage:"swap",leg:"liquidity",...L,words:Pe(L)}}let f={provider:p.id,id:A.id,status:N.status};u("async-convert","building the conversion order");let k=ru({chainId:w,orderbook:m.orderbook||null,owner:y,sellToken:b,buyToken:km,receiver:y,sellAmountWei:E,buyAmountWei:I.nativeOutWei,validTo:t.validTo,feeAmountWei:I.leg2FeeWei,kind:"sell"});if(!k.ok)return{ok:!1,stage:"convert",leg:"native",...k,words:Pe(k)};u("async-convert","waiting for the wallet to sign the conversion intent");let _=await ou({typedData:k.typedData,wallet:n,address:y});if(!_.ok)return{ok:!1,stage:"convert",leg:"native",..._,words:Pe(_)};u("async-convert","submitting the conversion order");let K=await iu({orderbook:k.orderbook,order:k.order,signature:_.signature,owner:y,fetchImpl:o});if(!K.ok)return{ok:!1,stage:"convert",leg:"native",...K,words:Pe(K)};u("async-convert","order "+String(K.uid).slice(0,12));let H=await su({orderbook:k.orderbook,uid:K.uid,fetchImpl:o,pollMs:i,timeoutMs:s,now:a,sleep:c,onTick:L=>u("async-convert","status "+L)});if(!H.ok)return{ok:!1,stage:"convert",leg:"native",...H,words:Pe(H)};if(!H.settled){let L={ok:!1,code:"async-order-dead",params:{leg:"native",uid:K.uid,status:H.status}};return{ok:!1,stage:"convert",leg:"native",...L,words:Pe(L)}}let P={provider:m.id,uid:K.uid,status:H.status};if(u("async-fund","funding the escrow with the converted native coin"),typeof r!="function")return{ok:!1,stage:"fund",code:"async-no-fund",legs:[f,P],words:Pe({code:"async-no-fund"})};let j=await r({kind:"composition",uid:K.uid,status:H.status,nativeOutWei:I.nativeOutWei,liquidity:f,native:P});return{ok:!0,kind:"composition",uid:K.uid,status:H.status,legs:[f,P],nativeOutWei:I.nativeOutWei,funded:j}}async function vS({route:e={},request:t={},wallet:n=null,fund:r=null,fetchImpl:o=null,pollMs:i=5e3,timeoutMs:s=3e5,now:a=null,sleep:c=null,onStep:l=null}={}){let u=(I,E)=>{typeof l=="function"&&l(I,E,au(I,E))};if(e&&(e.kind==="composition"||Array.isArray(e.legs)&&e.legs.length>1))return await Hm({route:e,request:t,wallet:n,fund:r,fetchImpl:o,pollMs:i,timeoutMs:s,now:a,sleep:c,onStep:l});let d=e.chainId!==void 0&&e.chainId!==null?e.chainId:t.chainId,p=nu(d,e.orderbook||t.orderbook||null,e.providerId||t.providerId||null);u("async-plan","");let m=ru({...t,chainId:d,orderbook:p});if(!m.ok)return{ok:!1,stage:"plan",...m,words:Pe(m)};u("async-sign","");let w=await ou({typedData:m.typedData,wallet:n,address:t.owner});if(!w.ok)return{ok:!1,stage:"sign",...w,words:Pe(w)};u("async-submit","");let y=await iu({orderbook:m.orderbook,order:m.order,signature:w.signature,owner:t.owner,fetchImpl:o});if(!y.ok)return{ok:!1,stage:"submit",...y,words:Pe(y)};u("async-wait","order "+String(y.uid).slice(0,12));let b=await su({orderbook:m.orderbook,uid:y.uid,fetchImpl:o,pollMs:i,timeoutMs:s,now:a,sleep:c,onTick:I=>u("async-wait","status "+I)});if(!b.ok)return{ok:!1,stage:"settle",uid:y.uid,...b,words:Pe(b)};if(!b.settled){let I={ok:!1,code:"async-order-dead",params:{uid:y.uid,status:b.status}};return{ok:!1,stage:"settle",uid:y.uid,...I,words:Pe(I)}}if(u("async-settled",""),typeof r!="function")return{ok:!1,stage:"fund",code:"async-no-fund",uid:y.uid,words:Pe({code:"async-no-fund"})};u("async-fund","");let x=await r({uid:y.uid,status:b.status,order:m.order});return{ok:!0,uid:y.uid,status:b.status,funded:x}}var Jl,km,Sm,vm,Em,Am,eu,tu,_m,Nm,xS,kS,Le,Hs,SS,Im,Zl,Vo,Tm,nu,Om,Bm,Pe,Ls,Lm=re(()=>{Ts();Ql();Jl="0x9008D19f58AAbD9eD0D60971565AA8510560ab41",km="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",Sm="/api/v1/orders",vm="/api/v1/orders/",Em=["Gnosis","Protocol"].join(" "),Am="v2",eu=[["sellToken","address"],["buyToken","address"],["receiver","address"],["sellAmount","uint256"],["buyAmount","uint256"],["validTo","uint32"],["appData","bytes32"],["feeAmount","uint256"],["kind","string"],["partiallyFillable","bool"],["sellTokenBalance","string"],["buyTokenBalance","string"]],tu=["presignaturePending","open","fulfilled","cancelled","expired"],_m=["fulfilled","cancelled","expired"],Nm="fulfilled",xS=["presignaturePending","open"],kS=["cow-unknown-network","cow-bad-order","cow-sign-failed","cow-unreachable","cow-order-unknown","cow-refused","cow-bad-response","cow-not-settled"],Le=(e,t={})=>({ok:!1,code:e,params:t}),Hs=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),SS=e=>/^(0x)?[0-9a-fA-F]{64}$/.test(String(e||"")),Im=e=>/^0x[0-9a-fA-F]{112}$/.test(String(e||"")),Zl=e=>/^0x[0-9a-fA-F]{130}$/.test(String(e||"")),Vo=e=>{if(e==null||e==="")return null;let t=String(e).trim();return/^0x[0-9a-fA-F]+$/.test(t)||/^[0-9]+$/.test(t)?t.replace(/^0x/,""):null},Tm=(e,t)=>String(e||"").replace(/\/+$/,"")+t,nu=(e,t=null,n=null)=>{if(t)return String(t).replace(/\/+$/,"");let r=Ul(e,n);return r&&r.orderbook?String(r.orderbook).replace(/\/+$/,""):null},Om=({order:e,chainId:t,settlement:n=Jl})=>({domain:{name:Em,version:Am,chainId:Number(t),verifyingContract:n},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],Order:eu.map(([r,o])=>({name:r,type:o}))},primaryType:"Order",message:{sellToken:e.sellToken,buyToken:e.buyToken,receiver:e.receiver,sellAmount:String(e.sellAmount),buyAmount:String(e.buyAmount),validTo:Number(e.validTo),appData:e.appData,feeAmount:String(e.feeAmount),kind:String(e.kind),partiallyFillable:!!e.partiallyFillable,sellTokenBalance:String(e.sellTokenBalance),buyTokenBalance:String(e.buyTokenBalance)}});Bm=({order:e,signature:t,owner:n,signingScheme:r="eip712",from:o=null})=>({sellToken:e.sellToken,buyToken:e.buyToken,receiver:e.receiver,sellAmount:String(e.sellAmount),buyAmount:String(e.buyAmount),validTo:Number(e.validTo),appData:String(e.appData),feeAmount:String(e.feeAmount),kind:String(e.kind),partiallyFillable:!!e.partiallyFillable,sellTokenBalance:String(e.sellTokenBalance),buyTokenBalance:String(e.buyTokenBalance),signingScheme:r,signature:t,from:o||n});Pe=e=>{let t=e&&e.code?String(e.code):null;return{"cow-unknown-network":"no asynchronous provider serves this network","cow-bad-order":"the swap intent is incomplete and was not sent","cow-sign-failed":"the wallet did not sign the swap intent","cow-unreachable":"the order book could not be reached","cow-order-unknown":"the order book does not know this order","cow-refused":"the order book did not accept the order","cow-bad-response":"the order book answered in a shape we do not know","cow-not-settled":"the swap did not settle in time","async-order-dead":"the swap order was cancelled or expired - nothing was funded","kyber-unknown-network":"no KyberSwap liquidity provider serves this network","kyber-bad-order":"the liquidity swap intent is incomplete and was not sent","kyber-sign-failed":"the wallet did not sign the liquidity swap intent","kyber-unreachable":"the KyberSwap order book could not be reached","kyber-order-unknown":"the KyberSwap order book does not know this order","kyber-refused":"the KyberSwap order book did not accept the order","kyber-bad-response":"the KyberSwap order book answered in a shape we do not know","kyber-not-settled":"the liquidity swap did not settle in time","async-bad-composition":"this route is not a two-leg composition (a liquidity leg and a native leg are both required)","composition-short":"the swap does not cover the escrow deposit, its reserve and the conversion fee"}[t]||t||"the asynchronous route stopped"},Ls=e=>{if(e==null||e==="")return null;try{return BigInt(typeof e=="bigint"?e:String(e))}catch{return null}}});var Ie={};Be(Ie,{ASYNC_BUY_ETH_ADDRESS:()=>km,ASYNC_DEFAULT_NEED:()=>Ll,ASYNC_DOMAIN_NAME:()=>Em,ASYNC_DOMAIN_VERSION:()=>Am,ASYNC_FINAL_STATUSES:()=>_m,ASYNC_NEEDS:()=>em,ASYNC_OPEN_STATUSES:()=>xS,ASYNC_ORDER_FIELDS:()=>eu,ASYNC_ORDER_PATH:()=>vm,ASYNC_REFUSAL_CODES:()=>kS,ASYNC_SETTLED_STATUS:()=>Nm,ASYNC_SETTLEMENT:()=>Jl,ASYNC_SETTLES:()=>Mo,ASYNC_STATUSES:()=>tu,ASYNC_SUBMIT_PATH:()=>Sm,EIP2612_METHOD:()=>Ko,ERC20_METHOD:()=>cm,ESCROW_METHODS:()=>rn,FACTORY_METHODS:()=>Ol,FACTORY_READS:()=>bs,GAS_CREATE_ORDER_AND_FUND:()=>Zh,KYBER_LEG_CONTRACT:()=>jl,KYBER_LEG_CREATE_PATH:()=>hm,KYBER_LEG_DOMAIN_NAME:()=>dm,KYBER_LEG_DOMAIN_VERSION:()=>fm,KYBER_LEG_FINAL_STATUSES:()=>ym,KYBER_LEG_MAKER_ORDERS_PATH:()=>mm,KYBER_LEG_OPEN_STATUSES:()=>yS,KYBER_LEG_ORDERBOOK:()=>Rs,KYBER_LEG_ORDER_FIELDS:()=>Kl,KYBER_LEG_REFUSAL_CODES:()=>bS,KYBER_LEG_SETTLED_STATUS:()=>bm,KYBER_LEG_SIGN_MESSAGE_PATH:()=>pm,KYBER_LEG_STATUSES:()=>wm,KYBER_LEG_STATUS_BUCKETS:()=>gm,KYBER_LEG_VENUE:()=>wS,ORDER_CREATED_TOPIC:()=>gs,ORDER_CREATED_TOPICS:()=>qk,ORDER_CREATED_TOPIC_V1:()=>Bh,QUOTE_FIELDS:()=>Tl,address:()=>er,asyncIntentVerdict:()=>ru,asyncOrderSubmission:()=>Bm,asyncOrderTypedData:()=>Om,asyncOrderbookFor:()=>nu,asyncReadVerdict:()=>Cm,asyncRefusalWords:()=>Pe,asyncRouteChains:()=>rm,asyncRouteChoice:()=>im,asyncRouteForChain:()=>Ul,asyncRouteInjection:()=>aS,asyncRouteProvider:()=>jo,asyncRouteProviderIds:()=>Dl,asyncRouteProviderSettles:()=>om,asyncRouteProvidersForChain:()=>Is,asyncRouteVerdict:()=>Ml,asyncSettledVerdict:()=>su,asyncSignVerdict:()=>ou,asyncStageWords:()=>au,asyncSubmitVerdict:()=>iu,balanceOf:()=>zp,chainIdOf:()=>$p,compositionVerdict:()=>Rm,connect:()=>qp,connectInjected:()=>ol,currentProvider:()=>Oo,decodeAddress:()=>xs,decodeBytes32:()=>Wh,decodeImplementation:()=>Ch,decodeImplementationCodeHash:()=>Rh,decodeStatus:()=>Ss,decodeUint64:()=>Vh,disconnect:()=>Zp,encodeApprove:()=>pS,encodeClaim:()=>Fh,encodeCreateOrderAndFund:()=>Pl,encodeDomainSeparator:()=>fS,encodeFactoryRead:()=>tS,encodeMarkReady:()=>Lh,encodeNonces:()=>dS,encodePermit:()=>uS,encodePredict:()=>Bl,encodeRead:()=>Kh,encodeRefund:()=>Uh,encodeStatus:()=>ks,encodeT1:()=>Mh,encodeTermsHash:()=>jh,escrowFromReceipt:()=>Jh,escrowNativeWei:()=>oS,fundOrder:()=>Hl,fundOrderLive:()=>_S,fundingReceiptVerdict:()=>Ns,isConnected:()=>Wt,kyberLegPlan:()=>zl,kyberLegRead:()=>xm,kyberLegRefusalWords:()=>gS,kyberLegSettled:()=>ql,kyberLegSign:()=>Yl,kyberLegSubmit:()=>Gl,kyberLegUnsigned:()=>Xl,newSecret:()=>As,orderTerms:()=>$h,permitSupportVerdict:()=>hS,readCode:()=>ls,readContract:()=>gn,readReceipt:()=>sl,refreshBalances:()=>Kt,restore:()=>Gp,restoreInjected:()=>rl,runAsyncRoute:()=>vS,runComposedRoute:()=>Hm,sendTransaction:()=>al,setAsyncRouteInjection:()=>sS,simulateEscrowFunding:()=>AS,status:()=>Vp,subscribe:()=>Wp,switchChain:()=>il,testOrderTerms:()=>Qh,toWei:()=>_s,usdcWithoutEthVerdict:()=>mS,verifyFactoryImplementation:()=>Hh,verifyFactoryImplementationOnChain:()=>nS,wallets:()=>ES,word:()=>me});function ES(){return To()}async function AS(e){await new Promise(r=>setTimeout(r,900));let t=new Uint8Array(32);return crypto.getRandomValues(t),{hash:"0x"+Array.from(t,r=>r.toString(16).padStart(2,"0")).join(""),...e,simulated:!0}}async function _S({factory:e,locker:t,claimer:n,commitHalfLocker:r,commitHalfClaimer:o,edPointLocker:i,edPointClaimer:s,edViewPointLocker:a,salt:c,amountWei:l,amountLabel:u,claimWindowSeconds:d=3600,readyWindowSeconds:p=14400,readyBy:m,t1:w,quote:y,onStep:b}){return Hl({factory:e,quote:y,locker:t,claimer:n,commitHalfLocker:r,commitHalfClaimer:o,edPointLocker:i,edPointClaimer:s,edViewPointLocker:a,salt:c,amountLabel:u,amountWei:l,claimWindowSeconds:d,readyWindowSeconds:p,readyBy:m,t1:w,call:gn,send:al,receipt:sl,onStep:b})}var cu=re(()=>{us();zc();Pr();Cl();vs();Pr();lm();Ts();Lm();Ql();us()});var ot={};Be(ot,{DEX_METHOD:()=>on,declaredRoutePath:()=>Dm,decodeQuoteExactInput:()=>du,dexLegVerdict:()=>fu,encodeGetPool:()=>Wm,encodePath:()=>uu,encodeQuoteExactInput:()=>zm,encodeQuoteExactInputSingle:()=>Km,encodeQuoteExactOutputSingle:()=>Vm,feeTierLabel:()=>Rr,feeTierPct:()=>Xm,noRouteWords:()=>Jm,poolAddress:()=>Ym,poolState:()=>CS,priceGateVerdict:()=>Zm,quoteDexOut:()=>pu,quoteExactOutPath:()=>$m,quoteExactOutSingle:()=>OS,quotePath:()=>qm,quoteTier:()=>Gm,resetDexCache:()=>TS,routeLabel:()=>Um,routeSignature:()=>Qm,routeSteps:()=>Mm,unwrapLeg:()=>RS});function Dm({token:e,tokens:t=[],wrapped:n,route:r}){if(!e||!r||!Array.isArray(r.steps)||!r.steps.length)return null;let o=new Map((t||[]).map(u=>[String(u.symbol).toUpperCase(),u])),i=u=>{let d=String(u).toUpperCase();if(n&&d===String(n.symbol).toUpperCase())return n.address;let p=o.get(d);return p&&p.address?p.address:null},s=[e.symbol],a=[e.address],c=[],l=[];for(let u of r.steps){let d=i(u.to);if(!d)return{error:`declared route names a token that this network has no address for: ${u.to}`};a.push(d),s.push(String(u.to).toUpperCase()===String(n&&n.symbol).toUpperCase()?n.symbol:u.to),c.push(Number(u.fee)),l.push(u.pool||null)}return{tokens:a,symbols:s,fees:c,pools:l}}function Um(e){if(!e||!e.symbols)return"";let t=e.symbols[0];for(let n=0;n<e.fees.length;n++)t+=" \u2192 "+e.symbols[n+1]+" "+Rr(e.fees[n]);return t}function Mm(e){return!e||!e.symbols?[]:e.fees.map((t,n)=>({from:e.symbols[n],to:e.symbols[n+1],fee:t,feeLabel:Rr(t)}))}function IS(e){let t=lu.get(e);if(t&&Date.now()-t.at<NS)return t.value}function Fm(e,t){return lu.set(e,{at:Date.now(),value:t}),t}function TS(){lu.clear()}async function An(e,t,n=[],{timeoutMs:r=15e3}={}){if(!e||!e.rpcUrl)return{ok:!1,why:"network has no RPC endpoint"};let o=typeof AbortController=="function"?new AbortController:null,i=o?setTimeout(()=>o.abort(),r):null;try{let s=await fetch(e.rpcUrl,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:t,params:n}),signal:o?o.signal:void 0});if(!s.ok)return{ok:!1,why:t+": HTTP "+s.status};let a=await s.json();return a.error?{ok:!1,why:t+": "+String(a.error.message||"rpc error").slice(0,120)}:{ok:!0,result:a.result}}catch(s){let a=s&&s.name==="AbortError";return{ok:!1,why:t+": "+(a?"no answer in "+r+" ms":String(s&&s.message||s))}}finally{i&&clearTimeout(i)}}function Cr(e){let t=Fs(e),n=[];for(let r=0;r+64<=t.length;r+=64)n.push(BigInt("0x"+t.slice(r,r+64)));return n}function Km({tokenIn:e,tokenOut:t,amountInWei:n,fee:r,sqrtPriceLimitX96:o=0}){return on.quoteExactInputSingle.hex+_n(e)+_n(t)+gt(n)+gt(r)+gt(o)}function Wm({tokenA:e,tokenB:t,fee:n}){return on.getPool.hex+_n(e)+_n(t)+gt(n)}function Vm({tokenIn:e,tokenOut:t,amountOutWei:n,fee:r,sqrtPriceLimitX96:o=0}){return on.quoteExactOutputSingle.hex+_n(e)+_n(t)+gt(n)+gt(r)+gt(o)}async function OS(e,{tokenIn:t,tokenOut:n,amountOutWei:r,fee:o},i={}){let s=e&&e.uniswap;if(!s||!s.quoter)return{ok:!1,why:"no verified QuoterV2 for this network"};let a=Vm({tokenIn:t,tokenOut:n,amountOutWei:r,fee:o}),c=await An(e,"eth_call",[{to:s.quoter,data:a},"latest"],i);if(!c.ok)return{ok:!1,why:c.why};let l=Cr(c.result);return l.length?l[0]<=0n?{ok:!1,why:"pool cannot serve this output"}:{ok:!0,amountInWei:l[0].toString(),gasEstimate:l.length>1?l[l.length-1].toString():null}:{ok:!1,why:"quoter answered without data"}}async function $m(e,{route:t,amountOutWei:n},r={}){let o=e&&e.uniswap;if(!o||!o.quoter)return{ok:!1,why:"no verified QuoterV2 for this network"};if(!t||!Array.isArray(t.tokens)||t.tokens.length<2)return{ok:!1,why:"route has no path"};let i=t.tokens.slice().reverse(),s=(t.fees||[]).slice().reverse(),a=uu({tokens:i,fees:s}),c=on.quoteExactOutput.hex+gt(64)+gt(n)+gt(a.bytes)+a.packed.padEnd(Math.ceil(a.packed.length/64)*64,"0"),l=await An(e,"eth_call",[{to:o.quoter,data:c},"latest"],r);if(!l.ok)return{ok:!1,why:l.why};let u=du(l.result);return!u||u.amountOutWei<=0n?{ok:!1,why:"pool cannot serve exactly this output"}:{ok:!0,amountInWei:u.amountOutWei.toString(),gasEstimate:u.gasEstimate.toString(),shapeOk:u.sqrtPriceX96After.length===s.length,reversed:i.map(d=>d).length===s.length+1}}function uu({tokens:e,fees:t}){let n=[];for(let o=0;o<e.length;o++)n.push(Fs(e[o]).toLowerCase().padStart(40,"0")),o<t.length&&n.push(Fs(Number(t[o]).toString(16)).toLowerCase().padStart(6,"0"));let r=n.join("");return{packed:r,bytes:r.length/2}}function zm({tokens:e,fees:t,amountInWei:n}){let{packed:r,bytes:o}=uu({tokens:e,fees:t}),i=r.padEnd(Math.ceil(o/32)*64,"0");return on.quoteExactInput.hex+jm("0x40")+gt(n)+gt(o)+i}function Xm(e){let t=Number(e);return Number.isFinite(t)?t/1e4:null}function Rr(e){let t=Xm(e);return t===null?String(e):String(Number(t.toFixed(4)))+"%"}async function Ym(e,{tokenIn:t,tokenOut:n,fee:r},o={}){let i=e&&e.uniswap;if(!i||!i.factory)return{ok:!1,why:"no verified Uniswap factory for this network"};let s=await An(e,"eth_call",[{to:i.factory,data:Wm({tokenA:t,tokenB:n,fee:r})},"latest"],o);if(!s.ok)return{ok:!1,why:s.why};let a=Cr(s.result),c=BS(a[0]);return!c||c===PS?{ok:!0,pool:null}:{ok:!0,pool:c}}async function CS(e,t,{tokenIn:n,tokenOut:r},o={}){if(!t)return null;let[i,s,a]=await Promise.all([An(e,"eth_call",[{to:t,data:on.liquidity.hex},"latest"],o),An(e,"eth_call",[{to:n,data:on.balanceOf.hex+_n(t)},"latest"],o),An(e,"eth_call",[{to:r,data:on.balanceOf.hex+_n(t)},"latest"],o)]),c=l=>l.ok?Cr(l.result)[0]??null:null;return{liquidity:i.ok?BigInt(Cr(i.result)[0]??0n).toString():null,reserveInWei:s.ok&&c(s)!==null?c(s).toString():null,reserveOutWei:a.ok&&c(a)!==null?c(a).toString():null}}async function Gm(e,{tokenIn:t,tokenOut:n,amountInWei:r,fee:o},i={}){let s=e&&e.uniswap;if(!s||!s.quoter)return{fee:o,ok:!1,why:"no verified QuoterV2 for this network"};let a=Km({tokenIn:t,tokenOut:n,amountInWei:r,fee:o}),c=await An(e,"eth_call",[{to:s.quoter,data:a},"latest"],i);if(!c.ok)return{fee:o,ok:!1,why:c.why};let l=Cr(c.result);if(l.length<4)return{fee:o,ok:!1,why:"quoter answered "+l.length+" words, expected 4"};let u=l[0];return u<=0n?{fee:o,ok:!1,why:"pool cannot serve this size"}:{fee:o,ok:!0,amountOutWei:u.toString(),gasEstimate:l[3].toString(),sqrtPriceX96After:l[1].toString(),initializedTicksCrossed:l[2].toString()}}function du(e){let t=Cr(e);if(t.length<4)return null;let n=o=>Number(o)/32,r=o=>{let i=n(o);if(!Number.isInteger(i)||i<0||i>=t.length)return[];let s=Number(t[i]);return!Number.isInteger(s)||s<=0||i+1+s>t.length?[]:t.slice(i+1,i+1+s).map(String)};return{amountOutWei:t[0],sqrtPriceX96After:r(t[1]),initializedTicksCrossed:r(t[2]),gasEstimate:t[3]}}async function qm(e,{route:t,amountInWei:n},r={}){let o=e&&e.uniswap;if(!o||!o.quoter)return{...t,ok:!1,why:"no verified QuoterV2 for this network"};let i=zm({tokens:t.tokens,fees:t.fees,amountInWei:n}),s=await An(e,"eth_call",[{to:o.quoter,data:i},"latest"],r);if(!s.ok)return{...t,ok:!1,why:s.why};let a=du(s.result);return a?a.amountOutWei<=0n?{...t,ok:!1,why:"pool cannot serve this size"}:{...t,ok:!0,amountOutWei:a.amountOutWei.toString(),gasEstimate:a.gasEstimate.toString(),sqrtPriceX96After:a.sqrtPriceX96After,initializedTicksCrossed:a.initializedTicksCrossed,hops:t.fees.length,shapeOk:a.sqrtPriceX96After.length===t.fees.length}:{...t,ok:!1,why:"quoter answered a shape that is not quoteExactInput"}}function Qm(e){return!e||!Array.isArray(e.steps)||!e.steps.length?e&&e.unwrap?"unwrap":"none":e.steps.map(t=>String(t.to).toUpperCase()+":"+Number(t.fee)+(t.pool?":"+String(t.pool).toLowerCase():"")).join("+")}function Zm({amountInWei:e=null,amountOutWei:t=null,inDecimals:n=null,outDecimals:r=null,tokenUsd:o=null,referenceUsd:i=null,stableSteps:s=[],tolerated:a=!1,gates:c=null}={}){let l=c&&Number.isFinite(Number(c.maxDeviationPct))&&Number(c.maxDeviationPct)>0?Number(c.maxDeviationPct):null,u=c&&Number.isFinite(Number(c.stableBandPct))&&Number(c.stableBandPct)>=0?Number(c.stableBandPct):null,d=[],p=(Array.isArray(s)?s:[]).map(R=>{let A={from:R.from,to:R.to,fee:R.fee,feeLabel:Rr(R.fee),inWei:R.inWei||null,outWei:R.outWei||null,exactAmount:!!R.exact,quoted:!!R.ok,ok:!1,ratio:null,deviationPct:null,why:null};if(!R.ok)return A.why="the 1:1 step could not be quoted ("+(R.why||"no answer")+")",d.push(A.why),A;let N=Number(R.inWei)/10**Number(R.inDecimals),f=Number(R.outWei)/10**Number(R.outDecimals);return!(N>0)||!(f>0)?(A.why="the 1:1 step answered with a number that cannot be read",d.push(A.why),A):(A.ratio=f/N,A.deviationPct=Math.abs(1-A.ratio)*100,u===null?(A.why="the 1:1 band is not declared for this step, so this step cannot be checked",d.push(A.why),A):A.deviationPct>u?(A.why=`${A.from}\u2192${A.to} at ${A.feeLabel} pays ${A.ratio.toFixed(6)} ${A.to} per 1 ${A.from} - ${A.deviationPct.toFixed(2)}% off 1:1, and the band is ${u}%`,d.push(A.why),A):(A.ok=!0,A))}),m=Number.isFinite(Number(n))&&Number(e)>0?Number(e)/10**Number(n):null,w=Number.isFinite(Number(r))&&Number(t)>0?Number(t)/10**Number(r):null,y=m!==null&&Number(o)>0?m*Number(o):null,b=y!==null&&w!==null&&w>0?y/w:null,x=Number(i)>0?Number(i):null,I=b!==null&&x!==null?Math.abs(b-x)/x*100:null,E=I!==null&&l!==null&&I>l;E?d.push(`the route implies the native coin at $${b.toFixed(2)} while the reference price is $${x.toFixed(2)} - ${I.toFixed(1)}% apart, and the limit is ${l}%: this is not the market price`):I===null?d.push(x===null?"the reference price of the native coin is not known, so the price cannot be checked":"the price of the token being paid is not known, so the price cannot be checked"):l===null&&d.push("the price limit is not declared for this route, so the price cannot be checked");let U=I!==null&&l!==null,S=E||p.some(R=>!R.ok);return{checked:U,bad:S,tolerated:!!a,blocks:a?!1:S||!U,why:d.length?d.join("; "):null,impliedUsd:b,referenceUsd:x,deviationPct:I,maxDeviationPct:l,stableBandPct:u,tokenUsd:Number(o)>0?Number(o):null,stable:p}}function Jm({paySymbol:e,wrappedSymbol:t,chainName:n,route:r=null}){let o=`no route from ${e} to ${t} on ${n}`,i=r&&r.why?String(r.why):null;return i?o+": "+i:o+": no route for "+e+" is declared - routes are declared by hand, not searched"}function fu(e,t=null){if(e&&e.unwrap)return{blocked:!1,kind:"unwrap",reason:null,price:null};if(!e)return{blocked:!0,kind:"unquoted",reason:"the swap leg has not been quoted yet",price:null};if(!e.ok)return{blocked:!0,kind:"no-route",reason:e.why||"no route",price:null};let n=e.price||null,r=!!(n&&n.bad),o=!!(n&&n.checked===!1),i=!!(n&&n.blocks&&(r||o)),s=t!=null&&Number(t)>0?BigInt(t):null,a=BigInt(e.amountOutWei),c=s===null?null:{needWei:s.toString(),getsWei:a.toString(),covers:a>=s,shortfallWei:(a>=s?0n:s-a).toString()},l={...c||{},price:n,routeLabel:e.routeLabel||null,decimals:e.wrapped?e.wrapped.decimals:null,wrappedSymbol:e.wrapped?e.wrapped.symbol:null};return i?{blocked:!0,...l,kind:r?"bad-price":"price-unchecked",reason:n.why}:c===null?{blocked:!0,...l,kind:"unchecked",reason:"the required escrow amount is not known yet, so coverage cannot be checked"}:c.covers?r?{blocked:!1,...l,kind:"bad-price-tolerated",reason:n.why}:{blocked:!1,...l,kind:"covers",reason:null}:{blocked:!0,...l,kind:"short",reason:"the declared route returns less than the order needs"}}async function pu(e,{token:t,amountWei:n,requiredOutWei:r=null,route:o=null,tokens:i=[],referenceNativeUsd:s=null,gates:a=null}={},c={}){let l=e&&e.uniswap;if(!t||!t.address)return{ok:!1,why:t&&t.native?"paying the native coin needs no DEX leg":"no token address"};if(!l||!l.quoter||!l.wrapped)return{ok:!1,why:"no verified Uniswap addresses for "+(e&&e.name?e.name:"this network")};let u=BigInt(n||0);if(u<=0n)return{ok:!1,why:"amount not entered"};let d=l.wrapped,p=e&&e.name||e&&e.id||"this network";if(String(t.address).toLowerCase()===String(d.address).toLowerCase())return{ok:!1,why:"this is the wrapped native coin: no pool needed, it unwraps 1:1",unwrap:!0};let m=o||null,w=String(e&&e.dexPriceGate||"")==="tolerated",y=m?{steps:(Array.isArray(m.steps)?m.steps:[]).map(f=>({to:f.to,fee:f.fee,pool:f.pool||null,verified:f.verified||null})),why:m.why||null,unwrap:!!m.unwrap}:null;if(!m||!Array.isArray(m.steps)||!m.steps.length)return m&&m.unwrap?{ok:!1,why:"this is the wrapped native coin: no pool needed, it unwraps 1:1",unwrap:!0}:{ok:!1,why:Jm({paySymbol:t.symbol,wrappedSymbol:d.symbol,chainName:p,route:m}),declared:!0,declaration:y,steps:[]};let b=Dm({token:t,tokens:i,wrapped:d,route:m});if(!b||b.error)return{ok:!1,declared:!0,dataError:!0,declaration:y,why:"the declared route for "+t.symbol+" on "+p+" cannot be built: "+(b&&b.error||"unknown reason")};let x=new Map((Array.isArray(i)?i:[]).filter(f=>f&&f.address).map(f=>[String(f.address).toLowerCase(),f])),I=f=>{if(String(f).toLowerCase()===String(t.address).toLowerCase())return t.decimals;if(String(f).toLowerCase()===String(d.address).toLowerCase())return d.decimals;let k=x.get(String(f).toLowerCase());return k&&Number.isFinite(Number(k.decimals))?Number(k.decimals):null},E=[e.id,t.symbol,u.toString(),Qm(m)].join("|"),U=IS(E);if(U===void 0){let f=await qm(e,{route:{tokens:b.tokens,fees:b.fees,symbols:b.symbols,via:null},amountInWei:u},c);if(!f.ok)return Fm(E,{ok:!1,why:f.why,declared:!0});U={ok:!0,quote:f},Fm(E,U)}if(!U.ok)return{...U,declaration:y};let S=U.quote;if(U.hops===void 0){let f=[];for(let k=0;k<b.fees.length;k++){let _=b.fees[k],K=b.tokens[k],H=b.tokens[k+1],P=m.steps&&m.steps[k]||{},j=await Ym(e,{tokenIn:K,tokenOut:H,fee:_},c),L=j.ok?j.pool:null,z=P.pool||null;f.push({step:k+1,from:b.symbols[k],to:b.symbols[k+1],fee:_,feeLabel:Rr(_),decimals:[I(K),I(H)],pool:L,declaredPool:z,poolMatchesDeclared:L&&z?String(L).toLowerCase()===String(z).toLowerCase():null,verified:P.verified||null})}U.hops=f}let B=U.hops;if(U.stableSteps===void 0){let f=(a&&Array.isArray(a.stables)?a.stables:[]).map(_=>String(_).toUpperCase()),k=[];for(let _=0;_<b.fees.length;_++){let K=String(b.symbols[_]).toUpperCase(),H=String(b.symbols[_+1]).toUpperCase();if(!f.includes(K)||!f.includes(H))continue;let P=await Gm(e,{tokenIn:b.tokens[_],tokenOut:b.tokens[_+1],amountInWei:u,fee:b.fees[_]},c);k.push({from:b.symbols[_],to:b.symbols[_+1],fee:b.fees[_],inWei:u.toString(),outWei:P.ok?P.amountOutWei:null,inDecimals:I(b.tokens[_]),outDecimals:I(b.tokens[_+1]),ok:!!P.ok,why:P.ok?null:P.why,exact:_===0})}U.stableSteps=k}let R=Zm({amountInWei:u,amountOutWei:S.amountOutWei,inDecimals:t.decimals,outDecimals:d.decimals,tokenUsd:Number(t.usd)>0?Number(t.usd):null,referenceUsd:s,stableSteps:U.stableSteps,tolerated:w,gates:a}),A=null;if(r!=null&&Number(r)>0){let f=await $m(e,{route:S,amountOutWei:BigInt(r)},c);A=f.ok?{ok:!0,amountInWei:f.amountInWei,gasEstimate:f.gasEstimate,enough:BigInt(f.amountInWei)<=u,enteredWei:u.toString(),spareInWei:(BigInt(f.amountInWei)<=u?u-BigInt(f.amountInWei):0n).toString(),shortInWei:(BigInt(f.amountInWei)<=u?0n:BigInt(f.amountInWei)-u).toString()}:{ok:!1,why:f.why}}let N=r!=null&&Number(r)>0?(()=>{let f=BigInt(r),k=BigInt(S.amountOutWei);return{outWei:f.toString(),getsWei:k.toString(),covers:k>=f,shortfallWei:(k>=f?0n:f-k).toString()}})():null;return{ok:!0,leg:"pool",venue:"Uniswap v3",payToken:t.symbol,wrapped:d,declaredRoute:y,route:{symbols:S.symbols.slice(),fees:S.fees.slice(),pools:b.pools.slice(),via:null,hops:S.fees.length},routeLabel:Um(S),steps:Mm(S),fee:S.fees[S.fees.length-1],feeLabel:S.fees.map(f=>Rr(f)).join(" / "),amountInWei:u.toString(),amountOutWei:S.amountOutWei,gasEstimate:S.gasEstimate,required:N,price:R,exactOut:A,hopsDetail:B,pool:B.length?B[0].pool:null,at:Date.now()}}function RS(e){let t=e&&e.uniswap;if(!t||!t.wrapped)return{ok:!1,why:"no verified wrapped native coin for this network"};let n=t.wrapped;return{ok:!0,leg:"unwrap",venue:n.name||n.symbol,wrapped:n,rate:1,gasEstimate:null,why:null}}var on,NS,lu,Fs,jm,_n,gt,BS,PS,hu=re(()=>{on={quoteExactOutputSingle:{hex:"0xbd21704a",signature:"quoteExactOutputSingle((address,address,uint256,uint24,uint160))"},quoteExactOutput:{hex:"0x2f80bb1d",signature:"quoteExactOutput(bytes,uint256)"},quoteExactInputSingle:{hex:"0xc6a5026a",signature:"quoteExactInputSingle((address,address,uint256,uint24,uint160))"},quoteExactInput:{hex:"0xcdca1753",signature:"quoteExactInput(bytes,uint256)"},getPool:{hex:"0x1698ee82",signature:"getPool(address,address,uint24)"},liquidity:{hex:"0x1a686502",signature:"liquidity()"},balanceOf:{hex:"0x70a08231",signature:"balanceOf(address)"},withdraw:{hex:"0x2e1a7d4d",signature:"withdraw(uint256)"}};NS=2e4,lu=new Map;Fs=e=>String(e||"").replace(/^0x/,""),jm=e=>Fs(e).toLowerCase().padStart(64,"0"),_n=e=>jm(e),gt=e=>{let t="",n=BigInt(e);for(;n>0n;)t=(n&0xffn).toString(16).padStart(2,"0")+t,n>>=8n;return t.padStart(64,"0")};BS=e=>e==null?null:"0x"+e.toString(16).padStart(40,"0"),PS="0x"+"0".repeat(40)});var Ds={};Be(Ds,{createOrderWorker:()=>mu});function mu(){if(typeof Worker>"u")throw new Error("workers are unavailable in this environment");let e=new Worker(new URL("./order-worker.js",import.meta.url),{type:"module"}),t=new Map,n=0;e.onmessage=o=>{let i=o.data||{},s=t.get(i.id);if(s){if(i.kind==="progress"){s.onProgress?.(i.stage,i.detail);return}t.delete(i.id),i.kind==="done"?s.resolve(i.result):s.reject(new Error(i.message||"worker returned an error"))}},e.onerror=o=>{let i=new Error("worker crashed: "+(o.message||"no message"));for(let[,s]of t)s.reject(i);t.clear()};let r=(o,i={},s)=>{let a=++n;return new Promise((c,l)=>{t.set(a,{resolve:c,reject:l,onProgress:s}),e.postMessage({id:a,type:o,...i})})};return{buildSide:(o,i)=>r("newSide",{orderContext:o},i),sealHalf:(o,i,s,a)=>r("seal",{orderContext:o,ownHalf:i,counterparty:{encPub:s}},a),verifyCounterparty:(o,i,s,a)=>r("verify",{orderContext:o,counterparty:i,sealedBytes:s},a),halfCommitment:o=>r("commit",{ownHalf:o}),pointOf:o=>r("pointOf",{ownHalf:o}),jointAddress:o=>r("jointAddress",{joint:o}),makerMaterial:()=>r("newMakerMaterial"),stop:()=>e.terminate()}}var wu=re(()=>{});function ew(e,t={readyWindowSeconds:14400,claimWindowSeconds:3600}){let n=Number(e&&e.costSec||0),r=Math.max(t.readyWindowSeconds,n+900);return{readyWindowSeconds:r,claimWindowSeconds:Math.max(t.claimWindowSeconds,r+3600)}}var tw=re(()=>{});function iw(e,t){let n=ow.get(e);if(n&&Date.now()-n.at<t)return n.value}function Hr(e,t){return ow.set(e,{at:Date.now(),value:t}),t}async function $o(e,t,n=[]){let r=await fetch(e.rpcUrl,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:t,params:n})});if(!r.ok)throw new Error(t+": HTTP "+r.status);let o=await r.json();if(o.error)throw new Error(t+": "+(o.error.message||"RPC error"));return o.result}function DS(e){let t=String(e||"");if(t.length<130)return"";let n=Number(BigInt("0x"+t.slice(66,130))),r=t.slice(130,130+n*2),o=new Uint8Array(r.length/2);for(let i=0;i<o.length;i++)o[i]=parseInt(r.slice(i*2,i*2+2),16);return new TextDecoder().decode(o)}async function sw(e,{force:t=!1}={}){let n=e&&e.priceFeed;if(!n||!n.address)return null;let r=e.id+":usd";if(!t){let o=iw(r,HS);if(o!==void 0)return o}try{let[o,i]=await Promise.all([$o(e,"eth_call",[{to:n.address,data:nw.description},"latest"]),$o(e,"eth_call",[{to:n.address,data:nw.latestRoundData},"latest"])]),s=DS(o),a=rw(i,1),c=Number(rw(i,3))*1e3,l=Number(n.decimals||8),u=Number(a)/10**l,d=c>0&&Date.now()-c<FS,p=u>=(n.min||.01)&&u<=(n.max||1e7);return s!==n.pair||!d||!p?Hr(r,null):Hr(r,{usd:u,updatedAt:c,source:"chainlink",pair:s})}catch{return Hr(r,null)}}async function US(e,{from:t=null,payToken:n=null,amountWei:r=null}={}){let o=e.id+":gas",i=iw(o,LS);if(i!==void 0)return i;let s=await sw(e);if(!s)return Hr(o,null);try{let a=BigInt(await $o(e,"eth_gasPrice")),c=null,l=!1;try{let p=!!(n&&!n.native);if(p&&t){let m=String(t||"").replace(/^0x/,"").padStart(64,"0"),w=BigInt(r||1).toString(16).padStart(64,"0");c=BigInt(await $o(e,"eth_estimateGas",[{from:t,to:n.address,data:"0xa9059cbb"+m+w}])),l=!0}else t?(c=BigInt(await $o(e,"eth_estimateGas",[{from:t,to:t,value:"0x1"}])),l=!0):c=BigInt(e.gasLimitFallback||(p?65e3:21e3))}catch{c=BigInt(e.gasLimitFallback||(tokenTransfer?65e3:21e3))}let u=a*c,d=Number(u)/1e18*s.usd;return Hr(o,{usd:d,gasLimit:c.toString(),gasPrice:a.toString(),native:s,source:"rpc",measured:l})}catch{return Hr(o,null)}}async function aw(e,t={}){if(!e||!e.rpcUrl)return{nativeUsd:null,gasUsd:null,source:"none"};let[n,r]=await Promise.all([sw(e),US(e,t)]);return n&&Number.isFinite(n.usd)&&(e.native.usd=n.usd),{nativeUsd:n?n.usd:null,nativeUpdatedAt:n?n.updatedAt:null,gasUsd:r?r.usd:null,gasPriceWei:r?r.gasPrice:null,gasSource:r?r.source:null,gasMeasured:r?!!r.measured:!1,source:n?"chainlink":"demo"}}function cw(e){if(!e||!e.source||e.source==="none"||e.source!=="chainlink")return"demo values";let t=e.nativeUpdatedAt?new Date(e.nativeUpdatedAt).toISOString().slice(11,16):"?";return(e.gasMeasured?"gas by RPC":"gas estimate")+", price by Chainlink at "+t+" UTC"}var nw,HS,LS,FS,ow,rw,lw=re(()=>{nw={description:"0x7284e416",latestRoundData:"0xfeaf968c"},HS=6e4,LS=3e4,FS=1440*60*1e3,ow=new Map;rw=(e,t)=>BigInt("0x"+String(e).slice(2).slice(t*64,(t+1)*64))});function MS({gasPriceWei:e,readyGasLimit:t=uw,refundGasLimit:n=dw,depositGasLimit:r=0n,extraFeeWei:o=0n}={}){let i=$t(e);if(i===null||i<=0n)return null;let s=$t(t),a=$t(n),c=$t(r),l=$t(o);return s===null||a===null||c===null||l===null||s<=0n||a<=0n||c<0n||l<0n?null:i*(s+a+c)+l}function jS({reserveWei:e,nativeUsd:t,decimals:n=18}={}){let r=$t(e);if(r===null||r<=0n)return null;let o=Number(r)/10**n,i=Number.isFinite(Number(t))&&Number(t)>0?o*Number(t):null;return{native:o,usd:i}}function KS({nativeBalanceWei:e,reserveWei:t}={}){let n=$t(t);if(n===null||n<=0n)return{measured:!1,enough:null,show:!1,balanceUnread:!1};let r=$t(e);return r===null?{measured:!0,enough:!1,show:!0,balanceUnread:!0}:{measured:!0,enough:r>=n,show:r<n,balanceUnread:!1}}function fw({gasPriceWei:e=null,nativeBalanceWei:t=null,nativeUsd:n=null,decimals:r=18,depositGasLimit:o=0n,extraFeeWei:i=0n}={}){let s=MS({gasPriceWei:e,depositGasLimit:o,extraFeeWei:i}),a=$t(o),c=$t(i),l=s===null?null:jS({reserveWei:s,nativeUsd:n,decimals:r}),u=KS({nativeBalanceWei:t,reserveWei:s});return{measured:s!==null,gasPriceWei:e==null?null:String(e),reserveWei:s===null?null:s.toString(),depositGasLimit:a===null?null:a.toString(),extraFeeWei:c===null?null:c.toString(),native:l?l.native:null,usd:l?l.usd:null,enough:u.enough,show:u.show,balanceUnread:!!u.balanceUnread}}var uw,dw,yI,$t,pw=re(()=>{uw=120000n,dw=250000n,yI=uw+dw,$t=e=>{if(e==null||e==="")return null;try{return BigInt(typeof e=="bigint"?e:String(e))}catch{return null}}});var ww={};Be(ww,{STEP_LABELS:()=>yl,activeSwaps:()=>xl,amountInputValue:()=>Fp,cachedFeeRate:()=>Gh,cachedFeeTerms:()=>Yh,claimOrder:()=>GS,createOrderWorker:()=>mu,createReverseSwap:()=>gl,createSwap:()=>bl,createSwapWallet:()=>Zi,dealSwapIds:()=>Al,dexLegVerdict:()=>fu,ensureFeeTerms:()=>qh,evm:()=>Ie,feeWeiFor:()=>Rl,markReadyOrder:()=>YS,moneroNode:()=>Ho,networkFromShape:()=>Er,networkLabel:()=>dp,nodeHeight:()=>wv,orderDeadlines:()=>mv,orderGasReservePlan:()=>fw,orderStatus:()=>hv,priceLabel:()=>cw,probeMode:()=>up,quoteDexOut:()=>pu,refreshChainPrices:()=>aw,refundOrder:()=>qS,sdkAddressNetwork:()=>Sv,sdkAutoRefund:()=>QS,sdkBook:()=>iv,sdkBookSnapshot:()=>sv,sdkBookUse:()=>tv,sdkBundle:()=>gu,sdkConfirmReady:()=>bv,sdkCoreModules:()=>rr,sdkForgetSwap:()=>pv,sdkGetSwap:()=>cv,sdkListSwaps:()=>av,sdkOpenRecovery:()=>ZS,sdkOrderQuote:()=>lv,sdkOrderTerms:()=>xu,sdkProgress:()=>yv,sdkQuotesSnapshot:()=>ev,sdkRefundEth:()=>gv,sdkSetDestination:()=>kv,sdkStartSwap:()=>uv,sdkSweepNow:()=>xv,sdkSyncSwaps:()=>fv,sdkWatchQuotes:()=>JS,sdkWatchSwap:()=>dv,serverRestoreHeightFor:()=>_l,setLiveFocus:()=>Nl,swapCore:()=>fe,toWei:()=>_s,useStartSwap:()=>VS});function VS(e=null){return Ms=typeof e=="function"?e:null,!!Ms}async function gu(){return yu||(yu=(async()=>{try{return await import(WS)}catch(e){return console.warn("[bridge] the built SDK core was not served to the page ("+(e&&e.message||e)+"): actions go by the previous engine call; see www/js/sdk/bridge.js"),null}})()),yu}async function rr(){let e=await gu();return e?{actions:{createActions:e.createActions},wallet:{evmWallet:e.evmWallet},recovery:{createRecovery:e.createRecovery}}:null}async function $S(){let e=await gu();return e?{factory:e.createNinsei}:null}function zS(e){return e&&e.escrow&&e.escrow.mode==="live"?"live":"sim"}function XS(e){return{settlement:{chain:e.id},xmrNetwork:e.monero&&e.monero.networkType||ve.networkType,assetsBase:"/",mode:zS(e),storage:Vc(),serverAuth:async()=>{if(ds())return ds();try{await nh()}catch{return null}return ds()},evmCall:t=>gn(t),evmCode:t=>ls({address:t}),allowedProviders:gc(e),knownFactoryCodes:xc(e),knownImplementationCodes:kc(e)}}async function Fe(e){let t=await $S();if(!t)return null;let n=Je(e||Nt);return bu.has(n.id)||bu.set(n.id,t.factory(XS(n))),{chain:n,sdk:bu.get(n.id)}}function zo(e){let t=typeof Oo=="function"?Oo():null;return t?e.wallet.evmWallet(t):null}async function YS({escrow:e,expect:t}={}){let n=await rr(),r=n?zo(n):null;if(!n||!r)throw new Error("[bridge] nothing to sign the readiness mark with: "+(n?"wallet not connected":"the SDK core was not served to the page"));return await n.actions.createActions({call:o=>gn(o)}).markReady({escrow:e,expect:t},r)}async function GS({escrow:e,halfClaimer:t,expect:n}={}){let r=await rr(),o=r?zo(r):null;if(!r||!o)throw new Error("[bridge] nothing to sign the claim with: "+(r?"wallet not connected":"the SDK core was not served to the page"));return await r.actions.createActions({call:i=>gn(i)}).claim({escrow:e,halfClaimer:t,expect:n},o)}async function qS({escrow:e,halfLocker:t}={}){let n=await rr(),r=n?zo(n):null;if(!n||!r)throw new Error("[bridge] nothing to sign the refund with: "+(n?"wallet not connected":"the SDK core was not served to the page"));return await n.actions.createActions({call:o=>gn(o)}).refund({escrow:e,halfLocker:t},r)}async function QS(e){let t=await Fe(e&&e.chain);if(!t)return null;let n={...e||{}};if(!n.nodes&&t.sdk.config&&typeof t.sdk.config.nodesFor=="function"&&(n.nodes=t.sdk.config.nodesFor(n.xmrNetwork||ve.networkType)),!n.wallet){let r=await rr(),o=r?zo(r):null;o&&(n.wallet=o)}return t.sdk.swaps.refundIfXmrMissing(n)}async function ZS(e,t){let n=await rr();return n?await n.recovery.createRecovery().open(e,t):null}async function JS(e,t){let n=await Fe(e&&e.chain);return n?n.sdk.quotes.watch(e,t):null}async function ev(e){let t=await Fe(e);return t?t.sdk.quotes.snapshot():null}function tv(e){if(hw=e||null,nr=null,Us=null,Nn=null,Ot)try{Ot()}catch{}Ot=null}function mw(e){let t=Number.isFinite(Number(e.at))?Number(e.at):null;return{providerId:e.providerId,displayName:e.displayName,pair:e.pair,asset:e.asset,currency:e.currency,assetNetwork:e.assetNetwork,currencyNetwork:e.currencyNetwork,networkStated:e.networkStated===!0,rateQuote:e.rateQuote,rate:e.rate,min:e.min,max:e.max,step:e.step,ttlMs:e.ttlMs,at:t,ageMs:t===null?null:Math.max(0,Date.now()-t),seq:e.seq,why:e.why,signature:e.signature,keyId:e.keyId,finality:e.finality,networksDerived:e.networksDerived===!0,networksUnnamed:e.networksUnnamed===!0}}function rv(e){return{...mw(e),code:e.code,kind:nv[e.code]||e.code,why:e.why}}function ov(e){if(!e)return{ok:!1,error:null,data:null,at:0,fetching:!1};let t=(Array.isArray(e.offers)?e.offers:[]).map(mw),n=(Array.isArray(e.refused)?e.refused:[]).map(rv),r=t.map(o=>o.at).filter(o=>Number.isFinite(o));return{ok:!e.error,error:e.error?String(e.error.code||"unknown"):null,at:e.at,fetching:!1,data:{offers:t,refused:n,quotes:t,best:e.best||null,seq:e.seq===void 0?null:e.seq,references:Array.isArray(e.references)?e.references:[],at:r.length?Math.max(...r):null}}}async function iv({chain:e,direction:t,token:n,size:r}={}){let o=hw,i="injected";if(!o){let l=await Fe(e);if(!l){if(Ot){try{Ot()}catch{}Ot=null}return Us=null,Nn=null,nr=null,null}o=l.sdk.quotes,i=l.chain.id}let s=t==="sell"?"sell":"buy",a=i+"|"+s+"|"+String(n||"")+"|"+String(r??"");if(Ot&&Us===a)return nr;if(Ot){try{Ot()}catch{}Ot=null}Us=a,Nn=null;let c=new Promise(l=>{Nn=l});try{Ot=o.watch({direction:s,token:n,size:r},l=>{if(nr=l,Nn){let u=Nn;Nn=null,u()}})}catch(l){return Nn=null,nr=null,console.warn("[bridge] the quote book was not served to the core ("+(l&&l.message||l)+"): there will be no offers; see www/js/sdk/bridge.js"),null}return await c,nr}function sv(){return ov(nr)}async function av(e){let t=await Fe(e);return t?t.sdk.swaps.list():null}async function cv(e,t){let n=await Fe(t);return n?n.sdk.swaps.get(e):null}function xu({chain:e,amountWei:t,finality:n=null,salt:r=null,asset:o="XMR"}={}){let i=ew(n),s=Math.floor(Date.now()/1e3),a=e&&e.escrow||{};if(!a.cashier)throw new Error("no fee cashier set on this network (escrow.cashier) - the order cannot be assembled");return{chainId:e.chainId,factory:a.address,cashier:a.cashier,locker:er(),amount:String(t),asset:String(o||"XMR"),readyBy:String(s+i.readyWindowSeconds),t1:String(s+i.claimWindowSeconds),salt:r||As()}}async function lv({chain:e,providerId:t,amountWei:n,finality:r=null,salt:o=null,asset:i="XMR"}={}){let s=await Fe(e);if(!s)return null;let a=xu({chain:s.chain,amountWei:n,finality:r,salt:o,asset:i}),c=await s.sdk.quotes.firm({providerId:t,order:a});return{order:a,quote:c}}async function uv(e){if(Ms)return Ms({...e||{}});let t=await Fe(e&&e.chain);if(!t)return null;let n={...e||{}};if(!n.wallet){let r=await rr(),o=r?zo(r):null;o&&(n.wallet=o)}if(n.wallet)try{t.sdk.wallet.use(n.wallet),await t.sdk.wallet.connect({chainId:t.chain.chainId})}catch{}return n.order||(n.order=xu({chain:t.chain,amountWei:n.amountWei,finality:n.finality,salt:n.salt,asset:n.receiveAsset})),!n.orderQuote&&n.providerId&&(n.orderQuote=await t.sdk.quotes.firm({providerId:n.providerId,order:n.order})),n.orderQuote&&(n.orderQuote.claimer&&(n.order={...n.order,claimer:n.orderQuote.claimer}),n.orderQuote.id&&(n.quote={...n.quote||{},id:n.orderQuote.id}),n.counterparty||(n.counterparty=n.orderQuote)),n.quote={...n.quote||{},readyBy:Number(n.order.readyBy),t1:Number(n.order.t1)},t.sdk.swaps.start(n)}async function dv(e){let t=await Fe(e&&e.chain);return t?t.sdk.swaps.watch(e):null}async function fv(e){let t=await Fe(e);return t?t.sdk.swaps.sync():null}async function pv(e,t){let n=await Fe(t);return n?n.sdk.swaps.forget(e):null}async function hv(e){let t=await Fe(void 0);if(!t)throw new Error("[bridge] cannot read the order state: the SDK core was not served to the page");return t.sdk.order.status(e)}async function mv(e){let t=await Fe(void 0);if(!t)throw new Error("[bridge] cannot read the order deadlines: the SDK core was not served to the page");return t.sdk.order.deadlines(e)}async function wv(){return ul()}async function yv(e,t){let n=await Fe(t);return n?n.sdk.swaps.progress(e):null}async function bv(e){let t=await Fe(void 0);return t?t.sdk.swaps.confirmReady(e):Sl(e)}async function gv(e,t="you"){let n=await Fe(void 0);return n?n.sdk.swaps.refundEth(e,t):El(e,t)}async function xv(e){let t=await Fe(void 0);return t?t.sdk.swaps.sweepNow(e):vl(e)}async function kv(e,t){let n=await Fe(void 0);if(n)return n.sdk.swaps.setDestination(e,t);let r=Ir(e);return r?(r.receiveAddress=t,kl(r)):null}async function Sv(e){let t=await Fe(void 0);if(t)return t.sdk.swaps.addressNetwork(e);try{return Er(e)}catch{return null}}var WS,Ms,yu,bu,Ot,Us,nr,Nn,hw,nv,yw=re(()=>{mt();is();ll();cu();tw();Pr();Uo();Es();Qn();Lo();Pc();Xc();lw();pw();hu();Pr();Es();wu();Uo();Uo();Lo();WS=new URL("../../assets/vendors/sdk/sdk-browser.js?v=69d79c13",import.meta.url).href,Ms=null;yu=null;bu=new Map;Ot=null,Us=null,nr=null,Nn=null,hw=null;nv={disabled:"off"}});mt();Nc();Sp();is();ll();Uo();Mc();Io();var bt={};Be(bt,{ORDER_CONTEXT_VERSION:()=>Ah,orderContextString:()=>Vk});var Ah="ninsei-order-v3",Kk=e=>String(e??"").trim().toLowerCase(),Wk=e=>{if(typeof e=="bigint")return e.toString(10);if(typeof e=="number")return String(Math.trunc(e));let t=Kk(e);return t.startsWith("0x")?BigInt(t).toString(10):t},Eh=["chainId","factory","locker","claimer","amount","readyBy","t1","salt"];function Vk(e){if(!e||typeof e!="object")throw new Error("order context needs an object with the order fields");let t=Eh.filter(n=>e[n]===void 0||e[n]===null||e[n]==="");if(t.length)throw new Error("order context is missing fields: "+t.join(", "));return Ah+"|"+Eh.map(n=>Wk(e[n])).join("|")}var ys={};Be(ys,{createOrderBuilder:()=>Gk});Io();function ms(e,t,n){if(!t||!n)throw new Error("secp256k1 and keccak256 are required");let r=BigInt(e);if(r<=0n)throw new Error("the half must be a positive number");let i=t.Point.BASE.multiply(r).toBytes(!1).slice(1);return"0x"+Array.from(n(i),s=>s.toString(16).padStart(2,"0")).join("")}function _h({ed25519:e,secp256k1:t,keccak256:n,sha3_512:r,randomBytes:o}){if(typeof r!="function")throw new Error("createDleq2: sha3_512 is required (SHA3-512 from @noble/hashes)");let i=e.Point.Fn.ORDER,s=t.Point.Fn.ORDER,a=Math.min(i.toString(2).length,s.toString(2).length),c={A:{name:"secp256k1",P:t.Point,order:s,G:t.Point.BASE,Galt:t.Point.fromHex("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0")},B:{name:"ed25519",P:e.Point,order:i,G:e.Point.BASE,Galt:e.Point.fromHex("8b655970153799af2aeadc9ff1add0ea6c7251d54154cfa92c173a0dd39c1f94")}};c.A.Galt.precompute(8),c.B.Galt.precompute(8);let l=g=>{let T=String(g??""),v=[];for(let V=0;V<T.length;V++){let D=T.codePointAt(V);D>65535&&V++,D<128?v.push(D):D<2048?v.push(192|D>>6,128|D&63):D<65536?v.push(224|D>>12,128|D>>6&63,128|D&63):v.push(240|D>>18,128|D>>12&63,128|D>>6&63,128|D&63)}return new Uint8Array(v)},u=g=>typeof g=="string"?g:g.toHex?g.toHex():String(g);function d(g){let T=g.replace(/^0x/i,""),v=new Uint8Array(T.length/2);for(let V=0;V<v.length;V++)v[V]=parseInt(T.substr(V*2,2),16);return v}let p=g=>g.toString(16).padStart(64,"0");function m(g){let T=0n;for(let v of g)T=T<<8n|BigInt(v);return T}function w(g){let T=0n;for(let v=g.length-1;v>=0;v--)T=T<<8n|BigInt(g[v]);return T}function y(g){let T=g.reduce((D,F)=>D+F.length,0),v=new Uint8Array(T),V=0;for(let D of g)v.set(D,V),V+=D.length;return v}function b(g,T){let v=r(y(T.map(V=>typeof V=="string"?d(V):V)));if(v.length!==64)throw new Error("challenge: sha3_512 returned "+v.length+" bytes instead of 64");return w(v)%g.order}function x(g){let T=w(o(64))%g.order;return T===0n?1n:T}function I(g,T){return g>>BigInt(T)&1n}function E(g,T,v){let D=((typeof v=="bigint"?v:BigInt(v))%g.order+g.order)%g.order;return D===0n?g.P.ZERO:T===g.Galt?T.multiply(D):T.multiplyUnsafe(D)}function U(g,T,v){return E(g,v||g.G,typeof T=="bigint"?T:BigInt(T))}let S=(g,T)=>g.add(T),B=(g,T)=>g.subtract(T),R=g=>d(g.toHex()),A=g=>d(p(g));function N(g,T){let v=[],V=[],D=0n,F=1n;for(let M=0;M<a;M++){if(M===a-1){let G=f(F,g.order);v[M]=(g.order-D%g.order)*G%g.order}else v[M]=x(g),D=(D+v[M]*F)%g.order,F=F*2n%g.order;let X=I(T,M);V.push(S(U(g,X),U(g,v[M],g.Galt)))}return{rs:v,cs:V}}function f(g,T){let[v,V]=[g%T,T],[D,F]=[1n,0n];for(;V!==0n;){let M=v/V;[v,V]=[V,v-M*V],[D,F]=[F,D-M*F]}if(v!==1n)throw new Error("modInv: not invertible");return(D%T+T)%T}function k(g,T){let v=T[0];for(let V=1;V<T.length;V++)v=S(v,U(g,2n**BigInt(V)%g.order,T[V]));return v}function _(g,T,v,V,D,F,M){let X=x(c.A),G=x(c.B),Z=(ne,we)=>[l(M),R(v),R(V),R(ne),R(we)],J=b(c.A,Z(U(c.A,X,c.A.Galt),U(c.B,G,c.B.Galt)),M),te=b(c.B,Z(U(c.A,X,c.A.Galt),U(c.B,G,c.B.Galt)),M);if((g===1n||g===1?1n:0n)===0n){let ne=x(c.A),we=x(c.B),nt=B(v,c.A.G),ht=B(V,c.B.G),Ki=b(c.A,Z(B(U(c.A,ne,c.A.Galt),E(c.A,nt,J)),B(U(c.B,we,c.B.Galt),E(c.B,ht,te))),M),Wi=b(c.B,Z(B(U(c.A,ne,c.A.Galt),E(c.A,nt,J)),B(U(c.B,we,c.B.Galt),E(c.B,ht,te))),M);return{eA:Ki,eB:Wi,a0:ne,a1:(X+Ki*D)%c.A.order,b0:we,b1:(G+Wi*F)%c.B.order}}let Y=x(c.A),ee=x(c.B),le=b(c.A,Z(B(U(c.A,Y,c.A.Galt),E(c.A,v,J)),B(U(c.B,ee,c.B.Galt),E(c.B,V,te))),M),Oe=b(c.B,Z(B(U(c.A,Y,c.A.Galt),E(c.A,v,J)),B(U(c.B,ee,c.B.Galt),E(c.B,V,te))),M);return{eA:J,eB:te,a0:(X+le*D)%c.A.order,a1:Y,b0:(G+Oe*F)%c.B.order,b1:ee}}let K=g=>({eA:p(g.eA),eB:p(g.eB),a0:p(g.a0),a1:p(g.a1),b0:p(g.b0),b1:p(g.b1)});function H(g,T,v,V,D){let F=x(g),M=U(g,F),X=b(g,[l(V),l("ninsei-dleq-pok|"+D),R(v),R(M)]);return{R:u(M),s:p((F+X*T)%g.order)}}function P(g,T,v,V,D){if(!v||typeof v!="object"||typeof v.R!="string"||typeof v.s!="string")return!1;let F,M;try{F=g.P.fromHex(v.R.replace(/^0x/i,"")),M=BigInt(String(v.s).startsWith("0X")?"0x"+String(v.s).slice(2):String(v.s).startsWith("0x")?v.s:"0x"+v.s)}catch{return!1}let X=b(g,[l(V),l("ninsei-dleq-pok|"+D),R(T),R(F)]);return U(g,M).equals(S(F,E(g,T,X)))}function j(g,T){g=typeof g=="bigint"?g:BigInt(g);let v=U(c.A,g),V=U(c.B,g),D=N(c.A,g),F=N(c.B,g),M=[];for(let X=0;X<a;X++)M.push({i:X,bit:I(g,X)===1n?1:0,cA:u(D.cs[X]),cB:u(F.cs[X]),rA:p(D.rs[X]),rB:p(F.rs[X])});return{XA:u(v),XB:u(V),context:String(T??""),pokA:H(c.A,g,v,T,"A"),pokB:H(c.B,g,V,T,"B"),bits:M}}function L(g,T){let v=_(g.bit===1?1n:0n,g.i,c.A.P.fromHex(String(g.cA).replace(/^0x/,"")),c.B.P.fromHex(String(g.cB).replace(/^0x/,"")),BigInt("0x"+String(g.rA).replace(/^0x/,"")),BigInt("0x"+String(g.rB).replace(/^0x/,"")),T);return{i:g.i,cA:g.cA,cB:g.cB,sig:K(v)}}function z(g,T){let v=new Map(T.map(D=>[D.i,D])),V=[];for(let D=0;D<a;D++){let F=v.get(D);if(!F)throw new Error("assembleProof: no part for bit "+D);V.push({cA:F.cA,cB:F.cB,sig:F.sig})}return{XA:g.XA,XB:g.XB,pokA:g.pokA,pokB:g.pokB,proofs:V}}function W(g,T,v){let V=j(g,T),D=[];for(let F=0;F<a;F++)v&&(F%16===0||F===a-1)&&v(F+1,a),D.push(L(V.bits[F],V.context));return z(V,D)}function $(g,T){if(g.name!=="ed25519")return!0;try{return T.isTorsionFree()===!0}catch{return!1}}function O(g,T,v={}){if(!g||typeof g!="object")return{ok:!1,reason:"proof: an object is expected"};if(typeof g.XA!="string"||typeof g.XB!="string")return{ok:!1,reason:"proof: no XA or XB"};if(!Array.isArray(g.proofs))return{ok:!1,reason:"proof: no parts list"};if(g.proofs.length!==a)return{ok:!1,reason:"proof: "+g.proofs.length+" parts, expected "+a};let V=v.requireKnowledge!==!1,D=(Z,J)=>Z.P.fromHex(String(J).replace(/^0x/i,"")),F,M,X,G;try{if(F=D(c.A,g.XA),M=D(c.B,g.XB),!$(c.B,M))return{ok:!1,reason:"proof: XB is not in the prime-order subgroup"}}catch(Z){return{ok:!1,reason:"proof: XA or XB is unparsable ("+String(Z&&Z.message||Z)+")"}}if(V)try{if(!P(c.A,F,g.pokA,T,"A"))return{ok:!1,reason:"proof: the secp256k1 knowledge proof did not verify"};if(!P(c.B,M,g.pokB,T,"B"))return{ok:!1,reason:"proof: the ed25519 knowledge proof did not verify"}}catch(Z){return{ok:!1,reason:"proof: the knowledge proof is unparsable ("+String(Z&&Z.message||Z)+")"}}try{X=g.proofs.map((Z,J)=>{try{return D(c.A,Z.cA)}catch(te){throw new Error("bit "+J+": "+String(te&&te.message||te))}}),G=g.proofs.map((Z,J)=>{try{return D(c.B,Z.cB)}catch(te){throw new Error("bit "+J+": "+String(te&&te.message||te))}})}catch(Z){return{ok:!1,reason:"proof: "+String(Z&&Z.message||Z)}}if(!k(c.A,X).equals(F))return{ok:!1,reason:"the commitment sum does not give X on secp256k1"};if(!k(c.B,G).equals(M))return{ok:!1,reason:"the commitment sum does not give X on ed25519"};for(let Z=0;Z<g.proofs.length;Z++){let J=g.proofs[Z];try{if(!$(c.B,G[Z]))return{ok:!1,reason:"bit "+Z+": the commitment is not in the prime-order subgroup"};let te=J.cA,ke=J.cB,Y={};for(let Vi of["eA","eB","a0","a1","b0","b1"]){let mc=J.sig[Vi],wc=String(mc);Y[Vi]=BigInt(/^0x/i.test(wc)?wc:"0x"+wc)}let ee=D(c.A,te),le=D(c.B,ke),Oe=(Vi,mc)=>[l(T),R(ee),R(le),R(Vi),R(mc)],ne=U(c.A,Y.a1,c.A.Galt),we=E(c.A,ee,Y.eA),nt=U(c.B,Y.b1,c.B.Galt),ht=E(c.B,le,Y.eB),Ki=b(c.A,Oe(B(ne,we),B(nt,ht)),T),Wi=b(c.B,Oe(B(ne,we),B(nt,ht)),T),Wf=U(c.A,Y.a0,c.A.Galt),Vf=E(c.A,B(ee,c.A.G),Ki),$f=U(c.B,Y.b0,c.B.Galt),zf=E(c.B,B(le,c.B.G),Wi),wx=b(c.A,Oe(B(Wf,Vf),B($f,zf)),T),yx=b(c.B,Oe(B(Wf,Vf),B($f,zf)),T);if(wx!==Y.eA||yx!==Y.eB)return{ok:!1,reason:"bit "+Z+": challenges did not match"}}catch(te){return{ok:!1,reason:"bit "+Z+": fields are unparsable ("+String(te&&te.message||te)+")"}}}return{ok:!0}}return{BITS:a,curves:c,prove:W,verify:O,prepareProof:j,proveBit:L,assembleProof:z,torsionFree:$}}var Nh="halfenc is locked: the sealed-half envelope is not part of the live flow (keccak commit/reveal replaced it). Set globalThis.ARRAKIS_ALLOW_HALFENC = true to work with it in a test or a spike.";function Ih(){return globalThis.ARRAKIS_ALLOW_HALFENC===!0}function Th({secp256k1:e,ed25519:t,keccak256:n,randomBytes:r}){let o=t.Point.Fn.ORDER,i=e.Point.Fn.ORDER,s=o<i?o:i;function a(y){let b=0n;for(let x of y)b=b<<8n|BigInt(x);return b}function c(y){for(let b=0;b<256;b++){let x=a(r(32));if(x>0n&&x<y)return x}throw new Error("randScalar: failed in 256 attempts")}let l=y=>y.toString(16).padStart(64,"0");function u(){let y=c(i);return{priv:y,pub:e.Point.BASE.multiply(y).toHex()}}function d(y,b){let x=n(Uint8Array.from(Buffer.concat([Buffer.from(y.replace(/^0x/,""),"hex"),Buffer.from(b||"","utf8")])));return a(x)%s}function p(y,b,x){if(!Ih())throw new Error(Nh);if(!(y>0n&&y<s))throw new Error("seal: half outside min(l, n)");let I=e.Point.fromHex(b.replace(/^0x/,"")),E=c(i),U=e.Point.BASE.multiply(E),S=I.multiply(E),B=d(S.toHex(),x),R=A=>"0x"+String(A).replace(/^0x/i,"").toLowerCase();return{recipient:R(b),ephemeral:R(U.toHex()),masked:"0x"+l((y+B)%s),context:x||""}}function m(y,b,x){if(!Ih())return{ok:!1,reason:Nh};if(!y||!y.ephemeral||!y.masked)return{ok:!1,reason:"incomplete envelope"};let E=e.Point.fromHex(y.ephemeral.replace(/^0x/,"")).multiply(b),U=d(E.toHex(),y.context),S=(BigInt(y.masked)-U+s)%s;if(S===0n)return{ok:!1,reason:"restored zero"};if(!x)return{ok:!0,x:S};let B=t.Point.BASE.multiply(S).toHex(),R=t.Point.fromHex(x.startsWith("0x")?x.slice(2):x).toHex();return B!==R?{ok:!1,reason:"the ciphertext holds a different half"}:{ok:!0,x:S}}function w(y){let b=n(ws(y));return"0x"+vn(b)}return{LIMIT:s,recipientKeyPair:u,seal:p,open:m,packSealed:Il,unpackSealed:Xk,sealedCommitmentOf:w}}var Oh=1;function vn(e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}function $k(e){let t=String(e??""),n=[];for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);o<128?n.push(o):o<2048?n.push(192|o>>6,128|o&63):n.push(224|o>>12,128|o>>6&63,128|o&63)}return new Uint8Array(n)}function zk(e){let t="";for(let n=0;n<e.length;n++){let r=e[n];r<128?t+=String.fromCharCode(r):r<224?t+=String.fromCharCode((r&31)<<6|e[++n]&63):t+=String.fromCharCode((r&15)<<12|(e[++n]&63)<<6|e[++n]&63)}return t}var ws=e=>{let t=String(e||"").replace(/^0x/i,""),n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++)n[r]=parseInt(t.substr(r*2,2),16);return n};function Il(e){if(!e||!e.recipient||!e.ephemeral||!e.masked)throw new Error("packSealed: incomplete envelope");let t=ws(e.recipient),n=ws(e.ephemeral);if(t.length!==33)throw new Error("packSealed: recipient key must be 33 bytes (compressed point)");if(n.length!==33)throw new Error("packSealed: ephemeral point must be 33 bytes (compressed)");let r=BigInt(e.masked).toString(16).padStart(64,"0"),o=$k(e.context);if(o.length>255)throw new Error("packSealed: context longer than 255 bytes");return"0x"+vn(Uint8Array.of(Oh))+vn(t)+vn(n)+r+o.length.toString(16).padStart(2,"0")+vn(o)}function Xk(e){let t=ws(e);if(t.length<100)throw new Error("unpackSealed: envelope shorter than 100 bytes");if(t[0]!==Oh)throw new Error("unpackSealed: unknown format version: "+t[0]);let n=t[99];if(t.length!==100+n)throw new Error("unpackSealed: length does not match the one in the context");return{recipient:"0x"+vn(t.slice(1,34)),ephemeral:"0x"+vn(t.slice(34,67)),masked:"0x"+vn(t.slice(67,99)),context:zk(t.slice(100))}}Qn();jc();function Gk({ed25519:e,secp256k1:t,keccak256:n,sha3_512:r,randomBytes:o}){let i=No({ed25519:e,secp256k1:t,keccak256:n,randomBytes:o}),s=_h({ed25519:e,secp256k1:t,keccak256:n,sha3_512:r,randomBytes:o}),a=Th({secp256k1:t,ed25519:e,keccak256:n,randomBytes:o});function c(b,x=!1,I){let E=i.newHalf(),U=i.publicHalves(E),S=i.newHalf(),B=i.publicHalves(S).ed,R=a.recipientKeyPair(),A=s.prove(E,b,I);return{half:E,pub:U,viewHalf:S,viewPub:B,enc:R,proof:A,standIn:x}}function l(b,x,I,E){let U=s.verify(b.proof,x);if(!U.ok)return{ok:!1,reason:"counterparty DLEQ failed: "+U.reason};if(b.pub&&b.pub.ed&&String(b.proof.XB).toLowerCase()!==String(b.pub.ed).toLowerCase())return{ok:!1,reason:"the proven ed25519 point does not match the declared one: "+b.proof.XB+" vs "+b.pub.ed};if(b.commitHalfClaimer){let S=null;try{let A=t.Point.fromHex(String(b.proof.XA).replace(/^0x/,"")).toBytes(!1).slice(1);S="0x"+Array.from(n(A),N=>N.toString(16).padStart(2,"0")).join("")}catch{S=null}let B=R=>String(R||"").replace(/^0x/,"").toLowerCase().slice(-40);if(!S||B(S)!==B(b.commitHalfClaimer))return{ok:!1,reason:"the proven secp256k1 point does not match commitHalfClaimer: "+(S||"unparsed")+" vs "+b.commitHalfClaimer}}else return{ok:!1,reason:"the counterparty side carries no commitHalfClaimer"};if(I&&E){let S=a.open(a.unpackSealed(I),E,b.pub.ed);if(!S.ok)return{ok:!1,reason:"the counterparty envelope does not confirm the half: "+S.reason}}return{ok:!0}}function u(b,x,I){let E=a.seal(x,b.enc.pub,I),U=Il(E);return{sealed:E,bytes:U,commitment:a.sealedCommitmentOf(U)}}function d(b,x,I){return a.open(a.unpackSealed(b),x,I)}function p(b){return ms(b,t,n)}function m(b,x){return i.combinePublic(b.pub.ed,x.pub.ed)}function w(b){return i.publicHalves(typeof b=="bigint"?b:BigInt(b)).ed}function y({ownSpendHalf:b,ownViewHalf:x,otherSpendPoint:I,otherViewPoint:E,network:U}){return ns({halves:i,addressFromKeys:qn,deps:{keccak256:n},ownSpendHalf:b,ownViewHalf:x,otherSpendPoint:I,otherViewPoint:E,network:U})}return{halves:i,dleq:s,enc:a,newSide:c,verifySide:l,sealFor:u,openFrom:d,jointAddressPoint:m,pointOf:w,jointAddress:y,halfCommitment:p}}cu();hu();wu();var js={};Be(js,{checkOrderQuoteShape:()=>Ev,pairAsset:()=>Bv,pairCurrency:()=>Pv,pairFacingUser:()=>Ov,quoteNetworksFit:()=>Rv,refreshRfq:()=>ku,requestOrderQuote:()=>vv,rfqOffers:()=>Cv,rfqQuery:()=>Iv,rfqSnapshot:()=>Tv,setRfqQuery:()=>Nv,startRfqPolling:()=>Hv});mt();async function vv({providerId:e,order:t}){if(!e)throw new Error("no provider selected: there is no one to ask for an order quote");let n=await fetch(_v()+"/order-quote",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({providerId:e,order:t})}),r=null;try{r=await n.json()}catch{r=null}if(!n.ok||!r||r.ok!==!0||!r.quote){let o=r&&(r.error||r.why)||"HTTP "+n.status;throw new Error("the provider gave no order quote: "+o)}if(r.signatureVerified!==!0)throw new Error("provider signature not confirmed: "+String(r.signatureWhy||"the backend did not verify"));return r.quote}function Ev(e){let t=["providerId","amount","claimer","edPointClaimer","commitHalfClaimer","viewHalfClaimer","proof","context","expiresAt"].filter(n=>e[n]===void 0||e[n]===null||e[n]==="");if(t.length)throw new Error("the order quote is missing fields: "+t.join(", "));if(e.quoteKind!=="orderQuote")throw new Error("not an order quote, but "+String(e.quoteKind));if(Number(e.expiresAt)<=Date.now())throw new Error("the order quote has expired")}var Av=null,_v=()=>Av||Zt.base,xt={size:1,side:"buy",chain:Nt,token:null};function Nv(e){e&&((e.side==="buy"||e.side==="sell")&&(xt.side=e.side),e.size!==null&&e.size!==void 0&&Number(e.size)>0?xt.size=Number(e.size):xt.size=1,typeof e.chain=="string"&&e.chain&&(xt.chain=e.chain),typeof e.token=="string"&&e.token&&(xt.token=e.token))}function Iv(){return{...xt}}var Ve={ok:!1,error:null,data:null,at:0,fetching:!1};function Tv(){return Ve}function Ov(e=xt.side,t="ETH"){return e==="sell"?t.toUpperCase()+"/XMR":"XMR/"+t.toUpperCase()}function Bv(e){return String(e||"").split("/")[0].toUpperCase()}function Pv(e){return String(e||"").split("/")[1]?String(e).split("/")[1].toUpperCase():""}function Cv(){let e=Ve.ok&&Ve.data?Ve.data:null;return e?{offers:e.offers||[],refused:e.refused||[],seq:e.seq===void 0?null:e.seq,at:e.at===void 0?null:e.at}:{offers:[],refused:[],seq:null,at:null}}function Rv(e,{monero:t,evm:n}){let r=e.asset==="XMR",o=e.currency==="XMR";if(!r&&!o)return{ok:!1,stated:e.networkStated,why:"pair "+e.pair+" has no XMR on either side"};let i=r?e.assetNetwork:e.currencyNetwork,s=r?e.currencyNetwork:e.assetNetwork,a=r?"assetNetwork":"currencyNetwork",c=r?"currencyNetwork":"assetNetwork";return i&&i!==t?{ok:!1,stated:!0,why:e.pair+": "+a+" is "+i+", but this page pays XMR on "+t}:s&&s!==n?{ok:!1,stated:!0,why:e.pair+": "+c+" is "+s+", but this page settles on "+n}:{ok:!0,stated:e.networkStated,moneroNet:i||null,evmNet:s||null,why:null}}async function ku(){if(Ve.fetching)return Ve;Ve.fetching=!0;try{let e=await Promise.resolve().then(()=>(yw(),ww));await e.sdkBook({chain:xt.chain,direction:xt.side,token:xt.token,size:xt.size});let t=e.sdkBookSnapshot();Ve.ok=t.ok,Ve.error=t.error,Ve.data=t.data,Ve.at=t.at||Date.now()}catch(e){Ve.ok=!1,Ve.error=String(e&&e.message||e),Ve.data=null,Ve.at=Date.now()}finally{Ve.fetching=!1}return Ve}var bw=null;function Hv(e=null,t=Zt.pollMs){typeof e=="string"&&e&&(xt.chain=e),!bw&&(ku(),bw=setInterval(()=>ku(),t))}cs();vs();var Ks={};Be(Ks,{scalarFromMoneroHex:()=>Fv,spendKeysFromRevealedHalf:()=>Lv});function Lv({halves:e,ownSpendHalf:t,ownViewHalf:n,otherSpendPoint:r,otherViewHalf:o,revealedHalf:i}){if(!e)throw new Error("half maths is required");for(let[w,y]of Object.entries({ownSpendHalf:t,ownViewHalf:n,otherSpendPoint:r,otherViewHalf:o,revealedHalf:i}))if(y==null||y==="")throw new Error("not set: "+w);let s=BigInt(i)%e.SECP_ORDER,a=e.combineHalves(BigInt(t),s),c=e.publicHalves(a).ed,l=e.combinePublic(e.publicHalves(BigInt(t)).ed,r),u=w=>String(w).replace(/^0x/i,"").toLowerCase();if(u(c)!==u(l))throw new Error("revealed half does not match the address: (s_a + s_b)*G != the order spend key. The half is from another order or substituted - sweeping is not allowed");let d=e.combineHalves(BigInt(n),BigInt(o)),p=w=>BigInt(w).toString(16).padStart(64,"0"),m=w=>p(w).match(/../g).reverse().join("");return{privateSpendKey:m(a),privateViewKey:m(d)}}function Fv(e){let t=String(e).replace(/^0x/i,"");if(!/^[0-9a-f]{64}$/.test(t))throw new Error("key is not in Monero notation: expected 64 hex");return BigInt("0x"+t.match(/../g).reverse().join(""))}Qn();var gw=5e8;function Su(e,{height:t=null,nowSec:n=null}={}){let r=Number(e)||0;if(r<=0)return{code:"unlocked",locked:!1,untilHeight:null,untilTime:null};if(r>=5e8){let s=n==null?Math.floor(Date.now()/1e3):Number(n),a=Number.isFinite(s)&&s>=r;return{code:a?"unlocked":"locked_time",locked:!a,untilHeight:null,untilTime:r}}let o=t==null?null:Number(t),i=o!==null&&Number.isFinite(o)&&o>=r;return{code:i?"unlocked":"locked_height",locked:!i,untilHeight:r,untilTime:null}}function Ws(e){return e?e.untilTime!==null&&e.untilTime!==void 0?Number(e.untilTime):e.untilHeight!==null&&e.untilHeight!==void 0?Number(e.untilHeight):-1:-1}var si={};Be(si,{ED_ORDER:()=>St,PEDERSEN_H:()=>xy,UNLOCK_TIME_BLOCK_MAX:()=>gw,amountMaskCommitment:()=>ky,bytesToHex:()=>zr,decodeAmount:()=>Ny,decodeMask:()=>Gu,derivedOutputKey:()=>vy,fetchBlock:()=>Oy,fetchTransactions:()=>By,findOurOutputs:()=>Iy,hashToScalar:()=>Xr,hexToBytes:()=>lr,keccak:()=>qu,keyDerivation:()=>Yu,laterBoundary:()=>Ws,matchTransaction:()=>Py,scalarFromBytesLE:()=>ma,scalarFromHexLE:()=>Qu,scalarToBytesLE:()=>ha,scanRange:()=>K1,txPublicKeyFromExtra:()=>Ey,unlockStateOf:()=>Su,varint:()=>Zu,viewKeyFormForAddress:()=>M1,viewSecretCandidates:()=>Ju});var Vs=BigInt(4294967295),xw=BigInt(32);function Uv(e,t=!1){return t?{h:Number(e&Vs),l:Number(e>>xw&Vs)}:{h:Number(e>>xw&Vs)|0,l:Number(e&Vs)|0}}function $s(e,t=!1){let n=e.length,r=new Uint32Array(n),o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=Uv(e[i],t);[r[i],o[i]]=[s,a]}return[r,o]}var Mv=e=>e/2**32|0,jv=e=>e>>>0;function kw(e,t,n,r){let o=Mv(n),i=jv(n);e.setUint32(t,r?i:o,r),e.setUint32(t+4,r?o:i,r)}var vu=(e,t,n)=>e>>>n,Eu=(e,t,n)=>e<<32-n|t>>>n,or=(e,t,n)=>e>>>n|t<<32-n,ir=(e,t,n)=>e<<32-n|t>>>n,Xo=(e,t,n)=>e<<64-n|t>>>n-32,Yo=(e,t,n)=>e>>>n-32|t<<64-n;function zt(e,t,n,r){let o=(t>>>0)+(r>>>0);return{h:e+n+(o/2**32|0)|0,l:o|0}}var Sw=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),vw=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Ew=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Aw=(e,t,n,r,o)=>t+n+r+o+(e/2**32|0)|0,_w=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Nw=(e,t,n,r,o,i)=>t+n+r+o+i+(e/2**32|0)|0;function zs(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Xs=e=>e?`"${e}" `:"";function Ce(e,t=""){if(typeof e!="number")throw new TypeError(Xs(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Xs(t)+"expected integer >= 0, got "+e);return e}function Ow(e,t=""){if(typeof e!="boolean")throw new TypeError(Xs(t)+"expected boolean, got type="+typeof e);return e}function Me(e,t,n=""){if(zs(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Ce(t,"length");let r=zs(e),o=t!==void 0?` of length ${t}`:"",i=r?`length=${e.length}`:`type=${typeof e}`,s=Xs(n)+"expected Uint8Array"+o+", got "+i;throw r?new RangeError(s):new TypeError(s)}function Lr(e){if(typeof e!="function"||typeof e.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Ce(e.outputLen),Ce(e.blockLen),e.outputLen<1||e.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var Wv=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},Iw=(e,t)=>{Wv(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function sn(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function Fr(e,t){Me(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function Au(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function tt(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Dr(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Bt(e,t){return e<<32-t|e>>>t}var Vv=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function $v(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function zv(e){for(let t=0;t<e.length;t++)e[t]=$v(e[t]);return e}var _u=Vv?e=>e:zv,Bw=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Xv=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ys(e){if(Me(e),Bw)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Xv[e[n]];return t}function Tw(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Gs(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(Bw)try{return Uint8Array.fromHex(e)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let t=e.length,n=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);let r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){let s=Tw(e.charCodeAt(i)),a=Tw(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}r[o]=s*16+a}return r}function Yv(e){if(typeof e!="string")throw new TypeError("string expected");let t=new TextEncoder().encode(e);try{return new Uint8Array(t)}finally{tt(t)}}function Nu(e,t=""){return typeof e=="string"?Yv(e):Me(e,void 0,t)}function Iu(...e){let t=0;for(let r=0;r<e.length;r++){let o=e[r];Me(o),t+=o.length}let n=new Uint8Array(t);for(let r=0,o=0;r<e.length;r++){let i=e[r];n.set(i,o),o+=i.length}return n}function qs(e,t,n="opts"){return Iw(e,"defaults"),t!==void 0&&Iw(t,n),Object.assign(Object.create(null),e,t)}function Go(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=qs({},t,"info");let n=(o,i)=>e(i).update(o).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>e(o),Object.assign(n,t),Object.freeze(n)}function Tu(e=32){Ce(e,"bytesLength");let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(e>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var qo=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Pw(e,t,n){return e&t^~e&n}function Cw(e,t,n){return e&t^e&n^t&n}var Qo=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,n,r,o){this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Dr(this.buffer)}update(t){sn(this),Me(t);let{view:n,buffer:r,blockLen:o}=this,i=t.length,s=!1;for(let a=0;a<i;){let c=Math.min(o-this.pos,i-a);if(c===o){let l=Dr(t);for(;o<=i-a;a+=o)this.process(l,a);s=!0;continue}r.set(a===0&&c===i?t:t.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(n,0),this.pos=0,s=!0)}return this.length+=t.length,s&&this.roundClean(),this}digestInto(t){sn(this),Fr(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,n.fill(0,s),this.padOffset>o-s&&(this.process(r,0),n.fill(0)),kw(r,o-8,this.length*8,i),this.process(r,0),this.roundClean();let a=t===n?r:Dr(t),c=this.outputLen,l=c/4,u=this.get();if(c%4||l>u.length)throw new Error("invalid outputLen");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],i)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneIntoMeta(t){let{buffer:n,length:r,finished:o,destroyed:i,pos:s}=this;return t.destroyed=i,t.finished=o,t.length=r,t.pos=s,s&&t.buffer.set(n),t}clone(){return this._cloneInto()}},Rw=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Hw=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Gv=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),In=new Uint32Array(64),Ou=class extends Qo{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(t,n){super(64,t,8,!1),this.A=n[0]|0,this.B=n[1]|0,this.C=n[2]|0,this.D=n[3]|0,this.E=n[4]|0,this.F=n[5]|0,this.G=n[6]|0,this.H=n[7]|0}get(){let{A:t,B:n,C:r,D:o,E:i,F:s,G:a,H:c}=this;return[t,n,r,o,i,s,a,c]}set(t,n,r,o,i,s,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let d=0;d<16;d++,n+=4)In[d]=t.getUint32(n,!1);for(let d=16;d<64;d++){let p=In[d-15],m=In[d-2],w=Bt(p,7)^Bt(p,18)^p>>>3,y=Bt(m,17)^Bt(m,19)^m>>>10;In[d]=y+In[d-7]+w+In[d-16]|0}let{A:r,B:o,C:i,D:s,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let p=Bt(a,6)^Bt(a,11)^Bt(a,25),m=u+p+Pw(a,c,l)+Gv[d]+In[d]|0,y=(Bt(r,2)^Bt(r,13)^Bt(r,22))+Cw(r,o,i)|0;u=l,l=c,c=a,a=s+m|0,s=i,i=o,o=r,r=m+y|0}r=r+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,o,i,s,a,c,l,u)}roundClean(){tt(In)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),tt(this.buffer)}},Bu=class extends Ou{constructor(){super(32,Rw)}};var Lw=$s(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),qv=Lw[0],Qv=Lw[1],Tn=new Uint32Array(80),On=new Uint32Array(80),Pu=class extends Qo{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(t,n){super(128,t,16,!1),this.Ah=n[0]|0,this.Al=n[1]|0,this.Bh=n[2]|0,this.Bl=n[3]|0,this.Ch=n[4]|0,this.Cl=n[5]|0,this.Dh=n[6]|0,this.Dl=n[7]|0,this.Eh=n[8]|0,this.El=n[9]|0,this.Fh=n[10]|0,this.Fl=n[11]|0,this.Gh=n[12]|0,this.Gl=n[13]|0,this.Hh=n[14]|0,this.Hl=n[15]|0}get(){let{Ah:t,Al:n,Bh:r,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:p,Gh:m,Gl:w,Hh:y,Hl:b}=this;return[t,n,r,o,i,s,a,c,l,u,d,p,m,w,y,b]}set(t,n,r,o,i,s,a,c,l,u,d,p,m,w,y,b){this.Ah=t|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=p|0,this.Gh=m|0,this.Gl=w|0,this.Hh=y|0,this.Hl=b|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let E=0;E<16;E++,n+=4)Tn[E]=t.getUint32(n),On[E]=t.getUint32(n+=4);for(let E=16;E<80;E++){let U=Tn[E-15]|0,S=On[E-15]|0,B=or(U,S,1)^or(U,S,8)^vu(U,S,7),R=ir(U,S,1)^ir(U,S,8)^Eu(U,S,7),A=Tn[E-2]|0,N=On[E-2]|0,f=or(A,N,19)^Xo(A,N,61)^vu(A,N,6),k=ir(A,N,19)^Yo(A,N,61)^Eu(A,N,6),_=Ew(R,k,On[E-7],On[E-16]),K=Aw(_,B,f,Tn[E-7],Tn[E-16]);Tn[E]=K|0,On[E]=_|0}let{Ah:r,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:p,Fh:m,Fl:w,Gh:y,Gl:b,Hh:x,Hl:I}=this;for(let E=0;E<80;E++){let U=or(d,p,14)^or(d,p,18)^Xo(d,p,41),S=ir(d,p,14)^ir(d,p,18)^Yo(d,p,41),B=d&m^~d&y,R=p&w^~p&b,A=_w(I,S,R,Qv[E],On[E]),N=Nw(A,x,U,B,qv[E],Tn[E]),f=A|0,k=or(r,o,28)^Xo(r,o,34)^Xo(r,o,39),_=ir(r,o,28)^Yo(r,o,34)^Yo(r,o,39),K=r&i^r&a^i&a,H=o&s^o&c^s&c;x=y|0,I=b|0,y=m|0,b=w|0,m=d|0,w=p|0,{h:d,l:p}=zt(l|0,u|0,N|0,f|0),l=a|0,u=c|0,a=i|0,c=s|0,i=r|0,s=o|0;let P=Sw(f,_,H);r=vw(P,N,k,K),o=P|0}({h:r,l:o}=zt(this.Ah|0,this.Al|0,r|0,o|0)),{h:i,l:s}=zt(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=zt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=zt(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:p}=zt(this.Eh|0,this.El|0,d|0,p|0),{h:m,l:w}=zt(this.Fh|0,this.Fl|0,m|0,w|0),{h:y,l:b}=zt(this.Gh|0,this.Gl|0,y|0,b|0),{h:x,l:I}=zt(this.Hh|0,this.Hl|0,x|0,I|0),this.set(r,o,i,s,a,c,l,u,d,p,m,w,y,b,x,I)}roundClean(){tt(Tn,On)}destroy(){this.destroyed=!0,tt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Cu=class extends Pu{constructor(){super(64,Hw)}};var Qs=Go(()=>new Bu,qo(1));var Zo=Go(()=>new Cu,qo(3));function Js(e,t,n=()=>{}){if(!Array.isArray(e))throw new TypeError(`"${t}" expected array, got type=${typeof e}`);for(let r=0;r<e.length;r++)n(e[r],`${t}[${r}]`);return e}var ue=(e,t,n)=>Me(e,t,n),Ru=Ce;function Dw(e,t=""){if(typeof e!="string"){let n=t&&`"${t}" `;throw new TypeError(n+"expected string, got type="+typeof e)}return e}function Bn(e,t="object"){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(t==="object"?"expected valid options object":`"${t}" expected object, got type=${typeof e}`);return e}function sr(e,t){if(typeof e!="function")throw new TypeError(`"${t}" is invalid: expected function, got ${typeof e}`);return e}var Jo=Ys,kt=(...e)=>Iu(...e),Ur=e=>Gs(e),Cn=zs,ar=e=>Tu(e),Zs=BigInt(0),Fw=BigInt(1),Zv=e=>e?`"${e}" `:"";function it(e,t=""){if(typeof e!="boolean")throw new TypeError(Zv(t)+"expected boolean, got type="+typeof e);return e}function ea(e){if(typeof e=="bigint"){if(!Pn(e))throw new RangeError("positive bigint expected, got "+e)}else Ru(e);return e}function an(e,t=""){if(typeof e!="number"){let n=t&&`"${t}" `;throw new TypeError(n+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let n=t&&`"${t}" `;throw new RangeError(n+"expected safe integer, got "+e)}}function ei(e){let t=ea(e).toString(16);return t.length&1?"0"+t:t}function Uw(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?Zs:BigInt("0x"+e)}function Xt(e){return Uw(Ys(e))}function cr(e){return Uw(Ys(ti(Me(e)).reverse()))}function ta(e,t){if(Ce(t),t===0)throw new Error("zero output length is invalid");e=ea(e);let n=t*2,r=e.toString(16);if(r.length>n)throw new RangeError("number is too large");return Gs(r.padStart(n,"0"))}function Hu(e,t){return ta(e,t).reverse()}function ti(e){return Uint8Array.from(ue(e))}function Pn(e){return typeof e=="bigint"&&Zs<=e}function Lu(e,t,n){return Pn(e)&&Pn(t)&&Pn(n)&&t<=e&&e<n}function Mr(e,t,n,r){if(!Lu(t,n,r))throw new RangeError("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function jr(e){if(e<Zs)throw new Error("expected non-negative bigint, got "+e);return e===Zs?0:e.toString(2).length}var ni=e=>(an(e,"n"),(Fw<<BigInt(e))-Fw);function Mw(e,t,n){if(Ce(e,"hashLen"),Ce(t,"qByteLen"),typeof n!="function")throw new TypeError("hmacFn must be a function");let r=b=>new Uint8Array(b),o=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1e3,c=r(e),l=r(e),u=0,d=()=>{c.fill(1),l.fill(0),u=0},p=(...b)=>n(l,kt(c,...b)),m=(b=o)=>{l=p(i,b),c=p(),b.length!==0&&(l=p(s,b),c=p())},w=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let b=0,x=[];for(;b<t;){c=p();let I=c.slice();x.push(I),b+=c.length}return kt(...x)};return(b,x)=>{d(),m(b);let I;for(;(I=x(w()))===void 0;)m();return d(),I}}function st(e,t={},n={},r="object"){Bn(e,r),Bn(t,"fields"),Bn(n,"optFields");function o(s,a,c){let l=r==="object"?`param "${String(s)}"`:`"${r}.${String(s)}"`,u=e[s];if(!Object.hasOwn(e,s)&&(c?u!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(c&&u===void 0)return;let d=typeof u;if(d!==a||u===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${d}`)}let i=(s,a)=>Object.entries(s).forEach(([c,l])=>o(c,l,a));i(t,!1),i(n,!0)}var De=BigInt(0),de=BigInt(1),Rn=BigInt(2),Ww=BigInt(3),Fu=BigInt(4),Vw=BigInt(5),Jv=BigInt(7),$w=BigInt(8),e1=BigInt(9),t1=BigInt(15),zw=BigInt(16),n1=BigInt("0x10000000000000000");function _e(e,t){if(t<=De)throw new Error("mod: expected positive modulus, got "+t);let n=e%t;return n>=De?n:t+n}function Xw(e,t,n){if(n<=de)throw new Error("pow: expected modulus > 1, got "+n);if(typeof t!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof t);if(t<De)throw new Error("invalid exponent, negatives unsupported");if(t===De)return de;if(t===de)return e;let r=e%n;if(r<De&&(r+=n),t<n1){let a=de;for(;t>De;)t&de&&(a=a*r%n),r=r*r%n,t>>=de;return a}let o=[];for(;t>De;)o.push(Number(t&t1)),t>>=Fu;let i=new Array(16);i[0]=de,i[1]=r;for(let a=2;a<16;a++)i[a]=i[a-1]*r%n;let s=i[o[o.length-1]];for(let a=o.length-2;a>=0;a--){s=s*s%n,s=s*s%n,s=s*s%n,s=s*s%n;let c=o[a];c!==0&&(s=s*i[c]%n)}return s}function Ee(e,t,n){if(n<=de)throw new Error("pow2: expected modulus > 1, got "+n);if(t<De)throw new Error("pow2: expected non-negative exponent, got "+t);let r=e;for(;t-- >De;)r*=r,r%=n;return r}function jw(e,t){if(e===De)throw new Error("invert: expected non-zero number");if(t<=de)throw new Error("invert: expected modulus > 1, got "+t);let n=_e(e,t),r=t,o=De,i=de;for(;n!==De;){let a=r/n,c=r-n*a,l=o-i*a;r=n,n=c,o=i,i=l}if(r!==de)throw new Error("invert: does not exist");return _e(o,t)}function Yw(e,t){if(t<=de)throw new Error("invertCt: expected prime modulus > 1, got "+t);let n=_e(e,t);if(n===De)throw new Error("invertCt: expected non-zero number");let r=Xw(n,t-Rn,t);if(_e(n*r,t)!==de)throw new Error("invertCt: does not exist");return r}function Du(e,t,n){let r=e;if(!r.eql(r.sqr(t),n))throw new Error("Cannot find square root")}function Uu(e,t){if((e&de)===De)throw new Error(t+": expected odd modulus, got "+e)}function Gw(e,t){let n=e,r=(n.ORDER+de)/Fu,o=n.pow(t,r);return Du(n,o,t),o}function r1(e,t){let n=e,r=(n.ORDER-Vw)/$w,o=n.mul(t,Rn),i=n.pow(o,r),s=n.mul(t,i),a=n.mul(n.mul(s,Rn),i),c=n.mul(s,n.sub(a,n.ONE));return Du(n,c,t),c}function o1(e){let t=Wr(e),n=qw(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+Jv)/zw;return((a,c)=>{let l=a,u=l.pow(c,s),d=l.mul(u,r),p=l.mul(u,o),m=l.mul(u,i),w=l.eql(l.sqr(d),c),y=l.eql(l.sqr(p),c);u=l.cmov(u,d,w),d=l.cmov(m,p,y);let b=l.eql(l.sqr(d),c),x=l.cmov(u,d,b);return Du(l,x,c),x})}function qw(e){if(e<Ww)throw new Error("sqrt is not defined for small field");Uu(e,"tonelliShanks");let t=e-de,n=0;for(;t%Rn===De;)t/=Rn,n++;let r=Rn,o=Wr(e);for(;ri(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Gw;let i=o.pow(r,t),s=(t+de)/Rn;return function(c,l){let u=c;if(u.is0(l))return l;if(ri(u,l)!==1)throw new Error("Cannot find square root");let d=n,p=u.mul(u.ONE,i),m=u.pow(l,t),w=u.pow(l,s);for(;!u.eql(m,u.ONE);){if(u.is0(m))throw new Error("Cannot find square root: probably non-prime P");let y=1,b=u.sqr(m);for(;!u.eql(b,u.ONE);)if(y++,b=u.sqr(b),y===d)throw new Error("Cannot find square root");let x=de<<BigInt(d-y-1),I=u.pow(p,x);d=y,p=u.sqr(I),m=u.mul(m,p),w=u.mul(w,I)}return w}}function i1(e){return Uu(e,"Fp.sqrt"),e%Fu===Ww?Gw:e%$w===Vw?r1:e%zw===e1?o1(e):qw(e)}var Qw=(e,t)=>(_e(e,t)&de)===de,s1=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Kr(e){if(Bn(e,"field"),typeof e.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof e.ORDER);an(e.BYTES,"BYTES"),an(e.BITS,"BITS");for(let t of s1)sr(e[t],"field."+t);if(e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=de)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function ra(e,t,n=!1){Kr(e),Js(t,"nums"),it(n,"passZero");let r=e,o=new Array(t.length).fill(n?r.ZERO:void 0),i=t.reduce((a,c,l)=>r.is0(c)?a:(o[l]=a,r.mul(a,c)),r.ONE),s=r.inv(i);return t.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),s),o}function ri(e,t){Kr(e);let n=e;Uu(n.ORDER,"FpLegendre");let r=(n.ORDER-de)/Rn,o=n.pow(t,r),i=n.eql(o,n.ONE),s=n.eql(o,n.ZERO),a=n.eql(o,n.neg(n.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function a1(e,t){if(t!==void 0&&Ru(t),e<=De)throw new Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw new Error("invalid n length: expected positive bit length, got "+t);let n=jr(e);if(t!==void 0&&t<n)throw new Error(`invalid n length: expected nBitLength (${t}) >= bitLen(n) (${n})`);let r=t!==void 0?t:n,o=Math.ceil(r/8);return{nBitLength:r,nByteLength:o}}var Kw=new WeakMap,na=class{ORDER;BITS;BYTES;isLE;ZERO=De;ONE=de;_lengths;_mod;constructor(t,n={}){if(t<=de)throw new Error("invalid field: expected ORDER > 1, got "+t);let r;this.isLE=!1,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:n.sqrt,enumerable:!0}),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=Object.freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=a1(t,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=i,Object.freeze(this)}create(t){return _e(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof t);return De<=t&&t<this.ORDER}is0(t){return t===De}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&de)===de}neg(t){return _e(-t,this.ORDER)}eql(t,n){return t===n}sqr(t){return _e(t*t,this.ORDER)}add(t,n){return _e(t+n,this.ORDER)}sub(t,n){return _e(t-n,this.ORDER)}mul(t,n){return _e(t*n,this.ORDER)}pow(t,n){return Xw(t,n,this.ORDER)}div(t,n){return _e(t*jw(n,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,n){return t+n}subN(t,n){return t-n}mulN(t,n){return t*n}inv(t){return jw(t,this.ORDER)}sqrt(t){let n=Kw.get(this);return n||Kw.set(this,n=i1(this.ORDER)),n(this,t)}toBytes(t){return this.isLE?Hu(t,this.BYTES):ta(t,this.BYTES)}fromBytes(t,n=!1){ue(t);let{_lengths:r,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(r){if(t.length<1||!r.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+t.length);let l=new Uint8Array(o);l.set(t,i?0:l.length-t.length),t=l}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=i?cr(t):Xt(t);if(a&&(c=_e(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return ra(this,t,!0)}cmov(t,n,r){return it(r,"condition"),r?n:t}};function Wr(e,t={}){return Object.freeze(na.prototype),new na(e,t)}function Zw(e){if(typeof e!="bigint")throw new Error("field order must be bigint");if(e<=de)throw new Error("field order must be greater than 1");let t=jr(e-de);return Math.ceil(t/8)}function oa(e){let t=Zw(e);return t+Math.ceil(t/2)}function ia(e,t,n=!1){ue(e);let r=e.length,o=Zw(t),i=Math.max(oa(t),16);if(r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let s=n?cr(e):Xt(e),a=_e(s,t-de)+de;return n?Hu(a,o):ta(a,o)}var Ku=BigInt(0),oi=BigInt(1),c1=BigInt(4),Mu=16,Jw=128,l1=5,ey=2**31;function Hn(e){let t=e;if(typeof t!="function")throw new TypeError('"Point" expected constructor, got type='+typeof e);sr(t.fromAffine,"Point.fromAffine"),sr(t.fromBytes,"Point.fromBytes"),sr(t.fromHex,"Point.fromHex"),Bn(t.BASE,"Point.BASE"),Bn(t.ZERO,"Point.ZERO"),Kr(t.Fp),Kr(t.Fn)}function sa(e,t){Hn(e),ny(t,e);let n=ra(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function u1(e,t,n=1){if(!Number.isSafeInteger(e)||e<n||e>t)throw new Error("invalid window size, expected ["+n+".."+t+"], got W="+e)}function d1(e,t){let n=e*(4*t+128);if(n>ey)throw new Error("invalid window size: table would need ~"+Math.ceil(n/2**20)+" MiB, max "+ey/2**20+" MiB")}function Wu(e,t){if(e!==void 0){sr(e,"randomBytes");try{let n=e(t);if(!Cn(n)||n.length!==t)return}catch{return}return e}}function ny(e,t){Js(e,"points"),e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function f1(e,t,n){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,o)=>{if(!(n===void 0?t.isValid(r):Pn(r)&&r<n))throw new Error("invalid scalar at index "+o)})}var ry=new WeakMap;function ju(e){return ry.get(e)||1}function p1(e,t){let n=e.double(),r=[e];for(let o=1;o<t;o++)r.push(r[o-1].add(n));return r}function h1(e,t){let n=2**t,r=n/2,o=BigInt(n-1),i=[];for(;e>Ku;){let s=0;e&oi&&(s=Number(e&o),s>=r&&(s-=n),e-=BigInt(s)),i.push(s),e>>=oi}return i}function m1(e,t,n){let r=2**t,o=r/2,i=BigInt(r-1),s=BigInt(t),a=[];for(let c=0;c<n;c++){let l=Number(e&i);e>>=s,l>o&&(l-=r,e+=oi),a.push(l)}if(e!==Ku)throw new Error("invalid wnaf");return a}function w1(e,t,n){let r=0;for(let i of n)r=Math.max(r,i.length);let o=e;for(let i=r-1;i>=0;i--){i!==r-1&&(o=o.double());for(let s=0;s<n.length;s++){let a=n[s][i];if(a){let c=t[s][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}var Vr=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(t,n){Hn(t),this.randomBytes=Wu(n,Mu),this.Point=t,this.BASE=t.BASE,this.ZERO=t.ZERO,this.bits=t.Fn.BITS}buildWnafTable(t,n,r){let o=Math.ceil(r/n)+1,i=2**(n-1),s=[],a=t;for(let c=0;c<o;c++){let l=a;for(let u=0;u<i;u++)s.push(l),l=l.add(a);a=s[s.length-1].double()}return{W:n,bits:r,windows:o,comp:s}}wnafCachedCT(t,n){let{W:r,windows:o,comp:i}=t,s=2**(r-1),a=m1(n,r,o),c=this.ZERO,l=this.BASE;for(let u=0;u<o;u++){let d=a[u],p=u*s,m=Math.abs(d)-1,w=i[p];for(let b=1;b<s;b++)w=b===m?i[p+b]:w;let y=w.negate();d===0?l=l.add(i[p]):c=c.add(d<0?y:w)}return{p:c,f:l}}getWnafPrecomputes(t,n,r,o){let i=this.wnafPrecomputes.get(n),s=i?.find(a=>a.W===t&&a.bits===r);return s||(s=this.buildWnafTable(n,t,r),typeof o=="function"&&(s={...s,comp:o(s.comp)}),i||(i=[],this.wnafPrecomputes.set(n,i)),i.push(s)),s}assertPoint(t){if(!(t instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof t)}validateMulInput(t,n){if(this.assertPoint(t),!Lu(n,oi,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(t,n,r,o){let i=ju(t);return i===1?this.fixedWindowCT(t,n,r):this.wnafCachedCT(this.getWnafPrecomputes(i,t,r,o),n)}mulCT(t,n,r){return this.validateMulInput(t,n),this.runCT(t,n,this.bits,r)}mulCTBlinded(t,n,r){if(this.validateMulInput(t,n),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+Jw,i=this.randomBytes(Mu);if(!Cn(i)||i.length!==Mu)throw new Error("randomBytes returned invalid byte array");i[0]=i[0]&63|128;let s=n+Xt(i)*this.Point.Fn.ORDER;return this.runCT(t,s,o,r)}fixedWindowCT(t,n,r){let o=l1,i=1<<o,s=ni(o),a=new Array(i);a[0]=this.ZERO;for(let u=1;u<i;u++)a[u]=a[u-1].add(t);let c=Math.ceil(r/o),l=this.ZERO;for(let u=c-1;u>=0;u--){if(u!==c-1)for(let m=0;m<o;m++)l=l.double();let d=Number(n>>BigInt(u*o)&s),p=a[0];for(let m=1;m<i;m++)p=m===d?a[m]:p;l=l.add(p)}return{p:l,f:l}}shouldBlind(t,n){return this.randomBytes===void 0?!1:n===oi?!0:t!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(t,n,r,o){return this.shouldBlind(t,r)?this.mulCTBlinded(t,n,o):this.mulCT(t,n,o)}mulUnsafe(t,n,r){if(this.assertPoint(t),!Pn(n))throw new Error("invalid scalar");let o=ju(t);if(o===1||n>=this.Point.Fn.ORDER)return aa(this.Point,[t],[n],!0);let i=this.getWnafPrecomputes(o,t,this.bits,r);return this.wnafCachedCT(i,n).p}setWindowSize(t,n){this.assertPoint(t),u1(n,this.bits);let r=Math.ceil((this.bits+Jw)/n)+1;d1(r*2**(n-1),this.Point.Fp.BYTES),ry.set(t,n),this.wnafPrecomputes.delete(t)}hasWindowSize(t){return ju(t)!==1}};function aa(e,t,n,r=!1){if(Hn(e),ny(t,e),it(r,"allowOversized"),f1(n,e.Fn,r?e.Fn.ORDER**c1:void 0),t.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=t.map(s=>p1(s,4)),i=n.map(s=>h1(s,4));return w1(e.ZERO,o,i)}function ty(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Kr(t),t}else return Wr(e,{isLE:n})}function ca(e,t,n={},r){if(e!=="weierstrass"&&e!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(r===void 0&&(r=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);st(n);for(let c of["p","n","h"]){let l=t[c];if(!(Pn(l)&&l!==Ku))throw new Error(`CURVE.${c} must be positive bigint`)}let o=ty(t.p,n.Fp,r),i=ty(t.n,n.Fn,r),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}function la(e,t){return function(r){let o=e(r);return{secretKey:o,publicKey:t(o)}}}var ua=BigInt(0),da=BigInt(1),fa=BigInt(2),y1=BigInt(4),oy=BigInt(8);function b1(e,t,n,r){let o=e.sqr(n),i=e.sqr(r),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}function iy(e,t={}){st(t,{},{},"extraOpts");let n=t,r=ca("edwards",e,n,n.FpFnLE),{Fp:o,Fn:i}=r,s=r.CURVE,{h:a}=s;if(ri(o,s.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(ri(o,s.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");st(n,{},{uvRatio:"function",randomBytes:"function"});let c=n.randomBytes===void 0?ar:n.randomBytes,l=fa<<BigInt(o.BYTES*8)-da;function u(I){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(I)}let d=n.uvRatio===void 0?(I,E)=>{try{return{isValid:!0,value:o.sqrt(o.div(I,E))}}catch{return{isValid:!1,value:ua}}}:n.uvRatio;if(!b1(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");let p=o.eql(s.a,o.neg(o.ONE))?I=>o.neg(I):o.eql(s.a,o.ONE)?I=>I:I=>o.mul(s.a,I);function m(I,E,U=!1){let S=U?da:ua;return Mr("coordinate "+I,E,S,l),E}function w(I){if(!(I instanceof y))throw new Error("EdwardsPoint expected")}class y{static BASE=new y(s.Gx,s.Gy,o.ONE,o.mul(s.Gx,s.Gy));static ZERO=new y(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=i;X;Y;Z;T;constructor(E,U,S,B){this.X=m("x",E),this.Y=m("y",U),this.Z=m("z",S,!0),this.T=m("t",B),Object.freeze(this)}static CURVE(){return s}static fromAffine(E){if(E instanceof y)throw new Error("extended point not allowed");let{x:U,y:S}=E||{};return m("x",U),m("y",S),new y(U,S,o.ONE,o.mul(U,S))}static fromBytes(E,U=!1){let S=o.BYTES,{a:B,d:R}=s;E=ti(ue(E,S,"point")),it(U,"zip215");let A=ti(E),N=E[S-1];A[S-1]=N&-129;let f=cr(A),k=U?l:o.ORDER;Mr("point.y",f,ua,k);let _=o.sqr(f),K=o.sub(_,o.ONE),H=o.sub(o.mulN(R,_),B),{isValid:P,value:j}=d(K,H);if(!P)throw new Error("bad point: invalid y coordinate");let L=u(j),z=(N&128)!==0;if(!U&&o.is0(j)&&z)throw new Error("bad point: x=0 and x_0=1");return z!==L&&(j=o.neg(j)),y.fromAffine({x:j,y:f})}static fromHex(E,U=!1){return y.fromBytes(Ur(E),U)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(E=6,U=!0){return x.setWindowSize(this,E),U||this.multiply(fa),this}assertValidity(){let E=this,{a:U,d:S}=s;if(E.is0())throw new Error("bad point: ZERO");let{X:B,Y:R,Z:A,T:N}=E,f=o.sqr(B),k=o.sqr(R),_=o.sqr(A),K=o.sqr(_),H=o.mul(f,U),P=o.mul(o.add(H,k),_),j=o.add(K,o.mul(S,o.mul(f,k)));if(!o.eql(P,j))throw new Error("bad point: equation left != right (1)");let L=o.mul(B,R),z=o.mul(A,N);if(!o.eql(L,z))throw new Error("bad point: equation left != right (2)")}equals(E){w(E);let{X:U,Y:S,Z:B}=this,{X:R,Y:A,Z:N}=E,f=o.mul(U,N),k=o.mul(R,B),_=o.mul(S,N),K=o.mul(A,B);return o.eql(f,k)&&o.eql(_,K)}is0(){return this.equals(y.ZERO)}negate(){return new y(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:E,Y:U,Z:S}=this,B=o.sqr(E),R=o.sqr(U),A=o.mul(o.sqr(S),fa),N=p(B),f=o.addN(E,U),k=o.sub(o.subN(o.sqr(f),B),R),_=o.addN(N,R),K=o.subN(_,A),H=o.subN(N,R),P=o.mul(k,K),j=o.mul(_,H),L=o.mul(k,H),z=o.mul(K,_);return new y(P,j,z,L)}add(E){w(E);let{d:U}=s,{X:S,Y:B,Z:R,T:A}=this,{X:N,Y:f,Z:k,T:_}=E,K=o.mul(S,N),H=o.mul(B,f),P=o.mul(o.mulN(A,U),_),j=o.mul(R,k),L=o.sub(o.subN(o.mulN(o.addN(S,B),o.addN(N,f)),K),H),z=o.subN(j,P),W=o.addN(j,P),$=o.sub(H,p(K)),O=o.mul(L,z),g=o.mul(W,$),T=o.mul(L,$),v=o.mul(z,W);return new y(O,g,v,T)}subtract(E){return w(E),this.add(E.negate())}multiply(E){if(!i.isValidNot0(E))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:U,f:S}=x.mulSecret(this,E,a,b);return b([U,S])[0]}multiplyUnsafe(E){if(!i.isValid(E))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return E===ua?y.ZERO:this.is0()||E===da?this:x.mulUnsafe(this,E,b)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return x.mulUnsafe(this,s.n).is0()}toAffine(E){let U=this,S=E;if(S!=null&&typeof S!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof S);let{X:B,Y:R,Z:A}=U,N=U.is0();S==null&&(S=N?o.create(oy):o.inv(A));let f=o.mul(B,S),k=o.mul(R,S),_=o.mul(A,S);if(N)return{x:o.ZERO,y:o.ONE};if(!o.eql(_,o.ONE))throw new Error("invZ was invalid");return{x:f,y:k}}clearCofactor(){return a===da?this:a===fa?this.double():a===y1?this.double().double():a===oy?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:E,y:U}=this.toAffine(),S=o.toBytes(U);return S[S.length-1]|=u(E)?128:0,S}toHex(){return Jo(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let b=I=>sa(y,I),x=new Vr(y,c);return x.bits>=6&&y.BASE.precompute(6),Object.freeze(y.prototype),Object.freeze(y),y}function sy(e,t,n={}){if(Hn(e),typeof t!="function")throw new Error('"hash" function param is required');let r=t,o=n;st(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=e,l=r.outputLen,u=2*a.BYTES;if(l!==void 0&&(an(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let d=o.randomBytes===void 0?ar:o.randomBytes,p=o.toMontgomery,m=o.toMontgomerySecret,w=o.adjustScalarBytes===void 0?H=>H:o.adjustScalarBytes,y=o.domain===void 0?(H,P,j)=>{if(it(j,"phflag"),P.length||j)throw new Error("Contexts/pre-hash are not supported");return H}:o.domain;function b(H){return c.create(cr(H))}function x(H){let P=N.secretKey;ue(H,N.secretKey,"secretKey");let j=ue(r(H),2*P,"hashedSecretKey"),L=w(j.slice(0,P)),z=j.slice(P,2*P),W=b(L);return{head:L,prefix:z,scalar:W}}function I(H){let{head:P,prefix:j,scalar:L}=x(H),z=s.multiply(L),W=z.toBytes();return{head:P,prefix:j,scalar:L,point:z,pointBytes:W}}function E(H){return I(H).pointBytes}function U(H=Uint8Array.of(),...P){let j=kt(...P);return b(r(y(j,ue(H,void 0,"context"),!!i)))}function S(H,P,j={}){st(j,{},{},"options"),H=ti(ue(H,void 0,"message")),i&&(H=i(H));let{prefix:L,scalar:z,pointBytes:W}=I(P),$=U(j.context,L,H),O=s.multiply($).toBytes(),g=U(j.context,O,W,H),T=c.create($+g*z);if(!c.isValid(T))throw new Error("sign failed: invalid s");let v=kt(O,c.toBytes(T));return ue(v,N.signature,"result")}let B={zip215:o.zip215};function R(H,P,j,L=B){st(L);let{context:z}=L,W=L.zip215===void 0?!!B.zip215:L.zip215,$=N.signature;H=ue(H,$,"signature"),P=ue(P,void 0,"message"),j=ue(j,N.publicKey,"publicKey"),W!==void 0&&it(W,"zip215"),i&&(P=i(P));let O=$/2,g=H.subarray(0,O),T=cr(H.subarray(O,$)),v,V,D;try{v=e.fromBytes(j,W),V=e.fromBytes(g,W),D=s.multiplyUnsafe(T)}catch{return!1}if(!W&&v.isSmallOrder())return!1;let F=U(z,g,j,P);return V.add(v.multiplyUnsafe(F)).subtract(D).clearCofactor().is0()}let A=a.BYTES,N={secretKey:A,publicKey:A,signature:2*A,seed:A};function f(H){return H=H===void 0?d(N.seed):H,ue(H,N.seed,"seed")}function k(H){return Cn(H)&&H.length===N.secretKey}function _(H,P){try{return!!e.fromBytes(H,P===void 0?B.zip215:P)}catch{return!1}}let K={getExtendedPublicKey:I,randomSecretKey:f,isValidSecretKey:k,isValidPublicKey:_,toMontgomery(H){if(p===void 0)throw new Error("Montgomery conversion is not supported for this curve");return p(e.fromBytes(H))},toMontgomerySecret(H){if(m===void 0)throw new Error("Montgomery conversion is not supported for this curve");return m(H)}};return Object.freeze(N),Object.freeze(K),Object.freeze({keygen:la(f,E),getPublicKey:E,sign:S,verify:R,utils:K,Point:e,lengths:N})}var Vu=BigInt(1),ay=BigInt(2);var g1=BigInt(5),x1=BigInt(8),$u=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),k1={p:$u,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:x1,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function S1(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=$u,a=e*e%i*e%i,c=Ee(a,ay,i)*a%i,l=Ee(c,Vu,i)*e%i,u=Ee(l,g1,i)*l%i,d=Ee(u,t,i)*u%i,p=Ee(d,n,i)*d%i,m=Ee(p,r,i)*p%i,w=Ee(m,o,i)*m%i,y=Ee(w,o,i)*m%i,b=Ee(y,t,i)*u%i;return{pow_p_5_8:Ee(b,ay,i)*e%i,b2:a}}function uy(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var cy=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function v1(e,t){let n=$u,r=_e(t*t*t,n),o=_e(r*r*t,n),i=S1(e*o).pow_p_5_8,s=_e(e*r*i,n),a=_e(t*s*s,n),c=s,l=_e(s*cy,n),u=a===e,d=a===_e(-e,n),p=a===_e(-e*cy,n);return u&&(s=c),(d||p)&&(s=l),Qw(s,n)&&(s=_e(-s,n)),{isValid:u||d,value:s}}var zu=iy(k1,{uvRatio:v1}),ly=zu.Fp;function E1(e){let{y:t}=e;return ly.toBytes(ly.div(Vu+t,Vu-t))}function A1(e){let t=zu.Fp.BYTES;return Me(e,t),uy(Zo(e.subarray(0,t))).subarray(0,t)}function _1(e){return sy(zu,Zo,Object.assign({adjustScalarBytes:uy,toMontgomery:E1,toMontgomerySecret:A1,zip215:!0},e))}var Ge=_1({});var N1=BigInt(0),ii=BigInt(1),I1=BigInt(2),T1=BigInt(7),O1=BigInt(256),B1=BigInt(113),py=[],hy=[],my=[];for(let e=0,t=ii,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],py.push(2*(5*r+n)),hy.push((e+1)*(e+2)/2%64);let o=N1;for(let i=0;i<7;i++)t=(t<<ii^(t>>T1)*B1)%O1,t&I1&&(o^=ii<<(ii<<BigInt(i))-ii);my.push(o)}var wy=$s(my,!0),P1=wy[0],C1=wy[1],R1=(e,t,n)=>e<<n|t>>>32-n,H1=(e,t,n)=>t<<n|e>>>32-n,L1=(e,t,n)=>t<<n-32|e>>>64-n,F1=(e,t,n)=>e<<n-32|t>>>64-n,dy=(e,t,n)=>n>32?L1(e,t,n):R1(e,t,n),fy=(e,t,n)=>n>32?F1(e,t,n):H1(e,t,n),$r=new Uint32Array(10);function D1(e,t=24){if(!(e instanceof Uint32Array))throw new TypeError('"s" expected Uint32Array(50), got type='+typeof e);if(e.length!==50)throw new RangeError('"s" expected Uint32Array(50), got length='+e.length);if(Ce(t,"rounds"),t<1||t>24)throw new Error('"rounds" expected integer 1..24');for(let n=24-t;n<24;n++){for(let i=0;i<10;i++)$r[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){let s=(i+8)%10,a=(i+2)%10,c=$r[a],l=$r[a+1],u=dy(c,l,1)^$r[s],d=fy(c,l,1)^$r[s+1];for(let p=0;p<50;p+=10)e[i+p]^=u,e[i+p+1]^=d}let r=e[2],o=e[3];for(let i=0;i<24;i++){let s=hy[i],a=dy(r,o,s),c=fy(r,o,s),l=py[i];r=e[l],o=e[l+1],e[l]=a,e[l+1]=c}for(let i=0;i<50;i+=10){let s=e[i],a=e[i+1],c=e[i+2],l=e[i+3];e[i]^=~e[i+2]&e[i+4],e[i+1]^=~e[i+3]&e[i+5],e[i+2]^=~e[i+4]&e[i+6],e[i+3]^=~e[i+5]&e[i+7],e[i+4]^=~e[i+6]&e[i+8],e[i+5]^=~e[i+7]&e[i+9],e[i+6]^=~e[i+8]&s,e[i+7]^=~e[i+9]&a,e[i+8]^=~s&c,e[i+9]^=~a&l}e[0]^=P1[n],e[1]^=C1[n]}tt($r)}var Xu=class e{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;canXOF;enableXOF=!1;rounds;constructor(t,n,r,o=!1,i=24){if(Ce(t,"blockLen"),Ce(n,"suffix"),Ce(i,"rounds"),Ow(o,"enableXOF"),this.blockLen=t,this.suffix=n,this.outputLen=r,this.enableXOF=o,this.canXOF=o,this.rounds=i,Ce(r,"outputLen"),!(0<t&&t<200))throw new Error('"blockLen" must be 1..199');this.state=new Uint8Array(200),this.state32=Au(this.state)}clone(){return this._cloneInto()}keccak(){_u(this.state32),D1(this.state32,this.rounds),_u(this.state32),this.posOut=0,this.pos=0}update(t){sn(this),Me(t);let{blockLen:n,state:r,state32:o}=this,i=t.length,s=n%4===0&&t.byteOffset%4===0,a=n/4,c=s&&i>=n?Au(t):void 0;for(let l=0;l<i;){if(c!==void 0&&this.pos===0&&l%4===0&&i-l>=n){for(let d=0,p=l/4;d<a;d++)o[d]^=c[p+d];l+=n,this.pos=n,this.keccak();continue}let u=Math.min(n-this.pos,i-l);for(let d=0;d<u;d++)r[this.pos++]^=t[l++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:t,suffix:n,pos:r,blockLen:o}=this;t[r]^=n,(n&128)!==0&&r===o-1&&this.keccak(),t[o-1]^=128,this.keccak()}writeInto(t){sn(this,!1),Me(t),this.finish();let n=this.state,{blockLen:r}=this;for(let o=0,i=t.length;o<i;){this.posOut>=r&&this.keccak();let s=Math.min(r-this.posOut,i-o);t.set(n.subarray(this.posOut,this.posOut+s),o),this.posOut+=s,o+=s}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not enabled");return this.writeInto(t)}xof(t){return Ce(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(Fr(t,this),this.finished)throw new Error("digest() was already called");this.writeInto(t.length===this.outputLen?t:t.subarray(0,this.outputLen)),this.destroy()}digest(){let t=new Uint8Array(this.outputLen);return this.digestInto(t),t}destroy(){this.destroyed=!0,tt(this.state)}_cloneInto(t){let{blockLen:n,suffix:r,outputLen:o,rounds:i,enableXOF:s}=this;return t||=new e(n,r,o,s,i),t.blockLen=n,t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=i,t.suffix=r,t.outputLen=o,t.enableXOF=s,t.canXOF=this.canXOF,t.destroyed=this.destroyed,t}},yy=(e,t,n,r={})=>Go(()=>new Xu(t,e,n),r);var by=yy(6,72,64,qo(10));var pa=yy(1,136,32);function qu(e){return pa(e)}var St=Ge.Point.CURVE().n,xy="8b655970153799af2aeadc9ff1add0ea6c7251d54154cfa92c173a0dd39c1f94",U1=Ge.Point.fromHex(xy);function gy(e,t){let n=(BigInt(t)%St+St)%St;return n===0n?Ge.Point.ZERO:e.multiply(n)}function ky(e,t){let n=BigInt(e);if(n<0n)throw new Error("the amount must not be negative");return gy(Ge.Point.BASE,t).add(gy(U1,n)).toHex()}function lr(e){let t=String(e).trim().replace(/^0x/,"");if(t.length%2)throw new Error("odd hex length");let n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++)n[r]=parseInt(t.substr(r*2,2),16);return n}function zr(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function ma(e){let t=Uint8Array.from(e).reverse();return BigInt("0x"+zr(t))}function Qu(e){return ma(lr(e))}function ha(e,t=32){let n=new Uint8Array(t),r=BigInt(e);for(let o=0;o<t;o++)n[o]=Number(r&0xffn),r>>=8n;return n}function Xr(...e){let t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return ma(qu(n))%St}function Zu(e){let t=[],n=BigInt(e);for(;n>=0x80n;)t.push(Number(n&0x7fn|0x80n)),n>>=7n;return t.push(Number(n)),new Uint8Array(t)}function Sy(e){return Ge.Point.fromHex(String(e).replace(/^0x/,""))}function Ju(e){if(typeof e=="bigint")return[["number",e%St]];let t=String(e).replace(/^0x/,"");return/^[0-9a-fA-F]{64}$/.test(t)?[["BE-number",BigInt("0x"+t)%St],["LE-bytes",Qu(t)%St]]:[["unparsed",null]]}function M1(e,t){let n=String(t||"").toLowerCase();if(!n)return null;for(let[r,o]of Ju(e))if(o!==null&&Ge.Point.BASE.multiply(o).toHex().toLowerCase()===n)return r;return!1}function Yu(e,t){let n=Sy(e),r=(typeof t=="bigint"?t:Qu(String(t).replace(/^0x/,"")))%St,o=n.multiply(r);return lr(o.multiply(8n).toHex())}function vy(e,t,n){let r=Xr(e,Zu(t));return Ge.Point.BASE.multiply(r).add(Sy(n)).toHex()}function Ey(e){let t=Array.isArray(e)?Uint8Array.from(e):lr(e),n=0;for(;n<t.length;){let r=t[n];if(r===1)return zr(t.subarray(n+1,n+33));if(r===2){n+=1+t[n+1];continue}if(r===0){n+=1+t[n+1];continue}return null}return null}function Ay(e){return Number(e)>=4}function j1(e,t){let n=Xr(e);return t==="mask"?n:Xr(lr(n.toString(16).padStart(64,"0")))}function _y(e,t,n,r){if(Ay(n)){if(r==="mask")return Xr(new TextEncoder().encode("commitment_mask"),t);let s=lr(e),a=new TextEncoder().encode(r),c=new Uint8Array(a.length+t.length);c.set(a,0),c.set(t,a.length);let l=qu(c),u=s.slice();for(let d=0;d<u.length&&d<l.length;d++)u[d]^=l[d];return ma(u)}let o=lr(e);return(BigInt("0x"+zr(o))%St-j1(t,r)+St)%St}function Ny(e,t,n){return _y(e,t,n,"amount")}function Gu(e,t,n){return _y(e,t,n,"mask")}function Iy({txPublicKey:e,viewSecretHex:t,spendPubHex:n,outputs:r,ecdhAmounts:o=[],ecdhMasks:i=[],outPk:s=[],rctVersion:a=2}){if(!e)throw new Error("the transaction has no public key (extra tag 0x01) - nothing to parse");let c=Ju(t).filter(([,u])=>u!==null),l=c[0]||["unparsed",null];for(let[u,d]of c){let p=Yu(e,d),m=[];for(let w of r){let y=Xr(p,Zu(w.index));if(vy(p,w.index,n).toLowerCase()===String(w.key).toLowerCase()){let x=o[w.index]?Ny(o[w.index],ha(y),a):null,I=Ay(a)?Gu(null,ha(y),a):i[w.index]?Gu(i[w.index],ha(y),a):null,E=!1;if(x!==null&&I!==null&&s[w.index])try{E=ky(x,I).toLowerCase()===String(s[w.index]).replace(/^0x/,"").toLowerCase()}catch{E=!1}m.push({index:w.index,key:w.key,amountAtomic:x,maskAtomic:I,amountVerified:E})}}if(m.length)return{derivation:zr(p),outputs:m,viewKeyForm:u}}return{derivation:l[1]===null?null:zr(Yu(e,l[1])),outputs:[],viewKeyForm:l[0]}}var Ty=e=>{let t=String(e);for(;t.endsWith("/");)t=t.slice(0,-1);return t};async function Oy(e,t,n=globalThis.fetch){let o=await(await n(`${Ty(e)}/json_rpc`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:"block",method:"get_block",params:{height:t}})})).json();if(o&&String(o.status||"").toUpperCase()==="BUSY")throw new Error(`block ${t}: daemon is BUSY`);if(!o.result)throw new Error(`block ${t} not received: ${o.error?o.error.message:"empty answer"}`);if(String(o.result.status||"").toUpperCase()==="BUSY")throw new Error(`block ${t}: daemon is BUSY`);if(o.result.json===void 0||o.result.json===null||o.result.json==="")throw new Error(`block ${t}: no decoded body`);return o.result}async function By(e,t,n=globalThis.fetch){if(!t.length)return[];let o=await(await n(`${Ty(e)}/get_transactions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txs_hashes:t,decode_as_json:!0})})).json();if(o&&String(o.status||"").toUpperCase()==="BUSY")throw new Error("transactions-busy");let i=Array.isArray(o&&o.txs)?o.txs:[],s=Array.isArray(o&&o.txs_as_json)?o.txs_as_json:[],a=[...new Set(t.map(d=>String(d).replace(/^0x/,"").toLowerCase()))],c=new Map;for(let d of i){let p=String(d&&d.tx_hash||"").replace(/^0x/,"").toLowerCase();if(p){if(c.has(p))throw new Error("transactions-duplicate: "+p);c.set(p,d)}}let l=a.filter(d=>!c.has(d));if(l.length)throw new Error("transactions-missing: "+l.length);if(c.size!==a.length)throw new Error("transactions-extra: "+(c.size-a.length));if(s.length!==i.length)throw new Error("transactions-undecoded");let u=new Map(i.map((d,p)=>[String(d&&d.tx_hash||"").replace(/^0x/,"").toLowerCase(),p]));return a.map(d=>{let p=c.get(d)||{},m=s[u.get(d)],w=typeof m=="string"?JSON.parse(m):m;return w.tx_hash=p.tx_hash||w.tx_hash||null,w.block_height=p.block_height??null,w.confirmations=p.confirmations??null,w.in_pool=p.in_pool??null,w})}function Py(e,t,{height:n=null,tipHeight:r=null,nowSec:o=null}={}){let i=[],s=Ey(e.extra);if(!s)return i;let a=n??e.block_height??null,c=r==null?a:Number(r),l=Su(e.unlock_time,{height:c,nowSec:o}),u=x=>((x.target||{}).tagged_key||x.target||{}).key,d=(e.vout||[]).map((x,I)=>({index:I,key:u(x)})),p=(e.rct_signatures||{}).ecdhInfo||[],m=p.map(x=>x.amount),w=p.map(x=>x.mask),y=(e.rct_signatures||{}).outPk||[],b=(e.rct_signatures||{}).type||2;for(let x of t){let I=Iy({txPublicKey:s,viewSecretHex:x.viewSecret,spendPubHex:x.spendPub,outputs:d,ecdhAmounts:m,ecdhMasks:w,outPk:y,rctVersion:Number(b)||1});I.outputs.length&&i.push({address:x.address,index:x.index??null,outputs:I.outputs,derivation:I.derivation,viewKeyForm:I.viewKeyForm,unlockTime:Number(e.unlock_time)||0,unlock:l})}return i}async function K1({daemonUrl:e,fromHeight:t,toHeight:n,watched:r,log:o=()=>{},concurrency:i=4,nowSec:s=null,tipHeight:a=null,fetchImpl:c=globalThis.fetch}){let l=Number(t),u=Number(n);if(!(l>=0)||!(u>=l))throw new Error("bad height range: "+t+".."+n);let d=new Map;for(let x of r)d.set(x.address,{address:x.address,receivedAtomic:0n,lockedAtomic:0n,lockedUntil:null,lockedTxids:[],txids:[],bestHeight:null,outputs:0,viewKeyForm:null});let p=[];for(let x=l;x<=u;x++)p.push(x);let m=[],w=0,y=async()=>{for(;w<p.length;){let x=p[w++];try{let I=await Oy(e,x,c),E=I.json?(typeof I.json=="string"?JSON.parse(I.json):I.json).tx_hashes||[]:[];if(!E.length)continue;let U=await By(e,E,c);for(let S of U)for(let B of Py(S,r,{height:x,tipHeight:a??u,nowSec:s})){let R=d.get(B.address);if(!R)continue;B.viewKeyForm&&(R.viewKeyForm=B.viewKeyForm);let A=!!(B.unlock&&B.unlock.locked),N=String(S.tx_hash||"").replace(/^0x/,"");for(let f of B.outputs){let k=f.amountVerified&&f.amountAtomic||0n;A?(R.lockedAtomic+=k,N&&!R.lockedTxids.includes(N)&&R.lockedTxids.push(N),Ws(B.unlock)>Ws(R.lockedUntil)&&(R.lockedUntil=B.unlock)):(R.receivedAtomic+=k,R.outputs+=1),N&&!R.txids.includes(N)&&R.txids.push(N),(R.bestHeight===null||x>R.bestHeight)&&(R.bestHeight=x)}}}catch(I){m.push(x),o({event:"indexer_block_error",height:x,error:String(I.message).slice(0,160)})}}};await Promise.all(Array.from({length:Math.max(1,Math.min(i,p.length))},y));let b=[...new Set(m)].sort((x,I)=>x-I);return{fromHeight:l,toHeight:u,results:Array.from(d.values()),complete:b.length===0,missingHeights:b,...b.length?{incompleteReason:"blocks-unreadable"}:{}}}var wa=["awaiting_funding","funded","maker_locking","xmr_locked","ready","claimed","swept"];var ya=["balance","gas","allowance","consent","network","settlement-network","stale","deadline","range","size","escrow-state","escrow-points","counterparty","slots","unchecked","unknown"],Yr=["not-implemented","bad-input","wallet-not-connected","wallet-rejected","wrong-chain","wrong-account","quote-unavailable","quote-refused","address-denied","quote-stale","quote-signature-invalid","quote-key-mismatch","quote-field-unbound","quote-expired","quote-registry-unchecked","quote-key-unknown","quote-provider-mismatch","quote-provider-not-allowed","quote-factory-unchecked","quote-factory-unknown","quote-factory-mismatch","quote-factory-code-unknown","recovery-declined","recovery-failed","storage-unavailable","server-unavailable","server-refused","funding-pending","xmr-timeout","xmr-locked","xmr-nodes-disagree","xmr-no-nodes","xmr-underpaid","xmr-too-late","contract-reverted","insufficient-funds","sweep-fee-too-high","gas-refused-by-maker","gas-not-arrived","gas-too-little","unknown"];var W1=Object.freeze({"not-implemented":{retryable:!1,side:"caller"},"bad-input":{retryable:!1,side:"caller"},"wallet-not-connected":{retryable:!1,side:"wallet"},"wallet-rejected":{retryable:!1,side:"wallet"},"wrong-chain":{retryable:!1,side:"wallet"},"wrong-account":{retryable:!1,side:"wallet"},"quote-unavailable":{retryable:!0,side:"provider"},"quote-refused":{retryable:!1,side:"provider"},"address-denied":{retryable:!1,side:"caller"},"quote-stale":{retryable:!0,side:"provider"},"quote-signature-invalid":{retryable:!1,side:"provider"},"quote-key-mismatch":{retryable:!1,side:"provider"},"quote-field-unbound":{retryable:!1,side:"provider"},"quote-expired":{retryable:!0,side:"provider"},"quote-registry-unchecked":{retryable:!0,side:"chain"},"quote-key-unknown":{retryable:!1,side:"chain"},"quote-provider-mismatch":{retryable:!1,side:"chain"},"quote-provider-not-allowed":{retryable:!1,side:"caller"},"quote-factory-unchecked":{retryable:!0,side:"chain"},"quote-factory-unknown":{retryable:!1,side:"chain"},"quote-factory-mismatch":{retryable:!1,side:"chain"},"quote-factory-code-unknown":{retryable:!1,side:"chain"},"recovery-declined":{retryable:!1,side:"wallet"},"recovery-failed":{retryable:!1,side:"wallet"},"storage-unavailable":{retryable:!0,side:"service"},"server-unavailable":{retryable:!0,side:"service"},"server-refused":{retryable:!1,side:"service"},"funding-pending":{retryable:!0,side:"chain"},"xmr-timeout":{retryable:!0,side:"chain"},"xmr-locked":{retryable:!0,side:"chain"},"xmr-nodes-disagree":{retryable:!0,side:"chain"},"xmr-no-nodes":{retryable:!0,side:"chain"},"xmr-underpaid":{retryable:!1,side:"chain"},"xmr-too-late":{retryable:!1,side:"chain"},"contract-reverted":{retryable:!1,side:"chain"},"insufficient-funds":{retryable:!1,side:"wallet"},"sweep-fee-too-high":{retryable:!1,side:"chain"},"gas-refused-by-maker":{retryable:!1,side:"provider"},"gas-not-arrived":{retryable:!0,side:"chain"},"gas-too-little":{retryable:!1,side:"provider"},unknown:{retryable:!1,side:"unknown"}}),V1={"in-range":"range","above-max":"range","below-min":"range","range-unstated":"range","size-unstated":"size","amount-unstated":"size","unit-mismatch":"range","balance-enough":"balance","balance-short":"balance","balance-unchecked":"balance","gas-enough":"gas","gas-short":"gas","reserve-unstated":"gas","native-unchecked":"gas","not-needed":"allowance",allowed:"allowance","allowance-short":"allowance","allowance-unchecked":"allowance","consent-missing":"consent","network-match":"network","network-unknown":"network","wallet-unknown":"network","wallet-network":"network","settlement-network":"settlement-network","real-provider":"counterparty","stand-in-provider":"counterparty","standin-on-production":"counterparty",fresh:"stale",stale:"stale","no-ttl":"stale",untimed:"stale",expired:"stale","deadlines-ok":"deadline","deadlines-unstated":"deadline","ready-by-in-past":"deadline","t1-not-after-ready-by":"deadline","ready-window-too-short":"deadline","claim-window-too-short":"deadline","deadline-too-far":"deadline",new:"escrow-state","already-funded":"escrow-state","already-claimed":"escrow-state","already-refunded":"escrow-state","state-unchecked":"escrow-state","off-step":"escrow-state","points-match":"escrow-points","point-mismatch":"escrow-points","commit-mismatch":"escrow-points","points-unchecked":"escrow-points","slots-match":"slots","slots-unchecked":"slots",unchecked:"unchecked"},Cy=e=>V1[e]||"unknown";var h=class extends Error{constructor(t,n={}){super(t),this.name="SdkError",this.code=t,this.params=n}toJSON(){return{code:this.code,params:this.params}}},C=(e,t)=>{throw new h(e,t)};var Fd={};Be(Fd,{ASYNC:()=>je,BALANCE_OF_SELECTOR:()=>J0,SETTLES:()=>Ld,SYNC:()=>ai,balances:()=>VE,carriesNativeVerdict:()=>YE,providerSettles:()=>tb,requireAsyncProvider:()=>zE,requireProvider:()=>XE,requireSyncProvider:()=>$E,routeProviderFor:()=>Fa,routeProviders:()=>ro,sameChain:()=>KE,vm:()=>jE,walletChainId:()=>Z0});var ai="sync",je="async";var ed=e=>!e||typeof e!="object"?{ok:!1,reason:"provider-absent"}:e.shape!==ai&&e.shape!==je?{ok:!1,reason:"provider-shape-unknown",shape:e.shape===void 0?null:e.shape}:e.shape===je&&typeof e.settled!="function"?{ok:!1,reason:"provider-incomplete",shape:je,missing:"settled"}:{ok:!0,shape:e.shape};var ba=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(t,n){if(Lr(t),Me(n,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?t.create().update(n).digest():n);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=t.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),tt(o)}update(t){return sn(this),this.iHash.update(t),this}digestInto(t){sn(this),Fr(t,this),this.finished=!0;let n=t.subarray(0,this.outputLen);this.iHash.digestInto(n),this.oHash.update(n),this.oHash.digestInto(n),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:n,iHash:r,finished:o,destroyed:i,blockLen:s,outputLen:a,canXOF:c}=this;return t=t,t.finished=o,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.canXOF=c,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ga=(()=>{let e=((t,n,r)=>new ba(t,n).update(r).digest());return e.create=(t,n)=>new ba(t,n),e})();var $1=BigInt(0),td=class extends Error{constructor(t=""){super(t)}},cn={Err:td,_tlv:{encode:(e,t)=>{let{Err:n}=cn;if(an(e,"tag"),e<0||e>255)throw new n("tlv.encode: wrong tag");if(Dw(t,"data"),t.length&1)throw new n("tlv.encode: unpadded data");let r=t.length/2,o=ei(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");let i=r>127?ei(o.length/2|128):"";return ei(e)+i+o+t},decode(e,t){let{Err:n}=cn;t=ue(t,void 0,"DER data");let r=0;if(e<0||e>255)throw new n("tlv.decode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");let o=t[r++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");let l=t.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(r+=c,s<128)throw new n("tlv.decode(long): not minimal encoding")}let a=t.subarray(r,r+s);if(a.length!==s)throw new n("tlv.decode: wrong value length");return{v:a,l:t.subarray(r+s)}}},_int:{encode(e){let{Err:t}=cn;if(ea(e),e<$1)throw new t("integer: negative integers are not allowed");let n=ei(e);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){let{Err:t}=cn;if(e.length<1)throw new t("invalid signature integer: empty");if(e[0]&128)throw new t("invalid signature integer: negative");if(e.length>1&&e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Xt(e)}},toSig(e,t){let{Err:n,_int:r,_tlv:o}=cn;if(t!==void 0&&(an(t,"maxScalarBytes"),t<1))throw new n("invalid signature: maxScalarBytes must be positive");let i=ue(e,void 0,"signature"),{v:s,l:a}=o.decode(48,i);if(a.length)throw new n("invalid signature: left bytes after parsing");let{v:c,l}=o.decode(2,s),{v:u,l:d}=o.decode(2,l);if(d.length)throw new n("invalid signature: left bytes after parsing");if(t!==void 0&&(c.length>t||u.length>t))throw new n("invalid signature: integer too large");return{r:r.decode(c),s:r.decode(u)}},hexFromSig(e){let{_tlv:t,_int:n}=cn;st(e,{r:"bigint",s:"bigint"},{},"sig");let r=t.encode(2,n.encode(e.r)),o=t.encode(2,n.encode(e.s)),i=r+o;return t.encode(48,i)}},xa=(Object.freeze(cn._tlv),Object.freeze(cn._int),Object.freeze(cn));var Ry=(e,t)=>(e+(e>=0?t:-t)/Hy)/t;function z1(e,t,n){Mr("scalar",e,ln,n);let[[r,o],[i,s]]=t,a=Ry(s*e,n),c=Ry(-o*e,n),l=e-a*r-c*i,u=-a*o-c*s,d=l<ln,p=u<ln;d&&(l=-l),p&&(u=-u);let m=ni(Math.ceil(jr(n)/2))+ur;if(l<ln||l>=m||u<ln||u>=m)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:d,k1:l,k2neg:p,k2:u}}function od(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function nd(e,t){st(e);let n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return it(n.lowS,"lowS"),it(n.prehash,"prehash"),n.format!==void 0&&od(n.format),n}var ln=BigInt(0),ur=BigInt(1),Hy=BigInt(2),rd=BigInt(3),X1=BigInt(4);function Ly(e,t={}){let n=ca("weierstrass",e,t),r=n.Fp,o=n.Fn,i=n.CURVE,{h:s,n:a}=i;st(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:l,clearCofactor:u,isTorsionFree:d,fromBytes:p,toBytes:m}=t,w=t.randomBytes===void 0?ar:t.randomBytes;if(c&&(!r.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let y=c?{beta:c.beta,basises:c.basises.map($=>[...$])}:void 0,b=Dy(r,o);function x(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function I($,O,g){if(O.is0()){if(!l)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:T,y:v}=O.toAffine(),V=r.toBytes(T);if(it(g,"isCompressed"),g){x();let D=!r.isOdd(v);return kt(Fy(D),V)}else return kt(Uint8Array.of(4),V,r.toBytes(v))}function E($){ue($,void 0,"Point");let{publicKey:O,publicKeyUncompressed:g}=b,T=$.length,v=$[0],V=$.subarray(1);if(l&&T===1&&v===0)return{x:r.ZERO,y:r.ZERO};if(T===O&&(v===2||v===3)){let D=r.fromBytes(V);if(!r.isValid(D))throw new Error("bad point: is not on curve, wrong x");let F=A(D),M;try{M=r.sqrt(F)}catch(Z){let J=Z instanceof Error?": "+Z.message:"";throw new Error("bad point: is not on curve, sqrt error"+J)}x();let X=r.isOdd(M);return(v&1)===1!==X&&(M=r.neg(M)),{x:D,y:M}}else if(T===g&&v===4){let D=r.BYTES,F=r.fromBytes(V.subarray(0,D)),M=r.fromBytes(V.subarray(D,D*2));if(!N(F,M))throw new Error("bad point: is not on curve");return{x:F,y:M}}else throw new Error(`bad point: got length ${T}, expected compressed=${O} or uncompressed=${g}`)}let U=m===void 0?I:m,S=p===void 0?E:p,B=r.mul(i.b,rd),R=r.is0(i.a)?$=>r.ZERO:$=>r.mul(i.a,$);function A($){let O=r.sqr($),g=r.mul(O,$);return r.add(r.add(g,r.mul($,i.a)),i.b)}function N($,O){let g=r.sqr(O),T=A($);return r.eql(g,T)}if(!N(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let f=r.mul(r.pow(i.a,rd),X1),k=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(f,k)))throw new Error("bad curve params: a or b");function _($,O,g=!1){if(!r.isValid(O)||g&&r.is0(O))throw new Error(`bad point coordinate ${$}`);return typeof O=="object"&&O!==null?r.create(O):O}function K($){if(!($ instanceof L))throw new Error("Weierstrass Point expected")}function H($){if(!y||!y.basises)throw new Error("no endo");return z1($,y.basises,o.ORDER)}function P($,O,g,T){if(!o.isValid(T))throw new RangeError("invalid scalar: out of range");if(y){let{k1neg:v,k1:V,k2neg:D,k2:F}=H(T),M=new L(r.mul(g.X,y.beta),g.Y,g.Z);$.push(v?g.negate():g,D?M.negate():M),O.push(V,F)}else $.push(g),O.push(T)}let j=new WeakSet;class L{static BASE=new L(i.Gx,i.Gy,r.ONE);static ZERO=new L(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=o;X;Y;Z;constructor(O,g,T){this.X=_("x",O),this.Y=_("y",g,!0),this.Z=_("z",T),Object.freeze(this)}static CURVE(){return i}static fromAffine(O){let{x:g,y:T}=O||{};if(!O||!r.isValid(g)||!r.isValid(T))throw new Error("invalid affine point");if(O instanceof L)throw new Error("projective point not allowed");return r.is0(g)&&r.is0(T)?L.ZERO:new L(g,T,r.ONE)}static fromBytes(O){let g=L.fromAffine(S(ue(O,void 0,"point")));return g.assertValidity(),g}static fromHex(O){return L.fromBytes(Ur(O))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(O=6,g=!0){return W.setWindowSize(this,O),g||this.multiply(rd),this}assertValidity(){let O=this;if(O.is0()){if(l&&r.is0(O.X)&&r.eql(O.Y,r.ONE)&&r.is0(O.Z))return;throw new Error("bad point: ZERO")}if(j.has(O))return;let{x:g,y:T}=O.toAffine();if(!r.isValid(g)||!r.isValid(T))throw new Error("bad point: x or y not field elements");if(!N(g,T))throw new Error("bad point: equation left != right");if(!O.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");j.add(O)}hasEvenY(){let{y:O}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(O)}equals(O){K(O);let{X:g,Y:T,Z:v}=this,{X:V,Y:D,Z:F}=O,M=r.eql(r.mul(g,F),r.mul(V,v)),X=r.eql(r.mul(T,F),r.mul(D,v));return M&&X}negate(){return new L(this.X,r.neg(this.Y),this.Z)}double(){let{X:O,Y:g,Z:T}=this,v=r.ZERO,V=r.ZERO,D=r.ZERO,F=r.mul(O,O),M=r.mul(g,g),X=r.mul(T,T),G=r.mul(O,g);return G=r.add(G,G),D=r.mul(O,T),D=r.add(D,D),v=R(D),V=r.mul(B,X),V=r.add(v,V),v=r.sub(M,V),V=r.add(M,V),V=r.mul(v,V),v=r.mul(G,v),D=r.mul(B,D),X=R(X),G=r.sub(F,X),G=R(G),G=r.add(G,D),D=r.add(F,F),F=r.add(D,F),F=r.add(F,X),F=r.mul(F,G),V=r.add(V,F),X=r.mul(g,T),X=r.add(X,X),F=r.mul(X,G),v=r.sub(v,F),D=r.mul(X,M),D=r.add(D,D),D=r.add(D,D),new L(v,V,D)}add(O){K(O);let{X:g,Y:T,Z:v}=this,{X:V,Y:D,Z:F}=O,M=r.ZERO,X=r.ZERO,G=r.ZERO,Z=r.mul(g,V),J=r.mul(T,D),te=r.mul(v,F),ke=r.add(g,T),Y=r.add(V,D);ke=r.mul(ke,Y),Y=r.add(Z,J),ke=r.sub(ke,Y),Y=r.add(g,v);let ee=r.add(V,F);return Y=r.mul(Y,ee),ee=r.add(Z,te),Y=r.sub(Y,ee),ee=r.add(T,v),M=r.add(D,F),ee=r.mul(ee,M),M=r.add(J,te),ee=r.sub(ee,M),G=R(Y),M=r.mul(B,te),G=r.add(M,G),M=r.sub(J,G),G=r.add(J,G),X=r.mul(M,G),J=r.add(Z,Z),J=r.add(J,Z),te=R(te),Y=r.mul(B,Y),J=r.add(J,te),te=r.sub(Z,te),te=R(te),Y=r.add(Y,te),Z=r.mul(J,Y),X=r.add(X,Z),Z=r.mul(ee,Y),M=r.mul(ke,M),M=r.sub(M,Z),Z=r.mul(ke,J),G=r.mul(ee,G),G=r.add(G,Z),new L(M,X,G)}subtract(O){return K(O),this.add(O.negate())}is0(){return this.equals(L.ZERO)}multiply(O){if(!o.isValidNot0(O))throw new RangeError("invalid scalar: out of range");let{p:g,f:T}=W.mulSecret(this,O,s,z);return z([g,T])[0]}multiplyUnsafe(O){let g=this,T=O;if(!o.isValid(T))throw new RangeError("invalid scalar: out of range");if(T===ln||g.is0())return L.ZERO;if(T===ur)return g;if(W.hasWindowSize(this))return W.mulUnsafe(g,T,z);let v=[],V=[];return P(v,V,g,T),aa(L,v,V)}mulAddUnsafe(O,g,T){K(g);let v=[],V=[];return P(v,V,this,O),P(v,V,g,T),aa(L,v,V)}toAffine(O){let g=this,T=O;if(T!=null&&!r.isValid(T))throw new RangeError('"invertedZ" expected valid field element');let{X:v,Y:V,Z:D}=g;if(r.eql(D,r.ONE))return{x:v,y:V};let F=g.is0();T==null&&(T=F?r.ONE:r.inv(D));let M=r.mul(v,T),X=r.mul(V,T),G=r.mul(D,T);if(F)return{x:r.ZERO,y:r.ZERO};if(!r.eql(G,r.ONE))throw new Error("invZ was invalid");return{x:M,y:X}}isTorsionFree(){return s===ur?!0:d?d(L,this):W.mulUnsafe(this,a).is0()}clearCofactor(){return s===ur?this:u?u(L,this):this.multiplyUnsafe(s)}isSmallOrder(){return s===ur?this.is0():this.clearCofactor().is0()}toBytes(O=!0){return it(O,"isCompressed"),this.assertValidity(),U(L,this,O)}toHex(O=!0){return Jo(this.toBytes(O))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let z=$=>sa(L,$),W=new Vr(L,w);return W.bits>=6&&L.BASE.precompute(6),Object.freeze(L.prototype),Object.freeze(L),L}function Fy(e){return Uint8Array.of(e?2:3)}function Dy(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Y1(e,t={}){Hn(e);let{Fn:n}=e,r=t.randomBytes===void 0?ar:t.randomBytes,o=Object.assign(Dy(e.Fp,n),{seed:Math.max(oa(n.ORDER),16)});function i(m){try{let w=n.fromBytes(m);return n.isValidNot0(w)}catch{return!1}}function s(m,w){let{publicKey:y,publicKeyUncompressed:b}=o;try{let x=m.length;return w===!0&&x!==y||w===!1&&x!==b?!1:!e.fromBytes(m).is0()}catch{return!1}}function a(m){return m=m===void 0?r(o.seed):m,ia(ue(m,o.seed,"seed"),n.ORDER)}function c(m,w=!0){return e.BASE.multiply(n.fromBytes(m)).toBytes(w)}function l(m){let{secretKey:w,publicKey:y,publicKeyUncompressed:b}=o,x=n._lengths;if(!Cn(m))return;let I=ue(m,void 0,"key").length,E=I===y||I===b,U=I===w||!!x?.includes(I);if(!(E&&U))return E}function u(m,w,y=!0){if(l(m)===!0)throw new Error("first arg must be private key");if(l(w)===!1)throw new Error("second arg must be public key");let b=n.fromBytes(m),x=e.fromBytes(w);if(x.is0())throw new Error("invalid public key: point at infinity");return x.multiply(b).toBytes(y)}let d={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},p=la(a,c);return Object.freeze(d),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:p,Point:e,utils:d,lengths:o})}function Uy(e,t,n={}){Hn(e);let r=t;Lr(r),st(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let o=Object.assign({},n),i=o.randomBytes===void 0?ar:o.randomBytes,s=o.hmac===void 0?($,O)=>ga(r,$,O):o.hmac,{Fp:a,Fn:c}=e,{ORDER:l,BITS:u}=c,d=oa(l),p=Wu(i,d),{keygen:m,getPublicKey:w,getSharedSecret:y,utils:b,lengths:x}=Y1(e,o),I={prehash:!0,lowS:typeof o.lowS=="boolean"?o.lowS:!0,format:"compact",extraEntropy:!1},E=l*Hy+ur<a.ORDER;function U($){let O=l>>ur;return $>O}function S($,O){if(!c.isValidNot0(O))throw new Error(`invalid signature ${$}: out of range 1..Point.Fn.ORDER`);return O}function B(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function R($,O,g){return B(),($===g?0:2)|Number(a.isOdd(O))}function A(){if(E)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function N($,O){od(O);let g=x.signature,T=O==="compact"?g:O==="recovered"?g+1:void 0;return ue($,T)}class f{r;s;recovery;constructor(O,g,T){if(this.r=S("r",O),this.s=S("s",g),T!=null){if(A(),![0,1,2,3].includes(T))throw new Error("invalid recovery id");this.recovery=T}Object.freeze(this)}static fromBytes(O,g=I.format){N(O,g);let T;if(g==="der"){if(O.length>2*c.BYTES+16)throw new xa.Err("invalid signature: DER signature too long");let{r:F,s:M}=xa.toSig(ue(O),c.BYTES+1);return new f(F,M)}g==="recovered"&&(T=O[0],g="compact",O=O.subarray(1));let v=x.signature/2,V=O.subarray(0,v),D=O.subarray(v,v*2);return new f(c.fromBytes(V),c.fromBytes(D),T)}static fromHex(O,g){return this.fromBytes(Ur(O),g)}assertRecovery(){let{recovery:O}=this;if(O==null)throw new Error("invalid recovery id: must be present");return O}addRecoveryBit(O){return new f(this.r,this.s,O)}recoverPublicKey(O){let{r:g,s:T}=this,v=this.assertRecovery(),V=v===2||v===3?g+l:g;if(!a.isValid(V))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let D=a.toBytes(V),F=e.fromBytes(kt(Fy((v&1)===0),D)),M=c.inv(V),X=_(ue(O,void 0,"msgHash")),G=c.create(-X*M),Z=c.create(T*M),J=e.BASE.mulAddUnsafe(G,F,Z);if(J.is0())throw new Error("invalid recovery: point at infinify");return J.assertValidity(),J}hasHighS(){return U(this.s)}toBytes(O=I.format){if(od(O),O==="der")return Ur(xa.hexFromSig(this));let{r:g,s:T}=this,v=c.toBytes(g),V=c.toBytes(T);return O==="recovered"?(A(),kt(Uint8Array.of(this.assertRecovery()),v,V)):kt(v,V)}toHex(O){return Jo(this.toBytes(O))}}Object.freeze(f.prototype),Object.freeze(f);let k=o.bits2int===void 0?function(O){if(O.length>8192)throw new Error("input is too large");let g=Xt(O),T=O.length*8-u;return T>0?g>>BigInt(T):g}:o.bits2int,_=o.bits2int_modN===void 0?function(O){return c.create(k(O))}:o.bits2int_modN,K=ni(u);function H($){return Mr("num < 2^"+u,$,ln,K),c.toBytes($)}function P($,O){return ue($,void 0,"message"),O?ue(r($),void 0,"prehashed message"):$}function j($,O,g){let{lowS:T,prehash:v,extraEntropy:V}=nd(g,I);$=P($,v);let D=_($),F=c.fromBytes(O);if(!c.isValidNot0(F))throw new Error("invalid private key");let M=[H(F),H(D)];if(V!=null&&V!==!1){let J=V===!0?i(x.secretKey):V;M.push(ue(J,void 0,"extraEntropy"))}let X=kt(...M),G=D;function Z(J){let te=k(J);if(!c.isValidNot0(te))return;let ke=e.BASE.multiply(te).toAffine(),Y=c.create(ke.x);if(Y===ln)return;let ee;if(p!==void 0){let ne=Xt(ia(p(d),l)),we=c.inv(c.mul(ne,te)),nt=c.mul(ne,G),ht=c.mul(ne,F);ee=c.create(we*c.create(nt+ht*Y))}else{let ne=Yw(te,l);ee=c.create(ne*c.create(G+Y*F))}if(ee===ln)return;let le=R(ke.x,ke.y,Y),Oe=ee;return T&&U(ee)&&(Oe=c.neg(ee),le^=1),new f(Y,Oe,E?void 0:le)}return{seed:X,k2sig:Z}}function L($,O,g={}){let{seed:T,k2sig:v}=j($,O,g);return Mw(r.outputLen,c.BYTES,s)(T,v).toBytes(g.format)}function z($,O,g,T={}){let{lowS:v,prehash:V,format:D}=nd(T,I);if(g=ue(g,void 0,"publicKey"),O=P(O,V),!Cn($)){let F=$ instanceof f?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+F)}N($,D);try{let F=f.fromBytes($,D),M=e.fromBytes(g);if(M.is0()||v&&F.hasHighS())return!1;let{r:X,s:G}=F,Z=_(O),J=c.inv(G),te=c.create(Z*J),ke=c.create(X*J),Y=e.BASE.mulAddUnsafe(te,M,ke);if(Y.is0())return!1;let ee=Y.toAffine();return!(c.create(ee.x)!==X||D==="recovered"&&F.recovery!==R(ee.x,ee.y,X))}catch{return!1}}function W($,O,g={}){let{prehash:T}=nd(g,I);return O=P(O,T),f.fromBytes($,"recovered").recoverPublicKey(O).toBytes()}return Object.freeze({keygen:m,getPublicKey:w,getSharedSecret:y,utils:b,lengths:x,Point:e,sign:L,verify:z,recoverPublicKey:W,Signature:f,hash:r})}var sd={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},G1={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var My=BigInt(2);function q1(e){let t=sd.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,d=Ee(u,n,t)*u%t,p=Ee(d,n,t)*u%t,m=Ee(p,My,t)*l%t,w=Ee(m,o,t)*m%t,y=Ee(w,i,t)*w%t,b=Ee(y,a,t)*y%t,x=Ee(b,c,t)*b%t,I=Ee(x,a,t)*y%t,E=Ee(I,n,t)*u%t,U=Ee(E,s,t)*w%t,S=Ee(U,r,t)*l%t,B=Ee(S,My,t);if(!id.eql(id.sqr(B),e))throw new Error("Cannot find square root");return B}var id=Wr(sd.p,{sqrt:q1}),Q1=Ly(sd,{Fp:id,endo:G1}),Ue=Uy(Q1,Qs);var q=e=>{let t=typeof e=="string"?new TextEncoder().encode(e):e;return pa(t)};var ka=e=>{let t=new Uint8Array(e),n=globalThis.crypto;return(!n||typeof n.getRandomValues!="function")&&C("bad-input",{field:"random-bytes",why:"no-source"}),n.getRandomValues(t),t},Ln={ed25519:Ge,secp256k1:Ue,keccak256:q,sha3_512:by,randomBytes:ka};var jy="NinseiEscrowFactory";var Z1=["EIP712Domain(","string name,","string version,","uint256 chainId,","address verifyingContract)"],Ky=Z1.join(""),va=[["provider","address"],["quoteKey","address"],["registry","address"],["cashier","address"],["locker","address"],["claimer","address"],["amount","uint256"],["readyBy","uint64"],["t1","uint64"],["salt","bytes32"],["commitHalfClaimer","bytes32"],["edPointClaimer","bytes32"],["chainId","uint256"],["feeBps","uint256"],["fee","uint256"],["feeRecipient","address"],["validUntil","uint64"],["nonce","uint256"],["xmrAmount","uint256"],["claimTip","uint256"],["commitHalfLocker","bytes32"],["edPointLocker","bytes32"],["edViewPointLocker","bytes32"]],Wy="OrderQuote("+va.map(e=>e[1]+" "+e[0]).join(",")+")",Fn=e=>{throw new Error(e)},Sa=e=>new TextEncoder().encode(String(e)),Ea=(...e)=>{let t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n},cd=e=>{let t=String(e).replace(/^0x/,"");t.length%2&&Fn("eip712-odd-hex");let n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++){let o=parseInt(t.slice(r*2,r*2+2),16);Number.isNaN(o)&&Fn("eip712-bad-hex"),n[r]=o}return n},J1=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},e2=e=>{if(typeof e=="bigint")return e;let t=String(e??"").trim();if(/^0x[0-9a-fA-F]+$/.test(t)||/^[0-9]+$/.test(t))return BigInt(t);Fn("eip712-bad-number")},ad=(e,t)=>{let n=e2(e);n<0n&&Fn("eip712-negative"),n>=1n<<BigInt(t)&&Fn("eip712-overflow");let r=new Uint8Array(32),o=n;for(let i=31;i>=0&&o>0n;i--)r[i]=Number(o&0xffn),o>>=8n;return r},Vy=e=>{let t=String(e??"").trim();/^(0x)?[0-9a-fA-F]{40}$/.test(t)||Fn("eip712-bad-address");let n=new Uint8Array(32);return n.set(cd(t.replace(/^0x/,"")),12),n},t2=e=>{let t=String(e??"").trim();return/^(0x)?[0-9a-fA-F]{64}$/.test(t)||Fn("eip712-bad-bytes32"),cd(t.replace(/^0x/,""))},n2=(e,t)=>{if(e==="address")return Vy(t);if(e==="bytes32")return t2(t);if(e==="uint64")return ad(t,64);if(e==="uint256")return ad(t,256);Fn("eip712-bad-type")},ld=e=>{let t=[];for(let[n]of va){let r=e?e[n]:void 0;(r==null||r==="")&&t.push(n)}return e&&(e.factory===void 0||e.factory===null||e.factory==="")&&t.push("factory"),e&&(e.signature===void 0||e.signature===null||e.signature==="")&&t.push("signature"),t};function r2({crypto:e,quote:t}){return e.keccak256(Ea(e.keccak256(Sa(Ky)),e.keccak256(Sa(jy)),e.keccak256(Sa("1")),ad(t.chainId,256),Vy(t.factory)))}function o2({crypto:e,quote:t}){let n=[e.keccak256(Sa(Wy))];for(let[r,o]of va)n.push(n2(o,t?t[r]:void 0));return e.keccak256(Ea(...n))}function $y({crypto:e,quote:t}){return e.keccak256(Ea(Uint8Array.from([25,1]),r2({crypto:e,quote:t}),o2({crypto:e,quote:t})))}function zy({crypto:e,quote:t}){try{if(ld(t).length)return null;let n=cd(String(t.signature).replace(/^0x/,""));if(n.length!==65)return null;let r=n[64];if(r>=27&&(r-=27),r!==0&&r!==1)return null;let o=$y({crypto:e,quote:t}),s=e.secp256k1.Signature.fromBytes(Ea(n.slice(0,32),n.slice(32,64))).addRecoveryBit(r).recoverPublicKey(o).toBytes(!1);return J1(e.keccak256(s.slice(1)).slice(12))}catch{return null}}var Xy=["Gnosis","Protocol"].join(" "),Yy="v2",dr="0x9008D19f58AAbD9eD0D60971565AA8510560ab41",Gy="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",i2=["EIP712Domain(","string name,","string version,","uint256 chainId,","address verifyingContract)"],s2=i2.join(""),Gr=[["sellToken","address"],["buyToken","address"],["receiver","address"],["sellAmount","uint256"],["buyAmount","uint256"],["validTo","uint32"],["appData","bytes32"],["feeAmount","uint256"],["kind","string"],["partiallyFillable","bool"],["sellTokenBalance","string"],["buyTokenBalance","string"]],a2="Order("+Gr.map(e=>e[1]+" "+e[0]).join(",")+")";var Pt=e=>{throw new Error(e)},ci=e=>new TextEncoder().encode(String(e)),Na=(...e)=>{let t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n},Aa=e=>{let t=String(e).replace(/^0x/,"");t.length%2&&Pt("cow-odd-hex");let n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++){let o=parseInt(t.slice(r*2,r*2+2),16);Number.isNaN(o)&&Pt("cow-bad-hex"),n[r]=o}return n},qy=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},c2=e=>{if(typeof e=="bigint")return e;let t=String(e??"").trim();if(/^0x[0-9a-fA-F]+$/.test(t)||/^[0-9]+$/.test(t))return BigInt(t);Pt("cow-bad-number")},_a=(e,t)=>{let n=c2(e);n<0n&&Pt("cow-negative"),n>=1n<<BigInt(t)&&Pt("cow-overflow");let r=new Uint8Array(32),o=n;for(let i=31;i>=0&&o>0n;i--)r[i]=Number(o&0xffn),o>>=8n;return r},Qy=e=>{let t=String(e??"").trim();/^(0x)?[0-9a-fA-F]{40}$/.test(t)||Pt("cow-bad-address");let n=new Uint8Array(32);return n.set(Aa(t.replace(/^0x/,"")),12),n},l2=e=>{let t=String(e??"").trim();return/^(0x)?[0-9a-fA-F]{64}$/.test(t)||Pt("cow-bad-bytes32"),Aa(t.replace(/^0x/,""))},u2=e=>{let t=new Uint8Array(32);return e===!0||e==="true"||e===1||e==="1"?t[31]=1:e===!1||e==="false"||e===0||e==="0"||e===void 0||e===null?t[31]=0:Pt("cow-bad-bool"),t},d2=e=>q(ci(e)),f2=(e,t)=>{if(e==="address")return Qy(t);if(e==="bytes32")return l2(t);if(e==="uint32")return _a(t,32);if(e==="uint256")return _a(t,256);if(e==="bool")return u2(t);if(e==="string")return d2(t);Pt("cow-bad-type")},Zy=e=>{let t=[];for(let[n]of Gr){let r=e?e[n]:void 0;(r==null||r==="")&&t.push(n)}return t},p2=({chainId:e,settlement:t=dr})=>q(Na(q(ci(s2)),q(ci(Xy)),q(ci(Yy)),_a(e,256),Qy(t))),h2=e=>{let t=[q(ci(a2))];for(let[n,r]of Gr)t.push(f2(r,e?e[n]:void 0));return q(Na(...t))},m2=({order:e,chainId:t,settlement:n=dr})=>q(Na(Uint8Array.from([25,1]),p2({chainId:t,settlement:n}),h2(e))),Jy=e=>qy(m2(e)),e0=({digest:e,owner:t,validTo:n})=>{let r=Aa(e);r.length!==32&&Pt("cow-bad-digest");let o=Aa(t);o.length!==20&&Pt("cow-bad-owner");let i=_a(n,32).slice(28);return qy(Na(r,o,i))},t0=({order:e,chainId:t,settlement:n=dr})=>({domain:{name:Xy,version:Yy,chainId:Number(t),verifyingContract:n},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],Order:Gr.map(([r,o])=>({name:r,type:o}))},primaryType:"Order",message:{sellToken:e.sellToken,buyToken:e.buyToken,receiver:e.receiver,sellAmount:String(e.sellAmount),buyAmount:String(e.buyAmount),validTo:Number(e.validTo),appData:e.appData,feeAmount:String(e.feeAmount),kind:String(e.kind),partiallyFillable:!!e.partiallyFillable,sellTokenBalance:String(e.sellTokenBalance),buyTokenBalance:String(e.buyTokenBalance)}});var w2=()=>typeof fetch=="function"?fetch:null;function at({apiBase:e,fetchImpl:t=null,timeoutMs:n=2e4}){let r=t||w2();return{async json(o,{signal:i=null,method:s="GET",headers:a=null,body:c=null}={}){if(!e)throw new h("server-unavailable",{why:"no-api-base"});if(typeof r!="function")throw new h("bad-input",{field:"fetch"});let l=new AbortController,u=setTimeout(()=>l.abort(),n),d=()=>l.abort();i&&i.addEventListener("abort",d,{once:!0});try{let p={signal:l.signal,method:s,headers:{accept:"application/json",...a||{}}};c!=null&&(p.body=c);let m=await r(e+o,p);if(!m||typeof m.ok!="boolean")throw new h("server-unavailable",{why:"bad-response"});if(!m.ok)throw new h("server-unavailable",{status:m.status});return await m.json()}catch(p){throw p instanceof h?p:new h("server-unavailable",{why:p&&p.name==="AbortError"?"timeout":"fetch"})}finally{clearTimeout(u),i&&i.removeEventListener("abort",d)}},async tryJson(o,{signal:i=null,method:s="GET",headers:a=null,body:c=null}={}){if(!e)throw new h("server-unavailable",{why:"no-api-base"});if(typeof r!="function")throw new h("bad-input",{field:"fetch"});let l=new AbortController,u=setTimeout(()=>l.abort(),n),d=()=>l.abort();i&&i.addEventListener("abort",d,{once:!0});try{let p={signal:l.signal,method:s,headers:{accept:"application/json",...a||{}}};c!=null&&(p.body=c);let m=await r(e+o,p);if(!m||typeof m.ok!="boolean")throw new h("server-unavailable",{why:"bad-response"});let w=null;try{w=await m.json()}catch{w=null}return{ok:m.ok,status:m.status,body:w}}catch(p){throw p instanceof h?p:new h("server-unavailable",{why:p&&p.name==="AbortError"?"timeout":"fetch"})}finally{clearTimeout(u),i&&i.removeEventListener("abort",d)}}}}var ud=Object.freeze({1:{slug:"mainnet",orderbook:"https://api.cow.fi/mainnet"},100:{slug:"xdai",orderbook:"https://api.cow.fi/xdai"},42161:{slug:"arbitrum_one",orderbook:"https://api.cow.fi/arbitrum_one"},8453:{slug:"base",orderbook:"https://api.cow.fi/base"},56:{slug:"bnb",orderbook:"https://api.cow.fi/bnb"},11155111:{slug:"sepolia",orderbook:"https://api.cow.fi/sepolia"}}),y2=["presignaturePending","open","fulfilled","cancelled","expired"],n0=["fulfilled","cancelled","expired"],r0="fulfilled";var Ne=(e,t={})=>({ok:!1,code:e,params:t}),dd=e=>{let t=ud[Number(e)];return t?t.orderbook:null},Ia=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),b2=e=>/^(0x)?[0-9a-fA-F]{64}$/.test(String(e||""));function o0(e={}){let t=Number(e.chainId);if(dd(t)===null)return{...Ne("cow-unknown-network",{chainId:Number.isFinite(t)?t:null}),known:Object.keys(ud).map(Number)};let n=e.owner,r=e.receiver===void 0||e.receiver===null?n:e.receiver,o={sellToken:e.sellToken,buyToken:e.buyToken,receiver:r||n,sellAmount:e.sellAmountWei,buyAmount:e.buyAmountWei,validTo:e.validTo,appData:e.appData===void 0||e.appData===null?"0x"+"00".repeat(32):e.appData,feeAmount:e.feeAmountWei===void 0||e.feeAmountWei===null?"0":e.feeAmountWei,kind:e.kind===void 0||e.kind===null?"sell":e.kind,partiallyFillable:e.partiallyFillable===void 0||e.partiallyFillable===null?!1:e.partiallyFillable,sellTokenBalance:e.sellTokenBalance===void 0||e.sellTokenBalance===null?"erc20":e.sellTokenBalance,buyTokenBalance:e.buyTokenBalance===void 0||e.buyTokenBalance===null?"erc20":e.buyTokenBalance},i=Zy(o);if(Ia(n)||i.push("owner"),b2(o.appData)||i.push("appData"),(!Ia(o.sellToken)||!Ia(o.buyToken)||!Ia(o.receiver))&&i.push("token"),i.length)return Ne("cow-bad-order",{missing:[...new Set(i)]});try{let s=Jy({order:o,chainId:t,settlement:dr}),a=e0({digest:s,owner:n,validTo:o.validTo}),c=t0({order:o,chainId:t,settlement:dr});return{ok:!0,chainId:t,owner:n,order:o,digest:s,uid:a,typedData:c}}catch(s){return Ne("cow-bad-order",{why:String(s&&s.message?s.message:s)})}}function g2({order:e,signature:t,owner:n,signingScheme:r="eip712",from:o=null}){return{sellToken:e.sellToken,buyToken:e.buyToken,receiver:e.receiver,sellAmount:String(e.sellAmount),buyAmount:String(e.buyAmount),validTo:Number(e.validTo),appData:String(e.appData),feeAmount:String(e.feeAmount),kind:String(e.kind),partiallyFillable:!!e.partiallyFillable,sellTokenBalance:String(e.sellTokenBalance),buyTokenBalance:String(e.buyTokenBalance),signingScheme:r,signature:t,from:o||n}}function x2(e={}){let t=o0(e);return t.ok?{ok:!0,provider:"cowswap",venue:"CoWSwap",shape:je,route:"cowswap",expectedOutWei:String(t.order.buyAmount),order:t.order,typedData:t.typedData,digest:t.digest,uid:t.uid,owner:t.owner,endsWith:{kind:"order-status",settledWhen:r0,final:[...n0],endpoint:"/api/v1/orders/{uid}"}}:t}async function k2({typedData:e,wallet:t,address:n=null}={}){if(!e||typeof e!="object")return Ne("cow-bad-order",{field:"typedData"});try{if(t&&typeof t.signTypedData=="function"){let o=await t.signTypedData(e);return typeof o!="string"||!/^0x[0-9a-fA-F]{130}$/.test(o)?Ne("cow-sign-failed",{why:"bad-signature-shape"}):{ok:!0,signature:o}}let r=t&&typeof t.driver=="function"?t.driver():null;if(r&&typeof r.request=="function"){let o=n||(typeof t.address=="function"?await t.address():null),i=await r.request({method:"eth_signTypedData_v4",params:[o,JSON.stringify(e)]});return typeof i!="string"||!/^0x[0-9a-fA-F]{130}$/.test(i)?Ne("cow-sign-failed",{why:"bad-signature-shape"}):{ok:!0,signature:i}}return Ne("cow-sign-failed",{why:"no-wallet"})}catch(r){return Ne("cow-sign-failed",{why:String(r&&r.code||r&&r.message||r)})}}async function S2({order:e,signature:t,owner:n,chainId:r,fetchImpl:o=null,timeoutMs:i=2e4,signingScheme:s="eip712",from:a=null}={}){let c=dd(r);if(c===null)return Ne("cow-unknown-network",{chainId:Number(r)});if(typeof t!="string"||!/^0x[0-9a-fA-F]{130}$/.test(t))return Ne("cow-bad-order",{field:"signature"});let l=at({apiBase:c,fetchImpl:o,timeoutMs:i}),u=JSON.stringify(g2({order:e,signature:t,owner:n,signingScheme:s,from:a})),d;try{d=await l.tryJson("/api/v1/orders",{method:"POST",headers:{"content-type":"application/json"},body:u})}catch(p){return Ne("cow-unreachable",{why:String(p&&p.params&&p.params.why||p&&p.code||p)})}return!d||typeof d.ok!="boolean"?Ne("cow-bad-response",{where:"submit"}):d.ok?typeof d.body!="string"||!/^0x[0-9a-fA-F]{112}$/.test(d.body)?Ne("cow-bad-response",{where:"submit",got:typeof d.body}):{ok:!0,uid:d.body}:Ne("cow-refused",{status:d.status,reason:d.body&&d.body.errorType?d.body.errorType:null})}async function i0({uid:e,chainId:t,fetchImpl:n=null,timeoutMs:r=2e4}={}){let o=dd(t);if(o===null)return Ne("cow-unknown-network",{chainId:Number(t)});if(typeof e!="string"||!/^0x[0-9a-fA-F]{112}$/.test(e))return Ne("cow-bad-order",{field:"uid"});let i=at({apiBase:o,fetchImpl:n,timeoutMs:r}),s;try{s=await i.tryJson("/api/v1/orders/"+e)}catch(c){return Ne("cow-unreachable",{why:String(c&&c.params&&c.params.why||c&&c.code||c)})}if(!s||typeof s.ok!="boolean")return Ne("cow-bad-response",{where:"status"});if(s.status===404)return Ne("cow-order-unknown",{uid:e});if(!s.ok)return Ne("cow-refused",{status:s.status});let a=s.body&&s.body.status;return typeof a!="string"||!y2.includes(a)?Ne("cow-bad-response",{where:"status",got:typeof a=="string"?a:null}):{ok:!0,status:a,order:s.body}}async function v2(e={},t={}){let{uid:n,chainId:r}=e;if(typeof n!="string"||!/^0x[0-9a-fA-F]{112}$/.test(n))return Ne("cow-bad-order",{field:"uid"});let o=typeof t.now=="function"?t.now:()=>Date.now(),i=typeof t.sleep=="function"?t.sleep:u=>new Promise(d=>setTimeout(d,u)),s=Number.isFinite(t.pollMs)&&t.pollMs>0?t.pollMs:5e3,a=Number.isFinite(t.timeoutMs)&&t.timeoutMs>0?t.timeoutMs:3e5,c=o(),l=null;for(;;){let u=await i0({uid:n,chainId:r,fetchImpl:t.fetchImpl,timeoutMs:t.requestTimeoutMs});if(!u.ok)return u;if(l=u.status,n0.includes(l))return{ok:!0,done:!0,settled:l===r0,status:l,uid:n};if(o()-c>=a)return Ne("cow-not-settled",{uid:n,status:l,waitedMs:o()-c});await i(s)}}function E2({order:e=null,requiredOutWei:t=null,tokenUsd:n=null,referenceNativeUsd:r=null,tolerated:o=!1,gates:i=null,sellDecimals:s=null,buyDecimals:a=null,buySymbol:c=null,allowanceWei:l=null,allowanceConsent:u=!1,tokenIsNative:d=!1,symbol:p=null,decimals:m=null}={}){if(!e)return{ok:!1,blocked:!0,reason:"cow-no-order",checks:[]};let w=ot.priceGateVerdict({amountInWei:e.sellAmount,amountOutWei:e.buyAmount,inDecimals:s,outDecimals:a,tokenUsd:Number(n)>0?Number(n):null,referenceUsd:Number(r)>0?Number(r):null,stableSteps:[],tolerated:!!o,gates:i}),y={ok:!0,amountOutWei:String(e.buyAmount),price:w,wrapped:{symbol:c,decimals:a}},b=ot.dexLegVerdict(y,t),x={ok:!b.blocked,checked:b.kind!=="unchecked"&&b.kind!=="unquoted",blocks:b.blocked===!0,kind:b.kind,reason:b.reason},I=pe.allowanceVerdict({tokenIsNative:d,allowanceWei:l,amountWei:e.sellAmount,consent:u===!0,symbol:p,decimals:Number.isFinite(Number(m))?Number(m):18});return{...pe.signingGateVerdict([x,I]),price:w,coverage:b,allowance:I}}var s0=Object.freeze({id:"cowswap",kind:"cow",venue:"CoWSwap",shape:je,settles:"native",networks:ud,settlement:dr,buyEthAddress:Gy,orderFields:Gr,plan:x2,settled:v2,buildIntent:o0,sign:k2,submit:S2,status:i0,gate:E2});var A2=["Kyber","DSLO","Protocol"].join(" "),_2="1",$e="0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C",N2=["EIP712Domain(","string name,","string version,","uint256 chainId,","address verifyingContract)"],I2=N2.join(""),qr=[["salt","uint256"],["makerAsset","address"],["takerAsset","address"],["maker","address"],["receiver","address"],["allowedSender","address"],["makingAmount","uint256"],["takingAmount","uint256"],["feeConfig","uint256"],["makerAssetData","bytes"],["takerAssetData","bytes"],["getMakerAmount","bytes"],["getTakerAmount","bytes"],["predicate","bytes"],["interaction","bytes"]],T2="Order("+qr.map(e=>e[1]+" "+e[0]).join(",")+")";var O2=[["orderHash","bytes32"],["opExpireTime","uint32"]],QT="DSOrder("+O2.map(e=>e[1]+" "+e[0]).join(",")+")";var Dn=e=>{throw new Error(e)},Ta=e=>new TextEncoder().encode(String(e)),pd=(...e)=>{let t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n},hd=e=>{let t=String(e??"").replace(/^0x/,"");t.length%2&&Dn("kyber-odd-hex");let n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++){let o=parseInt(t.slice(r*2,r*2+2),16);Number.isNaN(o)&&Dn("kyber-bad-hex"),n[r]=o}return n},B2=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},P2=e=>{if(typeof e=="bigint")return e;let t=String(e??"").trim();if(/^0x[0-9a-fA-F]+$/.test(t)||/^[0-9]+$/.test(t))return BigInt(t);Dn("kyber-bad-number")},fd=(e,t)=>{let n=P2(e);n<0n&&Dn("kyber-negative"),n>=1n<<BigInt(t)&&Dn("kyber-overflow");let r=new Uint8Array(32),o=n;for(let i=31;i>=0&&o>0n;i--)r[i]=Number(o&0xffn),o>>=8n;return r},a0=e=>{let t=String(e??"").trim();/^(0x)?[0-9a-fA-F]{40}$/.test(t)||Dn("kyber-bad-address");let n=new Uint8Array(32);return n.set(hd(t.replace(/^0x/,"")),12),n},C2=e=>{let t=String(e??"").trim();return/^(0x)?[0-9a-fA-F]{64}$/.test(t)||Dn("kyber-bad-bytes32"),hd(t.replace(/^0x/,""))},R2=e=>q(hd(e)),H2=(e,t)=>{if(e==="address")return a0(t);if(e==="bytes32")return C2(t);if(e==="uint32")return fd(t,32);if(e==="uint256")return fd(t,256);if(e==="bytes")return R2(t);Dn("kyber-bad-type")},c0=e=>{let t=[];for(let[n,r]of qr){let o=e?e[n]:void 0;(o==null||r!=="bytes"&&o==="")&&t.push(n)}return t},L2=({chainId:e,contract:t=$e})=>q(pd(q(Ta(I2)),q(Ta(A2)),q(Ta(_2)),fd(e,256),a0(t))),F2=e=>{let t=[q(Ta(T2))];for(let[n,r]of qr)t.push(H2(r,e?e[n]:void 0));return q(pd(...t))},D2=({order:e,chainId:t,contract:n=$e})=>q(pd(Uint8Array.from([25,1]),L2({chainId:t,contract:n}),F2(e))),l0=e=>B2(D2(e));var ft="https://limit-order.kyberswap.com",d0=["KyberSwap","Limit","Order"].join(" "),Oa=Object.freeze({1:{orderbook:ft,contract:$e},10:{orderbook:ft,contract:$e},56:{orderbook:ft,contract:$e},137:{orderbook:ft,contract:$e},250:{orderbook:ft,contract:$e},324:{orderbook:ft,contract:$e},5e3:{orderbook:ft,contract:$e},8453:{orderbook:ft,contract:$e},42161:{orderbook:ft,contract:$e},43114:{orderbook:ft,contract:$e},59144:{orderbook:ft,contract:$e},534352:{orderbook:ft,contract:$e},81457:{orderbook:ft,contract:$e}}),U2="/write/api/v1/orders/sign-message",M2="/write/api/v1/orders",f0="/read-ks/api/v1/orders";var j2=["active","open","partially_filled","cancelling","closed","filled","cancelled","expired"],p0=["filled","cancelled","expired"],h0="filled";var K2=["active","closed"];var ae=(e,t={})=>({ok:!1,code:e,params:t}),ui=e=>{let t=Oa[Number(e)];return t?t.orderbook:null},m0=e=>{let t=Oa[Number(e)];return t?t.contract:null},li=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),u0=e=>{try{return BigInt(String(e))>0n}catch{return!1}};function W2(e={}){let t=Number(e.chainId);if(ui(t)===null)return{...ae("kyber-unknown-network",{chainId:Number.isFinite(t)?t:null}),known:Object.keys(Oa).map(Number)};let n=e.maker,r=e.receiver===void 0||e.receiver===null?n:e.receiver,o={chainId:String(t),makerAsset:e.makerAsset,takerAsset:e.takerAsset,maker:n,receiver:r,makingAmount:String(e.makingAmount),takingAmount:String(e.takingAmount),expiredAt:e.expiredAt};e.allowedSenders!==void 0&&e.allowedSenders!==null&&(o.allowedSenders=e.allowedSenders);let i=[];return li(n)||i.push("maker"),li(o.makerAsset)||i.push("makerAsset"),li(o.takerAsset)||i.push("takerAsset"),li(o.receiver)||i.push("receiver"),u0(o.makingAmount)||i.push("makingAmount"),u0(o.takingAmount)||i.push("takingAmount"),Number.isInteger(Number(o.expiredAt))||i.push("expiredAt"),i.length?ae("kyber-bad-order",{missing:[...new Set(i)]}):{ok:!0,chainId:t,orderbook:ui(t),contract:m0(t),maker:n,params:o,expectedOutWei:String(o.takingAmount)}}function V2(e={}){let t=W2(e);return t.ok?{ok:!0,provider:"kyberswap",venue:d0,shape:je,route:"kyberswap",expectedOutWei:t.expectedOutWei,params:t.params,owner:t.maker,endsWith:{kind:"order-status",settledWhen:h0,final:[...p0],endpoint:f0}}:t}async function $2({params:e,chainId:t=null,fetchImpl:n=null,timeoutMs:r=2e4,clientId:o=null}={}){let i=Number(t!==null?t:e&&e.chainId),s=ui(i);if(s===null)return ae("kyber-unknown-network",{chainId:Number.isFinite(i)?i:null});if(!e||typeof e!="object")return ae("kyber-bad-order",{field:"params"});let a=at({apiBase:s,fetchImpl:n,timeoutMs:r}),c={"content-type":"application/json"};o&&(c["X-Client-Id"]=String(o));let l;try{l=await a.tryJson(U2,{method:"POST",headers:c,body:JSON.stringify(e)})}catch(E){return ae("kyber-unreachable",{why:String(E&&E.params&&E.params.why||E&&E.code||E)})}if(!l||typeof l.ok!="boolean")return ae("kyber-bad-response",{where:"sign-message"});if(!l.ok)return ae("kyber-refused",{status:l.status,stage:"sign-message",reason:l.body&&l.body.message?l.body.message:null});let u=l.body&&l.body.data;if(!u||typeof u!="object")return ae("kyber-bad-response",{where:"sign-message"});let d=u.domain||{},p=u.message||{},m=u.types&&Array.isArray(u.types.Order)?u.types.Order.map(E=>(E?E.name:"")+":"+(E?E.type:"")).join(","):null,w=qr.map(([E,U])=>E+":"+U).join(","),y=m0(i);if(!(d.name===void 0?!1:String(d.name)===["Kyber","DSLO","Protocol"].join(" ")&&String(d.version)==="1"&&Number(d.chainId)===i&&String(d.verifyingContract||"").toLowerCase()===String(y).toLowerCase()))return ae("kyber-bad-response",{where:"sign-message",field:"domain"});if(m!==w)return ae("kyber-bad-response",{where:"sign-message",field:"types"});let x=c0(p);if(x.length)return ae("kyber-bad-response",{where:"sign-message",missing:x});let I;try{I=l0({order:p,chainId:i,contract:y})}catch(E){return ae("kyber-bad-response",{where:"sign-message",why:String(E&&E.message?E.message:E)})}return{ok:!0,chainId:i,orderbook:s,contract:y,salt:String(p.salt),message:p,digest:I,typedData:{domain:d,types:u.types,primaryType:u.primaryType||"Order",message:p}}}async function z2({typedData:e,wallet:t,address:n=null}={}){if(!e||typeof e!="object")return ae("kyber-bad-order",{field:"typedData"});try{if(t&&typeof t.signTypedData=="function"){let o=await t.signTypedData(e);return typeof o!="string"||!/^0x[0-9a-fA-F]{130}$/.test(o)?ae("kyber-sign-failed",{why:"bad-signature-shape"}):{ok:!0,signature:o}}let r=t&&typeof t.driver=="function"?t.driver():null;if(r&&typeof r.request=="function"){let o=n||(typeof t.address=="function"?await t.address():null),i=await r.request({method:"eth_signTypedData_v4",params:[o,JSON.stringify(e)]});return typeof i!="string"||!/^0x[0-9a-fA-F]{130}$/.test(i)?ae("kyber-sign-failed",{why:"bad-signature-shape"}):{ok:!0,signature:i}}return ae("kyber-sign-failed",{why:"no-wallet"})}catch(r){return ae("kyber-sign-failed",{why:String(r&&r.code||r&&r.message||r)})}}async function X2({params:e,salt:t,signature:n,chainId:r=null,fetchImpl:o=null,timeoutMs:i=2e4,clientId:s=null}={}){let a=Number(r!==null?r:e&&e.chainId),c=ui(a);if(c===null)return ae("kyber-unknown-network",{chainId:Number.isFinite(a)?a:null});if(!e||typeof e!="object")return ae("kyber-bad-order",{field:"params"});if(typeof n!="string"||!/^0x[0-9a-fA-F]{130}$/.test(n))return ae("kyber-bad-order",{field:"signature"});if(t==null||t==="")return ae("kyber-bad-order",{field:"salt"});let l=at({apiBase:c,fetchImpl:o,timeoutMs:i}),u={"content-type":"application/json"};s&&(u["X-Client-Id"]=String(s));let d=JSON.stringify({...e,salt:String(t),signature:n}),p;try{p=await l.tryJson(M2,{method:"POST",headers:u,body:d})}catch(y){return ae("kyber-unreachable",{why:String(y&&y.params&&y.params.why||y&&y.code||y)})}if(!p||typeof p.ok!="boolean")return ae("kyber-bad-response",{where:"submit"});if(!p.ok)return ae("kyber-refused",{status:p.status,stage:"submit",reason:p.body&&p.body.message?p.body.message:null});let m=p.body&&p.body.data,w=m&&m.id;return!Number.isInteger(Number(w))||Number(w)<=0?ae("kyber-bad-response",{where:"submit",got:typeof w}):{ok:!0,id:Number(w)}}async function w0({id:e,chainId:t,maker:n,fetchImpl:r=null,timeoutMs:o=2e4}={}){let i=Number(t),s=ui(i);if(s===null)return ae("kyber-unknown-network",{chainId:Number.isFinite(i)?i:null});if(!Number.isInteger(Number(e))||Number(e)<=0)return ae("kyber-bad-order",{field:"id"});if(!li(n))return ae("kyber-bad-order",{field:"maker"});let a=at({apiBase:s,fetchImpl:r,timeoutMs:o});for(let c of K2){let l=f0+"?chainId="+i+"&maker="+n+"&status="+c,u;try{u=await a.tryJson(l)}catch(m){return ae("kyber-unreachable",{why:String(m&&m.params&&m.params.why||m&&m.code||m)})}if(!u||typeof u.ok!="boolean")return ae("kyber-bad-response",{where:"orders"});if(!u.ok)return ae("kyber-refused",{status:u.status,stage:"orders"});let d=u.body&&u.body.data&&u.body.data.orders;if(!Array.isArray(d))return ae("kyber-bad-response",{where:"orders"});let p=d.find(m=>m&&Number(m.id)===Number(e))||null;if(p){let m=p.status;return typeof m!="string"||!j2.includes(m)?ae("kyber-bad-response",{where:"status",got:typeof m=="string"?m:null}):{ok:!0,status:m,order:p,bucket:c}}}return ae("kyber-order-unknown",{id:Number(e),maker:n})}async function Y2(e={},t={}){let{id:n,chainId:r,maker:o}=e;if(!Number.isInteger(Number(n))||Number(n)<=0)return ae("kyber-bad-order",{field:"id"});let i=typeof t.now=="function"?t.now:()=>Date.now(),s=typeof t.sleep=="function"?t.sleep:d=>new Promise(p=>setTimeout(p,d)),a=Number.isFinite(t.pollMs)&&t.pollMs>0?t.pollMs:5e3,c=Number.isFinite(t.timeoutMs)&&t.timeoutMs>0?t.timeoutMs:3e5,l=i(),u=null;for(;;){let d=await w0({id:n,chainId:r,maker:o,fetchImpl:t.fetchImpl,timeoutMs:t.requestTimeoutMs});if(!d.ok)return d;if(u=d.status,p0.includes(u))return{ok:!0,done:!0,settled:u===h0,status:u,id:Number(n)};if(i()-l>=c)return ae("kyber-not-settled",{id:Number(n),status:u,waitedMs:i()-l});await s(a)}}function G2({order:e=null,requiredOutWei:t=null,tokenUsd:n=null,referenceNativeUsd:r=null,tolerated:o=!1,gates:i=null,sellDecimals:s=null,buyDecimals:a=null,buySymbol:c=null,allowanceWei:l=null,allowanceConsent:u=!1,tokenIsNative:d=!1,symbol:p=null,decimals:m=null}={}){if(!e)return{ok:!1,blocked:!0,reason:"kyber-no-order",checks:[]};let w=ot.priceGateVerdict({amountInWei:e.makingAmount,amountOutWei:e.takingAmount,inDecimals:s,outDecimals:a,tokenUsd:Number(n)>0?Number(n):null,referenceUsd:Number(r)>0?Number(r):null,stableSteps:[],tolerated:!!o,gates:i}),y={ok:!0,amountOutWei:String(e.takingAmount),price:w,wrapped:{symbol:c,decimals:a}},b=ot.dexLegVerdict(y,t),x={ok:!b.blocked,checked:b.kind!=="unchecked"&&b.kind!=="unquoted",blocks:b.blocked===!0,kind:b.kind,reason:b.reason},I=pe.allowanceVerdict({tokenIsNative:d,allowanceWei:l,amountWei:e.makingAmount,consent:u===!0,symbol:p,decimals:Number.isFinite(Number(m))?Number(m):18});return{...pe.signingGateVerdict([x,I]),price:w,coverage:b,allowance:I}}var y0=Object.freeze({id:"kyberswap",kind:"kyber",venue:d0,shape:je,settles:"wrapped",networks:Oa,settlement:$e,orderFields:qr,plan:V2,settled:Y2,unsignedOrder:$2,sign:z2,submit:X2,status:w0,gate:G2});var q2="Permit2",md="0x000000000022D473030F116dDEE9F6B43aC78BA3",wd="0x0000000000000000000000000000000000000000",Q2=["EIP712Domain(","string name,","uint256 chainId,","address verifyingContract)"],i5=Q2.join(""),yd=[["reactor","address"],["swapper","address"],["nonce","uint256"],["deadline","uint256"],["additionalValidationContract","address"],["additionalValidationData","bytes"]],bd=[["token","address"],["startAmount","uint256"],["endAmount","uint256"],["recipient","address"]],di=[["info","OrderInfo"],["cosigner","address"],["baseInputToken","address"],["baseInputStartAmount","uint256"],["baseInputEndAmount","uint256"],["baseOutputs","DutchOutput[]"]],b0=[["permitted","TokenPermissions"],["spender","address"],["nonce","uint256"],["deadline","uint256"],["witness","V2DutchOrder"]],g0=[["token","address"],["amount","uint256"]],fi=(e,t)=>e+"("+t.map(n=>n[1]+" "+n[0]).join(",")+")",gd=fi("OrderInfo",yd),xd=fi("DutchOutput",bd),x0=fi("V2DutchOrder",di),Z2=fi("TokenPermissions",g0),s5=fi("PermitWitnessTransferFrom",b0)+xd+gd+Z2+x0,J2=x0+xd+gd;var Qr=e=>{throw new Error(e)},kd=e=>new TextEncoder().encode(String(e)),Ba=(...e)=>{let t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n},k0=e=>{let t=String(e).replace(/^0x/,"");t.length%2&&Qr("uniswapx-odd-hex");let n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++){let o=parseInt(t.slice(r*2,r*2+2),16);Number.isNaN(o)&&Qr("uniswapx-bad-hex"),n[r]=o}return n},eE=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},tE=e=>{if(typeof e=="bigint")return e;let t=String(e??"").trim();if(/^0x[0-9a-fA-F]+$/.test(t)||/^[0-9]+$/.test(t))return BigInt(t);Qr("uniswapx-bad-number")},Zr=(e,t)=>{let n=tE(e);n<0n&&Qr("uniswapx-negative"),n>=1n<<BigInt(t)&&Qr("uniswapx-overflow");let r=new Uint8Array(32),o=n;for(let i=31;i>=0&&o>0n;i--)r[i]=Number(o&0xffn),o>>=8n;return r},fr=e=>{let t=String(e??"").trim();/^(0x)?[0-9a-fA-F]{40}$/.test(t)||Qr("uniswapx-bad-address");let n=new Uint8Array(32);return n.set(k0(t.replace(/^0x/,"")),12),n},nE=e=>q(k0(e??"0x")),S0=e=>{let t=[];for(let[r,o]of yd){let i=e?e[r]:void 0;(i==null||o!=="bytes"&&i==="")&&t.push(r)}for(let[r]of di){if(r==="info"||r==="baseOutputs")continue;let o=e?e[r]:void 0;(o==null||o==="")&&t.push(r)}let n=e?e.baseOutputs:void 0;if(!Array.isArray(n)||n.length===0)return t.push("baseOutputs"),t;for(let r of n)for(let[o]of bd){let i=r?r[o]:void 0;(i==null||i==="")&&t.push("baseOutputs."+o)}return t},rE=e=>q(Ba(q(kd(gd)),fr(e.reactor),fr(e.swapper),Zr(e.nonce,256),Zr(e.deadline,256),fr(e.additionalValidationContract),nE(e.additionalValidationData))),oE=e=>q(Ba(q(kd(xd)),fr(e.token),Zr(e.startAmount,256),Zr(e.endAmount,256),fr(e.recipient))),iE=e=>q(Ba(...(e||[]).map(oE))),sE=e=>q(Ba(q(kd(J2)),rE(e),fr(e.cosigner),fr(e.baseInputToken),Zr(e.baseInputStartAmount,256),Zr(e.baseInputEndAmount,256),iE(e.baseOutputs))),v0=e=>eE(sE(e));var E0=({order:e,chainId:t,permit2:n=md})=>({domain:{name:q2,chainId:Number(t),verifyingContract:n},types:{EIP712Domain:[{name:"name",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],PermitWitnessTransferFrom:b0.map(([r,o])=>({name:r,type:o})),TokenPermissions:g0.map(([r,o])=>({name:r,type:o})),V2DutchOrder:di.map(([r,o])=>({name:r,type:o})),OrderInfo:yd.map(([r,o])=>({name:r,type:o})),DutchOutput:bd.map(([r,o])=>({name:r,type:o}))},primaryType:"PermitWitnessTransferFrom",message:{permitted:{token:e.baseInputToken,amount:String(e.baseInputEndAmount)},spender:e.reactor,nonce:String(e.nonce),deadline:String(e.deadline),witness:{info:{reactor:e.reactor,swapper:e.swapper,nonce:String(e.nonce),deadline:String(e.deadline),additionalValidationContract:e.additionalValidationContract,additionalValidationData:e.additionalValidationData},cosigner:e.cosigner,baseInputToken:e.baseInputToken,baseInputStartAmount:String(e.baseInputStartAmount),baseInputEndAmount:String(e.baseInputEndAmount),baseOutputs:(e.baseOutputs||[]).map(r=>({token:r.token,startAmount:String(r.startAmount),endAmount:String(r.endAmount),recipient:r.recipient}))}}});var aE="https://api.uniswap.org/v2",A0="/orders",_0="UniswapX",cE="0x4449Cd34d1eb1FEDCF02A1Be3834FfDe8E6A6180",lE="0x0000000000000000000000000000000000000000",pi=Object.freeze({1:{orderbook:aE,reactor:"0x00000011F84B9aa48e5f8aA8B9897600006289Be"}}),N0=["open","expired","error","cancelled","filled","insufficient-funds"],I0=["expired","error","cancelled","filled","insufficient-funds"],T0="filled";var be=(e,t={})=>({ok:!1,code:e,params:t});var uE=e=>{let t=pi[Number(e)];return t?t.orderbook:null},Jr=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),Pa=e=>{try{return BigInt(String(e))>0n}catch{return!1}},O0=e=>/^0x[0-9a-fA-F]{64}$/.test(String(e||""));function B0(e={}){let t=Number(e.chainId),n=pi[t];if(!n)return{...be("uniswapx-unknown-network",{chainId:Number.isFinite(t)?t:null}),known:Object.keys(pi).map(Number)};let r=e.swapper,o=e.recipient===void 0||e.recipient===null?r:e.recipient,i={reactor:e.reactor===void 0||e.reactor===null?n.reactor:e.reactor,swapper:r,nonce:e.nonce,deadline:e.deadline,additionalValidationContract:e.additionalValidationContract===void 0||e.additionalValidationContract===null?lE:e.additionalValidationContract,additionalValidationData:e.additionalValidationData===void 0||e.additionalValidationData===null?"0x":e.additionalValidationData,cosigner:e.cosigner===void 0||e.cosigner===null?cE:e.cosigner,baseInputToken:e.sellToken,baseInputStartAmount:e.sellAmountWei,baseInputEndAmount:e.sellAmountEndWei===void 0||e.sellAmountEndWei===null?e.sellAmountWei:e.sellAmountEndWei,baseOutputs:[{token:e.buyToken,startAmount:e.buyAmountWei,endAmount:e.buyAmountEndWei===void 0||e.buyAmountEndWei===null?e.buyAmountWei:e.buyAmountEndWei,recipient:o}]},s=S0(i);if(Jr(r)||s.push("swapper"),Jr(i.reactor)||s.push("reactor"),Jr(i.cosigner)||s.push("cosigner"),Jr(i.baseInputToken)||s.push("sellToken"),(!Pa(i.baseInputStartAmount)||!Pa(i.baseInputEndAmount))&&s.push("sellAmountWei"),(!Pa(i.baseOutputs[0].startAmount)||!Pa(i.baseOutputs[0].endAmount))&&s.push("buyAmountWei"),(!Jr(i.baseOutputs[0].token)||!Jr(i.baseOutputs[0].recipient))&&s.push("buyToken"),Number.isInteger(Number(i.deadline))||s.push("deadline"),s.length)return be("uniswapx-bad-order",{missing:[...new Set(s)]});try{let a=E0({order:i,chainId:t}),c=v0(i);return{ok:!0,chainId:t,owner:r,reactor:i.reactor,order:i,orderHash:c,typedData:a}}catch(a){return be("uniswapx-bad-order",{why:String(a&&a.message?a.message:a)})}}function dE(e={}){let t=B0(e);if(!t.ok)return t;let n=t.order.baseOutputs[0];return{ok:!0,provider:"uniswapx",venue:_0,shape:je,route:"uniswapx",expectedOutWei:String(n.endAmount),order:t.order,orderHash:t.orderHash,typedData:t.typedData,owner:t.owner,reactor:t.reactor,nativeOutput:String(n.token).toLowerCase()===wd,endsWith:{kind:"order-status",settledWhen:T0,final:[...I0],endpoint:A0}}}async function fE({typedData:e,wallet:t,address:n=null}={}){if(!e||typeof e!="object")return be("uniswapx-bad-order",{field:"typedData"});try{if(t&&typeof t.signTypedData=="function"){let o=await t.signTypedData(e);return typeof o!="string"||!/^0x[0-9a-fA-F]{130}$/.test(o)?be("uniswapx-sign-failed",{why:"bad-signature-shape"}):{ok:!0,signature:o}}let r=t&&typeof t.driver=="function"?t.driver():null;if(r&&typeof r.request=="function"){let o=n||(typeof t.address=="function"?await t.address():null),i=await r.request({method:"eth_signTypedData_v4",params:[o,JSON.stringify(e)]});return typeof i!="string"||!/^0x[0-9a-fA-F]{130}$/.test(i)?be("uniswapx-sign-failed",{why:"bad-signature-shape"}):{ok:!0,signature:i}}return be("uniswapx-sign-failed",{why:"no-wallet"})}catch(r){return be("uniswapx-sign-failed",{why:String(r&&r.code||r&&r.message||r)})}}async function pE({quote:e=null,signature:t=null,routing:n="DUTCH_V2",submitter:r=null,fetchImpl:o=null,timeoutMs:i=2e4}={}){if(typeof t!="string"||!/^0x[0-9a-fA-F]{130}$/.test(t))return be("uniswapx-bad-order",{field:"signature"});if(!e||typeof e!="object")return be("uniswapx-bad-order",{field:"quote"});let s=r==null||r===""?null:String(r);if(!s)return be("uniswapx-no-submitter",{field:"submitter"});let a=at({apiBase:s,fetchImpl:o,timeoutMs:i}),c=JSON.stringify({signature:t,quote:e,routing:n}),l;try{l=await a.tryJson("",{method:"POST",headers:{"content-type":"application/json"},body:c})}catch(p){return be("uniswapx-unreachable",{why:String(p&&p.params&&p.params.why||p&&p.code||p)})}if(!l||typeof l.ok!="boolean")return be("uniswapx-bad-response",{where:"submit"});if(!l.ok)return be("uniswapx-refused",{status:l.status,stage:"submit"});let u=l.body&&typeof l.body=="object"?l.body:null;if(!u||typeof u.orderId!="string"||u.orderId==="")return be("uniswapx-bad-response",{where:"submit",field:"orderId"});let d=u.orderStatus;return typeof d!="string"||!N0.includes(d)?be("uniswapx-bad-response",{where:"submit",field:"orderStatus"}):{ok:!0,orderId:u.orderId,orderStatus:d,requestId:typeof u.requestId=="string"?u.requestId:null}}async function P0({orderHash:e,chainId:t=null,fetchImpl:n=null,timeoutMs:r=2e4,api:o=null}={}){let i=Number(t),s=o?String(o):Number.isFinite(i)?uE(i):null;if(!s)return be("uniswapx-unknown-network",{chainId:Number.isFinite(i)?i:null});if(!O0(e))return be("uniswapx-bad-order",{field:"orderHash"});let a=at({apiBase:s,fetchImpl:n,timeoutMs:r}),c;try{c=await a.tryJson(A0+"?orderHash="+e)}catch(p){return be("uniswapx-unreachable",{why:String(p&&p.params&&p.params.why||p&&p.code||p)})}if(!c||typeof c.ok!="boolean")return be("uniswapx-bad-response",{where:"orders"});if(!c.ok)return be("uniswapx-refused",{status:c.status,stage:"orders"});let l=c.body&&c.body.orders;if(!Array.isArray(l))return be("uniswapx-bad-response",{where:"orders"});let u=l.find(p=>p&&String(p.orderHash||"").toLowerCase()===String(e).toLowerCase())||l[0]||null;if(!u)return be("uniswapx-order-unknown",{orderHash:e});let d=u.orderStatus;return typeof d!="string"||!N0.includes(d)?be("uniswapx-bad-response",{where:"orderStatus",got:typeof d=="string"?d:null}):{ok:!0,status:d,order:u}}async function hE(e={},t={}){let{orderHash:n,chainId:r=null}=e;if(!O0(n))return be("uniswapx-bad-order",{field:"orderHash"});let o=typeof t.now=="function"?t.now:()=>Date.now(),i=typeof t.sleep=="function"?t.sleep:u=>new Promise(d=>setTimeout(d,u)),s=Number.isFinite(t.pollMs)&&t.pollMs>0?t.pollMs:5e3,a=Number.isFinite(t.timeoutMs)&&t.timeoutMs>0?t.timeoutMs:3e5,c=o(),l=null;for(;;){let u=await P0({orderHash:n,chainId:r,fetchImpl:t.fetchImpl,timeoutMs:t.requestTimeoutMs,api:t.api});if(!u.ok)return u;if(l=u.status,I0.includes(l))return{ok:!0,done:!0,settled:l===T0,status:l,orderHash:n};if(o()-c>=a)return be("uniswapx-not-settled",{orderHash:n,status:l,waitedMs:o()-c});await i(s)}}function mE({order:e=null,requiredOutWei:t=null,tokenUsd:n=null,referenceNativeUsd:r=null,tolerated:o=!1,gates:i=null,sellDecimals:s=null,buyDecimals:a=null,buySymbol:c=null,allowanceWei:l=null,allowanceConsent:u=!1,tokenIsNative:d=!1,symbol:p=null,decimals:m=null}={}){if(!e)return{ok:!1,blocked:!0,reason:"uniswapx-no-order",checks:[]};let w=Array.isArray(e.baseOutputs)&&e.baseOutputs.length?e.baseOutputs[0]:null,y=w?w.endAmount:null,b=ot.priceGateVerdict({amountInWei:e.baseInputEndAmount,amountOutWei:y,inDecimals:s,outDecimals:a,tokenUsd:Number(n)>0?Number(n):null,referenceUsd:Number(r)>0?Number(r):null,stableSteps:[],tolerated:!!o,gates:i}),x={ok:!0,amountOutWei:y===null?null:String(y),price:b,wrapped:{symbol:c,decimals:a}},I=ot.dexLegVerdict(x,t),E={ok:!I.blocked,checked:I.kind!=="unchecked"&&I.kind!=="unquoted",blocks:I.blocked===!0,kind:I.kind,reason:I.reason},U=pe.allowanceVerdict({tokenIsNative:d,allowanceWei:l,amountWei:e.baseInputEndAmount,consent:u===!0,symbol:p,decimals:Number.isFinite(Number(m))?Number(m):18});return{...pe.signingGateVerdict([E,U]),price:b,coverage:I,allowance:U}}var C0=Object.freeze({id:"uniswapx",kind:"uniswapx",venue:_0,shape:je,settles:"native",networks:pi,settlement:pi[1].reactor,permit2:md,nativeToken:wd,orderFields:di,plan:dE,settled:hE,buildIntent:B0,sign:fE,submit:pE,status:P0,gate:mE});var wE="Permit2",Ca="0x000000000022D473030F116dDEE9F6B43aC78BA3",Sd="0x0000000000000000000000000000000000000000",yE="0x0000000000000000000000000000000000000002",bE="0x24856bc3",R0=Object.freeze({v3SwapExactIn:0,sweep:4,wrapEth:11,unwrapWeth:12}),gE=3,xE=["EIP712Domain(","string name,","uint256 chainId,","address verifyingContract)"],p5=xE.join(""),vd=[["reactor","address"],["swapper","address"],["nonce","uint256"],["deadline","uint256"]],Ed=[["token","address"],["amount","uint256"],["recipient","address"]],Ad=[["token","address"],["startAmount","uint256"],["endAmount","uint256"],["startTime","uint256"],["endTime","uint256"]],Ra=[["info","RelayOrderInfo"],["input","Input"],["fee","FeeEscalator"],["universalRouterCalldata","bytes"]],H0=[["token","address"],["amount","uint256"]],L0=[["permitted","TokenPermissions[]"],["spender","address"],["nonce","uint256"],["deadline","uint256"],["witness","RelayOrder"]],to=(e,t)=>e+"("+t.map(n=>n[1]+" "+n[0]).join(",")+")",_d=to("RelayOrderInfo",vd),Nd=to("Input",Ed),Id=to("FeeEscalator",Ad),F0=to("RelayOrder",Ra),kE=to("TokenPermissions",H0),SE=F0+Id+Nd+_d,h5=to("PermitBatchWitnessTransferFrom",L0)+Id+Nd+F0+_d+kE;var Mn=e=>{throw new Error(e)},Ha=e=>new TextEncoder().encode(String(e)),Un=(...e)=>{let t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n},hi=e=>{let t=String(e).replace(/^0x/,"");t.length%2&&Mn("uniswaprelay-odd-hex");let n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++){let o=parseInt(t.slice(r*2,r*2+2),16);Number.isNaN(o)&&Mn("uniswaprelay-bad-hex"),n[r]=o}return n},Td=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},D0=e=>{if(typeof e=="bigint")return e;let t=String(e??"").trim();if(/^0x[0-9a-fA-F]+$/.test(t)||/^[0-9]+$/.test(t))return BigInt(t);Mn("uniswaprelay-bad-number")},pt=(e,t)=>{let n=D0(e);return n<0n&&Mn("uniswaprelay-negative"),n>=1n<<BigInt(t)&&Mn("uniswaprelay-overflow"),hi("0x"+n.toString(16).padStart(64,"0"))},pr=e=>{let t=String(e??"").trim();/^(0x)?[0-9a-fA-F]{40}$/.test(t)||Mn("uniswaprelay-bad-address");let n=new Uint8Array(32);return n.set(hi(t.replace(/^0x/,"")),12),n},vE=e=>pt(e?1:0,8);var U0=e=>{let t=[];for(let[n]of vd){let r=e&&e.info?e.info[n]:void 0;(r==null||r==="")&&t.push("info."+n)}for(let[n]of Ed){let r=e&&e.input?e.input[n]:void 0;(r==null||r==="")&&t.push("input."+n)}for(let[n]of Ad){let r=e&&e.fee?e.fee[n]:void 0;(r==null||r==="")&&t.push("fee."+n)}return(!e||e.universalRouterCalldata===void 0||e.universalRouterCalldata===null)&&t.push("universalRouterCalldata"),t},EE=e=>q(Un(q(Ha(_d)),pr(e.info.reactor),pr(e.info.swapper),pt(e.info.nonce,256),pt(e.info.deadline,256))),AE=e=>q(Un(q(Ha(Nd)),pr(e.token),pt(e.amount,256),pr(e.recipient))),_E=e=>q(Un(q(Ha(Id)),pr(e.token),pt(e.startAmount,256),pt(e.endAmount,256),pt(e.startTime,256),pt(e.endTime,256))),NE=e=>q(Un(q(Ha(SE)),EE(e),AE(e.input),_E(e.fee),q(hi(e.universalRouterCalldata)))),M0=e=>Td(NE(e));var j0=({order:e,chainId:t,permit2:n=Ca})=>({domain:{name:wE,chainId:Number(t),verifyingContract:n},types:{EIP712Domain:[{name:"name",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],PermitBatchWitnessTransferFrom:L0.map(([r,o])=>({name:r,type:o})),TokenPermissions:H0.map(([r,o])=>({name:r,type:o})),RelayOrder:Ra.map(([r,o])=>({name:r,type:o})),RelayOrderInfo:vd.map(([r,o])=>({name:r,type:o})),Input:Ed.map(([r,o])=>({name:r,type:o})),FeeEscalator:Ad.map(([r,o])=>({name:r,type:o}))},primaryType:"PermitBatchWitnessTransferFrom",message:{permitted:[{token:e.input.token,amount:String(e.input.amount)},{token:e.fee.token,amount:String(e.fee.endAmount)}],spender:e.info.reactor,nonce:String(e.info.nonce),deadline:String(e.info.deadline),witness:{info:{reactor:e.info.reactor,swapper:e.info.swapper,nonce:String(e.info.nonce),deadline:String(e.info.deadline)},input:{token:e.input.token,amount:String(e.input.amount),recipient:e.input.recipient},fee:{token:e.fee.token,startAmount:String(e.fee.startAmount),endAmount:String(e.fee.endAmount),startTime:String(e.fee.startTime),endTime:String(e.fee.endTime)},universalRouterCalldata:e.universalRouterCalldata}}});var Od=e=>{let t=String(e).replace(/^0x/,"").toLowerCase();return t.length%64===0?t:t.padEnd(Math.ceil(t.length/64)*64,"0")},eo=e=>D0(e).toString(16).padStart(64,"0");var IE=e=>{let t=e.map(s=>String(s).replace(/^0x/,"")),n=eo(t.length),r=[],o=t.length*32;for(let s of t)r.push(eo(o)),o+=32+Math.ceil(s.length/64)*32;let i=t.map(s=>eo(s.length/2)+Od(s)).join("");return"0x"+n+r.join("")+i},TE=(e,t)=>{(!Array.isArray(e)||e.length!==t.length+1)&&Mn("uniswaprelay-bad-path");let n="";for(let r=0;r<t.length;r++){n+=String(e[r]).replace(/^0x/,"").toLowerCase();let o=Number(t[r]);(!Number.isInteger(o)||o<0||o>16777215)&&Mn("uniswaprelay-bad-fee"),n+=o.toString(16).padStart(gE*2,"0")}return n+=String(e[e.length-1]).replace(/^0x/,"").toLowerCase(),"0x"+n},OE=({recipient:e,amountInWei:t,amountOutMinimumWei:n,path:r,payerIsUser:o=!1})=>{let i=String(r).replace(/^0x/,""),s=Un(pr(e),pt(t,256),pt(n,256),pt(160,256),vE(o)),a=Un(pt(i.length/2,256),hi("0x"+Od(i)));return Td(Un(s,a))},BE=({recipient:e,amountMinimumWei:t})=>Td(Un(pr(e),pt(t,256))),K0=({tokenIn:e,weth:t,fee:n,amountInWei:r,amountOutMinimumWei:o,recipient:i})=>{let s=TE([e,t],[n]),a="0x"+R0.v3SwapExactIn.toString(16).padStart(2,"0")+R0.unwrapWeth.toString(16).padStart(2,"0"),c=OE({recipient:yE,amountInWei:r,amountOutMinimumWei:o,path:s,payerIsUser:!1}),l=BE({recipient:i,amountMinimumWei:o}),u=a.replace(/^0x/,""),d=eo(hi(a).length)+Od(u),p=IE([c,l]).replace(/^0x/,""),m=64,w=64+d.length/2;return bE+eo(m)+eo(w)+d+p};var W0="0x0000000000A4e21E2597DCac987455c48b12edBF",V0="0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD",$0=["Uniswap","Relay"].join(" "),Cd=Object.freeze({1:{reactor:W0,universalRouter:V0,permit2:Ca}}),PE=["Relay(","bytes32,","address,","address,","uint256)"],z0=()=>PE.join(""),CE=z0(),La=(()=>{let e="0x";for(let t of q(z0()))e+=t.toString(16).padStart(2,"0");return e})();var RE=["filled","expired"],Rd="filled";var Te=(e,t={})=>({ok:!1,code:e,params:t});var Hd=e=>Cd[Number(e)]||null,no=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),Bd=e=>{try{return BigInt(String(e))>0n}catch{return!1}},X0=e=>/^0x[0-9a-fA-F]{64}$/.test(String(e||"")),Pd=e=>/^0x[0-9a-fA-F]{130}$/.test(String(e||""));function Y0(e={}){let t=Number(e.chainId),n=Hd(t);if(!n)return{...Te("uniswap-relay-unknown-network",{chainId:Number.isFinite(t)?t:null}),known:Object.keys(Cd).map(Number)};let r=e.swapper,o=e.recipient===void 0||e.recipient===null?r:e.recipient,i=e.universalRouter===void 0||e.universalRouter===null?n.universalRouter:e.universalRouter,s=e.wrappedToken,a=[];if(no(r)||a.push("swapper"),(!no(o)||String(o).toLowerCase()===Sd)&&a.push("recipient"),no(e.sellToken)||a.push("sellToken"),no(s)||a.push("wrappedToken"),no(i)||a.push("universalRouter"),Number.isInteger(Number(e.fee))||a.push("fee"),Bd(e.sellAmountWei)||a.push("sellAmountWei"),Bd(e.buyAmountWei)||a.push("buyAmountWei"),no(e.feeToken)||a.push("feeToken"),Bd(e.feeEndAmountWei)||a.push("feeEndAmountWei"),Number.isInteger(Number(e.deadline))||a.push("deadline"),a.length)return Te("uniswap-relay-bad-order",{missing:[...new Set(a)]});let c=e.feeStartAmountWei===void 0||e.feeStartAmountWei===null?e.feeEndAmountWei:e.feeStartAmountWei,l=e.feeStartTime===void 0||e.feeStartTime===null?e.deadline:e.feeStartTime,u=e.feeEndTime===void 0||e.feeEndTime===null?e.deadline:e.feeEndTime,d;try{d=K0({tokenIn:e.sellToken,weth:s,fee:e.fee,amountInWei:e.sellAmountWei,amountOutMinimumWei:e.buyAmountWei,recipient:o})}catch(w){return Te("uniswap-relay-bad-order",{why:String(w&&w.message?w.message:w)})}let p={info:{reactor:n.reactor,swapper:r,nonce:e.nonce===void 0||e.nonce===null?"0":String(e.nonce),deadline:String(e.deadline)},input:{token:e.sellToken,amount:String(e.sellAmountWei),recipient:i},fee:{token:e.feeToken,startAmount:String(c),endAmount:String(e.feeEndAmountWei),startTime:String(l),endTime:String(u)},universalRouterCalldata:d},m=U0(p);if(m.length)return Te("uniswap-relay-bad-order",{missing:m});try{let w=j0({order:p,chainId:t}),y=M0(p);return{ok:!0,chainId:t,owner:r,reactor:p.info.reactor,order:p,orderHash:y,calldata:d,typedData:w}}catch(w){return Te("uniswap-relay-bad-order",{why:String(w&&w.message?w.message:w)})}}function HE(e={}){let t=Y0(e);return t.ok?{ok:!0,provider:"uniswaprelay",venue:$0,shape:je,route:"uniswaprelay",expectedOutWei:String(e.buyAmountWei),order:t.order,orderHash:t.orderHash,typedData:t.typedData,calldata:t.calldata,owner:t.owner,reactor:t.reactor,nativeOutput:!0,endsWith:{kind:"onchain-effect",settledWhen:Rd,final:[...RE],event:CE}}:t}async function LE({typedData:e,wallet:t,address:n=null}={}){if(!e||typeof e!="object")return Te("uniswap-relay-bad-order",{field:"typedData"});try{if(t&&typeof t.signTypedData=="function"){let o=await t.signTypedData(e);return Pd(o)?{ok:!0,signature:o}:Te("uniswap-relay-sign-failed",{why:"bad-signature-shape"})}let r=t&&typeof t.driver=="function"?t.driver():null;if(r&&typeof r.request=="function"){let o=n||(typeof t.address=="function"?await t.address():null),i=await r.request({method:"eth_signTypedData_v4",params:[o,JSON.stringify(e)]});return Pd(i)?{ok:!0,signature:i}:Te("uniswap-relay-sign-failed",{why:"bad-signature-shape"})}return Te("uniswap-relay-sign-failed",{why:"no-wallet"})}catch(r){return Te("uniswap-relay-sign-failed",{why:String(r&&r.code||r&&r.message||r)})}}function FE({order:e=null,signature:t=null,chainId:n=null}={}){let r=Number(n);return Hd(r)?!e||typeof e!="object"?Te("uniswap-relay-bad-order",{field:"order"}):Pd(t)?Te("uniswap-relay-no-discovery",{reactorIsPermissionless:!0,documentedSubmissionEndpoint:null,reason:"undocumented"}):Te("uniswap-relay-bad-order",{field:"signature"}):Te("uniswap-relay-unknown-network",{chainId:Number.isFinite(r)?r:null})}var DE=async({driver:e=null,getLogs:t=null,reactor:n,orderHash:r,fromBlock:o="earliest",toBlock:i="latest"})=>{try{return typeof t=="function"?{ok:!0,logs:await t({reactor:n,orderHash:r,fromBlock:o,toBlock:i,topic0:La})}:e&&typeof e.request=="function"?{ok:!0,logs:await e.request({method:"eth_getLogs",params:[{address:n,fromBlock:o,toBlock:i,topics:[La,r]}]})}:Te("uniswap-relay-unreachable",{why:"no-driver"})}catch(s){return Te("uniswap-relay-unreachable",{why:String(s&&s.code||s&&s.message||s)})}};async function G0({orderHash:e,chainId:t=null,reactor:n=null,deadline:r=null,driver:o=null,getLogs:i=null,fromBlock:s="earliest",toBlock:a="latest",nowSec:c=null}={}){let l=Number(t),u=Hd(l),d=n||(u?u.reactor:null);if(!d)return Te("uniswap-relay-unknown-network",{chainId:Number.isFinite(l)?l:null});if(!X0(e))return Te("uniswap-relay-bad-order",{field:"orderHash"});let p=await DE({driver:o,getLogs:i,reactor:d,orderHash:e,fromBlock:s,toBlock:a});if(!p.ok)return p;let m=p.logs;if(!Array.isArray(m))return Te("uniswap-relay-bad-response",{where:"logs",got:typeof m});let w=m.filter(y=>{if(!y||!Array.isArray(y.topics))return!1;let b=String(y.topics[0]||"").toLowerCase(),x=String(y.topics[1]||"").toLowerCase();return b===La.toLowerCase()&&x===String(e).toLowerCase()});if(m.length>0&&w.length===0)return Te("uniswap-relay-bad-response",{where:"logs",detail:"topics-mismatch"});if(w.length>0)return{ok:!0,status:Rd,log:w[0]};if(r!=null){let y=typeof c=="function"?c():Number.isFinite(c)?c:Math.floor(Date.now()/1e3);if(Number(r)<y)return{ok:!0,status:"expired"}}return{ok:!0,status:"open"}}async function UE(e={},t={}){let{orderHash:n,chainId:r=null,reactor:o=null,deadline:i=null}=e;if(!X0(n))return Te("uniswap-relay-bad-order",{field:"orderHash"});let s=typeof t.now=="function"?t.now:()=>Date.now(),a=typeof t.sleep=="function"?t.sleep:p=>new Promise(m=>setTimeout(m,p)),c=Number.isFinite(t.pollMs)&&t.pollMs>0?t.pollMs:5e3,l=Number.isFinite(t.timeoutMs)&&t.timeoutMs>0?t.timeoutMs:3e5,u=s(),d=null;for(;;){let p=await G0({orderHash:n,chainId:r,reactor:o,deadline:i,driver:t.driver||null,getLogs:t.getLogs||null,fromBlock:t.fromBlock===void 0?"earliest":t.fromBlock,toBlock:t.toBlock===void 0?"latest":t.toBlock,nowSec:t.nowSec===void 0?null:t.nowSec});if(!p.ok)return p;if(d=p.status,d===Rd)return{ok:!0,done:!0,settled:!0,status:d,orderHash:n};if(d==="expired")return{ok:!0,done:!0,settled:!1,status:d,orderHash:n};if(s()-u>=l)return Te("uniswap-relay-not-settled",{orderHash:n,status:d,waitedMs:s()-u});await a(c)}}function ME({order:e=null,amountInWei:t=null,expectedOutWei:n=null,requiredOutWei:r=null,tokenUsd:o=null,referenceNativeUsd:i=null,tolerated:s=!1,gates:a=null,sellDecimals:c=null,buyDecimals:l=null,buySymbol:u=null,allowanceWei:d=null,allowanceConsent:p=!1,tokenIsNative:m=!1,symbol:w=null,decimals:y=null}={}){if(!e)return{ok:!1,blocked:!0,reason:"uniswap-relay-no-order",checks:[]};let b=t??(e.input?e.input.amount:null),x=n??null,I=ot.priceGateVerdict({amountInWei:b,amountOutWei:x,inDecimals:c,outDecimals:l,tokenUsd:Number(o)>0?Number(o):null,referenceUsd:Number(i)>0?Number(i):null,stableSteps:[],tolerated:!!s,gates:a}),E={ok:!0,amountOutWei:x===null?null:String(x),price:I,wrapped:{symbol:u,decimals:l}},U=ot.dexLegVerdict(E,r??x),S={ok:!U.blocked,checked:U.kind!=="unchecked"&&U.kind!=="unquoted",blocks:U.blocked===!0,kind:U.kind,reason:U.reason},B=pe.allowanceVerdict({tokenIsNative:m,allowanceWei:d,amountWei:b,consent:p===!0,symbol:w,decimals:Number.isFinite(Number(y))?Number(y):18});return{...pe.signingGateVerdict([S,B]),price:I,coverage:U,allowance:B}}var q0=Object.freeze({id:"uniswaprelay",kind:"uniswaprelay",venue:$0,shape:je,settles:"native",networks:Cd,settlement:W0,universalRouter:V0,permit2:Ca,nativeToken:Sd,eventTopic:La,orderFields:Ra,plan:HE,settled:UE,buildIntent:Y0,sign:LE,submit:FE,status:G0,gate:ME});var jE="evm",Z0=e=>Number(e.chainId),KE=(e,t)=>{let n=Z0(t),r=Number(e);return Number.isFinite(r)&&Number.isFinite(n)&&r===n},J0="0x70a08231",Q0=e=>{try{return BigInt(e).toString(10)}catch{return null}},WE=e=>String(e).replace(/^0x/,"").toLowerCase().padStart(64,"0");async function VE({driver:e,address:t,tokens:n}){let r=[];for(let o of n){let i=null;try{if(o.address===null)i=Q0(await e.request({method:"eth_getBalance",params:[t,"latest"]}));else{let s=J0+WE(t);i=Q0(await e.request({method:"eth_call",params:[{to:o.address,data:s},"latest"]}))}}catch{i=null}r.push({token:o.id,symbol:o.symbol,decimals:o.decimals,amount:i})}return r}var eb={declared:{id:"declared",kind:"declared",shape:ai,async plan(){return{ok:!1,code:"not-implemented",stage:3}}},cowswap:s0,kyberswap:y0,uniswapx:C0,uniswaprelay:q0},ro=()=>Object.keys(eb).sort(),Fa=e=>eb[e]||null,$E=e=>{let t=Fa(e);return t?t.shape!==ai?{ok:!1,reason:"provider-not-synchronous",provider:t.id,shape:t.shape===void 0?null:t.shape}:{ok:!0,provider:t}:{ok:!1,reason:"provider-unknown",provider:typeof e=="string"?e:null,known:ro()}},zE=e=>{let t=Fa(e);if(!t)return{ok:!1,reason:"provider-unknown",provider:typeof e=="string"?e:null,known:ro()};if(t.shape!==je)return{ok:!1,reason:"provider-not-asynchronous",provider:t.id,shape:t.shape===void 0?null:t.shape};let n=ed(t);return n.ok?{ok:!0,provider:t}:{ok:!1,reason:n.reason,provider:t.id,shape:t.shape===void 0?null:t.shape,missing:n.missing??null}},XE=e=>{let t=Fa(e);if(!t)return{ok:!1,reason:"provider-unknown",provider:typeof e=="string"?e:null,known:ro()};let n=ed(t);return n.ok?{ok:!0,provider:t}:{ok:!1,reason:n.reason,provider:t.id,shape:n.shape??null,missing:n.missing??null}},Ld=Object.freeze({NATIVE:"native",WRAPPED:"wrapped"}),tb=e=>e&&e.settles?e.settles:null,YE=e=>{let t=tb(e),n=e&&e.id?e.id:null;return t===Ld.NATIVE?{ok:!0,settles:t,provider:n}:t===Ld.WRAPPED?{ok:!1,reason:"settles-wrapped",settles:t,provider:n}:{ok:!1,reason:"settles-unstated",settles:null,provider:n}};var GE=Object.freeze({evm:Object.freeze({vm:"evm",addressFormat:"hex-20",settlementKind:"contract",refKind:"address",txRef:"hash"}),tron:Object.freeze({vm:"tron",addressFormat:"base58check",settlementKind:"contract",refKind:"address",txRef:"hash"}),solana:Object.freeze({vm:"solana",addressFormat:"base58",settlementKind:"program",refKind:"pda",txRef:"signature"}),bitcoin:Object.freeze({vm:"bitcoin",addressFormat:"base58check-or-bech32-or-bech32m",settlementKind:"utxo-script",refKind:"script",txRef:"txid"})}),nb=e=>GE[e]||null;var rb={evm:Fd},ob=()=>Object.keys(rb).sort(),oo=e=>rb[e]||null,qE=e=>(oe.CHAINS||[]).find(t=>t&&t.id===e)||null,Dd=e=>{let t=qE(e);return t&&t.vm?t.vm:null},ib=e=>{let t=Dd(e);return t?nb(t):null};var QE=e=>{let t=typeof oe.chainByChainId=="function"?oe.chainByChainId(e):null;t||C("bad-input",{field:"chain.chainId",unknown:e,why:"no-network-with-this-chainId"});let n=oe.tokensOf(t.id),r=[t.native,...t.tokens||[]].filter(Boolean),o=i=>String(i.symbol).toLowerCase();return n.map(o).join("|")!==r.map(o).join("|")&&C("bad-input",{field:"chain.tokens",unknown:e,why:"tokens-belong-to-another-network"}),n},ZE=e=>({id:e.id,name:e.name,vm:e.vm||null,settlementProfile:ib(e.id),chainId:e.chainId,nativeSymbol:e.native&&e.native.symbol?e.native.symbol:null,tokens:QE(e.chainId).map(t=>({id:String(t.symbol).toLowerCase(),symbol:String(t.symbol),address:t.address||null,decimals:Number(t.decimals)})),dex:e.dex?{routes:e.dex.routes||[]}:null,escrow:e.escrow?{address:e.escrow.address||null,mode:e.escrow.mode||null,deploymentBlock:Number.isSafeInteger(e.escrow.deploymentBlock)?e.escrow.deploymentBlock:null}:null}),Ud=Object.freeze({swaps:"/swaps",swap:"/swaps/{id}",evmSwaps:"/evm-swaps",orderQuote:"/order-quote",orderSell:"/order-sell",revealedHalf:"/escrow/revealed-half",swept:"/swaps/{id}/swept"}),sb=Object.freeze({mainnet:[{url:"https://xmr-node.cakewallet.com:18081",operator:"Cake Wallet"},{url:"https://xmr.cryptostorm.is",operator:"cryptostorm"},{url:"https://node.monero.fail",operator:"monero.fail"},{url:"https://mainnet.xmr.kernal.eu:18089",operator:"kernal.eu"}],stagenet:[{url:"https://xmr-stagenet.ninsei.finance",operator:"Ninsei"},{url:"https://stagenet.xmr.kernal.eu:38089",operator:"kernal.eu"}]}),JE=e=>typeof e=="string"&&e||e&&typeof e=="object"&&typeof e.url=="string"&&e.url,Md=e=>Array.isArray(e)&&e.every(JE),eA=(e,t)=>{let n=e&&e.nodes,r=e&&e.addNodes,o={mainnet:[...sb.mainnet],stagenet:[...sb.stagenet]};if(n!=null)if(Md(n))t in o||C("bad-input",{field:"nodes",network:t}),o[t]=[...n];else if(n&&typeof n=="object"&&!Array.isArray(n))for(let i of Object.keys(n))i in o||C("bad-input",{field:"nodes",unknown:i,known:Object.keys(o)}),Md(n[i])||C("bad-input",{field:"nodes."+i}),o[i]=[...n[i]];else C("bad-input",{field:"nodes"});return r!=null&&(Md(r)||C("bad-input",{field:"addNodes"}),t in o||C("bad-input",{field:"addNodes",network:t}),o[t]=[...o[t],...r]),o},tA=(e,t)=>e.replace(/\{([a-z]+)\}/g,(n,r)=>{let o=t?t[r]:void 0;return(o==null||o==="")&&C("bad-input",{field:"route.param",param:r}),encodeURIComponent(String(o))}),nA=e=>{let t=e&&e.routes||{};for(let n of Object.keys(t))n in Ud||C("bad-input",{field:"routes",unknown:n,known:Object.keys(Ud)}),(typeof t[n]!="string"||!t[n])&&C("bad-input",{field:"routes."+n});return{...Ud,...t}},jd=e=>Number.isFinite(Number(e))&&Number(e)>0?Number(e):null,rA=e=>{let t=e&&e.watch||{},n=t.pollMs===void 0?jd(oe.API&&oe.API.pollMs)||5e3:Number(t.pollMs);(!Number.isFinite(n)||n<=0)&&C("bad-input",{field:"watch.pollMs"});let r=oe.MONERO||{},o=(jd(r.blockTimeReal)||12e4)*(jd(r.confirmTarget)||10),i=t.timeoutMs===void 0?o:Number(t.timeoutMs);return(!Number.isFinite(i)||i<=0)&&C("bad-input",{field:"watch.timeoutMs"}),{pollMs:n,timeoutMs:i}},oA=(e,t)=>{let n=t&&t.endpoints||{},r=n.explorer||{},o=n.rpc||{},i=s=>typeof s=="string"&&s?s:null;return{explorer:{evmTx:i(r.evmTx)||i(e.explorerTx),evmAddr:i(r.evmAddr)||i(e.explorerAddr),evmName:i(r.evmName)||i(e.explorerName),xmrTx:i(r.xmrTx)},rpc:{evm:i(o.evm)||i(e.rpcUrl),monero:i(o.monero)}}};function ab(e){let t=oe.CHAINS.map(ZE),n=t.find(y=>y.id===e.settlement.chain)||null;n||C("bad-input",{field:"settlement.chain",known:t.map(y=>y.id)});let r=oe.CHAINS.find(y=>y.id===e.settlement.chain)||{},o=nA(e),i=rA(e),s=oA(r,e),a=eA(e,e.xmrNetwork),c=e.settlement.vm||n.vm;c||C("bad-input",{field:"settlement.vm"}),c!==n.vm&&C("bad-input",{field:"settlement.vm",chain:n.id,vm:n.vm,got:c}),oo(c)||C("not-implemented",{surface:"settlement.vm",vm:c,implemented:ob()});let u=ro(),d=Array.isArray(e.routing&&e.routing.prefer)&&e.routing.prefer.length?e.routing.prefer.map(y=>String(y)):u.filter(y=>y==="declared");for(let y of d)u.includes(y)||C("bad-input",{field:"routing.prefer",unknown:y,known:u});let p=["mainnet","stagenet","testnet","fakechain"],m=[...new Set([...Object.values(oe.XMR_NETWORKS||{}),...p])];m.includes(e.xmrNetwork)||C("bad-input",{field:"xmrNetwork",known:m});let w=oe.SIGNING_GUARDS||{};return{settlement:{chain:n,vm:c},chains:t,xmrNetworks:m,assetsBase:e.assetsBase,apiBase:e.apiBase,mode:e.mode,limits:{minAmount:null,maxAmount:null,stepAmount:null,xmrConfirmTarget:oe.MONERO.confirmTarget??null,watchPollMs:i.pollMs,watchTimeoutMs:i.timeoutMs,xmrConfirmations:oe.MONERO.confirmTarget??10,xmrBlockTimeSec:Math.round((oe.MONERO.blockTimeReal??12e4)/1e3),readyLeadWarnSec:w.readyLeadWarnSec??null,quotePollMs:oe.API.pollMs??5e3,httpTimeoutMs:oe.API.timeoutMs??2e4},routing:{providers:u,prefer:d},routes:{...o},endpoints:s,xmrNodes:a,nodesFor:y=>a&&a[y]?a[y]:[],route:(y,b)=>(y in o||C("bad-input",{field:"route",unknown:y,known:Object.keys(o)}),tA(o[y],b)),codes:{steps:wa,checks:ya,errors:Yr}}}function cb({chain:e,knownFactoryCodes:t}={}){return t??oe.knownFactoryCodesFor(e)}function lb({chain:e,knownImplementationCodes:t}={}){if(t!=null)return t;let n=typeof e=="string"?e:e&&e.id,r=n?oe.chainById(n):null;return!r||String(r.id)!==String(n)?null:oe.knownImplementationCodesFor(e)}var io="0.56.1";var iA={keccak256:q,secp256k1:Ue};var Kd=e=>ld(e);var mi=e=>zy({crypto:iA,quote:e});cs();var Wd=10n**BigInt(12);function ub(e,{trim:t=!0}={}){let n;try{n=BigInt(e)}catch{throw new RangeError("formatXmr: expected whole atomic units")}if(typeof e=="number"&&!Number.isInteger(e))throw new RangeError("formatXmr: expected whole atomic units");let r=n<0n,o=r?-n:n,i=o/Wd,s=(o%Wd).toString().padStart(12,"0"),a=t?s.replace(/0+$/,""):s,c=a?`${i}.${a}`:`${i}`;return r?`-${c}`:c}function db(e){let t=String(e??"").trim().replace(/\s+/g,"");if(!t||t.includes(".")&&t.includes(","))return null;let n=t.replace(",",".");if(!/^\d+(\.\d*)?$/.test(n))return null;let[r,o=""]=n.split("."),i=o.replace(/0+$/,"");return i.length>12?null:BigInt(r)*Wd+BigInt((i||"0").padEnd(12,"0"))}function sA(e,t,n,r){Lr(e);let o=qs({dkLen:32,asyncTick:10},r),{c:i,dkLen:s,asyncTick:a}=o;if(Ce(i,"c"),Ce(s,"dkLen"),Ce(a,"asyncTick"),i<1)throw new Error('"c" (iterations) must be >= 1');if(s<1)throw new Error('"dkLen" must be >= 1');if(s>(2**32-1)*e.outputLen)throw new Error("derived key too long");let c=Nu(t,"password");try{let l=Nu(n,"salt");try{let u=new Uint8Array(s),{iHash:d,oHash:p,outputLen:m}=ga.create(e,c),w=new Uint8Array(m),y=aA(d,p,l,w);return{c:i,dkLen:s,asyncTick:a,DK:u,outputLen:m,eng:y}}finally{typeof n=="string"&&tt(l)}}finally{typeof t=="string"&&tt(c)}}function aA(e,t,n,r){let o=new Uint8Array(4),i=Dr(o),s=e._cloneInto().update(n),a=t._cloneInto(),c=e._cloneInto,l=t._cloneInto;return{u1:(u,d)=>{i.setInt32(0,u,!1),s._cloneInto(a).update(o).digestInto(r),t._cloneInto(a).update(r).digestInto(r),d.set(r.subarray(0,d.length))},rounds:(u,d)=>{for(let p=1;p<u;p++){c.call(e,a).update(r).digestInto(r),l.call(t,a).update(r).digestInto(r);for(let m=0;m<d.length;m++)d[m]^=r[m]}},output:u=>(e.destroy(),t.destroy(),s.destroy(),a.destroy(),tt(r),u)}}function fb(e,t,n,r){let{c:o,dkLen:i,DK:s,outputLen:a,eng:c}=sA(e,t,n,r);for(let l=1,u=0;u<i;l++,u+=a){let d=s.subarray(u,u+a);c.u1(l,d),c.rounds(o,d)}return c.output(s)}function pb(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n>=55296&&n<=56319){if(t+1>=e.length)return!1;let r=e.charCodeAt(++t);if(r<56320||r>57343)return!1}else if(n>=56320&&n<=57343)return!1}return!0}function hb(e){if(typeof e!="string")throw new TypeError("invalid mnemonic type: "+typeof e);if(!pb(e))throw new TypeError("expected well-formed Unicode string");return e.normalize("NFKD")}function mb(e){let t=hb(e),n=t.split(" ");if(![12,15,18,21,24].includes(n.length))throw new Error("Invalid mnemonic");return{nfkd:t,words:n}}function cA(e){if(Me(e),![16,20,24,28,32].includes(e.length))throw new RangeError("invalid entropy length")}var lA=e=>{let t=8-e.length/4;return Qs(e)[0]>>t<<t};function uA(e){if(!Array.isArray(e)||e.length!==2048||typeof e[0]!="string")throw new TypeError("Wordlist: expected array of 2048 strings");e.forEach(t=>{if(typeof t!="string")throw new TypeError("wordlist: non-string element: "+t);if(!pb(t))throw new TypeError("wordlist: expected well-formed Unicode string")})}function dA(e,t){uA(t);let n=e.length/3*4,r=new Uint8Array(n+1),o=0,i=0,s=0;for(let c of e){let l=t.indexOf(c);if(l===-1)throw new Error("Unknown word: "+c);for(o=o<<11|l,i+=11;i>=8;)i-=8,r[s++]=o>>>i&255;o&=(1<<i)-1}i>0&&(r[s]=o<<8-i);let a=r.subarray(0,n);if(r[n]!==lA(a))throw new Error("Invalid checksum");return Uint8Array.from(a)}function fA(e,t){let{words:n}=mb(e),r=dA(n,t);return cA(r),r}function wb(e,t){try{fA(e,t)}catch{return!1}return!0}var pA=e=>{if(typeof e!="string")throw new TypeError("invalid passphrase type: "+typeof e);return hb("mnemonic"+e)};function yb(e,t=""){return fb(Zo,mb(e).nfkd,pA(t),{c:2048,dkLen:64})}var bb=Object.freeze(`abandon
|
|
1
|
+
/*! @ninsei-labs/sdk includes a port of github.com/athanorlabs/go-dleq, licensed LGPL-3.0-only. See THIRD_PARTY_NOTICES.md. */
|
|
2
|
+
var rg=Object.create;var rc=Object.defineProperty;var og=Object.getOwnPropertyDescriptor;var ig=Object.getOwnPropertyNames;var sg=Object.getPrototypeOf,ag=Object.prototype.hasOwnProperty;var Le=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var cg=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},Be=(e,t)=>{for(var n in t)rc(e,n,{get:t[n],enumerable:!0})},lg=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ig(t))!ag.call(e,o)&&o!==n&&rc(e,o,{get:()=>t[o],enumerable:!(r=og(t,o))||r.enumerable});return e};var ug=(e,t,n)=>(n=e!=null?rg(sg(e)):{},lg(t||!e||!e.__esModule?rc(n,"default",{value:e,enumerable:!0}):n,e));function Rg(e,t=!1){return t?{h:Number(e&Ui),l:Number(e>>rf&Ui)}:{h:Number(e>>rf&Ui)|0,l:Number(e&Ui)|0}}function Mi(e,t=!1){let n=e.length,r=new Uint32Array(n),o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=Rg(e[i],t);[r[i],o[i]]=[s,a]}return[r,o]}function of(e,t,n,r){let o=Hg(n),i=Lg(n);e.setUint32(t,r?i:o,r),e.setUint32(t+4,r?o:i,r)}function Ot(e,t,n,r){let o=(t>>>0)+(r>>>0);return{h:e+n+(o/2**32|0)|0,l:o|0}}var Ui,rf,Hg,Lg,hc,mc,Fn,Dn,No,To,sf,af,cf,lf,uf,df,Ki=Le(()=>{Ui=BigInt(4294967295),rf=BigInt(32);Hg=e=>e/2**32|0,Lg=e=>e>>>0;hc=(e,t,n)=>e>>>n,mc=(e,t,n)=>e<<32-n|t>>>n,Fn=(e,t,n)=>e>>>n|t<<32-n,Dn=(e,t,n)=>e<<32-n|t>>>n,No=(e,t,n)=>e<<64-n|t>>>n-32,To=(e,t,n)=>e>>>n-32|t<<64-n;sf=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),af=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,cf=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),lf=(e,t,n,r,o)=>t+n+r+o+(e/2**32|0)|0,uf=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),df=(e,t,n,r,o,i)=>t+n+r+o+i+(e/2**32|0)|0});function ji(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Te(e,t=""){if(typeof e!="number")throw new TypeError(Wi(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Wi(t)+"expected integer >= 0, got "+e);return e}function hf(e,t=""){if(typeof e!="boolean")throw new TypeError(Wi(t)+"expected boolean, got type="+typeof e);return e}function Fe(e,t,n=""){if(ji(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Te(t,"length");let r=ji(e),o=t!==void 0?` of length ${t}`:"",i=r?`length=${e.length}`:`type=${typeof e}`,s=Wi(n)+"expected Uint8Array"+o+", got "+i;throw r?new RangeError(s):new TypeError(s)}function gr(e){if(typeof e!="function"||typeof e.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Te(e.outputLen),Te(e.blockLen),e.outputLen<1||e.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}function Wt(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function xr(e,t){Fe(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function wc(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function qe(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function kr(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function vt(e,t){return e<<32-t|e>>>t}function Mg(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function Kg(e){for(let t=0;t<e.length;t++)e[t]=Mg(e[t]);return e}function Vi(e){if(Fe(e),mf)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=jg[e[n]];return t}function pf(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function $i(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(mf)try{return Uint8Array.fromHex(e)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let t=e.length,n=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);let r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){let s=pf(e.charCodeAt(i)),a=pf(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}r[o]=s*16+a}return r}function Wg(e){if(typeof e!="string")throw new TypeError("string expected");let t=new TextEncoder().encode(e);try{return new Uint8Array(t)}finally{qe(t)}}function bc(e,t=""){return typeof e=="string"?Wg(e):Fe(e,void 0,t)}function gc(...e){let t=0;for(let r=0;r<e.length;r++){let o=e[r];Fe(o),t+=o.length}let n=new Uint8Array(t);for(let r=0,o=0;r<e.length;r++){let i=e[r];n.set(i,o),o+=i.length}return n}function zi(e,t,n="opts"){return ff(e,"defaults"),t!==void 0&&ff(t,n),Object.assign(Object.create(null),e,t)}function Po(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=zi({},t,"info");let n=(o,i)=>e(i).update(o).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>e(o),Object.assign(n,t),Object.freeze(n)}function xc(e=32){Te(e,"bytesLength");let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(e>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var Wi,Dg,ff,Ug,yc,mf,jg,Bo,Ct=Le(()=>{Wi=e=>e?`"${e}" `:"";Dg=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},ff=(e,t)=>{Dg(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};Ug=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;yc=Ug?e=>e:Kg,mf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",jg=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));Bo=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])})});function wf(e,t,n){return e&t^~e&n}function yf(e,t,n){return e&t^e&n^t&n}var Oo,bf,gf,xf=Le(()=>{Ki();Ct();Oo=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,n,r,o){this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(t),this.view=kr(this.buffer)}update(t){Wt(this),Fe(t);let{view:n,buffer:r,blockLen:o}=this,i=t.length,s=!1;for(let a=0;a<i;){let c=Math.min(o-this.pos,i-a);if(c===o){let l=kr(t);for(;o<=i-a;a+=o)this.process(l,a);s=!0;continue}r.set(a===0&&c===i?t:t.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(n,0),this.pos=0,s=!0)}return this.length+=t.length,s&&this.roundClean(),this}digestInto(t){Wt(this),xr(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,n.fill(0,s),this.padOffset>o-s&&(this.process(r,0),n.fill(0)),of(r,o-8,this.length*8,i),this.process(r,0),this.roundClean();let a=t===n?r:kr(t),c=this.outputLen,l=c/4,u=this.get();if(c%4||l>u.length)throw new Error("invalid outputLen");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],i)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneIntoMeta(t){let{buffer:n,length:r,finished:o,destroyed:i,pos:s}=this;return t.destroyed=i,t.finished=o,t.length=r,t.pos=s,s&&t.buffer.set(n),t}clone(){return this._cloneInto()}},bf=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),gf=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});var Vg,sn,kc,Sc,kf,$g,zg,an,cn,vc,Ec,Xi,Co,Yi=Le(()=>{xf();Ki();Ct();Vg=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),sn=new Uint32Array(64),kc=class extends Oo{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(t,n){super(64,t,8,!1),this.A=n[0]|0,this.B=n[1]|0,this.C=n[2]|0,this.D=n[3]|0,this.E=n[4]|0,this.F=n[5]|0,this.G=n[6]|0,this.H=n[7]|0}get(){let{A:t,B:n,C:r,D:o,E:i,F:s,G:a,H:c}=this;return[t,n,r,o,i,s,a,c]}set(t,n,r,o,i,s,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let f=0;f<16;f++,n+=4)sn[f]=t.getUint32(n,!1);for(let f=16;f<64;f++){let h=sn[f-15],m=sn[f-2],w=vt(h,7)^vt(h,18)^h>>>3,x=vt(m,17)^vt(m,19)^m>>>10;sn[f]=x+sn[f-7]+w+sn[f-16]|0}let{A:r,B:o,C:i,D:s,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let h=vt(a,6)^vt(a,11)^vt(a,25),m=u+h+wf(a,c,l)+Vg[f]+sn[f]|0,x=(vt(r,2)^vt(r,13)^vt(r,22))+yf(r,o,i)|0;u=l,l=c,c=a,a=s+m|0,s=i,i=o,o=r,r=m+x|0}r=r+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,o,i,s,a,c,l,u)}roundClean(){qe(sn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),qe(this.buffer)}},Sc=class extends kc{constructor(){super(32,bf)}},kf=Mi(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),$g=kf[0],zg=kf[1],an=new Uint32Array(80),cn=new Uint32Array(80),vc=class extends Oo{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(t,n){super(128,t,16,!1),this.Ah=n[0]|0,this.Al=n[1]|0,this.Bh=n[2]|0,this.Bl=n[3]|0,this.Ch=n[4]|0,this.Cl=n[5]|0,this.Dh=n[6]|0,this.Dl=n[7]|0,this.Eh=n[8]|0,this.El=n[9]|0,this.Fh=n[10]|0,this.Fl=n[11]|0,this.Gh=n[12]|0,this.Gl=n[13]|0,this.Hh=n[14]|0,this.Hl=n[15]|0}get(){let{Ah:t,Al:n,Bh:r,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:h,Gh:m,Gl:w,Hh:x,Hl:y}=this;return[t,n,r,o,i,s,a,c,l,u,f,h,m,w,x,y]}set(t,n,r,o,i,s,a,c,l,u,f,h,m,w,x,y){this.Ah=t|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=h|0,this.Gh=m|0,this.Gl=w|0,this.Hh=x|0,this.Hl=y|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let g=0;g<16;g++,n+=4)an[g]=t.getUint32(n),cn[g]=t.getUint32(n+=4);for(let g=16;g<80;g++){let P=an[g-15]|0,E=cn[g-15]|0,B=Fn(P,E,1)^Fn(P,E,8)^hc(P,E,7),p=Dn(P,E,1)^Dn(P,E,8)^mc(P,E,7),b=an[g-2]|0,S=cn[g-2]|0,v=Fn(b,S,19)^No(b,S,61)^hc(b,S,6),H=Dn(b,S,19)^To(b,S,61)^mc(b,S,6),A=cf(p,H,cn[g-7],cn[g-16]),O=lf(A,B,v,an[g-7],an[g-16]);an[g]=O|0,cn[g]=A|0}let{Ah:r,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:h,Fh:m,Fl:w,Gh:x,Gl:y,Hh:k,Hl:I}=this;for(let g=0;g<80;g++){let P=Fn(f,h,14)^Fn(f,h,18)^No(f,h,41),E=Dn(f,h,14)^Dn(f,h,18)^To(f,h,41),B=f&m^~f&x,p=h&w^~h&y,b=uf(I,E,p,zg[g],cn[g]),S=df(b,k,P,B,$g[g],an[g]),v=b|0,H=Fn(r,o,28)^No(r,o,34)^No(r,o,39),A=Dn(r,o,28)^To(r,o,34)^To(r,o,39),O=r&i^r&a^i&a,D=o&s^o&c^s&c;k=x|0,I=y|0,x=m|0,y=w|0,m=f|0,w=h|0,{h:f,l:h}=Ot(l|0,u|0,S|0,v|0),l=a|0,u=c|0,a=i|0,c=s|0,i=r|0,s=o|0;let L=sf(v,A,D);r=af(L,S,H,O),o=L|0}({h:r,l:o}=Ot(this.Ah|0,this.Al|0,r|0,o|0)),{h:i,l:s}=Ot(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Ot(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Ot(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:h}=Ot(this.Eh|0,this.El|0,f|0,h|0),{h:m,l:w}=Ot(this.Fh|0,this.Fl|0,m|0,w|0),{h:x,l:y}=Ot(this.Gh|0,this.Gl|0,x|0,y|0),{h:k,l:I}=Ot(this.Hh|0,this.Hl|0,k|0,I|0),this.set(r,o,i,s,a,c,l,u,f,h,m,w,x,y,k,I)}roundClean(){qe(an,cn)}destroy(){this.destroyed=!0,qe(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Ec=class extends vc{constructor(){super(64,gf)}},Xi=Po(()=>new Sc,Bo(1)),Co=Po(()=>new Ec,Bo(3))});function qi(e,t,n=()=>{}){if(!Array.isArray(e))throw new TypeError(`"${t}" expected array, got type=${typeof e}`);for(let r=0;r<e.length;r++)n(e[r],`${t}[${r}]`);return e}function vf(e,t=""){if(typeof e!="string"){let n=t&&`"${t}" `;throw new TypeError(n+"expected string, got type="+typeof e)}return e}function ln(e,t="object"){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(t==="object"?"expected valid options object":`"${t}" expected object, got type=${typeof e}`);return e}function Un(e,t){if(typeof e!="function")throw new TypeError(`"${t}" is invalid: expected function, got ${typeof e}`);return e}function Ze(e,t=""){if(typeof e!="boolean")throw new TypeError(Xg(t)+"expected boolean, got type="+typeof e);return e}function Qi(e){if(typeof e=="bigint"){if(!un(e))throw new RangeError("positive bigint expected, got "+e)}else Ac(e);return e}function Vt(e,t=""){if(typeof e!="number"){let n=t&&`"${t}" `;throw new TypeError(n+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let n=t&&`"${t}" `;throw new RangeError(n+"expected safe integer, got "+e)}}function Ho(e){let t=Qi(e).toString(16);return t.length&1?"0"+t:t}function Ef(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?Gi:BigInt("0x"+e)}function Rt(e){return Ef(Vi(e))}function Kn(e){return Ef(Vi(Lo(Fe(e)).reverse()))}function Zi(e,t){if(Te(t),t===0)throw new Error("zero output length is invalid");e=Qi(e);let n=t*2,r=e.toString(16);if(r.length>n)throw new RangeError("number is too large");return $i(r.padStart(n,"0"))}function _c(e,t){return Zi(e,t).reverse()}function Lo(e){return Uint8Array.from(pe(e))}function un(e){return typeof e=="bigint"&&Gi<=e}function Ic(e,t,n){return un(e)&&un(t)&&un(n)&&t<=e&&e<n}function vr(e,t,n,r){if(!Ic(t,n,r))throw new RangeError("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Er(e){if(e<Gi)throw new Error("expected non-negative bigint, got "+e);return e===Gi?0:e.toString(2).length}function Af(e,t,n){if(Te(e,"hashLen"),Te(t,"qByteLen"),typeof n!="function")throw new TypeError("hmacFn must be a function");let r=y=>new Uint8Array(y),o=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1e3,c=r(e),l=r(e),u=0,f=()=>{c.fill(1),l.fill(0),u=0},h=(...y)=>n(l,dt(c,...y)),m=(y=o)=>{l=h(i,y),c=h(),y.length!==0&&(l=h(s,y),c=h())},w=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,k=[];for(;y<t;){c=h();let I=c.slice();k.push(I),y+=c.length}return dt(...k)};return(y,k)=>{f(),m(y);let I;for(;(I=k(w()))===void 0;)m();return f(),I}}function Je(e,t={},n={},r="object"){ln(e,r),ln(t,"fields"),ln(n,"optFields");function o(s,a,c){let l=r==="object"?`param "${String(s)}"`:`"${r}.${String(s)}"`,u=e[s];if(!Object.hasOwn(e,s)&&(c?u!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(c&&u===void 0)return;let f=typeof u;if(f!==a||u===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${f}`)}let i=(s,a)=>Object.entries(s).forEach(([c,l])=>o(c,l,a));i(t,!1),i(n,!0)}var pe,Ac,Ro,dt,Sr,dn,Mn,Gi,Sf,Xg,Fo,Ar=Le(()=>{Ct();pe=(e,t,n)=>Fe(e,t,n),Ac=Te;Ro=Vi,dt=(...e)=>gc(...e),Sr=e=>$i(e),dn=ji,Mn=e=>xc(e),Gi=BigInt(0),Sf=BigInt(1),Xg=e=>e?`"${e}" `:"";Fo=e=>(Vt(e,"n"),(Sf<<BigInt(e))-Sf)});function ve(e,t){if(t<=He)throw new Error("mod: expected positive modulus, got "+t);let n=e%t;return n>=He?n:t+n}function Of(e,t,n){if(n<=he)throw new Error("pow: expected modulus > 1, got "+n);if(typeof t!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof t);if(t<He)throw new Error("invalid exponent, negatives unsupported");if(t===He)return he;if(t===he)return e;let r=e%n;if(r<He&&(r+=n),t<Qg){let a=he;for(;t>He;)t&he&&(a=a*r%n),r=r*r%n,t>>=he;return a}let o=[];for(;t>He;)o.push(Number(t&qg)),t>>=Nc;let i=new Array(16);i[0]=he,i[1]=r;for(let a=2;a<16;a++)i[a]=i[a-1]*r%n;let s=i[o[o.length-1]];for(let a=o.length-2;a>=0;a--){s=s*s%n,s=s*s%n,s=s*s%n,s=s*s%n;let c=o[a];c!==0&&(s=s*i[c]%n)}return s}function Se(e,t,n){if(n<=he)throw new Error("pow2: expected modulus > 1, got "+n);if(t<He)throw new Error("pow2: expected non-negative exponent, got "+t);let r=e;for(;t-- >He;)r*=r,r%=n;return r}function _f(e,t){if(e===He)throw new Error("invert: expected non-zero number");if(t<=he)throw new Error("invert: expected modulus > 1, got "+t);let n=ve(e,t),r=t,o=He,i=he;for(;n!==He;){let a=r/n,c=r-n*a,l=o-i*a;r=n,n=c,o=i,i=l}if(r!==he)throw new Error("invert: does not exist");return ve(o,t)}function Cf(e,t){if(t<=he)throw new Error("invertCt: expected prime modulus > 1, got "+t);let n=ve(e,t);if(n===He)throw new Error("invertCt: expected non-zero number");let r=Of(n,t-fn,t);if(ve(n*r,t)!==he)throw new Error("invertCt: does not exist");return r}function Tc(e,t,n){let r=e;if(!r.eql(r.sqr(t),n))throw new Error("Cannot find square root")}function Pc(e,t){if((e&he)===He)throw new Error(t+": expected odd modulus, got "+e)}function Rf(e,t){let n=e,r=(n.ORDER+he)/Nc,o=n.pow(t,r);return Tc(n,o,t),o}function Zg(e,t){let n=e,r=(n.ORDER-Tf)/Pf,o=n.mul(t,fn),i=n.pow(o,r),s=n.mul(t,i),a=n.mul(n.mul(s,fn),i),c=n.mul(s,n.sub(a,n.ONE));return Tc(n,c,t),c}function Jg(e){let t=Ir(e),n=Hf(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+Yg)/Bf;return((a,c)=>{let l=a,u=l.pow(c,s),f=l.mul(u,r),h=l.mul(u,o),m=l.mul(u,i),w=l.eql(l.sqr(f),c),x=l.eql(l.sqr(h),c);u=l.cmov(u,f,w),f=l.cmov(m,h,x);let y=l.eql(l.sqr(f),c),k=l.cmov(u,f,y);return Tc(l,k,c),k})}function Hf(e){if(e<Nf)throw new Error("sqrt is not defined for small field");Pc(e,"tonelliShanks");let t=e-he,n=0;for(;t%fn===He;)t/=fn,n++;let r=fn,o=Ir(e);for(;Do(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Rf;let i=o.pow(r,t),s=(t+he)/fn;return function(c,l){let u=c;if(u.is0(l))return l;if(Do(u,l)!==1)throw new Error("Cannot find square root");let f=n,h=u.mul(u.ONE,i),m=u.pow(l,t),w=u.pow(l,s);for(;!u.eql(m,u.ONE);){if(u.is0(m))throw new Error("Cannot find square root: probably non-prime P");let x=1,y=u.sqr(m);for(;!u.eql(y,u.ONE);)if(x++,y=u.sqr(y),x===f)throw new Error("Cannot find square root");let k=he<<BigInt(f-x-1),I=u.pow(h,k);f=x,h=u.sqr(I),m=u.mul(m,h),w=u.mul(w,I)}return w}}function ex(e){return Pc(e,"Fp.sqrt"),e%Nc===Nf?Rf:e%Pf===Tf?Zg:e%Bf===Gg?Jg(e):Hf(e)}function _r(e){if(ln(e,"field"),typeof e.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof e.ORDER);Vt(e.BYTES,"BYTES"),Vt(e.BITS,"BITS");for(let t of tx)Un(e[t],"field."+t);if(e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=he)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function es(e,t,n=!1){_r(e),qi(t,"nums"),Ze(n,"passZero");let r=e,o=new Array(t.length).fill(n?r.ZERO:void 0),i=t.reduce((a,c,l)=>r.is0(c)?a:(o[l]=a,r.mul(a,c)),r.ONE),s=r.inv(i);return t.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),s),o}function Do(e,t){_r(e);let n=e;Pc(n.ORDER,"FpLegendre");let r=(n.ORDER-he)/fn,o=n.pow(t,r),i=n.eql(o,n.ONE),s=n.eql(o,n.ZERO),a=n.eql(o,n.neg(n.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function nx(e,t){if(t!==void 0&&Ac(t),e<=He)throw new Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw new Error("invalid n length: expected positive bit length, got "+t);let n=Er(e);if(t!==void 0&&t<n)throw new Error(`invalid n length: expected nBitLength (${t}) >= bitLen(n) (${n})`);let r=t!==void 0?t:n,o=Math.ceil(r/8);return{nBitLength:r,nByteLength:o}}function Ir(e,t={}){return Object.freeze(Ji.prototype),new Ji(e,t)}function Ff(e){if(typeof e!="bigint")throw new Error("field order must be bigint");if(e<=he)throw new Error("field order must be greater than 1");let t=Er(e-he);return Math.ceil(t/8)}function ts(e){let t=Ff(e);return t+Math.ceil(t/2)}function ns(e,t,n=!1){pe(e);let r=e.length,o=Ff(t),i=Math.max(ts(t),16);if(r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let s=n?Kn(e):Rt(e),a=ve(s,t-he)+he;return n?_c(a,o):Zi(a,o)}var He,he,fn,Nf,Nc,Tf,Yg,Pf,Gg,qg,Bf,Qg,Lf,tx,If,Ji,Nr=Le(()=>{Ar();He=BigInt(0),he=BigInt(1),fn=BigInt(2),Nf=BigInt(3),Nc=BigInt(4),Tf=BigInt(5),Yg=BigInt(7),Pf=BigInt(8),Gg=BigInt(9),qg=BigInt(15),Bf=BigInt(16),Qg=BigInt("0x10000000000000000");Lf=(e,t)=>(ve(e,t)&he)===he,tx=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];If=new WeakMap,Ji=class{ORDER;BITS;BYTES;isLE;ZERO=He;ONE=he;_lengths;_mod;constructor(t,n={}){if(t<=he)throw new Error("invalid field: expected ORDER > 1, got "+t);let r;this.isLE=!1,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:n.sqrt,enumerable:!0}),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=Object.freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=nx(t,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=i,Object.freeze(this)}create(t){return ve(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof t);return He<=t&&t<this.ORDER}is0(t){return t===He}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&he)===he}neg(t){return ve(-t,this.ORDER)}eql(t,n){return t===n}sqr(t){return ve(t*t,this.ORDER)}add(t,n){return ve(t+n,this.ORDER)}sub(t,n){return ve(t-n,this.ORDER)}mul(t,n){return ve(t*n,this.ORDER)}pow(t,n){return Of(t,n,this.ORDER)}div(t,n){return ve(t*_f(n,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,n){return t+n}subN(t,n){return t-n}mulN(t,n){return t*n}inv(t){return _f(t,this.ORDER)}sqrt(t){let n=If.get(this);return n||If.set(this,n=ex(this.ORDER)),n(this,t)}toBytes(t){return this.isLE?_c(t,this.BYTES):Zi(t,this.BYTES)}fromBytes(t,n=!1){pe(t);let{_lengths:r,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(r){if(t.length<1||!r.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+t.length);let l=new Uint8Array(o);l.set(t,i?0:l.length-t.length),t=l}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=i?Kn(t):Rt(t);if(a&&(c=ve(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return es(this,t,!0)}cmov(t,n,r){return Ze(r,"condition"),r?n:t}}});function pn(e){let t=e;if(typeof t!="function")throw new TypeError('"Point" expected constructor, got type='+typeof e);Un(t.fromAffine,"Point.fromAffine"),Un(t.fromBytes,"Point.fromBytes"),Un(t.fromHex,"Point.fromHex"),ln(t.BASE,"Point.BASE"),ln(t.ZERO,"Point.ZERO"),_r(t.Fp),_r(t.Fn)}function rs(e,t){pn(e),Kf(t,e);let n=es(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function ix(e,t,n=1){if(!Number.isSafeInteger(e)||e<n||e>t)throw new Error("invalid window size, expected ["+n+".."+t+"], got W="+e)}function sx(e,t){let n=e*(4*t+128);if(n>Uf)throw new Error("invalid window size: table would need ~"+Math.ceil(n/2**20)+" MiB, max "+Uf/2**20+" MiB")}function Rc(e,t){if(e!==void 0){Un(e,"randomBytes");try{let n=e(t);if(!dn(n)||n.length!==t)return}catch{return}return e}}function Kf(e,t){qi(e,"points"),e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function ax(e,t,n){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,o)=>{if(!(n===void 0?t.isValid(r):un(r)&&r<n))throw new Error("invalid scalar at index "+o)})}function Oc(e){return jf.get(e)||1}function cx(e,t){let n=e.double(),r=[e];for(let o=1;o<t;o++)r.push(r[o-1].add(n));return r}function lx(e,t){let n=2**t,r=n/2,o=BigInt(n-1),i=[];for(;e>Cc;){let s=0;e&Uo&&(s=Number(e&o),s>=r&&(s-=n),e-=BigInt(s)),i.push(s),e>>=Uo}return i}function ux(e,t,n){let r=2**t,o=r/2,i=BigInt(r-1),s=BigInt(t),a=[];for(let c=0;c<n;c++){let l=Number(e&i);e>>=s,l>o&&(l-=r,e+=Uo),a.push(l)}if(e!==Cc)throw new Error("invalid wnaf");return a}function dx(e,t,n){let r=0;for(let i of n)r=Math.max(r,i.length);let o=e;for(let i=r-1;i>=0;i--){i!==r-1&&(o=o.double());for(let s=0;s<n.length;s++){let a=n[s][i];if(a){let c=t[s][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}function os(e,t,n,r=!1){if(pn(e),Kf(t,e),Ze(r,"allowOversized"),ax(n,e.Fn,r?e.Fn.ORDER**rx:void 0),t.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=t.map(s=>cx(s,4)),i=n.map(s=>lx(s,4));return dx(e.ZERO,o,i)}function Mf(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return _r(t),t}else return Ir(e,{isLE:n})}function is(e,t,n={},r){if(e!=="weierstrass"&&e!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(r===void 0&&(r=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);Je(n);for(let c of["p","n","h"]){let l=t[c];if(!(un(l)&&l!==Cc))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Mf(t.p,n.Fp,r),i=Mf(t.n,n.Fn,r),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}function ss(e,t){return function(r){let o=e(r);return{secretKey:o,publicKey:t(o)}}}var Cc,Uo,rx,Bc,Df,ox,Uf,jf,Tr,Hc=Le(()=>{Ar();Nr();Cc=BigInt(0),Uo=BigInt(1),rx=BigInt(4),Bc=16,Df=128,ox=5,Uf=2**31;jf=new WeakMap;Tr=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(t,n){pn(t),this.randomBytes=Rc(n,Bc),this.Point=t,this.BASE=t.BASE,this.ZERO=t.ZERO,this.bits=t.Fn.BITS}buildWnafTable(t,n,r){let o=Math.ceil(r/n)+1,i=2**(n-1),s=[],a=t;for(let c=0;c<o;c++){let l=a;for(let u=0;u<i;u++)s.push(l),l=l.add(a);a=s[s.length-1].double()}return{W:n,bits:r,windows:o,comp:s}}wnafCachedCT(t,n){let{W:r,windows:o,comp:i}=t,s=2**(r-1),a=ux(n,r,o),c=this.ZERO,l=this.BASE;for(let u=0;u<o;u++){let f=a[u],h=u*s,m=Math.abs(f)-1,w=i[h];for(let y=1;y<s;y++)w=y===m?i[h+y]:w;let x=w.negate();f===0?l=l.add(i[h]):c=c.add(f<0?x:w)}return{p:c,f:l}}getWnafPrecomputes(t,n,r,o){let i=this.wnafPrecomputes.get(n),s=i?.find(a=>a.W===t&&a.bits===r);return s||(s=this.buildWnafTable(n,t,r),typeof o=="function"&&(s={...s,comp:o(s.comp)}),i||(i=[],this.wnafPrecomputes.set(n,i)),i.push(s)),s}assertPoint(t){if(!(t instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof t)}validateMulInput(t,n){if(this.assertPoint(t),!Ic(n,Uo,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(t,n,r,o){let i=Oc(t);return i===1?this.fixedWindowCT(t,n,r):this.wnafCachedCT(this.getWnafPrecomputes(i,t,r,o),n)}mulCT(t,n,r){return this.validateMulInput(t,n),this.runCT(t,n,this.bits,r)}mulCTBlinded(t,n,r){if(this.validateMulInput(t,n),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+Df,i=this.randomBytes(Bc);if(!dn(i)||i.length!==Bc)throw new Error("randomBytes returned invalid byte array");i[0]=i[0]&63|128;let s=n+Rt(i)*this.Point.Fn.ORDER;return this.runCT(t,s,o,r)}fixedWindowCT(t,n,r){let o=ox,i=1<<o,s=Fo(o),a=new Array(i);a[0]=this.ZERO;for(let u=1;u<i;u++)a[u]=a[u-1].add(t);let c=Math.ceil(r/o),l=this.ZERO;for(let u=c-1;u>=0;u--){if(u!==c-1)for(let m=0;m<o;m++)l=l.double();let f=Number(n>>BigInt(u*o)&s),h=a[0];for(let m=1;m<i;m++)h=m===f?a[m]:h;l=l.add(h)}return{p:l,f:l}}shouldBlind(t,n){return this.randomBytes===void 0?!1:n===Uo?!0:t!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(t,n,r,o){return this.shouldBlind(t,r)?this.mulCTBlinded(t,n,o):this.mulCT(t,n,o)}mulUnsafe(t,n,r){if(this.assertPoint(t),!un(n))throw new Error("invalid scalar");let o=Oc(t);if(o===1||n>=this.Point.Fn.ORDER)return os(this.Point,[t],[n],!0);let i=this.getWnafPrecomputes(o,t,this.bits,r);return this.wnafCachedCT(i,n).p}setWindowSize(t,n){this.assertPoint(t),ix(n,this.bits);let r=Math.ceil((this.bits+Df)/n)+1;sx(r*2**(n-1),this.Point.Fp.BYTES),jf.set(t,n),this.wnafPrecomputes.delete(t)}hasWindowSize(t){return Oc(t)!==1}}});function px(e,t,n,r){let o=e.sqr(n),i=e.sqr(r),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}function Vf(e,t={}){Je(t,{},{},"extraOpts");let n=t,r=is("edwards",e,n,n.FpFnLE),{Fp:o,Fn:i}=r,s=r.CURVE,{h:a}=s;if(Do(o,s.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Do(o,s.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Je(n,{},{uvRatio:"function",randomBytes:"function"});let c=n.randomBytes===void 0?Mn:n.randomBytes,l=ls<<BigInt(o.BYTES*8)-cs;function u(I){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(I)}let f=n.uvRatio===void 0?(I,g)=>{try{return{isValid:!0,value:o.sqrt(o.div(I,g))}}catch{return{isValid:!1,value:as}}}:n.uvRatio;if(!px(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");let h=o.eql(s.a,o.neg(o.ONE))?I=>o.neg(I):o.eql(s.a,o.ONE)?I=>I:I=>o.mul(s.a,I);function m(I,g,P=!1){let E=P?cs:as;return vr("coordinate "+I,g,E,l),g}function w(I){if(!(I instanceof x))throw new Error("EdwardsPoint expected")}class x{static BASE=new x(s.Gx,s.Gy,o.ONE,o.mul(s.Gx,s.Gy));static ZERO=new x(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=i;X;Y;Z;T;constructor(g,P,E,B){this.X=m("x",g),this.Y=m("y",P),this.Z=m("z",E,!0),this.T=m("t",B),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){if(g instanceof x)throw new Error("extended point not allowed");let{x:P,y:E}=g||{};return m("x",P),m("y",E),new x(P,E,o.ONE,o.mul(P,E))}static fromBytes(g,P=!1){let E=o.BYTES,{a:B,d:p}=s;g=Lo(pe(g,E,"point")),Ze(P,"zip215");let b=Lo(g),S=g[E-1];b[E-1]=S&-129;let v=Kn(b),H=P?l:o.ORDER;vr("point.y",v,as,H);let A=o.sqr(v),O=o.sub(A,o.ONE),D=o.sub(o.mulN(p,A),B),{isValid:L,value:V}=f(O,D);if(!L)throw new Error("bad point: invalid y coordinate");let U=u(V),j=(S&128)!==0;if(!P&&o.is0(V)&&j)throw new Error("bad point: x=0 and x_0=1");return j!==U&&(V=o.neg(V)),x.fromAffine({x:V,y:v})}static fromHex(g,P=!1){return x.fromBytes(Sr(g),P)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=6,P=!0){return k.setWindowSize(this,g),P||this.multiply(ls),this}assertValidity(){let g=this,{a:P,d:E}=s;if(g.is0())throw new Error("bad point: ZERO");let{X:B,Y:p,Z:b,T:S}=g,v=o.sqr(B),H=o.sqr(p),A=o.sqr(b),O=o.sqr(A),D=o.mul(v,P),L=o.mul(o.add(D,H),A),V=o.add(O,o.mul(E,o.mul(v,H)));if(!o.eql(L,V))throw new Error("bad point: equation left != right (1)");let U=o.mul(B,p),j=o.mul(b,S);if(!o.eql(U,j))throw new Error("bad point: equation left != right (2)")}equals(g){w(g);let{X:P,Y:E,Z:B}=this,{X:p,Y:b,Z:S}=g,v=o.mul(P,S),H=o.mul(p,B),A=o.mul(E,S),O=o.mul(b,B);return o.eql(v,H)&&o.eql(A,O)}is0(){return this.equals(x.ZERO)}negate(){return new x(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:g,Y:P,Z:E}=this,B=o.sqr(g),p=o.sqr(P),b=o.mul(o.sqr(E),ls),S=h(B),v=o.addN(g,P),H=o.sub(o.subN(o.sqr(v),B),p),A=o.addN(S,p),O=o.subN(A,b),D=o.subN(S,p),L=o.mul(H,O),V=o.mul(A,D),U=o.mul(H,D),j=o.mul(O,A);return new x(L,V,j,U)}add(g){w(g);let{d:P}=s,{X:E,Y:B,Z:p,T:b}=this,{X:S,Y:v,Z:H,T:A}=g,O=o.mul(E,S),D=o.mul(B,v),L=o.mul(o.mulN(b,P),A),V=o.mul(p,H),U=o.sub(o.subN(o.mulN(o.addN(E,B),o.addN(S,v)),O),D),j=o.subN(V,L),F=o.addN(V,L),R=o.sub(D,h(O)),_=o.mul(U,j),N=o.mul(F,R),W=o.mul(U,R),$=o.mul(j,F);return new x(_,N,$,W)}subtract(g){return w(g),this.add(g.negate())}multiply(g){if(!i.isValidNot0(g))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:P,f:E}=k.mulSecret(this,g,a,y);return y([P,E])[0]}multiplyUnsafe(g){if(!i.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===as?x.ZERO:this.is0()||g===cs?this:k.mulUnsafe(this,g,y)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return k.mulUnsafe(this,s.n).is0()}toAffine(g){let P=this,E=g;if(E!=null&&typeof E!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof E);let{X:B,Y:p,Z:b}=P,S=P.is0();E==null&&(E=S?o.create(Wf):o.inv(b));let v=o.mul(B,E),H=o.mul(p,E),A=o.mul(b,E);if(S)return{x:o.ZERO,y:o.ONE};if(!o.eql(A,o.ONE))throw new Error("invZ was invalid");return{x:v,y:H}}clearCofactor(){return a===cs?this:a===ls?this.double():a===fx?this.double().double():a===Wf?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:g,y:P}=this.toAffine(),E=o.toBytes(P);return E[E.length-1]|=u(g)?128:0,E}toHex(){return Ro(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let y=I=>rs(x,I),k=new Tr(x,c);return k.bits>=6&&x.BASE.precompute(6),Object.freeze(x.prototype),Object.freeze(x),x}function $f(e,t,n={}){if(pn(e),typeof t!="function")throw new Error('"hash" function param is required');let r=t,o=n;Je(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=e,l=r.outputLen,u=2*a.BYTES;if(l!==void 0&&(Vt(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let f=o.randomBytes===void 0?Mn:o.randomBytes,h=o.toMontgomery,m=o.toMontgomerySecret,w=o.adjustScalarBytes===void 0?D=>D:o.adjustScalarBytes,x=o.domain===void 0?(D,L,V)=>{if(Ze(V,"phflag"),L.length||V)throw new Error("Contexts/pre-hash are not supported");return D}:o.domain;function y(D){return c.create(Kn(D))}function k(D){let L=S.secretKey;pe(D,S.secretKey,"secretKey");let V=pe(r(D),2*L,"hashedSecretKey"),U=w(V.slice(0,L)),j=V.slice(L,2*L),F=y(U);return{head:U,prefix:j,scalar:F}}function I(D){let{head:L,prefix:V,scalar:U}=k(D),j=s.multiply(U),F=j.toBytes();return{head:L,prefix:V,scalar:U,point:j,pointBytes:F}}function g(D){return I(D).pointBytes}function P(D=Uint8Array.of(),...L){let V=dt(...L);return y(r(x(V,pe(D,void 0,"context"),!!i)))}function E(D,L,V={}){Je(V,{},{},"options"),D=Lo(pe(D,void 0,"message")),i&&(D=i(D));let{prefix:U,scalar:j,pointBytes:F}=I(L),R=P(V.context,U,D),_=s.multiply(R).toBytes(),N=P(V.context,_,F,D),W=c.create(R+N*j);if(!c.isValid(W))throw new Error("sign failed: invalid s");let $=dt(_,c.toBytes(W));return pe($,S.signature,"result")}let B={zip215:o.zip215};function p(D,L,V,U=B){Je(U);let{context:j}=U,F=U.zip215===void 0?!!B.zip215:U.zip215,R=S.signature;D=pe(D,R,"signature"),L=pe(L,void 0,"message"),V=pe(V,S.publicKey,"publicKey"),F!==void 0&&Ze(F,"zip215"),i&&(L=i(L));let _=R/2,N=D.subarray(0,_),W=Kn(D.subarray(_,R)),$,X,Y;try{$=e.fromBytes(V,F),X=e.fromBytes(N,F),Y=s.multiplyUnsafe(W)}catch{return!1}if(!F&&$.isSmallOrder())return!1;let G=P(j,N,V,L);return X.add($.multiplyUnsafe(G)).subtract(Y).clearCofactor().is0()}let b=a.BYTES,S={secretKey:b,publicKey:b,signature:2*b,seed:b};function v(D){return D=D===void 0?f(S.seed):D,pe(D,S.seed,"seed")}function H(D){return dn(D)&&D.length===S.secretKey}function A(D,L){try{return!!e.fromBytes(D,L===void 0?B.zip215:L)}catch{return!1}}let O={getExtendedPublicKey:I,randomSecretKey:v,isValidSecretKey:H,isValidPublicKey:A,toMontgomery(D){if(h===void 0)throw new Error("Montgomery conversion is not supported for this curve");return h(e.fromBytes(D))},toMontgomerySecret(D){if(m===void 0)throw new Error("Montgomery conversion is not supported for this curve");return m(D)}};return Object.freeze(S),Object.freeze(O),Object.freeze({keygen:ss(v,g),getPublicKey:g,sign:E,verify:p,utils:O,Point:e,lengths:S})}var as,cs,ls,fx,Wf,zf=Le(()=>{Ar();Hc();Nr();as=BigInt(0),cs=BigInt(1),ls=BigInt(2),fx=BigInt(4),Wf=BigInt(8)});function yx(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=Fc,a=e*e%i*e%i,c=Se(a,Xf,i)*a%i,l=Se(c,Lc,i)*e%i,u=Se(l,hx,i)*l%i,f=Se(u,t,i)*u%i,h=Se(f,n,i)*f%i,m=Se(h,r,i)*h%i,w=Se(m,o,i)*m%i,x=Se(w,o,i)*m%i,y=Se(x,t,i)*u%i;return{pow_p_5_8:Se(y,Xf,i)*e%i,b2:a}}function qf(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function bx(e,t){let n=Fc,r=ve(t*t*t,n),o=ve(r*r*t,n),i=yx(e*o).pow_p_5_8,s=ve(e*r*i,n),a=ve(t*s*s,n),c=s,l=ve(s*Yf,n),u=a===e,f=a===ve(-e,n),h=a===ve(-e*Yf,n);return u&&(s=c),(f||h)&&(s=l),Lf(s,n)&&(s=ve(-s,n)),{isValid:u||f,value:s}}function gx(e){let{y:t}=e;return Gf.toBytes(Gf.div(Lc+t,Lc-t))}function xx(e){let t=Dc.Fp.BYTES;return Fe(e,t),qf(Co(e.subarray(0,t))).subarray(0,t)}function kx(e){return $f(Dc,Co,Object.assign({adjustScalarBytes:qf,toMontgomery:gx,toMontgomerySecret:xx,zip215:!0},e))}var Lc,Xf,hx,mx,Fc,wx,Yf,Dc,Gf,_e,Uc=Le(()=>{Yi();Ct();zf();Nr();Lc=BigInt(1),Xf=BigInt(2),hx=BigInt(5),mx=BigInt(8),Fc=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),wx={p:Fc,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:mx,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};Yf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");Dc=Vf(wx,{uvRatio:bx}),Gf=Dc.Fp;_e=kx({})});var us,ds,Mc=Le(()=>{Ct();us=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(t,n){if(gr(t),Fe(n,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?t.create().update(n).digest():n);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=t.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),qe(o)}update(t){return Wt(this),this.iHash.update(t),this}digestInto(t){Wt(this),xr(t,this),this.finished=!0;let n=t.subarray(0,this.outputLen);this.iHash.digestInto(n),this.oHash.update(n),this.oHash.digestInto(n),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:n,iHash:r,finished:o,destroyed:i,blockLen:s,outputLen:a,canXOF:c}=this;return t=t,t.finished=o,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.canXOF=c,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ds=(()=>{let e=((t,n,r)=>new us(t,n).update(r).digest());return e.create=(t,n)=>new us(t,n),e})()});var Sx,Kc,$t,fs,Qf=Le(()=>{Ar();Sx=BigInt(0),Kc=class extends Error{constructor(t=""){super(t)}},$t={Err:Kc,_tlv:{encode:(e,t)=>{let{Err:n}=$t;if(Vt(e,"tag"),e<0||e>255)throw new n("tlv.encode: wrong tag");if(vf(t,"data"),t.length&1)throw new n("tlv.encode: unpadded data");let r=t.length/2,o=Ho(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");let i=r>127?Ho(o.length/2|128):"";return Ho(e)+i+o+t},decode(e,t){let{Err:n}=$t;t=pe(t,void 0,"DER data");let r=0;if(e<0||e>255)throw new n("tlv.decode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");let o=t[r++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");let l=t.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(r+=c,s<128)throw new n("tlv.decode(long): not minimal encoding")}let a=t.subarray(r,r+s);if(a.length!==s)throw new n("tlv.decode: wrong value length");return{v:a,l:t.subarray(r+s)}}},_int:{encode(e){let{Err:t}=$t;if(Qi(e),e<Sx)throw new t("integer: negative integers are not allowed");let n=Ho(e);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){let{Err:t}=$t;if(e.length<1)throw new t("invalid signature integer: empty");if(e[0]&128)throw new t("invalid signature integer: negative");if(e.length>1&&e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Rt(e)}},toSig(e,t){let{Err:n,_int:r,_tlv:o}=$t;if(t!==void 0&&(Vt(t,"maxScalarBytes"),t<1))throw new n("invalid signature: maxScalarBytes must be positive");let i=pe(e,void 0,"signature"),{v:s,l:a}=o.decode(48,i);if(a.length)throw new n("invalid signature: left bytes after parsing");let{v:c,l}=o.decode(2,s),{v:u,l:f}=o.decode(2,l);if(f.length)throw new n("invalid signature: left bytes after parsing");if(t!==void 0&&(c.length>t||u.length>t))throw new n("invalid signature: integer too large");return{r:r.decode(c),s:r.decode(u)}},hexFromSig(e){let{_tlv:t,_int:n}=$t;Je(e,{r:"bigint",s:"bigint"},{},"sig");let r=t.encode(2,n.encode(e.r)),o=t.encode(2,n.encode(e.s)),i=r+o;return t.encode(48,i)}},fs=(Object.freeze($t._tlv),Object.freeze($t._int),Object.freeze($t))});function vx(e,t,n){vr("scalar",e,zt,n);let[[r,o],[i,s]]=t,a=Zf(s*e,n),c=Zf(-o*e,n),l=e-a*r-c*i,u=-a*o-c*s,f=l<zt,h=u<zt;f&&(l=-l),h&&(u=-u);let m=Fo(Math.ceil(Er(n)/2))+jn;if(l<zt||l>=m||u<zt||u>=m)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:l,k2neg:h,k2:u}}function Vc(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function jc(e,t){Je(e);let n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return Ze(n.lowS,"lowS"),Ze(n.prehash,"prehash"),n.format!==void 0&&Vc(n.format),n}function ep(e,t={}){let n=is("weierstrass",e,t),r=n.Fp,o=n.Fn,i=n.CURVE,{h:s,n:a}=i;Je(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:l,clearCofactor:u,isTorsionFree:f,fromBytes:h,toBytes:m}=t,w=t.randomBytes===void 0?Mn:t.randomBytes;if(c&&(!r.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let x=c?{beta:c.beta,basises:c.basises.map(R=>[...R])}:void 0,y=np(r,o);function k(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function I(R,_,N){if(_.is0()){if(!l)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:W,y:$}=_.toAffine(),X=r.toBytes(W);if(Ze(N,"isCompressed"),N){k();let Y=!r.isOdd($);return dt(tp(Y),X)}else return dt(Uint8Array.of(4),X,r.toBytes($))}function g(R){pe(R,void 0,"Point");let{publicKey:_,publicKeyUncompressed:N}=y,W=R.length,$=R[0],X=R.subarray(1);if(l&&W===1&&$===0)return{x:r.ZERO,y:r.ZERO};if(W===_&&($===2||$===3)){let Y=r.fromBytes(X);if(!r.isValid(Y))throw new Error("bad point: is not on curve, wrong x");let G=b(Y),Z;try{Z=r.sqrt(G)}catch(T){let K=T instanceof Error?": "+T.message:"";throw new Error("bad point: is not on curve, sqrt error"+K)}k();let ne=r.isOdd(Z);return($&1)===1!==ne&&(Z=r.neg(Z)),{x:Y,y:Z}}else if(W===N&&$===4){let Y=r.BYTES,G=r.fromBytes(X.subarray(0,Y)),Z=r.fromBytes(X.subarray(Y,Y*2));if(!S(G,Z))throw new Error("bad point: is not on curve");return{x:G,y:Z}}else throw new Error(`bad point: got length ${W}, expected compressed=${_} or uncompressed=${N}`)}let P=m===void 0?I:m,E=h===void 0?g:h,B=r.mul(i.b,Wc),p=r.is0(i.a)?R=>r.ZERO:R=>r.mul(i.a,R);function b(R){let _=r.sqr(R),N=r.mul(_,R);return r.add(r.add(N,r.mul(R,i.a)),i.b)}function S(R,_){let N=r.sqr(_),W=b(R);return r.eql(N,W)}if(!S(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let v=r.mul(r.pow(i.a,Wc),Ex),H=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(v,H)))throw new Error("bad curve params: a or b");function A(R,_,N=!1){if(!r.isValid(_)||N&&r.is0(_))throw new Error(`bad point coordinate ${R}`);return typeof _=="object"&&_!==null?r.create(_):_}function O(R){if(!(R instanceof U))throw new Error("Weierstrass Point expected")}function D(R){if(!x||!x.basises)throw new Error("no endo");return vx(R,x.basises,o.ORDER)}function L(R,_,N,W){if(!o.isValid(W))throw new RangeError("invalid scalar: out of range");if(x){let{k1neg:$,k1:X,k2neg:Y,k2:G}=D(W),Z=new U(r.mul(N.X,x.beta),N.Y,N.Z);R.push($?N.negate():N,Y?Z.negate():Z),_.push(X,G)}else R.push(N),_.push(W)}let V=new WeakSet;class U{static BASE=new U(i.Gx,i.Gy,r.ONE);static ZERO=new U(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=o;X;Y;Z;constructor(_,N,W){this.X=A("x",_),this.Y=A("y",N,!0),this.Z=A("z",W),Object.freeze(this)}static CURVE(){return i}static fromAffine(_){let{x:N,y:W}=_||{};if(!_||!r.isValid(N)||!r.isValid(W))throw new Error("invalid affine point");if(_ instanceof U)throw new Error("projective point not allowed");return r.is0(N)&&r.is0(W)?U.ZERO:new U(N,W,r.ONE)}static fromBytes(_){let N=U.fromAffine(E(pe(_,void 0,"point")));return N.assertValidity(),N}static fromHex(_){return U.fromBytes(Sr(_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=6,N=!0){return F.setWindowSize(this,_),N||this.multiply(Wc),this}assertValidity(){let _=this;if(_.is0()){if(l&&r.is0(_.X)&&r.eql(_.Y,r.ONE)&&r.is0(_.Z))return;throw new Error("bad point: ZERO")}if(V.has(_))return;let{x:N,y:W}=_.toAffine();if(!r.isValid(N)||!r.isValid(W))throw new Error("bad point: x or y not field elements");if(!S(N,W))throw new Error("bad point: equation left != right");if(!_.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");V.add(_)}hasEvenY(){let{y:_}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(_)}equals(_){O(_);let{X:N,Y:W,Z:$}=this,{X,Y,Z:G}=_,Z=r.eql(r.mul(N,G),r.mul(X,$)),ne=r.eql(r.mul(W,G),r.mul(Y,$));return Z&&ne}negate(){return new U(this.X,r.neg(this.Y),this.Z)}double(){let{X:_,Y:N,Z:W}=this,$=r.ZERO,X=r.ZERO,Y=r.ZERO,G=r.mul(_,_),Z=r.mul(N,N),ne=r.mul(W,W),oe=r.mul(_,N);return oe=r.add(oe,oe),Y=r.mul(_,W),Y=r.add(Y,Y),$=p(Y),X=r.mul(B,ne),X=r.add($,X),$=r.sub(Z,X),X=r.add(Z,X),X=r.mul($,X),$=r.mul(oe,$),Y=r.mul(B,Y),ne=p(ne),oe=r.sub(G,ne),oe=p(oe),oe=r.add(oe,Y),Y=r.add(G,G),G=r.add(Y,G),G=r.add(G,ne),G=r.mul(G,oe),X=r.add(X,G),ne=r.mul(N,W),ne=r.add(ne,ne),G=r.mul(ne,oe),$=r.sub($,G),Y=r.mul(ne,Z),Y=r.add(Y,Y),Y=r.add(Y,Y),new U($,X,Y)}add(_){O(_);let{X:N,Y:W,Z:$}=this,{X,Y,Z:G}=_,Z=r.ZERO,ne=r.ZERO,oe=r.ZERO,T=r.mul(N,X),K=r.mul(W,Y),M=r.mul($,G),ee=r.add(N,W),C=r.add(X,Y);ee=r.mul(ee,C),C=r.add(T,K),ee=r.sub(ee,C),C=r.add(N,$);let q=r.add(X,G);return C=r.mul(C,q),q=r.add(T,M),C=r.sub(C,q),q=r.add(W,$),Z=r.add(Y,G),q=r.mul(q,Z),Z=r.add(K,M),q=r.sub(q,Z),oe=p(C),Z=r.mul(B,M),oe=r.add(Z,oe),Z=r.sub(K,oe),oe=r.add(K,oe),ne=r.mul(Z,oe),K=r.add(T,T),K=r.add(K,T),M=p(M),C=r.mul(B,C),K=r.add(K,M),M=r.sub(T,M),M=p(M),C=r.add(C,M),T=r.mul(K,C),ne=r.add(ne,T),T=r.mul(q,C),Z=r.mul(ee,Z),Z=r.sub(Z,T),T=r.mul(ee,K),oe=r.mul(q,oe),oe=r.add(oe,T),new U(Z,ne,oe)}subtract(_){return O(_),this.add(_.negate())}is0(){return this.equals(U.ZERO)}multiply(_){if(!o.isValidNot0(_))throw new RangeError("invalid scalar: out of range");let{p:N,f:W}=F.mulSecret(this,_,s,j);return j([N,W])[0]}multiplyUnsafe(_){let N=this,W=_;if(!o.isValid(W))throw new RangeError("invalid scalar: out of range");if(W===zt||N.is0())return U.ZERO;if(W===jn)return N;if(F.hasWindowSize(this))return F.mulUnsafe(N,W,j);let $=[],X=[];return L($,X,N,W),os(U,$,X)}mulAddUnsafe(_,N,W){O(N);let $=[],X=[];return L($,X,this,_),L($,X,N,W),os(U,$,X)}toAffine(_){let N=this,W=_;if(W!=null&&!r.isValid(W))throw new RangeError('"invertedZ" expected valid field element');let{X:$,Y:X,Z:Y}=N;if(r.eql(Y,r.ONE))return{x:$,y:X};let G=N.is0();W==null&&(W=G?r.ONE:r.inv(Y));let Z=r.mul($,W),ne=r.mul(X,W),oe=r.mul(Y,W);if(G)return{x:r.ZERO,y:r.ZERO};if(!r.eql(oe,r.ONE))throw new Error("invZ was invalid");return{x:Z,y:ne}}isTorsionFree(){return s===jn?!0:f?f(U,this):F.mulUnsafe(this,a).is0()}clearCofactor(){return s===jn?this:u?u(U,this):this.multiplyUnsafe(s)}isSmallOrder(){return s===jn?this.is0():this.clearCofactor().is0()}toBytes(_=!0){return Ze(_,"isCompressed"),this.assertValidity(),P(U,this,_)}toHex(_=!0){return Ro(this.toBytes(_))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let j=R=>rs(U,R),F=new Tr(U,w);return F.bits>=6&&U.BASE.precompute(6),Object.freeze(U.prototype),Object.freeze(U),U}function tp(e){return Uint8Array.of(e?2:3)}function np(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Ax(e,t={}){pn(e);let{Fn:n}=e,r=t.randomBytes===void 0?Mn:t.randomBytes,o=Object.assign(np(e.Fp,n),{seed:Math.max(ts(n.ORDER),16)});function i(m){try{let w=n.fromBytes(m);return n.isValidNot0(w)}catch{return!1}}function s(m,w){let{publicKey:x,publicKeyUncompressed:y}=o;try{let k=m.length;return w===!0&&k!==x||w===!1&&k!==y?!1:!e.fromBytes(m).is0()}catch{return!1}}function a(m){return m=m===void 0?r(o.seed):m,ns(pe(m,o.seed,"seed"),n.ORDER)}function c(m,w=!0){return e.BASE.multiply(n.fromBytes(m)).toBytes(w)}function l(m){let{secretKey:w,publicKey:x,publicKeyUncompressed:y}=o,k=n._lengths;if(!dn(m))return;let I=pe(m,void 0,"key").length,g=I===x||I===y,P=I===w||!!k?.includes(I);if(!(g&&P))return g}function u(m,w,x=!0){if(l(m)===!0)throw new Error("first arg must be private key");if(l(w)===!1)throw new Error("second arg must be public key");let y=n.fromBytes(m),k=e.fromBytes(w);if(k.is0())throw new Error("invalid public key: point at infinity");return k.multiply(y).toBytes(x)}let f={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},h=ss(a,c);return Object.freeze(f),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:h,Point:e,utils:f,lengths:o})}function rp(e,t,n={}){pn(e);let r=t;gr(r),Je(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let o=Object.assign({},n),i=o.randomBytes===void 0?Mn:o.randomBytes,s=o.hmac===void 0?(R,_)=>ds(r,R,_):o.hmac,{Fp:a,Fn:c}=e,{ORDER:l,BITS:u}=c,f=ts(l),h=Rc(i,f),{keygen:m,getPublicKey:w,getSharedSecret:x,utils:y,lengths:k}=Ax(e,o),I={prehash:!0,lowS:typeof o.lowS=="boolean"?o.lowS:!0,format:"compact",extraEntropy:!1},g=l*Jf+jn<a.ORDER;function P(R){let _=l>>jn;return R>_}function E(R,_){if(!c.isValidNot0(_))throw new Error(`invalid signature ${R}: out of range 1..Point.Fn.ORDER`);return _}function B(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function p(R,_,N){return B(),(R===N?0:2)|Number(a.isOdd(_))}function b(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function S(R,_){Vc(_);let N=k.signature,W=_==="compact"?N:_==="recovered"?N+1:void 0;return pe(R,W)}class v{r;s;recovery;constructor(_,N,W){if(this.r=E("r",_),this.s=E("s",N),W!=null){if(b(),![0,1,2,3].includes(W))throw new Error("invalid recovery id");this.recovery=W}Object.freeze(this)}static fromBytes(_,N=I.format){S(_,N);let W;if(N==="der"){if(_.length>2*c.BYTES+16)throw new fs.Err("invalid signature: DER signature too long");let{r:G,s:Z}=fs.toSig(pe(_),c.BYTES+1);return new v(G,Z)}N==="recovered"&&(W=_[0],N="compact",_=_.subarray(1));let $=k.signature/2,X=_.subarray(0,$),Y=_.subarray($,$*2);return new v(c.fromBytes(X),c.fromBytes(Y),W)}static fromHex(_,N){return this.fromBytes(Sr(_),N)}assertRecovery(){let{recovery:_}=this;if(_==null)throw new Error("invalid recovery id: must be present");return _}addRecoveryBit(_){return new v(this.r,this.s,_)}recoverPublicKey(_){let{r:N,s:W}=this,$=this.assertRecovery(),X=$===2||$===3?N+l:N;if(!a.isValid(X))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let Y=a.toBytes(X),G=e.fromBytes(dt(tp(($&1)===0),Y)),Z=c.inv(X),ne=A(pe(_,void 0,"msgHash")),oe=c.create(-ne*Z),T=c.create(W*Z),K=e.BASE.mulAddUnsafe(oe,G,T);if(K.is0())throw new Error("invalid recovery: point at infinify");return K.assertValidity(),K}hasHighS(){return P(this.s)}toBytes(_=I.format){if(Vc(_),_==="der")return Sr(fs.hexFromSig(this));let{r:N,s:W}=this,$=c.toBytes(N),X=c.toBytes(W);return _==="recovered"?(b(),dt(Uint8Array.of(this.assertRecovery()),$,X)):dt($,X)}toHex(_){return Ro(this.toBytes(_))}}Object.freeze(v.prototype),Object.freeze(v);let H=o.bits2int===void 0?function(_){if(_.length>8192)throw new Error("input is too large");let N=Rt(_),W=_.length*8-u;return W>0?N>>BigInt(W):N}:o.bits2int,A=o.bits2int_modN===void 0?function(_){return c.create(H(_))}:o.bits2int_modN,O=Fo(u);function D(R){return vr("num < 2^"+u,R,zt,O),c.toBytes(R)}function L(R,_){return pe(R,void 0,"message"),_?pe(r(R),void 0,"prehashed message"):R}function V(R,_,N){let{lowS:W,prehash:$,extraEntropy:X}=jc(N,I);R=L(R,$);let Y=A(R),G=c.fromBytes(_);if(!c.isValidNot0(G))throw new Error("invalid private key");let Z=[D(G),D(Y)];if(X!=null&&X!==!1){let K=X===!0?i(k.secretKey):X;Z.push(pe(K,void 0,"extraEntropy"))}let ne=dt(...Z),oe=Y;function T(K){let M=H(K);if(!c.isValidNot0(M))return;let ee=e.BASE.multiply(M).toAffine(),C=c.create(ee.x);if(C===zt)return;let q;if(h!==void 0){let re=Rt(ns(h(f),l)),ae=c.inv(c.mul(re,M)),Ge=c.mul(re,oe),ie=c.mul(re,G);q=c.create(ae*c.create(Ge+ie*C))}else{let re=Cf(M,l);q=c.create(re*c.create(oe+C*G))}if(q===zt)return;let J=p(ee.x,ee.y,C),le=q;return W&&P(q)&&(le=c.neg(q),J^=1),new v(C,le,g?void 0:J)}return{seed:ne,k2sig:T}}function U(R,_,N={}){let{seed:W,k2sig:$}=V(R,_,N);return Af(r.outputLen,c.BYTES,s)(W,$).toBytes(N.format)}function j(R,_,N,W={}){let{lowS:$,prehash:X,format:Y}=jc(W,I);if(N=pe(N,void 0,"publicKey"),_=L(_,X),!dn(R)){let G=R instanceof v?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+G)}S(R,Y);try{let G=v.fromBytes(R,Y),Z=e.fromBytes(N);if(Z.is0()||$&&G.hasHighS())return!1;let{r:ne,s:oe}=G,T=A(_),K=c.inv(oe),M=c.create(T*K),ee=c.create(ne*K),C=e.BASE.mulAddUnsafe(M,Z,ee);if(C.is0())return!1;let q=C.toAffine();return!(c.create(q.x)!==ne||Y==="recovered"&&G.recovery!==p(q.x,q.y,ne))}catch{return!1}}function F(R,_,N={}){let{prehash:W}=jc(N,I);return _=L(_,W),v.fromBytes(R,"recovered").recoverPublicKey(_).toBytes()}return Object.freeze({keygen:m,getPublicKey:w,getSharedSecret:x,utils:y,lengths:k,Point:e,sign:U,verify:j,recoverPublicKey:F,Signature:v,hash:r})}var Zf,zt,jn,Jf,Wc,Ex,op=Le(()=>{Mc();Ct();Ar();Hc();Qf();Nr();Zf=(e,t)=>(e+(e>=0?t:-t)/Jf)/t;zt=BigInt(0),jn=BigInt(1),Jf=BigInt(2),Wc=BigInt(3),Ex=BigInt(4)});function Ix(e){let t=zc.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,f=Se(u,n,t)*u%t,h=Se(f,n,t)*u%t,m=Se(h,ip,t)*l%t,w=Se(m,o,t)*m%t,x=Se(w,i,t)*w%t,y=Se(x,a,t)*x%t,k=Se(y,c,t)*y%t,I=Se(k,a,t)*x%t,g=Se(I,n,t)*u%t,P=Se(g,s,t)*w%t,E=Se(P,r,t)*l%t,B=Se(E,ip,t);if(!$c.eql($c.sqr(B),e))throw new Error("Cannot find square root");return B}var zc,_x,ip,$c,Nx,Ce,sp=Le(()=>{Yi();Nr();op();zc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},_x={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},ip=BigInt(2);$c=Ir(zc.p,{sqrt:Ix}),Nx=ep(zc,{Fp:$c,endo:_x}),Ce=rp(Nx,Xi)});function Mx(e,t=24){if(!(e instanceof Uint32Array))throw new TypeError('"s" expected Uint32Array(50), got type='+typeof e);if(e.length!==50)throw new RangeError('"s" expected Uint32Array(50), got length='+e.length);if(Te(t,"rounds"),t<1||t>24)throw new Error('"rounds" expected integer 1..24');for(let n=24-t;n<24;n++){for(let i=0;i<10;i++)Pr[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){let s=(i+8)%10,a=(i+2)%10,c=Pr[a],l=Pr[a+1],u=ap(c,l,1)^Pr[s],f=cp(c,l,1)^Pr[s+1];for(let h=0;h<50;h+=10)e[i+h]^=u,e[i+h+1]^=f}let r=e[2],o=e[3];for(let i=0;i<24;i++){let s=up[i],a=ap(r,o,s),c=cp(r,o,s),l=lp[i];r=e[l],o=e[l+1],e[l]=a,e[l+1]=c}for(let i=0;i<50;i+=10){let s=e[i],a=e[i+1],c=e[i+2],l=e[i+3];e[i]^=~e[i+2]&e[i+4],e[i+1]^=~e[i+3]&e[i+5],e[i+2]^=~e[i+4]&e[i+6],e[i+3]^=~e[i+5]&e[i+7],e[i+4]^=~e[i+6]&e[i+8],e[i+5]^=~e[i+7]&e[i+9],e[i+6]^=~e[i+8]&s,e[i+7]^=~e[i+9]&a,e[i+8]^=~s&c,e[i+9]^=~a&l}e[0]^=Rx[n],e[1]^=Hx[n]}qe(Pr)}var Tx,Mo,Px,Bx,Ox,Cx,lp,up,dp,fp,Rx,Hx,Lx,Fx,Dx,Ux,ap,cp,Pr,Xc,pp,Yc,ps,Gc=Le(()=>{Ki();Ct();Tx=BigInt(0),Mo=BigInt(1),Px=BigInt(2),Bx=BigInt(7),Ox=BigInt(256),Cx=BigInt(113),lp=[],up=[],dp=[];for(let e=0,t=Mo,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],lp.push(2*(5*r+n)),up.push((e+1)*(e+2)/2%64);let o=Tx;for(let i=0;i<7;i++)t=(t<<Mo^(t>>Bx)*Cx)%Ox,t&Px&&(o^=Mo<<(Mo<<BigInt(i))-Mo);dp.push(o)}fp=Mi(dp,!0),Rx=fp[0],Hx=fp[1],Lx=(e,t,n)=>e<<n|t>>>32-n,Fx=(e,t,n)=>t<<n|e>>>32-n,Dx=(e,t,n)=>t<<n-32|e>>>64-n,Ux=(e,t,n)=>e<<n-32|t>>>64-n,ap=(e,t,n)=>n>32?Dx(e,t,n):Lx(e,t,n),cp=(e,t,n)=>n>32?Ux(e,t,n):Fx(e,t,n),Pr=new Uint32Array(10);Xc=class e{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;canXOF;enableXOF=!1;rounds;constructor(t,n,r,o=!1,i=24){if(Te(t,"blockLen"),Te(n,"suffix"),Te(i,"rounds"),hf(o,"enableXOF"),this.blockLen=t,this.suffix=n,this.outputLen=r,this.enableXOF=o,this.canXOF=o,this.rounds=i,Te(r,"outputLen"),!(0<t&&t<200))throw new Error('"blockLen" must be 1..199');this.state=new Uint8Array(200),this.state32=wc(this.state)}clone(){return this._cloneInto()}keccak(){yc(this.state32),Mx(this.state32,this.rounds),yc(this.state32),this.posOut=0,this.pos=0}update(t){Wt(this),Fe(t);let{blockLen:n,state:r,state32:o}=this,i=t.length,s=n%4===0&&t.byteOffset%4===0,a=n/4,c=s&&i>=n?wc(t):void 0;for(let l=0;l<i;){if(c!==void 0&&this.pos===0&&l%4===0&&i-l>=n){for(let f=0,h=l/4;f<a;f++)o[f]^=c[h+f];l+=n,this.pos=n,this.keccak();continue}let u=Math.min(n-this.pos,i-l);for(let f=0;f<u;f++)r[this.pos++]^=t[l++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:t,suffix:n,pos:r,blockLen:o}=this;t[r]^=n,(n&128)!==0&&r===o-1&&this.keccak(),t[o-1]^=128,this.keccak()}writeInto(t){Wt(this,!1),Fe(t),this.finish();let n=this.state,{blockLen:r}=this;for(let o=0,i=t.length;o<i;){this.posOut>=r&&this.keccak();let s=Math.min(r-this.posOut,i-o);t.set(n.subarray(this.posOut,this.posOut+s),o),this.posOut+=s,o+=s}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not enabled");return this.writeInto(t)}xof(t){return Te(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(xr(t,this),this.finished)throw new Error("digest() was already called");this.writeInto(t.length===this.outputLen?t:t.subarray(0,this.outputLen)),this.destroy()}digest(){let t=new Uint8Array(this.outputLen);return this.digestInto(t),t}destroy(){this.destroyed=!0,qe(this.state)}_cloneInto(t){let{blockLen:n,suffix:r,outputLen:o,rounds:i,enableXOF:s}=this;return t||=new e(n,r,o,s,i),t.blockLen=n,t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=i,t.suffix=r,t.outputLen=o,t.enableXOF=s,t.canXOF=this.canXOF,t.destroyed=this.destroyed,t}},pp=(e,t,n,r={})=>Po(()=>new Xc(t,e,n),r),Yc=pp(6,72,64,Bo(10)),ps=pp(1,136,32)});var d,z,fe=Le(()=>{d=class extends Error{constructor(t,n={}){super(t),this.name="SdkError",this.code=t,this.params=n}toJSON(){return{code:this.code,params:this.params}}},z=(e,t)=>{throw new d(e,t)}});var hp={};Be(hp,{ed25519:()=>_e,keccak256:()=>Q,keccak256Bytes:()=>Kx,primitives:()=>Xt,randomBytes:()=>Wn,secp256k1:()=>Ce,sha3_512:()=>Yc});var Q,Kx,Wn,Xt,Ee=Le(()=>{Uc();sp();Gc();fe();Q=e=>{let t=typeof e=="string"?new TextEncoder().encode(e):e;return ps(t)},Kx=e=>Q(e),Wn=e=>{let t=new Uint8Array(e),n=globalThis.crypto;return(!n||typeof n.getRandomValues!="function")&&z("bad-input",{field:"random-bytes",why:"no-source"}),n.getRandomValues(t),t},Xt={ed25519:_e,secp256k1:Ce,keccak256:Q,sha3_512:Yc,randomBytes:Wn}});var mn={};Be(mn,{PREFIX_BY_NETWORK:()=>ms,addressForNetwork:()=>zx,addressFromKeys:()=>hn,addressPayload:()=>kp,checkAddress:()=>Jc,decodeMoneroBase58:()=>ws,encodeMoneroBase58:()=>xp,formatCheck:()=>Qc,isStagenetShaped:()=>Vx,networkFromShape:()=>Zc,prefixFor:()=>bp});function bp(e,t="primary"){let n=ms[e];if(!n)throw new Error("Unknown network: "+e);let r=n[t];if(r===void 0)throw new Error("Unknown address kind: "+t);return r}function Qc(e){let t=String(e||"").trim();return![95,106].includes(t.length)||!/^[1-9A-HJ-NP-Za-km-z]+$/.test(t)?!1:["4","5","7","8","9","A","B"].includes(t[0])}function Zc(e){let t=String(e||"").trim();return Qc(t)?t[0]==="4"||t[0]==="8"?"mainnet":t[0]==="5"||t[0]==="7"?"stagenet":["9","A","B"].includes(t[0])?"testnet":null:null}function Vx(e){return Zc(e)==="stagenet"}function wp(e){let t=0n;for(let r of e)t=t<<8n|BigInt(r);let n="";for(;t>0n;)n=gp[Number(t%58n)]+n,t/=58n;return n}function yp(e,t){let n=0n;for(let o of e){let i=$x.get(o);if(i===void 0)throw new Error("Invalid Monero base58 character: "+o);n=n*58n+i}let r=new Uint8Array(t);for(let o=t-1;o>=0;o--)r[o]=Number(n&0xffn),n>>=8n;if(n!==0n)throw new Error("Base58 block does not fit in "+t+" bytes");return r}function ws(e){let t=String(e),n=t.length,r=n%hs,o=r===0?hs:r,i=jx[o];if(!i)throw new Error("Invalid Monero base58 length");let s=[],a=n-o;for(let u=0;u<a;u+=hs)s.push(yp(t.slice(u,u+hs),8));s.push(yp(t.slice(a),i));let c=new Uint8Array(s.reduce((u,f)=>u+f.length,0)),l=0;for(let u of s)c.set(u,l),l+=u.length;return c}function xp(e){let t=Array.from(e),n=t.length,r=n%8,o=r===0?8:r,i=n-o,s="";for(let c=0;c<i;c+=8){let l=wp(t.slice(c,c+8));s+="1".repeat(Math.max(0,mp[8]-l.length))+l}let a=wp(t.slice(i));return s+="1".repeat(Math.max(0,mp[o]-a.length))+a,s}function kp({network:e,kind:t="primary",spendPub:n,viewPub:r,paymentId:o}){let i=bp(e,t),s=qc(n,32,"public spend key"),a=qc(r,32,"public view key"),c=[i,...s,...a];if(t==="integrated"){let l=qc(o,8,"payment id");c.push(...l)}return Uint8Array.from(c)}function qc(e,t,n){let r=String(e||"").trim();if(!new RegExp("^[0-9a-fA-F]{"+t*2+"}$").test(r))throw new Error("Bad "+n+": expected "+t*2+" hex characters");let o=new Uint8Array(t);for(let i=0;i<t;i++)o[i]=parseInt(r.slice(i*2,i*2+2),16);return o}function hn({network:e,kind:t="primary",spendPub:n,viewPub:r,paymentId:o},i){if(!i?.keccak256)throw new Error("addressFromKeys needs { keccak256 }");let s=kp({network:e,kind:t,spendPub:n,viewPub:r,paymentId:o}),a=i.Buffer?i.Buffer.from(s):s,c=Uint8Array.from(i.keccak256(a)),l=new Uint8Array(s.length+4);return l.set(s,0),l.set(c.slice(0,4),s.length),xp(l)}async function Jc(e,t={}){let n=String(e||"").trim();if(!Qc(n))return{ok:!1,reason:"Not a Monero address (expected 95 or 106 base58 characters)"};let r=Zc(n);if(t.expectNetwork&&r&&r!==t.expectNetwork)return{ok:!1,reason:`This is a ${r} address, but the swap runs on ${t.expectNetwork}`};try{let o=ws(n),i=o.length-4;if(i<65)throw new Error("Address is too short");let s=o.slice(0,i),a=o.slice(i),c=Uint8Array.from(Q(s));if(!(a.length===4&&a.every((h,m)=>h===c[m])))return{ok:!1,reason:"Checksum mismatch: the address has a typo, is corrupted, or is a demo mock address (mock addresses have no checksum)"};let u=s[0],f=Wx[u]||{network:"unknown",kind:"unknown"};return f.network==="unknown"?{ok:!1,reason:`Unsupported address prefix ${u}`}:t.expectNetwork&&f.network!==t.expectNetwork?{ok:!1,reason:`This is a ${f.network} address, but the swap runs on ${t.expectNetwork}`}:{ok:!0,verified:!0,network:f.network,kind:f.kind,bytes:o.length}}catch(o){return{ok:!1,reason:"Address decode failed: "+o.message}}}async function zx({network:e,kind:t="primary",spendPub:n,viewPub:r}){return hn({network:e,kind:t,spendPub:n,viewPub:r},{keccak256:Q})}var hs,mp,jx,Wx,ms,gp,$x,Vn=Le(()=>{Ee();hs=11,mp={1:2,2:3,3:5,4:6,5:7,6:9,7:10,8:11},jx={2:1,3:2,5:3,6:4,7:5,9:6,10:7,11:8},Wx={18:{network:"mainnet",kind:"primary"},19:{network:"mainnet",kind:"integrated"},42:{network:"mainnet",kind:"subaddress"},24:{network:"stagenet",kind:"primary"},25:{network:"stagenet",kind:"integrated"},36:{network:"stagenet",kind:"subaddress"},53:{network:"testnet",kind:"primary"},54:{network:"testnet",kind:"integrated"},63:{network:"testnet",kind:"subaddress"}},ms={mainnet:{primary:18,integrated:19,subaddress:42},stagenet:{primary:24,integrated:25,subaddress:36},testnet:{primary:53,integrated:54,subaddress:63}};gp="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",$x=(()=>{let e=new Map;return[...gp].forEach((t,n)=>e.set(t,BigInt(n))),e})()});var Yt={};Be(Yt,{createHalves:()=>Wo});function Wo({ed25519:e,secp256k1:t,keccak256:n,randomBytes:r}){for(let[k,I]of[["ed25519",e],["secp256k1",t],["keccak256",n],["randomBytes",r]])if(!I)throw new Error("createHalves: not passed "+k);let o=e.Point.Fn.ORDER,i=t.Point.Fn.ORDER,s=o<i?o:i;function a(){for(let k=0;k<256;k++){let I=r(32),g=0n;for(let P of I)g=g<<8n|BigInt(P);if(g>0n&&g<s)return g}throw new Error("newHalf: could not get a scalar in 256 attempts")}let c="ninsei-order-half-v1",l="ninsei-order-view-v1";function u(k,I,g=c){if(!k||k.length<16)throw new Error("halfFromSeed: secret shorter than 16 bytes");if(!I)throw new Error("halfFromSeed: order binding not set");let P=new TextEncoder().encode(g+"|"+String(I)+"|");for(let E=0;E<256;E++){let B=new Uint8Array(P.length+k.length+4);B.set(P,0),B.set(k,P.length),B[P.length+k.length]=E>>>24&255,B[P.length+k.length+1]=E>>>16&255,B[P.length+k.length+2]=E>>>8&255,B[P.length+k.length+3]=E&255;let p=n(B),b=0n;for(let S of p)b=b<<8n|BigInt(S);if(b>0n&&b<s)return b}throw new Error("halfFromSeed: could not get a scalar in 256 attempts")}function f(k,I){return k.fromHex(I.startsWith("0x")?I.slice(2):I)}function h(k){if(typeof k=="bigint")return k;if(typeof k=="string"){let I=k.trim().replace(/^0x/,"");if(!/^[0-9a-fA-F]{1,64}$/.test(I))throw new Error("half does not look like a number: "+k.slice(0,12));return BigInt("0x"+I)}if(typeof k=="number")return BigInt(k);throw new Error("half of unknown type: "+typeof k)}function m(k){return k.toHex()}function w(k){return{ed:m(e.Point.BASE.multiply(h(k))),secp:m(t.Point.BASE.multiply(h(k)))}}function x(k,I){return(h(k)+h(I))%o}function y(k,I){return m(f(e.Point,k).add(f(e.Point,I)))}return{LIMIT:s,ED_ORDER:o,SECP_ORDER:i,HALF_DOMAIN:c,VIEW_HALF_DOMAIN:l,newHalf:a,halfFromSeed:u,publicHalves:w,combineHalves:x,combinePublic:y}}var Vo=Le(()=>{});var Yy=cg(()=>{});var ce={};Be(ce,{ALLOWED_PROVIDERS:()=>Jd,API:()=>on,APP:()=>_o,ASYNC_ROUTE_PROVIDERS:()=>Fi,CHAINS:()=>br,DEFAULT_CHAIN:()=>Hn,DEMO:()=>Kt,DEPLOYMENTS:()=>mr,DEPLOYMENT_CHAINS:()=>qd,DEPLOYMENT_VMS:()=>Qd,DEX_ASSETS:()=>Zd,DEX_CHAINS:()=>fg,DEX_HUBS:()=>pg,DEX_PRICE_GATE:()=>hg,DEX_ROUTES:()=>mg,ENDPOINTS:()=>Li,KNOWN_FACTORY_CODES:()=>ef,MONERO:()=>Re,SCENARIO_LABELS:()=>vg,SIGNING_DOMAIN:()=>dg,SIGNING_GUARDS:()=>Io,SWEEP:()=>ac,TEST_CLAIMER:()=>kg,TIMING:()=>St,XMR_NETWORKS:()=>nf,allowedProvidersFor:()=>wg,chainByChainId:()=>cc,chainById:()=>lt,deploymentFor:()=>ic,knownFactoryCodesFor:()=>yg,knownImplementationCodesFor:()=>bg,nativeOf:()=>tf,sweepOrigin:()=>Sg,tokenById:()=>xg,tokensOf:()=>lc,wrappedNativeOf:()=>gg});var Hi=e=>{if(e&&typeof e=="object"){Object.freeze(e);for(let t of Object.values(e))Hi(t)}return e},oc={"arbitrum-sepolia":{vm:"evm",network:"arbitrum-sepolia",caip2:"eip155:421614",chainRef:"421614",status:"live",release:{tag:"contracts-testnet-2026.11.04",commit:"930366a387c0c696bda6f5c038f23617447ebb78",toolchain:"0.8.38",deployedAt:"2026-11-04T15:00:55.822Z"},anchor:{kind:"block",value:"326005419"},artifacts:{factory:{role:"factory",kind:"contract",address:"0x245d3a4ac4b98d713f6c5130b56cd5d550f8cefe",addressFormat:"hex-20",codeHash:"0x1fdfa1c922f660506243cab4c889aa83e22ce27d818bac9c5e4ecbccbdd04906",hashKind:"keccak256",tx:{kind:"hash",value:"0xf62f54cbb0c236edc467652fce8c746c903a5d0ab4ecdd492649d57a92862296"}},cashier:{role:"cashier",kind:"contract",address:"0x40515449159EfbCb5eF5eB9e2E08ba432E150a1C",addressFormat:"hex-20",tx:{kind:"hash",value:"0xf62f54cbb0c236edc467652fce8c746c903a5d0ab4ecdd492649d57a92862296"}},registry:{role:"registry",kind:"contract",address:"0x92191dc3517e15db6468628b1a493576728a9798",addressFormat:"hex-20",tx:{kind:"hash",value:"0x8f60792dac889008ec5678c6f30790730d278518d512a3b19657829896391adf"}},implementation:{role:"implementation",kind:"contract",address:"0xF88658b53FcB965E580638bbFe048E8f587d6D11",addressFormat:"hex-20",codeHash:"0x7020a1017adbb4d4ce4710f7c632d48a5469a6f3076608e77d5675dee125653c",hashKind:"keccak256",tx:{kind:"hash",value:"0xf62f54cbb0c236edc467652fce8c746c903a5d0ab4ecdd492649d57a92862296"}}},escrow:{address:"0x245d3a4ac4b98d713f6c5130b56cd5d550f8cefe",mode:"live",deploymentBlock:326005419,cashier:"0x40515449159EfbCb5eF5eB9e2E08ba432E150a1C",registry:"0x92191dc3517e15db6468628b1a493576728a9798",implementationCodeHash:"0x7020a1017adbb4d4ce4710f7c632d48a5469a6f3076608e77d5675dee125653c"},knownFactoryCodes:["0x1fdfa1c922f660506243cab4c889aa83e22ce27d818bac9c5e4ecbccbdd04906"]}},mr=Hi(oc),qd=Hi(Object.keys(oc).sort()),Qd=Hi([...new Set(Object.values(oc).map(e=>e.vm))].sort());function ic(e){if(e==null)return null;let t=typeof e=="object"?e.id??e.network??e.caip2:e;return t==null?null:typeof t=="number"||/^[0-9]+$/.test(String(t))?Object.values(mr).find(n=>Number(n.chainRef)===Number(t))??null:mr[t]??Object.values(mr).find(n=>n.caip2===t)??null}var wr=typeof window<"u"&&window.NINSEI_DEPLOY?window.NINSEI_DEPLOY:null,yr=typeof process<"u"&&process.env?process.env:null,sc=Object.freeze({moneroNode:"http://127.0.0.1:38081",evmRpc:"http://127.0.0.1:8545",sweepOrigin:"http://localhost:5195"}),Li=Object.freeze({moneroNode:wr&&wr.moneroNode||yr&&yr.NINSEI_MONERO_NODE||sc.moneroNode,evmRpc:wr&&wr.evmRpc||yr&&yr.NINSEI_EVM_RPC||sc.evmRpc,sweepOrigin:wr&&wr.sweepOrigin||yr&&yr.NINSEI_SWEEP_ORIGIN||sc.sweepOrigin}),dg=Object.freeze({name:"NinseiEscrowFactory",version:"1"}),_o={name:"NinseiSwap",version:"0.1.0",demo:!0,storageKey:"ninsei.demo.v1"},fg=["arbitrum-sepolia","arbitrum","mainnet"],Zd=["USDT","USDC","DAI","USDS","USDe","PyUSD"],pg=["USDC","USDT","DAI"],hg={maxDeviationPct:2,stableBandPct:1,stables:Zd},Io={minReadyLeadSec:600,minClaimWindowSec:600,maxDeadlineSec:259200,readyLeadWarnSec:600},mg={"arbitrum-sepolia":{USDC:{steps:[{to:"WETH",fee:3e3,pool:"0x66eeab70ac52459dd74c6ad50d578ef76a441bbf",verified:{at:"2026-09-23",block:311900041}}]}},arbitrum:{USDT:{steps:[{to:"WETH",fee:500,pool:"0x641c00a822e8b671738d32a431a4fb6074e5c79d",verified:{at:"2026-09-23",block:508125577}}]},USDC:{steps:[{to:"WETH",fee:100,pool:"0x6f38e884725a116c9c7fbf208e79fe8828a2595f",verified:{at:"2026-09-23",block:508125577}}]},DAI:{steps:[{to:"WETH",fee:3e3,pool:"0xa961f0473da4864c5ed28e00fcc53a3aab056c1b",verified:{at:"2026-09-23",block:508125577}}]},USDe:{steps:[{to:"USDC",fee:100,pool:"0x3223859e24d5413947761cb79d3094f21be69bfa",verified:{at:"2026-09-23",block:508125577}},{to:"WETH",fee:100,pool:"0x6f38e884725a116c9c7fbf208e79fe8828a2595f",verified:{at:"2026-09-23",block:508125577}}]},WETH:{steps:[],unwrap:!0}},mainnet:{USDT:{steps:[{to:"WETH",fee:500,pool:"0x11b815efb8f581194ae79006d24e0d814b7697f6",verified:{at:"2026-09-23",block:26040283}}]},USDC:{steps:[{to:"WETH",fee:100,pool:"0xe0554a476a092703abdb3ef35c80e0d76d32939f",verified:{at:"2026-09-23",block:26040283}}]},DAI:{steps:[{to:"WETH",fee:500,pool:"0x60594a405d53811d3bc4766596efd80fd545a270",verified:{at:"2026-09-23",block:26040283}}]},USDe:{steps:[{to:"USDC",fee:100,pool:"0xe6d7ebb9f1a9519dc06d557e03c522d53520e76a",verified:{at:"2026-09-23",block:26040283}},{to:"WETH",fee:100,pool:"0xe0554a476a092703abdb3ef35c80e0d76d32939f",verified:{at:"2026-09-23",block:26040283}}]},USDS:{steps:[{to:"USDC",fee:3e3,pool:"0xa66a2770bc0e0c65b63b5a3bb4560e90f95d6146",verified:{at:"2026-09-23",block:26040283}},{to:"WETH",fee:100,pool:"0xe0554a476a092703abdb3ef35c80e0d76d32939f",verified:{at:"2026-09-23",block:26040283}}]},PyUSD:{steps:[{to:"USDC",fee:100,pool:"0x13394005c1012e708fce1eb974f1130fdc73a5ce",verified:{at:"2026-09-23",block:26040283}},{to:"WETH",fee:100,pool:"0xe0554a476a092703abdb3ef35c80e0d76d32939f",verified:{at:"2026-09-23",block:26040283}}]},WETH:{steps:[],unwrap:!0}}},Fi={cowswap:{venue:"CoWSwap",shape:"async",settles:"native",networks:{1:{slug:"mainnet",orderbook:"https://api.cow.fi/mainnet"},100:{slug:"xdai",orderbook:"https://api.cow.fi/xdai"},42161:{slug:"arbitrum_one",orderbook:"https://api.cow.fi/arbitrum_one"},8453:{slug:"base",orderbook:"https://api.cow.fi/base"},56:{slug:"bnb",orderbook:"https://api.cow.fi/bnb"},11155111:{slug:"sepolia",orderbook:"https://api.cow.fi/sepolia"}}},kyberswap:{venue:"KyberSwap Limit Order",shape:"async",settles:"wrapped",networks:{1:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},10:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},56:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},137:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},250:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},324:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},5e3:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},8453:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},42161:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},43114:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},59144:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},534352:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"},81457:{orderbook:"https://limit-order.kyberswap.com",contract:"0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C"}}},uniswapx:{venue:"UniswapX",shape:"async",settles:"native",networks:{1:{orderbook:"https://api.uniswap.org/v2",reactor:"0x00000011F84B9aa48e5f8aA8B9897600006289Be",submitter:"/api/uniswapx/order"}}},uniswaprelay:{venue:"Uniswap Relay",shape:"async",settles:"native",networks:{1:{reactor:"0x0000000000A4e21E2597DCac987455c48b12edBF",universalRouter:"0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD"}}}},br=[{id:"arbitrum-sepolia",name:"Arbitrum Sepolia",vm:"evm",chainId:421614,caip2:"eip155:421614",testnet:!0,native:{symbol:"ETH",decimals:18,usd:3212.4},rpcUrl:Li.evmRpc,priceFeed:{address:"0xd30e2101a97dcbAeBCBC04F14C3f624E67A35165",pair:"ETH / USD",decimals:8,min:100,max:2e4},explorerTx:"https://sepolia.arbiscan.io/tx/",explorerAddr:"https://sepolia.arbiscan.io/address/",explorerName:"arbiscan (sepolia)",gasUsd:.01,routeType:"atomic",escrow:ic("arbitrum-sepolia").escrow,tokens:[{symbol:"USDC",address:"0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d",decimals:6,usd:1,cls:"ar-token-usdc"},{symbol:"WETH",address:"0x980B62Da83eFf3D4576C647993b0c1D7faf17c73",decimals:18,cls:"ar-token-eth",peg:"native",hidden:!0}],uniswap:{factory:"0x248ab79bbb9bc29bb72f7cd42f17e054fc40188e",quoter:"0x2779a0CC1c3e0E44D2542EC3e79e3864Ae93Ef0B",router:"0x101F443B4d1b059569D643917553c771E1b9663E",permit2:"0x000000000022D473030F116dDEE9F6B43aC78BA3",wrapped:{symbol:"WETH",name:"Wrapped Ether",address:"0x980B62Da83eFf3D4576C647993b0c1D7faf17c73",decimals:18},feeTiers:[100,500,3e3,1e4]},dexPriceGate:"tolerated"},{id:"local-anvil",name:"Local (anvil)",hidden:!0,vm:"evm",chainId:31337,caip2:"eip155:31337",testnet:!0,native:{symbol:"ETH",decimals:18,usd:3212.4},rpcUrl:"http://127.0.0.1:8545",priceFeed:null,explorerTx:"",explorerAddr:"",explorerName:"",gasUsd:1e-4,routeType:"atomic",escrow:{address:"0xcbEAF3BDe82155F56486Fb5a1072cb8baAf547cc",mode:"live",cashier:"0x1429859428C0aBc9C2C47C8Ee9FBaf82cFA0F20f",implementationCodeHash:"0xfd1ef12c1d96d3ee7060bd5901e06108723783403fad00c9630dcdeb6193674b"},tokens:[]},{id:"arbitrum",name:"Arbitrum One",vm:"evm",chainId:42161,caip2:"eip155:42161",native:{symbol:"ETH",decimals:18,usd:3212.4},rpcUrl:"https://arb1.arbitrum.io/rpc",priceFeed:{address:"0x639Fe6ab55C921f74e7fac1ee960C0B6293ba612",pair:"ETH / USD",decimals:8,min:100,max:2e4},explorerTx:"https://arbiscan.io/tx/",explorerAddr:"https://arbiscan.io/address/",explorerName:"arbiscan",gasUsd:.21,routeType:"atomic",escrow:{address:null,mode:"simulated"},tokens:[{symbol:"USDC",address:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",decimals:6,usd:1,cls:"ar-token-usdc"},{symbol:"USDT",onChainSymbol:"USD\u20AE0",address:"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",decimals:6,usd:1,cls:"ar-token-usdt"},{symbol:"DAI",address:"0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1",decimals:18,usd:1,cls:"ar-token-dai"},{symbol:"USDe",address:"0x5d3a1Ff2b6BAb83b63cd9AD0787074081a52ef34",decimals:18,usd:1,cls:"ar-token-usde"},{symbol:"WETH",address:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",decimals:18,cls:"ar-token-eth",peg:"native",hidden:!0}],uniswap:{factory:"0x1F98431c8aD98523631AE4a59f267346ea31F984",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",wrapped:{symbol:"WETH",name:"Wrapped Ether",address:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",decimals:18},feeTiers:[100,500,3e3,1e4]}},{id:"mainnet",name:"Ethereum",vm:"evm",chainId:1,caip2:"eip155:1",native:{symbol:"ETH",decimals:18,usd:3212.4},rpcUrl:"https://ethereum-rpc.publicnode.com",priceFeed:{address:"0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419",pair:"ETH / USD",decimals:8,min:100,max:2e4},explorerTx:"https://etherscan.io/tx/",explorerAddr:"https://etherscan.io/address/",explorerName:"etherscan",gasUsd:3.4,routeType:"atomic",escrow:{address:null,mode:"simulated"},tokens:[{symbol:"USDC",address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",decimals:6,usd:1,cls:"ar-token-usdc"},{symbol:"USDT",address:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,usd:1,cls:"ar-token-usdt"},{symbol:"DAI",address:"0x6B175474E89094C44Da98b954EedeAC495271d0F",decimals:18,usd:1,cls:"ar-token-dai"},{symbol:"USDe",address:"0x4c9EDD5852cd905f086C759E8383e09bff1E68B3",decimals:18,usd:1,cls:"ar-token-usde"},{symbol:"USDS",address:"0xdC035D45d973E3EC169d2276DDab16f1e407384F",decimals:18,usd:1,cls:"ar-token-usds"},{symbol:"PyUSD",address:"0x6c3ea9036406852006290770BEdFcAbA0e23A0e8",decimals:6,usd:1,cls:"ar-token-pyusd"},{symbol:"WETH",address:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",decimals:18,cls:"ar-token-eth",peg:"native",hidden:!0}],uniswap:{factory:"0x1F98431c8aD98523631AE4a59f267346ea31F984",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",wrapped:{symbol:"WETH",name:"Wrapped Ether",address:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",decimals:18},feeTiers:[100,500,3e3,1e4]}},{id:"base",name:"Base",vm:"evm",chainId:8453,caip2:"eip155:8453",native:{symbol:"ETH",decimals:18,usd:3212.4},rpcUrl:"https://mainnet.base.org",priceFeed:{address:"0x71041dddad3595F9CEd3DcCFBe3D1F4b0a16Bb70",pair:"ETH / USD",decimals:8,min:100,max:2e4},explorerTx:"https://basescan.org/tx/",explorerAddr:"https://basescan.org/address/",explorerName:"basescan",gasUsd:.08,routeType:"atomic",escrow:{address:null,mode:"simulated"},tokens:[{symbol:"USDC",address:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",decimals:6,usd:1,cls:"ar-token-usdc"},{symbol:"USDT",address:"0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2",decimals:6,usd:1,cls:"ar-token-usdt"},{symbol:"DAI",address:"0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb",decimals:18,usd:1,cls:"ar-token-dai"},{symbol:"USDe",address:"0x5d3a1Ff2b6BAb83b63cd9AD0787074081a52ef34",decimals:18,usd:1,cls:"ar-token-usde"}]},{id:"bsc",name:"BNB Chain",vm:"evm",chainId:56,caip2:"eip155:56",native:{symbol:"BNB",decimals:18,usd:612.5},rpcUrl:"https://bsc-dataseed.binance.org",explorerTx:"https://bscscan.com/tx/",explorerAddr:"https://bscscan.com/address/",explorerName:"bscscan",gasUsd:.05,routeType:"atomic",escrow:{address:null,mode:"simulated"},tokens:[{symbol:"USDT",address:"0x55d398326f99059fF775485246999027B3197955",decimals:18,usd:1,cls:"ar-token-usdt"},{symbol:"USDC",address:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",decimals:18,usd:1,cls:"ar-token-usdc"}]},{id:"bitcoin",name:"Bitcoin",vm:"bitcoin",chainId:0,caip2:"bip122:000000000019d6689c085ae165831e93",native:{symbol:"BTC",decimals:8,usd:96e3},rpcUrl:"https://blockstream.info/api",explorerTx:"https://mempool.space/tx/",explorerAddr:"https://mempool.space/address/",explorerName:"mempool.space",gasUsd:1.2,routeType:"atomic",tokens:[],escrow:null,settlement:"native-atomic-swap"},{id:"tron",name:"Tron",vm:"tron",chainId:728126428,caip2:"tron:0x2b6653dc",native:{symbol:"TRX",decimals:6,usd:.28},rpcUrl:"https://api.trongrid.io",explorerTx:"https://tronscan.org/#/transaction/",explorerAddr:"https://tronscan.org/#/address/",explorerName:"tronscan",gasUsd:.35,routeType:"atomic",escrow:null,tokens:[{symbol:"USDT",address:"TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",decimals:6,usd:1,cls:"ar-token-usdt"}]},{id:"solana",name:"Solana",vm:"solana",chainId:101,caip2:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d",native:{symbol:"SOL",decimals:9,usd:198.4},rpcUrl:"https://api.mainnet-beta.solana.com",explorerTx:"https://solscan.io/tx/",explorerAddr:"https://solscan.io/account/",explorerName:"solscan",gasUsd:.002,routeType:"atomic",escrow:null,tokens:[{symbol:"USDC",address:"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",decimals:6,usd:1,cls:"ar-token-usdc"},{symbol:"USDT",address:"Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB",decimals:6,usd:1,cls:"ar-token-usdt"}]},{id:"monad",name:"Monad",vm:"evm",unsupported:!0,chainId:143,caip2:"eip155:143",native:{symbol:"MON",decimals:18,usd:.03},rpcUrl:"https://rpc.monad.xyz",explorerTx:"https://monadscan.com/tx/",explorerAddr:"https://monadscan.com/address/",explorerName:"monadscan",gasUsd:.01,routeType:"atomic",escrow:{address:null,mode:"simulated"},tokens:[{symbol:"USDC",address:"0x754704Bc059F8C67012fEd69BC8A327a5aafb603",decimals:6,usd:1,cls:"ar-token-usdc"},{symbol:"USDT",onChainSymbol:"USDT0",address:"0xe7cd86e13AC4309349F30B3435a9d337750fC82D",decimals:6,usd:1,cls:"ar-token-usdt"}]},{id:"hyperevm",name:"Hyperliquid EVM",vm:"evm",unsupported:!0,chainId:999,caip2:"eip155:999",native:{symbol:"HYPE",decimals:18,usd:38.5},rpcUrl:"https://rpc.hyperliquid.xyz/evm",explorerTx:"https://hyperevmscan.io/tx/",explorerAddr:"https://hyperevmscan.io/address/",explorerName:"hyperevmscan",gasUsd:.01,routeType:"atomic",escrow:{address:null,mode:"simulated"},tokens:[{symbol:"USDC",address:"0xb88339CB7199b77E23DB6E890353E22632Ba630f",decimals:6,usd:1,cls:"ar-token-usdc"},{symbol:"USDT",onChainSymbol:"USD\u20AE0",address:"0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb",decimals:6,usd:1,cls:"ar-token-usdt"}]}],Hn="arbitrum-sepolia",Jd={"local-anvil":["0x60af2ad4963c738aa6ac16d6cb0af1982508ba21"]};function wg(e){let t=typeof e=="string"?e:e&&e.id,n=Jd[t];return!Array.isArray(n)||n.length===0?null:n.map(r=>String(r).toLowerCase())}var ef=Object.freeze(Object.fromEntries(Object.values(mr).filter(e=>e.status==="live"&&e.knownFactoryCodes.length>0).map(e=>[e.network,[...e.knownFactoryCodes]])));function yg(e){let t=typeof e=="string"?e:e&&e.id,n=ef[t];return!Array.isArray(n)||n.length===0?null:n.map(r=>String(r).toLowerCase())}function bg(e){let t=typeof e=="string"?e:e&&e.id,n=br.find(o=>o.id===t)||lt(t),r=n&&n.escrow?n.escrow.implementationCodeHash:null;return typeof r!="string"||!/^0x[0-9a-fA-F]{64}$/.test(r)?null:[r.toLowerCase()]}function lt(e){return br.find(t=>t.id===e)||br.find(t=>t.id===Hn)||br[0]}function cc(e){return br.find(t=>t.chainId===Number(e))||null}function lc(e){let t=lt(e);return[tf(e),...t.tokens]}function tf(e){let t=lt(e);return{symbol:t.native.symbol,label:t.native.symbol,address:null,decimals:t.native.decimals,usd:t.native.usd,cls:"ar-token-eth",native:!0}}function gg(e){return(lt(e).tokens||[]).find(n=>n&&n.peg==="native")||null}function xg(e,t){let n=e,r=t;typeof e=="string"&&e.includes(":")&&([n,r]=e.split(":"));let o=lc(n);return o.find(i=>i.symbol===String(r).toUpperCase())||o[0]}var kg="0xc14C7841C7d6350859474dD6DF8dC9672047A6A0",Re={networkType:"stagenet",confirmTarget:10,blockTimeSim:12e4,blockTimeReal:12e4,node:Li.moneroNode,nodePollMs:3e4},on={base:null,xmrSource:"app",pollMs:5e3,maxProviders:5,timeoutMs:6e4},nf={app:"stagenet",mock:"stagenet",fakechain:"fakechain"};function Sg(){let e=typeof location<"u"?location.hostname:"";return/^(localhost|127\.0\.0\.1|\[::1\])$/.test(e)||/\.local$/.test(e)?ac.localOrigin:ac.origin}var ac={origin:Li.sweepOrigin,localOrigin:"http://localhost:5195"},St={quoteValid:12e3,quoteRefresh:5e3,fundingMined:6e3,makerLock:3e4,xmrConfirm:Re.blockTimeSim,readyWindow:60*6e4,makerClaim:45e3,sweep:3e4,t0Refund:20*6e4,t1Refund:40*6e4,watchtowerGrace:5*6e4,makerReclaim:10*6e4},Kt={speeds:[1,20,60,300],defaultSpeed:60,scenarios:["happy","maker_no_lock","user_no_ready","maker_stall"],defaultScenario:"happy",chainModes:["mock","live"],defaultChainMode:"live",xmrSources:["app","mock"],defaultXmrSource:"app",defaultChain:Hn},vg={happy:"happy path",maker_no_lock:"maker never locks XMR",user_no_ready:"user never confirms",maker_stall:"maker stalls after ready"};var we={};Be(we,{allowanceVerdict:()=>Ng,counterpartyVerdict:()=>Pg,deadlineVerdict:()=>dc,escrowPointsVerdict:()=>uc,escrowStateVerdict:()=>fc,gasReserveVerdict:()=>_g,liveOrderSlotsVerdict:()=>Bg,networkGateVerdict:()=>Tg,payBalanceVerdict:()=>Ag,quoteFreshnessVerdict:()=>Ig,rangeVerdict:()=>Eg,signingGateVerdict:()=>Og,signingGateWords:()=>Cg});var Ln=e=>{if(e==null||e==="")return null;try{let t=BigInt(e);return t>=0n?t:null}catch{return null}},ut=e=>String(Number(Number(e).toFixed(4))),Oe=e=>e==null||e===""?null:Number.isFinite(Number(e))?Number(e):null,ze=(e,t=18)=>{let n=Number(e)/10**Number(t);return Number.isFinite(n)?String(Number(n.toFixed(6))):String(e)};function Eg({size:e=null,unit:t=null,min:n=null,max:r=null,step:o=null,quoteUnit:i=null}={}){let s=String(t||i||"").toUpperCase(),a=String(i||"").toUpperCase();if(a&&s&&a!==s)return{ok:!1,checked:!0,blocks:!0,kind:"unit-mismatch",reason:`the size is measured in ${s} while the quote states its range in ${a} - the two cannot be compared`,size:e,min:n,max:r,step:o,unit:s,quoteUnit:a};let c=Oe(e);if(c===null||c<=0)return{ok:!1,checked:!1,blocks:!1,kind:"size-unstated",reason:"the size is not entered, so the provider's range cannot be checked",size:null,min:Oe(n),max:Oe(r),step:Oe(o),unit:s};let l=Oe(n),u=Oe(r),f=Oe(o);if(l===null&&u===null)return{ok:!0,checked:!1,blocks:!1,kind:"range-unstated",reason:"the provider did not state a volume range (min/max), so the size could not be checked against it",size:c,min:null,max:null,step:f,unit:s};let h={size:c,min:l,max:u,step:f,unit:s,quoteUnit:a||s};if(l!==null&&c<l)return{ok:!1,checked:!0,blocks:!0,kind:"below-min",...h,reason:`the order size ${ut(c)} ${s} is below the provider minimum ${ut(l)} ${s} - short by ${ut(l-c)} ${s}: the provider does not take this size`};if(u!==null&&c>u)return{ok:!1,checked:!0,blocks:!0,kind:"above-max",...h,reason:`the order size ${ut(c)} ${s} is above the provider maximum ${ut(u)} ${s} - over by ${ut(c-u)} ${s}: the provider does not take this size`};if(f!==null&&f>0){let m=l!==null?l:0,w=(c-m)/f;if(Math.abs(w-Math.round(w))>1e-6)return{ok:!1,checked:!0,blocks:!0,kind:"off-step",...h,reason:`the order size ${ut(c)} ${s} does not sit on the ${ut(f)} ${s} step from ${ut(m)} ${s}`}}return{ok:!0,checked:!0,blocks:!1,kind:"in-range",...h,reason:`the order size ${ut(c)} ${s} is inside the provider range ${l===null?"?":ut(l)}..${u===null?"?":ut(u)} ${s}`}}function Ag({payBalanceWei:e=null,payAmountWei:t=null,symbol:n=null,decimals:r=18}={}){let o=Ln(e),i=Ln(t);return i===null||i<=0n?{ok:!1,checked:!1,blocks:!1,kind:"amount-unstated",reason:"the amount to fund is not known, so the wallet balance cannot be checked against it"}:o===null?{ok:!1,checked:!1,blocks:!0,kind:"balance-unchecked",reason:"the wallet balance was not read, so it is unknown whether the wallet covers the order - signing is blocked"}:o<i?{ok:!1,checked:!0,blocks:!0,kind:"balance-short",haveWei:o.toString(),needWei:i.toString(),shortfallWei:(i-o).toString(),reason:`the wallet holds ${ze(o,r)} ${n} but the order locks ${ze(i,r)} ${n} - short by ${ze(i-o,r)} ${n}`}:{ok:!0,checked:!0,blocks:!1,kind:"balance-enough",haveWei:o.toString(),needWei:i.toString(),reason:`the wallet holds ${ze(o,r)} ${n} for the order's ${ze(i,r)} ${n}`}}function _g({nativeBalanceWei:e=null,requiredNativeWei:t=null,gasReserveWei:n=null,symbol:r=null,decimals:o=18}={}){let i=Ln(t),s=Ln(n),a=Ln(e);if(s===null||s<=0n)return{ok:!0,checked:!1,blocks:!1,kind:"reserve-unstated",reason:"the gas reserve was not measured, so the gas part of the funding could not be checked (the wallet will name any shortfall)"};if(i===null)return{ok:!1,checked:!1,blocks:!1,kind:"amount-unstated",reserveWei:s.toString(),reason:"the amount to fund is not known, so the native balance cannot be checked against amount + gas"};if(a===null)return{ok:!1,checked:!1,blocks:!0,kind:"native-unchecked",needWei:i.toString(),reserveWei:s.toString(),reason:"the native balance was not read, so it is unknown whether the wallet covers amount + gas - signing is blocked"};let c=i+s;return a<c?{ok:!1,checked:!0,blocks:!0,kind:"gas-short",haveWei:a.toString(),needWei:i.toString(),reserveWei:s.toString(),requiredTotalWei:c.toString(),shortfallWei:(c-a).toString(),reason:`funding needs ${ze(i,o)} ${r} plus ${ze(s,o)} ${r} of gas, but the wallet holds ${ze(a,o)} ${r} - short by ${ze(c-a,o)} ${r}`}:{ok:!0,checked:!0,blocks:!1,kind:"gas-enough",haveWei:a.toString(),needWei:i.toString(),reserveWei:s.toString(),requiredTotalWei:c.toString(),reason:`the wallet holds ${ze(a,o)} ${r}: ${ze(i,o)} for the order and ${ze(s,o)} for gas`}}function Ig({at:e=null,ttlMs:t=null,expiresAt:n=null,nowMs:r=null}={}){let o=Oe(r)===null?Date.now():Number(r),i=Oe(n);if(i!==null&&i<=o)return{ok:!1,checked:!0,blocks:!0,kind:"expired",expiresAt:i,nowMs:o,reason:`the order quote expired ${Math.round((o-i)/1e3)}s ago`};let s=Oe(e);if(s===null)return{ok:!1,checked:!1,blocks:!1,kind:"untimed",reason:"the quote carries no timestamp, so its age could not be checked"};let a=Oe(t),c=Math.max(0,o-s);return a===null||a<=0?{ok:!0,checked:!1,blocks:!1,kind:"no-ttl",at:s,ageMs:c,reason:`the provider did not state how long the quote lives, so only its age is known: said ${Math.round(c/1e3)}s ago`}:c>a?{ok:!1,checked:!0,blocks:!0,kind:"stale",at:s,ttlMs:a,ageMs:c,overMs:c-a,reason:`the quote is ${Math.round(c/1e3)}s old while it was valid for ${Math.round(a/1e3)}s - it expired ${Math.round((c-a)/1e3)}s ago`}:{ok:!0,checked:!0,blocks:!1,kind:"fresh",at:s,ttlMs:a,ageMs:c,reason:`the quote is ${Math.round(c/1e3)}s old and valid for ${Math.round(a/1e3)}s`}}function dc({nowSec:e=null,readyBy:t=null,t1:n=null,minReadyLeadSec:r=null,minClaimWindowSec:o=null,maxDeadlineSec:i=null}={}){let s=Oe(e)===null?Math.floor(Date.now()/1e3):Number(e),a=Oe(t),c=Oe(n);if(a===null||c===null)return{ok:!1,checked:!1,blocks:!0,kind:"deadlines-unstated",reason:"the order's deadlines are not stated, so neither the ready window nor the claim window can be checked - signing is blocked"};if(a<=s)return{ok:!1,checked:!0,blocks:!0,kind:"ready-by-in-past",readyBy:a,nowSec:s,reason:`the order would be created already past its ready-by deadline (${a} is ${Math.round(s-a)}s ago): nothing could be claimed in it`};if(c<=a)return{ok:!1,checked:!0,blocks:!0,kind:"t1-not-after-ready-by",readyBy:a,t1:c,reason:`t1 (${c}) must be later than readyBy (${a}): an overlapping window lets claim and refund both be valid at once`};let l=Oe(r),u=Oe(o);if(l!==null&&a-s<l)return{ok:!1,checked:!0,blocks:!0,kind:"ready-window-too-short",readyBy:a,nowSec:s,minReadyLeadSec:l,reason:`the ready-by deadline is only ${Math.round(a-s)}s away while the mark-ready window needs at least ${l}s - XMR confirmations alone take minutes`};if(u!==null&&c-a<u)return{ok:!1,checked:!0,blocks:!0,kind:"claim-window-too-short",readyBy:a,t1:c,minClaimWindowSec:u,reason:`the claim window is ${Math.round(c-a)}s while at least ${u}s is needed to take the funds before the refund opens`};let f=Oe(i);return f!==null&&c-s>f?{ok:!1,checked:!0,blocks:!0,kind:"deadline-too-far",readyBy:a,t1:c,nowSec:s,maxDeadlineSec:f,reason:`the order's deadline is ${Math.round(c-s)}s (${Math.round((c-s)/3600)}h) away while at most ${f}s (${Math.round(f/3600)}h) is allowed: a deposit locked that long could not be refunded until t1`}:{ok:!0,checked:!0,blocks:!1,kind:"deadlines-ok",readyBy:a,t1:c,nowSec:s,reason:`ready in ${Math.round(a-s)}s, claim window ${Math.round(c-a)}s`}}function fc({status:e=null,error:t=null,address:n=null}={}){let r=n?" the escrow at "+n:" the escrow";return t?{ok:!1,checked:!1,blocks:!0,kind:"state-unchecked",error:String(t),reason:`the state of${r} could not be read (${String(t)}), so it is unknown whether this order already exists - signing is blocked`}:e?e.isClaimed?{ok:!1,checked:!0,blocks:!0,kind:"already-claimed",status:e,address:n||null,reason:`${r} is already claimed: the order is settled, a new signature would create a second order`}:e.isRefunded?{ok:!1,checked:!0,blocks:!0,kind:"already-refunded",status:e,address:n||null,reason:`${r} was already refunded: the order is closed, a new signature would create a second order`}:e.isFunded?{ok:!1,checked:!0,blocks:!0,kind:"already-funded",status:e,address:n||null,reason:`${r} is already funded: the contract refuses a second funding (AlreadyFunded) - top up that order instead of signing a new one`}:{ok:!0,checked:!0,blocks:!1,kind:"new",status:e,address:n||null,reason:`${r} exists but holds nothing: this is a new order`}:{ok:!0,checked:!0,blocks:!1,kind:"new",address:n||null,reason:n?`no escrow exists at ${n} yet: this is a new order`:"no escrow exists yet: this is a new order"}}function Ng({tokenIsNative:e=!1,allowanceWei:t=null,amountWei:n=null,consent:r=!1,symbol:o=null,decimals:i=18}={}){if(e)return{ok:!0,checked:!0,blocks:!1,kind:"not-needed",reason:"the payment is the network's own coin: no ERC-20 approval and no pool are involved"};let s=Ln(n),a=Ln(t);return r!==!0?{ok:!1,checked:!1,blocks:!0,kind:"consent-missing",needWei:s===null?null:s.toString(),reason:`swapping ${o||"the token"} needs an ERC-20 approval for you to sign, and no consent was given for it`}:a===null?{ok:!1,checked:!1,blocks:!0,kind:"allowance-unchecked",reason:`the existing allowance for ${o||"the token"} was not read, so it is unknown whether the approval is needed - signing is blocked`}:s===null||s<=0n?{ok:!1,checked:!1,blocks:!1,kind:"amount-unstated",reason:"the amount to swap is not known, so the allowance cannot be checked against it"}:a<s?{ok:!1,checked:!0,blocks:!0,kind:"allowance-short",allowanceWei:a.toString(),needWei:s.toString(),reason:`the approved amount is ${ze(a,i)} ${o||""} but the swap spends ${ze(s,i)} ${o||""}: the approval must be raised first`}:{ok:!0,checked:!0,blocks:!1,kind:"allowed",allowanceWei:a.toString(),needWei:s.toString(),reason:`the approved amount ${ze(a,i)} ${o||""} covers the swap of ${ze(s,i)} ${o||""}`}}function Tg({walletChainId:e=null,selectedChainId:t=null,settlementChainId:n=null,selectedChainName:r=null}={}){let o=Oe(e),i=Oe(t),s=Oe(n);return o===null?{ok:!1,checked:!1,blocks:!0,kind:"wallet-unknown",reason:"the wallet's network is unknown, so balances and the funding transaction have no network - signing is blocked"}:i===null?{ok:!1,checked:!1,blocks:!0,kind:"network-unknown",reason:"the page's settlement network is unknown, so it cannot be compared with the wallet's - signing is blocked"}:o!==i?{ok:!1,checked:!0,blocks:!0,kind:"wallet-network",walletChainId:o,selectedChainId:i,reason:`the wallet is on chain ${o} while this page settles on chain ${i}${r?" ("+r+")":""}: balances and the funding transaction would come from another network`}:s!==null&&s!==i?{ok:!1,checked:!0,blocks:!0,kind:"settlement-network",walletChainId:o,selectedChainId:i,settlementChainId:s,reason:`the escrow contract sits on chain ${s} while the page is set to chain ${i}: the money would go to a network where this order's escrow does not exist`}:{ok:!0,checked:!0,blocks:!1,kind:"network-match",chainId:i,reason:`the wallet and the page agree on chain ${i}${r?" ("+r+")":""}`}}function Pg({standIn:e=!1,liveChain:t=!1,network:n=null,chainId:r=null}={}){let o=(s,a,c)=>({ok:s,checked:!0,blocks:!s,kind:a,words:c,reason:c}),i=(n||"this network")+(r==null?"":" (chainId "+r+")");return e?t?o(!1,"standin-on-production",`${i} is a live network and the counterparty is a local stand-in: the proof would be checked against itself, so the signature stays locked until a real provider answers`):o(!0,"standin-on-testnet",`demo mode: the counterparty is a local stand-in and ${i} is a testnet (not a live network), the proof proves nothing by itself`):o(!0,"real-provider","counterparty is a real provider: the proof is checked against it")}var $e=e=>e==null?"":String(e).replace(/^0x/i,"").toLowerCase();function uc({role:e=null,what:t=null,point:n=null,onchainPoint:r=null,commit:o=null,onchainCommit:i=null,readError:s=null}={}){let a=t||(e?"the "+e+" point":"the point");if(s)return{ok:!1,checked:!1,blocks:!0,kind:"points-unchecked",reason:`${a} of the live escrow could not be read (${String(s)}): whether the order holds the points that DLEQ proved is unknown - signing is blocked`};let c=!1;if($e(n)){if(c=!0,!$e(r))return{ok:!1,checked:!1,blocks:!0,kind:"points-unchecked",reason:`the live escrow did not return ${a}: the order may hold different points than the proof proved - signing is blocked`};if($e(n)!==$e(r))return{ok:!1,checked:!0,blocks:!0,kind:"point-mismatch",reason:`${a} in the escrow (0x${$e(r)}) is NOT the point DLEQ proved (0x${$e(n)}): the Monero address would be assembled from other halves and the XMR could not be swept after claim`}}if($e(o)){if(c=!0,!$e(i))return{ok:!1,checked:!1,blocks:!0,kind:"points-unchecked",reason:`the live escrow did not return ${a}: the order may hold a different half than we do - signing is blocked`};if($e(o)!==$e(i))return{ok:!1,checked:!0,blocks:!0,kind:"commit-mismatch",reason:`${a} in the escrow (0x${$e(i)}) is NOT the one we hold (0x${$e(o)}): the reveal would not match the order`}}return c?{ok:!0,checked:!0,blocks:!1,kind:"points-match",reason:`${a} in the escrow matches what we hold${$e(n)&&$e(o)?" (point and commitment)":""}`}:{ok:!1,checked:!1,blocks:!0,kind:"points-unchecked",reason:`nothing to compare for ${a}: neither a point nor a commitment was recorded - signing is blocked`}}function Bg({slots:e=null,expect:t=null,readError:n=null}={}){if(n||!e)return{ok:!1,checked:!1,blocks:!0,kind:"slots-unchecked",reason:`the live escrow slots could not be read (${String(n||"no answer")}): whether the order holds the points and halves we assembled is unknown - signing is blocked`};let r=[["edPointLocker","the locker spend point","point"],["edPointClaimer","the claimer spend point","point"],["edViewPointLocker","the locker view point","point"],["commitHalfLocker","the commitment of the locker half","commit"],["commitHalfClaimer","the commitment of the claimer half","commit"]],o=[],i=[];for(let[s,a,c]of r){if(!$e(t&&t[s]))continue;if(!$e(e[s])){i.push(a);continue}let l=uc(c==="point"?{what:a,point:t[s],onchainPoint:e[s]}:{what:a,commit:t[s],onchainCommit:e[s]});if(l.blocks)return{...l,fields:o.concat([s])};o.push(s)}return o.length?i.length?{ok:!1,checked:!0,blocks:!0,kind:"slots-unchecked",reason:`the live escrow did not return ${i.join(", ")}: the order may differ from what was proved - signing is blocked`}:{ok:!0,checked:!0,blocks:!1,kind:"slots-match",fields:o,reason:`the live escrow holds exactly what we assembled: ${o.join(", ")}`}:{ok:!1,checked:!1,blocks:!0,kind:"slots-unchecked",reason:"nothing to compare: the app recorded neither a point nor a commitment for this order - signing is blocked"}}function Og(e=[]){let t=(Array.isArray(e)?e:[]).filter(o=>o&&typeof o=="object"),n=t.filter(o=>o.blocks===!0),r=t.filter(o=>o.blocks!==!0&&o.checked===!1);return{ok:n.length===0,blocked:n.length>0,kind:n.length?n[0].kind:t.length?t[t.length-1].kind:"nothing-to-check",reason:n.length?n.map(o=>o.reason).filter(Boolean).join("; "):null,blockedBy:n.map(o=>o.kind),unchecked:r.map(o=>o.kind),checks:t}}function Cg(e){if(!e||!e.blocked)return null;let t=(e.checks||[]).find(r=>r.blocks===!0)||null;return"Signing is blocked: "+(t&&t.reason?t.reason:"the order cannot be checked")+" ("+e.kind+")"}var vs={};Be(vs,{assertNoSecretsInShare:()=>Wp,restoreFromFile:()=>yk,restoreFromHalves:()=>jp,restoreWalletFromPayload:()=>Kp,watchOnlyShareFromWallet:()=>bk});function Di(e=16){let t=new Uint8Array(e);return crypto.getRandomValues(t),jt(t)}function jt(e){let t=e instanceof Uint8Array?e:Uint8Array.from(e||[]);return Array.from(t,n=>n.toString(16).padStart(2,"0")).join("")}function pc(){return Di(8)}Ee();Vn();Ee();var $n=["abbey","abducts","ability","ablaze","abnormal","abort","abrasive","absorb","abyss","academy","aces","aching","acidic","acoustic","acquire","across","actress","acumen","adapt","addicted","adept","adhesive","adjust","adopt","adrenalin","adult","adventure","aerial","afar","affair","afield","afloat","afoot","afraid","after","against","agenda","aggravate","agile","aglow","agnostic","agony","agreed","ahead","aided","ailments","aimless","airport","aisle","ajar","akin","alarms","album","alchemy","alerts","algebra","alkaline","alley","almost","aloof","alpine","already","also","altitude","alumni","always","amaze","ambush","amended","amidst","ammo","amnesty","among","amply","amused","anchor","android","anecdote","angled","ankle","annoyed","answers","antics","anvil","anxiety","anybody","apart","apex","aphid","aplomb","apology","apply","apricot","aptitude","aquarium","arbitrary","archer","ardent","arena","argue","arises","army","around","arrow","arsenic","artistic","ascend","ashtray","aside","asked","asleep","aspire","assorted","asylum","athlete","atlas","atom","atrium","attire","auburn","auctions","audio","august","aunt","austere","autumn","avatar","avidly","avoid","awakened","awesome","awful","awkward","awning","awoken","axes","axis","axle","aztec","azure","baby","bacon","badge","baffles","bagpipe","bailed","bakery","balding","bamboo","banjo","baptism","basin","batch","bawled","bays","because","beer","befit","begun","behind","being","below","bemused","benches","berries","bested","betting","bevel","beware","beyond","bias","bicycle","bids","bifocals","biggest","bikini","bimonthly","binocular","biology","biplane","birth","biscuit","bite","biweekly","blender","blip","bluntly","boat","bobsled","bodies","bogeys","boil","boldly","bomb","border","boss","both","bounced","bovine","bowling","boxes","boyfriend","broken","brunt","bubble","buckets","budget","buffet","bugs","building","bulb","bumper","bunch","business","butter","buying","buzzer","bygones","byline","bypass","cabin","cactus","cadets","cafe","cage","cajun","cake","calamity","camp","candy","casket","catch","cause","cavernous","cease","cedar","ceiling","cell","cement","cent","certain","chlorine","chrome","cider","cigar","cinema","circle","cistern","citadel","civilian","claim","click","clue","coal","cobra","cocoa","code","coexist","coffee","cogs","cohesive","coils","colony","comb","cool","copy","corrode","costume","cottage","cousin","cowl","criminal","cube","cucumber","cuddled","cuffs","cuisine","cunning","cupcake","custom","cycling","cylinder","cynical","dabbing","dads","daft","dagger","daily","damp","dangerous","dapper","darted","dash","dating","dauntless","dawn","daytime","dazed","debut","decay","dedicated","deepest","deftly","degrees","dehydrate","deity","dejected","delayed","demonstrate","dented","deodorant","depth","desk","devoid","dewdrop","dexterity","dialect","dice","diet","different","digit","dilute","dime","dinner","diode","diplomat","directed","distance","ditch","divers","dizzy","doctor","dodge","does","dogs","doing","dolphin","domestic","donuts","doorway","dormant","dosage","dotted","double","dove","down","dozen","dreams","drinks","drowning","drunk","drying","dual","dubbed","duckling","dude","duets","duke","dullness","dummy","dunes","duplex","duration","dusted","duties","dwarf","dwelt","dwindling","dying","dynamite","dyslexic","each","eagle","earth","easy","eating","eavesdrop","eccentric","echo","eclipse","economics","ecstatic","eden","edgy","edited","educated","eels","efficient","eggs","egotistic","eight","either","eject","elapse","elbow","eldest","eleven","elite","elope","else","eluded","emails","ember","emerge","emit","emotion","empty","emulate","energy","enforce","enhanced","enigma","enjoy","enlist","enmity","enough","enraged","ensign","entrance","envy","epoxy","equip","erase","erected","erosion","error","eskimos","espionage","essential","estate","etched","eternal","ethics","etiquette","evaluate","evenings","evicted","evolved","examine","excess","exhale","exit","exotic","exquisite","extra","exult","fabrics","factual","fading","fainted","faked","fall","family","fancy","farming","fatal","faulty","fawns","faxed","fazed","feast","february","federal","feel","feline","females","fences","ferry","festival","fetches","fever","fewest","fiat","fibula","fictional","fidget","fierce","fifteen","fight","films","firm","fishing","fitting","five","fixate","fizzle","fleet","flippant","flying","foamy","focus","foes","foggy","foiled","folding","fonts","foolish","fossil","fountain","fowls","foxes","foyer","framed","friendly","frown","fruit","frying","fudge","fuel","fugitive","fully","fuming","fungal","furnished","fuselage","future","fuzzy","gables","gadget","gags","gained","galaxy","gambit","gang","gasp","gather","gauze","gave","gawk","gaze","gearbox","gecko","geek","gels","gemstone","general","geometry","germs","gesture","getting","geyser","ghetto","ghost","giant","giddy","gifts","gigantic","gills","gimmick","ginger","girth","giving","glass","gleeful","glide","gnaw","gnome","goat","goblet","godfather","goes","goggles","going","goldfish","gone","goodbye","gopher","gorilla","gossip","gotten","gourmet","governing","gown","greater","grunt","guarded","guest","guide","gulp","gumball","guru","gusts","gutter","guys","gymnast","gypsy","gyrate","habitat","hacksaw","haggled","hairy","hamburger","happens","hashing","hatchet","haunted","having","hawk","haystack","hazard","hectare","hedgehog","heels","hefty","height","hemlock","hence","heron","hesitate","hexagon","hickory","hiding","highway","hijack","hiker","hills","himself","hinder","hippo","hire","history","hitched","hive","hoax","hobby","hockey","hoisting","hold","honked","hookup","hope","hornet","hospital","hotel","hounded","hover","howls","hubcaps","huddle","huge","hull","humid","hunter","hurried","husband","huts","hybrid","hydrogen","hyper","iceberg","icing","icon","identity","idiom","idled","idols","igloo","ignore","iguana","illness","imagine","imbalance","imitate","impel","inactive","inbound","incur","industrial","inexact","inflamed","ingested","initiate","injury","inkling","inline","inmate","innocent","inorganic","input","inquest","inroads","insult","intended","inundate","invoke","inwardly","ionic","irate","iris","irony","irritate","island","isolated","issued","italics","itches","items","itinerary","itself","ivory","jabbed","jackets","jaded","jagged","jailed","jamming","january","jargon","jaunt","javelin","jaws","jazz","jeans","jeers","jellyfish","jeopardy","jerseys","jester","jetting","jewels","jigsaw","jingle","jittery","jive","jobs","jockey","jogger","joining","joking","jolted","jostle","journal","joyous","jubilee","judge","juggled","juicy","jukebox","july","jump","junk","jury","justice","juvenile","kangaroo","karate","keep","kennel","kept","kernels","kettle","keyboard","kickoff","kidneys","king","kiosk","kisses","kitchens","kiwi","knapsack","knee","knife","knowledge","knuckle","koala","laboratory","ladder","lagoon","lair","lakes","lamb","language","laptop","large","last","later","launching","lava","lawsuit","layout","lazy","lectures","ledge","leech","left","legion","leisure","lemon","lending","leopard","lesson","lettuce","lexicon","liar","library","licks","lids","lied","lifestyle","light","likewise","lilac","limits","linen","lion","lipstick","liquid","listen","lively","loaded","lobster","locker","lodge","lofty","logic","loincloth","long","looking","lopped","lordship","losing","lottery","loudly","love","lower","loyal","lucky","luggage","lukewarm","lullaby","lumber","lunar","lurk","lush","luxury","lymph","lynx","lyrics","macro","madness","magically","mailed","major","makeup","malady","mammal","maps","masterful","match","maul","maverick","maximum","mayor","maze","meant","mechanic","medicate","meeting","megabyte","melting","memoir","menu","merger","mesh","metro","mews","mice","midst","mighty","mime","mirror","misery","mittens","mixture","moat","mobile","mocked","mohawk","moisture","molten","moment","money","moon","mops","morsel","mostly","motherly","mouth","movement","mowing","much","muddy","muffin","mugged","mullet","mumble","mundane","muppet","mural","musical","muzzle","myriad","mystery","myth","nabbing","nagged","nail","names","nanny","napkin","narrate","nasty","natural","nautical","navy","nearby","necklace","needed","negative","neither","neon","nephew","nerves","nestle","network","neutral","never","newt","nexus","nibs","niche","niece","nifty","nightly","nimbly","nineteen","nirvana","nitrogen","nobody","nocturnal","nodes","noises","nomad","noodles","northern","nostril","noted","nouns","novelty","nowhere","nozzle","nuance","nucleus","nudged","nugget","nuisance","null","number","nuns","nurse","nutshell","nylon","oaks","oars","oasis","oatmeal","obedient","object","obliged","obnoxious","observant","obtains","obvious","occur","ocean","october","odds","odometer","offend","often","oilfield","ointment","okay","older","olive","olympics","omega","omission","omnibus","onboard","oncoming","oneself","ongoing","onion","online","onslaught","onto","onward","oozed","opacity","opened","opposite","optical","opus","orange","orbit","orchid","orders","organs","origin","ornament","orphans","oscar","ostrich","otherwise","otter","ouch","ought","ounce","ourselves","oust","outbreak","oval","oven","owed","owls","owner","oxidant","oxygen","oyster","ozone","pact","paddles","pager","pairing","palace","pamphlet","pancakes","paper","paradise","pastry","patio","pause","pavements","pawnshop","payment","peaches","pebbles","peculiar","pedantic","peeled","pegs","pelican","pencil","people","pepper","perfect","pests","petals","phase","pheasants","phone","phrases","physics","piano","picked","pierce","pigment","piloted","pimple","pinched","pioneer","pipeline","pirate","pistons","pitched","pivot","pixels","pizza","playful","pledge","pliers","plotting","plus","plywood","poaching","pockets","podcast","poetry","point","poker","polar","ponies","pool","popular","portents","possible","potato","pouch","poverty","powder","pram","present","pride","problems","pruned","prying","psychic","public","puck","puddle","puffin","pulp","pumpkins","punch","puppy","purged","push","putty","puzzled","pylons","pyramid","python","queen","quick","quote","rabbits","racetrack","radar","rafts","rage","railway","raking","rally","ramped","randomly","rapid","rarest","rash","rated","ravine","rays","razor","react","rebel","recipe","reduce","reef","refer","regular","reheat","reinvest","rejoices","rekindle","relic","remedy","renting","reorder","repent","request","reruns","rest","return","reunion","revamp","rewind","rhino","rhythm","ribbon","richly","ridges","rift","rigid","rims","ringing","riots","ripped","rising","ritual","river","roared","robot","rockets","rodent","rogue","roles","romance","roomy","roped","roster","rotate","rounded","rover","rowboat","royal","ruby","rudely","ruffled","rugged","ruined","ruling","rumble","runway","rural","rustled","ruthless","sabotage","sack","sadness","safety","saga","sailor","sake","salads","sample","sanity","sapling","sarcasm","sash","satin","saucepan","saved","sawmill","saxophone","sayings","scamper","scenic","school","science","scoop","scrub","scuba","seasons","second","sedan","seeded","segments","seismic","selfish","semifinal","sensible","september","sequence","serving","session","setup","seventh","sewage","shackles","shelter","shipped","shocking","shrugged","shuffled","shyness","siblings","sickness","sidekick","sieve","sifting","sighting","silk","simplest","sincerely","sipped","siren","situated","sixteen","sizes","skater","skew","skirting","skulls","skydive","slackens","sleepless","slid","slower","slug","smash","smelting","smidgen","smog","smuggled","snake","sneeze","sniff","snout","snug","soapy","sober","soccer","soda","software","soggy","soil","solved","somewhere","sonic","soothe","soprano","sorry","southern","sovereign","sowed","soya","space","speedy","sphere","spiders","splendid","spout","sprig","spud","spying","square","stacking","stellar","stick","stockpile","strained","stunning","stylishly","subtly","succeed","suddenly","suede","suffice","sugar","suitcase","sulking","summon","sunken","superior","surfer","sushi","suture","swagger","swept","swiftly","sword","swung","syllabus","symptoms","syndrome","syringe","system","taboo","tacit","tadpoles","tagged","tail","taken","talent","tamper","tanks","tapestry","tarnished","tasked","tattoo","taunts","tavern","tawny","taxi","teardrop","technical","tedious","teeming","tell","template","tender","tepid","tequila","terminal","testing","tether","textbook","thaw","theatrics","thirsty","thorn","threaten","thumbs","thwart","ticket","tidy","tiers","tiger","tilt","timber","tinted","tipsy","tirade","tissue","titans","toaster","tobacco","today","toenail","toffee","together","toilet","token","tolerant","tomorrow","tonic","toolbox","topic","torch","tossed","total","touchy","towel","toxic","toyed","trash","trendy","tribal","trolling","truth","trying","tsunami","tubes","tucks","tudor","tuesday","tufts","tugs","tuition","tulips","tumbling","tunnel","turnip","tusks","tutor","tuxedo","twang","tweezers","twice","twofold","tycoon","typist","tyrant","ugly","ulcers","ultimate","umbrella","umpire","unafraid","unbending","uncle","under","uneven","unfit","ungainly","unhappy","union","unjustly","unknown","unlikely","unmask","unnoticed","unopened","unplugs","unquoted","unrest","unsafe","until","unusual","unveil","unwind","unzip","upbeat","upcoming","update","upgrade","uphill","upkeep","upload","upon","upper","upright","upstairs","uptight","upwards","urban","urchins","urgent","usage","useful","usher","using","usual","utensils","utility","utmost","utopia","uttered","vacation","vague","vain","value","vampire","vane","vapidly","vary","vastness","vats","vaults","vector","veered","vegan","vehicle","vein","velvet","venomous","verification","vessel","veteran","vexed","vials","vibrate","victim","video","viewpoint","vigilant","viking","village","vinegar","violin","vipers","virtual","visited","vitals","vivid","vixen","vocal","vogue","voice","volcano","vortex","voted","voucher","vowels","voyage","vulture","wade","waffle","wagtail","waist","waking","wallets","wanted","warped","washing","water","waveform","waxing","wayside","weavers","website","wedge","weekday","weird","welders","went","wept","were","western","wetsuit","whale","when","whipped","whole","wickets","width","wield","wife","wiggle","wildly","winter","wipeout","wiring","wise","withdrawn","wives","wizard","wobbly","woes","woken","wolf","womanly","wonders","woozy","worry","wounded","woven","wrap","wrist","wrong","yacht","yahoo","yanks","yard","yawning","yearbook","yellow","yesterday","yeti","yields","yodel","yoga","younger","yoyo","zapped","zeal","zebra","zero","zesty","zigzags","zinger","zippers","zodiac","zombie","zones","zoom"];var ys=24,Sp=25,el=32,Xx=3,bs=new Map($n.map((e,t)=>[e,t])),Yx=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t+=1){let n=t;for(let r=0;r<8;r+=1)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n>>>0}return e})();function Gx(e){let t=4294967295;for(let n of e)t=Yx[(t^n)&255]^t>>>8;return(t^4294967295)>>>0}function qx(e,t,n){let r=$n.length,o=bs.get(e),i=bs.get(t),s=bs.get(n);if(o===void 0||i===void 0||s===void 0)throw new Error("invalid mnemonic word");return o+r*(((i-o)%r+r)%r)+r*r*(((s-i)%r+r)%r)}function Qx(e){let t=$n.length,n=e%t,r=(Math.floor(e/t)+n)%t,o=(Math.floor(Math.floor(e/t)/t)+r)%t;return[$n[n],$n[r],$n[o]]}function vp(e){let t=e.map(n=>n.slice(0,Xx)).join("");return e[Gx(new TextEncoder().encode(t))%e.length]}function Zx(e){return(e.length===ys||e.length===Sp)&&e.every(t=>bs.has(t))}function Jx(e){let t=e instanceof Uint8Array?e:Uint8Array.from(e);if(t.length!==el)throw new Error("invalid entropy length");let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=[];for(let o=0;o<t.length;o+=4)r.push(...Qx(n.getUint32(o,!0)));return r.join(" ")}function ek(e){let t=Jx(e).split(" ");return t.push(vp(t)),t.join(" ")}function Ep(){return ek(Wn(el))}function Ap(e){let t=String(e||"").trim().split(/\s+/).filter(Boolean);if(!Zx(t))throw new Error("invalid mnemonic phrase (length or words)");if(t.length===Sp){let i=t.slice(0,ys);if(t[ys]!==vp(i))throw new Error("invalid mnemonic checksum")}let n=new Uint8Array(el),r=new DataView(n.buffer),o=Math.min(t.length,ys);for(let i=0;i<o/3;i+=1)r.setUint32(i*4,qx(t[i*3],t[i*3+1],t[i*3+2]),!0);return n}function _p(e){try{return Ap(e),!0}catch{return!1}}function Ip(e){return Ap(e)}Ee();var Pp=_e.Point.Fn.ORDER,Br=32;function jo(e){let t=0n;for(let n=e.length-1;n>=0;n-=1)t=t<<8n|BigInt(e[n]);return t}function nk(e,t=Br){let n=new Uint8Array(t),r=e;for(let o=0;o<t;o+=1)n[o]=Number(r&0xffn),r>>=8n;return n}function rl(e){if(e.length>64)throw new Error("scalar is longer than 64 bytes");let t=new Uint8Array(64);return t.set(e),nk(jo(t)%Pp)}function rk(e){return e instanceof Uint8Array?e:e&&e.buffer instanceof ArrayBuffer?new Uint8Array(e):Uint8Array.from(e||[])}function ok(e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}function Np(e){return _e.Point.fromHex(ok(e))}function tl(e){return _e.Point.BASE.multiply(jo(e)).toBytes()}function Tp(e){if(!Number.isSafeInteger(e)||e<0||e>=2**32)throw new Error("invalid subaddress index");let t=new Uint8Array(4);return t[0]=e&255,t[1]=e>>>8&255,t[2]=e>>>16&255,t[3]=e>>>24&255,t}var Ko=new TextEncoder().encode("SubAddr\0");function ik({privateView:e,publicSpend:t},n,r){if(n===0&&r===0)return{publicSpendKey:t,publicViewKey:tl(e)};let o=new Uint8Array(Ko.length+Br+8);o.set(Ko,0),o.set(e,Ko.length),o.set(Tp(r),Ko.length+Br),o.set(Tp(n),Ko.length+Br+4);let i=rl(Q(o)),s=Np(t).add(_e.Point.BASE.multiply(jo(i))).toBytes(),a=Np(s).multiply(jo(e)).toBytes();return{publicSpendKey:s,publicViewKey:a}}var nl=class{#n;#e;#t;#r;constructor(t){if(!(t instanceof Uint8Array)||t.length!==Br)throw new Error("invalid private spend key");if(jo(t)>=Pp)throw new Error("invalid private spend key");this.#n=t,this.#e=rl(Q(t)),this.#t=tl(t),this.#r=tl(this.#e)}get privateSpendKey(){return this.#n}get privateViewKey(){return this.#e}get publicSpendKey(){return this.#t}get publicViewKey(){return this.#r}subaddress(t=0,n=0){return ik({privateView:this.#e,publicSpend:this.#t},t,n)}};function Bp(e){let t=rk(e);return new nl(rl(t.length===Br?t:Q(t)))}async function Op(){}async function ak({mnemonic:e,network:t=Re.networkType}={}){await Op();let n;if(e){if(!_p(e))throw new Error("the mnemonic failed its checksum check (file or form corrupted?)");n=String(e).trim()}else n=Ep();let r=Ip(n),o=Bp(r),i=t||"mainnet",s={keccak256:Q},a=jt(o.publicSpendKey),c=jt(o.publicViewKey),l=o.subaddress(1,0),u=hn({network:i,kind:"primary",spendPub:a,viewPub:c},s),f=hn({network:i,kind:"subaddress",spendPub:jt(l.publicSpendKey),viewPub:jt(l.publicViewKey)},s),h=hn({network:"mainnet",kind:"primary",spendPub:a,viewPub:c},s);return{source:"ninsei-monero-keys",library:"Ninsei Monero keys (@noble/curves + @noble/hashes)",network:i,mnemonic:n,mnemonicWords:n.split(" ").length,seedHex:jt(r),privateSpendKey:jt(o.privateSpendKey),privateViewKey:jt(o.privateViewKey),publicSpendKey:a,publicViewKey:c,address:u,subaddress:f,addressMainnet:h,createdAt:Date.now()}}async function Cp({network:e=Re.networkType,seed:t}={}){return ak({mnemonic:t,network:e})}var rt={};Be(rt,{ALG_NONE:()=>xs,ENVELOPE_VERSION:()=>Lp,FILE_MAGIC:()=>al,PAYLOAD_VERSION:()=>uk,UNENCRYPTED_ENVELOPE_VERSION:()=>cl,buildPayload:()=>pk,createRecoveryFile:()=>mk,decryptFile:()=>ul,encryptPayload:()=>Dp,envelopeAad:()=>ll,isEncrypted:()=>hk,recoveryFileName:()=>wk,scanStartHeight:()=>fk,validatePayload:()=>ks});var Hp="AES-GCM-256/PBKDF2-SHA256",wn=Object.freeze({name:"AES-GCM",tagLength:128,keyBits:256}),ol=Object.freeze({name:"PBKDF2",hash:"SHA-256"}),gs=new TextEncoder,ck=new TextDecoder,al="NINSEI-SWAP-RECOVERY",Lp=2,cl=3,xs="NONE",lk=[1,2,3],uk=3,Rp=[1,2,3],dk=["mainnet","stagenet","testnet","fakechain"];function il(e){return btoa(String.fromCharCode(...new Uint8Array(e)))}function sl(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))}function ll(e){let t=e.meta||{};return JSON.stringify([e.v,e.alg,e.iter,e.salt,e.iv,t.id??null,t.side??null,t.createdAt??null,t.termsHash??null])}async function Fp(e,t,n){let r=await crypto.subtle.importKey("raw",gs.encode(e),ol.name,!1,["deriveKey"]);return crypto.subtle.deriveKey({name:ol.name,salt:t,iterations:n,hash:ol.hash},r,{name:wn.name,length:wn.keyBits},!1,["encrypt","decrypt"])}function fk({escrowBirthHeight:e=null,serverRestoreHeight:t=null,nodeHeight:n=null}={}){let r=[e,t,n].map(o=>Number(o)).filter(o=>Number.isFinite(o)&&o>0);return r.length===0?null:Math.max(1,Math.min(...r)-1)}function pk({swap:e,swapWallet:t,escrow:n,receiveAddress:r,restoreHeight:o=null}){return{magic:al,version:t&&t.spendHalf?3:2,swapId:e.id,termsHash:e.escrow&&e.escrow.termsHash||null,side:e.side,network:e.network,moneroNetwork:e.moneroNetwork,createdAt:e.createdAt,pay:{token:e.payToken,amount:e.payAmount},receive:{token:"XMR",amount:e.xmrAmount,address:r},rate:e.rate,maker:e.maker,quote:{signature:e.quoteSignature,nonce:e.quoteSignature?e.quoteSignature.slice(-8):null},escrow:n||e.escrow||null,moneroWallet:t?t.spendHalf?{source:"halves",library:t.library||null,network:t.network,address:t.address,subaddress:t.subaddress||null,spendHalf:t.spendHalf,viewHalf:t.viewHalf,otherSpendPoint:t.otherSpendPoint,otherViewPoint:t.otherViewPoint,otherViewHalf:t.otherViewHalf||null,escrowAddress:n&&n.address||e.escrow&&e.escrow.address||null,restoreHeight:Number.isFinite(o)?o:null}:{source:t.source,library:t.library||null,network:t.network,address:t.address,subaddress:t.subaddress||null,mnemonic:t.mnemonic||null,publicSpendKey:t.publicSpendKey,publicViewKey:t.publicViewKey,restoreHeight:Number.isFinite(o)?o:null}:null,deadlines:e.timeline,recoveryClient:"any standalone client implementing the Ninsei swap protocol (see litepaper \xA75.3)"}}function ks(e){let t=i=>{throw new Error("Corrupt recovery file: "+i)};(!e||typeof e!="object")&&t("the content is not an object"),e.magic!==al&&t("foreign file (no Ninsei mark)"),Rp.includes(e.version)||t(`payload version ${e.version} is not supported (we support ${Rp.join(", ")})`),e.swapId||t("no deal id");let n=e.moneroWallet;if((!n||typeof n!="object")&&t("no Monero wallet data"),e.version>=3){for(let i of["spendHalf","viewHalf","otherSpendPoint","otherViewPoint","otherViewHalf"])n[i]||t("the halves file has no field "+i);n.mnemonic&&t("the halves file contains a mnemonic - the wallet was not built by the scheme")}else{n.mnemonic||t("no mnemonic - there is nothing that can restore the wallet");let i=String(n.mnemonic).trim().split(/\s+/).length;i!==25&&i!==13&&i!==24&&t(`the mnemonic does not look like a Monero phrase (${i} words)`)}n.address||t("no wallet address - nothing to check the restored one against");let r=n.network||e.moneroNetwork;dk.includes(r)||t(`unknown network "${r}"`),n.network&&e.moneroNetwork&&n.network!==e.moneroNetwork&&t(`the wallet network (${n.network}) does not match the deal network (${e.moneroNetwork})`);let o=[];return(!Number.isFinite(n.restoreHeight)||n.restoreHeight<=0)&&o.push("no restore height (restoreHeight): the wallet will scan history from zero, which is tens of hours - set the XMR lock height manually"),e.version===1&&o.push("an old-format file (v1): its keys were separate fields, the spend key is taken from the mnemonic"),{warnings:o}}async function Dp(e,t){let n=()=>({id:e.swapId,side:e.side,createdAt:e.createdAt,termsHash:e.termsHash||null});if(t==="")return{v:cl,alg:xs,meta:n(),payload:e};if(typeof t!="string"||t.length<12)throw new Error("Passphrase must be at least 12 characters");let r=crypto.getRandomValues(new Uint8Array(16)),o=crypto.getRandomValues(new Uint8Array(12)),i=await Fp(t,r,6e5),s={id:e.swapId,side:e.side,createdAt:e.createdAt,termsHash:e.termsHash||null},a={v:Lp,alg:Hp,iter:6e5,salt:il(r),iv:il(o)},c=await crypto.subtle.encrypt({name:wn.name,iv:o,tagLength:wn.tagLength,additionalData:gs.encode(ll({...a,meta:s}))},i,gs.encode(JSON.stringify(e,Up)));return{...a,ciphertext:il(c),meta:s}}function hk(e){return!!(e&&typeof e=="object"&&e.alg!==xs)}async function ul(e,t){if(!e||typeof e!="object")throw new Error("Not a recovery file (expecting JSON)");if(!lk.includes(e.v))throw new Error(`Unsupported recovery file version: ${e.v}`);if(e.v===cl){if(e.alg!==xs)throw new Error(`Unknown algorithm: ${e.alg}`);if(!e.payload||typeof e.payload!="object")throw new Error('Recovery file is missing "payload"');return e.payload}if(e.alg!==Hp)throw new Error(`Unknown algorithm: ${e.alg}`);for(let u of["salt","iv","ciphertext"])if(typeof e[u]!="string"||!e[u])throw new Error(`Recovery file is missing "${u}"`);let n=Number(e.iter);if(!Number.isInteger(n)||n<1e5)throw new Error(`Recovery file declares too few PBKDF2 iterations: ${e.iter} (minimum 100000)`);if(n>1e7)throw new Error(`Recovery file declares too many PBKDF2 iterations: ${n} (maximum 10000000)`);let r=sl(e.salt),o=sl(e.iv),i=await Fp(t,r,n),s=e.v>=2?gs.encode(ll(e)):void 0,a=s?{name:wn.name,iv:o,tagLength:wn.tagLength,additionalData:s}:{name:wn.name,iv:o,tagLength:wn.tagLength},c;try{c=await crypto.subtle.decrypt(a,i,sl(e.ciphertext))}catch{throw new Error("Could not decrypt the file: wrong password or the file was altered")}let l;try{l=JSON.parse(ck.decode(c))}catch{throw new Error("It decrypted, but the content is not JSON - the file is corrupt")}if(ks(l),e.meta&&e.meta.id!=null&&l.swapId!=null&&String(e.meta.id)!==String(l.swapId))throw new Error("The deal id in the header does not match the file content: the file was altered");return l}var Up=(e,t)=>typeof t=="bigint"?"0x"+t.toString(16):t;async function mk(e,t){let n=await Dp(e,t);return JSON.stringify(n,Up,2)}function wk(e){let t=String(e||"").trim();return`ninsei-${(t&&t!=="pending"?t:"pending").toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}.json.enc`}function Ss({halves:e,addressFromKeys:t,deps:n,ownSpendHalf:r,ownViewHalf:o,otherSpendPoint:i,otherViewPoint:s,network:a}){if(!e||!t)throw new Error("halves and addressFromKeys are required");for(let[m,w]of Object.entries({ownSpendHalf:r,ownViewHalf:o,otherSpendPoint:i,otherViewPoint:s}))if(w==null||w==="")throw new Error("not set: "+m);let c=e.publicHalves(r).ed,l=e.publicHalves(o).ed,u=e.combinePublic(c,i),f=e.combinePublic(l,s);return{address:t({network:a,kind:"primary",spendPub:u,viewPub:f},n),spendPub:u,viewPub:f,ownSpendPub:c,ownViewPub:l}}function Mp({halves:e,ownViewHalf:t,otherViewHalf:n}){return"0x"+e.combineHalves(t,BigInt(n)).toString(16).padStart(64,"0")}async function Kp(e,t={}){let{warnings:n}=ks(e),r=e.moneroWallet,o=r.network||e.moneroNetwork;if(e.version>=3)return await jp(e,n,t);let i=await Cp({seed:r.mnemonic,network:o});if(i.address!==r.address)throw new Error("the address from the file does not match the one derived from the mnemonic: the file is corrupted or altered");for(let[s,a]of[["publicSpendKey",i.publicSpendKey],["publicViewKey",i.publicViewKey]])if(r[s]&&r[s]!==a)throw new Error(`key ${s} from the file does not match the one derived from the mnemonic: the file was altered`);return{wallet:i,payload:e,restoreHeight:Number.isFinite(r.restoreHeight)&&r.restoreHeight>0?r.restoreHeight:0,warnings:n}}async function jp(e,t=[],n={}){let r=e.moneroWallet,o=r.network||e.moneroNetwork,i=n.halves&&n.addressFromKeys?{halves:n.halves,addressFromKeys:n.addressFromKeys,keccak256:n.keccak256}:await(async()=>{let{primitives:l}=await Promise.resolve().then(()=>(Ee(),hp)),{createHalves:u}=await Promise.resolve().then(()=>(Vo(),Yt)),{addressFromKeys:f}=await Promise.resolve().then(()=>(Vn(),mn));return{halves:u(l),addressFromKeys:f,keccak256:l.keccak256}})();if(!i.keccak256)throw new Error("no keccak256: the address cannot be checked without it");let s=Ss({halves:i.halves,addressFromKeys:i.addressFromKeys,deps:{keccak256:i.keccak256},ownSpendHalf:r.spendHalf,ownViewHalf:r.viewHalf,otherSpendPoint:r.otherSpendPoint,otherViewPoint:r.otherViewPoint,network:o});if(s.address!==r.address)throw new Error("the address from the file does not match the one built from the halves and counterparty points: the file is corrupted or altered");let a=Mp({halves:i.halves,ownViewHalf:r.viewHalf,otherViewHalf:r.otherViewHalf});return{wallet:{address:s.address,network:o,spendPub:s.spendPub,viewPub:s.viewPub,viewSeedHex:a,spendHalf:r.spendHalf,viewHalf:r.viewHalf,otherSpendPoint:r.otherSpendPoint,otherViewPoint:r.otherViewPoint,otherViewHalf:r.otherViewHalf,source:"halves",spendable:!1},payload:e,restoreHeight:Number.isFinite(r.restoreHeight)&&r.restoreHeight>0?r.restoreHeight:0,warnings:[...t,"this file describes the HALVES scheme: the view key sees arrivals, but spending needs the counterparty half, which is revealed on chain at the ETH claim"]}}async function yk(e,t,n={}){return Kp(await ul(e,t),n)}function Wp(e,t){for(let r of["mnemonic","seed","seedHex","privateSpendKey","spendKey","subaddressKeys","spendHalf","viewHalf"])if(Object.hasOwn(e,r))throw new Error("the watch-only share must not contain "+r);let n=JSON.stringify(e);for(let[r,o]of[["spend key",t.privateSpendKey],["mnemonic",t.mnemonic],["seed",t.seedHex],["spend key half",t.spendHalf],["view key half",t.viewHalf]])if(o&&n.includes(o))throw new Error(`the watch-only share leaked a secret (${r})`);return e}function bk({swapId:e=null,wallet:t,restoreHeight:n=null}={}){if(!t||!t.address||!t.privateViewKey)throw new Error("a watch-only wallet needs an address and a private view key");return Wp({swapId:e||null,network:t.network,address:t.address,privateViewKey:t.privateViewKey,restoreHeight:Number.isFinite(n)?n:null},t)}var Xn={};Be(Xn,{bindStorage:()=>kk,createStore:()=>vk,exportState:()=>_k,loadState:()=>et,memoryStorage:()=>Vp,reset:()=>Ak,saveState:()=>Ht,setStorage:()=>xk,storage:()=>Sk,update:()=>Ek});var dl={version:1,settings:{speed:Kt.defaultSpeed,scenario:Kt.defaultScenario,chainMode:Kt.defaultChainMode,chain:Kt.defaultChain,payToken:""},wallet:{connected:!1,address:null,balances:{}},swaps:{},activeSwapId:null};function Vp(e=new Map){return{get:t=>e.has(t)?e.get(t):null,set:(t,n)=>e.set(t,String(n)),remove:t=>e.delete(t)}}var gk=e=>{let t=typeof globalThis<"u"?globalThis[e]:void 0;return!t||typeof t.getItem!="function"?null:{get:n=>t.getItem(n),set:(n,r)=>t.setItem(n,String(r)),remove:n=>t.removeItem(n)}},yn=gk("localStorage")||Vp(),Es=null,fl=e=>{if(!(e&&typeof e.get=="function"&&typeof e.set=="function"&&typeof e.remove=="function"))throw new Error("storage must support get/set/remove")},zn=(e,t)=>{let n=new Error("storage-unavailable");return n.code="storage-unavailable",n.params={step:e},t&&(n.cause=t),n};function xk(e){return fl(e),yn=e,Es=null,yn}function kk(e){if(fl(e),Es&&Es!==e)throw zn("conflict");return Es=e,yn=e,yn}var Sk=()=>yn;function $p(e){let t;try{t=e.get(_o.storageKey)}catch(r){throw zn("read",r)}if(t==null||t==="")return structuredClone(dl);let n;try{n=JSON.parse(t)}catch(r){throw zn("parse",r)}if(!n||typeof n!="object"||Array.isArray(n))throw zn("parse");return{...structuredClone(dl),...n,settings:{...dl.settings,...n.settings||{}}}}function et(){return $p(yn)}var zp=(e,t)=>typeof t=="bigint"?"0x"+t.toString(16):t;function Xp(e,t){let n;try{n=JSON.stringify(t,zp)}catch(r){throw zn("serialize",r)}try{e.set(_o.storageKey,n)}catch(r){throw zn("write",r)}return t}function Ht(e){return Xp(yn,e)}function vk(e){return fl(e),{loadState:()=>$p(e),saveState:t=>Xp(e,t),storage:()=>e}}function Ek(e){let t=et(),n=e(t)||t;return Ht(n),n}function Ak(){try{yn.remove(_o.storageKey)}catch(e){throw zn("remove",e)}}function _k(){return JSON.stringify(et(),zp,2)}var Yp="eip6963:announceProvider",Ik="eip6963:requestProvider";function Gp(e){return(e&&(e.code||e.data&&e.data.originalError&&e.data.originalError.code))===4001?!0:/rejected|denied|cancell?ed|closed by user/i.test(String(e&&e.message||e||""))}function Nk(e){return e?e.isMetaMask?"MetaMask":e.isRabby?"Rabby":e.isCoinbaseWallet?"Coinbase Wallet":e.isBraveWallet?"Brave Wallet":e.isFrame?"Frame":"Browser wallet":null}function $o({win:e=globalThis,timeoutMs:t=250}={}){let n=[],r=new Set,o=s=>{let a=s.rdns||s.uuid||s.name;r.has(a)||(r.add(a),n.push(s))},i=s=>{let a=s&&s.detail;!a||!a.provider||!a.info||o({uuid:a.info.uuid||null,name:a.info.name||"Browser wallet",icon:a.info.icon||null,rdns:a.info.rdns||null,provider:a.provider,source:"eip6963"})};return e&&typeof e.addEventListener=="function"&&(e.addEventListener(Yp,i),typeof e.dispatchEvent=="function"&&e.dispatchEvent(new Event(Ik))),new Promise(s=>{let a=()=>{e&&typeof e.removeEventListener=="function"&&e.removeEventListener(Yp,i);let c=e&&e.ethereum;if(!n.length&&c){let l=Array.isArray(c.providers)&&c.providers.length?c.providers:[c];for(let u of l)o({name:Nk(u),icon:null,rdns:null,provider:u,source:"legacy"})}s(n)};t>0&&typeof setTimeout=="function"?setTimeout(a,t):a()})}async function qp(e){if(!e||typeof e.request!="function")throw new Error("This wallet does not support EIP-1193 (no request)");let t=await e.request({method:"eth_requestAccounts"}),n=Array.isArray(t)?t[0]:null,r=await e.request({method:"eth_chainId"});return{address:n||null,chainId:Number(r)||null}}async function Qp(e){if(!e||typeof e.request!="function")return[];try{let t=await e.request({method:"eth_accounts"});return Array.isArray(t)?t:[]}catch{return[]}}function Zp(e,t="Wallet"){let n=e&&(e.code||e.data&&e.data.originalError&&e.data.originalError.code),r=String(e&&e.message||e);return n===-32002||/already pending|already processing/i.test(r)?t+": the wallet already has a pending request, so a new window did not open. Open the extension, finish or cancel that request, then try again.":/no provider|not connected|provider is disconnected|undefined is not a function/i.test(r)?t+": the extension is not responding (the browser may have unloaded it, or the page is not where it works).":/user rejected|user denied|rejected by user/i.test(r)||n===4001?t+": the request was rejected in the wallet.":t+": "+r}function De(e,t={},n=[]){let r=document.createElement(e);for(let[i,s]of Object.entries(t||{}))s==null||s===!1||(i==="class"?r.className=s:i==="html"?r.innerHTML=s:i==="text"?r.textContent=s:i==="style"?typeof s=="string"?r.style.cssText=s:Object.assign(r.style,s):i.startsWith("on")&&typeof s=="function"?r.addEventListener(i.slice(2).toLowerCase(),s):r.setAttribute(i,s===!0?"":String(s)));let o=Array.isArray(n)?n:[n];for(let i of o)i==null||i===!1||r.appendChild(typeof i=="string"||typeof i=="number"?document.createTextNode(String(i)):i);return r}function Jp({title:e="Connect a wallet",subtitle:t="",hint:n=""}={}){let r={},o=De("div",{class:"ar-overlay"},[De("div",{class:"ar-modal"},[De("div",{class:"ar-modal-head"},[De("div",{class:"ar-modal-title",text:e}),r.closeBtn=De("button",{class:"ar-modal-close",type:"button",title:"Close",text:"\xD7"})]),r.subtitle=De("div",{class:"ar-modal-sub",text:t}),r.choices=De("div",{class:"ar-modal-choices"}),r.status=De("div",{class:"ar-modal-status"}),De("div",{class:"ar-modal-actions"},[r.cancelBtn=De("button",{class:"ar-btn-ghost",type:"button",text:"Cancel"})]),r.hint=De("div",{class:"ar-modal-hint",text:n})])]);document.body.appendChild(o);let i={value:!1},s=null;function a(){i.value||(i.value=!0,o.remove())}function c(){i.value||(a(),s&&s())}r.closeBtn.addEventListener("click",c),r.cancelBtn.addEventListener("click",c),o.addEventListener("click",u=>{u.target===o&&c()});function l(u){r.choices.innerHTML="",r.choices.hidden=!u||!u.length;for(let f of u||[]){let h=De("button",{class:"ar-modal-choice",type:"button"},[f.icon?De("img",{class:"ar-modal-choice-icon",src:f.icon,alt:""}):De("span",{class:"ar-modal-choice-icon ar-modal-choice-icon-empty"}),De("span",{class:"ar-modal-choice-text"},[De("span",{class:"ar-modal-choice-name",text:f.name}),f.hint?De("span",{class:"ar-modal-choice-hint",text:f.hint}):null])]);h.addEventListener("click",()=>{i.value||f.onClick()}),r.choices.appendChild(h)}return r.choices}return{closed:i,setChoices:l,close:a,cancel:c,setOnCancel(u){s=u},update({status:u,subtitle:f,hint:h,error:m}={}){if(i.value)return;f!==void 0&&(r.subtitle.textContent=f||""),h!==void 0&&(r.hint.textContent=h||"");let w=m||u;w!==void 0&&(r.status.className="ar-modal-status"+(m?" ar-modal-status-error":""),r.status.textContent=w||"")}}}function eh(e,t){return Number(e)/10**t}var j3=[[12345678900n,6,12345.6789],[108275582n,6,108.275582],[10n**18n,18,1],[1500000000000000000n,18,1.5],[55000000000000n,18,55e-6],[55000n,18,55e-15],[3120000000000000000000n,18,3120],[0n,18,0]];var _s={};Be(_s,{CLAIM_GAS_LIMIT:()=>pl,CLAIM_TIP_FLOOR_WEI:()=>th,DEFAULT_GIFT_RESERVE_BPS:()=>rh,claimGasGiftWei:()=>hl,claimMaxFeePerGasWei:()=>As,claimRequiredWei:()=>nh});var pl=200000n,th=0n,Or=e=>{if(e==null||e==="")return null;try{return BigInt(typeof e=="bigint"?e:String(e))}catch{return null}};function As({baseFeeWei:e,priorityFeeWei:t=0n,minTipWei:n=th}={}){let r=Or(e);if(r===null||r<=0n)return null;let o=Or(t),i=Or(n),s=i===null||i<0n?0n:i,a=o!==null&&o>s?o:s;return r*2n+a}function nh({gasLimit:e=pl,maxFeePerGasWei:t}={}){let n=Or(e),r=Or(t);return n===null||n<=0n||r===null||r<=0n?null:n*r}var rh=10000n;function hl({baseFeeWei:e,priorityFeeWei:t,minTipWei:n,gasLimit:r=pl,reserveBps:o=rh}={}){let i=As({baseFeeWei:e,priorityFeeWei:t,minTipWei:n}),s=nh({gasLimit:r,maxFeePerGasWei:i});if(s===null)return null;let a=Or(o),c=a===null||a<0n?0n:a;return s+s*c/10000n}var wl=new Set,te={status:"idle",kind:null,label:null,address:null,chainId:null,balances:{},error:null,lastRefresh:0},xe=null,ft=null;function pt(){for(let e of wl)try{e(Yn())}catch(t){console.warn("wallet listener failed",t)}}function Yn(){return{...te,balances:{...te.balances}}}function oh(e){return wl.add(e),()=>wl.delete(e)}function ih(){return Yn()}function Qn(){return te.status==="connected"&&!!te.address}function bl(){return te.address}function sh(){return te.chainId}function ah(){return xe}function ch(e,t){let n=lt(e),r=te.balances[`${n.chainId}:${String(t).toUpperCase()}`];return r===void 0?0:r}var Tk=e=>"0x"+Number(e).toString(16);function Gn(e="idle",t=null){te.status=e,te.error=t,te.kind=null,te.label=null,te.address=null,te.chainId=null,te.balances={},xe=null,pt()}function lh(e){e.on("chainChanged",t=>{te.chainId=Number(t),te.error=null,pt(),qn()}),e.on("accountsChanged",t=>{let n=t&&t[0]||null;if(!n){ft&&ft.close(),Gn("idle",null);return}te.address=n,pt(),qn()}),e.on("disconnect",()=>{ft&&ft.close(),Gn("idle",null)})}var yl="ninsei.wallet.optOut",Pk=()=>{try{return localStorage.getItem(yl)==="1"}catch{return!1}},uh=e=>{try{e?localStorage.setItem(yl,"1"):localStorage.removeItem(yl)}catch{}},ml=!1;async function dh(){return Pk()?(ml=!0,console.log("[wallet] restore skipped: wallet disconnected manually"),Yn()):ml||te.status==="connected"?Yn():(ml=!0,gl())}async function gl({wallets:e}={}){if(Qn())return Yn();let t=e||await $o();for(let n of t){let r=await Qp(n.provider);if(r.length){xe=n.provider,te.kind="injected",te.label=n.name||"Browser wallet",lh(xe),te.address=r[0];try{te.chainId=Number(await xe.request({method:"eth_chainId"}))||null}catch{te.chainId=null}return te.status="connected",te.error=null,pt(),await qn(),console.info("Browser wallet restored without a prompt: "+te.address),Yn()}}return Yn()}async function xl({wallet:e,chainSlug:t}={}){if(uh(!1),!e||!e.provider)throw new Error("No wallet extension found in this browser");if(Qn()&&te.kind==="injected"&&te.label===(e.name||null))return{address:te.address,chainId:te.chainId};let n=lt(t||te.chainId||void 0);xe=e.provider,te.kind="injected",te.label=e.name||"Browser wallet",te.status="pairing",te.error=null,pt(),lh(xe);try{let r=await qp(xe);if(!r.address)throw new Error("The wallet returned no address");return te.address=r.address,te.chainId=r.chainId||n.chainId,te.status="connected",te.error=null,pt(),te.chainId!==n.chainId&&await kl(n),await qn(),{address:te.address,chainId:te.chainId}}catch(r){let o=te.label||e.name||"Wallet",i=Zp(r,o);if(Gp(r))return console.info("[wallet] user refusal: "+i),Gn("idle",null),null;throw console.warn("[wallet] connect did not happen: "+i,r),Gn("error",i),new Error(i)}}async function fh({chainSlug:e}={}){if(Qn())return{address:te.address,chainId:te.chainId};let t=lt(e||te.chainId||void 0);te.status="pairing",te.error=null,pt();let n=await $o();n.length?console.info("[wallet] found in the browser: "+n.map(o=>o.name+" ["+o.source+(o.rdns?" "+o.rdns:"")+"]").join(", ")):console.info("[wallet] no browser wallets found"),ft=Jp({title:"Connect a wallet",subtitle:`Requested network: ${t.name}.`,hint:"Browser wallets are detected in this browser through EIP-6963."});let r=await new Promise(o=>{ft.setOnCancel(()=>o({type:"cancel"}));let i=n.map(s=>({key:s.rdns||s.name,name:s.name,icon:s.icon,hint:s.source==="eip6963"?null:"detected via window.ethereum",onClick:()=>o({type:"injected",wallet:s})}));ft.setChoices(i),ft.update({status:n.length?"Choose a browser wallet above.":"No browser wallet found in this browser. Install a browser wallet or use the host's own connector."})});if(r.type==="cancel")return Gn("idle",null),null;try{let o=await xl({wallet:r.wallet,chainSlug:t.id});return ft&&ft.close(),o}catch(o){let i=String(o&&o.message||o);throw ft&&ft.update({error:i,status:"Try again."}),o}}async function ph(){uh(!0);let e=xe;if(!e){Gn("idle",null);return}try{typeof e.revokePermissions=="function"&&await e.request({method:"wallet_revokePermissions",params:[{eth_accounts:{}}]})}catch(t){console.warn("disconnect failed",t)}Gn("idle",null)}async function kl(e){let t=typeof e=="object"?e:lt(e);if(!xe||!Qn())return!1;let n=Tk(t.chainId);try{await xe.request({method:"wallet_switchEthereumChain",params:[{chainId:n}]})}catch(r){if(!((r&&(r.code||r.data&&r.data.originalError&&r.data.originalError.code))===4902||/unrecognized chain|not added/i.test(String(r&&r.message))))return/rejected|denied/i.test(String(r&&r.message))||(te.error=String(r&&r.message||r),pt()),!1;try{await xe.request({method:"wallet_addEthereumChain",params:[{chainId:n,chainName:t.name,nativeCurrency:{name:t.native.symbol,symbol:t.native.symbol,decimals:t.native.decimals},rpcUrls:[t.rpcUrl],blockExplorerUrls:[t.explorerAddr]}]})}catch(s){return/rejected|denied/i.test(String(s&&s.message))||(te.error=String(s&&s.message||s),pt()),!1}}return te.chainId=t.chainId,pt(),await qn(),!0}async function Sl({to:e,data:t,block:n="latest"}={}){if(!xe)throw new Error("wallet not connected: nothing to read the contract with");if(!e)throw new Error("no contract address given");if(!t)throw new Error("no call data given");let r=await xe.request({method:"eth_call",params:[{to:e,data:t},n||"latest"]});if(typeof r!="string"||!r.startsWith("0x"))throw new Error("unexpected answer to a contract call: "+String(r).slice(0,60));return r}async function hh({address:e}={}){if(!xe)throw new Error("wallet not connected: nothing to read the contract code with");if(!e||!/^0x[0-9a-fA-F]{40}$/.test(String(e)))throw new Error("not an address for reading code: "+String(e));return await xe.request({method:"eth_getCode",params:[e,"latest"]})}async function vl({hash:e}={}){if(!xe)throw new Error("wallet not connected: nothing to read the receipt with");if(!e)throw new Error("no transaction hash given");let t=await xe.request({method:"eth_getTransactionReceipt",params:[e]});return!t||typeof t!="object"?null:t}async function El({to:e,data:t,value:n="0x0",gas:r}={}){if(!xe)throw new Error("wallet not connected: nothing to send with");if(!e)throw new Error("no contract address given");if(!t)throw new Error("no call data given");let o=bl();if(!o)throw new Error("wallet not connected: no sender address");let i={from:o,to:e,data:t,value:typeof n=="bigint"?"0x"+n.toString(16):n};r&&(i.gas=typeof r=="bigint"?"0x"+r.toString(16):r);try{let a=await xe.request({method:"eth_getBlockByNumber",params:["latest",!1]}),c=a&&a.baseFeePerGas?BigInt(a.baseFeePerGas):0n,l=0n;try{let f=await xe.request({method:"eth_gasPrice",params:[]});if(typeof f=="string"&&/^0x[0-9a-fA-F]+$/.test(f)){let h=BigInt(f)-c;h>0n&&(l=h)}}catch{}let u=As({baseFeeWei:c,priorityFeeWei:l});u!==null&&(i.maxPriorityFeePerGas="0x"+(u-c*2n).toString(16),i.maxFeePerGas="0x"+u.toString(16))}catch(a){console.warn("could not compute the fee, the wallet decides: "+(a&&a.message||a))}let s=await xe.request({method:"eth_sendTransaction",params:[i]});if(typeof s!="string"||!/^0x[0-9a-fA-F]{64}$/.test(s))throw new Error("the wallet returned not a transaction hash: "+String(s).slice(0,60));return s}async function qn(){if(!Qn()||!xe)return;let e=cc(te.chainId);if(!e){te.error=`Wallet is on chain ${te.chainId}, which this demo does not support`,pt();return}let t=te.address,n={},r=[[e.native.symbol,null,e.native.decimals,"eth_getBalance"]];for(let i of e.tokens)r.push([i.symbol,i.address,i.decimals,null]);let o=await Promise.all(r.map(async([i,s,a,c])=>{try{let l;if(c==="eth_getBalance")l=await xe.request({method:c,params:[t,"latest"]});else{let u="0x70a08231"+t.replace(/^0x/,"").toLowerCase().padStart(64,"0");l=await xe.request({method:"eth_call",params:[{to:s,data:u},"latest"]})}return[i,eh(BigInt(l),a)]}catch(l){return console.warn(`balance read failed for ${i}`,l),[i,void 0]}}));for(let[i,s]of o)s!==void 0&&(n[`${e.chainId}:${String(i).toUpperCase()}`]=s);te.balances={...te.balances,...n},te.lastRefresh=Date.now(),te.error=null,pt()}var ue={};Be(ue,{STEP_LABELS:()=>Kk,TERMINAL:()=>Rr,activeSwaps:()=>zk,addServerSwaps:()=>$k,allSwaps:()=>Ih,confirmReady:()=>Yk,createReverseSwap:()=>Wk,createSwap:()=>jk,dealSwapIds:()=>e1,derive:()=>Go,forgetSwap:()=>Vk,getSwap:()=>Ts,halvesWalletOf:()=>Ns,onNotify:()=>r1,refundEth:()=>qk,refundHalfRevealed:()=>Ph,saveSwap:()=>Xk,serverRestoreHeightFor:()=>t1,serverRowToSwap:()=>Nh,setLiveFocus:()=>n1,startTicker:()=>o1,subscribe:()=>Zk,sweepNow:()=>Gk,tick:()=>Oh,xmrAmountCheck:()=>Bh});var Et={softSec:600,hardSec:1200},mh=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?Math.floor(n):t};function wh({poolSeen:e,soft:t=Et.softSec,hard:n=Et.hardSec}={}){let r=mh(t,Et.softSec),o=mh(n,Et.hardSec),i=Math.min(r,o);return e?i:o}function ht(){return Date.now()}function zo(e,t=ht()){return Math.max(0,(t-e.realStart)*e.speed)}function Zn(e,t){return e.simStartWall+t}var Bk=Re.node,Ok=8e3,Ck=15e3,Jn={at:0,data:null,error:null},Xo=null;async function Rk(e,t={},n="/json_rpc"){let r=new AbortController,o=setTimeout(()=>r.abort(),Ok);try{let i=await fetch(Bk+n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:"ninsei-demo",method:e,params:t}),signal:r.signal});if(!i.ok)throw new Error("HTTP "+i.status);let s=await i.json();if(s.error)throw new Error(s.error.message||"RPC error");return s.result}finally{clearTimeout(o)}}function Is(){return Jn.data}async function yh({force:e=!1}={}){return Jn.data&&Date.now()-Jn.at<Ck&&!e?Jn.data:Xo||(Xo=Rk("get_info").then(n=>(Jn={at:Date.now(),data:Hk(n),error:null},Jn.data)).catch(n=>(Jn={at:Date.now(),data:null,error:n.message},null)).finally(()=>{Xo=null}),Xo)}function Hk(e){return{height:e.height,nettype:e.nettype||(e.mainnet?"mainnet":e.stagenet?"stagenet":"testnet"),offline:!!e.offline,busySyncing:!!e.busy_syncing,version:e.version,target:e.target,txPoolSize:e.tx_pool_size,outgoing:e.outgoing_connections_count,incoming:e.incoming_connections_count,databaseSizeGb:e.database_size?Math.round(e.database_size/1024**3):null,fetchedAt:Date.now()}}function Cr(...e){let t=e.join("|"),n=2166136261;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=n*16777619>>>0;return"0x"+n.toString(16).padStart(8,"0")+Di(28)}function Lk(e){return"0x"+Cr("escrow",e).slice(2,42)}function Fk(e){return"8"+Cr("xmrlock",e).slice(2,96)}function gh({swapId:e,ethAmountUsd:t,ethUsd:n}){return{mock:!0,txHash:Cr("fund",e),escrow:Lk(e),ethAmount:n>0?t/n:0,valueUsd:t,gasUsd:.21,method:"simulated funding (no real transaction)",confirmations:1}}function xh({swapId:e,xmrAmount:t}){return{mock:!0,txid:Cr("xmrtx",e),address:Fk(e),amount:t,viewKeyVerified:!0,unlocked:"1 of 2 spend key shares revealed (DLEQ bound)"}}function Al({swapId:e}){return{mock:!0,txid:Cr("sweep",e)}}function _l({swapId:e,by:t}){return{mock:!0,txHash:Cr("refund",e,t),by:t}}function kh(e,t){let n=e.timeline.confTarget;if(e.chainMode==="live"){let i=e.xmr&&e.xmr.lockHeight,s=Is();return i&&s&&typeof s.height=="number"&&s.height>=i?Math.max(0,Math.min(n,s.height-i)):(e.xmr,0)}let r=e.timeline.lockAtSim;if(r===null||t<r)return 0;let o=Math.floor((t-r)/e.timeline.blockSim);return Math.max(0,Math.min(n,o))}var bn={AWAITING:"awaiting_funding",FUNDED:"funded",LOCKED:"xmr_locked",READY:"ready",SWEPT:"swept",CLOSED:"closed"};function gn(e=on.xmrSource){return e==="app"}function Uk(e,t){let n=e.timeline&&e.timeline.confTarget||Re.confirmTarget,r=e.timeline?e.timeline.lockAtSim:0,o=r!==null&&t>=r,i=kh(e,t),s=o?i>=n?bn.READY:bn.FUNDED:bn.AWAITING,a=Number(e.xmr&&e.xmr.received),c=o?Number.isFinite(a)?a:e.xmrAmount:0;return{live:!1,status:s,received:c,unlocked:c,locked:0,lockedUntil:null,arrived:c,confirmations:i,confTarget:n,txids:e.xmr&&e.xmr.txid?[e.xmr.txid]:[],address:e.xmr&&e.xmr.address||null,sweepTxid:e.xmr&&e.xmr.sweepTxid||null,error:null}}function Mk(e){let t=e.timeline&&e.timeline.confTarget||Re.confirmTarget,n=e.xmrSession;return n?{live:!0,status:e.xmrSessionError?"error":n.status,received:Number(n.receivedXmr)||0,unlocked:Number(n.receivedXmr)||0,locked:Number(n.lockedXmr)||0,lockedUntil:n.lockedUntil||null,arrived:(Number(n.receivedXmr)||0)+(Number(n.lockedXmr)||0),confirmations:n.confirmations,confTarget:t,txids:n.fundingTxids,address:n.address||e.swapWallet&&e.swapWallet.address||null,sweepTxid:n.sweepTxid,error:e.xmrSessionError||null}:{live:!0,status:e.xmrSessionError?"error":"opening",received:0,unlocked:0,locked:0,lockedUntil:null,arrived:0,confirmations:0,confTarget:t,txids:[],address:e.swapWallet&&e.swapWallet.address||null,sweepTxid:null,error:e.xmrSessionError||null}}function Sh(e,t){return gn(e&&e.xmrSource)?Mk(e):Uk(e,t)}function vh(e,t="stagenet"){return e?`https://${t==="mainnet"?"":t+"."}xmrchain.net/tx/${e}`:null}var Kk=[["funded","Funded on-chain"],["maker_locking","Maker locking XMR"],["xmr_locked","XMR locked"],["ready","Verified by you"],["claimed","Claimed by maker"],["swept","Sent to your address"]],Rr={success:{phase:"success",label:"XMR delivered"},refunded_eth:{phase:"refunded_eth",label:"ETH refunded"}};function jk(e,t=null){let n=t?t.loadState():et(),r=Date.now(),o={id:pc(),side:e.side||"buy",scenario:e.scenario||"happy",speed:e.speed||60,network:e.network||Hn,moneroNetwork:e.moneroNetwork||Re.networkType,realStart:r,simStartWall:r,createdAt:new Date(r).toISOString(),payToken:e.payToken,payAmount:Number(e.payAmount),xmrAmount:Number(e.xmrAmount),rate:Number(e.rate),fee:Number(e.fee),maker:{id:e.makerId,name:e.makerName,spread:e.makerSpread},dexSpread:e.dexSpread,gasUsd:e.gasUsd,receiveAddress:e.receiveAddress,quoteSignature:e.quoteSignature,swapWallet:e.swapWallet||null,timeline:{fundAtSim:0,lockAtSim:e.scenario==="maker_no_lock"?null:St.makerLock,blockSim:Re.blockTimeSim,confTarget:Re.confirmTarget,t0Sim:St.t0Refund},chainMode:e.chainMode||Kt.defaultChainMode,xmrSource:e.xmrSource||on.xmrSource,xmrSession:null,xmrSessionError:null,events:[],escrow:null,xmr:null,settlement:null,log:[]};if(o.chainMode!=="live"){let i=gh({swapId:o.id,ethAmountUsd:o.payAmount,ethUsd:3212.4});o.escrow={address:i.escrow,fundTx:i.txHash,method:i.method,fundedAtSim:0,gasUsd:i.gasUsd},Gt(o,0,"Escrow funded",`eth escrow ${i.escrow}`)}else o.escrow={address:null,fundTx:null,method:null,fundedAtSim:0,gasUsd:e.gasUsd??null};return n.swaps[o.id]=o,n.activeSwapId=o.id,t?t.saveState(n):Ht(n),o}function Wk(e={}){let t=et(),n=Date.now(),r=Number(e.xmrAmount),o={id:pc(),side:"reverse",scenario:"happy",speed:Number(e.speed)||60,network:e.network||Hn,moneroNetwork:e.moneroNetwork||Re.networkType,realStart:n,simStartWall:n,createdAt:new Date(n).toISOString(),payToken:"XMR",payAmount:r,xmrAmount:r,rate:Number(e.rate)||0,fee:Number(e.fee)||0,maker:{id:e.providerId||null,name:e.providerName||null,spread:null},receiveAddress:e.claimer||null,quoteSignature:null,ticket:e.ticketId||null,timeline:{fundAtSim:0,lockAtSim:0,blockSim:Re.blockTimeSim,confTarget:Re.confirmTarget,t0Sim:St.t0Refund},chainMode:e.chainMode||Kt.defaultChainMode,xmrSource:e.xmrSource||on.xmrSource,xmrSession:null,xmrSessionError:null,events:[],escrow:{address:e.escrowAddress||null,moneroAddress:e.moneroAddress||null,half:e.ownSpendHalf||null,viewHalf:e.ownViewHalf||null,counterViewHalf:e.counterViewHalf||null,counterViewPoint:e.counterViewPoint||null,counterSpendPoint:e.counterSpendPoint||null,moneroNetwork:e.moneroNetwork||Re.networkType,birthHeight:e.escrowBirthHeight||null,readyBy:e.readyBy||null,t1:e.t1||null,counterHalf:null},xmr:null,settlement:null,log:[]};return t.swaps[o.id]=o,t.activeSwapId=o.id,Ht(t),o}function Gt(e,t,n,r){e.log.push({atSim:t,wall:Zn(e,t),title:n,detail:r||""}),console.log(`[swap ${e.id}] ${n}${r?" - "+r:""}`)}function Ns(e){let t=e&&e.escrow||{};return!t.half||!t.viewHalf||!t.counterViewHalf||!t.moneroAddress?null:{source:"halves",library:"ninsei-monero-keys",network:t.moneroNetwork||Re.networkType,address:t.moneroAddress,subaddress:null,spendHalf:t.half,viewHalf:t.viewHalf,otherSpendPoint:t.counterSpendPoint||t.edPointClaimer||null,otherViewPoint:t.counterViewPoint||null,otherViewHalf:t.counterViewHalf}}function Vk(e,t=null){let n=t?t.loadState():et();return n.swaps[e]?(delete n.swaps[e],t?t.saveState(n):Ht(n),!0):!1}function Ts(e,t=null){return(t?t.loadState():et()).swaps[e]||null}function Ih(){let e=et();return Object.values(e.swaps).sort((t,n)=>t.realStart<n.realStart?1:-1)}function Nh(e){let t=String(e&&e.escrow||"").toLowerCase();return{id:String(e.id),network:e.network||null,chain:e.network||null,source:"server",status:"in_progress",escrow:{address:t,t0:e.t0!=null?Number(e.t0):null,t1:e.t1!=null?Number(e.t1):null,hashlock:e.hashlock||null,amountWei:e.amount!=null?String(e.amount):null,fromServer:!0},log:[],events:[]}}function $k(e,t=null){if(!Array.isArray(e)||e.length===0)return 0;let n=t?t.loadState():et(),r=0;for(let o of e)!o||!o.id||!o.escrow||n.swaps[o.id]||(n.swaps[o.id]=Nh(o),r+=1);return r&&(t?t.saveState(n):Ht(n)),r}function zk(){return Ih().filter(e=>!e.settlement)}function Xk(e,t=null){return Ps(e,t)}function Ps(e,t=null){let n=t?t.loadState():et();return n.swaps[e.id]=e,t?t.saveState(n):Ht(n),e}function Eh(e,t,n,r={}){return e.events.push({type:t,atSim:n,...r}),e}function Th(e,t){return e.events.find(n=>n.type===t)||null}function Yk(e,t=null){let n=Ts(e,t);if(!n||n.settlement)return n;if(!Go(n).can.ready)throw new Error("ready() is not available in this phase");let o=zo(n);return Eh(n,"ready",o),Gt(n,o,"ready() called by you","maker may now claim the ETH escrow"),Th(n,"funded_note")||Eh(n,"funded_note",0),Ps(n,t)}function Ph(e){let t=e&&e.escrow||{};return t.revealedHalf||t.counterHalf||null}function Gk(e,t=null){let n=Ts(e,t);if(!n||n.settlement&&!(n.settlement.kind==="refund_eth"&&n.side==="reverse"))return n;if(!Go(n).can.sweep)throw new Error("sweep is not available in this phase");let o=zo(n),i=Al({swapId:n.id});n.xmr=n.xmr||{},n.xmr.sweepTxid=i.txid;let s=!!(n.settlement&&n.settlement.kind==="refund_eth");return n.settlement={kind:"success",phase:Rr.success.phase,atSim:o,txid:i.txid,by:"you",...s?{recovered:!0}:{}},Gt(n,o,"XMR swept to your address",i.txid),Ps(n,t)}function qk(e,t="you",n=null){let r=Ts(e,n);if(!r||r.settlement)return r;if(!Go(r).can.refund)throw new Error("refund is not available in this phase");let i=zo(r),s=_l({swapId:r.id,by:t});return r.settlement={kind:"refund_eth",phase:Rr.refunded_eth.phase,atSim:i,txHash:s.txHash,by:t},Gt(r,i,`ETH refunded to your wallet (${t})`,s.txHash),Ps(r,n)}function Ah(e){return((lt(e&&e.network||Hn)||{}).escrow||{}).mode==="live"}var _h=1e-6;function Bh(e,t){let n=Number(e&&e.xmrAmount),r=Number.isFinite(n)&&n>0,o=t&&t.arrived!==null&&t.arrived!==void 0?t.arrived:t?t.received:null,i=o!=null&&Number.isFinite(Number(o))?Number(o):null;return r?i===null?{ok:!1,checked:!0,expected:n,seen:null,why:"the amount of XMR on the address is not known ("+n+" XMR was quoted): ready stays closed until the sum is seen"}:i+_h<n?{ok:!1,checked:!0,expected:n,seen:i,why:"only "+i+" XMR arrived, the quote promised "+n+" XMR: ready is blocked - the escrow would pay out for less than agreed"}:i>n+_h?{ok:!1,checked:!0,expected:n,seen:i,why:i+" XMR arrived, but the record promises "+n+" XMR: the sum on the address does not match the quoted trade - ready is blocked until they agree (a node paying more than it quoted loses its spread)"}:{ok:!0,checked:!0,expected:n,seen:i,why:null}:{ok:!0,checked:!1,expected:null,seen:i,why:"the record has no quoted XMR amount, so the arrived sum cannot be compared - this is named, not assumed"}}function Go(e,t=ht()){let n=zo(e,t),r=e.timeline,i=(L=>Th(e,L))("ready"),s=gn(e.xmrSource),a=Sh(e,n),c=Number(a.arrived!==void 0&&a.arrived!==null?a.arrived:a.received||0),l=s?c>0?0:null:r.lockAtSim,u=a.confirmations,f=s?c>0:l!==null&&n>=l,h=i?i.atSim:null,m=e.escrow&&e.escrow.readyBy?Number(e.escrow.readyBy)*1e3:null,w=e.escrow&&e.escrow.t1?Number(e.escrow.t1)*1e3:null,x=Number(a.arrived!==void 0&&a.arrived!==null?a.arrived:a.received||0)>0,y=(()=>{if(e.side!=="reverse"||m===null)return null;let L=m-Et.hardSec*1e3,V=L+Et.softSec*1e3,U=wh({poolSeen:x,soft:Et.softSec,hard:Et.hardSec}),j=!x&&ht()>=V,F=j?L+U*1e3:V;return{startMs:L,atMs:F,leftMs:F-ht(),seen:x,extended:j,softSec:Et.softSec,hardSec:Et.hardSec,windowSec:U}})(),k=h!==null&&e.scenario!=="maker_stall"?h+St.makerClaim:null,I=k!==null?k+St.sweep:null,g=l!==null?l+St.readyWindow:null,P=g!==null?g+St.makerReclaim:null,E=h!==null?h+St.t1Refund:null,B=h===null&&P!==null&&n>=P,p={ready:!1,sweep:!1,refund:!1},b="xmr_locked",S="Waiting",v=null,H=null;if(e.settlement){if(b=e.settlement.phase,S=Object.values(Rr).find(L=>L.phase===e.settlement.phase)?.label||"Settled",e.settlement.kind==="refund_eth"&&e.side==="reverse"){let L=Ph(e),V=c>0;p.sweep=!!(L&&V&&Ns(e)),H=p.sweep?"The refund published the provider's half, so your XMR can be swept back from the swap's one-time address to your own wallet.":V?"The refund is done and your XMR is on the swap's one-time address, but the provider's half of the spend key is not published yet: sweeping needs both halves, so the button waits for the chain.":"The refund is done, but no XMR is on the swap's one-time address: there is nothing of yours to sweep back."}}else if(s&&h===null&&m!==null&&ht()>=m&&(w===null||ht()<w))b="dead_zone",S="Ready deadline passed - the refund opens at T1",p.ready=!1,p.refund=!1,p.refundByAnyone=!1,H="The ready() deadline has passed without your confirmation. The maker can claim now, and the escrow refuses a refund before T1 while the mark is absent. The refund opens at T1 and returns your ETH and publishes your half. "+(w!==null?"T1: "+new Date(w).toISOString()+".":"");else if(s&&h===null)if(w!==null&&ht()>=w)b="refund_available",S="Claim deadline passed - the refund is open",p.ready=!1,p.refund=!0,p.refundByAnyone=!0,H="The claim deadline passed without the ready mark. The refund is open to anyone who can present the depositor's half - that half is yours in the recovery file. It returns your ETH and publishes your half.";else if(a.status===bn.LOCKED){b="xmr_unlock_pending",S="XMR is on your address but locked on-chain",p.ready=!1;let L=a.lockedUntil||{},V=L.untilHeight!==null&&L.untilHeight!==void 0?"block "+L.untilHeight:L.untilTime!==null&&L.untilTime!==void 0?new Date(Number(L.untilTime)*1e3).toISOString()+" UTC":"a time the sender set";H="The sender set the transaction's unlock_time: "+(a.locked||0)+" XMR is on your address but cannot be spent until "+V+". Ready stays closed until then - confirming now would let the maker take the ETH behind locked XMR."}else if(!a.received)b="maker_locking",S="Waiting for XMR to arrive",H=a.error?"Backend unavailable: "+a.error:"The backend watches your swap address with the view key only - it cannot spend your XMR.";else if(a.status===bn.READY){b="xmr_locked",S="XMR received and confirmed ("+u+"/"+r.confTarget+")";let L=Bh(e,a);p.ready=L.ok,p.readyAmount=L,H=L.ok?"Confirm that you see the XMR on your address (ready).":L.why}else a.status===bn.SWEPT?(b="success",S="XMR delivered"):(b="xmr_locked",S="XMR received, waiting for confirmations ("+u+"/"+r.confTarget+")",H="About "+Math.max(1,Math.round((r.confTarget-u)*r.blockSim/6e4))+" min left of confirmations.");else if(l===null)n>=r.t0Sim?(b="refund_available",S="Maker did not lock XMR",v=r.t0Sim,p.refund=!0,H="The maker never locked XMR. You can take your ETH back from the escrow - no permission needed."):(b="maker_locking",S="Waiting for the maker to lock XMR",H="If the maker does not lock XMR by T0, you get a refund button.");else if(!f)b="maker_locking",S="Maker is locking XMR";else if(B)b="xmr_reclaimed",S="XMR returned to the maker",v=P,p.refund=!0,H="You did not confirm (ready) in time, so the maker took the XMR back. Your ETH is still in escrow - refund it.";else if(h===null)b="xmr_locked",S=u<r.confTarget?`Waiting for Monero confirmations (${u}/${r.confTarget})`:"XMR locked and verified - waiting for you",p.ready=s?a.status===bn.READY:u>=r.confTarget,v=g,H=u<r.confTarget?`About ${Math.max(1,Math.round((r.confTarget-u)*r.blockSim/6e4))} min left of confirmations. You can close this tab.`:"Confirm that you see the lock with your view key (ready). Until you do, the maker keeps the XMR.";else if(k!==null&&n<k)b="ready_wait_claim",S="Waiting for the maker to claim ETH",H="The maker claims the escrow and reveals the secret; your swap wallet uses it to sweep the XMR.";else if(k!==null&&n>=k&&I!==null&&n>=I)b="success",S="XMR delivered",p.sweep=!0;else if(k!==null)b="claimed",S="Secret revealed - sweeping XMR",p.sweep=!0;else{b="refund_available",S="Maker did not claim in time",v=E;let L=e.escrow&&e.escrow.t0?e.escrow.t0*1e3:null,V=e.escrow&&e.escrow.t1?e.escrow.t1*1e3:null,U=ht();V!==null?L!==null?(p.refund=U>=L,p.refundByAnyone=U>=V):(p.refund=U>=V,p.refundByAnyone=p.refund):Ah(e)?p.refund=!1:p.refund=n>=E,H=p.refund?p.refundByAnyone?"The claim deadline passed: the refund is open to anyone who can present the half of the depositor - that half is YOURS (it is in your recovery file), and the watchtower does not have it. Press Refund my ETH, or restore the file if you have lost this tab.":"The maker missed the claim deadline. You can take your ETH back from the escrow yourself.":L!==null?"This order predates the one-deadline rule: you could refund from T0, and from T1 anyone can.":"Waiting for T1: before it the ETH can only be claimed with the secret. From T1 the claim closes and the refund opens - and it always pays you, never the caller."}let A=u>=r.confTarget,O=k!==null&&n>=k,D=[{key:"funded",done:!0,atSim:0},{key:"maker_locking",done:f,active:!f&&!e.settlement&&l!==null,failed:l===null&&n>=r.t0Sim,atSim:l},{key:"xmr_locked",done:A&&!B,active:f&&!A,atSim:l},{key:"ready",done:h!==null,active:A&&h===null&&!B,atSim:h},{key:"claimed",done:O,active:h!==null&&!O,atSim:k},{key:"swept",done:!!e.settlement&&e.settlement.kind==="success",active:O&&!e.settlement,atSim:Qk(e)}];return{swap:e,sim:n,simWallTime:Zn(e,n),phase:b,phaseLabel:S,note:H,conf:u,confTarget:r.confTarget,confProgress:r.confTarget?u/r.confTarget:0,deadlines:{t0:e.escrow&&e.escrow.t0?e.escrow.t0*1e3:e.escrow?null:Zn(e,r.t0Sim),t0Sim:r.t0Sim,lockAtSim:l,readyBy:g!==null?Zn(e,g):null,readyBySim:g,t1:e.escrow&&e.escrow.t1?e.escrow.t1*1e3:E!==null?Zn(e,E):null,t1Sim:E,refundAfterSim:v,refundAfterWall:v!==null?Zn(e,v):null},refundLeftSim:v!==null?v-n:null,xmr:{live:a.live,source:e.xmrSource,status:a.status,received:a.received,locked:a.locked||0,lockedUntil:a.lockedUntil||null,arrived:Number(a.arrived!==void 0&&a.arrived!==null?a.arrived:a.received||0),confirmations:a.confirmations,confTarget:a.confTarget,txids:a.txids,address:a.address,explorer:vh(a.txids[0],e.xmrSession&&e.xmrSession.network||"stagenet"),error:a.error,sweepTxid:a.sweepTxid},simulated:{evm:!Ah(e),xmr:!a.live},can:p,readyDeadline:{atMs:m,soonMs:m!==null&&h===null?m-ht():null,soon:m!==null&&h===null&&m-ht()>0&&m-ht()<=Number(Io.readyLeadWarnSec||0)*1e3},xmrAmount:{expected:(()=>{let L=Number(e.xmrAmount);return Number.isFinite(L)&&L>0?L:null})(),seen:a.received!==null&&a.received!==void 0?Number(a.received):null},steps:D,sellWindow:y,terminal:e.settlement,xmrReclaimed:B}}function Qk(e){return e.settlement&&e.settlement.kind==="success"?e.settlement.atSim:null}var Il=null,Nl=new Set,Lt=new Set;function Zk(e){return Nl.add(e),()=>Nl.delete(e)}function Jk(){for(let e of Nl)try{e()}catch(t){console.error(t)}}function e1(e){let t=new Set([String(e&&e.id||"")].filter(Boolean)),r=(()=>{try{return Ns(e)||{}}catch{return{}}})().address||e&&e.escrow&&e.escrow.moneroAddress||null;if(!r)return[...t];for(let o of Object.values((et()||{}).swaps||{})){if(!o||!o.id)continue;(()=>{try{return Ns(o)||{}}catch{return{}}})().address===r&&t.add(String(o.id))}return[...t]}async function t1(){return null}function n1(e){return new Set(Array.isArray(e)?e.map(String):[]).size}function Oh(){let e=et(),t=!1;for(let n of Object.values(e.swaps)){if(n.settlement)continue;let r=Go(n);if(!gn(n.xmrSource)&&!n.xmr&&r.deadlines.lockAtSim!==null&&r.sim>=r.deadlines.lockAtSim){let o=xh({swapId:n.id,xmrAmount:n.xmrAmount});if(n.xmr={...o,reclaimed:!1,sweepTxid:null},n.chainMode==="live"){let s=Is();n.xmr.lockHeight=s?s.height:null,n.xmr.lockHeight||yh({force:!0}).then(a=>{if(a&&!n.settlement){let c=et();c.swaps[n.id]&&(c.swaps[n.id].xmr.lockHeight=a.height,Ht(c))}})}Gt(n,r.sim,"Maker locked XMR on the shared address",o.txid);let i=n.id+":lock";Lt.has(i)||(Lt.add(i),Yo(n.xmrAmount.toFixed(4)+" XMR locked; view key verified","ok")),t=!0}if(gn(n.xmrSource)&&!n.xmr&&r.xmr&&r.xmr.received>0){n.xmr={mock:!1,txid:r.xmr.txids[0]||null,address:r.xmr.address,amount:r.xmr.received,confirmations:r.xmr.confirmations,status:r.xmr.status,explorer:r.xmr.explorer,reclaimed:!1,sweepTxid:null},Gt(n,r.sim,"XMR received (backend, "+(n.xmrSession&&n.xmrSession.network||"stagenet")+")",n.xmr.txid||"");let o=n.id+":xmr-in";Lt.has(o)||(Lt.add(o),Yo(r.xmr.received.toFixed(6)+" XMR received; confirmations "+r.xmr.confirmations+"/"+r.xmr.confTarget,"ok")),t=!0}if(!gn(n.xmrSource)&&r.can.sweep&&r.phase==="success"){let o=r.sim;n.xmr.sweepTxid=Al({swapId:n.id}).txid,n.settlement={kind:"success",phase:Rr.success.phase,atSim:o,txid:n.xmr.sweepTxid,by:"your swap wallet"},Gt(n,o,"XMR swept to your address",n.xmr.sweepTxid);let i=n.id+":success";Lt.has(i)||(Lt.add(i),Yo("Swap "+n.id+" complete: XMR is on your address","ok")),t=!0;continue}if(!gn(n.xmrSource)&&r.can.refund&&r.refundLeftSim!==null&&r.refundLeftSim<=-St.watchtowerGrace){let o=r.sim,i=_l({swapId:n.id,by:"watchtower"});n.settlement={kind:"refund_eth",phase:Rr.refunded_eth.phase,atSim:o,txHash:i.txHash,by:"watchtower"},Gt(n,o,"Watchtower refunded your ETH",i.txHash);let s=n.id+":refund";Lt.has(s)||(Lt.add(s),Yo("Watchtower refunded the ETH escrow of swap "+n.id,"bad")),t=!0;continue}if(!gn(n.xmrSource)&&n.xmr&&r.xmrReclaimed&&!n.xmr.reclaimed){n.xmr.reclaimed=!0,Gt(n,r.sim,"Maker reclaimed the XMR",n.xmr.txid);let o=n.id+":reclaim";Lt.has(o)||(Lt.add(o),Yo("Maker took the XMR back: no ready() call in time","bad")),t=!0}}t&&Ht(e)}var Tl={fn:null};function r1(e){Tl.fn=e}function Yo(e,t){Tl.fn&&Tl.fn(e,t)}function o1(e=400){Il&&clearInterval(Il),Il=setInterval(()=>{try{Oh()}catch(t){console.error(t)}Jk()},e)}Vo();var xn={};Be(xn,{ORDER_CONTEXT_VERSION:()=>Rh,orderContextString:()=>a1});var Rh="ninsei-order-v3",i1=e=>String(e??"").trim().toLowerCase(),s1=e=>{if(typeof e=="bigint")return e.toString(10);if(typeof e=="number")return String(Math.trunc(e));let t=i1(e);return t.startsWith("0x")?BigInt(t).toString(10):t},Ch=["chainId","factory","locker","claimer","amount","readyBy","t1","salt"];function a1(e){if(!e||typeof e!="object")throw new Error("order context needs an object with the order fields");let t=Ch.filter(n=>e[n]===void 0||e[n]===null||e[n]==="");if(t.length)throw new Error("order context is missing fields: "+t.join(", "));return Rh+"|"+Ch.map(n=>s1(e[n])).join("|")}var Os={};Be(Os,{createOrderBuilder:()=>f1});Vo();function Hr(e,t,n){if(!t||!n)throw new Error("secp256k1 and keccak256 are required");let r=BigInt(e);if(r<=0n)throw new Error("the half must be a positive number");let i=t.Point.BASE.multiply(r).toBytes(!1).slice(1);return"0x"+Array.from(n(i),s=>s.toString(16).padStart(2,"0")).join("")}function Hh({ed25519:e,secp256k1:t,keccak256:n,sha3_512:r,randomBytes:o}){if(typeof r!="function")throw new Error("createDleq2: sha3_512 is required (SHA3-512 from @noble/hashes)");let i=e.Point.Fn.ORDER,s=t.Point.Fn.ORDER,a=Math.min(i.toString(2).length,s.toString(2).length),c={A:{name:"secp256k1",P:t.Point,order:s,G:t.Point.BASE,Galt:t.Point.fromHex("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0")},B:{name:"ed25519",P:e.Point,order:i,G:e.Point.BASE,Galt:e.Point.fromHex("8b655970153799af2aeadc9ff1add0ea6c7251d54154cfa92c173a0dd39c1f94")}};c.A.Galt.precompute(8),c.B.Galt.precompute(8);let l=T=>{let K=String(T??""),M=[];for(let ee=0;ee<K.length;ee++){let C=K.codePointAt(ee);C>65535&&ee++,C<128?M.push(C):C<2048?M.push(192|C>>6,128|C&63):C<65536?M.push(224|C>>12,128|C>>6&63,128|C&63):M.push(240|C>>18,128|C>>12&63,128|C>>6&63,128|C&63)}return new Uint8Array(M)},u=T=>typeof T=="string"?T:T.toHex?T.toHex():String(T);function f(T){let K=T.replace(/^0x/i,""),M=new Uint8Array(K.length/2);for(let ee=0;ee<M.length;ee++)M[ee]=parseInt(K.substr(ee*2,2),16);return M}let h=T=>T.toString(16).padStart(64,"0");function m(T){let K=0n;for(let M of T)K=K<<8n|BigInt(M);return K}function w(T){let K=0n;for(let M=T.length-1;M>=0;M--)K=K<<8n|BigInt(T[M]);return K}function x(T){let K=T.reduce((C,q)=>C+q.length,0),M=new Uint8Array(K),ee=0;for(let C of T)M.set(C,ee),ee+=C.length;return M}function y(T,K){let M=r(x(K.map(ee=>typeof ee=="string"?f(ee):ee)));if(M.length!==64)throw new Error("challenge: sha3_512 returned "+M.length+" bytes instead of 64");return w(M)%T.order}function k(T){let K=w(o(64))%T.order;return K===0n?1n:K}function I(T,K){return T>>BigInt(K)&1n}function g(T,K,M){let C=((typeof M=="bigint"?M:BigInt(M))%T.order+T.order)%T.order;return C===0n?T.P.ZERO:K===T.Galt?K.multiply(C):K.multiplyUnsafe(C)}function P(T,K,M){return g(T,M||T.G,typeof K=="bigint"?K:BigInt(K))}let E=(T,K)=>T.add(K),B=(T,K)=>T.subtract(K),p=T=>f(T.toHex()),b=T=>f(h(T));function S(T){let K=T.next();for(;!K.done;)K=T.next();return K.value}let v=async T=>typeof T=="function"?await T():globalThis.scheduler&&typeof globalThis.scheduler.yield=="function"?await globalThis.scheduler.yield():await new Promise(K=>setTimeout(K,0));function*H(T,K){let M=[],ee=[],C=0n,q=1n;for(let J=0;J<a;J++){if(J===a-1){let re=O(q,T.order);M[J]=(T.order-C%T.order)*re%T.order}else M[J]=k(T),C=(C+M[J]*q)%T.order,q=q*2n%T.order;let le=I(K,J);ee.push(E(P(T,le),P(T,M[J],T.Galt))),yield J+1}return{rs:M,cs:ee}}function A(T,K){return S(H(T,K))}function O(T,K){let[M,ee]=[T%K,K],[C,q]=[1n,0n];for(;ee!==0n;){let J=M/ee;[M,ee]=[ee,M-J*ee],[C,q]=[q,C-J*q]}if(M!==1n)throw new Error("modInv: not invertible");return(C%K+K)%K}function*D(T,K){let M=K[0];for(let ee=1;ee<K.length;ee++)M=E(M,P(T,2n**BigInt(ee)%T.order,K[ee])),yield{phase:"sum",done:ee,total:K.length};return M}function L(T,K){return S(D(T,K))}function V(T,K,M,ee,C,q,J){let le=k(c.A),re=k(c.B),ae=(Mt,Bt)=>[l(J),p(M),p(ee),p(Mt),p(Bt)],Ge=y(c.A,ae(P(c.A,le,c.A.Galt),P(c.B,re,c.B.Galt)),J),ie=y(c.B,ae(P(c.A,le,c.A.Galt),P(c.B,re,c.B.Galt)),J);if((T===1n||T===1?1n:0n)===0n){let Mt=k(c.A),Bt=k(c.B),So=B(M,c.A.G),vo=B(ee,c.B.G),Eo=y(c.A,ae(B(P(c.A,Mt,c.A.Galt),g(c.A,So,Ge)),B(P(c.B,Bt,c.B.Galt),g(c.B,vo,ie))),J),Ao=y(c.B,ae(B(P(c.A,Mt,c.A.Galt),g(c.A,So,Ge)),B(P(c.B,Bt,c.B.Galt),g(c.B,vo,ie))),J);return{eA:Eo,eB:Ao,a0:Mt,a1:(le+Eo*C)%c.A.order,b0:Bt,b1:(re+Ao*q)%c.B.order}}let je=k(c.A),xo=k(c.B),kt=y(c.A,ae(B(P(c.A,je,c.A.Galt),g(c.A,M,Ge)),B(P(c.B,xo,c.B.Galt),g(c.B,ee,ie))),J),ko=y(c.B,ae(B(P(c.A,je,c.A.Galt),g(c.A,M,Ge)),B(P(c.B,xo,c.B.Galt),g(c.B,ee,ie))),J);return{eA:Ge,eB:ie,a0:(le+kt*C)%c.A.order,a1:je,b0:(re+ko*q)%c.B.order,b1:xo}}let U=T=>({eA:h(T.eA),eB:h(T.eB),a0:h(T.a0),a1:h(T.a1),b0:h(T.b0),b1:h(T.b1)});function j(T,K,M,ee,C){let q=k(T),J=P(T,q),le=y(T,[l(ee),l("ninsei-dleq-pok|"+C),p(M),p(J)]);return{R:u(J),s:h((q+le*K)%T.order)}}function F(T,K,M,ee,C){if(!M||typeof M!="object"||typeof M.R!="string"||typeof M.s!="string")return!1;let q,J;try{q=T.P.fromHex(M.R.replace(/^0x/i,"")),J=BigInt(String(M.s).startsWith("0X")?"0x"+String(M.s).slice(2):String(M.s).startsWith("0x")?M.s:"0x"+M.s)}catch{return!1}let le=y(T,[l(ee),l("ninsei-dleq-pok|"+C),p(K),p(q)]);return P(T,J).equals(E(q,g(T,K,le)))}function*R(T,K){T=typeof T=="bigint"?T:BigInt(T);let M=P(c.A,T),ee=P(c.B,T);yield{phase:"prepare",done:0,total:a};let C=H(c.A,T),q=H(c.B,T);for(let ae=0;ae<a;ae++){let Ge=C.next(),ie=q.next();if(Ge.done||ie.done)throw new Error("prepareProof: commitments ended early");yield{phase:"prepare",done:ae+1,total:a}}let J=C.next().value,le=q.next().value,re=[];for(let ae=0;ae<a;ae++)re.push({i:ae,bit:I(T,ae)===1n?1:0,cA:u(J.cs[ae]),cB:u(le.cs[ae]),rA:h(J.rs[ae]),rB:h(le.rs[ae])});return yield{phase:"know",done:a,total:a},{XA:u(M),XB:u(ee),context:String(K??""),pokA:j(c.A,T,M,K,"A"),pokB:j(c.B,T,ee,K,"B"),bits:re}}function _(T,K){return S(R(T,K))}async function N(T,K,M={}){let ee=Number.isSafeInteger(M.chunkBits)&&M.chunkBits>0?Math.min(M.chunkBits,a):8,C=R(T,K),q=0;for(;;){let J=C.next();if(J.done)return J.value;q+=1,typeof M.onPrepare=="function"&&M.onPrepare(J.value),q%ee===0&&await v(M.yieldTo)}}function W(T,K){let M=V(T.bit===1?1n:0n,T.i,c.A.P.fromHex(String(T.cA).replace(/^0x/,"")),c.B.P.fromHex(String(T.cB).replace(/^0x/,"")),BigInt("0x"+String(T.rA).replace(/^0x/,"")),BigInt("0x"+String(T.rB).replace(/^0x/,"")),K);return{i:T.i,cA:T.cA,cB:T.cB,sig:U(M)}}function $(T,K){let M=new Map(K.map(C=>[C.i,C])),ee=[];for(let C=0;C<a;C++){let q=M.get(C);if(!q)throw new Error("assembleProof: no part for bit "+C);ee.push({cA:q.cA,cB:q.cB,sig:q.sig})}return{XA:T.XA,XB:T.XB,pokA:T.pokA,pokB:T.pokB,proofs:ee}}function X(T,K,M){let ee=_(T,K),C=[];for(let q=0;q<a;q++)M&&(q%16===0||q===a-1)&&M(q+1,a),C.push(W(ee.bits[q],ee.context));return $(ee,C)}async function Y(T,K,M={}){let ee=Number.isSafeInteger(M.chunkBits)&&M.chunkBits>0?Math.min(M.chunkBits,a):4,C=await N(T,K,{chunkBits:Number.isSafeInteger(M.prepareChunkBits)&&M.prepareChunkBits>0?M.prepareChunkBits:8,yieldTo:M.yieldTo,onPrepare:M.onPrepare}),q=[];for(let J=0;J<a;J++)q.push(W(C.bits[J],C.context)),((J+1)%ee===0||J===a-1)&&(typeof M.onBit=="function"&&M.onBit(J+1,a),await v(M.yieldTo));return $(C,q)}function G(T,K){if(T.name!=="ed25519")return!0;try{return K.isTorsionFree()===!0}catch{return!1}}function*Z(T,K,M={}){if(!T||typeof T!="object")return{ok:!1,reason:"proof: an object is expected"};if(typeof T.XA!="string"||typeof T.XB!="string")return{ok:!1,reason:"proof: no XA or XB"};if(!Array.isArray(T.proofs))return{ok:!1,reason:"proof: no parts list"};if(T.proofs.length!==a)return{ok:!1,reason:"proof: "+T.proofs.length+" parts, expected "+a};let ee=M.requireKnowledge!==!1,C=(ie,Pt)=>ie.P.fromHex(String(Pt).replace(/^0x/i,"")),q,J,le,re;try{if(q=C(c.A,T.XA),J=C(c.B,T.XB),J.equals(c.B.P.ZERO))return{ok:!1,reason:"proof: the subject point is the identity"};if(!G(c.B,J))return{ok:!1,reason:"proof: XB is not in the prime-order subgroup"}}catch(ie){return{ok:!1,reason:"proof: XA or XB is unparsable ("+String(ie&&ie.message||ie)+")"}}if(ee)try{if(!F(c.A,q,T.pokA,K,"A"))return{ok:!1,reason:"proof: the secp256k1 knowledge proof did not verify"};if(!F(c.B,J,T.pokB,K,"B"))return{ok:!1,reason:"proof: the ed25519 knowledge proof did not verify"}}catch(ie){return{ok:!1,reason:"proof: the knowledge proof is unparsable ("+String(ie&&ie.message||ie)+")"}}try{le=T.proofs.map((ie,Pt)=>{try{return C(c.A,ie.cA)}catch(je){throw new Error("bit "+Pt+": "+String(je&&je.message||je))}}),re=T.proofs.map((ie,Pt)=>{try{return C(c.B,ie.cB)}catch(je){throw new Error("bit "+Pt+": "+String(je&&je.message||je))}})}catch(ie){return{ok:!1,reason:"proof: "+String(ie&&ie.message||ie)}}if(!(yield*D(c.A,le)).equals(q))return{ok:!1,reason:"the commitment sum does not give X on secp256k1"};if(!(yield*D(c.B,re)).equals(J))return{ok:!1,reason:"the commitment sum does not give X on ed25519"};for(let ie=0;ie<T.proofs.length;ie++){let Pt=T.proofs[ie];try{if(!G(c.B,re[ie]))return{ok:!1,reason:"bit "+ie+": the commitment is not in the prime-order subgroup"};let je=Pt.cA,xo=Pt.cB,kt={};for(let Ri of["eA","eB","a0","a1","b0","b1"]){let tc=Pt.sig[Ri],nc=String(tc);kt[Ri]=BigInt(/^0x/i.test(nc)?nc:"0x"+nc)}let ko=C(c.A,je),Mt=C(c.B,xo),Bt=(Ri,tc)=>[l(K),p(ko),p(Mt),p(Ri),p(tc)],So=P(c.A,kt.a1,c.A.Galt),vo=g(c.A,ko,kt.eA),Eo=P(c.B,kt.b1,c.B.Galt),Ao=g(c.B,Mt,kt.eB),Jb=y(c.A,Bt(B(So,vo),B(Eo,Ao)),K),eg=y(c.B,Bt(B(So,vo),B(Eo,Ao)),K),zd=P(c.A,kt.a0,c.A.Galt),Xd=g(c.A,B(ko,c.A.G),Jb),Yd=P(c.B,kt.b0,c.B.Galt),Gd=g(c.B,B(Mt,c.B.G),eg),tg=y(c.A,Bt(B(zd,Xd),B(Yd,Gd)),K),ng=y(c.B,Bt(B(zd,Xd),B(Yd,Gd)),K);if(tg!==kt.eA||ng!==kt.eB)return{ok:!1,reason:"bit "+ie+": challenges did not match"}}catch(je){return{ok:!1,reason:"bit "+ie+": fields are unparsable ("+String(je&&je.message||je)+")"}}yield{phase:"verify",done:ie+1,total:T.proofs.length}}return{ok:!0}}function ne(T,K,M={}){return S(Z(T,K,M))}async function oe(T,K,M={}){let ee=Z(T,K,M),C=null,q=0;for(;;){let J=ee.next();if(J.done)return J.value;let le=J.value&&J.value.phase?J.value.phase:null;le!==C&&(C=le,q=0),q+=1,typeof M.onProgress=="function"&&M.onProgress(J.value);let re=C==="sum"?16:Number.isSafeInteger(M.verifyChunkBits)&&M.verifyChunkBits>0?Math.min(M.verifyChunkBits,a):2;q%re===0&&await v(M.yieldTo)}}return{BITS:a,curves:c,prove:X,proveChunked:Y,verify:ne,verifyChunked:oe,prepareProof:_,prepareProofChunked:N,proveBit:W,assembleProof:$,torsionFree:G}}var Lh="halfenc is locked: the sealed-half envelope is not part of the live flow (keccak commit/reveal replaced it). Set globalThis.ARRAKIS_ALLOW_HALFENC = true to work with it in a test or a spike.";function Fh(){return globalThis.ARRAKIS_ALLOW_HALFENC===!0}function Dh({secp256k1:e,ed25519:t,keccak256:n,randomBytes:r}){let o=t.Point.Fn.ORDER,i=e.Point.Fn.ORDER,s=o<i?o:i;function a(x){let y=0n;for(let k of x)y=y<<8n|BigInt(k);return y}function c(x){for(let y=0;y<256;y++){let k=a(r(32));if(k>0n&&k<x)return k}throw new Error("randScalar: failed in 256 attempts")}let l=x=>x.toString(16).padStart(64,"0");function u(){let x=c(i);return{priv:x,pub:e.Point.BASE.multiply(x).toHex()}}function f(x,y){let k=n(Uint8Array.from(Buffer.concat([Buffer.from(x.replace(/^0x/,""),"hex"),Buffer.from(y||"","utf8")])));return a(k)%s}function h(x,y,k){if(!Fh())throw new Error(Lh);if(!(x>0n&&x<s))throw new Error("seal: half outside min(l, n)");let I=e.Point.fromHex(y.replace(/^0x/,"")),g=c(i),P=e.Point.BASE.multiply(g),E=I.multiply(g),B=f(E.toHex(),k),p=b=>"0x"+String(b).replace(/^0x/i,"").toLowerCase();return{recipient:p(y),ephemeral:p(P.toHex()),masked:"0x"+l((x+B)%s),context:k||""}}function m(x,y,k){if(!Fh())return{ok:!1,reason:Lh};if(!x||!x.ephemeral||!x.masked)return{ok:!1,reason:"incomplete envelope"};let g=e.Point.fromHex(x.ephemeral.replace(/^0x/,"")).multiply(y),P=f(g.toHex(),x.context),E=(BigInt(x.masked)-P+s)%s;if(E===0n)return{ok:!1,reason:"restored zero"};if(!k)return{ok:!0,x:E};let B=t.Point.BASE.multiply(E).toHex(),p=t.Point.fromHex(k.startsWith("0x")?k.slice(2):k).toHex();return B!==p?{ok:!1,reason:"the ciphertext holds a different half"}:{ok:!0,x:E}}function w(x){let y=n(Bs(x));return"0x"+kn(y)}return{LIMIT:s,recipientKeyPair:u,seal:h,open:m,packSealed:Pl,unpackSealed:u1,sealedCommitmentOf:w}}var Uh=1;function kn(e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}function c1(e){let t=String(e??""),n=[];for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);o<128?n.push(o):o<2048?n.push(192|o>>6,128|o&63):n.push(224|o>>12,128|o>>6&63,128|o&63)}return new Uint8Array(n)}function l1(e){let t="";for(let n=0;n<e.length;n++){let r=e[n];r<128?t+=String.fromCharCode(r):r<224?t+=String.fromCharCode((r&31)<<6|e[++n]&63):t+=String.fromCharCode((r&15)<<12|(e[++n]&63)<<6|e[++n]&63)}return t}var Bs=e=>{let t=String(e||"").replace(/^0x/i,""),n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++)n[r]=parseInt(t.substr(r*2,2),16);return n};function Pl(e){if(!e||!e.recipient||!e.ephemeral||!e.masked)throw new Error("packSealed: incomplete envelope");let t=Bs(e.recipient),n=Bs(e.ephemeral);if(t.length!==33)throw new Error("packSealed: recipient key must be 33 bytes (compressed point)");if(n.length!==33)throw new Error("packSealed: ephemeral point must be 33 bytes (compressed)");let r=BigInt(e.masked).toString(16).padStart(64,"0"),o=c1(e.context);if(o.length>255)throw new Error("packSealed: context longer than 255 bytes");return"0x"+kn(Uint8Array.of(Uh))+kn(t)+kn(n)+r+o.length.toString(16).padStart(2,"0")+kn(o)}function u1(e){let t=Bs(e);if(t.length<100)throw new Error("unpackSealed: envelope shorter than 100 bytes");if(t[0]!==Uh)throw new Error("unpackSealed: unknown format version: "+t[0]);let n=t[99];if(t.length!==100+n)throw new Error("unpackSealed: length does not match the one in the context");return{recipient:"0x"+kn(t.slice(1,34)),ephemeral:"0x"+kn(t.slice(34,67)),masked:"0x"+kn(t.slice(67,99)),context:l1(t.slice(100))}}Vn();function f1({ed25519:e,secp256k1:t,keccak256:n,sha3_512:r,randomBytes:o}){let i=Wo({ed25519:e,secp256k1:t,keccak256:n,randomBytes:o}),s=Hh({ed25519:e,secp256k1:t,keccak256:n,sha3_512:r,randomBytes:o}),a=Dh({secp256k1:t,ed25519:e,keccak256:n,randomBytes:o});function c(g,P=!1,E){let B=i.newHalf(),p=i.publicHalves(B),b=i.newHalf(),S=i.publicHalves(b).ed,v=a.recipientKeyPair(),H=s.prove(B,g,E);return{half:B,pub:p,viewHalf:b,viewPub:S,enc:v,proof:H,standIn:P}}async function l(g,P=!1,E={}){let B=i.newHalf(),p=i.publicHalves(B),b=i.newHalf(),S=i.publicHalves(b).ed,v=a.recipientKeyPair(),H=await s.proveChunked(B,g,E);return{half:B,pub:p,viewHalf:b,viewPub:S,enc:v,proof:H,standIn:P}}function u(g,P,E,B,p){if(!p.ok)return{ok:!1,reason:"counterparty DLEQ failed: "+p.reason};if(g.pub&&g.pub.ed&&String(g.proof.XB).toLowerCase()!==String(g.pub.ed).toLowerCase())return{ok:!1,reason:"the proven ed25519 point does not match the declared one: "+g.proof.XB+" vs "+g.pub.ed};if(g.commitHalfClaimer){let b=null;try{let H=t.Point.fromHex(String(g.proof.XA).replace(/^0x/,"")).toBytes(!1).slice(1);b="0x"+Array.from(n(H),A=>A.toString(16).padStart(2,"0")).join("")}catch{b=null}let S=v=>String(v||"").replace(/^0x/,"").toLowerCase().slice(-40);if(!b||S(b)!==S(g.commitHalfClaimer))return{ok:!1,reason:"the proven secp256k1 point does not match commitHalfClaimer: "+(b||"unparsed")+" vs "+g.commitHalfClaimer}}else return{ok:!1,reason:"the counterparty side carries no commitHalfClaimer"};if(E&&B){let b=a.open(a.unpackSealed(E),B,g.pub.ed);if(!b.ok)return{ok:!1,reason:"the counterparty envelope does not confirm the half: "+b.reason}}return{ok:!0}}function f(g,P,E,B){return u(g,P,E,B,s.verify(g.proof,P))}async function h(g,P,E,B,p={}){let b=await s.verifyChunked(g.proof,P,p);return u(g,P,E,B,b)}function m(g,P,E){let B=a.seal(P,g.enc.pub,E),p=Pl(B);return{sealed:B,bytes:p,commitment:a.sealedCommitmentOf(p)}}function w(g,P,E){return a.open(a.unpackSealed(g),P,E)}function x(g){return Hr(g,t,n)}function y(g,P){return i.combinePublic(g.pub.ed,P.pub.ed)}function k(g){return i.publicHalves(typeof g=="bigint"?g:BigInt(g)).ed}function I({ownSpendHalf:g,ownViewHalf:P,otherSpendPoint:E,otherViewPoint:B,network:p}){return Ss({halves:i,addressFromKeys:hn,deps:{keccak256:n},ownSpendHalf:g,ownViewHalf:P,otherSpendPoint:E,otherViewPoint:B,network:p})}return{halves:i,dleq:s,enc:a,newSide:c,newSideChunked:l,verifySide:f,verifySideChunked:h,sealFor:m,openFrom:w,jointAddressPoint:y,pointOf:k,jointAddress:I,halfCommitment:x}}var Ue={};Be(Ue,{ASYNC_DEFAULT_NEED:()=>Fl,ASYNC_NEEDS:()=>lm,ASYNC_SETTLES:()=>qo,EIP2612_METHOD:()=>Zo,ERC20_METHOD:()=>ym,ESCROW_METHODS:()=>qt,FACTORY_METHODS:()=>Ol,FACTORY_READS:()=>Cs,GAS_CREATE_ORDER_AND_FUND:()=>am,ORDER_CREATED_TOPIC:()=>Rs,ORDER_CREATED_TOPICS:()=>p1,ORDER_CREATED_TOPIC_V1:()=>Mh,QUOTE_FIELDS:()=>Bl,address:()=>bl,asyncRouteChains:()=>fm,asyncRouteChoice:()=>hm,asyncRouteForChain:()=>N1,asyncRouteInjection:()=>_1,asyncRouteProvider:()=>Qo,asyncRouteProviderIds:()=>Ul,asyncRouteProviderSettles:()=>pm,asyncRouteProvidersForChain:()=>Us,asyncRouteVerdict:()=>Ml,balanceOf:()=>ch,chainIdOf:()=>sh,connect:()=>fh,connectInjected:()=>xl,currentProvider:()=>ah,decodeAddress:()=>Hs,decodeBytes32:()=>Jh,decodeImplementation:()=>Wh,decodeImplementationCodeHash:()=>Vh,decodeStatus:()=>Fs,decodeUint64:()=>em,disconnect:()=>ph,encodeApprove:()=>C1,encodeClaim:()=>Xh,encodeCreateOrderAndFund:()=>Rl,encodeDomainSeparator:()=>O1,encodeFactoryRead:()=>b1,encodeMarkReady:()=>zh,encodeNonces:()=>B1,encodePermit:()=>P1,encodePredict:()=>Cl,encodeRead:()=>Zh,encodeRefund:()=>Gh,encodeStatus:()=>Ls,encodeT1:()=>qh,encodeTermsHash:()=>Qh,escrowFromReceipt:()=>cm,escrowNativeWei:()=>v1,fundOrder:()=>Ll,fundOrderLive:()=>D1,fundingReceiptVerdict:()=>Ds,isConnected:()=>Qn,newSecret:()=>om,orderTerms:()=>tm,permitSupportVerdict:()=>R1,readCode:()=>hh,readContract:()=>Sl,readReceipt:()=>vl,refreshBalances:()=>qn,restore:()=>dh,restoreInjected:()=>gl,sendTransaction:()=>El,setAsyncRouteInjection:()=>A1,simulateEscrowFunding:()=>F1,status:()=>ih,subscribe:()=>oh,switchChain:()=>kl,testOrderTerms:()=>im,toWei:()=>sm,usdcWithoutEthVerdict:()=>H1,verifyFactoryImplementation:()=>$h,verifyFactoryImplementationOnChain:()=>g1,wallets:()=>L1,word:()=>ye});var Ol={predict:"0x76e3fdc8",createOrderAndFund:"0x50db6721"},Rs="0x09add13cca47b227c377447295bfaa00ef3169bfed0f5513d06f8be04af78aad",Mh="0xa22cdabaed3cce4f51dde71626a108ffe9c7bc4216fd14d5e719f892e2fd8ab0",p1=Object.freeze([Rs,Mh]),Bl=["provider","quoteKey","registry","cashier","locker","claimer","amount","readyBy","t1","salt","commitHalfClaimer","edPointClaimer","chainId","feeBps","fee","feeRecipient","validUntil","nonce","xmrAmount","claimTip","commitHalfLocker","edPointLocker","edViewPointLocker"],h1=["provider","quoteKey","registry","cashier","locker","claimer","feeRecipient"],m1=["salt","commitHalfClaimer","edPointClaimer","commitHalfLocker","edPointLocker","edViewPointLocker"];function ye(e,t=32){let n=String(e).trim(),r;if(/^0x[0-9a-fA-F]*$/.test(n))r=n.slice(2).toLowerCase(),r.length===0&&(r="0");else if(/^[0-9]+$/.test(n))r=BigInt(n).toString(16);else throw new Error("not a number and not hex: "+e);if(!/^[0-9a-f]*$/.test(r))throw new Error("not hex: "+e);if(r.length>t*2)throw new Error(`value does not fit in ${t} bytes: ${e}`);return r.padStart(t*2,"0")}var Lr=e=>{let t=String(e??"").trim();return/^[0-9a-fA-F]{64}$/.test(t)?"0x"+t.toLowerCase():t};function w1(e){for(let n of Bl)if(e[n]===void 0||e[n]===null||e[n]==="")throw new Error("the quote has no field: "+n);for(let n of h1)if(!/^(0x)?[0-9a-fA-F]{40}$/.test(String(e[n]).trim()))throw new Error("quote field "+n+" is not an address");for(let n of m1)if(!/^(0x)?[0-9a-fA-F]{64}$/.test(String(e[n]).trim()))throw new Error("quote field "+n+" is not bytes32");let t={provider:ye(e.provider,32),quoteKey:ye(e.quoteKey,32),registry:ye(e.registry,32),cashier:ye(e.cashier,32),locker:ye(e.locker,32),claimer:ye(e.claimer,32),amount:ye(e.amount,32),readyBy:ye(e.readyBy,32),t1:ye(e.t1,32),salt:ye(Lr(e.salt),32),commitHalfClaimer:ye(Lr(e.commitHalfClaimer),32),edPointClaimer:ye(Lr(e.edPointClaimer),32),chainId:ye(e.chainId,32),feeBps:ye(e.feeBps,32),fee:ye(e.fee,32),feeRecipient:ye(e.feeRecipient,32),validUntil:ye(e.validUntil,32),nonce:ye(e.nonce,32),xmrAmount:ye(e.xmrAmount,32),claimTip:ye(e.claimTip,32),commitHalfLocker:ye(Lr(e.commitHalfLocker),32),edPointLocker:ye(Lr(e.edPointLocker),32),edViewPointLocker:ye(Lr(e.edViewPointLocker),32)};return Bl.map(n=>t[n]).join("")}function y1(e){let t=String(e||"").replace(/^0x/,"");if(!/^[0-9a-fA-F]{130}$/.test(t))throw new Error("the quote signature must be 65 bytes: "+String(e).slice(0,20));let n=t.slice(0,64),r=t.slice(64,128),o=parseInt(t.slice(128,130),16);return o<27&&(o+=27),ye("0x"+n,32)+ye("0x"+r,32)+ye(o,32)}function Kh(e){return w1(e)+y1(e.signature)}function Cl(e){return Ol.predict+Kh(e)}function Rl(e){return Ol.createOrderAndFund+Kh(e)}var jh=(e,t,n=1)=>{if(typeof e!="string"||!/^0x[0-9a-fA-F]*$/.test(e))throw new Error("invalid "+t+": "+e);let r=e.slice(2);if(r.length!==n*64)throw new Error("short answer: "+e);return r.toLowerCase()};function Hs(e){return"0x"+jh(e,"predict()").slice(24,64)}var Cs={implementation:"0x5c60da1b",implementationCodeHash:"0xbc0a3981"};function b1(e){let t=Cs[e];if(typeof t!="string"||!/^0x[0-9a-f]{8}$/.test(t))throw new Error("no such factory read: "+e);return t}function Wh(e){return Hs(e)}function Vh(e){return"0x"+jh(e,"implementationCodeHash()")}function $h({implementation:e,implementationCodeHash:t,code:n,hashCode:r,policy:o}={}){if(!e||!/^0x[0-9a-fA-F]{40}$/.test(String(e)))return{ok:!1,why:"implementation-missing"};if(!t||!/^0x[0-9a-fA-F]{64}$/.test(String(t)))return{ok:!1,why:"code-hash-missing"};if(n==null||n==="0x"||n==="0x0")return{ok:!1,why:"implementation-has-no-code"};let i=String(t).toLowerCase();if(Array.isArray(o)&&o.length&&!o.map(s=>String(s).toLowerCase()).includes(i))return{ok:!1,why:"implementation-code-unknown",codeHash:i};if(typeof r=="function"){let s=String(r(n)).toLowerCase();if(s!==i)return{ok:!1,why:"implementation-code-mismatch",got:s,want:i}}return{ok:!0,codeHash:i}}async function g1({factory:e,read:t,code:n,policy:r=null,hashCode:o=null}={}){if(!e||!/^0x[0-9a-fA-F]{40}$/.test(String(e)))return{ok:!1,why:"factory-missing"};if(typeof t!="function")return{ok:!1,why:"no-chain-read"};if(typeof n!="function")return{ok:!1,why:"no-code-read"};let i,s;try{i=await t({to:e,data:Cs.implementation}),s=await t({to:e,data:Cs.implementationCodeHash})}catch{return{ok:!1,why:"implementation-unreadable",factory:String(e).toLowerCase()}}let a,c;try{a=Wh(i),c=Vh(s)}catch{return{ok:!1,why:"implementation-unreadable",factory:String(e).toLowerCase()}}let l;try{l=await n(a)}catch{return{ok:!1,why:"implementation-code-unreadable",implementation:a}}return{...$h({implementation:a,implementationCodeHash:c,code:l,hashCode:o,policy:r}),implementation:a,implementationCodeHash:c}}var Fr={};Be(Fr,{ESCROW_METHODS:()=>qt,decodeBytes32:()=>Jh,decodeStatus:()=>Fs,decodeUint64:()=>em,encodeClaim:()=>Xh,encodeMarkReady:()=>zh,encodeRead:()=>Zh,encodeRefund:()=>Gh,encodeStatus:()=>Ls,encodeT1:()=>qh,encodeTermsHash:()=>Qh,orderTerms:()=>tm});var qt={markReady:"0x1ca087e7",claim:"0xbd66528a",refund:"0x7249fbb6",status:"0x200d2ed2",t1:"0xfb5343f3",readyBy:"0x53fc2f40",ready:"0x6defbf80",revealedHalf:"0x3f267bb6",edPointLocker:"0x8c03382b",edPointClaimer:"0xdd98c465",edViewPointLocker:"0x9a06a5fe",commitHalfLocker:"0x498b422e",commitHalfClaimer:"0x7d4c81f7",termsHash:"0xb311d9fd",fee:"0xddca3f43",feeBps:"0x24a9d853",feeRecipient:"0x46904840",feeOnTop:"0x2296cc23",registry:"0x7b103999",cashier:"0xed740e97",provider:"0x085d4883",quoteKey:"0x391d53ca",validUntil:"0xddac6654",nonce:"0xaffed0e0"};function zh(){return qt.markReady}function Xh(e){return qt.claim+Yh(e,"secret")}function Yh(e,t){let n=String(e||"").replace(/^0x/i,"").toLowerCase();if(!/^[0-9a-f]{1,64}$/.test(n))throw new Error(t+" must be a number of up to 32 bytes: "+e);return n.padStart(64,"0")}function Gh(e){return qt.refund+Yh(e,"half")}function Ls(){return qt.status}function qh(){return qt.t1}function Qh(){return qt.termsHash}function Zh(e){let t=qt[e];if(typeof t!="string"||!/^0x[0-9a-f]{8}$/.test(t))throw new Error("no such escrow method: "+e);return t}var Hl=(e,t,n)=>{if(typeof e!="string"||!/^0x[0-9a-fA-F]*$/.test(e))throw new Error("invalid "+t+": "+e);let r=e.slice(2);if(r.length!==n*64)throw new Error("short answer "+t+": "+e);return r.toLowerCase()};function Jh(e,t="value"){return"0x"+Hl(e,t,1)}function em(e,t="value"){let n=Hl(e,t,1),r=BigInt("0x"+n);if(r>18446744073709551615n)throw new Error("answer "+t+" does not fit in uint64: "+r);return Number(r)}function Fs(e){let t=Hl(e,"status()",4),n=r=>t.slice(r*64,(r+1)*64);return{isFunded:BigInt("0x"+n(0))!==0n,isClaimed:BigInt("0x"+n(1))!==0n,isRefunded:BigInt("0x"+n(2))!==0n,balance:BigInt("0x"+n(3))}}function tm({locker:e,claimer:t,commitHalfLocker:n,commitHalfClaimer:r,edPointLocker:o,edPointClaimer:i,amount:s,readyBy:a,t1:c}){for(let[l,u]of Object.entries({locker:e,claimer:t,commitHalfLocker:n,commitHalfClaimer:r,edPointLocker:o,edPointClaimer:i,amount:s}))if(u==null||u==="")throw new Error("order term not set: "+l);if(Number(a)<=Math.floor(Date.now()/1e3))throw new Error("readyBy must be in the future: "+a);if(Number(c)<=Number(a))throw new Error("t1 must be later than readyBy");return{locker:e,claimer:t,commitHalfLocker:n,commitHalfClaimer:r,edPointLocker:o,edPointClaimer:i,amount:s,readyBy:a,t1:c}}function x1(e,t){let n=BigInt(e==null||e===""?0:e),r=BigInt(Number(t)||0);if(n<0n||r<0n)throw new Error("fee: negative amount or rate");return n*r/10000n}var nm=(e,t)=>String(e||"").toLowerCase()===String(t||"").toLowerCase(),k1=e=>!e||/^0x0{40}$/i.test(String(e)),S1=null;function rm(e){if(!e||typeof e!="object")throw new Error("no signed quote: there is nowhere to take the fee and the registry address");let t=BigInt(String(e.amount)),n=Number(e.feeBps===void 0||e.feeBps===null?0:e.feeBps);if(!Number.isFinite(n)||n<0||n>200)throw new Error("fee rate outside the ceiling: "+e.feeBps);let r=x1(t,n);if(BigInt(String(e.fee===void 0||e.fee===null?0:e.fee))!==r)throw new Error("signed fee "+e.fee+" diverges from the formula amount * rate ("+r+") - signature not started");if(n!==0&&k1(e.feeRecipient))throw new Error("with a non-zero rate the fee recipient must be named");let o=nm(e.locker,e.provider),i=nm(e.claimer,e.provider);if(o===i)throw new Error("cannot tell who pays the fee: the provider is named neither as depositor nor as claimer");let s=i,a={bps:n,feeWei:r,totalWei:s?t+r:t,recipient:e.feeRecipient||null,feeOnTop:s,legacy:!1};return S1=a,a}function om(){let e=new Uint8Array(32);return crypto.getRandomValues(e),"0x"+Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function im({locker:e,claimer:t,commitHalfLocker:n,commitHalfClaimer:r,edPointLocker:o,edPointClaimer:i,edViewPointLocker:s,amountWei:a,salt:c,claimWindowSeconds:l=3600,readyWindowSeconds:u=14400,readyBy:f,t1:h}){for(let[g,P]of Object.entries({commitHalfLocker:n,commitHalfClaimer:r,edPointLocker:o,edPointClaimer:i,edViewPointLocker:s}))if(!P)throw new Error("order term not set: "+g);let m=Math.floor(Date.now()/1e3),w=f!=null&&f!=="",x=h!=null&&h!=="",y=w?Number(f):m+u,k=x?Number(h):y+l;if(!(k>y))throw new Error("the settlement deadline must be later than the readiness deadline: t1="+k+", readyBy="+y);let I=dc({nowSec:m,readyBy:y,t1:k,...Io});if(I.blocks)throw new Error("order deadlines are not usable: "+I.reason);return{locker:e,claimer:t,commitHalfLocker:n,commitHalfClaimer:r,edPointLocker:o,edPointClaimer:i,edViewPointLocker:s,amount:String(a),readyBy:String(y),t1:String(k),salt:c}}function sm(e,t=18){let[n,r=""]=String(e).split("."),o=(r+"0".repeat(t)).slice(0,t);return BigInt(n||"0")*10n**BigInt(t)+BigInt(o||"0")}function v1({quote:e=null,nativeDecimals:t=18}={}){let n=e?e.payNative:null;if(n==null||n==="")return{ok:!1,code:"native-amount-unread",reason:"the quote carries no native amount"};let r=Number(n);if(!Number.isFinite(r)||r<=0)return{ok:!1,code:"native-amount-unread",reason:"the quote's native amount is not a positive number"};let o=Number(t);if(!Number.isInteger(o)||o<0)return{ok:!1,code:"native-amount-unread",reason:"the native decimals are not a whole number"};let i=/e/i.test(String(n))?r.toFixed(18):String(n);if(!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(i))return{ok:!1,code:"native-amount-unread",reason:"the native amount is not a decimal number"};let s;try{s=sm(i,o)}catch{return{ok:!1,code:"native-amount-unread",reason:"the native amount is not a decimal number"}}return s<=0n?{ok:!1,code:"native-amount-unread",reason:"the native amount rounds to zero wei"}:{ok:!0,wei:s.toString(),source:"native"}}var am=700000n;function cm(e,{factory:t=null,expectedEscrow:n=null}={}){if(!e||!Array.isArray(e.logs))return null;let r=t?String(t).toLowerCase():null,o=n?String(n).toLowerCase():null;for(let i of e.logs){if(r&&String(i&&i.address||"").toLowerCase()!==r)continue;let s=i.topics||[];if(String(s[0]).toLowerCase()!==Rs||s.length<2)continue;let a="0x"+String(s[1]).slice(26).toLowerCase();if(!(!/^0x[0-9a-f]{40}$/.test(a)||/^0x0{40}$/.test(a))&&!(o&&a!==o))return a}return null}function Ds(e,{factory:t=null,expectedEscrow:n=null}={}){if(!e||typeof e!="object")return{status:"pending",reason:"no-receipt"};if(e.status===void 0||e.status===null||e.status==="")return{status:"pending",reason:"no-status"};let r=Number(e.status);if(!Number.isFinite(r))return{status:"pending",reason:"bad-status"};if(r===0)return{status:"reverted",reason:"status-0"};if(r!==1)return{status:"pending",reason:"bad-status"};let o=cm(e,{factory:t,expectedEscrow:n});if(!o)return{status:"pending",reason:"no-order-created"};let i=Number(e.blockNumber);return{status:"funded",escrow:o,birthBlock:Number.isFinite(i)?i:null}}async function E1(e,t,{tries:n=12,delayMs:r=1500}={}){for(let o=0;o<n;o+=1){let i=await e({hash:t}).catch(()=>null);if(i)return i;await new Promise(s=>setTimeout(s,r))}return null}async function Ll({factory:e,locker:t,claimer:n,commitHalfLocker:r,commitHalfClaimer:o,edPointLocker:i,edPointClaimer:s,edViewPointLocker:a,salt:c,amountWei:l,amountLabel:u,claimWindowSeconds:f,readyWindowSeconds:h,readyBy:m,t1:w,quote:x,call:y,send:k,receipt:I,onStep:g,onPredicted:P}){if(!e)throw new Error("no escrow factory address set for this network");if(!t)throw new Error("no EVM wallet connected: there is nobody to deposit");if(!n)throw new Error("the order recipient (claimer) is not set");if(t.toLowerCase()===n.toLowerCase())throw new Error("locker and claimer must not coincide: the contract rejects such an order");if(!x||typeof x!="object")throw new Error("a signed quote is required: the factory takes a quote, not bare order terms");let E=c||om(),B=im({locker:t,claimer:n,commitHalfLocker:r,commitHalfClaimer:o,edPointLocker:i,edPointClaimer:s,edViewPointLocker:a,amountWei:l,salt:E,claimWindowSeconds:f,readyWindowSeconds:h,readyBy:m,t1:w});g?.("computing the escrow address");let p={...x,commitHalfLocker:B.commitHalfLocker,edPointLocker:B.edPointLocker,edViewPointLocker:B.edViewPointLocker},b=(W,$)=>String(W??"").replace(/^0x/i,"").toLowerCase()===String($??"").replace(/^0x/i,"").toLowerCase();for(let W of["locker","claimer","amount","readyBy","t1","salt","commitHalfClaimer","edPointClaimer"])if(!b(x[W],B[W]))throw new Error("the quote and the order terms diverge on field "+W);let S=await y({to:e,data:Cl(p)}),v=Hs(S);if(!/^0x[0-9a-fA-F]{40}$/.test(v)||/^0x0{40}$/i.test(v))throw new Error("the factory returned an invalid escrow address: "+String(S).slice(0,40));g?.("checking the order is not already on chain");let H=null;try{let W=await y({to:v,data:Ls()});H=String(W||"").replace(/^0x/,"").length>=256?{status:Fs(W)}:{status:null}}catch(W){H={error:String(W&&W.message||W)}}let A=fc({status:H.status,error:H.error,address:v});if(A.blocks)throw new Error("signature not started: "+A.reason);g?.("reading the escrow fee from the signed quote");let O=rm(x),D=O.totalWei,L=O.feeWei>0n?" (order "+l+" + fee "+O.feeWei+")":"";g?.("locking "+(u||"funds")+L+" in one transaction - confirm in wallet"),typeof P=="function"&&await P({escrow:v,salt:E,terms:B});let V=Rl(p),U=await k({to:e,data:V,value:"0x"+D.toString(16),gas:am}),j=null,F=null,R={status:"pending",reason:"no-receipt-reader"};if(typeof I=="function"){let W=await E1(I,U);if(R=Ds(W,{factory:e,expectedEscrow:v}),R.status==="reverted"){let $=new Error("the funding transaction reverted");throw $.code="contract-reverted",$.receiptStatus=0,$}R.status==="funded"?(j=R.escrow,F=R.birthBlock,j!==String(v).toLowerCase()&&(console.warn("[escrow] receipt address "+j+" != predicted "+v+" - using the receipt one"),g?.("receipt address differs from predicted - using the receipt one"))):g?.(W?"receipt has no matching OrderCreated - funding is pending, not funded":"no receipt yet - funding is pending, not funded")}let _=U,N={feeWei:O.feeWei,feeTotalWei:D,feeBps:O.bps,feeWasLegacyFactory:!!O.legacy,predictedEscrow:v,salt:E,terms:B,createHash:U,lockHash:_};return R.status!=="funded"?{...N,escrow:null,birthBlock:null,funded:!1,pending:!0,pendingReason:R.reason}:{...N,escrow:j,escrowMismatch:j!==String(v).toLowerCase(),birthBlock:F,funded:!0,pending:!1}}var lm=["native","wrapped"],Fl="native",qo=Object.freeze({NATIVE:"native",WRAPPED:"wrapped"}),Sn=[],um=()=>Sn.length===0?null:Sn.length===1?Sn[0]:Sn,A1=(e=null)=>(Array.isArray(e)?Sn=e.filter(Boolean):e&&typeof e=="object"?Sn=[e]:Sn=[],um()),_1=()=>um(),dm=e=>Sn.filter(t=>t&&Number(t.chainId)===Number(e)),Qo=e=>e&&Fi[e]||null,Ul=()=>Object.keys(Fi).sort(),fm=e=>Object.keys((Qo(e)||{}).networks||{}).map(Number).filter(Number.isFinite).sort((t,n)=>t-n),pm=e=>{let t=Qo(e);return t?t.settles===void 0?null:t.settles:null},I1=(e,t={})=>t.settles?t.settles:pm(e),Dl=(e,t,n,r={})=>{let o=Qo(e)||{};return{id:e,venue:r.venue||o.venue||e,shape:r.shape||o.shape||"async",chainId:Number(t),slug:n.slug===void 0?null:n.slug,orderbook:n.orderbook===void 0?null:n.orderbook,contract:n.contract===void 0?null:n.contract,settles:I1(e,r)}},Us=e=>{let t=Number(e),n=new Map;for(let r of Ul()){let o=Qo(r),i=o.networks&&o.networks[t];i&&n.set(r,Dl(r,t,i))}for(let r of dm(t))n.set(r.id,Dl(r.id,t,{slug:r.slug,orderbook:r.orderbook,contract:r.contract},{settles:r.settles,venue:r.venue,shape:r.shape}));return[...n.values()].sort((r,o)=>r.id.localeCompare(o.id))},N1=(e,t=null)=>{let n=Number(e);if(t){let o=dm(n).find(i=>i.id===t);return o?Dl(o.id,n,{slug:o.slug,orderbook:o.orderbook,contract:o.contract},{settles:o.settles,venue:o.venue,shape:o.shape}):Us(n).find(i=>i.id===t)||null}let r=Us(n);return r.length?r[0]:null},T1=e=>fm(e||Ul()[0]||null),hm=({chainId:e=null,providerId:t=null,need:n=Fl}={})=>{let r=Number(e),o=Number.isFinite(r),i=lm.includes(n)?n:Fl,s=o?Us(r):[];if(!s.length)return{ok:!1,reason:"no-async-provider",chainId:o?r:null,need:i,provider:t||null,known:T1(t)};let a=null;if(t&&(a=s.find(m=>m.id===t)||null,!a))return{ok:!1,reason:"no-async-provider",chainId:r,need:i,provider:t,known:s.map(m=>m.id)};let c=a?[a]:s,l=c.filter(m=>m.settles===i);if(l.length){let m=l[0];return{ok:!0,kind:"single",...m,need:i,provider:m.id,legs:[m]}}let u=c.filter(m=>m.settles===qo.WRAPPED),f=s.filter(m=>m.settles===qo.NATIVE);if(i===qo.NATIVE&&u.length&&f.length){let m=u[0],w=f[0];return{ok:!0,kind:"composition",need:i,chainId:r,provider:m.id,venue:m.venue,shape:"async",orderbook:m.orderbook,legs:[m,w]}}return{ok:!1,reason:i===qo.NATIVE&&u.length&&!f.length?"no-native-async-provider":"no-async-provider",chainId:r,need:i,missing:i,provider:(a||u[0]||s[0]).id,known:s.map(m=>m.id)}},Ml=hm;var ym={approve:{hex:"0x095ea7b3",signature:"approve(address,uint256)"},allowance:{hex:"0xdd62ed3e",signature:"allowance(address,address)"},balanceOf:{hex:"0x70a08231",signature:"balanceOf(address)"}},Zo={permit:{hex:"0xd505accf",signature:"permit(address,address,uint256,uint256,uint8,bytes32,bytes32)"},nonces:{hex:"0x7ecebe00",signature:"nonces(address)"},DOMAIN_SEPARATOR:{hex:"0x3644e515",signature:"DOMAIN_SEPARATOR()"}},Ws=e=>String(e??"").replace(/^0x/,""),Ks=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),js=e=>Ws(e).toLowerCase().padStart(64,"0"),Ms=e=>BigInt(e).toString(16).padStart(64,"0"),mm=e=>{let t=Ws(e);return t.length===0||t.length%2?null:t.length/2},wm=e=>{if(e==null||e==="")return null;try{return BigInt(typeof e=="bigint"?e:String(e))}catch{return null}};function P1({owner:e,spender:t,value:n,deadline:r,signature:o}){if(!Ks(e)||!Ks(t))throw new Error("permit: owner and spender must be addresses");let i=Ws(o);if(i.length!==130)throw new Error("permit: the signature must be 65 bytes, got "+i.length/2);let s=parseInt(i.slice(128,130),16);if(s<27&&(s+=27),s!==27&&s!==28)throw new Error("permit: v outside {27,28}: "+s);return Zo.permit.hex+js(e)+js(t)+Ms(n)+Ms(r)+Ms(s)+i.slice(0,64)+i.slice(64,128)}var B1=e=>Zo.nonces.hex+js(e),O1=()=>Zo.DOMAIN_SEPARATOR.hex,C1=({spender:e,amountWei:t})=>ym.approve.hex+js(e)+Ms(t);function R1({code:e=null,domainSeparator:t=null,nonces:n=null,owner:r=null}={}){let o=Ws(e);if(o.length===0)return{supported:null,kind:"no-code",reason:"no code at the token address - not a token, the allowance cannot be read"};if(!Ks(r))return{supported:null,kind:"no-owner",reason:"no owner given - cannot read nonces(owner)"};let i=mm(t);if(i===null)return{supported:null,kind:"domain-unread",reason:"DOMAIN_SEPARATOR did not answer 32 bytes: could not read"};if(i!==32)return{supported:!1,kind:"domain-empty",reason:"DOMAIN_SEPARATOR returned "+i+" bytes instead of 32: no EIP-712 domain declared"};let s=mm(n);return s===null?{supported:null,kind:"nonces-unread",reason:"nonces(owner) did not answer: could not read"}:s!==32?{supported:!1,kind:"nonces-empty",reason:"nonces(owner) returned "+s+" bytes instead of 32: no EIP-2612 counter"}:o.toLowerCase().includes(Zo.permit.hex.slice(2))?{supported:!0,kind:"eip2612",reason:"the token declares an EIP-712 domain, a nonces counter and the permit selector"}:{supported:!1,kind:"permit-selector-absent",reason:"the token bytecode has no permit selector: no signature allowance"}}function H1({orchestrator:e=null,permitSupported:t=null,token:n=null,nativeBalanceWei:r=null,gasNeedWei:o=null,asyncProvider:i=null,chainId:s=null}={}){let a=wm(o),c=i&&typeof i=="object"?i:s==null?null:Ml({chainId:s}),l=!!(c&&c.ok===!0),u=c&&c.ok===!1&&c.reason?String(c.reason):"no-async-provider";if(a!==null&&a>0n){let f=wm(r);if(f===null)return{ok:!1,blocked:!1,checked:!1,kind:"balance-unread",path:null,gasNeedWei:a.toString(),reason:"the wallet's native balance was not read, so it is unknown which path fits - read the balance before choosing"};if(f>=a)return{ok:!0,blocked:!1,checked:!0,kind:"own-gas",path:"sync",nativeBalanceWei:f.toString(),gasNeedWei:a.toString(),reason:"the wallet's own native covers the gas this deal needs, so the ordinary synchronous path is taken"};let h={checked:!0,nativeBalanceWei:f.toString(),gasNeedWei:a.toString(),shortfallWei:(a-f).toString()};return l?{ok:!0,blocked:!1,...h,kind:"async-route",path:"async",provider:c.provider??null,venue:c.venue??null,reason:"the wallet's own native does not cover the gas this deal needs, but an asynchronous provider serves this network: the swap settles first and the escrow is funded after it, so the deposit's gas is paid later"}:{ok:!1,blocked:!0,...h,kind:"no-async-provider",path:null,reason:"the wallet's own native does not cover the gas this deal needs and no asynchronous provider serves this network ("+u+"): there is no path for a purchase without own native coin here"}}return Ks(e)?t===!1?{ok:!1,blocked:!0,kind:"token-no-permit",reason:"the token has no signature allowance (EIP-2612): the allowance must be a separate approve, i.e. a separate transaction - the path does not assemble into one transaction"}:t!==!0?{ok:!1,blocked:!0,kind:"permit-unproven",reason:'unknown whether the token supports a signature allowance: "not checked" is not "possible". The capability must be read from the chain before assembling the path'}:{ok:!0,blocked:!1,kind:"one-tx-possible",path:"sync",reason:"an executor is present and the token declares EIP-2612: the one-transaction path assembles"}:{ok:!1,blocked:!0,kind:"no-orchestrator",path:null,reason:"no executor contract: only a contract could pull a token by the user signature and deposit native into the escrow in one transaction, and this build has none"}}function L1(){return $o()}async function F1(e){await new Promise(r=>setTimeout(r,900));let t=new Uint8Array(32);return crypto.getRandomValues(t),{hash:"0x"+Array.from(t,r=>r.toString(16).padStart(2,"0")).join(""),...e,simulated:!0}}async function D1({factory:e,locker:t,claimer:n,commitHalfLocker:r,commitHalfClaimer:o,edPointLocker:i,edPointClaimer:s,edViewPointLocker:a,salt:c,amountWei:l,amountLabel:u,claimWindowSeconds:f=3600,readyWindowSeconds:h=14400,readyBy:m,t1:w,quote:x,onStep:y}){return Ll({factory:e,quote:x,locker:t,claimer:n,commitHalfLocker:r,commitHalfClaimer:o,edPointLocker:i,edPointClaimer:s,edViewPointLocker:a,salt:c,amountLabel:u,amountWei:l,claimWindowSeconds:f,readyWindowSeconds:h,readyBy:m,t1:w,call:Sl,send:El,receipt:vl,onStep:y})}var tt={};Be(tt,{DEX_METHOD:()=>Qt,declaredRoutePath:()=>gm,decodeQuoteExactInput:()=>Wl,dexLegVerdict:()=>z1,encodeGetPool:()=>Em,encodePath:()=>jl,encodeQuoteExactInput:()=>Im,encodeQuoteExactInputSingle:()=>vm,encodeQuoteExactOutputSingle:()=>Am,feeTierLabel:()=>Ur,feeTierPct:()=>Nm,noRouteWords:()=>Rm,poolAddress:()=>Tm,poolState:()=>$1,priceGateVerdict:()=>Cm,quoteDexOut:()=>X1,quoteExactOutPath:()=>_m,quoteExactOutSingle:()=>j1,quotePath:()=>Bm,quoteTier:()=>Pm,resetDexCache:()=>K1,routeLabel:()=>xm,routeSignature:()=>Om,routeSteps:()=>km,unwrapLeg:()=>Y1});var Qt={quoteExactOutputSingle:{hex:"0xbd21704a",signature:"quoteExactOutputSingle((address,address,uint256,uint24,uint160))"},quoteExactOutput:{hex:"0x2f80bb1d",signature:"quoteExactOutput(bytes,uint256)"},quoteExactInputSingle:{hex:"0xc6a5026a",signature:"quoteExactInputSingle((address,address,uint256,uint24,uint160))"},quoteExactInput:{hex:"0xcdca1753",signature:"quoteExactInput(bytes,uint256)"},getPool:{hex:"0x1698ee82",signature:"getPool(address,address,uint24)"},liquidity:{hex:"0x1a686502",signature:"liquidity()"},balanceOf:{hex:"0x70a08231",signature:"balanceOf(address)"},withdraw:{hex:"0x2e1a7d4d",signature:"withdraw(uint256)"}};function gm({token:e,tokens:t=[],wrapped:n,route:r}){if(!e||!r||!Array.isArray(r.steps)||!r.steps.length)return null;let o=new Map((t||[]).map(u=>[String(u.symbol).toUpperCase(),u])),i=u=>{let f=String(u).toUpperCase();if(n&&f===String(n.symbol).toUpperCase())return n.address;let h=o.get(f);return h&&h.address?h.address:null},s=[e.symbol],a=[e.address],c=[],l=[];for(let u of r.steps){let f=i(u.to);if(!f)return{error:`declared route names a token that this network has no address for: ${u.to}`};a.push(f),s.push(String(u.to).toUpperCase()===String(n&&n.symbol).toUpperCase()?n.symbol:u.to),c.push(Number(u.fee)),l.push(u.pool||null)}return{tokens:a,symbols:s,fees:c,pools:l}}function xm(e){if(!e||!e.symbols)return"";let t=e.symbols[0];for(let n=0;n<e.fees.length;n++)t+=" \u2192 "+e.symbols[n+1]+" "+Ur(e.fees[n]);return t}function km(e){return!e||!e.symbols?[]:e.fees.map((t,n)=>({from:e.symbols[n],to:e.symbols[n+1],fee:t,feeLabel:Ur(t)}))}var U1=2e4,Kl=new Map;function M1(e){let t=Kl.get(e);if(t&&Date.now()-t.at<U1)return t.value}function bm(e,t){return Kl.set(e,{at:Date.now(),value:t}),t}function K1(){Kl.clear()}async function vn(e,t,n=[],{timeoutMs:r=15e3}={}){if(!e||!e.rpcUrl)return{ok:!1,why:"network has no RPC endpoint"};let o=typeof AbortController=="function"?new AbortController:null,i=o?setTimeout(()=>o.abort(),r):null;try{let s=await fetch(e.rpcUrl,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:t,params:n}),signal:o?o.signal:void 0});if(!s.ok)return{ok:!1,why:t+": HTTP "+s.status};let a=await s.json();return a.error?{ok:!1,why:t+": "+String(a.error.message||"rpc error").slice(0,120)}:{ok:!0,result:a.result}}catch(s){let a=s&&s.name==="AbortError";return{ok:!1,why:t+": "+(a?"no answer in "+r+" ms":String(s&&s.message||s))}}finally{i&&clearTimeout(i)}}var Vs=e=>String(e||"").replace(/^0x/,""),Sm=e=>Vs(e).toLowerCase().padStart(64,"0"),En=e=>Sm(e),mt=e=>{let t="",n=BigInt(e);for(;n>0n;)t=(n&0xffn).toString(16).padStart(2,"0")+t,n>>=8n;return t.padStart(64,"0")};function Dr(e){let t=Vs(e),n=[];for(let r=0;r+64<=t.length;r+=64)n.push(BigInt("0x"+t.slice(r,r+64)));return n}function vm({tokenIn:e,tokenOut:t,amountInWei:n,fee:r,sqrtPriceLimitX96:o=0}){return Qt.quoteExactInputSingle.hex+En(e)+En(t)+mt(n)+mt(r)+mt(o)}function Em({tokenA:e,tokenB:t,fee:n}){return Qt.getPool.hex+En(e)+En(t)+mt(n)}function Am({tokenIn:e,tokenOut:t,amountOutWei:n,fee:r,sqrtPriceLimitX96:o=0}){return Qt.quoteExactOutputSingle.hex+En(e)+En(t)+mt(n)+mt(r)+mt(o)}async function j1(e,{tokenIn:t,tokenOut:n,amountOutWei:r,fee:o},i={}){let s=e&&e.uniswap;if(!s||!s.quoter)return{ok:!1,why:"no verified QuoterV2 for this network"};let a=Am({tokenIn:t,tokenOut:n,amountOutWei:r,fee:o}),c=await vn(e,"eth_call",[{to:s.quoter,data:a},"latest"],i);if(!c.ok)return{ok:!1,why:c.why};let l=Dr(c.result);return l.length?l[0]<=0n?{ok:!1,why:"pool cannot serve this output"}:{ok:!0,amountInWei:l[0].toString(),gasEstimate:l.length>1?l[l.length-1].toString():null}:{ok:!1,why:"quoter answered without data"}}async function _m(e,{route:t,amountOutWei:n},r={}){let o=e&&e.uniswap;if(!o||!o.quoter)return{ok:!1,why:"no verified QuoterV2 for this network"};if(!t||!Array.isArray(t.tokens)||t.tokens.length<2)return{ok:!1,why:"route has no path"};let i=t.tokens.slice().reverse(),s=(t.fees||[]).slice().reverse(),a=jl({tokens:i,fees:s}),c=Qt.quoteExactOutput.hex+mt(64)+mt(n)+mt(a.bytes)+a.packed.padEnd(Math.ceil(a.packed.length/64)*64,"0"),l=await vn(e,"eth_call",[{to:o.quoter,data:c},"latest"],r);if(!l.ok)return{ok:!1,why:l.why};let u=Wl(l.result);return!u||u.amountOutWei<=0n?{ok:!1,why:"pool cannot serve exactly this output"}:{ok:!0,amountInWei:u.amountOutWei.toString(),gasEstimate:u.gasEstimate.toString(),shapeOk:u.sqrtPriceX96After.length===s.length,reversed:i.map(f=>f).length===s.length+1}}function jl({tokens:e,fees:t}){let n=[];for(let o=0;o<e.length;o++)n.push(Vs(e[o]).toLowerCase().padStart(40,"0")),o<t.length&&n.push(Vs(Number(t[o]).toString(16)).toLowerCase().padStart(6,"0"));let r=n.join("");return{packed:r,bytes:r.length/2}}function Im({tokens:e,fees:t,amountInWei:n}){let{packed:r,bytes:o}=jl({tokens:e,fees:t}),i=r.padEnd(Math.ceil(o/32)*64,"0");return Qt.quoteExactInput.hex+Sm("0x40")+mt(n)+mt(o)+i}var W1=e=>e==null?null:"0x"+e.toString(16).padStart(40,"0"),V1="0x"+"0".repeat(40);function Nm(e){let t=Number(e);return Number.isFinite(t)?t/1e4:null}function Ur(e){let t=Nm(e);return t===null?String(e):String(Number(t.toFixed(4)))+"%"}async function Tm(e,{tokenIn:t,tokenOut:n,fee:r},o={}){let i=e&&e.uniswap;if(!i||!i.factory)return{ok:!1,why:"no verified Uniswap factory for this network"};let s=await vn(e,"eth_call",[{to:i.factory,data:Em({tokenA:t,tokenB:n,fee:r})},"latest"],o);if(!s.ok)return{ok:!1,why:s.why};let a=Dr(s.result),c=W1(a[0]);return!c||c===V1?{ok:!0,pool:null}:{ok:!0,pool:c}}async function $1(e,t,{tokenIn:n,tokenOut:r},o={}){if(!t)return null;let[i,s,a]=await Promise.all([vn(e,"eth_call",[{to:t,data:Qt.liquidity.hex},"latest"],o),vn(e,"eth_call",[{to:n,data:Qt.balanceOf.hex+En(t)},"latest"],o),vn(e,"eth_call",[{to:r,data:Qt.balanceOf.hex+En(t)},"latest"],o)]),c=l=>l.ok?Dr(l.result)[0]??null:null;return{liquidity:i.ok?BigInt(Dr(i.result)[0]??0n).toString():null,reserveInWei:s.ok&&c(s)!==null?c(s).toString():null,reserveOutWei:a.ok&&c(a)!==null?c(a).toString():null}}async function Pm(e,{tokenIn:t,tokenOut:n,amountInWei:r,fee:o},i={}){let s=e&&e.uniswap;if(!s||!s.quoter)return{fee:o,ok:!1,why:"no verified QuoterV2 for this network"};let a=vm({tokenIn:t,tokenOut:n,amountInWei:r,fee:o}),c=await vn(e,"eth_call",[{to:s.quoter,data:a},"latest"],i);if(!c.ok)return{fee:o,ok:!1,why:c.why};let l=Dr(c.result);if(l.length<4)return{fee:o,ok:!1,why:"quoter answered "+l.length+" words, expected 4"};let u=l[0];return u<=0n?{fee:o,ok:!1,why:"pool cannot serve this size"}:{fee:o,ok:!0,amountOutWei:u.toString(),gasEstimate:l[3].toString(),sqrtPriceX96After:l[1].toString(),initializedTicksCrossed:l[2].toString()}}function Wl(e){let t=Dr(e);if(t.length<4)return null;let n=o=>Number(o)/32,r=o=>{let i=n(o);if(!Number.isInteger(i)||i<0||i>=t.length)return[];let s=Number(t[i]);return!Number.isInteger(s)||s<=0||i+1+s>t.length?[]:t.slice(i+1,i+1+s).map(String)};return{amountOutWei:t[0],sqrtPriceX96After:r(t[1]),initializedTicksCrossed:r(t[2]),gasEstimate:t[3]}}async function Bm(e,{route:t,amountInWei:n},r={}){let o=e&&e.uniswap;if(!o||!o.quoter)return{...t,ok:!1,why:"no verified QuoterV2 for this network"};let i=Im({tokens:t.tokens,fees:t.fees,amountInWei:n}),s=await vn(e,"eth_call",[{to:o.quoter,data:i},"latest"],r);if(!s.ok)return{...t,ok:!1,why:s.why};let a=Wl(s.result);return a?a.amountOutWei<=0n?{...t,ok:!1,why:"pool cannot serve this size"}:{...t,ok:!0,amountOutWei:a.amountOutWei.toString(),gasEstimate:a.gasEstimate.toString(),sqrtPriceX96After:a.sqrtPriceX96After,initializedTicksCrossed:a.initializedTicksCrossed,hops:t.fees.length,shapeOk:a.sqrtPriceX96After.length===t.fees.length}:{...t,ok:!1,why:"quoter answered a shape that is not quoteExactInput"}}function Om(e){return!e||!Array.isArray(e.steps)||!e.steps.length?e&&e.unwrap?"unwrap":"none":e.steps.map(t=>String(t.to).toUpperCase()+":"+Number(t.fee)+(t.pool?":"+String(t.pool).toLowerCase():"")).join("+")}function Cm({amountInWei:e=null,amountOutWei:t=null,inDecimals:n=null,outDecimals:r=null,tokenUsd:o=null,referenceUsd:i=null,stableSteps:s=[],tolerated:a=!1,gates:c=null}={}){let l=c&&Number.isFinite(Number(c.maxDeviationPct))&&Number(c.maxDeviationPct)>0?Number(c.maxDeviationPct):null,u=c&&Number.isFinite(Number(c.stableBandPct))&&Number(c.stableBandPct)>=0?Number(c.stableBandPct):null,f=[],h=(Array.isArray(s)?s:[]).map(p=>{let b={from:p.from,to:p.to,fee:p.fee,feeLabel:Ur(p.fee),inWei:p.inWei||null,outWei:p.outWei||null,exactAmount:!!p.exact,quoted:!!p.ok,ok:!1,ratio:null,deviationPct:null,why:null};if(!p.ok)return b.why="the 1:1 step could not be quoted ("+(p.why||"no answer")+")",f.push(b.why),b;let S=Number(p.inWei)/10**Number(p.inDecimals),v=Number(p.outWei)/10**Number(p.outDecimals);return!(S>0)||!(v>0)?(b.why="the 1:1 step answered with a number that cannot be read",f.push(b.why),b):(b.ratio=v/S,b.deviationPct=Math.abs(1-b.ratio)*100,u===null?(b.why="the 1:1 band is not declared for this step, so this step cannot be checked",f.push(b.why),b):b.deviationPct>u?(b.why=`${b.from}\u2192${b.to} at ${b.feeLabel} pays ${b.ratio.toFixed(6)} ${b.to} per 1 ${b.from} - ${b.deviationPct.toFixed(2)}% off 1:1, and the band is ${u}%`,f.push(b.why),b):(b.ok=!0,b))}),m=Number.isFinite(Number(n))&&Number(e)>0?Number(e)/10**Number(n):null,w=Number.isFinite(Number(r))&&Number(t)>0?Number(t)/10**Number(r):null,x=m!==null&&Number(o)>0?m*Number(o):null,y=x!==null&&w!==null&&w>0?x/w:null,k=Number(i)>0?Number(i):null,I=y!==null&&k!==null?Math.abs(y-k)/k*100:null,g=I!==null&&l!==null&&I>l;g?f.push(`the route implies the native coin at $${y.toFixed(2)} while the reference price is $${k.toFixed(2)} - ${I.toFixed(1)}% apart, and the limit is ${l}%: this is not the market price`):I===null?f.push(k===null?"the reference price of the native coin is not known, so the price cannot be checked":"the price of the token being paid is not known, so the price cannot be checked"):l===null&&f.push("the price limit is not declared for this route, so the price cannot be checked");let P=I!==null&&l!==null,E=g||h.some(p=>!p.ok);return{checked:P,bad:E,tolerated:!!a,blocks:a?!1:E||!P,why:f.length?f.join("; "):null,impliedUsd:y,referenceUsd:k,deviationPct:I,maxDeviationPct:l,stableBandPct:u,tokenUsd:Number(o)>0?Number(o):null,stable:h}}function Rm({paySymbol:e,wrappedSymbol:t,chainName:n,route:r=null}){let o=`no route from ${e} to ${t} on ${n}`,i=r&&r.why?String(r.why):null;return i?o+": "+i:o+": no route for "+e+" is declared - routes are declared by hand, not searched"}function z1(e,t=null){if(e&&e.unwrap)return{blocked:!1,kind:"unwrap",reason:null,price:null};if(!e)return{blocked:!0,kind:"unquoted",reason:"the swap leg has not been quoted yet",price:null};if(!e.ok)return{blocked:!0,kind:"no-route",reason:e.why||"no route",price:null};let n=e.price||null,r=!!(n&&n.bad),o=!!(n&&n.checked===!1),i=!!(n&&n.blocks&&(r||o)),s=t!=null&&Number(t)>0?BigInt(t):null,a=BigInt(e.amountOutWei),c=s===null?null:{needWei:s.toString(),getsWei:a.toString(),covers:a>=s,shortfallWei:(a>=s?0n:s-a).toString()},l={...c||{},price:n,routeLabel:e.routeLabel||null,decimals:e.wrapped?e.wrapped.decimals:null,wrappedSymbol:e.wrapped?e.wrapped.symbol:null};return i?{blocked:!0,...l,kind:r?"bad-price":"price-unchecked",reason:n.why}:c===null?{blocked:!0,...l,kind:"unchecked",reason:"the required escrow amount is not known yet, so coverage cannot be checked"}:c.covers?r?{blocked:!1,...l,kind:"bad-price-tolerated",reason:n.why}:{blocked:!1,...l,kind:"covers",reason:null}:{blocked:!0,...l,kind:"short",reason:"the declared route returns less than the order needs"}}async function X1(e,{token:t,amountWei:n,requiredOutWei:r=null,route:o=null,tokens:i=[],referenceNativeUsd:s=null,gates:a=null}={},c={}){let l=e&&e.uniswap;if(!t||!t.address)return{ok:!1,why:t&&t.native?"paying the native coin needs no DEX leg":"no token address"};if(!l||!l.quoter||!l.wrapped)return{ok:!1,why:"no verified Uniswap addresses for "+(e&&e.name?e.name:"this network")};let u=BigInt(n||0);if(u<=0n)return{ok:!1,why:"amount not entered"};let f=l.wrapped,h=e&&e.name||e&&e.id||"this network";if(String(t.address).toLowerCase()===String(f.address).toLowerCase())return{ok:!1,why:"this is the wrapped native coin: no pool needed, it unwraps 1:1",unwrap:!0};let m=o||null,w=String(e&&e.dexPriceGate||"")==="tolerated",x=m?{steps:(Array.isArray(m.steps)?m.steps:[]).map(v=>({to:v.to,fee:v.fee,pool:v.pool||null,verified:v.verified||null})),why:m.why||null,unwrap:!!m.unwrap}:null;if(!m||!Array.isArray(m.steps)||!m.steps.length)return m&&m.unwrap?{ok:!1,why:"this is the wrapped native coin: no pool needed, it unwraps 1:1",unwrap:!0}:{ok:!1,why:Rm({paySymbol:t.symbol,wrappedSymbol:f.symbol,chainName:h,route:m}),declared:!0,declaration:x,steps:[]};let y=gm({token:t,tokens:i,wrapped:f,route:m});if(!y||y.error)return{ok:!1,declared:!0,dataError:!0,declaration:x,why:"the declared route for "+t.symbol+" on "+h+" cannot be built: "+(y&&y.error||"unknown reason")};let k=new Map((Array.isArray(i)?i:[]).filter(v=>v&&v.address).map(v=>[String(v.address).toLowerCase(),v])),I=v=>{if(String(v).toLowerCase()===String(t.address).toLowerCase())return t.decimals;if(String(v).toLowerCase()===String(f.address).toLowerCase())return f.decimals;let H=k.get(String(v).toLowerCase());return H&&Number.isFinite(Number(H.decimals))?Number(H.decimals):null},g=[e.id,t.symbol,u.toString(),Om(m)].join("|"),P=M1(g);if(P===void 0){let v=await Bm(e,{route:{tokens:y.tokens,fees:y.fees,symbols:y.symbols,via:null},amountInWei:u},c);if(!v.ok)return bm(g,{ok:!1,why:v.why,declared:!0});P={ok:!0,quote:v},bm(g,P)}if(!P.ok)return{...P,declaration:x};let E=P.quote;if(P.hops===void 0){let v=[];for(let H=0;H<y.fees.length;H++){let A=y.fees[H],O=y.tokens[H],D=y.tokens[H+1],L=m.steps&&m.steps[H]||{},V=await Tm(e,{tokenIn:O,tokenOut:D,fee:A},c),U=V.ok?V.pool:null,j=L.pool||null;v.push({step:H+1,from:y.symbols[H],to:y.symbols[H+1],fee:A,feeLabel:Ur(A),decimals:[I(O),I(D)],pool:U,declaredPool:j,poolMatchesDeclared:U&&j?String(U).toLowerCase()===String(j).toLowerCase():null,verified:L.verified||null})}P.hops=v}let B=P.hops;if(P.stableSteps===void 0){let v=(a&&Array.isArray(a.stables)?a.stables:[]).map(A=>String(A).toUpperCase()),H=[];for(let A=0;A<y.fees.length;A++){let O=String(y.symbols[A]).toUpperCase(),D=String(y.symbols[A+1]).toUpperCase();if(!v.includes(O)||!v.includes(D))continue;let L=await Pm(e,{tokenIn:y.tokens[A],tokenOut:y.tokens[A+1],amountInWei:u,fee:y.fees[A]},c);H.push({from:y.symbols[A],to:y.symbols[A+1],fee:y.fees[A],inWei:u.toString(),outWei:L.ok?L.amountOutWei:null,inDecimals:I(y.tokens[A]),outDecimals:I(y.tokens[A+1]),ok:!!L.ok,why:L.ok?null:L.why,exact:A===0})}P.stableSteps=H}let p=Cm({amountInWei:u,amountOutWei:E.amountOutWei,inDecimals:t.decimals,outDecimals:f.decimals,tokenUsd:Number(t.usd)>0?Number(t.usd):null,referenceUsd:s,stableSteps:P.stableSteps,tolerated:w,gates:a}),b=null;if(r!=null&&Number(r)>0){let v=await _m(e,{route:E,amountOutWei:BigInt(r)},c);b=v.ok?{ok:!0,amountInWei:v.amountInWei,gasEstimate:v.gasEstimate,enough:BigInt(v.amountInWei)<=u,enteredWei:u.toString(),spareInWei:(BigInt(v.amountInWei)<=u?u-BigInt(v.amountInWei):0n).toString(),shortInWei:(BigInt(v.amountInWei)<=u?0n:BigInt(v.amountInWei)-u).toString()}:{ok:!1,why:v.why}}let S=r!=null&&Number(r)>0?(()=>{let v=BigInt(r),H=BigInt(E.amountOutWei);return{outWei:v.toString(),getsWei:H.toString(),covers:H>=v,shortfallWei:(H>=v?0n:v-H).toString()}})():null;return{ok:!0,leg:"pool",venue:"Uniswap v3",payToken:t.symbol,wrapped:f,declaredRoute:x,route:{symbols:E.symbols.slice(),fees:E.fees.slice(),pools:y.pools.slice(),via:null,hops:E.fees.length},routeLabel:xm(E),steps:km(E),fee:E.fees[E.fees.length-1],feeLabel:E.fees.map(v=>Ur(v)).join(" / "),amountInWei:u.toString(),amountOutWei:E.amountOutWei,gasEstimate:E.gasEstimate,required:S,price:p,exactOut:b,hopsDetail:B,pool:B.length?B[0].pool:null,at:Date.now()}}function Y1(e){let t=e&&e.uniswap;if(!t||!t.wrapped)return{ok:!1,why:"no verified wrapped native coin for this network"};let n=t.wrapped;return{ok:!0,leg:"unwrap",venue:n.name||n.symbol,wrapped:n,rate:1,gasEstimate:null,why:null}}var $s={};Be($s,{checkOrderQuoteShape:()=>q1,requestOrderQuote:()=>G1});async function G1({providerId:e,order:t}){if(!e)throw new Error("no provider selected: there is no one to ask for an order quote");let n=await fetch(Z1()+"/order-quote",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({providerId:e,order:t})}),r=null;try{r=await n.json()}catch{r=null}if(!n.ok||!r||r.ok!==!0||!r.quote){let o=r&&(r.error||r.why)||"HTTP "+n.status;throw new Error("the provider gave no order quote: "+o)}if(r.signatureVerified!==!0)throw new Error("provider signature not confirmed: "+String(r.signatureWhy||"the backend did not verify"));return r.quote}function q1(e){let t=["providerId","amount","claimer","edPointClaimer","commitHalfClaimer","viewHalfClaimer","proof","context","expiresAt"].filter(n=>e[n]===void 0||e[n]===null||e[n]==="");if(t.length)throw new Error("the order quote is missing fields: "+t.join(", "));if(e.quoteKind!=="orderQuote")throw new Error("not an order quote, but "+String(e.quoteKind));if(Number(e.expiresAt)<=Date.now())throw new Error("the order quote has expired")}var Q1=null,Z1=()=>Q1||on.base;var zs={};Be(zs,{scalarFromMoneroHex:()=>eS,spendKeysFromRevealedHalf:()=>J1});function J1({halves:e,ownSpendHalf:t,ownViewHalf:n,otherSpendPoint:r,otherViewHalf:o,revealedHalf:i}){if(!e)throw new Error("half maths is required");for(let[w,x]of Object.entries({ownSpendHalf:t,ownViewHalf:n,otherSpendPoint:r,otherViewHalf:o,revealedHalf:i}))if(x==null||x==="")throw new Error("not set: "+w);let s=BigInt(i)%e.SECP_ORDER,a=e.combineHalves(BigInt(t),s),c=e.publicHalves(a).ed,l=e.combinePublic(e.publicHalves(BigInt(t)).ed,r),u=w=>String(w).replace(/^0x/i,"").toLowerCase();if(u(c)!==u(l))throw new Error("revealed half does not match the address: (s_a + s_b)*G != the order spend key. The half is from another order or substituted - sweeping is not allowed");let f=e.combineHalves(BigInt(n),BigInt(o)),h=w=>BigInt(w).toString(16).padStart(64,"0"),m=w=>h(w).match(/../g).reverse().join("");return{privateSpendKey:m(a),privateViewKey:m(f)}}function eS(e){let t=String(e).replace(/^0x/i,"");if(!/^[0-9a-f]{64}$/.test(t))throw new Error("key is not in Monero notation: expected 64 hex");return BigInt("0x"+t.match(/../g).reverse().join(""))}Vn();var Xs=5e8;function Jo(e,{height:t=null,nowSec:n=null}={}){let r=Number(e)||0;if(r<=0)return{code:"unlocked",locked:!1,untilHeight:null,untilTime:null};if(r>=5e8){let s=n==null?Math.floor(Date.now()/1e3):Number(n),a=Number.isFinite(s)&&s>=r;return{code:a?"unlocked":"locked_time",locked:!a,untilHeight:null,untilTime:r}}let o=t==null?null:Number(t),i=o!==null&&Number.isFinite(o)&&o>=r;return{code:i?"unlocked":"locked_height",locked:!i,untilHeight:r,untilTime:null}}function Ys(e){return e?e.untilTime!==null&&e.untilTime!==void 0?Number(e.untilTime):e.untilHeight!==null&&e.untilHeight!==void 0?Number(e.untilHeight):-1:-1}var Ft={};Be(Ft,{ED_ORDER:()=>wt,PEDERSEN_H:()=>Fm,UNLOCK_TIME_BLOCK_MAX:()=>Xs,amountMaskCommitment:()=>Dm,bytesToHex:()=>tr,decodeAmount:()=>Wm,decodeMask:()=>Vl,derivedOutputKey:()=>Mm,fetchBlock:()=>zm,fetchTransactions:()=>Xm,findOurOutputs:()=>Vm,hashToScalar:()=>Mr,hexToBytes:()=>er,keccak:()=>$l,keyDerivation:()=>qs,laterBoundary:()=>Ys,matchTransaction:()=>Ym,scalarFromBytesLE:()=>Qs,scalarFromHexLE:()=>zl,scalarToBytesLE:()=>Gs,scanRange:()=>sS,txKeysFromExtra:()=>Gl,txPublicKeyFromExtra:()=>oS,unlockStateOf:()=>Jo,varint:()=>Xl,viewKeyFormForAddress:()=>rS,viewSecretCandidates:()=>Yl});Uc();Gc();function $l(e){return ps(e)}var wt=_e.Point.CURVE().n,Fm="8b655970153799af2aeadc9ff1add0ea6c7251d54154cfa92c173a0dd39c1f94",nS=_e.Point.fromHex(Fm);function Hm(e,t){let n=(BigInt(t)%wt+wt)%wt;return n===0n?_e.Point.ZERO:e.multiply(n)}function Dm(e,t){let n=BigInt(e);if(n<0n)throw new Error("the amount must not be negative");return Hm(_e.Point.BASE,t).add(Hm(nS,n)).toHex()}function er(e){let t=String(e).trim().replace(/^0x/,"");if(t.length%2)throw new Error("odd hex length");let n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++)n[r]=parseInt(t.substr(r*2,2),16);return n}function tr(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function Qs(e){let t=Uint8Array.from(e).reverse();return BigInt("0x"+tr(t))}function zl(e){return Qs(er(e))}function Gs(e,t=32){let n=new Uint8Array(t),r=BigInt(e);for(let o=0;o<t;o++)n[o]=Number(r&0xffn),r>>=8n;return n}function Mr(...e){let t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return Qs($l(n))%wt}function Xl(e){let t=[],n=BigInt(e);for(;n>=0x80n;)t.push(Number(n&0x7fn|0x80n)),n>>=7n;return t.push(Number(n)),new Uint8Array(t)}function Um(e){return _e.Point.fromHex(String(e).replace(/^0x/,""))}function Yl(e){if(typeof e=="bigint")return[["number",e%wt]];let t=String(e).replace(/^0x/,"");return/^[0-9a-fA-F]{64}$/.test(t)?[["BE-number",BigInt("0x"+t)%wt],["LE-bytes",zl(t)%wt]]:[["unparsed",null]]}function rS(e,t){let n=String(t||"").toLowerCase();if(!n)return null;for(let[r,o]of Yl(e))if(o!==null&&_e.Point.BASE.multiply(o).toHex().toLowerCase()===n)return r;return!1}function qs(e,t){let n=Um(e),r=(typeof t=="bigint"?t:zl(String(t).replace(/^0x/,"")))%wt,o=n.multiply(r);return er(o.multiply(8n).toHex())}function Mm(e,t,n){let r=Mr(e,Xl(t));return _e.Point.BASE.multiply(r).add(Um(n)).toHex()}function Lm(e,t){let n=0n,r=0n,o=t;for(let i=0;i<10&&o<e.length;i++){let s=e[o++];if(n|=BigInt(s&127)<<r,(s&128)===0)return{value:n,next:o};r+=7n}return null}function Gl(e){let t=Array.isArray(e)?Uint8Array.from(e):er(e),n=[],r=[],o=0;for(;o<t.length;){let i=t[o++];if(i===0){for(;o<t.length&&t[o]===0;)o++;continue}if(i===1){if(o+32>t.length)break;n.push(tr(t.subarray(o,o+32))),o+=32;continue}if(i===2||i===3){let s=Lm(t,o);if(!s||s.value>BigInt(t.length-s.next))break;o=s.next+Number(s.value);continue}if(i===4){let s=Lm(t,o);if(!s||s.value>BigInt(Math.floor((t.length-s.next)/32)))break;o=s.next;for(let a=0;a<Number(s.value);a++)r.push(tr(t.subarray(o,o+32))),o+=32;continue}break}return{txPublicKeys:n,additionalPublicKeys:r}}function oS(e){return Gl(e).txPublicKeys[0]||null}function Km(e){return Number(e)>=4}function iS(e,t){let n=Mr(e);return t==="mask"?n:Mr(er(n.toString(16).padStart(64,"0")))}function jm(e,t,n,r){if(Km(n)){if(r==="mask")return Mr(new TextEncoder().encode("commitment_mask"),t);let s=er(e),a=new TextEncoder().encode(r),c=new Uint8Array(a.length+t.length);c.set(a,0),c.set(t,a.length);let l=$l(c),u=s.slice();for(let f=0;f<u.length&&f<l.length;f++)u[f]^=l[f];return Qs(u)}let o=er(e);return(BigInt("0x"+tr(o))%wt-iS(t,r)+wt)%wt}function Wm(e,t,n){return jm(e,t,n,"amount")}function Vl(e,t,n){return jm(e,t,n,"mask")}function Vm({txPublicKey:e=null,txPublicKeys:t=null,additionalPublicKeys:n=[],viewSecretHex:r,spendPubHex:o,outputs:i,ecdhAmounts:s=[],ecdhMasks:a=[],outPk:c=[],rctVersion:l=2}){let u=Array.isArray(t)?t.filter(Boolean):e?[e]:[],f=Array.isArray(n)?n:[];if(!u.length&&!f.length)throw new Error("the transaction has no public key (extra tag 0x01/0x04) - nothing to parse");let h=Yl(r).filter(([,x])=>x!==null),m=h[0]||["unparsed",null];for(let[x,y]of h){let k=[];for(let g of u)try{k.push(qs(g,y))}catch{}let I=[];for(let g of i){let P=k.slice();if(f[g.index])try{P.push(qs(f[g.index],y))}catch{}for(let E of P){let B=Mr(E,Xl(g.index));if(Mm(E,g.index,o).toLowerCase()!==String(g.key).toLowerCase())continue;let b=s[g.index]?Wm(s[g.index],Gs(B),l):null,S=Km(l)?Vl(null,Gs(B),l):a[g.index]?Vl(a[g.index],Gs(B),l):null,v=!1;if(b!==null&&S!==null&&c[g.index])try{v=Dm(b,S).toLowerCase()===String(c[g.index]).replace(/^0x/,"").toLowerCase()}catch{v=!1}I.push({index:g.index,key:g.key,amountAtomic:b,maskAtomic:S,amountVerified:v,derivation:tr(E)});break}}if(I.length)return{derivation:I[0].derivation,outputs:I,viewKeyForm:x}}let w=null;if(m[1]!==null&&u.length)try{w=tr(qs(u[0],m[1]))}catch{w=null}return{derivation:w,outputs:[],viewKeyForm:m[0]}}var $m=e=>{let t=String(e);for(;t.endsWith("/");)t=t.slice(0,-1);return t};async function zm(e,t,n=globalThis.fetch,r=8e3){let o=typeof AbortSignal<"u"&&AbortSignal.timeout?AbortSignal.timeout(Math.max(1,Number(r)||8e3)):void 0,s=await(await n(`${$m(e)}/json_rpc`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:"block",method:"get_block",params:{height:t}}),signal:o})).json();if(s&&String(s.status||"").toUpperCase()==="BUSY")throw new Error(`block ${t}: daemon is BUSY`);if(!s.result)throw new Error(`block ${t} not received: ${s.error?s.error.message:"empty answer"}`);if(String(s.result.status||"").toUpperCase()==="BUSY")throw new Error(`block ${t}: daemon is BUSY`);if(s.result.json===void 0||s.result.json===null||s.result.json==="")throw new Error(`block ${t}: no decoded body`);return s.result}async function Xm(e,t,n=globalThis.fetch,r=8e3){if(!t.length)return[];let o=typeof AbortSignal<"u"&&AbortSignal.timeout?AbortSignal.timeout(Math.max(1,Number(r)||8e3)):void 0,s=await(await n(`${$m(e)}/get_transactions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txs_hashes:t,decode_as_json:!0}),signal:o})).json();if(s&&String(s.status||"").toUpperCase()==="BUSY")throw new Error("transactions-busy");let a=Array.isArray(s&&s.txs)?s.txs:[],c=Array.isArray(s&&s.txs_as_json)?s.txs_as_json:[],l=[...new Set(t.map(m=>String(m).replace(/^0x/,"").toLowerCase()))],u=new Map;for(let m of a){let w=String(m&&m.tx_hash||"").replace(/^0x/,"").toLowerCase();if(w){if(u.has(w))throw new Error("transactions-duplicate: "+w);u.set(w,m)}}let f=l.filter(m=>!u.has(m));if(f.length)throw new Error("transactions-missing: "+f.length);if(u.size!==l.length)throw new Error("transactions-extra: "+(u.size-l.length));if(c.length!==a.length)throw new Error("transactions-undecoded");let h=new Map(a.map((m,w)=>[String(m&&m.tx_hash||"").replace(/^0x/,"").toLowerCase(),w]));return l.map(m=>{let w=u.get(m)||{},x=c[h.get(m)],y=typeof x=="string"?JSON.parse(x):x;return y.tx_hash=w.tx_hash||y.tx_hash||null,y.block_height=w.block_height??null,y.confirmations=w.confirmations??null,y.in_pool=w.in_pool??null,y})}function Ym(e,t,{height:n=null,tipHeight:r=null,nowSec:o=null}={}){let i=[],s=Gl(e.extra);if(!s.txPublicKeys.length&&!s.additionalPublicKeys.length)return i;let a=n??e.block_height??null,c=r==null?a:Number(r),l=Jo(e.unlock_time,{height:c,nowSec:o}),u=k=>((k.target||{}).tagged_key||k.target||{}).key,f=(e.vout||[]).map((k,I)=>({index:I,key:u(k)})),h=(e.rct_signatures||{}).ecdhInfo||[],m=h.map(k=>k.amount),w=h.map(k=>k.mask),x=(e.rct_signatures||{}).outPk||[],y=(e.rct_signatures||{}).type||2;for(let k of t){let I=Vm({txPublicKeys:s.txPublicKeys,additionalPublicKeys:s.additionalPublicKeys,viewSecretHex:k.viewSecret,spendPubHex:k.spendPub,outputs:f,ecdhAmounts:m,ecdhMasks:w,outPk:x,rctVersion:Number(y)||1});I.outputs.length&&i.push({address:k.address,index:k.index??null,outputs:I.outputs,derivation:I.derivation,viewKeyForm:I.viewKeyForm,unlockTime:Number(e.unlock_time)||0,unlock:l})}return i}async function sS({daemonUrl:e,fromHeight:t,toHeight:n,watched:r,log:o=()=>{},concurrency:i=4,nowSec:s=null,tipHeight:a=null,fetchImpl:c=globalThis.fetch}){let l=Number(t),u=Number(n);if(!(l>=0)||!(u>=l))throw new Error("bad height range: "+t+".."+n);let f=new Map;for(let k of r)f.set(k.address,{address:k.address,receivedAtomic:0n,lockedAtomic:0n,lockedUntil:null,lockedTxids:[],txids:[],bestHeight:null,outputs:0,viewKeyForm:null});let h=[];for(let k=l;k<=u;k++)h.push(k);let m=[],w=0,x=async()=>{for(;w<h.length;){let k=h[w++];try{let I=await zm(e,k,c),g=I.json?(typeof I.json=="string"?JSON.parse(I.json):I.json).tx_hashes||[]:[];if(!g.length)continue;let P=await Xm(e,g,c);for(let E of P)for(let B of Ym(E,r,{height:k,tipHeight:a??u,nowSec:s})){let p=f.get(B.address);if(!p)continue;B.viewKeyForm&&(p.viewKeyForm=B.viewKeyForm);let b=!!(B.unlock&&B.unlock.locked),S=String(E.tx_hash||"").replace(/^0x/,"");for(let v of B.outputs){let H=v.amountVerified&&v.amountAtomic||0n;b?(p.lockedAtomic+=H,S&&!p.lockedTxids.includes(S)&&p.lockedTxids.push(S),Ys(B.unlock)>Ys(p.lockedUntil)&&(p.lockedUntil=B.unlock)):(p.receivedAtomic+=H,p.outputs+=1),S&&!p.txids.includes(S)&&p.txids.push(S),(p.bestHeight===null||k>p.bestHeight)&&(p.bestHeight=k)}}}catch(I){m.push(k),o({event:"indexer_block_error",height:k,error:String(I.message).slice(0,160)})}}};await Promise.all(Array.from({length:Math.max(1,Math.min(i,h.length))},x));let y=[...new Set(m)].sort((k,I)=>k-I);return{fromHeight:l,toHeight:u,results:Array.from(f.values()),complete:y.length===0,missingHeights:y,...y.length?{incompleteReason:"blocks-unreadable"}:{}}}var ei={};Be(ei,{UNLOCK_TIME_BLOCK_MAX:()=>Xs,decodeAddressKeys:()=>cS,scalarToLeHex:()=>lS,unlockStateOf:()=>Jo,viewKeyMatchesAddress:()=>uS});Vn();var aS=Object.fromEntries(Object.entries(ms).map(([e,t])=>[t.primary,e])),ql=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join("");function cS(e){let t=ws(String(e??"").trim());if(!t||t.length<69)throw new Error("not a Monero address: "+(t?t.length+" bytes":"not base58"));let n=t[0];return{network:aS[n]||null,netByte:n,spendPub:ql(t.slice(1,33)),viewPub:ql(t.slice(33,65))}}function lS(e,t=32){let n=Number(t);if(!Number.isInteger(n)||n<=0)throw new Error("scalarToLeHex: bad width");let r;try{r=BigInt(e)}catch{throw new Error("scalarToLeHex: not an integer")}if(r<0n||r>=1n<<BigInt(n*8))throw new Error("scalarToLeHex: value does not fit "+n+" bytes");let o=new Uint8Array(n),i=r;for(let s=0;s<n;s++)o[s]=Number(i&0xffn),i>>=8n;return ql(o)}function uS(e,t,n){let r=String(t||"").trim().toLowerCase().replace(/^0x/,"");if(!r)return null;if(!n||typeof n.publicHalves!="function")throw new Error("viewKeyMatchesAddress: createHalves is required");return String(n.publicHalves(e).ed||"").toLowerCase().replace(/^0x/,"")===r}var Zs=["awaiting_funding","funded","maker_locking","xmr_locked","ready","claimed","swept"];var Js=["balance","gas","allowance","consent","network","settlement-network","stale","deadline","range","size","escrow-state","escrow-points","counterparty","slots","unchecked","unknown"],Kr=["not-implemented","bad-input","wallet-not-connected","wallet-rejected","wrong-chain","wrong-account","quote-unavailable","quote-refused","address-denied","quote-stale","quote-signature-invalid","quote-key-mismatch","quote-field-unbound","quote-expired","quote-too-short","quote-registry-unchecked","quote-key-unknown","quote-provider-mismatch","quote-provider-not-allowed","quote-factory-unchecked","quote-factory-unknown","quote-factory-mismatch","quote-factory-code-unknown","quote-cashier-mismatch","recovery-declined","recovery-failed","storage-unavailable","server-unavailable","server-refused","claim-unknown","funding-pending","xmr-timeout","xmr-locked","xmr-nodes-disagree","xmr-no-nodes","xmr-underpaid","xmr-too-late","xmr-address-mismatch","contract-reverted","insufficient-funds","sweep-fee-too-high","sweep-fee-unknown","gas-refused-by-maker","gas-not-arrived","gas-too-little","unknown"];var dS=Object.freeze({"not-implemented":{retryable:!1,side:"caller"},"bad-input":{retryable:!1,side:"caller"},"wallet-not-connected":{retryable:!1,side:"wallet"},"wallet-rejected":{retryable:!1,side:"wallet"},"wrong-chain":{retryable:!1,side:"wallet"},"wrong-account":{retryable:!1,side:"wallet"},"quote-unavailable":{retryable:!0,side:"provider"},"quote-refused":{retryable:!1,side:"provider"},"address-denied":{retryable:!1,side:"caller"},"quote-stale":{retryable:!0,side:"provider"},"quote-signature-invalid":{retryable:!1,side:"provider"},"quote-key-mismatch":{retryable:!1,side:"provider"},"quote-field-unbound":{retryable:!1,side:"provider"},"quote-expired":{retryable:!0,side:"provider"},"quote-too-short":{retryable:!0,side:"provider"},"quote-registry-unchecked":{retryable:!0,side:"chain"},"quote-key-unknown":{retryable:!1,side:"chain"},"quote-provider-mismatch":{retryable:!1,side:"chain"},"quote-provider-not-allowed":{retryable:!1,side:"caller"},"quote-factory-unchecked":{retryable:!0,side:"chain"},"quote-factory-unknown":{retryable:!1,side:"chain"},"quote-factory-mismatch":{retryable:!1,side:"chain"},"quote-factory-code-unknown":{retryable:!1,side:"chain"},"quote-cashier-mismatch":{retryable:!1,side:"chain"},"recovery-declined":{retryable:!1,side:"wallet"},"recovery-failed":{retryable:!1,side:"wallet"},"storage-unavailable":{retryable:!0,side:"service"},"server-unavailable":{retryable:!0,side:"service"},"server-refused":{retryable:!1,side:"service"},"claim-unknown":{retryable:!1,side:"chain"},"funding-pending":{retryable:!0,side:"chain"},"xmr-timeout":{retryable:!0,side:"chain"},"xmr-locked":{retryable:!0,side:"chain"},"xmr-nodes-disagree":{retryable:!0,side:"chain"},"xmr-no-nodes":{retryable:!0,side:"chain"},"xmr-underpaid":{retryable:!1,side:"chain"},"xmr-too-late":{retryable:!1,side:"chain"},"xmr-address-mismatch":{retryable:!1,side:"caller"},"contract-reverted":{retryable:!1,side:"chain"},"insufficient-funds":{retryable:!1,side:"wallet"},"sweep-fee-too-high":{retryable:!1,side:"chain"},"sweep-fee-unknown":{retryable:!0,side:"chain"},"gas-refused-by-maker":{retryable:!1,side:"provider"},"gas-not-arrived":{retryable:!0,side:"chain"},"gas-too-little":{retryable:!1,side:"provider"},unknown:{retryable:!1,side:"unknown"}}),fS={"in-range":"range","above-max":"range","below-min":"range","range-unstated":"range","size-unstated":"size","amount-unstated":"size","unit-mismatch":"range","balance-enough":"balance","balance-short":"balance","balance-unchecked":"balance","gas-enough":"gas","gas-short":"gas","reserve-unstated":"gas","native-unchecked":"gas","not-needed":"allowance",allowed:"allowance","allowance-short":"allowance","allowance-unchecked":"allowance","consent-missing":"consent","network-match":"network","network-unknown":"network","wallet-unknown":"network","wallet-network":"network","settlement-network":"settlement-network","real-provider":"counterparty","stand-in-provider":"counterparty","standin-on-production":"counterparty",fresh:"stale",stale:"stale","no-ttl":"stale",untimed:"stale",expired:"stale","deadlines-ok":"deadline","deadlines-unstated":"deadline","ready-by-in-past":"deadline","t1-not-after-ready-by":"deadline","ready-window-too-short":"deadline","claim-window-too-short":"deadline","deadline-too-far":"deadline",new:"escrow-state","already-funded":"escrow-state","already-claimed":"escrow-state","already-refunded":"escrow-state","state-unchecked":"escrow-state","off-step":"escrow-state","points-match":"escrow-points","point-mismatch":"escrow-points","commit-mismatch":"escrow-points","points-unchecked":"escrow-points","slots-match":"slots","slots-unchecked":"slots",unchecked:"unchecked"},Gm=e=>fS[e]||"unknown";fe();var Iu={};Be(Iu,{ASYNC:()=>Me,BALANCE_OF_SELECTOR:()=>ly,SETTLES:()=>_u,SYNC:()=>ti,balances:()=>i2,carriesNativeVerdict:()=>l2,providerSettles:()=>dy,requireAsyncProvider:()=>a2,requireProvider:()=>c2,requireSyncProvider:()=>s2,routeProviderFor:()=>ma,routeProviders:()=>qr,sameChain:()=>r2,vm:()=>n2,walletChainId:()=>cy});var ti="sync",Me="async";var Ql=e=>!e||typeof e!="object"?{ok:!1,reason:"provider-absent"}:e.shape!==ti&&e.shape!==Me?{ok:!1,reason:"provider-shape-unknown",shape:e.shape===void 0?null:e.shape}:e.shape===Me&&typeof e.settled!="function"?{ok:!1,reason:"provider-incomplete",shape:Me,missing:"settled"}:{ok:!0,shape:e.shape};Ee();var qm="NinseiEscrowFactory";var pS=["EIP712Domain(","string name,","string version,","uint256 chainId,","address verifyingContract)"],Qm=pS.join(""),ta=[["provider","address"],["quoteKey","address"],["registry","address"],["cashier","address"],["locker","address"],["claimer","address"],["amount","uint256"],["readyBy","uint64"],["t1","uint64"],["salt","bytes32"],["commitHalfClaimer","bytes32"],["edPointClaimer","bytes32"],["chainId","uint256"],["feeBps","uint256"],["fee","uint256"],["feeRecipient","address"],["validUntil","uint64"],["nonce","uint256"],["xmrAmount","uint256"],["claimTip","uint256"],["commitHalfLocker","bytes32"],["edPointLocker","bytes32"],["edViewPointLocker","bytes32"]],Zm="OrderQuote("+ta.map(e=>e[1]+" "+e[0]).join(",")+")",An=e=>{throw new Error(e)},ea=e=>new TextEncoder().encode(String(e)),na=(...e)=>{let t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n},Jl=e=>{let t=String(e).replace(/^0x/,"");t.length%2&&An("eip712-odd-hex");let n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++){let o=parseInt(t.slice(r*2,r*2+2),16);Number.isNaN(o)&&An("eip712-bad-hex"),n[r]=o}return n},hS=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},mS=e=>{if(typeof e=="bigint")return e;let t=String(e??"").trim();if(/^0x[0-9a-fA-F]+$/.test(t)||/^[0-9]+$/.test(t))return BigInt(t);An("eip712-bad-number")},Zl=(e,t)=>{let n=mS(e);n<0n&&An("eip712-negative"),n>=1n<<BigInt(t)&&An("eip712-overflow");let r=new Uint8Array(32),o=n;for(let i=31;i>=0&&o>0n;i--)r[i]=Number(o&0xffn),o>>=8n;return r},Jm=e=>{let t=String(e??"").trim();/^(0x)?[0-9a-fA-F]{40}$/.test(t)||An("eip712-bad-address");let n=new Uint8Array(32);return n.set(Jl(t.replace(/^0x/,"")),12),n},wS=e=>{let t=String(e??"").trim();return/^(0x)?[0-9a-fA-F]{64}$/.test(t)||An("eip712-bad-bytes32"),Jl(t.replace(/^0x/,""))},yS=(e,t)=>{if(e==="address")return Jm(t);if(e==="bytes32")return wS(t);if(e==="uint64")return Zl(t,64);if(e==="uint256")return Zl(t,256);An("eip712-bad-type")},ew=e=>{let t=[];for(let[n]of ta){let r=e?e[n]:void 0;(r==null||r==="")&&t.push(n)}return e&&(e.factory===void 0||e.factory===null||e.factory==="")&&t.push("factory"),e&&(e.signature===void 0||e.signature===null||e.signature==="")&&t.push("signature"),t};function bS({crypto:e,quote:t}){return e.keccak256(na(e.keccak256(ea(Qm)),e.keccak256(ea(qm)),e.keccak256(ea("1")),Zl(t.chainId,256),Jm(t.factory)))}function gS({crypto:e,quote:t}){let n=[e.keccak256(ea(Zm))];for(let[r,o]of ta)n.push(yS(o,t?t[r]:void 0));return e.keccak256(na(...n))}function tw({crypto:e,quote:t}){return e.keccak256(na(Uint8Array.from([25,1]),bS({crypto:e,quote:t}),gS({crypto:e,quote:t})))}function nw({crypto:e,quote:t}){try{if(ew(t).length)return null;let n=Jl(String(t.signature).replace(/^0x/,""));if(n.length!==65)return null;let r=n[64];if(r>=27&&(r-=27),r!==0&&r!==1)return null;let o=tw({crypto:e,quote:t}),s=e.secp256k1.Signature.fromBytes(na(n.slice(0,32),n.slice(32,64))).addRecoveryBit(r).recoverPublicKey(o).toBytes(!1);return hS(e.keccak256(s.slice(1)).slice(12))}catch{return null}}var rw=["Gnosis","Protocol"].join(" "),ow="v2",nr="0x9008D19f58AAbD9eD0D60971565AA8510560ab41",iw="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",xS=["EIP712Domain(","string name,","string version,","uint256 chainId,","address verifyingContract)"],kS=xS.join(""),jr=[["sellToken","address"],["buyToken","address"],["receiver","address"],["sellAmount","uint256"],["buyAmount","uint256"],["validTo","uint32"],["appData","bytes32"],["feeAmount","uint256"],["kind","string"],["partiallyFillable","bool"],["sellTokenBalance","string"],["buyTokenBalance","string"]],SS="Order("+jr.map(e=>e[1]+" "+e[0]).join(",")+")";var At=e=>{throw new Error(e)},ni=e=>new TextEncoder().encode(String(e)),ia=(...e)=>{let t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n},ra=e=>{let t=String(e).replace(/^0x/,"");t.length%2&&At("cow-odd-hex");let n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++){let o=parseInt(t.slice(r*2,r*2+2),16);Number.isNaN(o)&&At("cow-bad-hex"),n[r]=o}return n},sw=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},vS=e=>{if(typeof e=="bigint")return e;let t=String(e??"").trim();if(/^0x[0-9a-fA-F]+$/.test(t)||/^[0-9]+$/.test(t))return BigInt(t);At("cow-bad-number")},oa=(e,t)=>{let n=vS(e);n<0n&&At("cow-negative"),n>=1n<<BigInt(t)&&At("cow-overflow");let r=new Uint8Array(32),o=n;for(let i=31;i>=0&&o>0n;i--)r[i]=Number(o&0xffn),o>>=8n;return r},aw=e=>{let t=String(e??"").trim();/^(0x)?[0-9a-fA-F]{40}$/.test(t)||At("cow-bad-address");let n=new Uint8Array(32);return n.set(ra(t.replace(/^0x/,"")),12),n},ES=e=>{let t=String(e??"").trim();return/^(0x)?[0-9a-fA-F]{64}$/.test(t)||At("cow-bad-bytes32"),ra(t.replace(/^0x/,""))},AS=e=>{let t=new Uint8Array(32);return e===!0||e==="true"||e===1||e==="1"?t[31]=1:e===!1||e==="false"||e===0||e==="0"||e===void 0||e===null?t[31]=0:At("cow-bad-bool"),t},_S=e=>Q(ni(e)),IS=(e,t)=>{if(e==="address")return aw(t);if(e==="bytes32")return ES(t);if(e==="uint32")return oa(t,32);if(e==="uint256")return oa(t,256);if(e==="bool")return AS(t);if(e==="string")return _S(t);At("cow-bad-type")},cw=e=>{let t=[];for(let[n]of jr){let r=e?e[n]:void 0;(r==null||r==="")&&t.push(n)}return t},NS=({chainId:e,settlement:t=nr})=>Q(ia(Q(ni(kS)),Q(ni(rw)),Q(ni(ow)),oa(e,256),aw(t))),TS=e=>{let t=[Q(ni(SS))];for(let[n,r]of jr)t.push(IS(r,e?e[n]:void 0));return Q(ia(...t))},PS=({order:e,chainId:t,settlement:n=nr})=>Q(ia(Uint8Array.from([25,1]),NS({chainId:t,settlement:n}),TS(e))),lw=e=>sw(PS(e)),uw=({digest:e,owner:t,validTo:n})=>{let r=ra(e);r.length!==32&&At("cow-bad-digest");let o=ra(t);o.length!==20&&At("cow-bad-owner");let i=oa(n,32).slice(28);return sw(ia(r,o,i))},dw=({order:e,chainId:t,settlement:n=nr})=>({domain:{name:rw,version:ow,chainId:Number(t),verifyingContract:n},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],Order:jr.map(([r,o])=>({name:r,type:o}))},primaryType:"Order",message:{sellToken:e.sellToken,buyToken:e.buyToken,receiver:e.receiver,sellAmount:String(e.sellAmount),buyAmount:String(e.buyAmount),validTo:Number(e.validTo),appData:e.appData,feeAmount:String(e.feeAmount),kind:String(e.kind),partiallyFillable:!!e.partiallyFillable,sellTokenBalance:String(e.sellTokenBalance),buyTokenBalance:String(e.buyTokenBalance)}});fe();var BS=()=>typeof fetch=="function"?fetch:null;function nt({apiBase:e,fetchImpl:t=null,timeoutMs:n=2e4}){let r=t||BS();return{async json(o,{signal:i=null,method:s="GET",headers:a=null,body:c=null}={}){if(!e)throw new d("server-unavailable",{why:"no-api-base"});if(typeof r!="function")throw new d("bad-input",{field:"fetch"});let l=new AbortController,u=setTimeout(()=>l.abort(),n),f=()=>l.abort();i&&i.addEventListener("abort",f,{once:!0});try{let h={signal:l.signal,method:s,headers:{accept:"application/json",...a||{}}};c!=null&&(h.body=c);let m=await r(e+o,h);if(!m||typeof m.ok!="boolean")throw new d("server-unavailable",{why:"bad-response"});if(!m.ok)throw new d("server-unavailable",{status:m.status});return await m.json()}catch(h){throw h instanceof d?h:new d("server-unavailable",{why:h&&h.name==="AbortError"?"timeout":"fetch"})}finally{clearTimeout(u),i&&i.removeEventListener("abort",f)}},async tryJson(o,{signal:i=null,method:s="GET",headers:a=null,body:c=null}={}){if(!e)throw new d("server-unavailable",{why:"no-api-base"});if(typeof r!="function")throw new d("bad-input",{field:"fetch"});let l=new AbortController,u=setTimeout(()=>l.abort(),n),f=()=>l.abort();i&&i.addEventListener("abort",f,{once:!0});try{let h={signal:l.signal,method:s,headers:{accept:"application/json",...a||{}}};c!=null&&(h.body=c);let m=await r(e+o,h);if(!m||typeof m.ok!="boolean")throw new d("server-unavailable",{why:"bad-response"});let w=null;try{w=await m.json()}catch{throw new d("server-unavailable",{why:"body"})}return{ok:m.ok,status:m.status,body:w}}catch(h){throw h instanceof d?h:new d("server-unavailable",{why:h&&h.name==="AbortError"?"timeout":"fetch"})}finally{clearTimeout(u),i&&i.removeEventListener("abort",f)}}}}var eu=Object.freeze({1:{slug:"mainnet",orderbook:"https://api.cow.fi/mainnet"},100:{slug:"xdai",orderbook:"https://api.cow.fi/xdai"},42161:{slug:"arbitrum_one",orderbook:"https://api.cow.fi/arbitrum_one"},8453:{slug:"base",orderbook:"https://api.cow.fi/base"},56:{slug:"bnb",orderbook:"https://api.cow.fi/bnb"},11155111:{slug:"sepolia",orderbook:"https://api.cow.fi/sepolia"}}),OS=["presignaturePending","open","fulfilled","cancelled","expired"],fw=["fulfilled","cancelled","expired"],pw="fulfilled";var Ae=(e,t={})=>({ok:!1,code:e,params:t}),tu=e=>{let t=eu[Number(e)];return t?t.orderbook:null},sa=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),CS=e=>/^(0x)?[0-9a-fA-F]{64}$/.test(String(e||""));function hw(e={}){let t=Number(e.chainId);if(tu(t)===null)return{...Ae("cow-unknown-network",{chainId:Number.isFinite(t)?t:null}),known:Object.keys(eu).map(Number)};let n=e.owner,r=e.receiver===void 0||e.receiver===null?n:e.receiver,o={sellToken:e.sellToken,buyToken:e.buyToken,receiver:r||n,sellAmount:e.sellAmountWei,buyAmount:e.buyAmountWei,validTo:e.validTo,appData:e.appData===void 0||e.appData===null?"0x"+"00".repeat(32):e.appData,feeAmount:e.feeAmountWei===void 0||e.feeAmountWei===null?"0":e.feeAmountWei,kind:e.kind===void 0||e.kind===null?"sell":e.kind,partiallyFillable:e.partiallyFillable===void 0||e.partiallyFillable===null?!1:e.partiallyFillable,sellTokenBalance:e.sellTokenBalance===void 0||e.sellTokenBalance===null?"erc20":e.sellTokenBalance,buyTokenBalance:e.buyTokenBalance===void 0||e.buyTokenBalance===null?"erc20":e.buyTokenBalance},i=cw(o);if(sa(n)||i.push("owner"),CS(o.appData)||i.push("appData"),(!sa(o.sellToken)||!sa(o.buyToken)||!sa(o.receiver))&&i.push("token"),i.length)return Ae("cow-bad-order",{missing:[...new Set(i)]});try{let s=lw({order:o,chainId:t,settlement:nr}),a=uw({digest:s,owner:n,validTo:o.validTo}),c=dw({order:o,chainId:t,settlement:nr});return{ok:!0,chainId:t,owner:n,order:o,digest:s,uid:a,typedData:c}}catch(s){return Ae("cow-bad-order",{why:String(s&&s.message?s.message:s)})}}function RS({order:e,signature:t,owner:n,signingScheme:r="eip712",from:o=null}){return{sellToken:e.sellToken,buyToken:e.buyToken,receiver:e.receiver,sellAmount:String(e.sellAmount),buyAmount:String(e.buyAmount),validTo:Number(e.validTo),appData:String(e.appData),feeAmount:String(e.feeAmount),kind:String(e.kind),partiallyFillable:!!e.partiallyFillable,sellTokenBalance:String(e.sellTokenBalance),buyTokenBalance:String(e.buyTokenBalance),signingScheme:r,signature:t,from:o||n}}function HS(e={}){let t=hw(e);return t.ok?{ok:!0,provider:"cowswap",venue:"CoWSwap",shape:Me,route:"cowswap",expectedOutWei:String(t.order.buyAmount),order:t.order,typedData:t.typedData,digest:t.digest,uid:t.uid,owner:t.owner,endsWith:{kind:"order-status",settledWhen:pw,final:[...fw],endpoint:"/api/v1/orders/{uid}"}}:t}async function LS({typedData:e,wallet:t,address:n=null}={}){if(!e||typeof e!="object")return Ae("cow-bad-order",{field:"typedData"});try{if(t&&typeof t.signTypedData=="function"){let o=await t.signTypedData(e);return typeof o!="string"||!/^0x[0-9a-fA-F]{130}$/.test(o)?Ae("cow-sign-failed",{why:"bad-signature-shape"}):{ok:!0,signature:o}}let r=t&&typeof t.driver=="function"?t.driver():null;if(r&&typeof r.request=="function"){let o=n||(typeof t.address=="function"?await t.address():null),i=await r.request({method:"eth_signTypedData_v4",params:[o,JSON.stringify(e)]});return typeof i!="string"||!/^0x[0-9a-fA-F]{130}$/.test(i)?Ae("cow-sign-failed",{why:"bad-signature-shape"}):{ok:!0,signature:i}}return Ae("cow-sign-failed",{why:"no-wallet"})}catch(r){return Ae("cow-sign-failed",{why:String(r&&r.code||r&&r.message||r)})}}async function FS({order:e,signature:t,owner:n,chainId:r,fetchImpl:o=null,timeoutMs:i=2e4,signingScheme:s="eip712",from:a=null}={}){let c=tu(r);if(c===null)return Ae("cow-unknown-network",{chainId:Number(r)});if(typeof t!="string"||!/^0x[0-9a-fA-F]{130}$/.test(t))return Ae("cow-bad-order",{field:"signature"});let l=nt({apiBase:c,fetchImpl:o,timeoutMs:i}),u=JSON.stringify(RS({order:e,signature:t,owner:n,signingScheme:s,from:a})),f;try{f=await l.tryJson("/api/v1/orders",{method:"POST",headers:{"content-type":"application/json"},body:u})}catch(h){return Ae("cow-unreachable",{why:String(h&&h.params&&h.params.why||h&&h.code||h)})}return!f||typeof f.ok!="boolean"?Ae("cow-bad-response",{where:"submit"}):f.ok?typeof f.body!="string"||!/^0x[0-9a-fA-F]{112}$/.test(f.body)?Ae("cow-bad-response",{where:"submit",got:typeof f.body}):{ok:!0,uid:f.body}:Ae("cow-refused",{status:f.status,reason:f.body&&f.body.errorType?f.body.errorType:null})}async function mw({uid:e,chainId:t,fetchImpl:n=null,timeoutMs:r=2e4}={}){let o=tu(t);if(o===null)return Ae("cow-unknown-network",{chainId:Number(t)});if(typeof e!="string"||!/^0x[0-9a-fA-F]{112}$/.test(e))return Ae("cow-bad-order",{field:"uid"});let i=nt({apiBase:o,fetchImpl:n,timeoutMs:r}),s;try{s=await i.tryJson("/api/v1/orders/"+e)}catch(c){return Ae("cow-unreachable",{why:String(c&&c.params&&c.params.why||c&&c.code||c)})}if(!s||typeof s.ok!="boolean")return Ae("cow-bad-response",{where:"status"});if(s.status===404)return Ae("cow-order-unknown",{uid:e});if(!s.ok)return Ae("cow-refused",{status:s.status});let a=s.body&&s.body.status;return typeof a!="string"||!OS.includes(a)?Ae("cow-bad-response",{where:"status",got:typeof a=="string"?a:null}):{ok:!0,status:a,order:s.body}}async function DS(e={},t={}){let{uid:n,chainId:r}=e;if(typeof n!="string"||!/^0x[0-9a-fA-F]{112}$/.test(n))return Ae("cow-bad-order",{field:"uid"});let o=typeof t.now=="function"?t.now:()=>Date.now(),i=typeof t.sleep=="function"?t.sleep:u=>new Promise(f=>setTimeout(f,u)),s=Number.isFinite(t.pollMs)&&t.pollMs>0?t.pollMs:5e3,a=Number.isFinite(t.timeoutMs)&&t.timeoutMs>0?t.timeoutMs:3e5,c=o(),l=null;for(;;){let u=await mw({uid:n,chainId:r,fetchImpl:t.fetchImpl,timeoutMs:t.requestTimeoutMs});if(!u.ok)return u;if(l=u.status,fw.includes(l))return{ok:!0,done:!0,settled:l===pw,status:l,uid:n};if(o()-c>=a)return Ae("cow-not-settled",{uid:n,status:l,waitedMs:o()-c});await i(s)}}function US({order:e=null,requiredOutWei:t=null,tokenUsd:n=null,referenceNativeUsd:r=null,tolerated:o=!1,gates:i=null,sellDecimals:s=null,buyDecimals:a=null,buySymbol:c=null,allowanceWei:l=null,allowanceConsent:u=!1,tokenIsNative:f=!1,symbol:h=null,decimals:m=null}={}){if(!e)return{ok:!1,blocked:!0,reason:"cow-no-order",checks:[]};let w=tt.priceGateVerdict({amountInWei:e.sellAmount,amountOutWei:e.buyAmount,inDecimals:s,outDecimals:a,tokenUsd:Number(n)>0?Number(n):null,referenceUsd:Number(r)>0?Number(r):null,stableSteps:[],tolerated:!!o,gates:i}),x={ok:!0,amountOutWei:String(e.buyAmount),price:w,wrapped:{symbol:c,decimals:a}},y=tt.dexLegVerdict(x,t),k={ok:!y.blocked,checked:y.kind!=="unchecked"&&y.kind!=="unquoted",blocks:y.blocked===!0,kind:y.kind,reason:y.reason},I=we.allowanceVerdict({tokenIsNative:f,allowanceWei:l,amountWei:e.sellAmount,consent:u===!0,symbol:h,decimals:Number.isFinite(Number(m))?Number(m):18});return{...we.signingGateVerdict([k,I]),price:w,coverage:y,allowance:I}}var ww=Object.freeze({id:"cowswap",kind:"cow",venue:"CoWSwap",shape:Me,settles:"native",networks:eu,settlement:nr,buyEthAddress:iw,orderFields:jr,plan:HS,settled:DS,buildIntent:hw,sign:LS,submit:FS,status:mw,gate:US});Ee();var MS=["Kyber","DSLO","Protocol"].join(" "),KS="1",We="0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C",jS=["EIP712Domain(","string name,","string version,","uint256 chainId,","address verifyingContract)"],WS=jS.join(""),Wr=[["salt","uint256"],["makerAsset","address"],["takerAsset","address"],["maker","address"],["receiver","address"],["allowedSender","address"],["makingAmount","uint256"],["takingAmount","uint256"],["feeConfig","uint256"],["makerAssetData","bytes"],["takerAssetData","bytes"],["getMakerAmount","bytes"],["getTakerAmount","bytes"],["predicate","bytes"],["interaction","bytes"]],VS="Order("+Wr.map(e=>e[1]+" "+e[0]).join(",")+")";var $S=[["orderHash","bytes32"],["opExpireTime","uint32"]],a5="DSOrder("+$S.map(e=>e[1]+" "+e[0]).join(",")+")";var _n=e=>{throw new Error(e)},aa=e=>new TextEncoder().encode(String(e)),ru=(...e)=>{let t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n},ou=e=>{let t=String(e??"").replace(/^0x/,"");t.length%2&&_n("kyber-odd-hex");let n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++){let o=parseInt(t.slice(r*2,r*2+2),16);Number.isNaN(o)&&_n("kyber-bad-hex"),n[r]=o}return n},zS=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},XS=e=>{if(typeof e=="bigint")return e;let t=String(e??"").trim();if(/^0x[0-9a-fA-F]+$/.test(t)||/^[0-9]+$/.test(t))return BigInt(t);_n("kyber-bad-number")},nu=(e,t)=>{let n=XS(e);n<0n&&_n("kyber-negative"),n>=1n<<BigInt(t)&&_n("kyber-overflow");let r=new Uint8Array(32),o=n;for(let i=31;i>=0&&o>0n;i--)r[i]=Number(o&0xffn),o>>=8n;return r},yw=e=>{let t=String(e??"").trim();/^(0x)?[0-9a-fA-F]{40}$/.test(t)||_n("kyber-bad-address");let n=new Uint8Array(32);return n.set(ou(t.replace(/^0x/,"")),12),n},YS=e=>{let t=String(e??"").trim();return/^(0x)?[0-9a-fA-F]{64}$/.test(t)||_n("kyber-bad-bytes32"),ou(t.replace(/^0x/,""))},GS=e=>Q(ou(e)),qS=(e,t)=>{if(e==="address")return yw(t);if(e==="bytes32")return YS(t);if(e==="uint32")return nu(t,32);if(e==="uint256")return nu(t,256);if(e==="bytes")return GS(t);_n("kyber-bad-type")},bw=e=>{let t=[];for(let[n,r]of Wr){let o=e?e[n]:void 0;(o==null||r!=="bytes"&&o==="")&&t.push(n)}return t},QS=({chainId:e,contract:t=We})=>Q(ru(Q(aa(WS)),Q(aa(MS)),Q(aa(KS)),nu(e,256),yw(t))),ZS=e=>{let t=[Q(aa(VS))];for(let[n,r]of Wr)t.push(qS(r,e?e[n]:void 0));return Q(ru(...t))},JS=({order:e,chainId:t,contract:n=We})=>Q(ru(Uint8Array.from([25,1]),QS({chainId:t,contract:n}),ZS(e))),gw=e=>zS(JS(e));var ot="https://limit-order.kyberswap.com",kw=["KyberSwap","Limit","Order"].join(" "),ca=Object.freeze({1:{orderbook:ot,contract:We},10:{orderbook:ot,contract:We},56:{orderbook:ot,contract:We},137:{orderbook:ot,contract:We},250:{orderbook:ot,contract:We},324:{orderbook:ot,contract:We},5e3:{orderbook:ot,contract:We},8453:{orderbook:ot,contract:We},42161:{orderbook:ot,contract:We},43114:{orderbook:ot,contract:We},59144:{orderbook:ot,contract:We},534352:{orderbook:ot,contract:We},81457:{orderbook:ot,contract:We}}),ev="/write/api/v1/orders/sign-message",tv="/write/api/v1/orders",Sw="/read-ks/api/v1/orders";var nv=["active","open","partially_filled","cancelling","closed","filled","cancelled","expired"],vw=["filled","cancelled","expired"],Ew="filled";var rv=["active","closed"];var se=(e,t={})=>({ok:!1,code:e,params:t}),oi=e=>{let t=ca[Number(e)];return t?t.orderbook:null},Aw=e=>{let t=ca[Number(e)];return t?t.contract:null},ri=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),xw=e=>{try{return BigInt(String(e))>0n}catch{return!1}};function ov(e={}){let t=Number(e.chainId);if(oi(t)===null)return{...se("kyber-unknown-network",{chainId:Number.isFinite(t)?t:null}),known:Object.keys(ca).map(Number)};let n=e.maker,r=e.receiver===void 0||e.receiver===null?n:e.receiver,o={chainId:String(t),makerAsset:e.makerAsset,takerAsset:e.takerAsset,maker:n,receiver:r,makingAmount:String(e.makingAmount),takingAmount:String(e.takingAmount),expiredAt:e.expiredAt};e.allowedSenders!==void 0&&e.allowedSenders!==null&&(o.allowedSenders=e.allowedSenders);let i=[];return ri(n)||i.push("maker"),ri(o.makerAsset)||i.push("makerAsset"),ri(o.takerAsset)||i.push("takerAsset"),ri(o.receiver)||i.push("receiver"),xw(o.makingAmount)||i.push("makingAmount"),xw(o.takingAmount)||i.push("takingAmount"),Number.isInteger(Number(o.expiredAt))||i.push("expiredAt"),i.length?se("kyber-bad-order",{missing:[...new Set(i)]}):{ok:!0,chainId:t,orderbook:oi(t),contract:Aw(t),maker:n,params:o,expectedOutWei:String(o.takingAmount)}}function iv(e={}){let t=ov(e);return t.ok?{ok:!0,provider:"kyberswap",venue:kw,shape:Me,route:"kyberswap",expectedOutWei:t.expectedOutWei,params:t.params,owner:t.maker,endsWith:{kind:"order-status",settledWhen:Ew,final:[...vw],endpoint:Sw}}:t}async function sv({params:e,chainId:t=null,fetchImpl:n=null,timeoutMs:r=2e4,clientId:o=null}={}){let i=Number(t!==null?t:e&&e.chainId),s=oi(i);if(s===null)return se("kyber-unknown-network",{chainId:Number.isFinite(i)?i:null});if(!e||typeof e!="object")return se("kyber-bad-order",{field:"params"});let a=nt({apiBase:s,fetchImpl:n,timeoutMs:r}),c={"content-type":"application/json"};o&&(c["X-Client-Id"]=String(o));let l;try{l=await a.tryJson(ev,{method:"POST",headers:c,body:JSON.stringify(e)})}catch(E){return se("kyber-unreachable",{why:String(E&&E.params&&E.params.why||E&&E.code||E)})}if(!l||typeof l.ok!="boolean")return se("kyber-bad-response",{where:"sign-message"});if(!l.ok)return se("kyber-refused",{status:l.status,stage:"sign-message",reason:l.body&&l.body.message?l.body.message:null});let u=l.body&&l.body.data;if(!u||typeof u!="object")return se("kyber-bad-response",{where:"sign-message"});let f=u.domain||{},h=u.message||{},m=u.types&&Array.isArray(u.types.Order)?u.types.Order.map(E=>(E?E.name:"")+":"+(E?E.type:"")).join(","):null,w=Wr.map(([E,B])=>E+":"+B).join(","),x=Aw(i);if(!(f.name===void 0?!1:String(f.name)===["Kyber","DSLO","Protocol"].join(" ")&&String(f.version)==="1"&&Number(f.chainId)===i&&String(f.verifyingContract||"").toLowerCase()===String(x).toLowerCase()))return se("kyber-bad-response",{where:"sign-message",field:"domain"});if(m!==w)return se("kyber-bad-response",{where:"sign-message",field:"types"});let k=bw(h);if(k.length)return se("kyber-bad-response",{where:"sign-message",missing:k});let I=["maker","makerAsset","takerAsset","receiver"];for(let E of I)if(String(h[E]||"").toLowerCase()!==String(e[E]||"").toLowerCase())return se("kyber-bad-response",{where:"sign-message",field:E});for(let E of["makingAmount","takingAmount"])if(String(h[E])!==String(e[E]))return se("kyber-bad-response",{where:"sign-message",field:E});let g=e.allowedSenders===void 0||e.allowedSenders===null?null:(Array.isArray(e.allowedSenders)?e.allowedSenders:[e.allowedSenders]).map(E=>String(E||"").toLowerCase());if(g&&g.length&&!g.includes(String(h.allowedSender||"").toLowerCase()))return se("kyber-bad-response",{where:"sign-message",field:"allowedSender"});let P;try{P=gw({order:h,chainId:i,contract:x})}catch(E){return se("kyber-bad-response",{where:"sign-message",why:String(E&&E.message?E.message:E)})}return{ok:!0,chainId:i,orderbook:s,contract:x,salt:String(h.salt),message:h,digest:P,typedData:{domain:f,types:u.types,primaryType:u.primaryType||"Order",message:h}}}async function av({typedData:e,wallet:t,address:n=null}={}){if(!e||typeof e!="object")return se("kyber-bad-order",{field:"typedData"});try{if(t&&typeof t.signTypedData=="function"){let o=await t.signTypedData(e);return typeof o!="string"||!/^0x[0-9a-fA-F]{130}$/.test(o)?se("kyber-sign-failed",{why:"bad-signature-shape"}):{ok:!0,signature:o}}let r=t&&typeof t.driver=="function"?t.driver():null;if(r&&typeof r.request=="function"){let o=n||(typeof t.address=="function"?await t.address():null),i=await r.request({method:"eth_signTypedData_v4",params:[o,JSON.stringify(e)]});return typeof i!="string"||!/^0x[0-9a-fA-F]{130}$/.test(i)?se("kyber-sign-failed",{why:"bad-signature-shape"}):{ok:!0,signature:i}}return se("kyber-sign-failed",{why:"no-wallet"})}catch(r){return se("kyber-sign-failed",{why:String(r&&r.code||r&&r.message||r)})}}async function cv({params:e,salt:t,signature:n,chainId:r=null,fetchImpl:o=null,timeoutMs:i=2e4,clientId:s=null}={}){let a=Number(r!==null?r:e&&e.chainId),c=oi(a);if(c===null)return se("kyber-unknown-network",{chainId:Number.isFinite(a)?a:null});if(!e||typeof e!="object")return se("kyber-bad-order",{field:"params"});if(typeof n!="string"||!/^0x[0-9a-fA-F]{130}$/.test(n))return se("kyber-bad-order",{field:"signature"});if(t==null||t==="")return se("kyber-bad-order",{field:"salt"});let l=nt({apiBase:c,fetchImpl:o,timeoutMs:i}),u={"content-type":"application/json"};s&&(u["X-Client-Id"]=String(s));let f=JSON.stringify({...e,salt:String(t),signature:n}),h;try{h=await l.tryJson(tv,{method:"POST",headers:u,body:f})}catch(x){return se("kyber-unreachable",{why:String(x&&x.params&&x.params.why||x&&x.code||x)})}if(!h||typeof h.ok!="boolean")return se("kyber-bad-response",{where:"submit"});if(!h.ok)return se("kyber-refused",{status:h.status,stage:"submit",reason:h.body&&h.body.message?h.body.message:null});let m=h.body&&h.body.data,w=m&&m.id;return!Number.isInteger(Number(w))||Number(w)<=0?se("kyber-bad-response",{where:"submit",got:typeof w}):{ok:!0,id:Number(w)}}async function _w({id:e,chainId:t,maker:n,fetchImpl:r=null,timeoutMs:o=2e4}={}){let i=Number(t),s=oi(i);if(s===null)return se("kyber-unknown-network",{chainId:Number.isFinite(i)?i:null});if(!Number.isInteger(Number(e))||Number(e)<=0)return se("kyber-bad-order",{field:"id"});if(!ri(n))return se("kyber-bad-order",{field:"maker"});let a=nt({apiBase:s,fetchImpl:r,timeoutMs:o});for(let c of rv){let l=Sw+"?chainId="+i+"&maker="+n+"&status="+c,u;try{u=await a.tryJson(l)}catch(m){return se("kyber-unreachable",{why:String(m&&m.params&&m.params.why||m&&m.code||m)})}if(!u||typeof u.ok!="boolean")return se("kyber-bad-response",{where:"orders"});if(!u.ok)return se("kyber-refused",{status:u.status,stage:"orders"});let f=u.body&&u.body.data&&u.body.data.orders;if(!Array.isArray(f))return se("kyber-bad-response",{where:"orders"});let h=f.find(m=>m&&Number(m.id)===Number(e))||null;if(h){let m=h.status;return typeof m!="string"||!nv.includes(m)?se("kyber-bad-response",{where:"status",got:typeof m=="string"?m:null}):{ok:!0,status:m,order:h,bucket:c}}}return se("kyber-order-unknown",{id:Number(e),maker:n})}async function lv(e={},t={}){let{id:n,chainId:r,maker:o}=e;if(!Number.isInteger(Number(n))||Number(n)<=0)return se("kyber-bad-order",{field:"id"});let i=typeof t.now=="function"?t.now:()=>Date.now(),s=typeof t.sleep=="function"?t.sleep:f=>new Promise(h=>setTimeout(h,f)),a=Number.isFinite(t.pollMs)&&t.pollMs>0?t.pollMs:5e3,c=Number.isFinite(t.timeoutMs)&&t.timeoutMs>0?t.timeoutMs:3e5,l=i(),u=null;for(;;){let f=await _w({id:n,chainId:r,maker:o,fetchImpl:t.fetchImpl,timeoutMs:t.requestTimeoutMs});if(!f.ok)return f;if(u=f.status,vw.includes(u))return{ok:!0,done:!0,settled:u===Ew,status:u,id:Number(n)};if(i()-l>=c)return se("kyber-not-settled",{id:Number(n),status:u,waitedMs:i()-l});await s(a)}}function uv({order:e=null,requiredOutWei:t=null,tokenUsd:n=null,referenceNativeUsd:r=null,tolerated:o=!1,gates:i=null,sellDecimals:s=null,buyDecimals:a=null,buySymbol:c=null,allowanceWei:l=null,allowanceConsent:u=!1,tokenIsNative:f=!1,symbol:h=null,decimals:m=null}={}){if(!e)return{ok:!1,blocked:!0,reason:"kyber-no-order",checks:[]};let w=tt.priceGateVerdict({amountInWei:e.makingAmount,amountOutWei:e.takingAmount,inDecimals:s,outDecimals:a,tokenUsd:Number(n)>0?Number(n):null,referenceUsd:Number(r)>0?Number(r):null,stableSteps:[],tolerated:!!o,gates:i}),x={ok:!0,amountOutWei:String(e.takingAmount),price:w,wrapped:{symbol:c,decimals:a}},y=tt.dexLegVerdict(x,t),k={ok:!y.blocked,checked:y.kind!=="unchecked"&&y.kind!=="unquoted",blocks:y.blocked===!0,kind:y.kind,reason:y.reason},I=we.allowanceVerdict({tokenIsNative:f,allowanceWei:l,amountWei:e.makingAmount,consent:u===!0,symbol:h,decimals:Number.isFinite(Number(m))?Number(m):18});return{...we.signingGateVerdict([k,I]),price:w,coverage:y,allowance:I}}var Iw=Object.freeze({id:"kyberswap",kind:"kyber",venue:kw,shape:Me,settles:"wrapped",networks:ca,settlement:We,orderFields:Wr,plan:iv,settled:lv,unsignedOrder:sv,sign:av,submit:cv,status:_w,gate:uv});Ee();var dv="Permit2",iu="0x000000000022D473030F116dDEE9F6B43aC78BA3",su="0x0000000000000000000000000000000000000000",fv=["EIP712Domain(","string name,","uint256 chainId,","address verifyingContract)"],m5=fv.join(""),au=[["reactor","address"],["swapper","address"],["nonce","uint256"],["deadline","uint256"],["additionalValidationContract","address"],["additionalValidationData","bytes"]],cu=[["token","address"],["startAmount","uint256"],["endAmount","uint256"],["recipient","address"]],ii=[["info","OrderInfo"],["cosigner","address"],["baseInputToken","address"],["baseInputStartAmount","uint256"],["baseInputEndAmount","uint256"],["baseOutputs","DutchOutput[]"]],Nw=[["permitted","TokenPermissions"],["spender","address"],["nonce","uint256"],["deadline","uint256"],["witness","V2DutchOrder"]],Tw=[["token","address"],["amount","uint256"]],si=(e,t)=>e+"("+t.map(n=>n[1]+" "+n[0]).join(",")+")",lu=si("OrderInfo",au),uu=si("DutchOutput",cu),Pw=si("V2DutchOrder",ii),pv=si("TokenPermissions",Tw),w5=si("PermitWitnessTransferFrom",Nw)+uu+lu+pv+Pw,hv=Pw+uu+lu;var Vr=e=>{throw new Error(e)},du=e=>new TextEncoder().encode(String(e)),la=(...e)=>{let t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n},Bw=e=>{let t=String(e).replace(/^0x/,"");t.length%2&&Vr("uniswapx-odd-hex");let n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++){let o=parseInt(t.slice(r*2,r*2+2),16);Number.isNaN(o)&&Vr("uniswapx-bad-hex"),n[r]=o}return n},mv=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},wv=e=>{if(typeof e=="bigint")return e;let t=String(e??"").trim();if(/^0x[0-9a-fA-F]+$/.test(t)||/^[0-9]+$/.test(t))return BigInt(t);Vr("uniswapx-bad-number")},$r=(e,t)=>{let n=wv(e);n<0n&&Vr("uniswapx-negative"),n>=1n<<BigInt(t)&&Vr("uniswapx-overflow");let r=new Uint8Array(32),o=n;for(let i=31;i>=0&&o>0n;i--)r[i]=Number(o&0xffn),o>>=8n;return r},rr=e=>{let t=String(e??"").trim();/^(0x)?[0-9a-fA-F]{40}$/.test(t)||Vr("uniswapx-bad-address");let n=new Uint8Array(32);return n.set(Bw(t.replace(/^0x/,"")),12),n},yv=e=>Q(Bw(e??"0x")),Ow=e=>{let t=[];for(let[r,o]of au){let i=e?e[r]:void 0;(i==null||o!=="bytes"&&i==="")&&t.push(r)}for(let[r]of ii){if(r==="info"||r==="baseOutputs")continue;let o=e?e[r]:void 0;(o==null||o==="")&&t.push(r)}let n=e?e.baseOutputs:void 0;if(!Array.isArray(n)||n.length===0)return t.push("baseOutputs"),t;for(let r of n)for(let[o]of cu){let i=r?r[o]:void 0;(i==null||i==="")&&t.push("baseOutputs."+o)}return t},bv=e=>Q(la(Q(du(lu)),rr(e.reactor),rr(e.swapper),$r(e.nonce,256),$r(e.deadline,256),rr(e.additionalValidationContract),yv(e.additionalValidationData))),gv=e=>Q(la(Q(du(uu)),rr(e.token),$r(e.startAmount,256),$r(e.endAmount,256),rr(e.recipient))),xv=e=>Q(la(...(e||[]).map(gv))),kv=e=>Q(la(Q(du(hv)),bv(e),rr(e.cosigner),rr(e.baseInputToken),$r(e.baseInputStartAmount,256),$r(e.baseInputEndAmount,256),xv(e.baseOutputs))),Cw=e=>mv(kv(e));var Rw=({order:e,chainId:t,permit2:n=iu})=>({domain:{name:dv,chainId:Number(t),verifyingContract:n},types:{EIP712Domain:[{name:"name",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],PermitWitnessTransferFrom:Nw.map(([r,o])=>({name:r,type:o})),TokenPermissions:Tw.map(([r,o])=>({name:r,type:o})),V2DutchOrder:ii.map(([r,o])=>({name:r,type:o})),OrderInfo:au.map(([r,o])=>({name:r,type:o})),DutchOutput:cu.map(([r,o])=>({name:r,type:o}))},primaryType:"PermitWitnessTransferFrom",message:{permitted:{token:e.baseInputToken,amount:String(e.baseInputEndAmount)},spender:e.reactor,nonce:String(e.nonce),deadline:String(e.deadline),witness:{info:{reactor:e.reactor,swapper:e.swapper,nonce:String(e.nonce),deadline:String(e.deadline),additionalValidationContract:e.additionalValidationContract,additionalValidationData:e.additionalValidationData},cosigner:e.cosigner,baseInputToken:e.baseInputToken,baseInputStartAmount:String(e.baseInputStartAmount),baseInputEndAmount:String(e.baseInputEndAmount),baseOutputs:(e.baseOutputs||[]).map(r=>({token:r.token,startAmount:String(r.startAmount),endAmount:String(r.endAmount),recipient:r.recipient}))}}});var Sv="https://api.uniswap.org/v2",Hw="/orders",Lw="UniswapX",vv="0x4449Cd34d1eb1FEDCF02A1Be3834FfDe8E6A6180",Ev="0x0000000000000000000000000000000000000000",ai=Object.freeze({1:{orderbook:Sv,reactor:"0x00000011F84B9aa48e5f8aA8B9897600006289Be"}}),Fw=["open","expired","error","cancelled","filled","insufficient-funds"],Dw=["expired","error","cancelled","filled","insufficient-funds"],Uw="filled";var be=(e,t={})=>({ok:!1,code:e,params:t});var Av=e=>{let t=ai[Number(e)];return t?t.orderbook:null},zr=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),ua=e=>{try{return BigInt(String(e))>0n}catch{return!1}},Mw=e=>/^0x[0-9a-fA-F]{64}$/.test(String(e||""));function Kw(e={}){let t=Number(e.chainId),n=ai[t];if(!n)return{...be("uniswapx-unknown-network",{chainId:Number.isFinite(t)?t:null}),known:Object.keys(ai).map(Number)};let r=e.swapper,o=e.recipient===void 0||e.recipient===null?r:e.recipient,i={reactor:e.reactor===void 0||e.reactor===null?n.reactor:e.reactor,swapper:r,nonce:e.nonce,deadline:e.deadline,additionalValidationContract:e.additionalValidationContract===void 0||e.additionalValidationContract===null?Ev:e.additionalValidationContract,additionalValidationData:e.additionalValidationData===void 0||e.additionalValidationData===null?"0x":e.additionalValidationData,cosigner:e.cosigner===void 0||e.cosigner===null?vv:e.cosigner,baseInputToken:e.sellToken,baseInputStartAmount:e.sellAmountWei,baseInputEndAmount:e.sellAmountEndWei===void 0||e.sellAmountEndWei===null?e.sellAmountWei:e.sellAmountEndWei,baseOutputs:[{token:e.buyToken,startAmount:e.buyAmountWei,endAmount:e.buyAmountEndWei===void 0||e.buyAmountEndWei===null?e.buyAmountWei:e.buyAmountEndWei,recipient:o}]},s=Ow(i);if(zr(r)||s.push("swapper"),zr(i.reactor)||s.push("reactor"),zr(i.cosigner)||s.push("cosigner"),zr(i.baseInputToken)||s.push("sellToken"),(!ua(i.baseInputStartAmount)||!ua(i.baseInputEndAmount))&&s.push("sellAmountWei"),(!ua(i.baseOutputs[0].startAmount)||!ua(i.baseOutputs[0].endAmount))&&s.push("buyAmountWei"),(!zr(i.baseOutputs[0].token)||!zr(i.baseOutputs[0].recipient))&&s.push("buyToken"),Number.isInteger(Number(i.deadline))||s.push("deadline"),s.length)return be("uniswapx-bad-order",{missing:[...new Set(s)]});try{let a=Rw({order:i,chainId:t}),c=Cw(i);return{ok:!0,chainId:t,owner:r,reactor:i.reactor,order:i,orderHash:c,typedData:a}}catch(a){return be("uniswapx-bad-order",{why:String(a&&a.message?a.message:a)})}}function _v(e={}){let t=Kw(e);if(!t.ok)return t;let n=t.order.baseOutputs[0];return{ok:!0,provider:"uniswapx",venue:Lw,shape:Me,route:"uniswapx",expectedOutWei:String(n.endAmount),order:t.order,orderHash:t.orderHash,typedData:t.typedData,owner:t.owner,reactor:t.reactor,nativeOutput:String(n.token).toLowerCase()===su,endsWith:{kind:"order-status",settledWhen:Uw,final:[...Dw],endpoint:Hw}}}async function Iv({typedData:e,wallet:t,address:n=null}={}){if(!e||typeof e!="object")return be("uniswapx-bad-order",{field:"typedData"});try{if(t&&typeof t.signTypedData=="function"){let o=await t.signTypedData(e);return typeof o!="string"||!/^0x[0-9a-fA-F]{130}$/.test(o)?be("uniswapx-sign-failed",{why:"bad-signature-shape"}):{ok:!0,signature:o}}let r=t&&typeof t.driver=="function"?t.driver():null;if(r&&typeof r.request=="function"){let o=n||(typeof t.address=="function"?await t.address():null),i=await r.request({method:"eth_signTypedData_v4",params:[o,JSON.stringify(e)]});return typeof i!="string"||!/^0x[0-9a-fA-F]{130}$/.test(i)?be("uniswapx-sign-failed",{why:"bad-signature-shape"}):{ok:!0,signature:i}}return be("uniswapx-sign-failed",{why:"no-wallet"})}catch(r){return be("uniswapx-sign-failed",{why:String(r&&r.code||r&&r.message||r)})}}async function Nv({quote:e=null,signature:t=null,routing:n="DUTCH_V2",submitter:r=null,fetchImpl:o=null,timeoutMs:i=2e4}={}){if(typeof t!="string"||!/^0x[0-9a-fA-F]{130}$/.test(t))return be("uniswapx-bad-order",{field:"signature"});if(!e||typeof e!="object")return be("uniswapx-bad-order",{field:"quote"});let s=r==null||r===""?null:String(r);if(!s)return be("uniswapx-no-submitter",{field:"submitter"});let a=nt({apiBase:s,fetchImpl:o,timeoutMs:i}),c=JSON.stringify({signature:t,quote:e,routing:n}),l;try{l=await a.tryJson("",{method:"POST",headers:{"content-type":"application/json"},body:c})}catch(h){return be("uniswapx-unreachable",{why:String(h&&h.params&&h.params.why||h&&h.code||h)})}if(!l||typeof l.ok!="boolean")return be("uniswapx-bad-response",{where:"submit"});if(!l.ok)return be("uniswapx-refused",{status:l.status,stage:"submit"});let u=l.body&&typeof l.body=="object"?l.body:null;if(!u||typeof u.orderId!="string"||u.orderId==="")return be("uniswapx-bad-response",{where:"submit",field:"orderId"});let f=u.orderStatus;return typeof f!="string"||!Fw.includes(f)?be("uniswapx-bad-response",{where:"submit",field:"orderStatus"}):{ok:!0,orderId:u.orderId,orderStatus:f,requestId:typeof u.requestId=="string"?u.requestId:null}}async function jw({orderHash:e,chainId:t=null,fetchImpl:n=null,timeoutMs:r=2e4,api:o=null}={}){let i=Number(t),s=o?String(o):Number.isFinite(i)?Av(i):null;if(!s)return be("uniswapx-unknown-network",{chainId:Number.isFinite(i)?i:null});if(!Mw(e))return be("uniswapx-bad-order",{field:"orderHash"});let a=nt({apiBase:s,fetchImpl:n,timeoutMs:r}),c;try{c=await a.tryJson(Hw+"?orderHash="+e)}catch(h){return be("uniswapx-unreachable",{why:String(h&&h.params&&h.params.why||h&&h.code||h)})}if(!c||typeof c.ok!="boolean")return be("uniswapx-bad-response",{where:"orders"});if(!c.ok)return be("uniswapx-refused",{status:c.status,stage:"orders"});let l=c.body&&c.body.orders;if(!Array.isArray(l))return be("uniswapx-bad-response",{where:"orders"});let u=l.find(h=>h&&String(h.orderHash||"").toLowerCase()===String(e).toLowerCase())||l[0]||null;if(!u)return be("uniswapx-order-unknown",{orderHash:e});let f=u.orderStatus;return typeof f!="string"||!Fw.includes(f)?be("uniswapx-bad-response",{where:"orderStatus",got:typeof f=="string"?f:null}):{ok:!0,status:f,order:u}}async function Tv(e={},t={}){let{orderHash:n,chainId:r=null}=e;if(!Mw(n))return be("uniswapx-bad-order",{field:"orderHash"});let o=typeof t.now=="function"?t.now:()=>Date.now(),i=typeof t.sleep=="function"?t.sleep:u=>new Promise(f=>setTimeout(f,u)),s=Number.isFinite(t.pollMs)&&t.pollMs>0?t.pollMs:5e3,a=Number.isFinite(t.timeoutMs)&&t.timeoutMs>0?t.timeoutMs:3e5,c=o(),l=null;for(;;){let u=await jw({orderHash:n,chainId:r,fetchImpl:t.fetchImpl,timeoutMs:t.requestTimeoutMs,api:t.api});if(!u.ok)return u;if(l=u.status,Dw.includes(l))return{ok:!0,done:!0,settled:l===Uw,status:l,orderHash:n};if(o()-c>=a)return be("uniswapx-not-settled",{orderHash:n,status:l,waitedMs:o()-c});await i(s)}}function Pv({order:e=null,requiredOutWei:t=null,tokenUsd:n=null,referenceNativeUsd:r=null,tolerated:o=!1,gates:i=null,sellDecimals:s=null,buyDecimals:a=null,buySymbol:c=null,allowanceWei:l=null,allowanceConsent:u=!1,tokenIsNative:f=!1,symbol:h=null,decimals:m=null}={}){if(!e)return{ok:!1,blocked:!0,reason:"uniswapx-no-order",checks:[]};let w=Array.isArray(e.baseOutputs)&&e.baseOutputs.length?e.baseOutputs[0]:null,x=w?w.endAmount:null,y=tt.priceGateVerdict({amountInWei:e.baseInputEndAmount,amountOutWei:x,inDecimals:s,outDecimals:a,tokenUsd:Number(n)>0?Number(n):null,referenceUsd:Number(r)>0?Number(r):null,stableSteps:[],tolerated:!!o,gates:i}),k={ok:!0,amountOutWei:x===null?null:String(x),price:y,wrapped:{symbol:c,decimals:a}},I=tt.dexLegVerdict(k,t),g={ok:!I.blocked,checked:I.kind!=="unchecked"&&I.kind!=="unquoted",blocks:I.blocked===!0,kind:I.kind,reason:I.reason},P=we.allowanceVerdict({tokenIsNative:f,allowanceWei:l,amountWei:e.baseInputEndAmount,consent:u===!0,symbol:h,decimals:Number.isFinite(Number(m))?Number(m):18});return{...we.signingGateVerdict([g,P]),price:y,coverage:I,allowance:P}}var Ww=Object.freeze({id:"uniswapx",kind:"uniswapx",venue:Lw,shape:Me,settles:"native",networks:ai,settlement:ai[1].reactor,permit2:iu,nativeToken:su,orderFields:ii,plan:_v,settled:Tv,buildIntent:Kw,sign:Iv,submit:Nv,status:jw,gate:Pv});Ee();Ee();var Bv="Permit2",da="0x000000000022D473030F116dDEE9F6B43aC78BA3",fu="0x0000000000000000000000000000000000000000",Ov="0x0000000000000000000000000000000000000002",Cv="0x24856bc3",Vw=Object.freeze({v3SwapExactIn:0,sweep:4,wrapEth:11,unwrapWeth:12}),Rv=3,Hv=["EIP712Domain(","string name,","uint256 chainId,","address verifyingContract)"],v5=Hv.join(""),pu=[["reactor","address"],["swapper","address"],["nonce","uint256"],["deadline","uint256"]],hu=[["token","address"],["amount","uint256"],["recipient","address"]],mu=[["token","address"],["startAmount","uint256"],["endAmount","uint256"],["startTime","uint256"],["endTime","uint256"]],fa=[["info","RelayOrderInfo"],["input","Input"],["fee","FeeEscalator"],["universalRouterCalldata","bytes"]],$w=[["token","address"],["amount","uint256"]],zw=[["permitted","TokenPermissions[]"],["spender","address"],["nonce","uint256"],["deadline","uint256"],["witness","RelayOrder"]],Yr=(e,t)=>e+"("+t.map(n=>n[1]+" "+n[0]).join(",")+")",wu=Yr("RelayOrderInfo",pu),yu=Yr("Input",hu),bu=Yr("FeeEscalator",mu),Xw=Yr("RelayOrder",fa),Lv=Yr("TokenPermissions",$w),Fv=Xw+bu+yu+wu,E5=Yr("PermitBatchWitnessTransferFrom",zw)+bu+yu+Xw+wu+Lv;var Nn=e=>{throw new Error(e)},pa=e=>new TextEncoder().encode(String(e)),In=(...e)=>{let t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n},ci=e=>{let t=String(e).replace(/^0x/,"");t.length%2&&Nn("uniswaprelay-odd-hex");let n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++){let o=parseInt(t.slice(r*2,r*2+2),16);Number.isNaN(o)&&Nn("uniswaprelay-bad-hex"),n[r]=o}return n},gu=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},Yw=e=>{if(typeof e=="bigint")return e;let t=String(e??"").trim();if(/^0x[0-9a-fA-F]+$/.test(t)||/^[0-9]+$/.test(t))return BigInt(t);Nn("uniswaprelay-bad-number")},it=(e,t)=>{let n=Yw(e);return n<0n&&Nn("uniswaprelay-negative"),n>=1n<<BigInt(t)&&Nn("uniswaprelay-overflow"),ci("0x"+n.toString(16).padStart(64,"0"))},or=e=>{let t=String(e??"").trim();/^(0x)?[0-9a-fA-F]{40}$/.test(t)||Nn("uniswaprelay-bad-address");let n=new Uint8Array(32);return n.set(ci(t.replace(/^0x/,"")),12),n},Dv=e=>it(e?1:0,8);var Gw=e=>{let t=[];for(let[n]of pu){let r=e&&e.info?e.info[n]:void 0;(r==null||r==="")&&t.push("info."+n)}for(let[n]of hu){let r=e&&e.input?e.input[n]:void 0;(r==null||r==="")&&t.push("input."+n)}for(let[n]of mu){let r=e&&e.fee?e.fee[n]:void 0;(r==null||r==="")&&t.push("fee."+n)}return(!e||e.universalRouterCalldata===void 0||e.universalRouterCalldata===null)&&t.push("universalRouterCalldata"),t},Uv=e=>Q(In(Q(pa(wu)),or(e.info.reactor),or(e.info.swapper),it(e.info.nonce,256),it(e.info.deadline,256))),Mv=e=>Q(In(Q(pa(yu)),or(e.token),it(e.amount,256),or(e.recipient))),Kv=e=>Q(In(Q(pa(bu)),or(e.token),it(e.startAmount,256),it(e.endAmount,256),it(e.startTime,256),it(e.endTime,256))),jv=e=>Q(In(Q(pa(Fv)),Uv(e),Mv(e.input),Kv(e.fee),Q(ci(e.universalRouterCalldata)))),qw=e=>gu(jv(e));var Qw=({order:e,chainId:t,permit2:n=da})=>({domain:{name:Bv,chainId:Number(t),verifyingContract:n},types:{EIP712Domain:[{name:"name",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],PermitBatchWitnessTransferFrom:zw.map(([r,o])=>({name:r,type:o})),TokenPermissions:$w.map(([r,o])=>({name:r,type:o})),RelayOrder:fa.map(([r,o])=>({name:r,type:o})),RelayOrderInfo:pu.map(([r,o])=>({name:r,type:o})),Input:hu.map(([r,o])=>({name:r,type:o})),FeeEscalator:mu.map(([r,o])=>({name:r,type:o}))},primaryType:"PermitBatchWitnessTransferFrom",message:{permitted:[{token:e.input.token,amount:String(e.input.amount)},{token:e.fee.token,amount:String(e.fee.endAmount)}],spender:e.info.reactor,nonce:String(e.info.nonce),deadline:String(e.info.deadline),witness:{info:{reactor:e.info.reactor,swapper:e.info.swapper,nonce:String(e.info.nonce),deadline:String(e.info.deadline)},input:{token:e.input.token,amount:String(e.input.amount),recipient:e.input.recipient},fee:{token:e.fee.token,startAmount:String(e.fee.startAmount),endAmount:String(e.fee.endAmount),startTime:String(e.fee.startTime),endTime:String(e.fee.endTime)},universalRouterCalldata:e.universalRouterCalldata}}});var xu=e=>{let t=String(e).replace(/^0x/,"").toLowerCase();return t.length%64===0?t:t.padEnd(Math.ceil(t.length/64)*64,"0")},Xr=e=>Yw(e).toString(16).padStart(64,"0");var Wv=e=>{let t=e.map(s=>String(s).replace(/^0x/,"")),n=Xr(t.length),r=[],o=t.length*32;for(let s of t)r.push(Xr(o)),o+=32+Math.ceil(s.length/64)*32;let i=t.map(s=>Xr(s.length/2)+xu(s)).join("");return"0x"+n+r.join("")+i},Vv=(e,t)=>{(!Array.isArray(e)||e.length!==t.length+1)&&Nn("uniswaprelay-bad-path");let n="";for(let r=0;r<t.length;r++){n+=String(e[r]).replace(/^0x/,"").toLowerCase();let o=Number(t[r]);(!Number.isInteger(o)||o<0||o>16777215)&&Nn("uniswaprelay-bad-fee"),n+=o.toString(16).padStart(Rv*2,"0")}return n+=String(e[e.length-1]).replace(/^0x/,"").toLowerCase(),"0x"+n},$v=({recipient:e,amountInWei:t,amountOutMinimumWei:n,path:r,payerIsUser:o=!1})=>{let i=String(r).replace(/^0x/,""),s=In(or(e),it(t,256),it(n,256),it(160,256),Dv(o)),a=In(it(i.length/2,256),ci("0x"+xu(i)));return gu(In(s,a))},zv=({recipient:e,amountMinimumWei:t})=>gu(In(or(e),it(t,256))),Zw=({tokenIn:e,weth:t,fee:n,amountInWei:r,amountOutMinimumWei:o,recipient:i})=>{let s=Vv([e,t],[n]),a="0x"+Vw.v3SwapExactIn.toString(16).padStart(2,"0")+Vw.unwrapWeth.toString(16).padStart(2,"0"),c=$v({recipient:Ov,amountInWei:r,amountOutMinimumWei:o,path:s,payerIsUser:!1}),l=zv({recipient:i,amountMinimumWei:o}),u=a.replace(/^0x/,""),f=Xr(ci(a).length)+xu(u),h=Wv([c,l]).replace(/^0x/,""),m=64,w=64+f.length/2;return Cv+Xr(m)+Xr(w)+f+h};var Jw="0x0000000000A4e21E2597DCac987455c48b12edBF",ey="0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD",ty=["Uniswap","Relay"].join(" "),vu=Object.freeze({1:{reactor:Jw,universalRouter:ey,permit2:da}}),Xv=["Relay(","bytes32,","address,","address,","uint256)"],ny=()=>Xv.join(""),Yv=ny(),ha=(()=>{let e="0x";for(let t of Q(ny()))e+=t.toString(16).padStart(2,"0");return e})();var Gv=["filled","expired"],Eu="filled";var Ie=(e,t={})=>({ok:!1,code:e,params:t});var Au=e=>vu[Number(e)]||null,Gr=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),ku=e=>{try{return BigInt(String(e))>0n}catch{return!1}},ry=e=>/^0x[0-9a-fA-F]{64}$/.test(String(e||"")),Su=e=>/^0x[0-9a-fA-F]{130}$/.test(String(e||""));function oy(e={}){let t=Number(e.chainId),n=Au(t);if(!n)return{...Ie("uniswap-relay-unknown-network",{chainId:Number.isFinite(t)?t:null}),known:Object.keys(vu).map(Number)};let r=e.swapper,o=e.recipient===void 0||e.recipient===null?r:e.recipient,i=e.universalRouter===void 0||e.universalRouter===null?n.universalRouter:e.universalRouter,s=e.wrappedToken,a=[];if(Gr(r)||a.push("swapper"),(!Gr(o)||String(o).toLowerCase()===fu)&&a.push("recipient"),Gr(e.sellToken)||a.push("sellToken"),Gr(s)||a.push("wrappedToken"),Gr(i)||a.push("universalRouter"),Number.isInteger(Number(e.fee))||a.push("fee"),ku(e.sellAmountWei)||a.push("sellAmountWei"),ku(e.buyAmountWei)||a.push("buyAmountWei"),Gr(e.feeToken)||a.push("feeToken"),ku(e.feeEndAmountWei)||a.push("feeEndAmountWei"),Number.isInteger(Number(e.deadline))||a.push("deadline"),a.length)return Ie("uniswap-relay-bad-order",{missing:[...new Set(a)]});let c=e.feeStartAmountWei===void 0||e.feeStartAmountWei===null?e.feeEndAmountWei:e.feeStartAmountWei,l=e.feeStartTime===void 0||e.feeStartTime===null?e.deadline:e.feeStartTime,u=e.feeEndTime===void 0||e.feeEndTime===null?e.deadline:e.feeEndTime,f;try{f=Zw({tokenIn:e.sellToken,weth:s,fee:e.fee,amountInWei:e.sellAmountWei,amountOutMinimumWei:e.buyAmountWei,recipient:o})}catch(w){return Ie("uniswap-relay-bad-order",{why:String(w&&w.message?w.message:w)})}let h={info:{reactor:n.reactor,swapper:r,nonce:e.nonce===void 0||e.nonce===null?"0":String(e.nonce),deadline:String(e.deadline)},input:{token:e.sellToken,amount:String(e.sellAmountWei),recipient:i},fee:{token:e.feeToken,startAmount:String(c),endAmount:String(e.feeEndAmountWei),startTime:String(l),endTime:String(u)},universalRouterCalldata:f},m=Gw(h);if(m.length)return Ie("uniswap-relay-bad-order",{missing:m});try{let w=Qw({order:h,chainId:t}),x=qw(h);return{ok:!0,chainId:t,owner:r,reactor:h.info.reactor,order:h,orderHash:x,calldata:f,typedData:w}}catch(w){return Ie("uniswap-relay-bad-order",{why:String(w&&w.message?w.message:w)})}}function qv(e={}){let t=oy(e);return t.ok?{ok:!0,provider:"uniswaprelay",venue:ty,shape:Me,route:"uniswaprelay",expectedOutWei:String(e.buyAmountWei),order:t.order,orderHash:t.orderHash,typedData:t.typedData,calldata:t.calldata,owner:t.owner,reactor:t.reactor,nativeOutput:!0,endsWith:{kind:"onchain-effect",settledWhen:Eu,final:[...Gv],event:Yv}}:t}async function Qv({typedData:e,wallet:t,address:n=null}={}){if(!e||typeof e!="object")return Ie("uniswap-relay-bad-order",{field:"typedData"});try{if(t&&typeof t.signTypedData=="function"){let o=await t.signTypedData(e);return Su(o)?{ok:!0,signature:o}:Ie("uniswap-relay-sign-failed",{why:"bad-signature-shape"})}let r=t&&typeof t.driver=="function"?t.driver():null;if(r&&typeof r.request=="function"){let o=n||(typeof t.address=="function"?await t.address():null),i=await r.request({method:"eth_signTypedData_v4",params:[o,JSON.stringify(e)]});return Su(i)?{ok:!0,signature:i}:Ie("uniswap-relay-sign-failed",{why:"bad-signature-shape"})}return Ie("uniswap-relay-sign-failed",{why:"no-wallet"})}catch(r){return Ie("uniswap-relay-sign-failed",{why:String(r&&r.code||r&&r.message||r)})}}function Zv({order:e=null,signature:t=null,chainId:n=null}={}){let r=Number(n);return Au(r)?!e||typeof e!="object"?Ie("uniswap-relay-bad-order",{field:"order"}):Su(t)?Ie("uniswap-relay-no-discovery",{reactorIsPermissionless:!0,documentedSubmissionEndpoint:null,reason:"undocumented"}):Ie("uniswap-relay-bad-order",{field:"signature"}):Ie("uniswap-relay-unknown-network",{chainId:Number.isFinite(r)?r:null})}var Jv=async({driver:e=null,getLogs:t=null,reactor:n,orderHash:r,fromBlock:o="earliest",toBlock:i="latest"})=>{try{return typeof t=="function"?{ok:!0,logs:await t({reactor:n,orderHash:r,fromBlock:o,toBlock:i,topic0:ha})}:e&&typeof e.request=="function"?{ok:!0,logs:await e.request({method:"eth_getLogs",params:[{address:n,fromBlock:o,toBlock:i,topics:[ha,r]}]})}:Ie("uniswap-relay-unreachable",{why:"no-driver"})}catch(s){return Ie("uniswap-relay-unreachable",{why:String(s&&s.code||s&&s.message||s)})}};async function iy({orderHash:e,chainId:t=null,reactor:n=null,deadline:r=null,driver:o=null,getLogs:i=null,fromBlock:s="earliest",toBlock:a="latest",nowSec:c=null}={}){let l=Number(t),u=Au(l),f=n||(u?u.reactor:null);if(!f)return Ie("uniswap-relay-unknown-network",{chainId:Number.isFinite(l)?l:null});if(!ry(e))return Ie("uniswap-relay-bad-order",{field:"orderHash"});let h=await Jv({driver:o,getLogs:i,reactor:f,orderHash:e,fromBlock:s,toBlock:a});if(!h.ok)return h;let m=h.logs;if(!Array.isArray(m))return Ie("uniswap-relay-bad-response",{where:"logs",got:typeof m});let w=m.filter(x=>{if(!x||!Array.isArray(x.topics))return!1;let y=String(x.topics[0]||"").toLowerCase(),k=String(x.topics[1]||"").toLowerCase();return y===ha.toLowerCase()&&k===String(e).toLowerCase()});if(m.length>0&&w.length===0)return Ie("uniswap-relay-bad-response",{where:"logs",detail:"topics-mismatch"});if(w.length>0)return{ok:!0,status:Eu,log:w[0]};if(r!=null){let x=typeof c=="function"?c():Number.isFinite(c)?c:Math.floor(Date.now()/1e3);if(Number(r)<x)return{ok:!0,status:"expired"}}return{ok:!0,status:"open"}}async function e2(e={},t={}){let{orderHash:n,chainId:r=null,reactor:o=null,deadline:i=null}=e;if(!ry(n))return Ie("uniswap-relay-bad-order",{field:"orderHash"});let s=typeof t.now=="function"?t.now:()=>Date.now(),a=typeof t.sleep=="function"?t.sleep:h=>new Promise(m=>setTimeout(m,h)),c=Number.isFinite(t.pollMs)&&t.pollMs>0?t.pollMs:5e3,l=Number.isFinite(t.timeoutMs)&&t.timeoutMs>0?t.timeoutMs:3e5,u=s(),f=null;for(;;){let h=await iy({orderHash:n,chainId:r,reactor:o,deadline:i,driver:t.driver||null,getLogs:t.getLogs||null,fromBlock:t.fromBlock===void 0?"earliest":t.fromBlock,toBlock:t.toBlock===void 0?"latest":t.toBlock,nowSec:t.nowSec===void 0?null:t.nowSec});if(!h.ok)return h;if(f=h.status,f===Eu)return{ok:!0,done:!0,settled:!0,status:f,orderHash:n};if(f==="expired")return{ok:!0,done:!0,settled:!1,status:f,orderHash:n};if(s()-u>=l)return Ie("uniswap-relay-not-settled",{orderHash:n,status:f,waitedMs:s()-u});await a(c)}}function t2({order:e=null,amountInWei:t=null,expectedOutWei:n=null,requiredOutWei:r=null,tokenUsd:o=null,referenceNativeUsd:i=null,tolerated:s=!1,gates:a=null,sellDecimals:c=null,buyDecimals:l=null,buySymbol:u=null,allowanceWei:f=null,allowanceConsent:h=!1,tokenIsNative:m=!1,symbol:w=null,decimals:x=null}={}){if(!e)return{ok:!1,blocked:!0,reason:"uniswap-relay-no-order",checks:[]};let y=t??(e.input?e.input.amount:null),k=n??null,I=tt.priceGateVerdict({amountInWei:y,amountOutWei:k,inDecimals:c,outDecimals:l,tokenUsd:Number(o)>0?Number(o):null,referenceUsd:Number(i)>0?Number(i):null,stableSteps:[],tolerated:!!s,gates:a}),g={ok:!0,amountOutWei:k===null?null:String(k),price:I,wrapped:{symbol:u,decimals:l}},P=tt.dexLegVerdict(g,r??k),E={ok:!P.blocked,checked:P.kind!=="unchecked"&&P.kind!=="unquoted",blocks:P.blocked===!0,kind:P.kind,reason:P.reason},B=we.allowanceVerdict({tokenIsNative:m,allowanceWei:f,amountWei:y,consent:h===!0,symbol:w,decimals:Number.isFinite(Number(x))?Number(x):18});return{...we.signingGateVerdict([E,B]),price:I,coverage:P,allowance:B}}var sy=Object.freeze({id:"uniswaprelay",kind:"uniswaprelay",venue:ty,shape:Me,settles:"native",networks:vu,settlement:Jw,universalRouter:ey,permit2:da,nativeToken:fu,eventTopic:ha,orderFields:fa,plan:qv,settled:e2,buildIntent:oy,sign:Qv,submit:Zv,status:iy,gate:t2});var n2="evm",cy=e=>Number(e.chainId),r2=(e,t)=>{let n=cy(t),r=Number(e);return Number.isFinite(r)&&Number.isFinite(n)&&r===n},ly="0x70a08231",ay=e=>{try{return BigInt(e).toString(10)}catch{return null}},o2=e=>String(e).replace(/^0x/,"").toLowerCase().padStart(64,"0");async function i2({driver:e,address:t,tokens:n}){let r=[];for(let o of n){let i=null;try{if(o.address===null)i=ay(await e.request({method:"eth_getBalance",params:[t,"latest"]}));else{let s=ly+o2(t);i=ay(await e.request({method:"eth_call",params:[{to:o.address,data:s},"latest"]}))}}catch{i=null}r.push({token:o.id,symbol:o.symbol,decimals:o.decimals,amount:i})}return r}var uy={declared:{id:"declared",kind:"declared",shape:ti,async plan(){return{ok:!1,code:"not-implemented",stage:3}}},cowswap:ww,kyberswap:Iw,uniswapx:Ww,uniswaprelay:sy},qr=()=>Object.keys(uy).sort(),ma=e=>uy[e]||null,s2=e=>{let t=ma(e);return t?t.shape!==ti?{ok:!1,reason:"provider-not-synchronous",provider:t.id,shape:t.shape===void 0?null:t.shape}:{ok:!0,provider:t}:{ok:!1,reason:"provider-unknown",provider:typeof e=="string"?e:null,known:qr()}},a2=e=>{let t=ma(e);if(!t)return{ok:!1,reason:"provider-unknown",provider:typeof e=="string"?e:null,known:qr()};if(t.shape!==Me)return{ok:!1,reason:"provider-not-asynchronous",provider:t.id,shape:t.shape===void 0?null:t.shape};let n=Ql(t);return n.ok?{ok:!0,provider:t}:{ok:!1,reason:n.reason,provider:t.id,shape:t.shape===void 0?null:t.shape,missing:n.missing??null}},c2=e=>{let t=ma(e);if(!t)return{ok:!1,reason:"provider-unknown",provider:typeof e=="string"?e:null,known:qr()};let n=Ql(t);return n.ok?{ok:!0,provider:t}:{ok:!1,reason:n.reason,provider:t.id,shape:n.shape??null,missing:n.missing??null}},_u=Object.freeze({NATIVE:"native",WRAPPED:"wrapped"}),dy=e=>e&&e.settles?e.settles:null,l2=e=>{let t=dy(e),n=e&&e.id?e.id:null;return t===_u.NATIVE?{ok:!0,settles:t,provider:n}:t===_u.WRAPPED?{ok:!1,reason:"settles-wrapped",settles:t,provider:n}:{ok:!1,reason:"settles-unstated",settles:null,provider:n}};var u2=Object.freeze({evm:Object.freeze({vm:"evm",addressFormat:"hex-20",settlementKind:"contract",refKind:"address",txRef:"hash"}),tron:Object.freeze({vm:"tron",addressFormat:"base58check",settlementKind:"contract",refKind:"address",txRef:"hash"}),solana:Object.freeze({vm:"solana",addressFormat:"base58",settlementKind:"program",refKind:"pda",txRef:"signature"}),bitcoin:Object.freeze({vm:"bitcoin",addressFormat:"base58check-or-bech32-or-bech32m",settlementKind:"utxo-script",refKind:"script",txRef:"txid"})}),fy=e=>u2[e]||null;var py={evm:Iu},hy=()=>Object.keys(py).sort(),Qr=e=>py[e]||null,d2=e=>(ce.CHAINS||[]).find(t=>t&&t.id===e)||null,Nu=e=>{let t=d2(e);return t&&t.vm?t.vm:null},my=e=>{let t=Nu(e);return t?fy(t):null};var f2=e=>{let t=typeof ce.chainByChainId=="function"?ce.chainByChainId(e):null;t||z("bad-input",{field:"chain.chainId",unknown:e,why:"no-network-with-this-chainId"});let n=ce.tokensOf(t.id),r=[t.native,...t.tokens||[]].filter(Boolean),o=i=>String(i.symbol).toLowerCase();return n.map(o).join("|")!==r.map(o).join("|")&&z("bad-input",{field:"chain.tokens",unknown:e,why:"tokens-belong-to-another-network"}),n},p2=e=>({id:e.id,name:e.name,vm:e.vm||null,settlementProfile:my(e.id),chainId:e.chainId,nativeSymbol:e.native&&e.native.symbol?e.native.symbol:null,tokens:f2(e.chainId).map(t=>({id:String(t.symbol).toLowerCase(),symbol:String(t.symbol),address:t.address||null,decimals:Number(t.decimals)})),dex:e.dex?{routes:e.dex.routes||[]}:null,escrow:e.escrow?{address:e.escrow.address||null,mode:e.escrow.mode||null,registry:e.escrow.registry||null,cashier:e.escrow.cashier||null,implementationCodeHash:e.escrow.implementationCodeHash||null,deploymentBlock:Number.isSafeInteger(e.escrow.deploymentBlock)?e.escrow.deploymentBlock:null}:null}),wy=Object.freeze({mainnet:[{url:"https://xmr-node.cakewallet.com:18081",operator:"Cake Wallet"},{url:"https://xmr.cryptostorm.is",operator:"cryptostorm"},{url:"https://node.monero.fail",operator:"monero.fail"},{url:"https://mainnet.xmr.kernal.eu:18089",operator:"kernal.eu"}],stagenet:[{url:"https://xmr-stagenet.ninsei.finance",operator:"Ninsei"},{url:"https://stagenet.xmr.kernal.eu:38089",operator:"kernal.eu"}]}),h2=e=>typeof e=="string"&&e||e&&typeof e=="object"&&typeof e.url=="string"&&e.url,Tu=e=>Array.isArray(e)&&e.every(h2),m2=(e,t)=>{let n=e&&e.nodes,r=e&&e.addNodes,o={mainnet:[...wy.mainnet],stagenet:[...wy.stagenet]};if(n!=null)if(Tu(n))t in o||z("bad-input",{field:"nodes",network:t}),o[t]=[...n];else if(n&&typeof n=="object"&&!Array.isArray(n))for(let i of Object.keys(n))i in o||z("bad-input",{field:"nodes",unknown:i,known:Object.keys(o)}),Tu(n[i])||z("bad-input",{field:"nodes."+i}),o[i]=[...n[i]];else z("bad-input",{field:"nodes"});return r!=null&&(Tu(r)||z("bad-input",{field:"addNodes"}),t in o||z("bad-input",{field:"addNodes",network:t}),o[t]=[...o[t],...r]),o},Pu=e=>Number.isFinite(Number(e))&&Number(e)>0?Number(e):null,w2=e=>{let t=e&&e.watch||{},n=t.pollMs===void 0?Pu(ce.API&&ce.API.pollMs)||5e3:Number(t.pollMs);(!Number.isFinite(n)||n<=0)&&z("bad-input",{field:"watch.pollMs"});let r=ce.MONERO||{},o=(Pu(r.blockTimeReal)||12e4)*(Pu(r.confirmTarget)||10),i=t.timeoutMs===void 0?o:Number(t.timeoutMs);return(!Number.isFinite(i)||i<=0)&&z("bad-input",{field:"watch.timeoutMs"}),{pollMs:n,timeoutMs:i}},y2=(e,t)=>{let n=t&&t.endpoints||{},r=n.explorer||{},o=n.rpc||{},i=s=>typeof s=="string"&&s?s:null;return{explorer:{evmTx:i(r.evmTx)||i(e.explorerTx),evmAddr:i(r.evmAddr)||i(e.explorerAddr),evmName:i(r.evmName)||i(e.explorerName),xmrTx:i(r.xmrTx)},rpc:{evm:i(o.evm)||i(e.rpcUrl),monero:i(o.monero)}}};function yy(e){let t=ce.CHAINS.map(p2),n=t.find(w=>w.id===e.settlement.chain)||null;n||z("bad-input",{field:"settlement.chain",known:t.map(w=>w.id)});let r=ce.CHAINS.find(w=>w.id===e.settlement.chain)||{},o=w2(e),i=y2(r,e),s=m2(e,e.xmrNetwork),a=e.settlement.vm||n.vm;a||z("bad-input",{field:"settlement.vm"}),a!==n.vm&&z("bad-input",{field:"settlement.vm",chain:n.id,vm:n.vm,got:a}),Qr(a)||z("not-implemented",{surface:"settlement.vm",vm:a,implemented:hy()});let l=qr(),u=Array.isArray(e.routing&&e.routing.prefer)&&e.routing.prefer.length?e.routing.prefer.map(w=>String(w)):l.filter(w=>w==="declared");for(let w of u)l.includes(w)||z("bad-input",{field:"routing.prefer",unknown:w,known:l});let f=["mainnet","stagenet","testnet","fakechain"],h=[...new Set([...Object.values(ce.XMR_NETWORKS||{}),...f])];h.includes(e.xmrNetwork)||z("bad-input",{field:"xmrNetwork",known:h});let m=ce.SIGNING_GUARDS||{};return{settlement:{chain:n,vm:a},chains:t,xmrNetworks:h,assetsBase:e.assetsBase,mode:e.mode,limits:{minAmount:null,maxAmount:null,stepAmount:null,xmrConfirmTarget:ce.MONERO.confirmTarget??null,watchPollMs:o.pollMs,watchTimeoutMs:o.timeoutMs,xmrConfirmations:ce.MONERO.confirmTarget??10,xmrBlockTimeSec:Math.round((ce.MONERO.blockTimeReal??12e4)/1e3),readyLeadWarnSec:m.readyLeadWarnSec??null},routing:{providers:l,prefer:u},endpoints:i,xmrNodes:s,nodesFor:w=>s&&s[w]?s[w]:[],codes:{steps:Zs,checks:Js,errors:Kr}}}function by({chain:e,knownFactoryCodes:t}={}){return t??ce.knownFactoryCodesFor(e)}function gy({chain:e,knownImplementationCodes:t}={}){if(t!=null)return t;let n=typeof e=="string"?e:e&&e.id,r=n?ce.chainById(n):null;return!r||String(r.id)!==String(n)?null:ce.knownImplementationCodesFor(e)}fe();Mc();Ct();function b2(e,t,n,r){gr(e);let o=zi({dkLen:32,asyncTick:10},r),{c:i,dkLen:s,asyncTick:a}=o;if(Te(i,"c"),Te(s,"dkLen"),Te(a,"asyncTick"),i<1)throw new Error('"c" (iterations) must be >= 1');if(s<1)throw new Error('"dkLen" must be >= 1');if(s>(2**32-1)*e.outputLen)throw new Error("derived key too long");let c=bc(t,"password");try{let l=bc(n,"salt");try{let u=new Uint8Array(s),{iHash:f,oHash:h,outputLen:m}=ds.create(e,c),w=new Uint8Array(m),x=g2(f,h,l,w);return{c:i,dkLen:s,asyncTick:a,DK:u,outputLen:m,eng:x}}finally{typeof n=="string"&&qe(l)}}finally{typeof t=="string"&&qe(c)}}function g2(e,t,n,r){let o=new Uint8Array(4),i=kr(o),s=e._cloneInto().update(n),a=t._cloneInto(),c=e._cloneInto,l=t._cloneInto;return{u1:(u,f)=>{i.setInt32(0,u,!1),s._cloneInto(a).update(o).digestInto(r),t._cloneInto(a).update(r).digestInto(r),f.set(r.subarray(0,f.length))},rounds:(u,f)=>{for(let h=1;h<u;h++){c.call(e,a).update(r).digestInto(r),l.call(t,a).update(r).digestInto(r);for(let m=0;m<f.length;m++)f[m]^=r[m]}},output:u=>(e.destroy(),t.destroy(),s.destroy(),a.destroy(),qe(r),u)}}function xy(e,t,n,r){let{c:o,dkLen:i,DK:s,outputLen:a,eng:c}=b2(e,t,n,r);for(let l=1,u=0;u<i;l++,u+=a){let f=s.subarray(u,u+a);c.u1(l,f),c.rounds(o,f)}return c.output(s)}Yi();Ct();function ky(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n>=55296&&n<=56319){if(t+1>=e.length)return!1;let r=e.charCodeAt(++t);if(r<56320||r>57343)return!1}else if(n>=56320&&n<=57343)return!1}return!0}function Sy(e){if(typeof e!="string")throw new TypeError("invalid mnemonic type: "+typeof e);if(!ky(e))throw new TypeError("expected well-formed Unicode string");return e.normalize("NFKD")}function vy(e){let t=Sy(e),n=t.split(" ");if(![12,15,18,21,24].includes(n.length))throw new Error("Invalid mnemonic");return{nfkd:t,words:n}}function x2(e){if(Fe(e),![16,20,24,28,32].includes(e.length))throw new RangeError("invalid entropy length")}var k2=e=>{let t=8-e.length/4;return Xi(e)[0]>>t<<t};function S2(e){if(!Array.isArray(e)||e.length!==2048||typeof e[0]!="string")throw new TypeError("Wordlist: expected array of 2048 strings");e.forEach(t=>{if(typeof t!="string")throw new TypeError("wordlist: non-string element: "+t);if(!ky(t))throw new TypeError("wordlist: expected well-formed Unicode string")})}function v2(e,t){S2(t);let n=e.length/3*4,r=new Uint8Array(n+1),o=0,i=0,s=0;for(let c of e){let l=t.indexOf(c);if(l===-1)throw new Error("Unknown word: "+c);for(o=o<<11|l,i+=11;i>=8;)i-=8,r[s++]=o>>>i&255;o&=(1<<i)-1}i>0&&(r[s]=o<<8-i);let a=r.subarray(0,n);if(r[n]!==k2(a))throw new Error("Invalid checksum");return Uint8Array.from(a)}function E2(e,t){let{words:n}=vy(e),r=v2(n,t);return x2(r),r}function Ey(e,t){try{E2(e,t)}catch{return!1}return!0}var A2=e=>{if(typeof e!="string")throw new TypeError("invalid passphrase type: "+typeof e);return Sy("mnemonic"+e)};function Ay(e,t=""){return xy(Co,vy(e).nfkd,A2(t),{c:2048,dkLen:64})}var _y=Object.freeze(`abandon
|
|
2
3
|
ability
|
|
3
4
|
able
|
|
4
5
|
about
|
|
@@ -2046,11 +2047,11 @@ zebra
|
|
|
2046
2047
|
zero
|
|
2047
2048
|
zone
|
|
2048
2049
|
zoo`.split(`
|
|
2049
|
-
`));
|
|
2050
|
-
`)}function
|
|
2050
|
+
`));Vo();fe();var _2=new Set(["mainnet","stagenet","testnet","fakechain"]);function Iy(e){let t=String(e&&e.nettype||"").trim().toLowerCase();return _2.has(t)?t:null}var Ny=8e3,I2=e=>typeof e=="string"?e.trim():"";async function Ty({url:e,fetchImpl:t=globalThis.fetch,timeoutMs:n=Ny}={}){let r=I2(e);for(;r.endsWith("/");)r=r.slice(0,-1);if(!r)return{ok:!1,why:"no-url"};if(typeof t!="function")return{ok:!1,why:"no-fetch"};let o=Date.now(),i=typeof AbortController=="function"?new AbortController:null,s=i?setTimeout(()=>i.abort(),Math.max(1,Number(n)||Ny)):null,a;try{a=await t(r+"/json_rpc",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:"0",method:"get_info"}),signal:i?i.signal:void 0})}catch(h){return s&&clearTimeout(s),{ok:!1,why:h&&(h.name==="AbortError"||h.code==="ABORT_ERR")?"timeout":"unreachable",ms:Date.now()-o}}if(!a||!a.ok)return s&&clearTimeout(s),{ok:!1,why:"http",status:a?a.status:null,ms:Date.now()-o};let c=null;try{c=await a.json()}catch{return s&&clearTimeout(s),{ok:!1,why:"not-json",ms:Date.now()-o}}if(s&&clearTimeout(s),!c||c.error)return{ok:!1,why:"rpc",rpc:c&&c.error?c.error.code??null:null,ms:Date.now()-o};let l=c.result||{},u=Number(l.height);if(!Number.isInteger(u)||u<0)return{ok:!1,why:"no-height",ms:Date.now()-o};let f=Iy(l);return f?{ok:!0,url:r,height:u,network:f,nettype:l.nettype??null,synchronized:l.synchronized===!0,version:l.version??null,status:l.status??null,ms:Date.now()-o}:{ok:!1,why:"nettype",nettype:l.nettype??null,ms:Date.now()-o}}Ee();var Tn=Wo({ed25519:_e,secp256k1:Ce,keccak256:Q,randomBytes:Wn}),By=1,N2=12,Oy="ninsei.recovery.key.v1",T2="NINSEI RECOVERY KEY",P2="ninsei-taker-v2",B2="ninsei-maker-view-v1",O2=1,C2="AES-GCM-256/PBKDF2-SHA256",Py=6e5;var R2=/^0x[0-9a-fA-F]{40}$/,wa=new TextEncoder,d4=new TextDecoder,Bu=e=>"0x"+BigInt(e).toString(16).padStart(64,"0");var Ou=e=>{let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t)};var yt=e=>new d("bad-input",{field:e}),Cy=e=>new d("recovery-failed",{stage:e});function Ry(e){if(typeof e!="string")throw yt("mnemonic");let t=e.trim().toLowerCase().replace(/\s+/g," ");if(!t||t.split(" ").length!==N2||!Ey(t,_y))throw yt("mnemonic");return t}function Hy(e){let t=e instanceof Date?e:e?new Date(e):new Date;if(Number.isNaN(t.getTime()))throw yt("createdAt");return t.toISOString()}function Lu(e,{createdAt:t}={}){return ya(e,t)}function ya(e,t){let n=Ry(e);return{version:By,mnemonic:n,fingerprint:Fu(n),createdAt:Hy(t)}}function Fu(e){let t=typeof e=="string"?e.trim().toLowerCase().replace(/\s+/g," "):"";if(!t)throw yt("mnemonic");return Array.from(Q(wa.encode(t)),n=>n.toString(16).padStart(2,"0")).join("").slice(0,4)}function H2(e){return Ay(Ry(e))}function L2(e,t){let n=Number(e);if(!Number.isSafeInteger(n)||n<0)throw yt(t);return n}function F2({chainId:e,factory:t,role:n="taker",salt:r}={}){if(typeof t!="string"||!R2.test(t))throw yt("factory");if(typeof n!="string"||!/^[a-z0-9-]{1,32}$/.test(n))throw yt("role");return`${P2}|${L2(e,"chainId")}|${t.toLowerCase()}|${n}|${Zt(r)}`}function ir({mnemonic:e,chainId:t,factory:n,role:r="taker",salt:o}={}){let i=Zt(o),s=F2({chainId:t,factory:n,role:r,salt:i});return{...D2(H2(e),s),derivation:"salt-v2",factory:n.toLowerCase(),role:r,salt:i}}function D2(e,t){let n=Tn.halfFromSeed(e,t,Tn.HALF_DOMAIN),r=Tn.halfFromSeed(e,t,Tn.VIEW_HALF_DOMAIN),o=Tn.halfFromSeed(e,t,B2),i=Tn.publicHalves(n),s=Tn.publicHalves(r),a=Tn.publicHalves(o);return{binding:t,spendHalf:Bu(n),viewHalf:Bu(r),spendPoint:i.ed,viewPoint:s.ed,makerViewHalf:Bu(o),makerViewPoint:a.ed,spendCommitment:Hr(n,Ce,Q)}}function Ly(){return"0x"+Array.from(Wn(32),e=>e.toString(16).padStart(2,"0")).join("")}function Zt(e){return typeof e=="bigint"?Cu("0x"+e.toString(16).padStart(64,"0")):typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?Cu("0x"+BigInt(e).toString(16).padStart(64,"0")):Cu(e)}function Cu(e){let t=String(e??"").trim().toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(t))throw yt("salt");return t}var Fy=e=>Hy(e).slice(0,10);function Du({mnemonic:e,fingerprint:t,createdAt:n}={}){let r=t||Fu(e);return`ninsei-recovery-key-DO-NOT-DELETE-${Fy(n)}-${r}.txt`}function U2({fingerprint:e,createdAt:t}){return[T2,"This file restores every swap made with this key.","Restore at https://recovery.ninsei.finance","Never share it with anyone, not even Ninsei.","This is not a wallet seed. Do not import it into a wallet.",`Key ${e}, created ${Fy(t)}`].join(`
|
|
2051
|
+
`)}function M2({mnemonic:e,createdAt:t}={}){let n=ya(e,t);return`${U2(n)}
|
|
2051
2052
|
|
|
2052
2053
|
${n.mnemonic}
|
|
2053
|
-
`}async function TA(e,t,n){if(!globalThis.crypto||!globalThis.crypto.subtle)throw Ab("crypto-unavailable");let r=await crypto.subtle.importKey("raw",Da.encode(e),"PBKDF2",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:t,iterations:n,hash:"SHA-256"},r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}var OA=e=>JSON.stringify({kind:"ninsei-recovery-key",v:e.v,alg:e.alg,iter:e.iter,salt:e.salt,iv:e.iv,meta:e.meta});async function Bb({mnemonic:e,createdAt:t,passphrase:n=""}={}){let r=Ua(e,t);if(typeof n!="string")throw vt("passphrase");if(n==="")return IA(r);if(n.length<12)throw vt("passphrase");if(!globalThis.crypto||!globalThis.crypto.subtle)throw Ab("crypto-unavailable");let o=crypto.getRandomValues(new Uint8Array(16)),i=crypto.getRandomValues(new Uint8Array(12)),s={v:xA,alg:kA,iter:Sb,salt:$d(o),iv:$d(i),meta:{fingerprint:r.fingerprint,createdAt:r.createdAt}},a=await TA(n,o,Sb),c=await crypto.subtle.encrypt({name:"AES-GCM",iv:i,tagLength:128,additionalData:Da.encode(OA(s))},a,Da.encode(JSON.stringify({mnemonic:r.mnemonic})));return JSON.stringify({...s,ciphertext:$d(new Uint8Array(c))},null,2)}var wi=e=>new h("storage-unavailable",{step:e}),BA=e=>{if(!e||typeof e.get!="function"||typeof e.set!="function"||typeof e.remove!="function")throw vt("storage");let t;try{t=e.get(Eb)}catch{throw wi("read")}if(t==null||t==="")return null;let n;try{n=JSON.parse(t)}catch{throw wi("parse")}if(!n||n.version!==vb||typeof n.mnemonic!="string")throw wi("parse");return n},PA=(e,t)=>{let n;try{n=JSON.stringify(t)}catch{throw wi("serialize")}try{e.set(Eb,n)}catch{throw wi("write")}};function Ma(e,t){let n=Ua(t&&t.mnemonic,t&&t.createdAt);return PA(e,{...n,backupConfirmed:t.backupConfirmed===!0}),n}function Qd(e){let t=BA(e);return t?{...t,fingerprint:t.fingerprint||qd(t.mnemonic)}:null}var CA=18,RA=45,l8=RA+CA*32;var Xd=e=>"0x"+Array.from(q(new TextEncoder().encode(e)),t=>t.toString(16).padStart(2,"0")).join(""),Yd=Object.freeze({halfRevealed:Xd("HalfRevealed(bytes32,bool)"),ready:Xd("Ready(address)"),declined:Xd("Declined(address)")}),u8=new Map([[Yd.halfRevealed,"HalfRevealed"],[Yd.ready,"Ready"],[Yd.declined,"Declined"]]);var Ct=()=>ys.createOrderBuilder(Ln);function Kn(e){if(!e||typeof e!="object")throw new h("bad-input",{field:"order"});try{return bt.orderContextString(e)}catch{throw new h("bad-input",{field:"order"})}}function Cb({side:e,order:t,sealed:n=null,ownEncPriv:r=null}){if(!e||typeof e!="object")throw new h("bad-input",{field:"side"});let o=Kn(t),i=null;try{i=Ct().verifySide(e,o,n,r)}catch{throw new h("bad-input",{field:"side"})}if(!i||i.ok!==!0)throw new h("quote-refused",{step:"proof",why:i&&i.reason?"rejected":"unknown"});return e}function so({ownSpendHalf:e,ownViewHalf:t,otherSpendPoint:n,otherViewPoint:r,network:o}){let i={ownSpendHalf:e,ownViewHalf:t,otherSpendPoint:n,otherViewPoint:r},s=Object.keys(i).filter(a=>i[a]===void 0||i[a]===null||i[a]==="");if(s.length)throw new h("bad-input",{field:"jointAddress",missing:s});try{return Ct().jointAddress({ownSpendHalf:e,ownViewHalf:t,otherSpendPoint:n,otherViewPoint:r,network:o})}catch{throw new h("bad-input",{field:"jointAddress"})}}var Se=e=>"0x"+String(e).replace(/^0x/i,"").toLowerCase(),dn=e=>"0x"+BigInt(e).toString(16).padStart(64,"0"),Zd=e=>/^0x[0-9a-f]{64}$/.test(String(e)),Pb=e=>e&&typeof e=="object"&&e.XB?{...e,XB:Se(e.XB)}:e,ja=e=>typeof e=="string"&&e?Se(e):e;function Jd(e){let t=e&&typeof e=="object"?e:{},n=[t.viewHalf,t.viewHalfClaimer].filter(s=>s!=null&&s!==""),r=null;if(n.length){try{r=BigInt(String(n[0]))}catch{throw new h("bad-input",{field:"counterparty",why:"view-half"})}for(let s of n.slice(1)){let a=null;try{a=BigInt(String(s))}catch{a=null}if(a===null||a!==r)throw new h("bad-input",{field:"counterparty",why:"conflicting-view-half"})}}let o=[t.viewPoint,t.viewPub].filter(s=>s!=null&&s!==""),i=null;if(o.length){if(i=ja(o[0]),!Zd(i))throw new h("bad-input",{field:"counterparty",why:"view-point"});for(let s of o.slice(1))if(ja(s)!==i)throw new h("bad-input",{field:"counterparty",why:"conflicting-view-point"})}if(r!==null){let s=null;try{s=ja(Ct().pointOf(r))}catch{s=null}if(!s)throw new h("bad-input",{field:"counterparty",why:"view-half"});if(i!==null&&i!==s)throw new h("bad-input",{field:"counterparty",why:"view-half-point-mismatch"});i=s}return{half:r===null?null:n[0],point:i}}function ef(e,t){let n=Kn(e),r=Ct().newSide(n,!1,t);return{context:n,side:r,spendPoint:Se(r.pub.ed),viewPoint:Se(r.viewPub),encPub:Se(r.enc.pub)}}function mr(e,{spendHalf:t,viewHalf:n}={}){let r=Kn(e),o=Ct(),i=(m,w)=>{let y=BigInt(m);if(y<=0n||y>=BigInt(o.halves.LIMIT))throw new h("bad-input",{field:w});return y},s=i(t,"spendHalf"),a=i(n,"viewHalf"),c=o.halves.publicHalves(s),l=o.halves.publicHalves(a).ed,u=o.enc.recipientKeyPair(),d=o.dleq.prove(s,r);return{context:r,side:{half:s,pub:c,viewHalf:a,viewPub:l,enc:u,proof:d,standIn:!1},spendPoint:Se(c.ed),viewPoint:Se(l),encPub:Se(u.pub)}}function tf({context:e,side:t=null,counterparty:n=null,standIn:r=!1}){let o=null;if(n&&typeof n=="object"){let c=n.pub&&typeof n.pub=="object"?n.pub:{},l=Jd(n);o={proof:Pb(n.proof),edPub:ja(n.edPub||n.edPoint||n.edPointClaimer||c.ed||null),viewPoint:l.point,viewHalf:l.half,half:n.half!==void 0?n.half:null,commitHalfClaimer:n.commitHalfClaimer||null,sealed:n.sealed||null,providerId:n.providerId||null,standIn:!1}}else if(r===!0){let c=Ct().newSide(e,!0);o={proof:Pb(c.proof),edPub:Se(c.pub.ed),viewPoint:Se(c.viewPub),viewHalf:c.viewHalf,half:c.half,commitHalfClaimer:Se(Ct().halfCommitment(c.half)),sealed:null,providerId:null,standIn:!0,mock:c}}else throw new h("bad-input",{field:"counterparty"});let i=[];if(o.proof||i.push("proof"),o.edPub||i.push("edPub"),o.commitHalfClaimer||i.push("commitHalfClaimer"),i.length)throw new h("bad-input",{field:"counterparty",missing:i});let s=o.sealed&&t&&t.enc?t.enc.priv:null,a=null;try{a=Ct().verifySide({proof:o.proof,pub:{ed:o.edPub},commitHalfClaimer:o.commitHalfClaimer},e,o.sealed,s)}catch{throw new h("bad-input",{field:"counterparty"})}if(!a||a.ok!==!0)throw new h("quote-refused",{step:"proof",why:a&&a.reason?"rejected":"unknown"});return o}function Rb({order:e,side:t=null,counterparty:n=null,standIn:r=!1,network:o=null}){let i=Kn(e),s=t?{context:i,side:t,spendPoint:Se(t.pub&&t.pub.ed),viewPoint:Se(t.viewPub),encPub:Se(t.enc&&t.enc.pub?t.enc.pub:null)}:ef(e),a=[];if((s.side.half===void 0||s.side.half===null)&&a.push("half"),(s.side.viewHalf===void 0||s.side.viewHalf===null)&&a.push("viewHalf"),Zd(s.spendPoint)||a.push("spendPoint"),Zd(s.viewPoint)||a.push("viewPoint"),a.length)throw new h("bad-input",{field:"side",missing:a});let c=tf({context:s.context,side:s.side,counterparty:n,standIn:r}),l=c.viewPoint||(c.viewHalf?Se(Ct().pointOf(c.viewHalf)):null);if(!l)throw new h("bad-input",{field:"counterparty",missing:["viewPoint"]});let u=null;try{u=Ct().jointAddress({ownSpendHalf:s.side.half,ownViewHalf:s.side.viewHalf,otherSpendPoint:c.edPub,otherViewPoint:l,network:o})}catch{throw new h("bad-input",{field:"network"})}return{context:s.context,own:{spendPoint:s.spendPoint,viewPoint:s.viewPoint,encPub:s.encPub,proof:s.side.proof},side:s.side,counterparty:c,wallet:{spendHalf:dn(s.side.half),viewHalf:dn(s.side.viewHalf),otherSpendPoint:c.edPub,otherViewPoint:Se(l),otherViewHalf:c.viewHalf?dn(c.viewHalf):null,address:u.address,spendPub:Se(u.spendPub),viewPub:Se(u.viewPub),otherCommitHalf:c.commitHalfClaimer||null,commitHalfLocker:Se(Ct().halfCommitment(s.side.half)),commitHalfClaimer:c.commitHalfClaimer||null,network:o||null}}}var HA="Ninsei Relay",LA="1",FA="EIP712Domain(string name,string version)",Lb="FirmWindow(string market,string side,string xmrNetwork,uint32 readyMinSeconds,uint32 readyMaxSeconds,uint32 settlementMinSeconds,uint32 settlementMaxSeconds,uint32 quoteTtlSeconds)",DA="NodeFeatures(string relayId,address provider,address quoteKey,address registry,bytes32 hpkeKey,FirmWindow[] firmWindows,uint64 time,bytes32 nonce)"+Lb,UA=[["market","string"],["side","string"],["xmrNetwork","string"],["readyMinSeconds","uint32"],["readyMaxSeconds","uint32"],["settlementMinSeconds","uint32"],["settlementMaxSeconds","uint32"],["quoteTtlSeconds","uint32"]],MA=[["relayId","string"],["provider","address"],["quoteKey","address"],["registry","address"],["hpkeKey","bytes32"],["firmWindows","FirmWindow[]"],["time","uint64"],["nonce","bytes32"]],ao=e=>new TextEncoder().encode(String(e)),co=(...e)=>{let t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n},Ka=(e,t,n)=>{let r=String(e??"").replace(/^0x/,"");if(!new RegExp("^[0-9a-fA-F]{"+n*2+"}$").test(r))throw new h("bad-input",{field:t});let o=new Uint8Array(n);for(let i=0;i<n;i+=1)o[i]=parseInt(r.slice(i*2,i*2+2),16);return o},Fb=(e,t,n)=>{let r=null;try{r=BigInt(String(e??"").trim())}catch{r=null}if(r===null||r<0n||r>=1n<<BigInt(n))throw new h("bad-input",{field:t});let o=new Uint8Array(32);for(let i=31;i>=0&&r>0n;i-=1)o[i]=Number(r&0xffn),r>>=8n;return o},jA=(e,t)=>{let n=String(e??"").trim();if(!/^(0x)?[0-9a-fA-F]{40}$/.test(n))throw new h("bad-input",{field:t});let r=new Uint8Array(32);return r.set(Ka(n,t,20),12),r},nf=e=>q(ao(e??"")),Hb=(e,t,n)=>{if(!Array.isArray(e))throw new h("bad-input",{field:t});let r=e.map(o=>n(o));return q(co(...r))};function KA(e){if(!e||typeof e!="object")throw new h("bad-input",{field:"firmWindows"});let t=[q(ao(Lb))];for(let[n,r]of UA)t.push(r==="string"?nf(e[n]):Fb(e[n],"firmWindows."+n,32));return q(co(...t))}function WA(e){if(!e||typeof e!="object")throw new h("bad-input",{field:"features"});let t=[q(ao(DA))];for(let[n,r]of MA)if(r==="string")t.push(nf(e[n]));else if(r==="address")t.push(jA(e[n],"features."+n));else if(r==="bytes32")t.push(Ka(e[n],"features."+n,32));else if(r==="uint64")t.push(Fb(e[n],"features."+n,64));else if(r==="string[]")t.push(Hb(e[n],"features."+n,o=>nf(o)));else if(r==="FirmWindow[]")t.push(Hb(e[n],"features."+n,KA));else throw new h("bad-input",{field:"features."+n});return q(co(...t))}function VA(){return q(co(q(ao(FA)),q(ao(HA)),q(ao(LA))))}function $A(e){return q(co(Uint8Array.from([25,1]),VA(),WA(e)))}var rf=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t};function zA(e,t){let n=String(t||"").replace(/^0x/,"");if(!/^[0-9a-fA-F]{130}$/.test(n))return null;let r=parseInt(n.slice(128,130),16);if(r>=27&&(r-=27),r!==0&&r!==1)return null;try{let o=Ue.Signature.fromBytes(co(Ka(n.slice(0,64),"signature",32),Ka(n.slice(64,128),"signature",32))).addRecoveryBit(r).recoverPublicKey(e);return rf(q(o.toBytes(!1).slice(1)).slice(12))}catch{return null}}function Db({features:e,terms:t=null}={}){if(!e||typeof e!="object")throw new h("bad-input",{field:"features"});if(e.type!=="node_features"||Number(e.version)!==1)throw new h("quote-refused",{step:"features",why:"version"});let n=$A(e),r=zA(n,e.signature),o=String(e.quoteKey||"").toLowerCase();if(r===null||r!==o)throw new h("quote-refused",{step:"features",why:"signature"});let i=String(e.hpkeKey||"").replace(/^0x/,"").toLowerCase();if(!/^[0-9a-f]{64}$/.test(i)||/^0+$/.test(i))throw new h("quote-refused",{step:"features",why:"hpke-key"});if(!Array.isArray(e.firmWindows)||e.firmWindows.length===0)throw new h("quote-refused",{step:"features",why:"windows"});if(t){if(String(e.provider||"").toLowerCase()!==String(t.maker||"").toLowerCase()||String(e.registry||"").toLowerCase()!==String(t.registry||"").toLowerCase())throw new h("quote-refused",{step:"features",why:"identity"});let s=String(t.market||""),a=String(t.side||""),c=String(t.xmrNetwork||""),l=e.firmWindows.find(u=>u&&u.market===s&&u.side===a&&u.xmrNetwork===c);if(!l)throw new h("quote-refused",{step:"features",why:"window"});return{featuresHash:rf(n),hpkeKey:"0x"+i,window:l}}return{featuresHash:rf(n),hpkeKey:"0x"+i,window:null}}var ct=class extends Error{constructor(t){let n;t instanceof Error?n=t.message:typeof t=="string"?n=t:n="",super(n),this.name=this.constructor.name}},Ke=class extends ct{};var Rt=class extends ct{},Et=class extends ct{},yi=class extends ct{},bi=class extends ct{},gi=class extends ct{},xi=class extends ct{},ki=class extends ct{},Si=class extends ct{},Wn=class extends ct{},lt=class extends ct{};var XA={},of=YA(globalThis,XA);function YA(e,t){return new Proxy(e,{get(n,r,o){return r in t?t[r]:e[r]},set(n,r,o){return r in t&&delete t[r],e[r]=o,!0},deleteProperty(n,r){let o=!1;return r in t&&(delete t[r],o=!0),r in e&&(delete e[r],o=!0),o},ownKeys(n){let r=Reflect.ownKeys(e),o=Reflect.ownKeys(t),i=new Set(o);return[...r.filter(s=>!i.has(s)),...o]},defineProperty(n,r,o){return r in t&&delete t[r],Reflect.defineProperty(e,r,o),!0},getOwnPropertyDescriptor(n,r){return r in t?Reflect.getOwnPropertyDescriptor(t,r):Reflect.getOwnPropertyDescriptor(e,r)},has(n,r){return r in t||r in e}})}async function GA(){if(of!==void 0&&globalThis.crypto!==void 0)return globalThis.crypto.subtle;try{let{webcrypto:e}=await import("crypto");return e.subtle}catch(e){throw new lt(e)}}var At=class{constructor(){Object.defineProperty(this,"_api",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}async _setup(){this._api===void 0&&(this._api=await GA())}};var Yt={Base:0,Psk:1,Auth:2,AuthPsk:3},Gt={NotAssigned:0,DhkemP256HkdfSha256:16,DhkemP384HkdfSha384:17,DhkemP521HkdfSha512:18,DhkemSecp256k1HkdfSha256:19,DhkemX25519HkdfSha256:32,DhkemX448HkdfSha512:33,HybridkemX25519Kyber768:48,MlKem512:64,MlKem768:65,MlKem1024:66,XWing:25722},vi={HkdfSha256:1,HkdfSha384:2,HkdfSha512:3,Sha3256:4,Sha3384:5,Sha3512:6,Shake128:16,Shake256:17,TurboShake128:18,TurboShake256:19},Vn={Aes128Gcm:1,Aes256Gcm:2,Chacha20Poly1305:3,ExportOnly:65535};var ge=new Uint8Array(0),Wa=0n;var Va=new Uint8Array([75,69,77,0,0]);var Mb=new Uint8Array([72,80,75,69,45,118,49]);function lo(e){return new Uint8Array(se(e))}function se(e){return e instanceof ArrayBuffer?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice().buffer:new Uint8Array(e).slice().buffer}var sf=class extends At{constructor(){super(),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:vi.HkdfSha256}),Object.defineProperty(this,"hashSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_suiteId",{enumerable:!0,configurable:!0,writable:!0,value:ge}),Object.defineProperty(this,"algHash",{enumerable:!0,configurable:!0,writable:!0,value:{name:"HMAC",hash:"SHA-256",length:256}})}init(t){this._suiteId=t}buildLabeledIkm(t,n){this._checkInit();let r=new Uint8Array(7+this._suiteId.byteLength+t.byteLength+n.byteLength);return r.set(Mb,0),r.set(this._suiteId,7),r.set(t,7+this._suiteId.byteLength),r.set(n,7+this._suiteId.byteLength+t.byteLength),r}buildLabeledInfo(t,n,r){this._checkInit();let o=new Uint8Array(9+this._suiteId.byteLength+t.byteLength+n.byteLength);return o.set(new Uint8Array([0,r]),0),o.set(Mb,2),o.set(this._suiteId,9),o.set(t,9+this._suiteId.byteLength),o.set(n,9+this._suiteId.byteLength+t.byteLength),o}async extract(t,n){await this._setup();let r=t.byteLength===0?new ArrayBuffer(this.hashSize):se(t);if(r.byteLength!==this.hashSize)throw new Ke("The salt length must be the same as the hashSize");let o=se(n),i=await this._api.importKey("raw",r,this.algHash,!1,["sign"]);return await this._api.sign("HMAC",i,o)}async expand(t,n,r){await this._setup();let o=se(t),i=await this._api.importKey("raw",o,this.algHash,!1,["sign"]),s=new ArrayBuffer(r),a=new Uint8Array(s),c=ge,l=lo(n),u=new Uint8Array(1);if(r>255*this.hashSize)throw new Error("Entropy limit reached");let d=new Uint8Array(this.hashSize+l.length+1);for(let p=1,m=0;m<a.length;p++)u[0]=p,d.set(c,0),d.set(l,c.length),d.set(u,c.length+l.length),c=new Uint8Array(await this._api.sign("HMAC",i,d.slice(0,c.length+l.length+1))),a.length-m>=c.length?(a.set(c,m),m+=c.length):(a.set(c.slice(0,a.length-m),m),m+=a.length-m);return s}async extractAndExpand(t,n,r,o){await this._setup();let i=se(n),s=await this._api.importKey("raw",i,"HKDF",!1,["deriveBits"]);return await this._api.deriveBits({name:"HKDF",hash:this.algHash.hash,salt:se(t),info:se(r)},s,o*8)}async labeledExtract(t,n,r){return await this.extract(t,this.buildLabeledIkm(n,r))}async labeledExpand(t,n,r,o){return await this.expand(t,this.buildLabeledInfo(n,r,o),o)}_checkInit(){if(this._suiteId===ge)throw new Error("Not initialized. Call init()")}},$n=class extends sf{constructor(){super(...arguments),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:vi.HkdfSha256}),Object.defineProperty(this,"hashSize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"algHash",{enumerable:!0,configurable:!0,writable:!0,value:{name:"HMAC",hash:"SHA-256",length:256}})}};var zn=e=>typeof e=="object"&&e!==null&&typeof e.privateKey=="object"&&typeof e.publicKey=="object";function Ht(e,t){if(t<=0)throw new Error("i2Osp: too small size");if(e>=256**t)throw new Error("i2Osp: too large integer");let n=new Uint8Array(t);for(let r=0;r<t&&e;r++)n[t-(r+1)]=e%256,e=Math.floor(e/256);return n}function wr(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function uo(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r}function af(e,t){if(e.byteLength!==t.byteLength)throw new Error("xor: different length inputs");let n=new Uint8Array(e.byteLength);for(let r=0;r<e.byteLength;r++)n[r]=e[r]^t[r];return n}var qA=new Uint8Array([101,97,101,95,112,114,107]),QA=new Uint8Array([115,104,97,114,101,100,95,115,101,99,114,101,116]);function ZA(e,t,n){let r=new Uint8Array(e.length+t.length+n.length);return r.set(e,0),r.set(t,e.length),r.set(n,e.length+t.length),r}var yr=class{constructor(t,n,r){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"secretSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"encSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"publicKeySize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"privateKeySize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_prim",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.id=t,this._prim=n,this._kdf=r;let o=new Uint8Array(Va);o.set(Ht(this.id,2),3),this._kdf.init(o)}async serializePublicKey(t){return await this._prim.serializePublicKey(t)}async deserializePublicKey(t){return await this._prim.deserializePublicKey(se(t))}async serializePrivateKey(t){return await this._prim.serializePrivateKey(t)}async deserializePrivateKey(t){return await this._prim.deserializePrivateKey(se(t))}async importKey(t,n,r=!0){return await this._prim.importKey(t,n,r)}async generateKeyPair(){return await this._prim.generateKeyPair()}async deriveKeyPair(t){let n=se(t);if(n.byteLength>8192)throw new Ke("Too long ikm");return await this._prim.deriveKeyPair(n)}async encap(t){let n;t.ekm===void 0?n=await this.generateKeyPair():zn(t.ekm)?n=t.ekm:n=await this.deriveKeyPair(t.ekm);let r=await this._prim.serializePublicKey(n.publicKey),o=await this._prim.serializePublicKey(t.recipientPublicKey);try{let i;if(t.senderKey===void 0)i=new Uint8Array(await this._prim.dh(n.privateKey,t.recipientPublicKey));else{let c=zn(t.senderKey)?t.senderKey.privateKey:t.senderKey,l=new Uint8Array(await this._prim.dh(n.privateKey,t.recipientPublicKey)),u=new Uint8Array(await this._prim.dh(c,t.recipientPublicKey));i=wr(l,u)}let s;if(t.senderKey===void 0)s=wr(new Uint8Array(r),new Uint8Array(o));else{let c=zn(t.senderKey)?t.senderKey.publicKey:await this._prim.derivePublicKey(t.senderKey),l=await this._prim.serializePublicKey(c);s=ZA(new Uint8Array(r),new Uint8Array(o),new Uint8Array(l))}let a=await this._generateSharedSecret(i,s);return{enc:r,sharedSecret:a}}catch(i){throw new yi(i)}}async decap(t){let n=se(t.enc),r=await this._prim.deserializePublicKey(n),o=zn(t.recipientKey)?t.recipientKey.privateKey:t.recipientKey,i=zn(t.recipientKey)?t.recipientKey.publicKey:await this._prim.derivePublicKey(t.recipientKey),s=await this._prim.serializePublicKey(i);try{let a;if(t.senderPublicKey===void 0)a=new Uint8Array(await this._prim.dh(o,r));else{let l=new Uint8Array(await this._prim.dh(o,r)),u=new Uint8Array(await this._prim.dh(o,t.senderPublicKey));a=wr(l,u)}let c;if(t.senderPublicKey===void 0)c=wr(new Uint8Array(n),new Uint8Array(s));else{let l=await this._prim.serializePublicKey(t.senderPublicKey);c=new Uint8Array(n.byteLength+s.byteLength+l.byteLength),c.set(new Uint8Array(n),0),c.set(new Uint8Array(s),n.byteLength),c.set(new Uint8Array(l),n.byteLength+s.byteLength)}return await this._generateSharedSecret(a,c)}catch(a){throw new bi(a)}}async _generateSharedSecret(t,n){let r=this._kdf.buildLabeledIkm(qA,t),o=this._kdf.buildLabeledInfo(QA,n,this.secretSize);return await this._kdf.extractAndExpand(ge,r,o,this.secretSize)}};var Xn=["deriveBits"],gr=new Uint8Array([100,107,112,95,112,114,107]),fo=new Uint8Array([115,107]);var G8={p:(1n<<521n)-1n,b:0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00n,gx:0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66n,gy:0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650n,coordinateSize:66};function e_(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Lt(e,t=""){if(!Number.isSafeInteger(e)||e<0){let n=t&&`"${t}" `;throw new Error(`${n}expected integer >0, got ${e}`)}}function xe(e,t,n=""){let r=e_(e),o=e?.length,i=t!==void 0;if(!r||i&&o!==t){let s=n&&`"${n}" `,a=i?` of length ${t}`:"",c=r?`length=${o}`:`type=${typeof e}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return e}function qt(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function po(e,t){xe(e,void 0,"digestInto() output");let n=t.outputLen;if(e.length<n)throw new Error('"digestInto() output" expected to be of length >='+n)}function _t(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function qe(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}var t_=new Uint32Array([287454020]),n_=new Uint8Array(t_.buffer),cf=n_[0]===68;function $a(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ei(e){Lt(e,"numberToBigint");let t=e,n=Wa,r=1n;for(;t>0;)t%2===1&&(n+=r),t=Math.floor(t/2),r<<=1n;return n}function fn(e){return Uint8Array.from(e)}function Kb(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Lt(e.outputLen),Lt(e.blockLen)}var za=class{constructor(t,n){if(Object.defineProperty(this,"oHash",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"iHash",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockLen",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputLen",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"finished",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Kb(t),xe(n,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?t.create().update(n).digest():n);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=t.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),qe(o)}update(t){return qt(this),this.iHash.update(t),this}digestInto(t){qt(this),xe(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:n,iHash:r,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Wb=(e,t,n)=>new za(e,t).update(n).digest();Wb.create=(e,t)=>new za(e,t);var Xa=0xffffffffn,Vb=32n;function r_(e,t=!1){return t?{h:Number(e&Xa),l:Number(e>>Vb&Xa)}:{h:Number(e>>Vb&Xa)|0,l:Number(e&Xa)|0}}function lf(e,t=!1){let n=e.length,r=new Uint32Array(n),o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=r_(e[i],t);[r[i],o[i]]=[s,a]}return[r,o]}var a_=0n,Ai=1n,c_=2n,l_=7n,u_=256n,d_=0x71n,f_=[],p_=[],$b=[];for(let e=0,t=Ai,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],f_.push(2*(5*r+n)),p_.push((e+1)*(e+2)/2%64);let o=a_;for(let i=0;i<7;i++)t=(t<<Ai^(t>>l_)*d_)%u_,t&c_&&(o^=Ai<<(Ai<<BigInt(i))-Ai);$b.push(o)}var zb=lf($b,!0),rO=zb[0],oO=zb[1];function ff(){return new Promise((e,t)=>{t(new lt("Not supported"))})}var y_=new Uint8Array([115,101,99]),ho=class{constructor(t,n,r){Object.defineProperty(this,"_api",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exporterSecret",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._api=t,this._kdf=n,this.exporterSecret=r}async seal(t,n){return await ff()}async open(t,n){return await ff()}async export(t,n){let r=se(t);if(r.byteLength>8192)throw new Ke("Too long exporter context");try{return await this._kdf.labeledExpand(this.exporterSecret,y_,new Uint8Array(r),n)}catch(o){throw new gi(o)}}},Ya=class extends ho{},Ga=class extends ho{constructor(t,n,r,o){super(t,n,r),Object.defineProperty(this,"enc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.enc=o}};var mo=class extends ho{constructor(t,n,r){if(super(t,n,r.exporterSecret),Object.defineProperty(this,"_aead",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nK",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nN",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nT",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ctx",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.key===void 0||r.baseNonce===void 0||r.seq===void 0)throw new Error("Required parameters are missing");this._aead=r.aead,this._nK=this._aead.keySize,this._nN=this._aead.nonceSize,this._nT=this._aead.tagSize;let o=this._aead.createEncryptionContext(r.key);this._ctx={key:o,baseNonce:r.baseNonce,seq:r.seq}}computeNonce(t){let n=Ht(t.seq,t.baseNonce.byteLength);return af(t.baseNonce,n).buffer}incrementSeq(t){if(t.seq>Number.MAX_SAFE_INTEGER)throw new Si("Message limit reached");t.seq+=1}};var b_=function(e,t,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(e):r?r.value:t.get(e)},g_=function(e,t,n,r,o){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(e,n):o?o.value=n:t.set(e,n),n},qa,wo=class{constructor(){qa.set(this,Promise.resolve())}async lock(){let t,n=new Promise(o=>{t=o}),r=b_(this,qa,"f");return g_(this,qa,n,"f"),await r,t}};qa=new WeakMap;var Gb=function(e,t,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(e):r?r.value:t.get(e)},x_=function(e,t,n,r,o){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(e,n):o?o.value=n:t.set(e,n),n},_i,Qa=class extends mo{constructor(){super(...arguments),_i.set(this,void 0)}async open(t,n=ge.buffer){x_(this,_i,Gb(this,_i,"f")??new wo,"f");let r=await Gb(this,_i,"f").lock(),o;try{o=await this._ctx.key.open(this.computeNonce(this._ctx),se(t),se(n))}catch(i){throw new ki(i)}finally{r()}return this.incrementSeq(this._ctx),o}};_i=new WeakMap;var qb=function(e,t,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(e):r?r.value:t.get(e)},k_=function(e,t,n,r,o){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(e,n):o?o.value=n:t.set(e,n),n},Ni,Za=class extends mo{constructor(t,n,r,o){super(t,n,r),Object.defineProperty(this,"enc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Ni.set(this,void 0),this.enc=o}async seal(t,n=ge.buffer){k_(this,Ni,qb(this,Ni,"f")??new wo,"f");let r=await qb(this,Ni,"f").lock(),o;try{o=await this._ctx.key.seal(this.computeNonce(this._ctx),se(t),se(n))}catch(i){throw new xi(i)}finally{r()}return this.incrementSeq(this._ctx),o}};Ni=new WeakMap;var S_=new Uint8Array([98,97,115,101,95,110,111,110,99,101]),v_=new Uint8Array([101,120,112]),E_=new Uint8Array([105,110,102,111,95,104,97,115,104]),A_=new Uint8Array([107,101,121]),__=new Uint8Array([112,115,107,95,105,100,95,104,97,115,104]),N_=new Uint8Array([115,101,99,114,101,116]),I_=new Uint8Array([72,80,75,69,0,0,0,0,0,0]),Ja=class extends At{constructor(t){if(super(),Object.defineProperty(this,"_kem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_aead",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_suiteId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof t.kem=="number")throw new Ke("KemId cannot be used");if(this._kem=t.kem,typeof t.kdf=="number")throw new Ke("KdfId cannot be used");if(this._kdf=t.kdf,typeof t.aead=="number")throw new Ke("AeadId cannot be used");this._aead=t.aead,this._suiteId=new Uint8Array(I_),this._suiteId.set(Ht(this._kem.id,2),4),this._suiteId.set(Ht(this._kdf.id,2),6),this._suiteId.set(Ht(this._aead.id,2),8),this._kdf.init(this._suiteId)}get kem(){return this._kem}get kdf(){return this._kdf}get aead(){return this._aead}async createSenderContext(t){this._validateInputLength(t),await this._setup();let n=await this._kem.encap(t),r;return t.psk!==void 0?r=t.senderKey!==void 0?Yt.AuthPsk:Yt.Psk:r=t.senderKey!==void 0?Yt.Auth:Yt.Base,await this._keyScheduleS(r,n.sharedSecret,n.enc,t)}async createRecipientContext(t){this._validateInputLength(t),await this._setup();let n=await this._kem.decap(t),r;return t.psk!==void 0?r=t.senderPublicKey!==void 0?Yt.AuthPsk:Yt.Psk:r=t.senderPublicKey!==void 0?Yt.Auth:Yt.Base,await this._keyScheduleR(r,n,t)}async seal(t,n,r=ge.buffer){let o=await this.createSenderContext(t);return{ct:await o.seal(n,r),enc:o.enc}}async open(t,n,r=ge.buffer){return await(await this.createRecipientContext(t)).open(n,r)}async _keySchedule(t,n,r){let o=r.psk===void 0?ge:lo(r.psk.id),i=await this._kdf.labeledExtract(ge,__,o),s=r.info===void 0?ge:lo(r.info),a=await this._kdf.labeledExtract(ge,E_,s),c=new Uint8Array(1+i.byteLength+a.byteLength);c.set(new Uint8Array([t]),0),c.set(new Uint8Array(i),1),c.set(new Uint8Array(a),1+i.byteLength);let l=r.psk===void 0?ge:lo(r.psk.key),u=this._kdf.buildLabeledIkm(N_,l),d=this._kdf.buildLabeledInfo(v_,c,this._kdf.hashSize),p=await this._kdf.extractAndExpand(n,u,d,this._kdf.hashSize);if(this._aead.id===Vn.ExportOnly)return{aead:this._aead,exporterSecret:p};let m=this._kdf.buildLabeledInfo(A_,c,this._aead.keySize),w=await this._kdf.extractAndExpand(n,u,m,this._aead.keySize),y=this._kdf.buildLabeledInfo(S_,c,this._aead.nonceSize),b=await this._kdf.extractAndExpand(n,u,y,this._aead.nonceSize);return{aead:this._aead,exporterSecret:p,key:w,baseNonce:new Uint8Array(b),seq:0}}async _keyScheduleS(t,n,r,o){let i=await this._keySchedule(t,n,o);return i.key===void 0?new Ga(this._api,this._kdf,i.exporterSecret,r):new Za(this._api,this._kdf,i,r)}async _keyScheduleR(t,n,r){let o=await this._keySchedule(t,n,r);return o.key===void 0?new Ya(this._api,this._kdf,o.exporterSecret):new Qa(this._api,this._kdf,o)}_validateInputLength(t){if(t.info!==void 0&&t.info.byteLength>268435456)throw new Ke("Too long info");if(t.psk!==void 0){if(t.psk.key.byteLength<32)throw new Ke(`PSK must have at least ${32} bytes`);if(t.psk.key.byteLength>8192)throw new Ke("Too long psk.key");if(t.psk.id.byteLength>8192)throw new Ke("Too long psk.id")}}};var Ii=class extends Ja{};var Ti=class extends $n{};var Oi="X25519",T_=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),O_=(()=>{let e=new Uint8Array(32);return e[0]=9,e})(),ec=class extends At{constructor(t){super(),Object.defineProperty(this,"_hkdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_alg",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nPk",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nSk",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nDh",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pkcs8AlgId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._alg={name:Oi},this._hkdf=t,this._nPk=32,this._nSk=32,this._nDh=32,this._pkcs8AlgId=T_}async serializePublicKey(t){await this._setup();try{return await this._api.exportKey("raw",t)}catch(n){throw new Rt(n)}}async deserializePublicKey(t){await this._setup();try{return await this._importRawKey(se(t),!0)}catch(n){throw new Et(n)}}async serializePrivateKey(t){await this._setup();try{let n=await this._api.exportKey("jwk",t);if(!("d"in n))throw new Error("Not private key");return uo(n.d).buffer}catch(n){throw new Rt(n)}}async deserializePrivateKey(t){await this._setup();try{return await this._importRawKey(se(t),!1)}catch(n){throw new Et(n)}}async importKey(t,n,r){await this._setup();try{if(t==="raw")return await this._importRawKey(n,r);if(n instanceof ArrayBuffer)throw new Error("Invalid jwk key format");return await this._importJWK(n,r)}catch(o){throw new Et(o)}}async generateKeyPair(){await this._setup();try{return await this._api.generateKey(Oi,!0,Xn)}catch(t){throw new lt(t)}}async deriveKeyPair(t){await this._setup();try{let n=se(t),r=await this._hkdf.labeledExtract(ge,gr,new Uint8Array(n)),o=await this._hkdf.labeledExpand(r,fo,ge,this._nSk),i=new Uint8Array(o),s=await this._deserializePkcs8Key(i);return i.fill(0),{privateKey:s,publicKey:await this.derivePublicKey(s)}}catch(n){throw new Wn(n)}}async derivePublicKey(t){await this._setup();try{let n=await this._api.exportKey("jwk",t);return delete n.d,delete n.key_ops,await this._api.importKey("jwk",n,this._alg,!0,[])}catch{try{let n=await this._api.importKey("raw",O_.buffer,this._alg,!0,[]),r=await this._api.deriveBits({name:Oi,public:n},t,this._nPk*8);return await this._api.importKey("raw",r,this._alg,!0,[])}catch(n){throw new Et(n)}}}async dh(t,n){await this._setup();try{return await this._api.deriveBits({name:Oi,public:n},t,this._nDh*8)}catch(r){throw new Rt(r)}}async _importRawKey(t,n){if(n&&t.byteLength!==this._nPk)throw new Error("Invalid public key for the ciphersuite");if(!n&&t.byteLength!==this._nSk)throw new Error("Invalid private key for the ciphersuite");return n?await this._api.importKey("raw",t,this._alg,!0,[]):await this._deserializePkcs8Key(new Uint8Array(t))}async _importJWK(t,n){if(typeof t.kty>"u"||t.kty!=="OKP")throw new Error(`Invalid kty: ${t.crv}`);if(typeof t.crv>"u"||t.crv!==Oi)throw new Error(`Invalid crv: ${t.crv}`);if(n){if(typeof t.d<"u")throw new Error("Invalid key: `d` should not be set");return await this._api.importKey("jwk",t,this._alg,!0,[])}if(typeof t.d>"u")throw new Error("Invalid key: `d` not found");return await this._api.importKey("jwk",t,this._alg,!0,Xn)}async _deserializePkcs8Key(t){let n=new Uint8Array(this._pkcs8AlgId.length+t.length);return n.set(this._pkcs8AlgId,0),n.set(t,this._pkcs8AlgId.length),await this._api.importKey("pkcs8",n,this._alg,!0,Xn)}};var Bi=class extends yr{constructor(){let t=new $n;super(Gt.DhkemX25519HkdfSha256,new ec(t),t),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:Gt.DhkemX25519HkdfSha256}),Object.defineProperty(this,"secretSize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"encSize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"publicKeySize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"privateKeySize",{enumerable:!0,configurable:!0,writable:!0,value:32})}};var GB=new Uint8Array([48,70,2,1,0,48,5,6,3,43,101,111,4,58,4,56]);function tc(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}var Qb=(e,t)=>{function n(r,...o){if(xe(r,void 0,"key"),!cf)throw new Error("Non little-endian hardware is not yet supported");if(e.nonceLength!==void 0){let u=o[0];xe(u,e.varSizeNonce?void 0:e.nonceLength,"nonce")}let i=e.tagLength;i&&o[1]!==void 0&&xe(o[1],void 0,"AAD");let s=t(r,...o),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");xe(d,void 0,"output")}},c=!1;return{encrypt(u,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,xe(u),a(s.encrypt.length,d),s.encrypt(u,d)},decrypt(u,d){if(xe(u),i&&u.length<i)throw new Error('"ciphertext" expected length bigger than tagLength='+i);return a(s.decrypt.length,d),s.decrypt(u,d)}}}return Object.assign(n,e),n};function Zb(e,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(e,t)}function Jb(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function pf(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(t.length!==e)throw new Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(n&&!B_(t))throw new Error("invalid output, must be aligned");return t}function eg(e,t,n){tc(n);let r=new Uint8Array(16),o=$a(r);return o.setBigUint64(0,Ei(t),n),o.setBigUint64(8,Ei(e),n),r}function B_(e){return e.byteOffset%4===0}var ng=e=>Uint8Array.from(e.split("").map(t=>t.charCodeAt(0))),P_=ng("expand 16-byte k"),C_=ng("expand 32-byte k"),R_=_t(P_),H_=_t(C_);function ce(e,t){return e<<t|e>>>32-t}function hf(e){return e.byteOffset%4===0}var nc=64,L_=16,rg=2**32-1,tg=Uint32Array.of();function F_(e,t,n,r,o,i,s,a){let c=o.length,l=new Uint8Array(nc),u=_t(l),d=hf(o)&&hf(i),p=d?_t(o):tg,m=d?_t(i):tg;for(let w=0;w<c;s++){if(e(t,n,r,u,s,a),s>=rg)throw new Error("arx: counter overflow");let y=Math.min(nc,c-w);if(d&&y===nc){let b=w/4;if(w%4!==0)throw new Error("arx: invalid block position");for(let x=0,I;x<L_;x++)I=b+x,m[I]=p[I]^u[x];w+=nc;continue}for(let b=0,x;b<y;b++)x=w+b,i[x]=o[x]^l[b];w+=y}}function og(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:o,counterRight:i,rounds:s}=Zb({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return Lt(o),Lt(s),tc(i),tc(n),(a,c,l,u,d=0)=>{xe(a,void 0,"key"),xe(c,void 0,"nonce"),xe(l,void 0,"data");let p=l.length;if(u===void 0&&(u=new Uint8Array(p)),xe(u,void 0,"output"),Lt(d),d<0||d>=rg)throw new Error("arx: counter overflow");if(u.length<p)throw new Error(`arx: output (${u.length}) is shorter than data (${p})`);let m=[],w=a.length,y,b;if(w===32)m.push(y=fn(a)),b=H_;else if(w===16&&n)y=new Uint8Array(32),y.set(a),y.set(a,16),b=R_,m.push(y);else throw xe(a,32,"arx key"),new Error("invalid key size");hf(c)||m.push(c=fn(c));let x=_t(y);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(b,x,_t(c.subarray(0,16)),x),c=c.subarray(16)}let I=16-o;if(I!==c.length)throw new Error(`arx: nonce must be ${I} or 16 bytes`);if(I!==12){let U=new Uint8Array(12);U.set(c,i?0:12-c.length),c=U,m.push(c)}let E=_t(c);return F_(e,b,x,E,l,u,d,s),qe(...m),u}}function ze(e,t){return e[t++]&255|(e[t++]&255)<<8}var mf=class{constructor(t){Object.defineProperty(this,"blockLen",{enumerable:!0,configurable:!0,writable:!0,value:16}),Object.defineProperty(this,"outputLen",{enumerable:!0,configurable:!0,writable:!0,value:16}),Object.defineProperty(this,"buffer",{enumerable:!0,configurable:!0,writable:!0,value:new Uint8Array(16)}),Object.defineProperty(this,"r",{enumerable:!0,configurable:!0,writable:!0,value:new Uint16Array(10)}),Object.defineProperty(this,"h",{enumerable:!0,configurable:!0,writable:!0,value:new Uint16Array(10)}),Object.defineProperty(this,"pad",{enumerable:!0,configurable:!0,writable:!0,value:new Uint16Array(8)}),Object.defineProperty(this,"pos",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"finished",{enumerable:!0,configurable:!0,writable:!0,value:!1}),t=fn(xe(t,32,"key"));let n=ze(t,0),r=ze(t,2),o=ze(t,4),i=ze(t,6),s=ze(t,8),a=ze(t,10),c=ze(t,12),l=ze(t,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|i<<9)&8191,this.r[4]=(i>>>4|s<<12)&255,this.r[5]=s>>>1&8190,this.r[6]=(s>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=ze(t,16+2*u)}process(t,n,r=!1){let o=r?0:2048,{h:i,r:s}=this,a=s[0],c=s[1],l=s[2],u=s[3],d=s[4],p=s[5],m=s[6],w=s[7],y=s[8],b=s[9],x=ze(t,n+0),I=ze(t,n+2),E=ze(t,n+4),U=ze(t,n+6),S=ze(t,n+8),B=ze(t,n+10),R=ze(t,n+12),A=ze(t,n+14),N=i[0]+(x&8191),f=i[1]+((x>>>13|I<<3)&8191),k=i[2]+((I>>>10|E<<6)&8191),_=i[3]+((E>>>7|U<<9)&8191),K=i[4]+((U>>>4|S<<12)&8191),H=i[5]+(S>>>1&8191),P=i[6]+((S>>>14|B<<2)&8191),j=i[7]+((B>>>11|R<<5)&8191),L=i[8]+((R>>>8|A<<8)&8191),z=i[9]+(A>>>5|o),W=0,$=W+N*a+f*(5*b)+k*(5*y)+_*(5*w)+K*(5*m);W=$>>>13,$&=8191,$+=H*(5*p)+P*(5*d)+j*(5*u)+L*(5*l)+z*(5*c),W+=$>>>13,$&=8191;let O=W+N*c+f*a+k*(5*b)+_*(5*y)+K*(5*w);W=O>>>13,O&=8191,O+=H*(5*m)+P*(5*p)+j*(5*d)+L*(5*u)+z*(5*l),W+=O>>>13,O&=8191;let g=W+N*l+f*c+k*a+_*(5*b)+K*(5*y);W=g>>>13,g&=8191,g+=H*(5*w)+P*(5*m)+j*(5*p)+L*(5*d)+z*(5*u),W+=g>>>13,g&=8191;let T=W+N*u+f*l+k*c+_*a+K*(5*b);W=T>>>13,T&=8191,T+=H*(5*y)+P*(5*w)+j*(5*m)+L*(5*p)+z*(5*d),W+=T>>>13,T&=8191;let v=W+N*d+f*u+k*l+_*c+K*a;W=v>>>13,v&=8191,v+=H*(5*b)+P*(5*y)+j*(5*w)+L*(5*m)+z*(5*p),W+=v>>>13,v&=8191;let V=W+N*p+f*d+k*u+_*l+K*c;W=V>>>13,V&=8191,V+=H*a+P*(5*b)+j*(5*y)+L*(5*w)+z*(5*m),W+=V>>>13,V&=8191;let D=W+N*m+f*p+k*d+_*u+K*l;W=D>>>13,D&=8191,D+=H*c+P*a+j*(5*b)+L*(5*y)+z*(5*w),W+=D>>>13,D&=8191;let F=W+N*w+f*m+k*p+_*d+K*u;W=F>>>13,F&=8191,F+=H*l+P*c+j*a+L*(5*b)+z*(5*y),W+=F>>>13,F&=8191;let M=W+N*y+f*w+k*m+_*p+K*d;W=M>>>13,M&=8191,M+=H*u+P*l+j*c+L*a+z*(5*b),W+=M>>>13,M&=8191;let X=W+N*b+f*y+k*w+_*m+K*p;W=X>>>13,X&=8191,X+=H*d+P*u+j*l+L*c+z*a,W+=X>>>13,X&=8191,W=(W<<2)+W|0,W=W+$|0,$=W&8191,W=W>>>13,O+=W,i[0]=$,i[1]=O,i[2]=g,i[3]=T,i[4]=v,i[5]=V,i[6]=D,i[7]=F,i[8]=M,i[9]=X}finalize(){let{h:t,pad:n}=this,r=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,r[0]=t[0]+5,o=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=t[a]+o,o=r[a]>>>13,r[a]&=8191;r[9]-=8192;let i=(o^1)-1;for(let a=0;a<10;a++)r[a]&=i;i=~i;for(let a=0;a<10;a++)t[a]=t[a]&i|r[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let s=t[0]+n[0];t[0]=s&65535;for(let a=1;a<8;a++)s=(t[a]+n[a]|0)+(s>>>16)|0,t[a]=s&65535;qe(r)}update(t){qt(this),xe(t),t=fn(t);let{buffer:n,blockLen:r}=this,o=t.length;for(let i=0;i<o;){let s=Math.min(r-this.pos,o-i);if(s===r){for(;r<=o-i;i+=r)this.process(t,i);continue}n.set(t.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){qe(this.h,this.r,this.buffer,this.pad)}digestInto(t){qt(this),po(t,this),this.finished=!0;let{buffer:n,h:r}=this,{pos:o}=this;if(o){for(n[o++]=1;o<16;o++)n[o]=0;this.process(n,0,!0)}this.finalize();let i=0;for(let s=0;s<8;s++)t[i++]=r[s]>>>0,t[i++]=r[s]>>>8;return t}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}};function D_(e){let t=(r,o)=>e(o).update(r).digest(),n=e(new Uint8Array(32));return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>e(r),t}var ig=D_(e=>new mf(e));function U_(e,t,n,r,o,i=20){let s=e[0],a=e[1],c=e[2],l=e[3],u=t[0],d=t[1],p=t[2],m=t[3],w=t[4],y=t[5],b=t[6],x=t[7],I=o,E=n[0],U=n[1],S=n[2],B=s,R=a,A=c,N=l,f=u,k=d,_=p,K=m,H=w,P=y,j=b,L=x,z=I,W=E,$=U,O=S;for(let T=0;T<i;T+=2)B=B+f|0,z=ce(z^B,16),H=H+z|0,f=ce(f^H,12),B=B+f|0,z=ce(z^B,8),H=H+z|0,f=ce(f^H,7),R=R+k|0,W=ce(W^R,16),P=P+W|0,k=ce(k^P,12),R=R+k|0,W=ce(W^R,8),P=P+W|0,k=ce(k^P,7),A=A+_|0,$=ce($^A,16),j=j+$|0,_=ce(_^j,12),A=A+_|0,$=ce($^A,8),j=j+$|0,_=ce(_^j,7),N=N+K|0,O=ce(O^N,16),L=L+O|0,K=ce(K^L,12),N=N+K|0,O=ce(O^N,8),L=L+O|0,K=ce(K^L,7),B=B+k|0,O=ce(O^B,16),j=j+O|0,k=ce(k^j,12),B=B+k|0,O=ce(O^B,8),j=j+O|0,k=ce(k^j,7),R=R+_|0,z=ce(z^R,16),L=L+z|0,_=ce(_^L,12),R=R+_|0,z=ce(z^R,8),L=L+z|0,_=ce(_^L,7),A=A+K|0,W=ce(W^A,16),H=H+W|0,K=ce(K^H,12),A=A+K|0,W=ce(W^A,8),H=H+W|0,K=ce(K^H,7),N=N+f|0,$=ce($^N,16),P=P+$|0,f=ce(f^P,12),N=N+f|0,$=ce($^N,8),P=P+$|0,f=ce(f^P,7);let g=0;r[g++]=s+B|0,r[g++]=a+R|0,r[g++]=c+A|0,r[g++]=l+N|0,r[g++]=u+f|0,r[g++]=d+k|0,r[g++]=p+_|0,r[g++]=m+K|0,r[g++]=w+H|0,r[g++]=y+P|0,r[g++]=b+j|0,r[g++]=x+L|0,r[g++]=I+z|0,r[g++]=E+W|0,r[g++]=U+$|0,r[g++]=S+O|0}var M_=og(U_,{counterRight:!1,counterLength:4,allowShortKeys:!1}),j_=new Uint8Array(16),sg=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(j_.subarray(n))},K_=new Uint8Array(32);function ag(e,t,n,r,o){o!==void 0&&xe(o,void 0,"AAD");let i=e(t,n,K_),s=eg(r.length,o?o.length:0,!0),a=ig.create(i);o&&sg(a,o),sg(a,r),a.update(s);let c=a.digest();return qe(i,s),c}var W_=e=>(t,n,r)=>({encrypt(i,s){let a=i.length;s=pf(a+16,s,!1),s.set(i);let c=s.subarray(0,-16);e(t,n,c,c,1);let l=ag(e,t,n,c,r);return s.set(l,a),qe(l),s},decrypt(i,s){s=pf(i.length-16,s,!1);let a=i.subarray(0,-16),c=i.subarray(-16),l=ag(e,t,n,a,r);if(!Jb(c,l))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),e(t,n,s,s,1),qe(l),s}}),wf=Qb({blockSize:64,nonceLength:12,tagLength:16},W_(M_));var yf=class{constructor(t){Object.defineProperty(this,"_key",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._key=new Uint8Array(se(t))}async seal(t,n,r){return await this._seal(se(t),se(n),se(r))}async open(t,n,r){return await this._open(se(t),se(n),se(r))}_seal(t,n,r){return new Promise(o=>{let i=wf(this._key,new Uint8Array(t),new Uint8Array(r)).encrypt(new Uint8Array(n));o(i.buffer)})}_open(t,n,r){return new Promise(o=>{let i=wf(this._key,new Uint8Array(t),new Uint8Array(r)).decrypt(new Uint8Array(n));o(i.buffer)})}},Pi=class{constructor(){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:Vn.Chacha20Poly1305}),Object.defineProperty(this,"keySize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"nonceSize",{enumerable:!0,configurable:!0,writable:!0,value:12}),Object.defineProperty(this,"tagSize",{enumerable:!0,configurable:!0,writable:!0,value:16})}createEncryptionContext(t){return new yf(t)}};var V_=e=>new TextEncoder().encode(String(e)),bf=e=>{if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);throw new h("bad-input",{field:"viewEnvelope"})},cg=e=>{let t="0x";for(let n of bf(e))t+=n.toString(16).padStart(2,"0");return t},lg=(e,t,n)=>{let r=String(e??"").replace(/^0x/,"");if(!new RegExp("^[0-9a-fA-F]{"+t*2+"}$").test(r))throw new h("bad-input",{field:n});let o=new Uint8Array(t);for(let i=0;i<t;i+=1)o[i]=parseInt(r.slice(i*2,i*2+2),16);return o},$_=()=>new Ii({kem:new Bi,kdf:new Ti,aead:new Pi}),z_="ninsei-relay-view-v1";function ug({termsDigest:e,commitHalf:t,edPoint:n,edViewPointClient:r,edViewPointNode:o}={}){let i=[["termsDigest",e],["commitHalf",t],["edPoint",n],["edViewPointClient",r],["edViewPointNode",o]].map(([l,u])=>lg(u,32,l)),s=V_(z_),a=new Uint8Array(s.length+i.reduce((l,u)=>l+u.length,0));a.set(s,0);let c=s.length;for(let l of i)a.set(l,c),c+=l.length;return a}async function dg({hpkeKey:e,info:t,plaintext:n}={}){let r=lg(e,32,"hpkeKey"),o=bf(n);if(o.length!==32&&o.length!==64)throw new h("bad-input",{field:"plaintext"});if(!(t instanceof Uint8Array))throw new h("bad-input",{field:"info"});let i=$_(),s=null;try{s=await i.kem.deserializePublicKey(r);let a=await i.createSenderContext({recipientPublicKey:s,info:t}),c=bf(await a.seal(o));return{enc:cg(a.enc),ciphertext:cg(c)}}catch(a){throw a instanceof h?a:new h("bad-input",{field:"hpkeKey"})}}var X_="Ninsei Relay",Y_="1",G_=["EIP712Domain(","string name,","string version)"],q_=G_.join(""),gf=[["chainId","uint256"],["factory","address"],["locker","address"],["claimer","address"],["amount","uint256"],["readyBy","uint64"],["t1","uint64"],["salt","bytes32"]],pg="FirmOrder("+gf.map(([e,t])=>t+" "+e).join(",")+")",xf=[["market","string"],["side","string"],["maker","address"],["registry","address"],["featuresHash","bytes32"],["xmrNetwork","string"],["order","FirmOrder"],["xmrAmount","uint256"],["claimTip","uint256"]],Q_="FirmTerms("+xf.map(([e,t])=>t+" "+e).join(",")+")"+pg,Ci=e=>new TextEncoder().encode(String(e)),kf=(...e)=>{let t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n},hg=(e,t)=>{let n=String(e??"").replace(/^0x/,"");if(!/^[0-9a-fA-F]*$/.test(n)||n.length%2)throw new h("bad-input",{field:t});let r=new Uint8Array(n.length/2);for(let o=0;o<r.length;o+=1)r[o]=parseInt(n.slice(o*2,o*2+2),16);return r},fg=(e,t,n)=>{let r=null;try{r=BigInt(String(e??"").trim())}catch{r=null}if(r===null||r<0n||r>=1n<<BigInt(n))throw new h("bad-input",{field:t});let o=new Uint8Array(32);for(let i=31;i>=0&&r>0n;i-=1)o[i]=Number(r&0xffn),r>>=8n;return o},Z_=(e,t)=>{let n=String(e??"").trim();if(!/^(0x)?[0-9a-fA-F]{40}$/.test(n))throw new h("bad-input",{field:t});let r=new Uint8Array(32);return r.set(hg(n.replace(/^0x/,""),t),12),r},J_=(e,t)=>{let n=hg(e,t);if(n.length!==32)throw new h("bad-input",{field:t});return n},e6=(e,t,n,r)=>{if(t==="string")return e.keccak256(Ci(n??""));if(t==="address")return Z_(n,r);if(t==="bytes32")return J_(n,r);if(t==="uint64")return fg(n,r,64);if(t==="uint256")return fg(n,r,256);throw new h("bad-input",{field:r})},mg=(e,t,n,r,o)=>{let i=[e.keccak256(Ci(t))];for(let[s,a]of n)if(a==="FirmOrder"){let c=r&&r.order;if(!c||typeof c!="object")throw new h("bad-input",{field:o+".order"});i.push(t6(e,c))}else i.push(e6(e,a,r?r[s]:void 0,o+"."+s));return e.keccak256(kf(...i))};function t6(e,t){return mg(e,pg,gf,t,"terms.order")}function n6(e){return e.keccak256(kf(e.keccak256(Ci(q_)),e.keccak256(Ci(X_)),e.keccak256(Ci(Y_))))}function r6({crypto:e,terms:t}={}){if(!e||typeof e.keccak256!="function")throw new h("bad-input",{field:"crypto"});return mg(e,Q_,xf,t,"terms")}function wg({crypto:e,terms:t}={}){if(!e||typeof e.keccak256!="function")throw new h("bad-input",{field:"crypto"});return e.keccak256(kf(Uint8Array.from([25,1]),n6(e),r6({crypto:e,terms:t})))}function yg(e){let t=[];if(!e||typeof e!="object")return["terms"];for(let[n]of xf)if(n==="order")if(!e.order||typeof e.order!="object")t.push("order");else for(let[r]of gf){let o=e.order[r];(o==null||o==="")&&t.push("order."+r)}else{let r=e[n];(r==null||r==="")&&t.push(n)}return t}var kg=(e,t,n)=>{let r=String(e??"").replace(/^0x/i,"");if(!new RegExp("^[0-9a-fA-F]{"+n*2+"}$").test(r))throw new h("bad-input",{field:t});let o=new Uint8Array(n);for(let i=0;i<n;i+=1)o[i]=parseInt(r.slice(i*2,i*2+2),16);return o},Ri=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},We=(e,t,n)=>Ri(kg(e,n,t)),Sg=(e,t)=>{let n=null;try{n=BigInt(e)}catch{n=null}if(n===null||n<=0n||n>=Ge.Point.Fn.ORDER)throw new h("bad-input",{field:t});return n},bg=(e,t)=>{let n=Sg(e,t),r=new Uint8Array(32);for(let o=31;o>=0&&n>0n;o-=1)r[o]=Number(n&0xffn),n>>=8n;return r},gg=(e,t)=>Ri(Ge.Point.BASE.multiply(Sg(e,t)).toBytes()),xg=(e,t)=>{let n=kg(e,t,32);try{Ge.Point.fromHex(Ri(n).slice(2))}catch{throw new h("bad-input",{field:t})}return Ri(n)},o6=["XA","XB","pokA","pokB","proofs"];function i6(e){if(!e||typeof e!="object")throw new h("bad-input",{field:"clientHalf.proof"});for(let a of o6)if(e[a]===void 0||e[a]===null||e[a]==="")throw new h("bad-input",{field:"clientHalf.proof."+a});if(!Array.isArray(e.proofs)||e.proofs.length!==253)throw new h("bad-input",{field:"clientHalf.proof.proofs"});let t=We(e.XA,33,"clientHalf.proof.XA"),n=We(e.XB,32,"clientHalf.proof.XB"),r=(a,c,l)=>{if(!a||typeof a!="object")throw new h("bad-input",{field:"clientHalf.proof."+c});return{R:We(a.R,l,"clientHalf.proof."+c+".R"),s:We(a.s,32,"clientHalf.proof."+c+".s")}},o=r(e.pokA,"pokA",33),i=r(e.pokB,"pokB",32),s=e.proofs.map((a,c)=>{if(!a||typeof a!="object"||!a.sig)throw new h("bad-input",{field:"clientHalf.proof.proofs."+c});let l={};for(let u of["eA","eB","a0","a1","b0","b1"])l[u]=We(a.sig[u],32,"clientHalf.proof.proofs."+c+".sig."+u);return{cA:We(a.cA,33,"clientHalf.proof.proofs."+c+".cA"),cB:We(a.cB,32,"clientHalf.proof.proofs."+c+".cB"),sig:l}});return{XA:t,XB:n,pokA:o,pokB:i,proofs:s}}async function vg({features:e,terms:t,clientHalf:n,edViewPointClient:r,edViewPointNode:o,nodeViewScalar:i,clientViewScalar:s=null,side:a=null}={}){let c=Db({features:e,terms:t}),l=String(a||t?.side||"");if(l!=="ask"&&l!=="bid")throw new h("bad-input",{field:"side"});if(t?.side!==void 0&&t.side!==l)throw new h("bad-input",{field:"terms.side"});if(!t||typeof t!="object"||!t.order||typeof t.order!="object")throw new h("bad-input",{field:"terms"});if(t.featuresHash!==void 0&&t.featuresHash!==null&&t.featuresHash!==""&&String(t.featuresHash).toLowerCase()!==c.featuresHash)throw new h("quote-refused",{step:"features",why:"hash"});let u=t.order,d=["chainId","factory","locker","claimer","amount","readyBy","t1","salt"];for(let H of d)if(u[H]===void 0||u[H]===null||u[H]==="")throw new h("bad-input",{field:"terms.order."+H});if(String(u.chainId)!==String(t.market||"").split(":")[0])throw new h("bad-input",{field:"terms.market"});let p=n||{},m=We(p.commitHalf,32,"clientHalf.commitHalf"),w=We(p.edPoint,32,"clientHalf.edPoint"),y=i6(p.proof);if(y.XB!==w)throw new h("bad-input",{field:"clientHalf.edPoint"});let b=We(t.maker,20,"terms.maker"),x=We(u.locker,20,"terms.order.locker"),I=We(u.claimer,20,"terms.order.claimer");if(x===I)throw new h("bad-input",{field:"terms.order.roles"});if(l==="ask"){if(I!==b)throw new h("bad-input",{field:"terms.order.claimer"});if(String(t.claimTip)!=="0")throw new h("bad-input",{field:"terms.claimTip"})}else if(x!==b)throw new h("bad-input",{field:"terms.order.locker"});let E=xg(r,"edViewPointClient"),U=xg(o,"edViewPointNode"),S=bg(i,"nodeViewScalar");if(gg(i,"nodeViewScalar").toLowerCase()!==U.toLowerCase())throw new h("bad-input",{field:"edViewPointNode"});let B=bg(s,"clientViewScalar");if(gg(s,"clientViewScalar").toLowerCase()!==E.toLowerCase())throw new h("bad-input",{field:"edViewPointClient"});let R={market:String(t.market),side:l,maker:We(t.maker,20,"terms.maker"),registry:We(t.registry,20,"terms.registry"),featuresHash:c.featuresHash,xmrNetwork:String(t.xmrNetwork),order:{chainId:String(u.chainId),factory:We(u.factory,20,"terms.order.factory"),locker:We(u.locker,20,"terms.order.locker"),claimer:We(u.claimer,20,"terms.order.claimer"),amount:String(u.amount),readyBy:Number(u.readyBy),t1:Number(u.t1),salt:We(u.salt,32,"terms.order.salt")},xmrAmount:String(t.xmrAmount),claimTip:String(t.claimTip)},A=yg(R);if(A.length)throw new h("bad-input",{field:"terms",missing:A});let N=Ri(wg({crypto:{keccak256:q},terms:R})),f=ug({termsDigest:N,commitHalf:m,edPoint:w,edViewPointClient:E,edViewPointNode:U}),k=new Uint8Array(64);k.set(S,0),k.set(B,32);let _=await dg({hpkeKey:c.hpkeKey,info:f,plaintext:k});return{payload:JSON.stringify({terms:R,clientHalf:{commitHalf:m,edPoint:w,proof:y},edViewPointClient:E,edViewPointNode:U,viewEnvelope:_}),terms:R,viewEnvelope:_,edViewPointClient:E,edViewPointNode:U}}var s6="Quote(string relayId,address provider,bytes32 session,bytes32 requestId,uint64 counter,bytes32 requestHash,string payload,uint64 time)",a6="EIP712Domain(string name,string version)",c6="Ninsei Relay",l6="1",Hi=e=>new TextEncoder().encode(String(e)),oc=(...e)=>{let t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n},rc=(e,t,n)=>{let r=String(e??"").replace(/^0x/,"");if(!new RegExp("^[0-9a-fA-F]{"+n*2+"}$").test(r))throw new h("bad-input",{field:t});let o=new Uint8Array(n);for(let i=0;i<n;i+=1)o[i]=parseInt(r.slice(i*2,i*2+2),16);return o},u6=(e,t)=>{let n=new Uint8Array(32);return n.set(rc(e,t,20),12),n},Sf=(e,t)=>rc(e,t,32),Eg=(e,t)=>{let n=null;try{n=BigInt(e)}catch{n=null}if(n===null||n<0n)throw new h("bad-input",{field:t});let r=new Uint8Array(32);for(let o=31;o>=0&&n>0n;o-=1)r[o]=Number(n&0xffn),n>>=8n;return r},Ag=e=>q(Hi(e??""));function d6(e){if(!e||typeof e!="object")throw new h("bad-input",{field:"answer"});return q(oc(q(Hi(s6)),Ag(e.relayId),u6(e.provider,"answer.provider"),Sf(e.session,"answer.session"),Sf(e.requestId,"answer.requestId"),Eg(e.counter,"answer.counter"),Sf(e.requestHash,"answer.requestHash"),Ag(e.payload),Eg(e.time,"answer.time")))}function f6(){return q(oc(q(Hi(a6)),q(Hi(c6)),q(Hi(l6))))}function p6(e){return q(oc(Uint8Array.from([25,1]),f6(),d6(e)))}var h6=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t};function m6(e,t){let n=String(t||"").replace(/^0x/,"");if(!/^[0-9a-fA-F]{130}$/.test(n))return null;let r=parseInt(n.slice(128,130),16);if(r>=27&&(r-=27),r!==0&&r!==1)return null;try{let o=Ue.Signature.fromBytes(oc(rc(n.slice(0,64),"signature",32),rc(n.slice(64,128),"signature",32))).addRecoveryBit(r).recoverPublicKey(e);return h6(q(o.toBytes(!1).slice(1)).slice(12))}catch{return null}}function w6(e,t){if(!e||typeof e!="object"||e.type!=="quote"||Number(e.version)!==1)throw new h("quote-refused",{step:"answer",why:"frame"});let n=m6(p6(e),e.signature);if(n===null||n!==String(t||"").toLowerCase())throw new h("quote-refused",{step:"answer",why:"signature"});return e}var y6="0x"+"00".repeat(20),_g=e=>String(e??"").toLowerCase(),Qt=(e,t)=>_g(e)===_g(t);function b6(e,t,n){let r=t.order;if(!e||typeof e!="object")throw new h("quote-refused",{step:"answer",why:"quote"});let o=[["chainId",String(r.chainId)],["factory",r.factory],["locker",r.locker],["claimer",r.claimer],["amount",String(r.amount)],["readyBy",String(r.readyBy)],["t1",String(r.t1)],["salt",r.salt],["xmrAmount",String(t.xmrAmount)],["claimTip",String(t.claimTip)],["provider",t.maker],["registry",t.registry]];for(let[l,u]of o)if(!Qt(e[l],u))throw new h("quote-refused",{step:"answer",why:"field",field:l});if(Qt(e.feeRecipient,y6))throw new h("quote-refused",{step:"answer",why:"fee-recipient"});let i=Number(e.feeBps),s=null,a=null;try{s=BigInt(String(e.fee)),a=BigInt(String(r.amount))}catch{throw new h("quote-refused",{step:"answer",why:"fee"})}if(!Number.isSafeInteger(i)||i<0||i>200)throw new h("quote-refused",{step:"answer",why:"fee"});if(s!==a*BigInt(i)/10000n)throw new h("quote-refused",{step:"answer",why:"fee"});let c=Number(e.validUntil);if(!Number.isSafeInteger(c)||c<=n)throw new h("quote-expired",{step:"answer",validUntil:e.validUntil})}function Ng({answer:e,features:t,request:n,now:r=null}={}){if(!n||!n.terms)throw new h("bad-input",{field:"request"});if(w6(e,t&&t.quoteKey),!e.relayId||!Qt(e.relayId,t&&t.relayId))throw new h("quote-refused",{step:"answer",why:"relay"});let o=null;try{o=JSON.parse(e.payload)}catch{throw new h("quote-refused",{step:"answer",why:"payload"})}if(!o||typeof o!="object"||!o.quote)throw new h("quote-refused",{step:"answer",why:"payload"});if(o.contextVersion!=="ninsei-order-v3"||Number(o.quoteVersion)!==10)throw new h("quote-refused",{step:"answer",why:"version"});if(!Qt(o.factory,n.terms.order.factory))throw new h("quote-refused",{step:"answer",why:"factory"});if(!Qt(e.provider,n.terms.maker))throw new h("quote-refused",{step:"answer",why:"provider"});let i={...o.quote,factory:n.terms.order.factory};i.quoteSignature||(i.quoteSignature=o.quoteSignature);let s=null;try{s=bt.orderContextString(n.terms.order)}catch{s=null}if(!s||o.context!==s)throw new h("quote-refused",{step:"context",why:"other-terms"});let a=mi({...i,signature:o.quoteSignature});if(a===null)throw new h("quote-refused",{step:"signature",why:"invalid"});if(!Qt(a,i.quoteKey))throw new h("quote-refused",{step:"signature",why:"key"});let c=Math.floor((r===null?Date.now():r)/1e3);b6(i,n.terms,c);let l=n.terms.side,u=l==="ask"?n.edViewPointClient:n.edViewPointNode,d=l==="ask"?n.edViewPointNode:n.edViewPointClient;if(!Qt(o.edViewPointLocker,u)||!Qt(o.edViewPointClaimer,d))throw new h("quote-refused",{step:"answer",why:"view-points"});let p=o.nodeHalf;if(!p||typeof p!="object"||!p.proof)throw new h("quote-refused",{step:"answer",why:"node-half"});if(l==="ask"&&(!Qt(p.commitHalf,i.commitHalfClaimer)||!Qt(p.edPoint,i.edPointClaimer)))throw new h("quote-refused",{step:"answer",why:"node-half"});return{quote:i,orderQuote:{...i,factory:o.factory,signature:o.quoteSignature},nodeHalf:p,edViewPointLocker:o.edViewPointLocker,edViewPointClaimer:o.edViewPointClaimer,context:s}}var g6=new Set(["compliance","no_liquidity","size","paused","unavailable","bad_request","price_changed"]),x6=(e,t)=>String(e??"")===String(t??"");async function Ig({relayUrl:e,partner:t=null,fetchImpl:n=null,timeoutMs:r=2e4,retryTimeouts:o=1,...i}={}){let s=String(e??"").trim().replace(/\/+$/,"");if(!s)throw new h("bad-input",{field:"relayUrl"});let a=await vg(i),c=JSON.stringify({version:1,payload:a.payload,...t?{partner:String(t)}:{}}),l=at({apiBase:s,fetchImpl:n,timeoutMs:r}),u=null;try{let x=await l.tryJson("/v1/relay");if(!x||x.ok!==!0||!x.body||typeof x.body!="object")throw new h("quote-refused",{step:"relay-info",why:"unavailable"});u=x.body}catch(x){throw x instanceof h?x:new h("quote-refused",{step:"relay-info",why:"unavailable"})}let d=()=>l.tryJson("/v1/quote",{method:"POST",headers:{"content-type":"application/json"},body:c}),p;try{p=await d()}catch(x){if(o>0&&x&&x.code==="server-unavailable"&&x.params&&x.params.why==="timeout")p=await d();else throw x}if(!p.ok){let x=p.body&&p.body.code?String(p.body.code):null;throw x&&g6.has(x)?new h("quote-refused",{step:"relay",code:x,status:p.status}):new h("server-unavailable",{step:"relay",status:p.status})}let m=p.body&&p.body.answer;if(!p.body||Number(p.body.version)!==1||!m)throw new h("quote-refused",{step:"answer",why:"envelope"});if(typeof p.body.relay!="string"||!p.body.relay||!p.body.forwarded||p.body.forwarded.relayId!==p.body.relay)throw new h("quote-refused",{step:"answer",why:"relay"});if(!x6(m.relayId,p.body.relay))throw new h("quote-refused",{step:"answer",why:"relay"});let w=Ng({answer:m,features:i.features,request:a}),y=String(u.feeRecipient===void 0||u.feeRecipient===null?"":u.feeRecipient).toLowerCase(),b=String(w.quote.feeRecipient===void 0||w.quote.feeRecipient===null?"":w.quote.feeRecipient).toLowerCase();if(!y||y!==b)throw new h("quote-refused",{step:"fee",why:"fee-recipient"});if(!t&&String(u.feeBps)!==String(w.quote.feeBps))throw new h("quote-refused",{step:"fee",why:"fee-bps"});if(u.relayId!==void 0&&u.relayId!==null&&String(u.relayId)!==String(p.body.relay))throw new h("quote-refused",{step:"relay-info",why:"relay"});return{...w,relay:p.body.relay??null,offered:p.body.offered??null,forwarded:p.body.forwarded??null,answer:m}}var Tg=e=>new TextEncoder().encode(String(e)),pn=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},k6=()=>pn(q(Tg("providerOf(address)")).slice(0,4)),ic=e=>k6()+"0".repeat(24)+String(e).toLowerCase().replace(/^0x/,""),S6=()=>pn(q(Tg("factoryOf(address)")).slice(0,4)),vf=e=>S6()+"0".repeat(24)+String(e).toLowerCase().replace(/^0x/,""),yo=e=>{let t=String(e??"").replace(/^0x/,"");if(t.length%2)return null;let n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++){let o=parseInt(t.slice(r*2,r*2+2),16);if(Number.isNaN(o))return null;n[r]=o}return n},Qe="0x"+"00".repeat(20),Li=(e,t)=>String(e??"").toLowerCase()===String(t??"").toLowerCase(),xr=e=>{let t=String(e??"").replace(/^0x/,"");return t.length>=40?"0x"+t.slice(-40).toLowerCase():null},Ze=e=>e==null||e===""?null:Number.isFinite(Number(e))?Number(e):null,v6=e=>String(e||"").split("/")[0].toUpperCase(),E6=e=>String(e||"").split("/")[1]?String(e).split("/")[1].toUpperCase():"";function A6(e,t,n={},r={}){let o=t&&typeof t=="object"?t:{},i=String(e||o.pair||"").trim().toUpperCase();if(!i.includes("/"))return null;let s=o.asset?String(o.asset).toUpperCase():null,a=o.currency?String(o.currency).toUpperCase():null,c=v6(i),l=E6(i),u=Ze(o.rateQuote),d=Ze(o.rate),p=u!==null?u:d,m=null;u!==null?m=d:p!==null&&(m=l==="XMR"?p>0?1/p:null:p);let w=s&&s!==c||a&&a!==l,y=Ze(o.at);return{providerId:String(n.providerId||o.providerId||"").trim(),displayName:n.displayName||o.displayName||null,finality:n.finality||o.finality||null,pair:i,asset:s||c,currency:a||l,assetNetwork:o.assetNetwork?String(o.assetNetwork):null,currencyNetwork:o.currencyNetwork?String(o.currencyNetwork):null,rateQuote:p,rate:m,claimTip:(()=>{if(o.claimTip===void 0||o.claimTip===null||o.claimTip==="")return"0";try{let b=BigInt(o.claimTip);return b<0n?"0":b.toString()}catch{return"0"}})(),min:Ze(o.min),max:Ze(o.max),step:Ze(o.step),ttlMs:Ze(o.ttlMs)&&Ze(o.ttlMs)>0?Ze(o.ttlMs):null,at:y,why:o.why?String(o.why):null,disabled:o.disabled===!0||d!==null&&!(d>0),networksUnnamed:o.networksUnnamed===!0,networksDerived:o.networksDerived===!0,seq:Ze(o.seq)!==null?Ze(o.seq):Ze(n.seq)!==null?Ze(n.seq):Ze(r.seq),signature:o.signature||n.signature||null,keyId:o.keyId||null,networkStated:!!(o.assetNetwork||o.currencyNetwork),contradicts:w,ageMs:y===null?null:Math.max(0,Date.now()-y)}}function _6(e=[],{direction:t="buy",amount:n=null}={}){let r=Array.isArray(e)?e.filter(a=>a&&Number(a.rate)>0):[],o=Number(n),i=a=>{let c=Number(a.rate);if(t!=="sell"||!(o>0))return c;let l=0;try{l=Number(BigInt(a.claimTip||"0"))/1e18}catch{l=0}return o*c-l},s=r.map(a=>({offer:a,net:i(a)})).sort((a,c)=>c.net-a.net||Number(c.offer.rate)-Number(a.offer.rate));return{best:s.length?s[0].offer:null,net:s.length?s[0].net:null,ranked:s}}function N6(e,t=Date.now()){let n=e&&e.quotes,r=[],o=(l,u,d)=>{let p=A6(l,u,d,e||{});p&&r.push(p)};if(Array.isArray(n))for(let l of n){if(!l||typeof l!="object")continue;let u=l.quotes&&!Array.isArray(l.quotes)&&typeof l.quotes=="object"?l.quotes:null;if(u)for(let[d,p]of Object.entries(u))o(d,p,l);else o(l.pair,l,l)}else if(n&&typeof n=="object")for(let[l,u]of Object.entries(n))o(l,u,u&&typeof u=="object"?u:{});let i=new Map;for(let l of r){let u=(l.providerId||"?")+"|"+l.pair,d=i.get(u);(!d||Number(l.at)>Number(d.at))&&i.set(u,l)}let s=[],a=[];for(let l of i.values()){if(l.contradicts){a.push({...l,code:"malformed"});continue}if(l.rateQuote===null&&l.rate===null){a.push({...l,code:"malformed"});continue}if(l.disabled||!(l.rate>0)){a.push({...l,code:"disabled"});continue}if(l.ttlMs&&l.ageMs!==null&&l.ageMs>l.ttlMs){a.push({...l,code:"stale"});continue}s.push(l)}let c=s.slice().sort((l,u)=>u.rate-l.rate)[0]||null;return{offers:s,refused:a,best:c,at:t}}function Og(e,{min:t=null,max:n=null,step:r=null}={}){let o=Number(e);if(!Number.isFinite(o)||o<=0)return{size:null,asked:e,snapped:!1,code:"bad-size"};let i=Number(r),s=Number.isFinite(Number(t))&&t!==null&&t!==""?Number(t):0,a=Number.isFinite(Number(n))&&n!==null&&n!==""?Number(n):null;if(o<s)return{size:o,asked:o,snapped:!1,code:"below-min"};if(a!==null&&o>a)return{size:o,asked:o,snapped:!1,code:"above-max"};if(!Number.isFinite(i)||i<=0)return{size:o,asked:o,snapped:!1,code:null};let c=Math.floor((o-s)/i+1e-9),l=Number((s+c*i).toFixed(12));return l<s&&(l=s),{size:l,asked:o,snapped:Math.abs(l-o)>1e-12,code:null}}function I6(e,t,n,r=Date.now()){let o=e&&Number.isFinite(Number(e.rate))&&Number(e.rate)>0?Number(e.rate):null,i=t==="sell"?o!==null&&n>0?n*o:null:o!==null&&n>0?n/o:null;if(i===null)return{rate:o,size:null,unit:null,code:"no-offer",xmr:null};let s=Og(i,e||{});return{rate:o,size:s.size,unit:t==="sell"?String(e.currency||"").toUpperCase()||null:"XMR",snapped:s.snapped,code:s.code,xmr:t==="sell"?n:Number.isFinite(Number(s.size))?Number(s.size):null}}var Bg=e=>({providerId:e.providerId,displayName:e.displayName,pair:e.pair,rate:e.rate,rateQuote:e.rateQuote,min:e.min,max:e.max,step:e.step,ttlMs:e.ttlMs,at:e.at,seq:e.seq,finality:e.finality||null,asset:e.asset,currency:e.currency,assetNetwork:e.assetNetwork,currencyNetwork:e.currencyNetwork,networkStated:e.networkStated,networksDerived:e.networksDerived===!0,networksUnnamed:e.networksUnnamed===!0,claimTip:e.claimTip,why:e.why,signature:e.signature,keyId:e.keyId,ageMs:e.ageMs,networks:{asset:e.assetNetwork,currency:e.currencyNetwork,stated:e.networkStated}}),T6=e=>({...Bg(e),code:e.code,why:e.why});function Fi({claimTipWei:e=0,baseFeeWei:t=null,priorityFeeWei:n=0,factor:r=2}={}){let o=0n;try{o=BigInt(e==null||e===""?0:e)}catch{return{ok:!1,code:"quote-tip-unreadable"}}if(o<0n)return{ok:!1,code:"quote-tip-unreadable"};if(o===0n)return{ok:!0,tipWei:"0",ceilingWei:null,estimateWei:null};if(t==null||t==="")return{ok:!1,code:"quote-tip-unchecked",tipWei:o.toString()};let i=Gc({baseFeeWei:t,priorityFeeWei:n});if(i===null)return{ok:!1,code:"quote-tip-unchecked",tipWei:o.toString()};let s=BigInt(r),a=i*s;return o>a?{ok:!1,code:"quote-tip-too-large",tipWei:o.toString(),estimateWei:i.toString(),ceilingWei:a.toString()}:{ok:!0,tipWei:o.toString(),estimateWei:i.toString(),ceilingWei:a.toString()}}function Ef({config:e,http:t,now:n=()=>Date.now(),evmCall:r=null,evmCode:o=null,evmBlock:i=null,providerAllowed:s=null,knownFactoryCodes:a=null,knownImplementationCodes:c=null,denylist:l=null}){let u=Array.isArray(a)&&a.length?a.map(S=>String(S).toLowerCase()).filter(Boolean):null,d=Array.isArray(c)&&c.length?c.map(S=>String(S).toLowerCase()).filter(Boolean):null,p=new Set,m=null,w=1,y=null,b={direction:"buy",token:null,amount:null},x=!1,I=()=>{for(let S of p)S(y)},E=async()=>{if(!x){x=!0;try{let S=Number.isFinite(Number(b.size))&&Number(b.size)>0,B=S?Number(b.size):w,R=await t.json("/rate?amount="+encodeURIComponent(B)+"&side="+encodeURIComponent(b.direction)),A=N6(R,n()),N=Number.isFinite(Number(b.amount))?Number(b.amount):null,k=_6(A.offers,{direction:b.direction,amount:N}).best||A.best,_=k&&N!==null&&!S?I6(k,b.direction,N,n()):null;_&&_.size!==null&&(w=_.size);let K=k&&String(k.currency||"").toUpperCase()||null,H=S&&k?Og(B,k):null;y={direction:b.direction,token:b.token,amount:N,size:S?B:w,unit:S?b.direction==="sell"?K:"XMR":_?_.unit:null,rate:S?k?Number(k.rate):null:_?_.rate:null,xmr:_?_.xmr:null,at:n(),providerId:k?k.providerId:null,sizeOk:S?!!(H&&H.code===null):!!(_&&_.code===null),sizeCode:S?H?H.code:"no-offer":_?_.code:"no-offer",seq:A.offers.length?(A.offers.find(P=>P.seq!==null)||{}).seq??null:null,best:R&&R.best&&typeof R.best=="object"?{providerId:String(R.best.providerId||""),pair:String(R.best.pair||"")}:null,offers:A.offers.map(Bg),refused:A.refused.map(T6),references:Array.isArray(R&&R.references)?R.references.map(P=>({source:P.source,value:Ze(P.value),at:Ze(P.at)})):[],ok:A.offers.length>0},I()}catch(S){y={...y||{direction:b.direction,token:b.token,amount:null,size:w,unit:null,rate:null,xmr:null,at:n(),providerId:null,sizeOk:!1,sizeCode:null,seq:null,best:null,offers:[],refused:[],references:[]},at:n(),ok:!1,error:{code:S&&S.code==="server-unavailable"?"quote-unavailable":"unknown"}},I()}finally{x=!1}}},U=()=>{m&&clearInterval(m),m=null,p.size>0&&(E(),m=setInterval(()=>{E()},e.limits.quotePollMs))};return{watch(S,B){typeof B!="function"&&C("bad-input",{field:"onSnapshot"});let R=S&&S.direction==="sell"?"sell":"buy",A=S&&typeof S.token=="string"&&S.token?S.token.toLowerCase():e.settlement.chain.nativeSymbol.toLowerCase();return b={direction:R,token:A,amount:S&&S.amount!==void 0?S.amount:null,size:S&&Number.isFinite(Number(S.size))&&Number(S.size)>0?Number(S.size):null},w=1,y=null,p.add(B),U(),()=>{p.delete(B),p.size===0&&(m&&clearInterval(m),m=null)}},snapshot:()=>y,async sale(S){(!S||typeof S!="object")&&C("bad-input",{field:"request"});let B=S.request&&typeof S.request=="object"?S.request:S,R={...S.request&&typeof S.request=="object"?S:{request:S},sdkVersion:io},A=null;try{A=await t.tryJson(e.route("orderSell"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(R)})}catch(D){if(D&&D.code==="bad-input")throw D;C("server-unavailable",{step:"order-sell"})}(!A||A.ok!==!0||!A.body||A.body.ok!==!0)&&C("quote-refused",{step:"order-sell"});let N=A.body,f=N.handoff&&N.handoff.quote||N.quote||null;(!f||typeof f!="object")&&C("quote-field-unbound",{step:"order-sell",field:"quote"});let k=Kd(f);k.length&&C("quote-field-unbound",{step:"signature",missing:k});let _=Number(f.validUntil),K=Math.floor(n()/1e3);(!Number.isSafeInteger(_)||_<=K)&&C("quote-expired",{step:"signature",validUntil:f.validUntil});let H=mi(f);H===null&&C("quote-signature-invalid",{step:"signature"});let P=String(f.quoteKey).toLowerCase();H!==P&&C("quote-key-mismatch",{step:"signature",got:H,want:P});let j=String(f.registry||"").toLowerCase();(!/^0x[0-9a-f]{40}$/.test(j)||j===Qe)&&C("quote-field-unbound",{step:"registry",field:"registry"});let L=String(f.provider||"").toLowerCase();(!/^0x[0-9a-f]{40}$/.test(L)||L===Qe)&&C("quote-field-unbound",{step:"registry",field:"provider"}),typeof r!="function"&&C("quote-registry-unchecked",{step:"registry",why:"no-chain-read"});let z=null;try{z=xr(await r({to:j,data:ic(P)}))}catch{C("quote-registry-unchecked",{step:"registry",why:"read-failed",registry:j})}(z===null||z===Qe)&&C("quote-key-unknown",{step:"registry",registry:j,quoteKey:P}),z!==L&&C("quote-provider-mismatch",{step:"registry",got:z,want:L}),typeof s=="function"&&s(L)!==!0&&C("quote-provider-not-allowed",{step:"policy",provider:L});let W=String(f.factory||"").toLowerCase();(!/^0x[0-9a-f]{40}$/.test(W)||W===Qe)&&C("quote-field-unbound",{step:"factory",field:"factory"});let $=null;try{$=xr(await r({to:j,data:vf(L)}))}catch{C("quote-factory-unchecked",{step:"factory",why:"read-failed",registry:j})}if(($===null||$===Qe)&&C("quote-factory-unknown",{step:"factory",registry:j,provider:L}),$!==W&&C("quote-factory-mismatch",{step:"factory",got:W,want:$}),u){typeof o!="function"&&C("quote-factory-unchecked",{step:"factory",why:"no-code-read"});let D=null;try{D=await o(W)}catch{C("quote-factory-unchecked",{step:"factory",why:"code-read-failed",factory:W})}let F=yo(D),M=pn(q(F||new Uint8Array(0)));u.includes(M)||C("quote-factory-code-unknown",{step:"factory",factory:W,codeHash:M})}if(d){typeof r!="function"&&C("quote-factory-unchecked",{step:"factory",why:"no-chain-read"}),typeof o!="function"&&C("quote-factory-unchecked",{step:"factory",why:"no-code-read"});let D=await Ie.verifyFactoryImplementationOnChain({factory:W,read:r,code:F=>o(F),policy:d,hashCode:F=>pn(q(yo(F)||new Uint8Array(0)))});if(!D.ok){let F=D.why==="implementation-code-unknown"||D.why==="implementation-code-mismatch"||D.why==="implementation-has-no-code";C(F?"quote-factory-code-unknown":"quote-factory-unchecked",{step:"factory",why:D.why,factory:W,implementation:D.implementation||null})}}let O=String(B&&B.claimer||f.claimer||"").toLowerCase();O&&l&&l.has(O)&&C("address-denied",{step:"order-sell"}),B&&B.claimer&&f.claimer&&String(B.claimer).toLowerCase()!==String(f.claimer).toLowerCase()&&C("quote-refused",{step:"order-sell",why:"claimer-not-bound"});let g=B&&(B.xmr!==void 0?B.xmr:B.xmrAmount!==void 0?B.xmrAmount:null);if(g!=null){let D=null;try{D=BigInt(String(g))}catch{D=null}if(D===null||D<10n**12n)try{D=db(String(g))}catch{D=null}let F=null;try{F=f.xmrAmount===void 0||f.xmrAmount===null||f.xmrAmount===""?null:BigInt(String(f.xmrAmount))}catch{F=null}(F===null||D===null||D!==F)&&C("quote-refused",{step:"order-sell",why:"xmr-amount"})}if(N.order&&typeof N.order=="object"){let D=(F,M)=>String(F??"").replace(/^0x/i,"").toLowerCase()===String(M??"").replace(/^0x/i,"").toLowerCase();for(let F of["locker","claimer","amount","readyBy","t1","salt"])D(N.order[F],f[F])||C("quote-refused",{step:"order-sell",why:"other-terms",field:F});if(f.context){let F=null;try{F=bt.orderContextString(N.order)}catch{F=null}F!==null&&String(f.context)!==F&&C("quote-refused",{step:"order-sell",why:"other-terms",field:"context"})}}let T=N.claimTip&&N.claimTip.wei!==void 0&&N.claimTip.wei!==null?String(N.claimTip.wei):null;T===null&&C("quote-field-unbound",{step:"claimTip",field:"claimTip"}),N.claimTip.signed!==!0&&C("quote-field-unbound",{step:"claimTip",field:"signed"});let v=null;try{v=f.claimTip===void 0||f.claimTip===null||f.claimTip===""?"0":BigInt(f.claimTip).toString()}catch{C("quote-field-unbound",{step:"claimTip",field:"claimTip"})}let V=null;try{V=BigInt(T)}catch{C("quote-tip-unreadable",{step:"claimTip"})}if((v===null||V<0n||BigInt(v)!==V)&&C("quote-refused",{step:"claimTip",why:"not-the-signed-tip"}),V>0n){typeof i!="function"&&C("quote-tip-unchecked",{step:"claimTip",why:"no-block-read"});let D=null;try{D=await i("latest")}catch{C("quote-tip-unchecked",{step:"claimTip",why:"block-read-failed"})}let F=D&&(D.baseFeePerGas!==void 0?D.baseFeePerGas:D.baseFeeWei),M=D&&D.priorityFeePerGas!==void 0?D.priorityFeePerGas:null;if(M===null&&D&&D.gasPrice!==void 0&&F!==void 0&&F!==null)try{let G=BigInt(D.gasPrice),Z=BigInt(F);M=G>Z?G-Z:0n}catch{M=0n}let X=Fi({claimTipWei:V,baseFeeWei:F,priorityFeeWei:M===null?0n:M});X.ok||C(X.code,{step:"claimTip",...X})}return N},async firm(S){(!S||typeof S!="object")&&C("bad-input",{field:"request"}),(typeof S.providerId!="string"||!S.providerId)&&C("bad-input",{field:"providerId"}),(!S.order||typeof S.order!="object")&&C("bad-input",{field:"order"}),l&&typeof S.order.locker=="string"&&l.has(S.order.locker.toLowerCase())&&C("address-denied",{step:"order-quote"});let B=null,R=S.viewHalfClaimer===void 0||S.viewHalfClaimer===null||S.viewHalfClaimer===""?null:String(S.viewHalfClaimer);try{B=await t.tryJson(e.route("orderQuote"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({providerId:S.providerId,order:S.order,...R===null?{}:{viewHalfClaimer:R},sdkVersion:io})})}catch(v){if(v&&v.code==="bad-input")throw v;C("server-unavailable",{step:"order-quote"})}(B&&B.body&&typeof B.body.code=="string"?B.body.code:null)==="denied-address"&&C("address-denied",{step:"order-quote"}),(!B||B.ok!==!0||!B.body||B.body.ok!==!0||!B.body.quote)&&C("quote-refused",{step:"order-quote"});let f=B.body.quote;if(R!==null){let v=f.viewHalfClaimer;(v==null||v==="")&&C("quote-field-unbound",{step:"viewHalfClaimer",field:"viewHalfClaimer"}),String(v).toLowerCase()!==R.toLowerCase()&&C("quote-refused",{step:"viewHalfClaimer",why:"not-echoed"})}let k=Kd(f);k.length&&C("quote-field-unbound",{step:"signature",missing:k});let _=Number(f.validUntil),K=Math.floor(n()/1e3);(!Number.isSafeInteger(_)||_<=K)&&C("quote-expired",{step:"signature",validUntil:f.validUntil});let H=mi(f);H===null&&C("quote-signature-invalid",{step:"signature"});let P=String(f.quoteKey).toLowerCase();H!==P&&C("quote-key-mismatch",{step:"signature",got:H,want:P});let j=String(f.registry||"").toLowerCase();(!/^0x[0-9a-f]{40}$/.test(j)||j===Qe)&&C("quote-field-unbound",{step:"registry",field:"registry"});let L=String(f.provider||"").toLowerCase();(!/^0x[0-9a-f]{40}$/.test(L)||L===Qe)&&C("quote-field-unbound",{step:"registry",field:"provider"}),typeof r!="function"&&C("quote-registry-unchecked",{step:"registry",why:"no-chain-read"});let z=null;try{z=xr(await r({to:j,data:ic(P)}))}catch{C("quote-registry-unchecked",{step:"registry",why:"read-failed",registry:j})}(z===null||z===Qe)&&C("quote-key-unknown",{step:"registry",registry:j,quoteKey:P}),z!==L&&C("quote-provider-mismatch",{step:"registry",got:z,want:L}),typeof s=="function"&&s(L)!==!0&&C("quote-provider-not-allowed",{step:"policy",provider:L});let W=String(f.factory||"").toLowerCase();(!/^0x[0-9a-f]{40}$/.test(W)||W===Qe)&&C("quote-field-unbound",{step:"factory",field:"factory"});let $=null;try{$=xr(await r({to:j,data:vf(L)}))}catch{C("quote-factory-unchecked",{step:"factory",why:"read-failed",registry:j})}if(($===null||$===Qe)&&C("quote-factory-unknown",{step:"factory",registry:j,provider:L}),$!==W&&C("quote-factory-mismatch",{step:"factory",got:W,want:$}),u){typeof o!="function"&&C("quote-factory-unchecked",{step:"factory",why:"no-code-read"});let v=null;try{v=await o(W)}catch{C("quote-factory-unchecked",{step:"factory",why:"code-read-failed",factory:W})}let V=yo(v),D=pn(q(V||new Uint8Array(0)));u.includes(D)||C("quote-factory-code-unknown",{step:"factory",factory:W,codeHash:D})}if(d){typeof r!="function"&&C("quote-factory-unchecked",{step:"factory",why:"no-chain-read"}),typeof o!="function"&&C("quote-factory-unchecked",{step:"factory",why:"no-code-read"});let v=await Ie.verifyFactoryImplementationOnChain({factory:W,read:r,code:V=>o(V),policy:d,hashCode:V=>pn(q(yo(V)||new Uint8Array(0)))});if(!v.ok){let V=v.why==="implementation-code-unknown"||v.why==="implementation-code-mismatch"||v.why==="implementation-has-no-code";C(V?"quote-factory-code-unknown":"quote-factory-unchecked",{step:"factory",why:v.why,factory:W,implementation:v.implementation||null})}}let O=null;try{O=bt.orderContextString(S.order)}catch{O=null}if(O===null){let v=f&&f.claimer;if(v)try{O=bt.orderContextString({...S.order,claimer:v})}catch{C("bad-input",{field:"order"})}else C("bad-input",{field:"order"})}let g=f.context||"";String(g)!==O&&C("quote-refused",{step:"context",why:g?"other-terms":"not-reported"});let T=(()=>{try{return Fi({claimTipWei:f.claimTip})}catch{return{ok:!0,tipWei:"0"}}})();if(!T.ok&&T.code==="quote-tip-unreadable"&&C("quote-field-unbound",{step:"claimTip",field:"claimTip"}),T.tipWei!=="0"){typeof i!="function"&&C("quote-tip-unchecked",{step:"claimTip",why:"no-block-read"});let v=null;try{v=await i("latest")}catch{C("quote-tip-unchecked",{step:"claimTip",why:"block-read-failed"})}let V=v&&(v.baseFeePerGas!==void 0?v.baseFeePerGas:v.baseFeeWei),D=Fi({claimTipWei:f.claimTip,baseFeeWei:V});D.ok||C(D.code,{step:"claimTip",...D})}return f},async firmRelay(S){(!S||typeof S!="object")&&C("bad-input",{field:"request"});let B=S.features,R=S.order&&typeof S.order=="object"?{...S.order}:null;(!B||typeof B!="object")&&C("bad-input",{field:"features"}),R||C("bad-input",{field:"order"});let A=String(S.side||"");A!=="ask"&&A!=="bid"&&C("bad-input",{field:"side"});let N=String(B.provider||"").toLowerCase(),f=String(B.registry||"").toLowerCase();(!/^0x[0-9a-f]{40}$/.test(N)||N===Qe)&&C("bad-input",{field:"features.provider"}),(!/^0x[0-9a-f]{40}$/.test(f)||f===Qe)&&C("bad-input",{field:"features.registry"}),(!/^0x[0-9a-f]{40}$/.test(String(B.quoteKey||"").toLowerCase())||String(B.quoteKey).toLowerCase()===Qe)&&C("bad-input",{field:"features.quoteKey"}),typeof r!="function"&&C("quote-registry-unchecked",{step:"features",why:"no-chain-read",registry:f});let k=null;try{k=xr(await r({to:f,data:ic(B.quoteKey)}))}catch{C("quote-registry-unchecked",{step:"features",why:"read-failed",registry:f})}(k===null||k===Qe)&&C("quote-key-unknown",{step:"registry",registry:f,quoteKey:B.quoteKey}),Li(k,B.provider)||C("quote-provider-mismatch",{step:"registry",got:k,want:B.provider}),l&&typeof R.locker=="string"&&l.has(R.locker.toLowerCase())&&C("address-denied",{step:"order-quote"}),A==="ask"?(R.claimer&&!Li(R.claimer,N)&&C("bad-input",{field:"order.claimer"}),R.claimer=N):(R.locker&&!Li(R.locker,N)&&C("bad-input",{field:"order.locker"}),R.locker=N);let _=Number(R.chainId);(!Number.isSafeInteger(_)||_<=0)&&C("bad-input",{field:"order.chainId"});let K=Array.isArray(B.firmWindows)?B.firmWindows.filter(ne=>ne&&ne.side===A):[],H=[...new Set(K.map(ne=>ne.market).filter(ne=>typeof ne=="string"&&ne))],P=S.market!==void 0?String(S.market):H.length===1?H[0]:null;P||C("bad-input",{field:"market"});let j=K.find(ne=>ne.market===P)||null;j||C("quote-refused",{step:"features",why:"window"});let L=S.xmrNetwork!==void 0?String(S.xmrNetwork):j.xmrNetwork;L||C("bad-input",{field:"xmrNetwork"}),(S.xmrAmount===void 0||S.xmrAmount===null||S.xmrAmount==="")&&C("bad-input",{field:"xmrAmount"});let z=S.claimTip===void 0||S.claimTip===null?"0":String(S.claimTip),W=typeof S.recoveryKey=="string"?S.recoveryKey:S.recoveryKey&&typeof S.recoveryKey.mnemonic=="string"?S.recoveryKey.mnemonic:null;W||C("bad-input",{field:"recoveryKey"});let $=S.recoverySalt!==void 0&&S.recoverySalt!==null;(!R.factory||!/^0x[0-9a-f]{40}$/i.test(String(R.factory)))&&C("bad-input",{field:"order.factory"});let O=null;try{O=un($?S.recoverySalt:R.salt)}catch{C("bad-input",{field:"recoverySalt"})}if($){let ne=null;try{ne=un(R.salt)}catch{C("bad-input",{field:"recoverySalt",why:"order-salt"})}O!==ne&&C("bad-input",{field:"recoverySalt",why:"order-salt"})}let g=hr({mnemonic:W,chainId:_,factory:R.factory,salt:O}),T={kind:"salt-v2",salt:O},v=mr(R,{spendHalf:g.spendHalf,viewHalf:g.viewHalf}),V=Ue.Point.fromHex(v.side.proof.XA),D={commitHalf:pn(q(V.toBytes(!1).slice(1))),edPoint:v.side.pub.ed,proof:v.side.proof},F=await Ig({relayUrl:S.relayUrl,partner:S.partner,fetchImpl:S.fetchImpl,timeoutMs:S.timeoutMs,features:B,terms:{market:P,side:A,maker:N,registry:f,xmrNetwork:L,order:R,xmrAmount:String(S.xmrAmount),claimTip:z},clientHalf:D,edViewPointClient:v.side.viewPub,edViewPointNode:g.makerViewPoint,nodeViewScalar:g.makerViewHalf,clientViewScalar:g.viewHalf,side:A}),M=F.quote,X=F.nodeHalf;tf({context:v.context,side:v.side,counterparty:A==="ask"?{proof:X.proof,edPub:M.edPointClaimer,commitHalfClaimer:M.commitHalfClaimer,viewPoint:F.edViewPointClaimer,viewHalf:g.makerViewHalf}:{proof:X.proof,edPub:X.edPoint,commitHalfClaimer:X.commitHalf,viewPoint:F.edViewPointLocker,viewHalf:g.makerViewHalf}});let G=A==="ask"?M.edPointClaimer:X.edPoint,Z=A==="ask"?F.edViewPointClaimer:F.edViewPointLocker,J=so({ownSpendHalf:g.spendHalf,ownViewHalf:g.viewHalf,otherSpendPoint:G,otherViewPoint:Z,network:L}),te=A==="ask"?{commitHalfLocker:D.commitHalf,edPointLocker:v.side.pub.ed,edViewPointLocker:v.side.viewPub}:{commitHalfLocker:X.commitHalf,edPointLocker:X.edPoint,edViewPointLocker:F.edViewPointLocker},ke=null;try{let ne=await r({to:M.factory,data:Ie.encodePredict({...F.orderQuote,...te,signature:F.orderQuote.signature})});ke=Ie.decodeAddress(ne)}catch{C("quote-escrow-unchecked",{step:"factory",why:"predict-failed",factory:M.factory})}s&&s(N)!==!0&&C("quote-provider-not-allowed",{step:"policy",provider:N}),typeof r!="function"&&C("quote-registry-unchecked",{step:"registry",why:"no-chain-read"});let Y=null;try{Y=xr(await r({to:f,data:ic(M.quoteKey)}))}catch{C("quote-registry-unchecked",{step:"registry",why:"read-failed",registry:f})}(Y===null||Y===Qe)&&C("quote-key-unknown",{step:"registry",registry:f,quoteKey:M.quoteKey}),Li(Y,M.provider)||C("quote-provider-mismatch",{step:"registry",got:Y,want:M.provider});let ee=null;try{ee=xr(await r({to:f,data:vf(M.provider)}))}catch{C("quote-factory-unchecked",{step:"factory",why:"read-failed",registry:f})}if((ee===null||ee===Qe)&&C("quote-factory-unknown",{step:"factory",registry:f,provider:M.provider}),Li(ee,M.factory)||C("quote-factory-mismatch",{step:"factory",got:M.factory,want:ee}),u){typeof o!="function"&&C("quote-factory-unchecked",{step:"factory",why:"no-code-read"});let ne=null;try{ne=await o(M.factory)}catch{C("quote-factory-unchecked",{step:"factory",why:"code-read-failed",factory:M.factory})}let we=pn(q(yo(ne)||new Uint8Array(0)));u.includes(we)||C("quote-factory-code-unknown",{step:"factory",factory:M.factory,codeHash:we})}if(d){typeof r!="function"&&C("quote-factory-unchecked",{step:"factory",why:"no-chain-read"}),typeof o!="function"&&C("quote-factory-unchecked",{step:"factory",why:"no-code-read"});let ne=await Ie.verifyFactoryImplementationOnChain({factory:M.factory,read:r,code:we=>o(we),policy:d,hashCode:we=>pn(q(yo(we)||new Uint8Array(0)))});if(!ne.ok){let we=ne.why==="implementation-code-unknown"||ne.why==="implementation-code-mismatch"||ne.why==="implementation-has-no-code";C(we?"quote-factory-code-unknown":"quote-factory-unchecked",{step:"factory",why:ne.why,factory:M.factory,implementation:ne.implementation||null})}}let le=(()=>{try{return Fi({claimTipWei:M.claimTip})}catch{return{ok:!0,tipWei:"0"}}})();if(!le.ok&&le.code==="quote-tip-unreadable"&&C("quote-field-unbound",{step:"claimTip",field:"claimTip"}),le.tipWei!=="0"){typeof i!="function"&&C("quote-tip-unchecked",{step:"claimTip",why:"no-block-read"});let ne=null;try{ne=await i("latest")}catch{C("quote-tip-unchecked",{step:"claimTip",why:"block-read-failed"})}let we=ne&&(ne.baseFeePerGas!==void 0?ne.baseFeePerGas:ne.baseFeeWei),nt=Fi({claimTipWei:M.claimTip,baseFeeWei:we});nt.ok||C(nt.code,{step:"claimTip",...nt})}let Oe=F.orderQuote&&F.orderQuote.xmrAmount!==void 0&&F.orderQuote.xmrAmount!==null?String(F.orderQuote.xmrAmount):null;return Oe||C("quote-field-unbound",{step:"xmrAmount",field:"orderQuote.xmrAmount"}),{...F,quote:{...M,viewHalfClaimer:g.makerViewHalf,xmrAmount:Oe},order:{...R,xmrAmount:Oe},counterparty:{proof:X.proof,edPointClaimer:A==="ask"?M.edPointClaimer:X.edPoint,commitHalfClaimer:A==="ask"?M.commitHalfClaimer:X.commitHalf,viewHalfClaimer:g.makerViewHalf,viewPoint:A==="ask"?F.edViewPointClaimer:F.edViewPointLocker},viewHalfClaimer:g.makerViewHalf,viewHalfPoint:g.makerViewPoint,jointAddress:J.address,escrow:ke,recovery:T}}}}var O6=e=>{let t=e&&typeof e=="object"?e:{},{reason:n,kind:r,ok:o,checked:i,blocks:s,...a}=t;return{code:Cy(r),ok:o===!0,checked:i!==!1,blocks:s===!0,kind:typeof r=="string"?r:"unknown",params:a}},Pg=(...e)=>e.some(t=>t!=null&&t!==""),Ft=(e,t)=>{try{return e(t)}catch(n){return{ok:!1,checked:!1,blocks:!1,kind:"unchecked",error:String(n&&n.message?n.message:n)}}};function Cg({config:e,wallet:t,limits:n={}}){return async function(o={},i={}){let s=oe.SIGNING_GUARDS||{},a=Number.isFinite(i.nowMs)?i.nowMs:Date.now(),c=o&&typeof o=="object"?o:{},l=!!i.tokenIsNative,u=e.evmNetwork,p=[Ft(pe.quoteFreshnessVerdict,{at:Number.isFinite(c.at)?c.at:null,ttlMs:Number.isFinite(c.ttlMs)?c.ttlMs:null,expiresAt:Number.isFinite(c.expiresAt)?c.expiresAt:null,nowMs:a}),Ft(pe.deadlineVerdict,{nowSec:Math.floor(a/1e3),readyBy:Number.isFinite(c.readyBy)?c.readyBy:null,t1:Number.isFinite(c.t1)?c.t1:null,minReadyLeadSec:s.minReadyLeadSec??null,minClaimWindowSec:s.minClaimWindowSec??null}),Ft(pe.rangeVerdict,{size:Number.isFinite(c.amount)?c.amount:null,unit:c.token||null,min:Number.isFinite(c.min)?c.min:n.minAmount??null,max:Number.isFinite(c.max)?c.max:n.maxAmount??null,step:Number.isFinite(c.step)?c.step:n.stepAmount??null,quoteUnit:c.token||null}),Ft(pe.payBalanceVerdict,{payBalanceWei:i.payBalanceWei??null,payAmountWei:i.payAmountWei??null,symbol:l?u.nativeSymbol:c.token||null,decimals:Number.isFinite(i.decimals)?i.decimals:18}),Ft(pe.gasReserveVerdict,{nativeBalanceWei:i.nativeBalanceWei??null,requiredNativeWei:i.requiredNativeWei??null,gasReserveWei:i.gasReserveWei??null,symbol:u.nativeSymbol,decimals:18}),Ft(pe.allowanceVerdict,{tokenIsNative:l,allowanceWei:i.allowanceWei??null,amountWei:i.payAmountWei??null,consent:i.allowanceConsent===!0,symbol:c.token||null,decimals:Number.isFinite(i.decimals)?i.decimals:18}),Ft(pe.networkGateVerdict,{walletChainId:t.status().chainId,selectedChainId:u.chainId,settlementChainId:u.chainId,selectedChainName:u.name}),Ft(pe.counterpartyVerdict,{standIn:i.standIn===!0,liveChain:i.liveChain===!0,network:e.evmNetwork.id,chainId:u.chainId}),Ft(pe.escrowStateVerdict,{status:i.escrowStatus??null,error:null,address:i.escrowAddress??null}),...Pg(i.point,i.commit)?[Ft(pe.escrowPointsVerdict,{role:i.pointsRole??null,what:i.pointsWhat??null,point:i.point??null,onchainPoint:i.onchainPoint??null,commit:i.commit??null,onchainCommit:i.onchainCommit??null,readError:i.pointsReadError??null})]:[],...Pg(i.slots)?[Ft(pe.liveOrderSlotsVerdict,{slots:i.slots??null,expect:i.slotsExpect??null,readError:i.slotsReadError??null})]:[]].map(O6),m=[...new Set(p.filter(w=>w.blocks).map(w=>w.code))];return{ok:m.length===0,blockedBy:m,checks:p}}}var Rg=e=>typeof e=="string"?e:e&&typeof e.contents=="string"?e.contents:null;function Af({http:e=null,config:t=null}={}){return{async open(n,r){let o=Rg(n);if(o===null)throw new h("bad-input",{field:"file"});let i;try{i=JSON.parse(o)}catch{throw new h("recovery-failed",{stage:"parse"})}let s;try{s=await rs.restoreFromFile(i,r)}catch{throw new h("recovery-failed",{stage:"restore"})}let a=s.payload||{},c=s.wallet||{},l=Number(a.version)>=3;return{address:typeof c.address=="string"?c.address:null,spendable:!l,swapId:typeof a.swapId=="string"?a.swapId:null}},async restoreHeight(n={}){let r=Rg(n.file);if(r===null)throw new h("bad-input",{field:"file"});if(typeof n.passphrase!="string")throw new h("bad-input",{field:"passphrase"});let o;try{o=JSON.parse(r)}catch{throw new h("recovery-failed",{stage:"parse"})}let i;try{i=await ut.decryptFile(o,n.passphrase),ut.validatePayload(i)}catch{throw new h("recovery-failed",{stage:"restore"})}let s=i.moneroWallet||{},a=typeof s.address=="string"&&s.address?s.address:null,c=Number(s.restoreHeight)||0,l=0,u=!1,d=null;if(e&&t&&a){u=!0;try{let w=await e.json(t.route("swaps")),b=(Array.isArray(w)?w:w&&w.swaps||[]).find(x=>String(x&&x.address||"")===String(a))||null;l=Number(b&&b.restoreHeight)||0,b||(d="no-row")}catch{d="unreachable"}}let p=l>0?l:c,m=l>0?"app":c>0?"file":"none";return{address:a,height:p,source:m,fileHeight:c,appHeight:l,appAsked:u,appProblem:m==="none"?d||"no-height":null}}}}var sc=Object.keys(oe.SCENARIO_LABELS||{});function Hg(){let e=sc[0]||null,t=1,n=0;return{scenarios:()=>sc.slice(),apply(r){sc.includes(r)||C("bad-input",{field:"scenario",known:sc}),e=r},speed(r){let o=Number(r);(!Number.isFinite(o)||o<=0)&&C("bad-input",{field:"speed"}),t=o},advance(r){let o=Number(r);Number.isFinite(o)||C("bad-input",{field:"ms"}),n+=o},debug:()=>({scenario:e,speed:t,advancedMs:n})}}var B6=["connect","disconnect","address","chainId","subscribe","driver"],Lg=e=>e&&Yr.includes(e.code)?e.code:"unknown",_f="monero",Di={token:"xmr",symbol:"XMR",decimals:12},P6=2;function Fg({settlement:e,leg:t}){let n=null,r={connected:!1,address:null,chainId:null,chainMatches:!1},o=new Set,i=null,s=async(c=!0)=>{if(!n)return r;let[l,u]=await Promise.all([Promise.resolve(n.address()).catch(()=>null),Promise.resolve(n.chainId()).catch(()=>null)]),d=typeof l=="string"&&l.length>0;if(r={connected:d,address:d?l:null,chainId:u===void 0?null:u,chainMatches:d&&t.sameChain(u,e)},c)for(let p of o)p(r);return r},a=()=>{typeof i=="function"&&i(),i=null};return{use(c){(!c||typeof c!="object")&&C("bad-input",{field:"adapter"});let l=B6.filter(d=>typeof c[d]!="function");l.length&&C("bad-input",{field:"adapter",missing:l}),(typeof c.vm!="string"||!c.vm)&&C("bad-input",{field:"adapter.vm"});let u=[e.vm,_f];u.includes(c.vm)||C("bad-input",{field:"adapter.vm",expected:e.vm,accepted:u,got:c.vm}),a(),n=c,i=n.subscribe(()=>{s().catch(()=>{})}),r={connected:!1,address:null,chainId:null,chainMatches:!1},s().catch(()=>{})},status:()=>r,async connect({chainId:c=null}={}){n||C("wallet-not-connected");try{let l=c===null&&n.vm===e.vm?t.walletChainId(e):c;await n.connect(l===null?{}:{chainId:l})}catch(l){throw new h(Lg(l),{vm:n.vm})}return s()},async disconnect(){return n&&await Promise.resolve(n.disconnect()).catch(()=>{}),a(),n=null,void await s()},address:()=>r.address,async switchChain(c){n||C("wallet-not-connected"),Number.isFinite(Number(c))||C("bad-input",{field:"chainId"}),(n.vm!==e.vm||typeof n.switchChain!="function")&&C("not-implemented",{surface:"wallet.switchChain",vm:n.vm,stage:P6});try{await n.switchChain(Number(c))}catch(u){throw new h(Lg(u),{vm:n.vm})}let l=await s();return l.chainMatches||C("wrong-chain",{got:l.chainId,want:t.walletChainId(e)}),l},async balances(c){n||C("wallet-not-connected");let l=r.connected?r:await s(!1);if(l.connected||C("wallet-not-connected"),n.vm===_f){let w=(Array.isArray(c)&&c.length?c.map(b=>String(b).toLowerCase()):[Di.token]).find(b=>b!==Di.token);w!==void 0&&C("bad-input",{field:"tokens",unknown:w}),typeof n.unlockedBalance!="function"&&C("not-implemented",{surface:"wallet.balances",vm:_f});let y=BigInt(await n.unlockedBalance()).toString();return[{token:Di.token,symbol:Di.symbol,decimals:Di.decimals,amount:y}]}l.chainMatches||C("wrong-chain",{got:l.chainId,want:t.walletChainId(e)}),typeof t.balances!="function"&&C("not-implemented",{surface:"wallet.balances",vm:e.vm});let u=e.tokens||[],d=Array.isArray(c)&&c.length?c.map(m=>String(m).toLowerCase()):u.map(m=>m.id),p=[];for(let m of d){let w=u.find(y=>y.id===m);w||C("bad-input",{field:"tokens",unknown:m}),p.push(w)}return t.balances({driver:n.driver(),address:l.address,tokens:p})},subscribe(c){return typeof c!="function"&&C("bad-input",{field:"handler"}),o.add(c),()=>o.delete(c)},driver:()=>n?n.driver():null}}function C6(e=null,t=null){if(t&&t.spendHalf&&t.viewHalf)return mr(e,t).side;if(e!=null)return ef(e).side;let n=tn.createHalves(Ln),r=n.newHalf(),o=n.newHalf();return{half:r,viewHalf:o,pub:n.publicHalves(r),viewPub:n.publicHalves(o).ed}}function Nf(e,{order:t=null,side:n=null,store:r=null}={}){if(!e||typeof e!="object")throw new h("bad-input",{field:"input"});let o=n||C6(t),i=null;try{i=fe.createSwap(e,r)}catch{throw new h("bad-input",{field:"input"})}let s={...i.escrow||{},half:dn(o.half),viewHalf:dn(o.viewHalf),edPointLocker:Se(o.pub.ed),edViewPointLocker:Se(o.viewPub)};if(e.expectedAtomic!==void 0&&e.expectedAtomic!==null){let l;try{l=BigInt(String(e.expectedAtomic))}catch{throw new h("bad-input",{field:"expectedAtomic"})}if(l<=0n)throw new h("bad-input",{field:"expectedAtomic"});s.expectedAtomic=l.toString()}o.enc&&o.enc.pub&&(s.encPub=Se(o.enc.pub));let a={...i,escrow:s},c=e&&e.orderQuoteId;c!=null&&c!==""&&(a.orderQuoteId=c);try{fe.saveSwap(a,r)}catch{throw new h("storage-unavailable",{step:"save-swap"})}return{swap:a,side:o,missing:["counterparty-half"],nextStep:"order"}}var H6="Declined",L6=()=>`${H6}(${["address"].join(",")})`,F6=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},bo=F6(q(L6())),D6="declined",cc="compliance",hn="declined",U6=["declined","terminal","code","source","at","checked"],Dg=e=>{let t={};for(let n of U6)t[n]=e[n]===void 0?null:e[n];return t},Ug=({source:e=null,at:t=null}={})=>Dg({declined:!0,terminal:hn,code:cc,source:e,at:t,checked:!0}),ac=({source:e=null,at:t=null,checked:n=!0}={})=>Dg({declined:!1,terminal:null,code:null,source:e,at:t,checked:n});function If(e,{escrow:t=null,at:n=null}={}){if(!Array.isArray(e))throw new h("bad-input",{field:"logs",why:"not-array"});let r=typeof t=="string"&&t?t.toLowerCase():null;for(let o of e){if(!o||typeof o!="object"||r&&typeof o.address=="string"&&o.address&&o.address.toLowerCase()!==r)continue;let i=Array.isArray(o.topics)?o.topics:[];if(String(i[0]||"").toLowerCase()===bo)return Ug({source:"event",at:n})}return ac({source:"event",at:n})}function M6(e,{at:t=null}={}){if(!e||typeof e!="object")return ac({source:"status",at:t,checked:!1});for(let n of[e,e.userStatus])if(!(!n||typeof n!="object")&&String(n.status||"")===D6&&String(n.code||"")===cc)return Ug({source:"status",at:t});return ac({source:"status",at:t})}function Mg({logs:e=void 0,status:t=void 0,escrow:n=null,at:r=null}={}){let o=Array.isArray(e)?If(e,{escrow:n,at:r}):null;if(o&&o.declined)return o;let i=t&&typeof t=="object"?M6(t,{at:r}):null;return i&&i.declined?i:o||i||ac({checked:!1,at:r})}async function j6({address:e,topics:t=[bo],fromBlock:n="earliest",toBlock:r="latest"}={}){if(typeof e!="string"||!/^0x[0-9a-fA-F]{40}$/.test(e))throw new h("bad-input",{field:"logs.address"});let o=null;try{o=typeof Ie.currentProvider=="function"?Ie.currentProvider():null}catch{o=null}if(!o||typeof o.request!="function")throw new h("bad-input",{field:"evmLogs",why:"no-provider"});let i=await o.request({method:"eth_getLogs",params:[{address:e,topics:t,fromBlock:n,toBlock:r}]});if(!Array.isArray(i))throw new h("server-unavailable",{step:"logs",why:"bad-response"});return i}var lc=e=>typeof e=="function"?e:j6,uc=(e,t="earliest")=>{let n=Number(e);return!Number.isFinite(n)||n<0?t:"0x"+Math.trunc(n).toString(16)};var{chainById:NC,DEFAULT_CHAIN:IC,MONERO:TC}=oe,{fundOrderLive:OC,newSecret:BC,sendTransaction:Tf,readContract:dc}=Ie,{encodeClaim:K6,encodeRefund:W6,encodeMarkReady:V6,encodeStatus:$6,encodeT1:z6,encodeTermsHash:X6,encodeRead:Of,decodeUint64:jg,decodeBytes32:Kg,decodeStatus:Y6}=Or,{liveOrderSlotsVerdict:G6,counterpartyVerdict:PC}=pe,{createOrderWorker:CC}=Ds,{orderContextString:RC}=bt,{requestOrderQuote:HC,checkOrderQuoteShape:LC}=js,{CLAIM_GAS_LIMIT:q6}=as;async function kr(e,t={}){if(!e)throw new h("bad-input",{field:"escrow"});let r=await(t.call||dc)({to:e,data:$6()});return Y6(r)}async function Wg(e,t={}){if(typeof e!="string"||!e)throw new h("bad-input",{field:"escrow"});let n=lc(t.logs),r=t.fromBlock===void 0?"earliest":uc(t.fromBlock),o=await n({address:e,topics:[bo],fromBlock:r,toBlock:"latest"});return If(o,{escrow:e,at:Number.isFinite(Number(t.at))?Number(t.at):null})}async function go(e,t={}){if(!e)throw new h("bad-input",{field:"escrow"});let n=t.call||dc,[r,o,i]=await Promise.all([n({to:e,data:z6()}),n({to:e,data:X6()}),n({to:e,data:Of("readyBy")})]);for(let[s,a]of[[r,"t1()"]])if(String(s||"").replace(/^0x/,"").length===0)throw new h("bad-input",{field:"escrow",why:"no-contract"});return{t1:jg(r,"t1()"),termsHash:Kg(o,"termsHash()"),readyBy:jg(i,"readyBy()")}}async function Q6(e,t={}){let n=t.call||dc;if(!e)throw new h("bad-input",{field:"escrow"});let r=["edPointLocker","edPointClaimer","edViewPointLocker","commitHalfLocker","commitHalfClaimer"];try{let o=await Promise.all(r.map(s=>n({to:e,data:Of(s)}))),i={};return r.forEach((s,a)=>{i[s]=Kg(o[a],s+"()")}),{slots:i}}catch(o){return{error:String(o&&o.message||o)}}}async function Ui(e,t,n="signature",r={}){if(!t)throw new h("bad-input",{field:"expect"});let o=await Q6(e,r),i=G6({slots:o.slots,readError:o.error,expect:t});if(i.blocks)throw new h("contract-reverted",{step:n,why:"slots-mismatch"});return i}async function Bf(e,t,n){let r=await kr(e,n);if(!r.isFunded||r.isClaimed||r.isRefunded)throw new h("contract-reverted",{step:t,why:"closed"})}async function Pf(e,t,n,r=null){if(typeof n.blockTime!="function")return;let o=n.call||dc,[i,s]=await Promise.all([o({to:e,data:Of("ready")}),go(e,n)]),a=BigInt(i)!==0n,c=Number(r===null?await n.blockTime():r);if(!(!Number.isSafeInteger(c)||c<=0)){if(t==="claim"){if(c>=Number(s.t1))throw new h("contract-reverted",{step:t,why:"window-closed"});if(!a&&c<Number(s.readyBy))throw new h("contract-reverted",{step:t,why:"not-ready"})}else if(t==="refund"){if(c<Number(s.t1)&&(c>=Number(s.readyBy)||a))throw new h("contract-reverted",{step:t,why:"too-early"})}else if(t==="mark-ready"){if(a)throw new h("contract-reverted",{step:t,why:"already-ready"});if(c>=Number(s.readyBy))throw new h("contract-reverted",{step:t,why:"ready-window-closed"})}}}async function Vg({escrow:e,halfClaimer:t,expect:n,onStep:r,deps:o={}}){if(!e)throw new h("bad-input",{field:"escrow"});if(!t)throw new h("bad-input",{field:"halfClaimer"});return await Bf(e,"claim",o),await Pf(e,"claim",o),await Ui(e,n,"claim",o),r?.("confirm-claim"),{hash:await(o.send||Tf)({to:e,data:K6(t),gas:q6})}}async function $g({escrow:e,halfLocker:t,onStep:n,expect:r=null,deps:o={}}){if(!e)throw new h("bad-input",{field:"escrow"});if(!t)throw new h("bad-input",{field:"halfLocker"});return await Bf(e,"refund",o),await Pf(e,"refund",o),r&&await Ui(e,r,"refund",o),n?.("confirm-refund"),{hash:await(o.send||Tf)({to:e,data:W6(t),gas:250000n})}}async function zg({escrow:e,expect:t,onStep:n,deps:r={}}){if(!e)throw new h("bad-input",{field:"escrow"});return await Bf(e,"mark-ready",r),await Pf(e,"mark-ready",r),await Ui(e,t,"mark-ready",r),n?.("confirm-mark-ready"),{hash:await(r.send||Tf)({to:e,data:V6(),gas:120000n})}}async function xo(e,t,n="send"){let r=Number(t);if(!Number.isSafeInteger(r)||r<=0)throw new h("bad-input",{field:"chainId",step:n});if(!e||typeof e.chainId!="function")throw new h("bad-input",{field:"wallet.chainId",step:n});let o=null;try{o=Number(await e.chainId())}catch{throw new h("wrong-chain",{vm:"evm",step:n,want:r,got:null,why:"unreadable"})}if(!Number.isSafeInteger(o)||o<=0)throw new h("wrong-chain",{vm:"evm",step:n,want:r,got:null,why:"unreadable"});if(o!==r)throw new h("wrong-chain",{vm:"evm",step:n,want:r,got:o});return r}var Z6=["commitHalfLocker","commitHalfClaimer","edPointLocker","edPointClaimer","edViewPointLocker"],J6=e=>typeof e=="string"&&e&&!/^0x/i.test(e)?"0x"+e:e;function Xg(e){if(!e||typeof e!="object")throw new h("bad-input",{field:"request"});let t={...e};for(let n of Z6)t[n]=J6(t[n]);return t}function e3(e){if(!e||typeof e!="object")throw new h("bad-input",{field:"request"});let n=["locker","claimer","commitHalfLocker","commitHalfClaimer","edPointLocker","edPointClaimer","amount","readyBy","t1"].filter(r=>e[r]===void 0||e[r]===null||e[r]==="");if(n.length)throw new h("bad-input",{field:"terms",missing:n});try{return Or.orderTerms(Xg(e))}catch{let o=Math.floor(Date.now()/1e3);throw Number(e.readyBy)<=o?new h("bad-input",{field:"readyBy",why:"not-in-future"}):Number(e.t1)<=Number(e.readyBy)?new h("bad-input",{field:"t1",why:"not-after-readyBy"}):new h("bad-input",{field:"terms"})}}var t3=e=>String(e??"").replace(/0x[0-9a-fA-F]{64}/g,"0x<redacted>").slice(0,200),n3=/fetch failed|network|ECONN|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|socket|timeout|HTTP \d|status \d|non-ok/i,r3=e=>n3.test(e);async function Yg(e,t,n={}){if(!e||typeof e!="object")throw new h("bad-input",{field:"request"});if(!t||typeof t.send!="function"||typeof t.receipt!="function")throw new h("bad-input",{field:"wallet",missing:["send","receipt"]});let r=Xg(e);e3({...r,amount:r.amountWei});let o=Ie;await xo(t,r.chainId,"fund-order");let i=typeof n.call=="function"?n.call:o.readContract;try{return await o.fundOrder({...r,call:i,send:s=>t.send({...s,chainId:r.chainId,from:r.locker}),receipt:s=>t.receipt(typeof s=="string"?s:s&&typeof s.hash=="string"?s.hash:s)})}catch(s){if(s&&typeof s.code=="string")throw s;let a=t3(s&&s.message||s);throw new h(r3(a)?"server-unavailable":"bad-input",{step:"fund-order",why:a})}}Pr();var i3=(e,t)=>t.filter(n=>e[n]===void 0||e[n]===null||e[n]===""),Rf=e=>{let t=["send","receipt"],n=e?t.filter(r=>typeof e[r]!="function"):t;if(n.length)throw new h("bad-input",{field:"wallet",missing:n});return e};function s3({sender:e=null,claimer:t=null}={}){let n=typeof e=="string"?e.trim().toLowerCase():"",r=typeof t=="string"?t.trim().toLowerCase():"";return r?n?n!==r?{ok:!1,code:"bad-input",field:"wallet",why:"not-the-claimer"}:{ok:!0}:{ok:!1,code:"bad-input",field:"wallet.address"}:{ok:!1,code:"bad-input",field:"claimer"}}var Hf=(e,t)=>{if(!e||typeof e!="object")throw new h("bad-input",{field:"request"});let n=i3(e,["escrow","expect",...t]);if(n.length)throw new h("bad-input",{field:"request",missing:n});return e},Lf=async(e,t)=>{try{return await t()}catch(n){throw n&&typeof n.code=="string"?n:new h("contract-reverted",{step:e})}};function Mi({call:e=null,blockTime:t=null}={}){let n=a=>{try{return a&&typeof a.driver=="function"?a.driver():null}catch{return null}},r=a=>{if(typeof e=="function")return e;let c=n(a);return!c||typeof c.request!="function"?async()=>{throw new h("wallet-not-connected",{surface:"actions.read"})}:async({to:l,data:u})=>{let d=await c.request({method:"eth_call",params:[{to:l,data:u},"latest"]});if(typeof d!="string"||!d.startsWith("0x"))throw new h("contract-reverted",{surface:"actions.read"});return d}},o=a=>typeof t=="function"?t:async()=>{try{let c=n(a);if(!c||typeof c.request!="function")return null;let l=await c.request({method:"eth_getBlockByNumber",params:["latest",!1]}),u=Number(l&&l.timestamp);return Number.isSafeInteger(u)&&u>0?u:null}catch{return null}},i=async(a,c)=>{let l=typeof a.address=="function"?await a.address():null;if(typeof l!="string"||!l.trim())throw new h("bad-input",{field:"wallet.address",step:c});return l},s=(a,c,l)=>({call:r(a),send:u=>a.send({...u,chainId:c,from:l}),receipt:u=>a.receipt(u),blockTime:o(a)});return{async markReady(a,c){Hf(a,[]),Rf(c);let{escrow:l,expect:u,onStep:d}=a,p=await i(c,"mark-ready");return await xo(c,u.chainId,"mark-ready"),await Lf("mark-ready",()=>zg({escrow:l,expect:u,onStep:d,deps:s(c,u.chainId,p)}))},async claim(a,c){Hf(a,["halfClaimer"]),Rf(c);let{escrow:l,halfClaimer:u,expect:d,onStep:p}=a,m=await i(c,"claim"),w=s3({sender:m,claimer:a.claimer||d&&d.claimer});if(!w.ok)throw new h(w.code,{field:w.field,why:w.why,surface:"actions.claim"});return await xo(c,d.chainId,"claim"),await Lf("claim",()=>Vg({escrow:l,halfClaimer:u,expect:d,onStep:p,deps:s(c,d.chainId,m)}))},async refund(a,c){Hf(a,["halfLocker"]),Rf(c);let{escrow:l,halfLocker:u,expect:d,onStep:p}=a,m=await i(c,"refund");return await xo(c,d.chainId,"refund"),await Lf("refund",()=>$g({escrow:l,halfLocker:u,expect:d,onStep:p,deps:s(c,d.chainId,m)}))}}}var ko=e=>typeof e=="string"&&e.length>0,fc=e=>{let t=Number(e);return Number.isFinite(t)?Math.trunc(t):null},a3=e=>ko(e)?e.trim().replace(/^0x/,"").toLowerCase():null,Gg=e=>{try{return new URL(e).host}catch{throw new h("bad-input",{field:"nodes.url",unknown:e})}},ji=(e,t)=>{let n=e&&e.params||{},r="network",o=n.why===void 0||n.why===null?"":String(n.why),i=String(n.name||e&&e.name||"");n.status!==void 0&&n.status!==null?r="http":/^(TimeoutError|AbortError)$/.test(i)||/timeout|abort/i.test(o)||/timeout|abort/i.test(i)?r="timeout":(o==="bad-json"||o==="no-height"||o==="no-block")&&(r="bad-answer");let s={url:t.url,operator:t.operator,code:r};return n.status!==void 0&&n.status!==null&&(s.status=n.status),o&&(s.why=o),s};function c3(e){if(!Array.isArray(e))throw new h("bad-input",{field:"nodes"});let t=[];for(let n of e)if(ko(n)){let r=n.replace(/\/+$/,"");t.push({url:r,operator:Gg(r)})}else if(n&&typeof n=="object"&&ko(n.url)){let r=n.url.replace(/\/+$/,"");t.push({url:r,operator:ko(n.operator)?n.operator:Gg(r)})}else throw new h("bad-input",{field:"nodes",why:"each-node-is-url-or-url+operator"});if(!t.length)throw new h("bad-input",{field:"nodes",why:"empty-list"});return t}async function Ff(e,t,n,r,o){let i;try{i=await r(e.url+t,{method:"POST",headers:{"Content-Type":"text/plain"},body:JSON.stringify(n),signal:typeof AbortSignal<"u"&&AbortSignal.timeout?AbortSignal.timeout(o):void 0})}catch(s){throw new h("xmr-no-nodes",{node:e.url,name:String(s&&s.name||""),why:String(s&&s.message||s).slice(0,120)})}if(!i||i.ok!==!0)throw new h("xmr-no-nodes",{node:e.url,status:i?i.status:null});try{return await i.json()}catch(s){let a=String(s&&s.name||""),c=/^(TimeoutError|AbortError)$/.test(a)||/timeout|abort/i.test(a);throw new h("xmr-no-nodes",{node:e.url,name:a,why:c?"timeout":"bad-json"})}}async function qg(e,t,n){let r=await Ff(e,"/json_rpc",{jsonrpc:"2.0",id:"info",method:"get_info"},t,n),o=r&&r.result;if(!o||!Number.isFinite(Number(o.height)))throw new h("xmr-no-nodes",{node:e.url,why:"no-height"});return{height:Number(o.height),synced:o.synchronized!==!1,nettype:o.nettype||null}}async function Qg(e,t,n,r){let o=await Ff(e,"/json_rpc",{jsonrpc:"2.0",id:"block",method:"get_block",params:{height:t}},n,r),i=o&&o.result;if(!i)throw new h("xmr-no-nodes",{node:e.url,why:"no-block"});let s=i.block_header&&i.block_header.hash||null,a=Array.isArray(i.tx_hashes)?i.tx_hashes:null;if(!a){let c=typeof i.json=="string"?JSON.parse(i.json):i.json;a=c&&c.tx_hashes||[]}return{hash:s,txHashes:a}}async function Zg(e,t,n,r){if(!t.length)return[];let o=await Ff(e,"/get_transactions",{txs_hashes:t,decode_as_json:!0},n,r),i=o.txs||[];return(o.txs_as_json||[]).map((s,a)=>{let c=typeof s=="string"?JSON.parse(s):s,l=i[a]||{};return c.tx_hash=String(l.tx_hash||c.tx_hash||"").replace(/^0x/,"").toLowerCase(),c.block_height=l.block_height??null,c.confirmations=l.confirmations??null,c})}var l3=e=>e.outputs.reduce((t,n)=>t+(n.amountVerified&&n.amountAtomic||0n),0n);async function u3(e,{txid:t,address:n,viewSecret:r,spendPub:o,fromHeight:i,toHeight:s,nowSec:a,fetchImpl:c,timeoutMs:l}){let u=Math.max(0,fc(i)??0),d=fc(s);if(!Number.isFinite(d)||d<u)throw new h("bad-input",{field:"fromHeight",got:i});for(let p=u;p<=d;p++){let{txHashes:m}=await Qg(e,p,c,l);if(!m.length||t&&!m.includes(t))continue;let w=await Zg(e,m,c,l);for(let y of w){if(t&&y.tx_hash!==t)continue;if(si.matchTransaction(y,[{address:n,viewSecret:r,spendPub:o}],{height:p,nowSec:a}).length)return{txid:y.tx_hash,height:p}}}return null}async function pc(e){if(!e||typeof e!="object")throw new h("bad-input",{field:"request"});let t=c3(e.nodes);if(!ko(e.address))throw new h("bad-input",{field:"address"});if(e.viewSecret===void 0||e.viewSecret===null)throw new h("bad-input",{field:"viewSecret"});if(!ko(e.spendPub))throw new h("bad-input",{field:"spendPub"});let n;try{n=BigInt(e.expectedAtomic)}catch{throw new h("bad-input",{field:"expectedAtomic"})}if(n<=0n)throw new h("bad-input",{field:"expectedAtomic"});let r=Math.max(1,fc(e.minConfirmations)??1),o=typeof e.fetch=="function"?e.fetch:globalThis.fetch;if(typeof o!="function")throw new h("bad-input",{field:"fetch"});let i=Number.isFinite(Number(e.nowSec))?Number(e.nowSec):Math.floor(Date.now()/1e3),s=Number.isFinite(Number(e.timeoutMs))&&Number(e.timeoutMs)>0?Number(e.timeoutMs):2e4,a=a3(e.txid),c={address:e.address,viewSecret:e.viewSecret,spendPub:e.spendPub},l=[],u=[];for(let A of t)try{let N=await qg(A,o,s);l.push({node:A,info:N})}catch(N){u.push(ji(N,A))}if(!l.length)throw new h("xmr-no-nodes",{tried:t.map(A=>A.url),nodes:u});let d=Math.max(...l.map(A=>A.info.height)),p=Math.max(0,d-1),m=null,w=!1;for(let{node:A}of l){try{m=await u3(A,{txid:a,address:e.address,viewSecret:e.viewSecret,spendPub:e.spendPub,fromHeight:e.fromHeight,toHeight:p,nowSec:i,fetchImpl:o,timeoutMs:s}),w=!0}catch(N){u.push(ji(N,A)),m=null}if(m)break}if(!m){if(!w)throw new h("xmr-no-nodes",{tried:t.map(A=>A.url),nodes:u});return{seen:!1,state:"pending",txid:a,tip:d,checked:l.map(A=>({url:A.node.url,operator:A.node.operator,height:A.info.height})),failed:u}}let y=[];for(let A of t){let N={url:A.url,operator:A.operator},f;try{f=await qg(A,o,s)}catch(H){N.state="down",N.failure=ji(H,A),u.push(N.failure),y.push(N);continue}if(!f.synced||f.height<m.height){N.state="stale",N.height=f.height,y.push(N);continue}N.height=f.height;let k;try{k=await Qg(A,m.height,o,s)}catch(H){N.state="down",N.failure=ji(H,A),u.push(N.failure),y.push(N);continue}if(N.blockHash=k.hash,!k.hash||!k.txHashes.includes(m.txid)){N.state="no-tx",y.push(N);continue}let _=null;try{_=(await Zg(A,k.txHashes,o,s)).find(H=>H.tx_hash===m.txid)||null}catch(H){N.state="down",N.failure=ji(H,A),u.push(N.failure),y.push(N);continue}if(!_){N.state="no-tx",y.push(N);continue}let K=si.matchTransaction(_,[c],{height:m.height,tipHeight:Math.max(0,f.height-1),nowSec:i});if(!K.length){N.state="no-output",y.push(N);continue}if(N.state="ok",N.amountAtomic=l3(K[0]),N.amountVerified=K[0].outputs.every(H=>H.amountVerified===!0),N.outputs=K[0].outputs.map(H=>({index:H.index,key:String(H.key||"").replace(/^0x/,"").toLowerCase(),amountAtomic:H.amountVerified?String(H.amountAtomic??null):null,amountVerified:H.amountVerified===!0})),N.unlock=K[0].unlock,N.confirmations=Number.isFinite(Number(_.confirmations))?Number(_.confirmations):f.height-m.height,!N.amountVerified){N.state="amount-unverified",y.push(N);continue}N.observation={txid:m.txid,blockHash:String(k.hash||"").replace(/^0x/,"").toLowerCase(),outputs:N.outputs,unlock:N.unlock?{locked:N.unlock.locked===!0,untilHeight:N.unlock.untilHeight??null,untilTime:N.unlock.untilTime??null}:null},y.push(N)}let b=y.filter(A=>A.state==="no-tx"||A.state==="no-output"||A.state==="amount-unverified");if(b.length)throw new h("xmr-nodes-disagree",{txid:m.txid,height:m.height,nodes:b.map(A=>({url:A.url,operator:A.operator,blockHash:A.blockHash||null,why:A.state,outputs:A.outputs||null})),agreed:y.filter(A=>A.state==="ok").map(A=>({url:A.url,operator:A.operator,blockHash:A.blockHash})),failed:u});let x=y.filter(A=>A.state==="ok");if(!x.length)return{seen:!1,state:"pending",txid:m.txid,height:m.height,checked:y,failed:u};let I=new Map;for(let A of x){let N=JSON.stringify(A.observation);I.has(N)||I.set(N,{observation:A.observation,operators:new Set,nodes:[]});let f=I.get(N);f.operators.add(A.operator),f.nodes.push(A)}if(I.size>1)throw new h("xmr-nodes-disagree",{txid:m.txid,height:m.height,nodes:x.map(A=>({url:A.url,operator:A.operator,blockHash:A.blockHash||null,outputs:A.outputs,why:"observation"})),agreed:[],failed:u});let E=[...I.values()][0],U=Math.min(...E.nodes.map(A=>A.confirmations)),S=E.nodes[0].amountAtomic,B=E.nodes.map(A=>({url:A.url,operator:A.operator,blockHash:A.blockHash,confirmations:A.confirmations})),R=E.nodes.find(A=>A.unlock&&A.unlock.locked);if(R){let A=R.unlock;throw new h("xmr-locked",{txid:m.txid,height:m.height,address:e.address,untilHeight:A.untilHeight??null,untilTime:A.untilTime??null,failed:u})}if(S<n)throw new h("xmr-underpaid",{txid:m.txid,height:m.height,got:S.toString(),want:n.toString(),failed:u});return E.operators.size<2?{seen:!1,state:"one-node",txid:m.txid,height:m.height,blockHash:E.observation.blockHash,amountAtomic:S.toString(),confirmations:U,operators:[...E.operators],agreedBy:B,checked:y,failed:u}:U<r?{seen:!1,state:"pending",why:"confirmations",txid:m.txid,height:m.height,blockHash:E.observation.blockHash,amountAtomic:S.toString(),confirmations:U,needConfirmations:r,agreedBy:B,checked:y,failed:u}:{seen:!0,state:"arrived",txid:m.txid,height:m.height,blockHash:E.observation.blockHash,amountAtomic:S.toString(),confirmations:U,needConfirmations:r,operators:[...E.operators],agreedBy:B,checked:y,failed:u}}function Df({readyBySec:e,nowSec:t,minConfirmations:n,blockTimeSec:r}={}){let o=Number(e),i=Number.isFinite(Number(t))?Number(t):Math.floor(Date.now()/1e3),s=Math.max(1,fc(n)??1),a=Number.isFinite(Number(r))&&Number(r)>0?Number(r):120;if(!Number.isFinite(o)||o<=0)return null;let c=s*a,l=Math.floor(o-i);if(l<c)throw new h("xmr-too-late",{needSec:c,leftSec:l,minConfirmations:s,readyBy:Math.floor(o)});return l}var f3={success:"success",refund_eth:"refunded_eth",[hn]:hn},Dt=e=>{let t=Number(e);return Number.isFinite(t)?t:null},p3="xmr_locked",h3=["id","network","escrow","quoteId","providerId","hashlock","amount","t0","t1","sdkVersion"],m3=["swapId","network","address","viewKey","expectedAmountXmr","restoreHeight","chain"];function w3(e,t,n=null){let r=e&&e.escrow||{},o=n&&typeof n=="object"?n:{},i=(...s)=>{for(let a of s)if(!(a==null||a===""))return typeof a=="bigint"?a.toString():a;return null};return{id:e.id||null,network:e.network||e.chain||null,escrow:t||r.address||null,quoteId:i(e.orderQuoteId,r.quoteId),providerId:i(e.providerId,r.providerId),hashlock:i(r.hashlock,e.hashlock),amount:i(r.amountWei,o.amount,e.amountWei),t0:i(r.t0,o.t0),t1:i(r.t1,o.t1),sdkVersion:io}}function Jg(e){let t=e&&e.escrow||{};if(typeof t.viewHalf!="string"||!t.viewHalf)throw new h("bad-input",{field:"viewHalf"});if(typeof t.counterViewHalf!="string"||!t.counterViewHalf)throw new h("bad-input",{field:"counterViewHalf"});try{return tn.createHalves(Ln).combineHalves(BigInt(t.viewHalf),BigInt(t.counterViewHalf)).toString(16).padStart(64,"0")}catch{throw new h("bad-input",{field:"viewKey"})}}function ex(e){if(!e||typeof e!="object")return null;let t=Number(e.receivedXmr);if(!Number.isFinite(t))return null;let n=Number(e.confirmations),r=e.status===p3,o=Dt(e.lockedXmr);return{id:e.id||null,address:e.address||null,status:e.status||null,expectedXmr:Dt(e.expectedAmountXmr),receivedXmr:t,confirmations:Number.isFinite(n)?n:0,txids:Array.isArray(e.fundingTxids)?e.fundingTxids:[],locked:r,lockedXmr:o===null?0:o,lockedUntil:e.lockedUntil||null,seen:t>0&&!r}}function tx(e){if(!e||typeof e!="object"||!e.id)throw new h("bad-input",{field:"swap"});let t=fe.derive(e),n=[],r=Array.isArray(t.steps)?t.steps:[],o=r.find(u=>u.key==="funded")||null;n.push({code:"awaiting_funding",done:!!(o&&o.done),active:!(o&&o.done),at:null});for(let u of r)n.push({code:u.key,done:!!u.done,active:!!u.active,failed:!!u.failed,at:t.simulated&&t.simulated.evm?u.atSim??null:null});let i=n.find(u=>u.active)||[...n].reverse().find(u=>u.done)||n[0],s=t.terminal?f3[t.terminal.kind]??"closed":null,a=s===hn,c=e.network||e.chain||null,l=c&&Dd(c)||"unknown";return{id:e.id,direction:e.side==="sell"?"sell":"buy",createdAt:e.createdAt??null,maker:{id:e.makerId!==void 0&&e.makerId!==null?e.makerId:(e.maker&&e.maker.id)??null,name:e.makerName!==void 0&&e.makerName!==null?e.makerName:(e.maker&&e.maker.name)??null},phase:t.phase||null,phaseLabel:t.phaseLabel||null,settled:!!e.settlement,funds:{receivedXmr:Dt(t.xmrAmount&&t.xmrAmount.seen)??0,escrowLocked:!!(e.escrow&&(e.escrow.fundTx||e.escrow.secret))},pay:{token:e.payToken||"eth",amount:Dt(e.payAmount)??0},get:{xmr:Dt(e.xmrAmount)??0},step:i.code,steps:n,deadlines:{readyBy:t.deadlines&&t.deadlines.readyBy!==void 0?Dt(t.deadlines.readyBy):null,t1:t.deadlines&&t.deadlines.t1!==void 0?Dt(t.deadlines.t1):null},xmr:{confirmations:Dt(t.xmr&&(t.xmr.confirmations!==void 0?t.xmr.confirmations:t.conf))??0,target:Dt(t.xmr&&t.xmr.confTarget)??Dt(t.confTarget)??0,txid:t.xmr&&Array.isArray(t.xmr.txids)&&t.xmr.txids[0]||null,amount:{expected:t.xmrAmount?t.xmrAmount.expected??null:null,seen:t.xmrAmount?t.xmrAmount.seen??null:null}},counterparty:{chain:c,vm:l,leg:e.escrow&&(e.escrow.address||e.escrow.leg)||null,status:t.phase||null,txs:e.escrow&&(e.escrow.txids||e.escrow.txs)||[]},actions:a?{markReady:!1,sweep:!1,refund:!1}:{markReady:!!(t.can&&t.can.ready),sweep:!!(t.can&&t.can.sweep),refund:!!(t.can&&t.can.refund)},simulated:{evm:!!(t.simulated&&t.simulated.evm),xmr:!!(t.simulated&&t.simulated.xmr)},terminal:s}}var nx=12,rx=(e,t=null)=>{let n=e&&e.quote&&typeof e.quote=="object"?e.quote:{},r=o=>o==null||o===""?void 0:o;return{side:e.side||"buy",network:n.chain?n.chain:void 0,moneroNetwork:e.moneroNetwork||t||void 0,payToken:n.asset?String(n.asset).toLowerCase():void 0,payAmount:n.amount!==void 0?n.amount:void 0,xmrAmount:n.size!==void 0?n.size:void 0,expectedAtomic:e.order&&e.order.xmrAmount!==void 0&&e.order.xmrAmount!==null?String(e.order.xmrAmount):e.orderQuote&&e.orderQuote.xmrAmount!==void 0&&e.orderQuote.xmrAmount!==null?String(e.orderQuote.xmrAmount):void 0,orderQuoteId:r(n.id),receiveAddress:r(e.receiveTo),makerId:r(n.makerId),makerName:r(n.makerName),makerSpread:r(n.makerSpread),quoteSignature:r(n.signature),fee:r(n.ninseiFee),dexSpread:r(n.dexSpread),gasUsd:r(n.gasUsd),rate:r(n.rate)}};async function y3({nodes:e=[],network:t=null,fetchImpl:n=globalThis.fetch}={}){let r=(Array.isArray(e)?e:[]).map(a=>typeof a=="string"?a:a&&a.url).filter(Boolean),o=await Promise.all(r.map(async a=>{try{return await kb({url:a,fetchImpl:n})}catch{return{ok:!1,why:"unreachable"}}})),i=o.filter(a=>a.ok===!0&&(!t||a.network===t));if(i.length){let a=i.map(u=>Number(u.height)).filter(u=>Number.isSafeInteger(u)&&u>=0);if(!a.length)throw new h("xmr-no-nodes",{step:"restore-height",network:t||null,why:"no-height"});let c=Math.min(...a),l=Math.max(...a);if(l-c>100)throw new h("xmr-no-nodes",{step:"restore-height",network:t||null,why:"disagree",low:c,high:l});return c}let s=o.find(a=>a.ok===!0)?"network":o[0]&&o[0].why||"no-node";throw new h("xmr-no-nodes",{step:"restore-height",network:t||null,why:s})}var b3=300;function g3({configuredMs:e=12e5,readyBySec:t=null,nowSec:n=Math.floor(Date.now()/1e3)}={}){let r=Number.isFinite(Number(e))&&Number(e)>0?Number(e):12e5,o=Number(t),i=Number(n);return!Number.isSafeInteger(o)||!Number.isSafeInteger(i)||o<=i?r:Math.max(r,(o-i+b3)*1e3)}function Uf({preflight:e,http:t,createRecord:n,mode:r=null,xmrNetwork:o=null,call:i=null,store:s=Jn,config:a=null,auth:c=null,denylist:l=null,watch:u=null,logs:d=null}={}){let p=typeof i=="function"?i:Ie.readContract,m=lc(d),w=Mi({call:typeof i=="function"?i:null}),y=(f,k)=>{if(!a||typeof a.route!="function")throw new h("bad-input",{field:"config",step:"server"});return a.route(f,k)},b=(f,k)=>{let _=a&&a.limits?a.limits[f]:null;return Number.isFinite(Number(_))&&Number(_)>0?Number(_):k};async function x(f,k){let _=Number(f.restoreHeight);if(Number.isSafeInteger(_)&&_>0)return _;let K=Array.isArray(f.xmrNodes)?f.xmrNodes:a&&typeof a.nodesFor=="function"?a.nodesFor(k):[];return y3({nodes:K,network:k,fetchImpl:f.fetchImpl||(typeof fetch=="function"?fetch:null)})}let I=()=>{let f=s.loadState();return Object.values(f&&f.swaps||{}).filter(_=>_&&_.id).sort((_,K)=>Number(K.createdAt||0)-Number(_.createdAt||0))},E=f=>{let k=String(f||"");return k&&I().find(_=>String(_.orderQuoteId||"")===k&&(_.fundingPending===!0||_.escrow&&_.escrow.fundingPending===!0))||null};async function U(f,k){let _=f.swap||f,K=_.escrow&&typeof _.escrow=="object"?_.escrow:{},H=K.fundTx||_.fundTx||null,P=null;if(K.address)try{P=await kr(K.address,{call:p})}catch{P=null}if(!H&&!(P&&P.isFunded))return{id:_.id||null,escrow:K.address||null,address:f.swapWallet&&f.swapWallet.address||null,step:"funding-pending",txHash:null,reason:"no-transaction-hash",next:"receipt"};let j=k.wallet,L=null;if(H&&j&&typeof j.receipt=="function")try{L=await j.receipt(H)}catch{L=null}let z=k.order&&typeof k.order=="object"?k.order:{},W=Ns(L,{factory:z.factory||k.orderQuote&&k.orderQuote.factory||null,expectedEscrow:K.address||null});if(W.status==="reverted")throw new h("contract-reverted",{step:"funding"});if(W.status==="funded"||P&&P.isFunded){let $=W.status==="funded"?W.escrow:K.address;if(!$)throw new h("funding-pending",{reason:"no-escrow-address"});_.escrow={...K,address:$,fundingPending:!1,evmBirthBlock:Number(W.birthBlock)>0?Number(W.birthBlock):K.evmBirthBlock??null},delete _.fundingPending;try{fe.saveSwap(_,s)}catch{throw new h("storage-unavailable",{step:"save-escrow"})}return{id:_.id||null,escrow:$,address:f.swapWallet&&f.swapWallet.address||null,step:"xmr-incoming",server:null,watch:null,next:"watch"}}return{id:_.id||null,escrow:K.address||null,address:f.swapWallet&&f.swapWallet.address||null,step:"funding-pending",txHash:H,reason:W.reason||"no-receipt",next:"receipt"}}async function S(f){let k=f.order&&typeof f.order=="object"?f.order:{},_=k.amount,K=_==null||_===""?null:String(_),H=Number(k.chainId),P=Number.isFinite(H)?oe.chainByChainId(H):null,j=P?oe.tokensOf(P.id):[],L=String(f.quote&&(f.quote.token||f.quote.asset)||"").toLowerCase(),z=j.find(g=>String(g.symbol).toLowerCase()===L)||null,W=j.find(g=>!g.address)||null,$=!!(z&&!z.address),O={tokenIsNative:$,standIn:!f.counterparty&&r!=="live",liveChain:!!(P&&P.escrow&&P.escrow.mode==="live"&&!P.testnet)};K!==null&&(O.payAmountWei=K,O.requiredNativeWei=K);try{let g=f.wallet,T=g&&typeof g.driver=="function"?g.driver():null,v=g&&typeof g.address=="function"?await g.address():null,V=oo("evm"),D=M=>String(M.symbol).toLowerCase(),F=[];if(W&&F.push({id:D(W),symbol:W.symbol,decimals:W.decimals,address:null}),z&&z.address&&F.push({id:D(z),symbol:z.symbol,decimals:z.decimals,address:z.address}),T&&v&&V&&typeof V.balances=="function"&&F.length){let M=await V.balances({driver:T,address:v,tokens:F}),X=J=>{let te=J?M.find(ke=>ke.token===D(J)):null;return te&&te.amount!==null?te.amount:null},G=W?X(W):null;G!==null&&(O.nativeBalanceWei=G);let Z=$?G:X(z);Z!==null&&(O.payBalanceWei=Z)}}catch{}return O}async function B(f,k,_){if(!t||typeof t.tryJson!="function")throw new h("bad-input",{field:"http",step:"mark"});let K=w3(f,k,_),H=JSON.stringify(Object.fromEntries(h3.map(L=>[L,K[L]]))),P={"content-type":"application/json"};if(typeof c=="function"){let L=null;try{L=await c()}catch{L=null}typeof L=="string"&&L&&(P.authorization="Bearer "+L)}let j=null;try{j=await t.tryJson(y("evmSwaps"),{method:"POST",headers:P,body:H})}catch(L){throw new h("server-unavailable",{step:"mark",why:L&&L.code||"fetch"})}if(!j||j.ok!==!0)throw new h("server-refused",{step:"mark",status:j?j.status:null,why:j&&j.body&&(j.body.error||j.body.detail)||null});return{marked:!0,httpStatus:j.status,orderBinding:j.body&&j.body.orderBinding||null}}async function R(f,k){if(!t||typeof t.tryJson!="function")throw new h("bad-input",{field:"http",step:"watch"});let _=f&&f.escrow||{},K=_.moneroAddress||f.swapWallet&&f.swapWallet.address||null;if(!K)throw new h("bad-input",{field:"moneroAddress"});let H=Dt(k&&k.xmrAmount!==void 0?k.xmrAmount:f.xmrAmount);if(!(H>0))throw new h("bad-input",{field:"expectedAmountXmr"});let P=f.moneroNetwork||o||null;if(!P)throw new h("bad-input",{field:"moneroNetwork"});let j=Number(f.restoreHeight)>0?Number(f.restoreHeight):Number(_.moneroRestoreHeight)>0?Number(_.moneroRestoreHeight):null;if(!(j>0))throw new h("bad-input",{field:"restoreHeight",step:"watch"});let L={swapId:f.id||null,network:P,address:K,viewKey:Jg(f),expectedAmountXmr:H,restoreHeight:j,chain:f.network||f.chain||null},z={sdkVersion:io};for(let O of m3)L[O]!==void 0&&L[O]!==null&&(z[O]=L[O]);u&&u.sendViewKeyToServer===!1&&delete z.viewKey;let W=null;try{W=await t.tryJson(y("swaps"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(z)})}catch(O){throw new h("server-unavailable",{step:"watch",why:O&&O.code||"fetch"})}if(!W||W.ok!==!0)throw new h("server-refused",{step:"watch",status:W?W.status:null,why:W&&W.body&&(W.body.error||W.body.detail)||null});let $=ex(W.body);if(!$)throw new h("server-unavailable",{step:"watch",why:"bad-response"});return{registered:!0,httpStatus:W.status,...$,expectedXmr:$.expectedXmr!==null?$.expectedXmr:H}}async function A(f){if(!t||typeof t.tryJson!="function")throw new h("bad-input",{field:"http",step:"watch"});let k=null;try{k=await t.tryJson(y("swap",{id:f}),{method:"GET"})}catch(_){throw new h("server-unavailable",{step:"watch",why:_&&_.code||"fetch"})}if(!k||k.ok!==!0)throw new h("server-refused",{step:"watch",status:k?k.status:null,id:f,why:k&&k.body&&(k.body.error||k.body.detail)||null});return k.body}async function N(f,k){if(!f||!k)throw new h("bad-input",{field:"escrow"});let _=null;try{_=await kr(f,{call:p})}catch{throw new h("quote-refused",{step:"send-xmr",why:"escrow-unreadable"})}if(!_||_.isFunded!==!0||_.isClaimed===!0||_.isRefunded===!0)throw new h("quote-refused",{step:"send-xmr",why:"escrow-not-open"});let K=null;try{K=await go(f,{call:p})}catch{throw new h("quote-refused",{step:"send-xmr",why:"deadline-unreadable"})}if(Number(K.readyBy)!==Number(k.readyBy)||Number(K.t1)!==Number(k.t1))throw new h("quote-refused",{step:"send-xmr",why:"terms-mismatch"});let H=Number(b("sellReadyLeadSec",600));if(Math.floor(Date.now()/1e3)+H>=Number(K.readyBy))throw new h("quote-refused",{step:"send-xmr",why:"deadline-too-close"});try{await Ui(f,k,"send-xmr",{call:p})}catch(P){throw P&&P.code==="contract-reverted"?P:new h("quote-refused",{step:"send-xmr",why:"slots-unreadable"})}}return{async list(){return I().map(tx)},async get(f){if(typeof f!="string"||!f)throw new h("bad-input",{field:"id"});let k=I().find(_=>_.id===f);return k?tx(k):null},async progress(f){if(typeof f!="string"||!f)throw new h("bad-input",{field:"id"});let k=fe.getSwap(f,s);return k?{id:String(k.id||f),swap:k,swapWallet:fe.halvesWalletOf(k),view:fe.derive(k)}:null},async confirmReady(f){if(typeof f!="string"||!f)throw new h("bad-input",{field:"id"});return fe.confirmReady(f,s)},async refundEth(f,k="you"){if(typeof f!="string"||!f)throw new h("bad-input",{field:"id"});return fe.refundEth(f,k,s)},async sweepNow(f){if(typeof f!="string"||!f)throw new h("bad-input",{field:"id"});return fe.sweepNow(f,s)},async setDestination(f,k){if(typeof f!="string"||!f)throw new h("bad-input",{field:"id"});if(typeof k!="string"||!k)throw new h("bad-input",{field:"address"});let _=fe.getSwap(f,s);return _?(_.receiveAddress=k,fe.saveSwap(_,s)):null},async addressNetwork(f){if(typeof f!="string"||!f)return null;try{return mn.networkFromShape(f)}catch{return null}},async forget(f){if(typeof f!="string"||!f)throw new h("bad-input",{field:"id"});let k=null;try{k=s.loadState()}catch{throw new h("storage-unavailable",{step:"forget"})}let _=k&&k.swaps;if(!_||!_[f])return!1;delete _[f];try{s.saveState(k)}catch{throw new h("storage-unavailable",{step:"forget"})}return!0},async sync(){if(!t||typeof t.tryJson!="function")throw new h("bad-input",{field:"http",step:"sync"});let f={};if(typeof c=="function"){let H=null;try{H=await c()}catch{H=null}typeof H=="string"&&H&&(f.authorization="Bearer "+H)}let k=null;try{k=await t.tryJson(y("evmSwaps"),{method:"GET",headers:f})}catch(H){throw new h("server-unavailable",{step:"sync",why:H&&H.code||"fetch"})}if(!k||k.ok!==!0)throw new h("server-refused",{step:"sync",status:k?k.status:null,why:k&&k.body&&(k.body.error||k.body.detail)||null});let _=k.body;if(!_||!Array.isArray(_.swaps))throw new h("server-unavailable",{step:"sync",why:"bad-response"});return{ok:!0,added:fe.addServerSwaps(_.swaps,s),seen:_.swaps.length}},verifyArrival:f=>pc(f),assertTimeForConfirmations:f=>Df(f),async refundIfXmrMissing(f={},k={}){let _=typeof k.verify=="function"?k.verify:pc,K=typeof k.refund=="function"?k.refund:w.refund,H=typeof k.now=="function"?k.now:()=>Math.floor(Date.now()/1e3);if(!f||typeof f!="object")throw new h("bad-input",{field:"request"});let P=f.swap&&typeof f.swap=="object"?f.swap:null,j=P&&P.escrow||{},L=f.escrow||j.address||null;if(!L)throw new h("bad-input",{field:"escrow"});let z=f.halfLocker||j.half||null;if(!z)throw new h("bad-input",{field:"halfLocker"});if(!f.expect||typeof f.expect!="object")throw new h("bad-input",{field:"expect"});let W=f.address||j.moneroAddress||null;if(!W)throw new h("bad-input",{field:"address"});let $=f.viewSecret!==void 0&&f.viewSecret!==null?f.viewSecret:P?Jg(P):null;if($==null)throw new h("bad-input",{field:"viewSecret"});let O=f.spendPub||j.moneroSpendPub||null;if(!O)throw new h("bad-input",{field:"spendPub"});let g=f.expectedAtomic!==void 0&&f.expectedAtomic!==null?f.expectedAtomic:j.expectedAtomic!==void 0&&j.expectedAtomic!==null?j.expectedAtomic:null;if(g===null&&P&&Number.isFinite(Number(P.xmrAmount))&&(g=BigInt(Math.round(Number(P.xmrAmount)*1e12)).toString()),g===null)throw new h("bad-input",{field:"expectedAtomic"});let T=Number(f.readyBySec!==void 0&&f.readyBySec!==null?f.readyBySec:j.readyBy);if(!Number.isFinite(T)||T<=0)throw new h("bad-input",{field:"readyBySec"});let v=Number.isFinite(Number(f.minConfirmations))&&Number(f.minConfirmations)>0?Math.trunc(Number(f.minConfirmations)):b("xmrConfirmations",10),V=Number.isFinite(Number(f.blockTimeSec))&&Number(f.blockTimeSec)>0?Number(f.blockTimeSec):b("xmrBlockTimeSec",120),D=Number.isFinite(Number(f.leadSec))&&Number(f.leadSec)>=0?Number(f.leadSec):v*V,F=Number.isFinite(Number(f.nowSec))?Number(f.nowSec):H(),M=Math.floor(T-F);if(M<=0)return{refunded:!1,state:"claim-window",leftSec:M,readyBy:T,nowSec:F};if(M>D)return{refunded:!1,state:"waiting",leftSec:M,needSec:D,readyBy:T,nowSec:F};let X=await _({nodes:f.nodes,address:W,viewSecret:$,spendPub:O,expectedAtomic:g,minConfirmations:v,txid:f.txid||null,fromHeight:f.fromHeight===void 0?null:f.fromHeight,timeoutMs:f.timeoutMs,nowSec:F});if(X.seen)return{refunded:!1,state:"arrived",leftSec:M,verdict:X};let G=await K({escrow:L,halfLocker:z,expect:f.expect,onStep:f.onStep},f.wallet);return{refunded:!0,state:"refunded",hash:G&&G.hash||null,leftSec:M,verified:X}},async start(f){if(!f||typeof f!="object")throw new h("bad-input",{field:"request"});if(f.side==="sell")throw new h("bad-input",{field:"side",why:"sell-not-supported",surface:"swaps.start"});if(!f.quote||typeof f.quote!="object")throw new h("bad-input",{field:"quote"});if(f.recoveryKey===void 0||f.recoveryKey===null)throw new h("bad-input",{field:"recoveryKey",why:"required"});if(!f.receiveTo||typeof f.receiveTo!="string")throw new h("bad-input",{field:"receiveTo"});if(!rx(f,o).expectedAtomic)throw new h("bad-input",{field:"expectedAtomic",why:"signed-amount-missing"});let k=f.orderQuote&&f.orderQuote.id||f.quote&&f.quote.id||null,_=E(k);if(_)return await U(_,f);if(f.recoverySalt===void 0||f.recoverySalt===null){if(!f.order||typeof f.order!="object")throw new h("bad-input",{field:"order"});(f.order.salt===void 0||f.order.salt===null||f.order.salt==="")&&(f.order={...f.order,salt:Ib()}),f.recoverySalt=f.order.salt}let K=await S(f),H=e?await e(f.quote,K):null,j=(H&&(H.checks||H.results)||[]).filter(Y=>Y&&Y.blocks===!0);if(j.length){let Y=j[0];throw new h(Y.code||"bad-input",{...Y.params||{},kind:Y.kind,surface:"swaps.start"})}let L=null,z=null,W=typeof n=="function"?n:async Y=>Nf(rx(Y,o),{order:Y.order,side:L,store:s}),$=typeof f.passphrase=="string"?f.passphrase:"";if(typeof $!="string")throw new h("bad-input",{field:"passphrase"});if($.length>0&&$.length<nx)throw new h("bad-input",{field:"passphrase",min:nx});let O=Kn(f.order),g=null;{let Y=s.storage(),ee=typeof f.recoveryKey=="string"?f.recoveryKey:f.recoveryKey&&typeof f.recoveryKey.mnemonic=="string"?f.recoveryKey.mnemonic:null,le=Qd(Y);if(le&&ee&&le.mnemonic!==ee)throw new h("bad-input",{field:"recoveryKey",why:"different-key"});if(!le&&!ee)throw new h("bad-input",{field:"recoveryKey"});let Oe=le||Gd(ee);le||Ma(Y,{...Oe,backupConfirmed:!1});let ne=f.order.chainId;if(typeof f.order.factory!="string"||!f.order.factory)throw new h("bad-input",{field:"order.factory"});let we;try{we=un(f.recoverySalt)}catch{throw new h("bad-input",{field:"recoverySalt"})}let nt;try{nt=un(f.order.salt)}catch{throw new h("bad-input",{field:"recoverySalt",why:"order-salt"})}if(we!==nt)throw new h("bad-input",{field:"recoverySalt",why:"order-salt"});let ht=hr({mnemonic:Oe.mnemonic,chainId:ne,factory:f.order.factory,salt:we});g={storage:Y,key:Oe,salt:we,derivation:"salt-v2",newKey:!le||le.backupConfirmed!==!0},L=mr(f.order,{spendHalf:ht.spendHalf,viewHalf:ht.viewHalf}).side,z={half:ht.makerViewHalf,point:ht.makerViewPoint}}if(z){let Y=f.counterparty&&typeof f.counterparty=="object"?f.counterparty:null,ee=Jd(Y);if(ee.half===null)throw new h("quote-field-unbound",{step:"viewHalfClaimer",field:"viewHalfClaimer"});let le=!1;try{le=BigInt(ee.half)===BigInt(z.half)}catch{le=!1}if(!le)throw new h("quote-refused",{step:"viewHalfClaimer",why:"not-the-derived-half"});if(ee.point!==null&&String(ee.point).replace(/^0x/,"").toLowerCase()!==String(z.point).replace(/^0x/,"").toLowerCase())throw new h("quote-refused",{step:"viewHalfClaimer",why:"point-mismatch"})}let T=null;try{T=await W(f)}catch(Y){throw Y&&typeof Y.code=="string"?Y:new h("storage-unavailable",{step:"create-record"})}if(!T||!T.swap)throw new h("bad-input",{field:"record"});let v=T,V=null;if(!v.swapWallet){let Y=Rb({order:f.order,side:T.side||null,counterparty:f.counterparty||null,standIn:r!=="live",network:v.swap.moneroNetwork||o||null}),ee=v.swap.escrow&&typeof v.swap.escrow=="object"?v.swap.escrow:{};v.swap.escrow={...ee,half:Y.wallet.spendHalf,viewHalf:Y.wallet.viewHalf,edPointLocker:Y.own.spendPoint,edViewPointLocker:Y.own.viewPoint,edPointClaimer:Y.wallet.otherSpendPoint,counterViewPoint:Y.wallet.otherViewPoint,counterViewHalf:Y.wallet.otherViewHalf,moneroAddress:Y.wallet.address,moneroSpendPub:Y.wallet.spendPub,moneroViewPub:Y.wallet.viewPub,moneroNetwork:Y.wallet.network,standIn:Y.counterparty.standIn,providerId:Y.counterparty.providerId,orderContext:Y.context};try{fe.saveSwap(v.swap,s)}catch{throw new h("storage-unavailable",{step:"save-swap"})}if(v={...v,swapWallet:fe.halvesWalletOf(v.swap)},!v.swapWallet)throw new h("bad-input",{field:"swapWallet"});V=Y}let D=await x(f,v.swap.moneroNetwork||o||null);v.swap.restoreHeight=D,v.restoreHeight=D,v.swap.escrow={...v.swap.escrow||{},moneroRestoreHeight:D};try{fe.saveSwap(v.swap,s)}catch{throw new h("storage-unavailable",{step:"save-restore-height"})}let F=null;if(g.newKey){if(typeof f.onRecoveryKey!="function")throw new h("bad-input",{field:"onRecoveryKey"});try{F={name:Ob(g.key),contents:await Bb({mnemonic:g.key.mnemonic,createdAt:g.key.createdAt,passphrase:$})}}catch{throw new h("recovery-failed",{step:"encrypt-key"})}if(await f.onRecoveryKey(F)!==!0)throw new h("recovery-declined",{key:g.key.fingerprint});try{Ma(g.storage,{...g.key,backupConfirmed:!0}),g.key={...g.key,backupConfirmed:!0}}catch{throw new h("storage-unavailable",{step:"save-recovery-key"})}}let M=f.wallet;if(!M||typeof M.send!="function"||typeof M.receipt!="function")throw new h("bad-input",{field:"wallet",missing:["send","receipt"],surface:"swaps.start",step:"lock"});if(l){let Y=typeof M.address=="function"?await M.address():null;if(typeof Y!="string"||!Y)throw new h("bad-input",{field:"wallet",missing:["address"],surface:"swaps.start",step:"lock"});if(l.has(Y.toLowerCase()))throw new h("address-denied",{step:"lock"})}let X=V?{commitHalfLocker:V.wallet.commitHalfLocker,commitHalfClaimer:V.wallet.commitHalfClaimer,edPointLocker:V.own.spendPoint,edPointClaimer:V.wallet.otherSpendPoint,edViewPointLocker:V.own.viewPoint}:{},G={...f.order,...X,amountWei:f.order.amount};if(f.orderQuote&&(V||f.counterparty)){let Y=Oe=>String(Oe??"").replace(/^0x/i,"").toLowerCase(),ee=V?V.wallet.commitHalfClaimer:f.counterparty.commitHalfClaimer||null,le=V?V.wallet.otherSpendPoint:f.counterparty.edPointClaimer||f.counterparty.edPub||null;if(!ee||!le||Y(f.orderQuote.commitHalfClaimer)!==Y(ee)||Y(f.orderQuote.edPointClaimer)!==Y(le))throw new h("quote-refused",{step:"quote-binding",why:"counterparty-half"})}G.quote=f.orderQuote||null;let Z=null;try{Z=await Yg(G,M,{call:p})}catch(Y){throw Y&&typeof Y.code=="string"?Y:new h("server-unavailable",{step:"lock"})}if(Z&&Z.pending){let Y=Z.createHash||null,ee=Z.predictedEscrow||null,le=v.swap.escrow&&typeof v.swap.escrow=="object"?v.swap.escrow:{};v.swap.fundingPending=!0,v.swap.escrow={...le,address:ee||le.address||null,fundTx:Y||le.fundTx||null,fundingPending:!0,fundingReason:Z.pendingReason||"no-receipt"};try{fe.saveSwap(v.swap,s)}catch{throw new h("storage-unavailable",{step:"save-pending"})}return{id:v.swap.id||null,escrow:v.swap.escrow.address||null,address:v.swapWallet&&v.swapWallet.address||null,step:"funding-pending",txHash:Y,reason:Z.pendingReason||"no-receipt",predictedEscrow:ee,next:"receipt"}}let J=Z&&Z.escrow||null;if(J){let Y=v.swap.escrow&&typeof v.swap.escrow=="object"?v.swap.escrow:{};v.swap.escrow={...Y,address:J,evmBirthBlock:Number(Z.birthBlock)>0?Number(Z.birthBlock):Y.evmBirthBlock??Y.birthHeight??null};try{fe.saveSwap(v.swap,s)}catch{throw new h("storage-unavailable",{step:"save-escrow"})}}let te=null,ke=null;return a&&a.apiBase&&(te=await B(v.swap,J,f.order),ke=await R(v.swap,f.order)),{id:v.swap.id||null,escrow:J,address:ke&&ke.address||v.swapWallet&&v.swapWallet.address||null,step:"xmr-incoming",server:te,watch:ke,next:"watch"}},async watch(f){if(!f||typeof f!="object")throw new h("bad-input",{field:"request"});let k=typeof f.id=="string"&&f.id?f.id:null;if(!k)throw new h("bad-input",{field:"id"});let _=f.expect!==void 0&&f.expect!==null,K=f.wallet!==void 0&&f.wallet!==null;if(_!==K)throw new h("bad-input",{field:_?"wallet":"expect"});if(_&&!(f.escrow||f.address))throw new h("bad-input",{field:"escrow"});let H=Number.isFinite(Number(f.pollMs))&&Number(f.pollMs)>0?Number(f.pollMs):b("watchPollMs",5e3),P=Number.isFinite(Number(f.timeoutMs))&&Number(f.timeoutMs)>0?Number(f.timeoutMs):b("watchTimeoutMs",12e5),j=Number.isFinite(Number(f.minConfirmations))&&Number(f.minConfirmations)>0?Math.trunc(Number(f.minConfirmations)):b("xmrConfirmations",10),L=f.verify&&typeof f.verify=="object"?{...f.verify,nodes:Array.isArray(f.verify.nodes)?f.verify.nodes:a&&typeof a.nodesFor=="function"?a.nodesFor(f.verify.network||f.network||o):[],minConfirmations:j}:null;if(L){let M=f.readyBySec!==void 0&&f.readyBySec!==null?Number(f.readyBySec):f.deadline&&f.deadline.readyBy!==void 0?Number(f.deadline.readyBy):null;M&&Df({readyBySec:M,nowSec:Math.floor(Date.now()/1e3),minConfirmations:j,blockTimeSec:b("xmrBlockTimeSec",120)})}let z=!!(a&&a.apiBase);if(!L&&!z)throw new h("bad-input",{field:"verify",why:"no-backend"});let W=Date.now(),$=null;try{$=fe.getSwap(k,s)}catch{$=null}let O=f.escrow||$&&$.escrow&&$.escrow.address||null,g=uc($&&$.escrow?$.escrow.evmBirthBlock??$.escrow.birthHeight:null),T={checked:!1,error:null,logs:void 0},v=async()=>{if(T.checked=!1,T.error=null,T.logs=void 0,!O){T.error="no-escrow";return}try{T.logs=await m({address:O,topics:[bo],fromBlock:g,toBlock:"latest"}),T.checked=!0}catch(M){T.error=M&&M.code||"logs-unread"}},V=(M,X)=>{if(!(!M||M.settlement)){M.settlement={kind:hn,phase:hn,at:X};try{fe.saveSwap(M,s)}catch{throw new h("storage-unavailable",{step:"decline"})}}},D=({source:M,at:X,waitedMs:G,address:Z,chainChecked:J,chainError:te})=>({id:k,escrow:O,address:Z||null,seen:!1,declined:!0,terminal:hn,code:cc,source:M,at:X,waitedMs:G,chain:{checked:!!J,error:te||null}});if($&&$.settlement&&$.settlement.kind===hn){let M=Number($.settlement.at);return D({source:"record",at:Number.isFinite(M)?M:Date.now(),waitedMs:0,address:null,chainChecked:!1,chainError:null})}let F=null;for(;;){await v();let M=L?{}:await A(k);F=L?{address:f.address||O,expectedXmr:f.expectedXmr??null,status:null}:ex(M);let X=Mg({logs:T.logs,escrow:O,at:Date.now()});if(X.declined)return V($,X.at),D({source:X.source,at:X.at,waitedMs:Date.now()-W,address:M&&M.address,chainChecked:T.checked,chainError:T.error});if(!F)throw new h("server-unavailable",{step:"watch",why:"bad-response",id:k});if(F.locked){let G=F.lockedUntil||{};throw new h("xmr-locked",{id:k,address:F.address,status:F.status,expectedXmr:F.expectedXmr,receivedXmr:F.receivedXmr,lockedXmr:F.lockedXmr,untilHeight:G.untilHeight??null,untilTime:G.untilTime??null,waitedMs:Date.now()-W})}if(L){let G=await pc({...L,nowSec:Math.floor(Date.now()/1e3)});if(F.verify=G,!G.seen){if(Date.now()-W>=P)throw new h("xmr-timeout",{id:k,address:F.address,expectedXmr:F.expectedXmr,state:G.state,confirmations:G.confirmations??0,waitedMs:Date.now()-W,timeoutMs:P,pollMs:H});await new Promise(J=>setTimeout(J,H));continue}let Z={seen:!0,id:k,address:F.address,status:F.status,expectedXmr:F.expectedXmr,receivedXmr:Number(G.amountAtomic)/1e12,confirmations:G.confirmations,txids:[G.txid],at:Date.now(),verified:{height:G.height,blockHash:G.blockHash,operators:G.operators,agreedBy:G.agreedBy},source:"client"};return _&&K?Z.marked=await w.markReady({escrow:f.escrow||F.address,expect:f.expect,onStep:f.onStep},f.wallet):Z.next="mark-ready",Z}if(F.seen)return{seen:!1,observed:{id:F.id,address:F.address,status:F.status,expectedXmr:F.expectedXmr,receivedXmr:F.receivedXmr,confirmations:F.confirmations,txids:F.txids},id:k,address:F.address,expectedXmr:F.expectedXmr,next:"verify",source:"service"};if(Date.now()-W>=P)throw new h("xmr-timeout",{id:k,address:F.address,expectedXmr:F.expectedXmr,receivedXmr:F.receivedXmr,confirmations:F.confirmations,waitedMs:Date.now()-W,timeoutMs:P,pollMs:H});await new Promise(G=>setTimeout(G,H))}},async startSell(f){if(!f||typeof f!="object")throw new h("bad-input",{field:"request"});let k=f.offer&&typeof f.offer=="object"?f.offer:null;if(!k)throw new h("bad-input",{field:"offer"});let _=k.order&&typeof k.order=="object"?k.order:null,K=k.quote&&typeof k.quote=="object"?k.quote:null;if(!_||!K)throw new h("bad-input",{field:"offer",missing:["order","quote"]});if(typeof k.jointAddress!="string"||!k.jointAddress)throw new h("bad-input",{field:"offer.jointAddress"});if(typeof k.escrow!="string"||!k.escrow)throw new h("bad-input",{field:"offer.escrow"});let H=(X,G)=>String(X||"").replace(/^0x/,"").toLowerCase()===String(G||"").replace(/^0x/,"").toLowerCase();if(!H(K.locker,_.locker)||!H(K.claimer,_.claimer)||!H(K.provider,_.locker)||!H(K.factory,_.factory)||Number(K.chainId)!==Number(_.chainId))throw new h("quote-refused",{step:"sell-record",why:"terms"});let P=K.id||K.nonce||null,j=I().find(X=>X.side==="sell"&&(X.escrow&&String(X.escrow.address||"").toLowerCase()===String(k.escrow).toLowerCase()||P!==null&&String(X.orderQuoteId||"")===String(P)));if(j){let X=j.quote&&typeof j.quote=="object"?j.quote:{},G=(Z,J)=>String(Z||"").replace(/^0x/,"").toLowerCase()===String(J||"").replace(/^0x/,"").toLowerCase();if(!G(X.commitHalfClaimer,K.commitHalfClaimer)||!G(X.edPointClaimer,K.edPointClaimer)||!G(j.escrow&&j.escrow.moneroAddress,k.jointAddress))throw new h("quote-refused",{step:"sell-record",why:"offer-changed"});return await N(j.escrow&&j.escrow.address||k.escrow,j.expect||null),{id:j.id,side:"sell",escrow:j.escrow&&j.escrow.address||k.escrow,address:j.escrow&&j.escrow.moneroAddress||k.jointAddress,xmrAmount:j.escrow&&j.escrow.xmrAmount||K.xmrAmount,claimTip:j.claimTip||K.claimTip,orderQuote:j.orderQuote||k.orderQuote,resumed:!0,next:"send-xmr"}}let L=s.storage(),z=typeof f.recoveryKey=="string"?f.recoveryKey:f.recoveryKey&&typeof f.recoveryKey.mnemonic=="string"?f.recoveryKey.mnemonic:null,W=Qd(L);if(W&&z&&W.mnemonic!==z)throw new h("bad-input",{field:"recoveryKey",why:"different-key"});if(!W&&!z)throw new h("bad-input",{field:"recoveryKey"});let $=W||Gd(z);W||Ma(L,{...$,backupConfirmed:!1});let O=Number(_.chainId);if(!Number.isSafeInteger(O)||O<=0)throw new h("bad-input",{field:"order.chainId"});if(!_.factory||_.salt===void 0||_.salt===null)throw new h("bad-input",{field:"order"});let g=null;try{g=un(k.recovery&&k.recovery.salt?k.recovery.salt:_.salt)}catch{throw new h("bad-input",{field:"offer.recovery"})}let T=hr({mnemonic:$.mnemonic,chainId:O,factory:_.factory,salt:g}),v=mr(_,{spendHalf:T.spendHalf,viewHalf:T.viewHalf}),V=(()=>{try{let X=Ue.Point.fromHex(v.side.proof.XA);return"0x"+Array.from(q(X.toBytes(!1).slice(1)),G=>G.toString(16).padStart(2,"0")).join("")}catch{return null}})(),D=X=>String(X||"").replace(/^0x/,"").toLowerCase().slice(-40);if(!V||D(V)!==D(K.commitHalfClaimer))throw new h("quote-refused",{step:"sell-record",why:"commitment"});if(String(v.spendPoint).toLowerCase()!==String(K.edPointClaimer||"").toLowerCase())throw new h("quote-refused",{step:"sell-record",why:"spend-point"});if(k.edViewPointClaimer&&String(v.viewPoint).toLowerCase()!==String(k.edViewPointClaimer).toLowerCase())throw new h("quote-refused",{step:"sell-record",why:"view-point"});let M=Nf({side:"sell",network:String(_.chainId),moneroNetwork:o||void 0,payToken:_.asset||K.asset||void 0,payAmount:K.amount,xmrAmount:Number(K.xmrAmount)/1e12,orderQuoteId:P||void 0,receiveAddress:_.claimer,makerId:K.provider||null},{order:_,side:v.side,store:s}).swap;M.side="sell",M.order=_,M.orderQuote=k.orderQuote||null,M.quote=K,M.claimTip=K.claimTip||null,M.expect={chainId:O,factory:_.factory,locker:_.locker,claimer:_.claimer,amount:String(_.amount),readyBy:_.readyBy,t1:_.t1,salt:_.salt,commitHalfLocker:k.nodeHalf&&k.nodeHalf.commitHalf||null,edPointLocker:k.nodeHalf&&k.nodeHalf.edPoint||null,edViewPointLocker:k.edViewPointLocker||null,commitHalfClaimer:K.commitHalfClaimer||null,edPointClaimer:K.edPointClaimer||null},M.escrow={...M.escrow||{},address:k.escrow,moneroAddress:k.jointAddress,half:dn(v.side.half),viewHalf:dn(v.side.viewHalf),edPointClaimer:v.spendPoint,edViewPointClaimer:Se(v.side.viewPub),commitHalfClaimer:K.commitHalfClaimer,edPointLocker:k.nodeHalf&&k.nodeHalf.edPoint||null,edViewPointLocker:k.edViewPointLocker||null,commitHalfLocker:k.nodeHalf&&k.nodeHalf.commitHalf||null,orderContext:k.context||null,xmrAmount:K.xmrAmount||null};try{await N(k.escrow,M.expect)}catch(X){try{fe.forgetSwap(M.id,s)}catch{}throw X}try{fe.saveSwap(M,s)}catch{throw new h("storage-unavailable",{step:"save-swap"})}return{id:M.id,side:"sell",escrow:k.escrow,address:k.jointAddress,xmrAmount:K.xmrAmount,claimTip:K.claimTip||null,orderQuote:k.orderQuote||null,resumed:!1,next:"send-xmr"}},async sellClaim(f,k){if(!f||typeof f!="object")throw new h("bad-input",{field:"request"});let _=String(f.id||"").trim();if(!_)throw new h("bad-input",{field:"id"});let K=null;try{K=fe.getSwap(_,s)}catch{K=null}if(!K||K.side!=="sell")throw new h("bad-input",{field:"id",why:"sell-not-found"});let H=f.escrow||K.escrow&&K.escrow.address||null,P=f.halfClaimer||K.escrow&&K.escrow.half||null;if(!H||!P)throw new h("bad-input",{field:"escrow",missing:["escrow","halfClaimer"]});let j=f.expect||K.expect||null;if(!j)throw new h("bad-input",{field:"expect",why:"not-in-record"});return w.claim({escrow:H,halfClaimer:P,claimer:K.order&&K.order.claimer,expect:j,onStep:f.onStep},k)},async sellWatch(f){if(!f||typeof f!="object")throw new h("bad-input",{field:"request"});let k=String(f.escrow||"").trim();if(!k)throw new h("bad-input",{field:"escrow"});let _=Number.isFinite(Number(f.pollMs))&&Number(f.pollMs)>0?Number(f.pollMs):b("watchPollMs",6e3),K=Number.isFinite(Number(f.timeoutMs))&&Number(f.timeoutMs)>0?Number(f.timeoutMs):b("watchTimeoutMs",12e5);if(!(Number.isFinite(Number(f.timeoutMs))&&Number(f.timeoutMs)>0))try{let L=await go(k,{call:p});K=g3({configuredMs:K,readyBySec:L.readyBy})}catch{}let H=Date.now(),P=null,j=null;for(;;){try{P=await kr(k,{call:p})}catch(L){j=L&&L.code||"status-unread",P=null}if(P&&(P.isClaimed||P.isRefunded))return{escrow:k,state:P.isClaimed?"claimed":"refunded",funded:P.isFunded,claimed:P.isClaimed,refunded:P.isRefunded,ready:null,balanceWei:String(P.balance),waitedMs:Date.now()-H};if(P&&P.isFunded){let L=null;try{let z=await p({to:k,data:Ie.encodeRead("ready")}),W=String(z||"").replace(/^0x/,"");L=W.length>0&&BigInt("0x"+W)!==0n}catch(z){j=z&&z.code||"ready-unread"}if(L===!0)return{escrow:k,state:"ready",funded:!0,claimed:!1,refunded:!1,ready:!0,balanceWei:String(P.balance),waitedMs:Date.now()-H}}if(Date.now()-H>=K)throw new h("sell-timeout",{escrow:k,waitedMs:Date.now()-H,timeoutMs:K,status:P,error:j});await new Promise(L=>setTimeout(L,_))}}}}var x3=2,k3=10,So=(e,t)=>{try{return BigInt(e)}catch{throw new h("bad-input",{field:t})}},S3=e=>{if(!e||typeof e.driver!="function")throw new h("bad-input",{field:"wallet.driver"});let t=e.driver();if(!t||typeof t!="object")throw new h("bad-input",{field:"wallet.driver"});let n=["setRestoreHeight","getBalance"].filter(r=>typeof t[r]!="function");if(n.length)throw new h("bad-input",{field:"wallet.driver",missing:n});return t},Ut=async(e,t)=>{try{return await t()}catch(n){throw n instanceof h?n:new h("wallet-rejected",{surface:e,why:String(n&&n.message||n)})}},ox=async(e,t)=>{if(typeof e[t]!="function")return null;try{let n=await e[t](),r=Number(n);return Number.isFinite(r)?r:null}catch{return null}},ix=async(e,{syncError:t=null,rescanError:n=null,spentChecked:r=!0}={})=>{let o=await ox(e,"getHeight"),i=await ox(e,"getDaemonHeight"),s=null;return n?s="rescan-failed":t?s="sync-failed":o===null||i===null?s="no-heights":o<i?s="behind-node":r||(s="spent-status-unavailable"),{scanComplete:s===null,...s===null?{}:{scanIncompleteReason:s},walletHeight:o,nodeHeight:i}};async function v3({nodeUrl:e,fromHeight:t,toHeight:n,fetchImpl:r=globalThis.fetch,sleep:o=E3,attempts:i=3}={}){let s=typeof e=="string"?e.trim():"";for(;s.endsWith("/");)s=s.slice(0,-1);let a=Number(t),c=Number(n);if(!s)throw new h("bad-input",{field:"window.nodeUrl"});if(!Number.isSafeInteger(a)||a<0)throw new h("bad-input",{field:"window.fromHeight"});if(!Number.isSafeInteger(c)||c<a)throw new h("bad-input",{field:"window.toHeight"});if(typeof r!="function")throw new h("bad-input",{field:"fetchImpl"});let l=Math.max(1,Math.min(5,Number(i)||3)),u=[];for(let d=a;d<=c;d+=1){let p=null,m=null;for(let x=1;x<=l;x+=1){try{p=await r(s+"/json_rpc",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:"block",method:"get_block",params:{height:d}}),signal:typeof AbortSignal<"u"&&AbortSignal.timeout?AbortSignal.timeout(8e3):void 0})}catch{if(p=null,m=new h("wallet-rejected",{surface:"window-blocks",height:d,why:"transport"}),x<l){await o(sx(x));continue}throw m}if(p&&p.ok===!0){m=null;break}let I=p?p.status:null;if(m=new h("wallet-rejected",{surface:"window-blocks",height:d,status:I}),(I===429||I!==null&&I>=500)&&x<l){await o(A3(p)??sx(x));continue}throw m}if(!p||p.ok!==!0)throw m||new h("wallet-rejected",{surface:"window-blocks",height:d});let w=null;try{w=await p.json()}catch{throw new h("wallet-rejected",{surface:"window-blocks",height:d,why:"not-json"})}if(!w||w.error||!w.result)throw new h("wallet-rejected",{surface:"window-blocks",height:d,why:"rpc"});let y=w.result,b=Array.isArray(y.tx_hashes)?y.tx_hashes:null;if(!b&&typeof y.json=="string")try{let x=JSON.parse(y.json);b=Array.isArray(x.tx_hashes)?x.tx_hashes:null}catch{b=null}if(!b)throw new h("wallet-rejected",{surface:"window-blocks",height:d,why:"no-tx-hashes"});u.push(...b.map(String))}return u}var E3=e=>new Promise(t=>setTimeout(t,e)),sx=e=>Math.min(4e3,250*2**Math.max(0,e-1));function A3(e){try{let t=e&&e.headers&&typeof e.headers.get=="function"?e.headers.get("retry-after"):null;if(t==null||t==="")return null;let n=Number(t);if(Number.isFinite(n)&&n>=0)return Math.min(5e3,Math.floor(n*1e3));let r=Date.parse(String(t));if(Number.isFinite(r))return Math.min(5e3,Math.max(0,r-Date.now()))}catch{}return null}async function ax(e={}){let t=e.wallet;if(!t||typeof t!="object")throw new h("bad-input",{field:"wallet"});let n=["sync","unlockedBalance"].filter(E=>typeof t[E]!="function");if(n.length)throw new h("bad-input",{field:"wallet",missing:n});let r=Number(e.fromHeight);if(!Number.isFinite(r)||r<=0)throw new h("bad-input",{field:"restoreHeight"});let o=Number.isFinite(Number(e.scanBack))&&Number(e.scanBack)>=0?Math.floor(Number(e.scanBack)):k3,i=Math.max(0,Math.floor(r)-o),s=S3(t),a=e.window&&typeof e.window=="object"?e.window:null,c=null,l=0n,u=0n;if(a){let E=Number(a.tipHeight);if(!Number.isSafeInteger(E)||E<=0)throw new h("bad-input",{field:"window.tipHeight"});c={used:!1,skipped:null,fallback:!1,fromHeight:r,toHeight:Number(a.toHeight),blocks:Math.max(0,Number(a.toHeight)-r+1),txs:0};let U=Array.isArray(a.txHashes)?a.txHashes.map(String):null;if(U===null)try{U=await v3({nodeUrl:a.nodeUrl,fromHeight:r,toHeight:a.toHeight,fetchImpl:e.fetchImpl})}catch(S){if(S&&S.code==="bad-input")throw S;c.fallback=!0,c.fallbackWhy="window-read",c.error={code:S&&S.code?S.code:"wallet-rejected",surface:S&&S.params&&S.params.surface?S.params.surface:"window-blocks",status:S&&S.params&&S.params.status!==void 0?S.params.status:null,height:S&&S.params&&S.params.height!==void 0?S.params.height:null,why:S&&S.params&&S.params.why?S.params.why:null},U=[]}if(c.txs=U.length,U.length&&typeof s.scanTxs=="function"){let S=null;try{await Ut("setRestoreHeight",()=>s.setRestoreHeight(E)),await Ut("scanTxs",()=>s.scanTxs(U));try{await t.sync()}catch(B){S=B}l=So(await Ut("getBalance",()=>s.getBalance()),"balance"),u=So(await Ut("unlockedBalance",()=>t.unlockedBalance()),"unlockedBalance"),c.used=!0}catch(B){if(B&&B.code==="bad-input")throw B;l=0n,u=0n,c.fallback=!0,c.fallbackWhy="window-scan",c.error={code:B&&B.code?B.code:"wallet-rejected",surface:B&&B.params&&B.params.surface?B.params.surface:"scanTxs",status:null,height:null,why:B&&B.params&&B.params.why?B.params.why:null}}if(c.used&&a.nodeUrl&&typeof s.getKeyImages=="function")try{let B=await s.getKeyImages(),A=(Array.isArray(B)?B:B&&typeof B.getKeyImages=="function"?B.getKeyImages():[]).map(N=>typeof N=="string"?N:N&&typeof N.getHex=="function"?N.getHex():N&&N.hex).filter(Boolean);if(A.length){let N=String(a.nodeUrl);for(;N.endsWith("/");)N=N.slice(0,-1);let f=await(e.fetchImpl||globalThis.fetch)(N+"/is_key_image_spent",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({key_images:A}),signal:typeof AbortSignal<"u"&&AbortSignal.timeout?AbortSignal.timeout(8e3):void 0}),k=f&&f.ok===!0?await f.json():null;k&&Array.isArray(k.spent_status)?(c.spent=k.spent_status.filter(_=>_===!0||_===1).length,c.keyImages=A.length):c.spent=null}else c.spent=null,c.spentWhy="no-key-images"}catch{c.spent=null,c.spentWhy="check-failed"}else c.used&&a.nodeUrl&&(c.spent=null,c.spentWhy="no-key-images");if(c.used&&(l>0n||u>0n||a.fallback===!1)){let B=await ix(s,{syncError:S,spentChecked:c.spent!==null&&c.spent!==void 0});return{total:l.toString(),unlocked:u.toString(),scanHeight:i,...B,passes:1,lockedPass:!1,window:c}}}else U.length&&(c.skipped="no-scan-txs")}if(c&&(c.fallback=!0,c.fallbackWhy||(c.fallbackWhy="empty-window")),await Ut("setRestoreHeight",()=>s.setRestoreHeight(i)),typeof s.rescanBlockchain!="function")throw new h("bad-input",{field:"wallet.driver.rescanBlockchain"});let d=null;try{await Ut("rescanBlockchain",()=>s.rescanBlockchain())}catch(E){d=E}let p=null;try{await t.sync()}catch(E){p=E}let m=So(await Ut("getBalance",()=>s.getBalance()),"balance"),w=So(await Ut("unlockedBalance",()=>t.unlockedBalance()),"unlockedBalance"),y=1,b=!1;if(e.rescanWhenLocked!==!1&&m>0n&&w===0n&&typeof s.rescanSpent=="function"&&y<x3){b=!0,await Ut("rescanSpent",()=>s.rescanSpent());try{await t.sync()}catch(E){p=E}m=So(await Ut("getBalance",()=>s.getBalance()),"balance"),w=So(await Ut("unlockedBalance",()=>t.unlockedBalance()),"unlockedBalance"),y+=1}let I=await ix(s,{syncError:p,rescanError:d});return{total:m.toString(),unlocked:w.toString(),scanHeight:i,...I,passes:y,lockedPass:b,window:c}}function cx(e){let t=Array.isArray(e)?e:[e];if(!t.length)return null;let n=0n;for(let r of t){if(!r||typeof r.getFee!="function")return null;let o;try{o=r.getFee()}catch{return null}if(o==null)return null;let i;try{i=BigInt(o)}catch{return null}if(i<0n)return null;n+=i}return n.toString()}var vo="monero",_3="ninsei-wallet-session",N3=["mainnet","stagenet","testnet","fakechain"],I3=()=>{let e=oe.XMR_NETWORKS||{};return[...new Set([...Object.values(e).filter(t=>typeof t=="string"&&t),...N3])].sort()};function lx({createWallet:e=null,network:t=null,serverUri:n=null,password:r=_3,keys:o={},restoreHeight:i=0,expectedAddress:s=null}={}){let a=null,c=null,l=new Set,u=()=>{for(let w of l)try{w()}catch{}},d=w=>{if(a===null)throw new h("wallet-not-connected",{vm:vo,surface:w});return a},p=()=>{if(typeof o.seed=="string"&&o.seed)return{seed:o.seed};if(o.privateSpendKey||o.privateViewKey){if(!o.primaryAddress)throw new h("bad-input",{field:"primaryAddress",why:"required-with-private-keys"});let w={};return o.privateSpendKey&&(w.privateSpendKey=o.privateSpendKey),o.privateViewKey&&(w.privateViewKey=o.privateViewKey),w.primaryAddress=o.primaryAddress,w}throw new h("bad-input",{field:"keys",missing:["seed","privateSpendKey"]})},m=async()=>{if(a===null)return;let w=a;a=null,c=null;try{await w.close()}catch{}};return{vm:vo,id:vo,async connect(){if(typeof e!="function")throw new h("bad-input",{field:"createWallet"});let w=I3();if(typeof t!="string"||!t)throw new h("bad-input",{field:"network",known:w});if(w.length&&!w.includes(t))throw new h("bad-input",{field:"network",known:w,got:t});if(typeof n!="string"||!n)throw new h("bad-input",{field:"serverUri"});let y=p(),b=Number(i);if(!Number.isFinite(b)||b<=0)throw new h("bad-input",{field:"restoreHeight",got:i});await m(),a=await e({networkType:t,server:{uri:n},password:r,restoreHeight:b,...y}),c=String(await a.getAddress(0,0));let I=typeof mn.networkFromShape=="function"?mn.networkFromShape(c):null;if(I&&I!==t)throw await m(),new h("wrong-chain",{got:I,want:t});if(s&&c!==s)throw await m(),new h("recovery-failed",{step:"address"});await a.setRestoreHeight(b),u()},async disconnect(){return await m()},async close(){return await m()},address(){return d("address"),c},chainId(){return t},async unlockedBalance(){return await d("unlockedBalance").getUnlockedBalance()},async sync(){await d("sync").sync(),u()},async open(w){if(a===null)throw new h("wallet-not-connected",{vm:vo,surface:"open"});let y=w&&w.address?String(w.address):null;if(y&&c!==y)throw new h("recovery-failed",{step:"address"})},async sweepUnlocked(w){return await d("sweepUnlocked").sweepUnlocked({address:w.address,relay:w.relay})},async relay(w){return await d("relay").relayTxs(w)},async fee(w){return cx(w)},subscribe(w){if(typeof w!="function")throw new h("bad-input",{field:"handler"});return l.add(w),()=>l.delete(w)},async send(){throw new h("not-implemented",{surface:"adapter.send",vm:vo})},async receipt(){throw new h("not-implemented",{surface:"adapter.receipt",vm:vo})},driver(){return a}}}Qn();var T3=e=>typeof e=="string"?e.trim():"";function O3(e){let t=e&&e.receive;return(t&&typeof t.address=="string"?t.address.trim():"")||null}async function ux(e,t){let n=T3(t),r=O3(e),o=e&&e.moneroWallet&&e.moneroWallet.network||null;if(!n)return{ok:!1,dest:n,promised:r,matches:r===null?null:!1,network:o,verified:!1,reason:"no address"};let i=await Bc(n,o?{expectNetwork:o}:{});return{ok:i.ok===!0,dest:n,promised:r,matches:r===null?null:n===r,network:o,verified:i.verified===!0,reason:i.reason||null}}var B3=/^[0-9a-f]{64}$/;function dx(e){let t=String(e??"").trim(),n=(t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t).toLowerCase();return!B3.test(n)||/^0+$/.test(n)?null:"0x"+n}var P3=e=>{if(e==null||e==="")return null;let t=String(e);if(/^\d+$/.test(t))return ub(BigInt(t));let n=Number(t);return Number.isFinite(n)&&n>0?t:null},hc=12,C3=["unlock","sync","sweep","relay"],R3=10000000000n;function H3({feeAtomic:e=null,amountAtomic:t=null,maxFeeAtomic:n=R3}={}){if(e==null)return{ok:!0,checked:!1,fee:null,limit:String(n)};let r,o,i;try{r=BigInt(e),o=t==null?null:BigInt(t),i=BigInt(n)}catch{return{ok:!1,code:"sweep-fee-too-high",why:"unreadable",fee:String(e),limit:String(n)}}return r<0n||i<0n?{ok:!1,code:"sweep-fee-too-high",why:"negative",fee:r.toString(),limit:i.toString()}:r>i?{ok:!1,code:"sweep-fee-too-high",why:"ceiling",fee:r.toString(),limit:i.toString(),amount:o===null?null:o.toString()}:{ok:!0,checked:!0,fee:r.toString(),limit:i.toString(),amount:o===null?null:o.toString()}}var L3="0x3f267bb6",Mf=e=>typeof e=="string"?e:e&&typeof e.contents=="string"?e.contents:null,Eo=e=>String(e??"").replace(/^0x/i,"").toLowerCase(),F3=async e=>{let t=e&&e.order;if(!t||typeof t!="object")throw new h("bad-input",{field:"order"});if(typeof e.mnemonic!="string"||!e.mnemonic.trim())throw new h("bad-input",{field:"mnemonic"});let n=Number(e.chainId);if(!Number.isSafeInteger(n)||n<=0)throw new h("bad-input",{field:"chainId"});let r=typeof e.network=="string"?e.network.trim():"",o=typeof e.moneroNetwork=="string"?e.moneroNetwork.trim():"";if(!r)throw new h("bad-input",{field:"network"});if(!o)throw new h("bad-input",{field:"moneroNetwork"});let i=typeof e.passphrase=="string"?e.passphrase:"";if(i&&i.length<hc)throw new h("bad-input",{field:"passphrase",min:hc});let s=t.side==="locker"?"buy":t.side==="claimer"?"sell":null;if(!s)throw new h("bad-input",{field:"order.side"});if(typeof t.factory!="string"||!/^0x[0-9a-fA-F]{40}$/.test(t.factory))throw new h("bad-input",{field:"order.factory"});let a=hr({mnemonic:e.mnemonic,chainId:n,factory:t.factory,salt:t.salt}),c=s==="buy";if(Eo(c?t.edPointLocker:t.edPointClaimer)!==Eo(a.spendPoint))throw new h("bad-input",{field:"order",why:"spend-point"});if(Eo(t.edViewPointLocker)!==Eo(c?a.viewPoint:a.makerViewPoint))throw new h("bad-input",{field:"order",why:c?"own-view-point":"maker-view-point"});let l="0x"+Eo(c?t.edPointClaimer:t.edPointLocker),u="0x"+Eo(a.makerViewPoint),d=so({ownSpendHalf:a.spendHalf,ownViewHalf:a.viewHalf,otherSpendPoint:l,otherViewPoint:u,network:o}),p=(()=>{try{let y=BigInt(String(t.xmrAmount));return y>0n?y.toString():null}catch{return null}})(),m={address:t.escrow,readyBy:t.readyBy,t1:t.t1,...p?{expectedAtomic:p}:{}},w=ut.buildPayload({swap:{id:t.escrow,side:s,network:r,moneroNetwork:o,createdAt:t.blockTime?Number(t.blockTime)*1e3:null,payToken:null,payAmount:null,xmrAmount:P3(t.xmrAmount),rate:null,maker:null,quoteSignature:null,escrow:m,timeline:null},swapWallet:{source:"halves",network:o,address:d.address,spendHalf:a.spendHalf,viewHalf:a.viewHalf,otherSpendPoint:l,otherViewPoint:u,otherViewHalf:a.makerViewHalf,escrowAddress:t.escrow},escrow:m,receiveAddress:null,restoreHeight:Number(t.startHeight)>0?Number(t.startHeight):null});return{payload:w,contents:await ut.createRecoveryFile(w,i),address:d.address}},fx=async(e,t)=>{try{return await t()}catch(n){throw n instanceof h?n:new h("wallet-rejected",{surface:e,why:String(n&&n.message||n)})}},D3=async(e,t)=>{if(!e||typeof e.fee!="function")return null;let n;try{n=await e.fee(t)}catch{return null}if(n==null)return null;let r=String(n);return/^\d+$/.test(r)?r:null};function px({http:e,config:t,call:n=null}){let r=new Map,o=0,i={mainnet:"MAINNET",stagenet:"STAGENET",testnet:"TESTNET"},s={async fromOrder(a={}){return await F3(a)},wallet(a={}){let c=a.moneroTs;if(!c||typeof c!="object")throw new h("bad-input",{field:"moneroTs"});if(typeof c.createWalletFull!="function")throw new h("bad-input",{field:"moneroTs.createWalletFull"});let l=String(a.network||"").trim().toLowerCase(),u=i[l]||null,d=u&&c.MoneroNetworkType?c.MoneroNetworkType[u]:void 0;if(d==null)throw new h("bad-input",{field:"network",known:Object.keys(i),got:a.network});if(typeof a.serverUri!="string"||!a.serverUri)throw new h("bad-input",{field:"serverUri"});return lx({createWallet:p=>c.createWalletFull({...p,networkType:d}),network:l,serverUri:a.serverUri,password:a.password,keys:a.keys||{},restoreHeight:a.restoreHeight,expectedAddress:a.expectedAddress||null})},async destination(a={}){let c=Mf(a.file);if(!c)throw new h("bad-input",{field:"file"});if(typeof a.passphrase!="string")throw new h("bad-input",{field:"passphrase"});if(typeof a.dest!="string"||!a.dest.trim())throw new h("bad-input",{field:"dest"});let l=null;try{l=await ut.decryptFile(JSON.parse(c),a.passphrase)}catch{throw new h("recovery-failed",{step:"decrypt"})}try{ut.validatePayload(l)}catch{throw new h("recovery-failed",{step:"validate"})}return ux(l,a.dest)},async plan(a){if(!a||typeof a!="object")throw new h("bad-input",{field:"request"});let c=Mf(a.file);if(!c)throw new h("bad-input",{field:"file"});if(typeof a.passphrase!="string"||a.passphrase.length>0&&a.passphrase.length<hc)throw new h("bad-input",{field:"passphrase",min:hc});let l=null;try{l=JSON.parse(c)}catch{throw new h("recovery-failed",{step:"parse"})}let u=null;try{u=await ut.decryptFile(l,a.passphrase)}catch{throw new h("recovery-failed",{step:"decrypt"})}try{ut.validatePayload(u)}catch{throw new h("recovery-failed",{step:"validate"})}let d=u.moneroWallet||{},p=d.address||null;if(!p)throw new h("recovery-failed",{step:"address"});let m=[],w=!!d.spendHalf;w||m.push("spendable");let y=Number(d.restoreHeight)||0;y>0||m.push("restore-height");let b=!1,x=null,I=d.escrowAddress||u.escrow&&u.escrow.address||null;if(I&&typeof n=="function")try{let E=String(await n({to:I,data:L3})||""),U=dx(E);U!==null&&(b=!0,x=U)}catch{b=!1}return b||m.push("revealed-half"),{swapId:u.swapId||null,address:p,spendable:w,restoreHeight:y,steps:C3,revealedHalf:b,half:x,missing:m}},async keys(a){let c=await s.plan(a);if(!c.half)throw new h("bad-input",{field:"revealedHalf",why:"not-revealed"});let l=Mf(a.file),u=null;try{u=await ut.decryptFile(JSON.parse(l),a.passphrase)}catch{throw new h("recovery-failed",{step:"decrypt"})}let d=u.moneroWallet||{},m=["spendHalf","viewHalf","otherSpendPoint","otherViewHalf"].filter(w=>d[w]===void 0||d[w]===null||d[w]==="");if(m.length)throw new h("bad-input",{field:"payload",missing:m});try{let w=tn.createHalves(Ln),y=Ks.spendKeysFromRevealedHalf({halves:w,ownSpendHalf:d.spendHalf,ownViewHalf:d.viewHalf,otherSpendPoint:d.otherSpendPoint,otherViewHalf:d.otherViewHalf,revealedHalf:c.half});return{privateSpendKey:y.privateSpendKey,privateViewKey:y.privateViewKey,address:c.address}}catch{throw new h("bad-input",{field:"revealedHalf",step:"verify"})}},async restore(a){return await ax(a||{})},async sign(a){let c=await s.plan(a);if(!a||typeof a.to!="string"||!a.to)throw new h("bad-input",{field:"to"});let l=a.wallet!==void 0&&a.wallet!==null?a.wallet:typeof a.connectWallet=="function"?await a.connectWallet(c):(()=>{throw new h("bad-input",{field:"connectWallet"})})(),d=["open","sync","unlockedBalance","sweepUnlocked","relay","close"].filter(p=>!l||typeof l[p]!="function");if(d.length)throw new h("bad-input",{field:"wallet",missing:d});await l.open(c);try{try{await l.sync()}catch{}let p=BigInt(await fx("unlockedBalance",()=>l.unlockedBalance()));if(p<=0n)throw new h("insufficient-funds",{unlocked:p.toString()});let m=await fx("sweepUnlocked",()=>l.sweepUnlocked({address:a.to,relay:!1})),w=await D3(l,m),y=w===null?null:BigInt(w),b=H3({feeAtomic:w,amountAtomic:p,...a.maxFeeAtomic===void 0||a.maxFeeAtomic===null?{}:{maxFeeAtomic:a.maxFeeAtomic}});if(!b.ok)throw new h(b.code,{fee:b.fee,limit:b.limit,amount:b.amount,why:b.why});let x="sweep-"+ ++o;return r.set(x,{wallet:l,plan:c,signed:m}),{token:x,amount:p.toString(),fee:w,receive:y===null||y>=p?null:(p-y).toString(),to:a.to,swept:c.address}}catch(p){try{await l.close()}catch{}throw p}},async relay(a){if(!a||typeof a.token!="string"||!a.token)throw new h("bad-input",{field:"token"});let c=r.get(a.token);if(!c)throw new h("bad-input",{field:"token",why:"no-open-session"});r.delete(a.token);let{wallet:l,plan:u,signed:d}=c;try{let p=await l.relay(d);return{txids:Array.isArray(p)?p:[],swept:u.address}}finally{await l.close()}},async run(a){let c=await s.sign(a);return await s.relay({token:c.token})}};return s}var U3=e=>{let t=e&&typeof e=="object"?e:{},n=t.settlement&&typeof t.settlement=="object"?t.settlement:null;(!n||typeof n.chain!="string"||!n.chain)&&C("bad-input",{field:"settlement.chain"}),n.vm!==void 0&&(typeof n.vm!="string"||!n.vm)&&C("bad-input",{field:"settlement.vm"}),(typeof t.xmrNetwork!="string"||!t.xmrNetwork)&&C("bad-input",{field:"xmrNetwork"});let r=t.mode===void 0?"live":t.mode;if(r!=="live"&&r!=="sim"&&C("bad-input",{field:"mode",known:["live","sim"]}),t.storage!==void 0){let o=t.storage;o&&typeof o.get=="function"&&typeof o.set=="function"&&typeof o.remove=="function"||C("bad-input",{field:"storage"})}if(t.fetch!==void 0&&typeof t.fetch!="function"&&C("bad-input",{field:"fetch"}),t.now!==void 0&&typeof t.now!="function"&&C("bad-input",{field:"now"}),t.routing!==void 0){let o=t.routing;(!o||typeof o!="object"||o.prefer!==void 0&&!Array.isArray(o.prefer))&&C("bad-input",{field:"routing"})}if(t.routes!==void 0&&(!t.routes||typeof t.routes!="object"||Array.isArray(t.routes))&&C("bad-input",{field:"routes"}),t.endpoints!==void 0&&(!t.endpoints||typeof t.endpoints!="object"||Array.isArray(t.endpoints))&&C("bad-input",{field:"endpoints"}),t.nodes!==void 0&&!Array.isArray(t.nodes)&&(!t.nodes||typeof t.nodes!="object")&&C("bad-input",{field:"nodes"}),t.addNodes!==void 0&&!Array.isArray(t.addNodes)&&C("bad-input",{field:"addNodes"}),t.evmCall!==void 0&&typeof t.evmCall!="function"&&C("bad-input",{field:"evmCall"}),t.evmCode!==void 0&&typeof t.evmCode!="function"&&C("bad-input",{field:"evmCode"}),t.evmLogs!==void 0&&typeof t.evmLogs!="function"&&C("bad-input",{field:"evmLogs"}),t.evmBlock!==void 0&&typeof t.evmBlock!="function"&&C("bad-input",{field:"evmBlock"}),t.allowedProviders!==void 0&&t.allowedProviders!==null){let o=t.allowedProviders;!Array.isArray(o)&&typeof o!="function"&&C("bad-input",{field:"allowedProviders"})}if(t.knownFactoryCodes!==void 0&&t.knownFactoryCodes!==null&&!Array.isArray(t.knownFactoryCodes)&&C("bad-input",{field:"knownFactoryCodes"}),t.knownImplementationCodes!==void 0&&t.knownImplementationCodes!==null&&!Array.isArray(t.knownImplementationCodes)&&C("bad-input",{field:"knownImplementationCodes"}),t.denylist!==void 0&&t.denylist!==null&&(!Array.isArray(t.denylist)||t.denylist.some(o=>typeof o!="string"))&&C("bad-input",{field:"denylist"}),t.serverAuth!==void 0&&typeof t.serverAuth!="function"&&C("bad-input",{field:"serverAuth"}),t.createRecord!==void 0&&typeof t.createRecord!="function"&&C("bad-input",{field:"createRecord"}),t.watch!==void 0){let o=t.watch;(!o||typeof o!="object"||Array.isArray(o))&&C("bad-input",{field:"watch"});for(let i of["pollMs","timeoutMs"])o[i]!==void 0&&!(Number.isFinite(Number(o[i]))&&Number(o[i])>0)&&C("bad-input",{field:"watch."+i})}return{settlement:{chain:n.chain,vm:n.vm},xmrNetwork:t.xmrNetwork,apiBase:typeof t.apiBase=="string"&&t.apiBase?t.apiBase:null,assetsBase:typeof t.assetsBase=="string"&&t.assetsBase?t.assetsBase:"/",mode:r,storage:t.storage||null,fetch:t.fetch||null,now:t.now||null,routing:t.routing||null,routes:t.routes||null,endpoints:t.endpoints||null,nodes:t.nodes===void 0?null:t.nodes,addNodes:t.addNodes===void 0?null:t.addNodes,evmCall:t.evmCall||null,evmCode:t.evmCode||null,evmLogs:t.evmLogs||null,evmBlock:t.evmBlock||null,allowedProviders:t.allowedProviders===void 0?null:t.allowedProviders,knownFactoryCodes:t.knownFactoryCodes===void 0?null:t.knownFactoryCodes,knownImplementationCodes:t.knownImplementationCodes===void 0?null:t.knownImplementationCodes,denylist:t.denylist===void 0?null:t.denylist,serverAuth:t.serverAuth||null,watch:t.watch||null,createRecord:t.createRecord||null}};function M3(e){let t=U3(e),n=ab({settlement:t.settlement,xmrNetwork:t.xmrNetwork,apiBase:t.apiBase,assetsBase:t.assetsBase,mode:t.mode,routing:t.routing,routes:t.routes,endpoints:t.endpoints,watch:t.watch,nodes:t.nodes,addNodes:t.addNodes}),r=cb({chain:n.settlement.chain,knownFactoryCodes:t.knownFactoryCodes}),o=lb({chain:n.settlement.chain,knownImplementationCodes:t.knownImplementationCodes}),i=oo(n.settlement.vm),s=Fg({settlement:n.settlement.chain,leg:i}),a=Cg({config:{...n,evmNetwork:n.settlement.chain},wallet:s,limits:n.limits}),c=t.mode==="sim"?Hg():null,l=Jn.createStore(t.storage||Jn.storage()),u=at({apiBase:n.apiBase,fetchImpl:t.fetch,timeoutMs:n.limits.httpTimeoutMs}),d=(()=>{let x=t.allowedProviders;if(x==null)return null;if(typeof x=="function")return E=>x(E)===!0;let I=new Set(x.map(E=>String(E).toLowerCase()));return E=>I.has(String(E).toLowerCase())})(),p=Array.isArray(t.denylist)&&t.denylist.length?new Set(t.denylist.map(x=>String(x).toLowerCase())):null,m=Ef({config:n,http:u,now:t.now||(()=>Date.now()),evmCall:t.evmCall||null,evmCode:t.evmCode||null,evmBlock:t.evmBlock||null,providerAllowed:d,knownFactoryCodes:r,knownImplementationCodes:o,denylist:p}),w=Mi({call:t.evmCall}),y=typeof t.evmCall=="function"?{call:t.evmCall}:{},b=typeof t.evmLogs=="function"?{logs:t.evmLogs}:{};return Object.freeze({config:n,wallet:s,preflight:a,recovery:Af({http:u,config:n}),actions:w,order:{context:x=>Kn(x),verifyCounterparty:x=>Cb(x),jointAddress:x=>so(x),escrowNativeWei:x=>Ie.escrowNativeWei(x),status:x=>kr(x,y),deadlines:x=>go(x,y),decline:(x,I={})=>Wg(x,{...b,...I||{}})},sim:c,quotes:{watch:(x,I)=>m.watch(x,I),snapshot:()=>m.snapshot(),firm:x=>m.firm(x),firmRelay:x=>m.firmRelay(x),sale:x=>m.sale(x)},swaps:Uf({preflight:a,http:u,mode:t.mode,xmrNetwork:t.xmrNetwork,call:t.evmCall,store:l,logs:t.evmLogs||null,config:n,auth:t.serverAuth,denylist:p,watch:t.watch,createRecord:t.createRecord}),sweep:px({http:u,config:n,call:t.evmCall})})}var jf=e=>typeof e=="string"&&/^0x[0-9a-f]+$/i.test(e)?Number.parseInt(e,16):null,Kf=/^0x[0-9a-fA-F]{40}$/,hx=e=>"0x"+Number(e).toString(16),j3=4902,K3=e=>(e&&(e.code||e.data&&e.data.originalError&&e.data.originalError.code))===j3||/unrecognized chain|not added/i.test(String(e&&e.message||"")),mx=e=>e&&e.code===4001||/rejected|denied/i.test(String(e&&e.message||""));function W3(e,{id:t="evm"}={}){let n=[];return{vm:"evm",id:t,async connect({chainId:r=null}={}){try{await e.request({method:"eth_requestAccounts"})}catch(o){let i=o&&(o.code===4001||o.code==="ACTION_REJECTED"),s=new Error(i?"wallet-rejected":"wallet-not-connected");throw s.code=i?"wallet-rejected":"wallet-not-connected",s}Number.isFinite(r)&&jf(await e.request({method:"eth_chainId"}).catch(()=>null))!==Number(r)&&await this.switchChain(r)},async disconnect(){for(;n.length;){let[r,o]=n.pop();typeof e.removeListener=="function"&&e.removeListener(r,o)}},async address(){let r=await e.request({method:"eth_accounts"}).catch(()=>null),o=Array.isArray(r)?r[0]:null;return typeof o=="string"&&Kf.test(o)?o:null},async chainId(){return jf(await e.request({method:"eth_chainId"}).catch(()=>null))},subscribe(r){if(typeof e.on!="function")return()=>{};for(let o of["accountsChanged","chainChanged"]){let i=()=>r();e.on(o,i),n.push([o,i])}return()=>{}},async switchChain(r){let o=Number(r),i=hx(o);try{await e.request({method:"wallet_switchEthereumChain",params:[{chainId:i}]})}catch(s){if(!K3(s))throw new h(mx(s)?"wallet-rejected":"wrong-chain",{vm:"evm"});let a=typeof oe.chainByChainId=="function"?oe.chainByChainId(o):null;if(!a)throw new h("wrong-chain",{vm:"evm",chainId:o});try{await e.request({method:"wallet_addEthereumChain",params:[{chainId:i,chainName:a.name,nativeCurrency:{name:a.native.symbol,symbol:a.native.symbol,decimals:a.native.decimals},rpcUrls:[a.rpcUrl],blockExplorerUrls:[a.explorerAddr]}]})}catch(c){throw new h(mx(c)?"wallet-rejected":"wrong-chain",{vm:"evm"})}}},async send({to:r,data:o="0x",value:i=0n,gas:s=null,chainId:a=null,from:c=null}){if(typeof r!="string"||!r)throw new h("bad-input",{field:"send.to"});let l=y=>"0x"+BigInt(y).toString(16),u=jf(await e.request({method:"eth_chainId"}).catch(()=>null));if(!Number.isSafeInteger(u)||u<=0)throw new h("wrong-chain",{vm:"evm",step:"send",want:a==null?null:Number(a),got:null,why:"unreadable"});let d=a==null?u:Number(a);if(!Number.isSafeInteger(d)||d<=0||u!==d)throw new h("wrong-chain",{vm:"evm",step:"send",want:d,got:u});let p=await e.request({method:"eth_accounts"}),m=Array.isArray(p)?p[0]:null;if(typeof m!="string"||!Kf.test(m))throw new h("wallet-not-connected",{step:"send"});if(c!=null){let y=String(c).toLowerCase();if(!Kf.test(y))throw new h("bad-input",{field:"send.from"});if(m.toLowerCase()!==y)throw new h("wrong-account",{vm:"evm",step:"send",want:y,got:m})}let w={from:m,to:r,data:o,value:l(i),chainId:hx(u)};return s!=null&&(w.gas=l(s)),await e.request({method:"eth_sendTransaction",params:[w]})},async receipt(r){if(typeof r!="string"||!r)throw new h("bad-input",{field:"receipt.txHash"});return await e.request({method:"eth_getTransactionReceipt",params:[r]})},async signTypedData(r){if(!r||typeof r!="object")throw new h("bad-input",{field:"signTypedData"});let o=await e.request({method:"eth_accounts"}),i=Array.isArray(o)?o[0]:null;if(!i)throw new h("wallet-not-connected",{step:"signTypedData"});let s=await e.request({method:"eth_signTypedData_v4",params:[i,JSON.stringify(r)]});if(typeof s!="string"||!/^0x[0-9a-fA-F]{130}$/.test(s))throw new h("wallet-rejected",{step:"signTypedData",why:"bad-signature-shape"});return s},driver(){return e}}}function V3(e="ninsei.sdk"){let t=n=>e+"."+n;return{get(n){return localStorage.getItem(t(n))},set(n,r){localStorage.setItem(t(n),String(r))},remove(n){localStorage.removeItem(t(n))}}}function $3(e={}){let t=new Map(Object.entries(e));return{get:n=>t.has(n)?t.get(n):null,set:(n,r)=>t.set(n,String(r)),remove:n=>t.delete(n)}}export{ya as CHECK_CODES,Yr as ERROR_CODES,wa as STEP_CODES,h as SdkError,Mi as createActions,M3 as createNinsei,Ef as createQuotes,Af as createRecovery,Uf as createSwaps,W3 as evmWallet,V3 as localStorageAdapter,$3 as memoryAdapter};
|
|
2054
|
+
`}async function K2(e,t,n){if(!globalThis.crypto||!globalThis.crypto.subtle)throw Cy("crypto-unavailable");let r=await crypto.subtle.importKey("raw",wa.encode(e),"PBKDF2",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:t,iterations:n,hash:"SHA-256"},r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}var j2=e=>JSON.stringify({kind:"ninsei-recovery-key",v:e.v,alg:e.alg,iter:e.iter,salt:e.salt,iv:e.iv,meta:e.meta});async function Uu({mnemonic:e,createdAt:t,passphrase:n=""}={}){let r=ya(e,t);if(typeof n!="string")throw yt("passphrase");if(n==="")return M2(r);if(n.length<12)throw yt("passphrase");if(!globalThis.crypto||!globalThis.crypto.subtle)throw Cy("crypto-unavailable");let o=crypto.getRandomValues(new Uint8Array(16)),i=crypto.getRandomValues(new Uint8Array(12)),s={kind:"ninsei-recovery-key",v:O2,alg:C2,iter:Py,salt:Ou(o),iv:Ou(i),meta:{fingerprint:r.fingerprint,createdAt:r.createdAt}},a=await K2(n,o,Py),c=await crypto.subtle.encrypt({name:"AES-GCM",iv:i,tagLength:128,additionalData:wa.encode(j2(s))},a,wa.encode(JSON.stringify({mnemonic:r.mnemonic})));return JSON.stringify({...s,ciphertext:Ou(new Uint8Array(c))},null,2)}var li=e=>new d("storage-unavailable",{step:e}),W2=e=>{if(!e||typeof e.get!="function"||typeof e.set!="function"||typeof e.remove!="function")throw yt("storage");let t;try{t=e.get(Oy)}catch{throw li("read")}if(t==null||t==="")return null;let n;try{n=JSON.parse(t)}catch{throw li("parse")}if(!n||n.version!==By||typeof n.mnemonic!="string")throw li("parse");return n},V2=(e,t)=>{let n;try{n=JSON.stringify(t)}catch{throw li("serialize")}try{e.set(Oy,n)}catch{throw li("write")}};function ui(e,t){let n=ya(t&&t.mnemonic,t&&t.createdAt);return V2(e,{...n,backupConfirmed:t.backupConfirmed===!0}),n}function Mu(e){let t=W2(e);return t?{...t,fingerprint:t.fingerprint||Fu(t.mnemonic)}:null}var $2=18,z2=45,f4=z2+$2*32;var Ru=e=>"0x"+Array.from(Q(new TextEncoder().encode(e)),t=>t.toString(16).padStart(2,"0")).join(""),Hu=Object.freeze({halfRevealed:Ru("HalfRevealed(bytes32,bool)"),ready:Ru("Ready(address)"),declined:Ru("Declined(address)")}),p4=new Map([[Hu.halfRevealed,"HalfRevealed"],[Hu.ready,"Ready"],[Hu.declined,"Declined"]]);fe();Ee();var Qe=()=>Os.createOrderBuilder(Xt);function _t(e){if(!e||typeof e!="object")throw new d("bad-input",{field:"order"});try{return xn.orderContextString(e)}catch{throw new d("bad-input",{field:"order"})}}function Uy({side:e,order:t,sealed:n=null,ownEncPriv:r=null}){if(!e||typeof e!="object")throw new d("bad-input",{field:"side"});let o=_t(t),i=null;try{i=Qe().verifySide(e,o,n,r)}catch{throw new d("bad-input",{field:"side"})}if(!i||i.ok!==!0)throw new d("quote-refused",{step:"proof",why:i&&i.reason?"rejected":"unknown"});return e}function Zr({ownSpendHalf:e,ownViewHalf:t,otherSpendPoint:n,otherViewPoint:r,network:o}){let i={ownSpendHalf:e,ownViewHalf:t,otherSpendPoint:n,otherViewPoint:r},s=Object.keys(i).filter(a=>i[a]===void 0||i[a]===null||i[a]==="");if(s.length)throw new d("bad-input",{field:"jointAddress",missing:s});try{return Qe().jointAddress({ownSpendHalf:e,ownViewHalf:t,otherSpendPoint:n,otherViewPoint:r,network:o})}catch{throw new d("bad-input",{field:"jointAddress"})}}var me=e=>"0x"+String(e).replace(/^0x/i,"").toLowerCase(),Jt=e=>"0x"+BigInt(e).toString(16).padStart(64,"0"),Ku=e=>/^0x[0-9a-f]{64}$/.test(String(e)),Dy=e=>e&&typeof e=="object"&&e.XB?{...e,XB:me(e.XB)}:e,ba=e=>typeof e=="string"&&e?me(e):e;function ju(e){let t=e&&typeof e=="object"?e:{},n=[t.viewHalf,t.viewHalfClaimer].filter(s=>s!=null&&s!==""),r=null;if(n.length){try{r=BigInt(String(n[0]))}catch{throw new d("bad-input",{field:"counterparty",why:"view-half"})}for(let s of n.slice(1)){let a=null;try{a=BigInt(String(s))}catch{a=null}if(a===null||a!==r)throw new d("bad-input",{field:"counterparty",why:"conflicting-view-half"})}}let o=[t.viewPoint,t.viewPub].filter(s=>s!=null&&s!==""),i=null;if(o.length){if(i=ba(o[0]),!Ku(i))throw new d("bad-input",{field:"counterparty",why:"view-point"});for(let s of o.slice(1))if(ba(s)!==i)throw new d("bad-input",{field:"counterparty",why:"conflicting-view-point"})}if(r!==null){let s=null;try{s=ba(Qe().pointOf(r))}catch{s=null}if(!s)throw new d("bad-input",{field:"counterparty",why:"view-half"});if(i!==null&&i!==s)throw new d("bad-input",{field:"counterparty",why:"view-half-point-mismatch"});i=s}return{half:r===null?null:n[0],point:i}}function Wu(e,t){let n=_t(e),r=Qe().newSide(n,!1,t);return{context:n,side:r,spendPoint:me(r.pub.ed),viewPoint:me(r.viewPub),encPub:me(r.enc.pub)}}async function X2(e,t={}){let n=_t(e),r=await Qe().newSideChunked(n,!1,t);return{context:n,side:r,spendPoint:me(r.pub.ed),viewPoint:me(r.viewPub),encPub:me(r.enc.pub)}}function Vu(e,{spendHalf:t,viewHalf:n}={}){let r=(s,a)=>{let c=BigInt(s);if(c<=0n||c>=BigInt(e.halves.LIMIT))throw new d("bad-input",{field:a});return c},o=r(t,"spendHalf"),i=r(n,"viewHalf");return{half:o,view:i,pub:e.halves.publicHalves(o),viewPub:e.halves.publicHalves(i).ed,encPair:e.enc.recipientKeyPair()}}function $u({half:e,view:t,pub:n,viewPub:r,encPair:o},i){return{side:{half:e,pub:n,viewHalf:t,viewPub:r,enc:o,proof:i,standIn:!1},spendPoint:me(n.ed),viewPoint:me(r),encPub:me(o.pub)}}function My(e,{spendHalf:t,viewHalf:n}={}){let r=_t(e),o=Qe(),i=Vu(o,{spendHalf:t,viewHalf:n}),s=o.dleq.prove(i.half,r),{side:a,spendPoint:c,viewPoint:l,encPub:u}=$u(i,s);return{context:r,side:a,spendPoint:c,viewPoint:l,encPub:u}}async function Ky(e,{spendHalf:t,viewHalf:n}={},r={}){let o=_t(e),i=Qe(),s=Vu(i,{spendHalf:t,viewHalf:n}),a=await i.dleq.proveChunked(s.half,o,r),{side:c,spendPoint:l,viewPoint:u,encPub:f}=$u(s,a);return{context:o,side:c,spendPoint:l,viewPoint:u,encPub:f,commitHalf:me(i.halfCommitment(s.half))}}function zu(e,{spendHalf:t,viewHalf:n}={}){let r=_t(e),o=Qe(),i=Vu(o,{spendHalf:t,viewHalf:n}),{side:s,spendPoint:a,viewPoint:c,encPub:l}=$u(i,null);return{context:r,side:s,spendPoint:a,viewPoint:c,encPub:l,commitHalf:me(o.halfCommitment(i.half))}}function Y2({context:e,side:t=null,counterparty:n=null,standIn:r=!1,mock:o=null}){let i=null;if(n&&typeof n=="object"){let c=n.pub&&typeof n.pub=="object"?n.pub:{},l=ju(n);i={proof:Dy(n.proof),edPub:ba(n.edPub||n.edPoint||n.edPointClaimer||c.ed||null),viewPoint:l.point,viewHalf:l.half,half:n.half!==void 0?n.half:null,commitHalfClaimer:n.commitHalfClaimer||null,sealed:n.sealed||null,providerId:n.providerId||null,standIn:!1}}else if(r===!0){let c=o||Qe().newSide(e,!0);i={proof:Dy(c.proof),edPub:me(c.pub.ed),viewPoint:me(c.viewPub),viewHalf:c.viewHalf,half:c.half,commitHalfClaimer:me(Qe().halfCommitment(c.half)),sealed:null,providerId:null,standIn:!0,mock:c}}else throw new d("bad-input",{field:"counterparty"});let s=[];if(i.proof||s.push("proof"),i.edPub||s.push("edPub"),i.commitHalfClaimer||s.push("commitHalfClaimer"),s.length)throw new d("bad-input",{field:"counterparty",missing:s});let a=i.sealed&&t&&t.enc?t.enc.priv:null;return{accepted:i,ownEncPriv:a}}async function Xu({context:e,side:t=null,counterparty:n=null,standIn:r=!1,options:o={}}){let i=n||r!==!0?null:await Qe().newSideChunked(e,!0,o),{accepted:s,ownEncPriv:a}=Y2({context:e,side:t,counterparty:n,standIn:r,mock:i}),c=null;try{c=await Qe().verifySideChunked({proof:s.proof,pub:{ed:s.edPub},commitHalfClaimer:s.commitHalfClaimer},e,s.sealed,a,o)}catch{throw new d("bad-input",{field:"counterparty"})}if(!c||c.ok!==!0)throw new d("quote-refused",{step:"proof",why:c&&c.reason?"rejected":"unknown"});return s}function G2({order:e,side:t,context:n}){return t?{context:n,side:t,spendPoint:me(t.pub&&t.pub.ed),viewPoint:me(t.viewPub),encPub:me(t.enc&&t.enc.pub?t.enc.pub:null)}:Wu(e)}function q2(e){let t=[];if((e.side.half===void 0||e.side.half===null)&&t.push("half"),(e.side.viewHalf===void 0||e.side.viewHalf===null)&&t.push("viewHalf"),Ku(e.spendPoint)||t.push("spendPoint"),Ku(e.viewPoint)||t.push("viewPoint"),t.length)throw new d("bad-input",{field:"side",missing:t})}function Q2({own:e,other:t,network:n}){let r=t.viewPoint||(t.viewHalf?me(Qe().pointOf(t.viewHalf)):null);if(!r)throw new d("bad-input",{field:"counterparty",missing:["viewPoint"]});let o=null;try{o=Qe().jointAddress({ownSpendHalf:e.side.half,ownViewHalf:e.side.viewHalf,otherSpendPoint:t.edPub,otherViewPoint:r,network:n})}catch{throw new d("bad-input",{field:"network"})}return{context:e.context,own:{spendPoint:e.spendPoint,viewPoint:e.viewPoint,encPub:e.encPub,proof:e.side.proof},side:e.side,counterparty:t,wallet:{spendHalf:Jt(e.side.half),viewHalf:Jt(e.side.viewHalf),otherSpendPoint:t.edPub,otherViewPoint:me(r),otherViewHalf:t.viewHalf?Jt(t.viewHalf):null,address:o.address,spendPub:me(o.spendPub),viewPub:me(o.viewPub),otherCommitHalf:t.commitHalfClaimer||null,commitHalfLocker:me(Qe().halfCommitment(e.side.half)),commitHalfClaimer:t.commitHalfClaimer||null,network:n||null}}}async function jy({order:e,side:t=null,counterparty:n=null,standIn:r=!1,network:o=null,options:i={}}){let s=_t(e),a=t?G2({order:e,side:t,context:s}):await X2(e,i);q2(a);let c=await Xu({context:a.context,side:a.side,counterparty:n,standIn:r,options:i});return Q2({own:a,other:c,network:o})}fe();fe();Ee();fe();Ee();var Z2="Ninsei Relay",J2="1",eE="EIP712Domain(string name,string version)",Vy="FirmWindow(string market,string side,string xmrNetwork,uint32 readyMinSeconds,uint32 readyMaxSeconds,uint32 settlementMinSeconds,uint32 settlementMaxSeconds,uint32 quoteTtlSeconds)",tE="NodeFeatures(string relayId,address provider,address quoteKey,address registry,bytes32 hpkeKey,FirmWindow[] firmWindows,uint64 time,bytes32 nonce)"+Vy,nE=[["market","string"],["side","string"],["xmrNetwork","string"],["readyMinSeconds","uint32"],["readyMaxSeconds","uint32"],["settlementMinSeconds","uint32"],["settlementMaxSeconds","uint32"],["quoteTtlSeconds","uint32"]],rE=[["relayId","string"],["provider","address"],["quoteKey","address"],["registry","address"],["hpkeKey","bytes32"],["firmWindows","FirmWindow[]"],["time","uint64"],["nonce","bytes32"]],Pn=(e,t)=>{if(typeof e=="string")return e;if(typeof e=="number"&&Number.isFinite(e)||typeof e=="bigint")return String(e);throw new d("bad-input",{field:t})},oE=(e,t)=>{let n=null;try{n=Number(e)}catch{n=null}if(!Number.isFinite(n))throw new d("bad-input",{field:t});return n},Jr=(e,t="text")=>new TextEncoder().encode(Pn(e,t)),eo=(...e)=>{let t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n},ga=(e,t,n)=>{let r=Pn(e??"",t).replace(/^0x/,"");if(!new RegExp("^[0-9a-fA-F]{"+n*2+"}$").test(r))throw new d("bad-input",{field:t});let o=new Uint8Array(n);for(let i=0;i<n;i+=1)o[i]=parseInt(r.slice(i*2,i*2+2),16);return o},$y=(e,t,n)=>{let r=null;try{r=BigInt(String(e??"").trim())}catch{r=null}if(r===null||r<0n||r>=1n<<BigInt(n))throw new d("bad-input",{field:t});let o=new Uint8Array(32);for(let i=31;i>=0&&r>0n;i-=1)o[i]=Number(r&0xffn),r>>=8n;return o},iE=(e,t)=>{let n=Pn(e??"",t).trim();if(!/^(0x)?[0-9a-fA-F]{40}$/.test(n))throw new d("bad-input",{field:t});let r=new Uint8Array(32);return r.set(ga(n,t,20),12),r},Yu=(e,t)=>Q(Jr(e??"",t)),Wy=(e,t,n)=>{if(!Array.isArray(e))throw new d("bad-input",{field:t});let r=e.map(o=>n(o));return Q(eo(...r))};function sE(e){if(!e||typeof e!="object")throw new d("bad-input",{field:"firmWindows"});let t=[Q(Jr(Vy))];for(let[n,r]of nE)t.push(r==="string"?Yu(e[n],"firmWindows."+n):$y(e[n],"firmWindows."+n,32));return Q(eo(...t))}function aE(e){if(!e||typeof e!="object")throw new d("bad-input",{field:"features"});let t=[Q(Jr(tE))];for(let[n,r]of rE)if(r==="string")t.push(Yu(e[n],"features."+n));else if(r==="address")t.push(iE(e[n],"features."+n));else if(r==="bytes32")t.push(ga(e[n],"features."+n,32));else if(r==="uint64")t.push($y(e[n],"features."+n,64));else if(r==="string[]")t.push(Wy(e[n],"features."+n,o=>Yu(o,"features."+n)));else if(r==="FirmWindow[]")t.push(Wy(e[n],"features."+n,sE));else throw new d("bad-input",{field:"features."+n});return Q(eo(...t))}function cE(){return Q(eo(Q(Jr(eE)),Q(Jr(Z2)),Q(Jr(J2))))}function lE(e){return Q(eo(Uint8Array.from([25,1]),cE(),aE(e)))}var Gu=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t};function uE(e,t){let n=Pn(t??"","signature").replace(/^0x/,"");if(!/^[0-9a-fA-F]{130}$/.test(n))return null;let r=parseInt(n.slice(128,130),16);if(r>=27&&(r-=27),r!==0&&r!==1)return null;try{let o=Ce.Signature.fromBytes(eo(ga(n.slice(0,64),"signature",32),ga(n.slice(64,128),"signature",32))).addRecoveryBit(r).recoverPublicKey(e);return Gu(Q(o.toBytes(!1).slice(1)).slice(12))}catch{return null}}function zy({features:e,terms:t=null}={}){if(!e||typeof e!="object")throw new d("bad-input",{field:"features"});if(e.type!=="node_features"||oE(e.version,"features.version")!==1)throw new d("quote-refused",{step:"features",why:"version"});let n=lE(e),r=uE(n,e.signature),o=Pn(e.quoteKey===void 0||e.quoteKey===null?"":e.quoteKey,"features.quoteKey").toLowerCase();if(r===null||r!==o)throw new d("quote-refused",{step:"features",why:"signature"});let i=Pn(e.hpkeKey===void 0||e.hpkeKey===null?"":e.hpkeKey,"features.hpkeKey").replace(/^0x/,"").toLowerCase();if(!/^[0-9a-f]{64}$/.test(i)||/^0+$/.test(i))throw new d("quote-refused",{step:"features",why:"hpke-key"});if(!Array.isArray(e.firmWindows)||e.firmWindows.length===0)throw new d("quote-refused",{step:"features",why:"windows"});if(t){if(Pn(e.provider===void 0||e.provider===null?"":e.provider,"features.provider").toLowerCase()!==String(t.maker||"").toLowerCase()||Pn(e.registry===void 0||e.registry===null?"":e.registry,"features.registry").toLowerCase()!==String(t.registry||"").toLowerCase())throw new d("quote-refused",{step:"features",why:"identity"});let s=String(t.market||""),a=String(t.side||""),c=String(t.xmrNetwork||""),l=e.firmWindows.find(u=>u&&u.market===s&&u.side===a&&u.xmrNetwork===c);if(!l)throw new d("quote-refused",{step:"features",why:"window"});return{featuresHash:Gu(n),hpkeKey:"0x"+i,window:l}}return{featuresHash:Gu(n),hpkeKey:"0x"+i,window:null}}var st=class extends Error{constructor(t){let n;t instanceof Error?n=t.message:typeof t=="string"?n=t:n="",super(n),this.name=this.constructor.name}},Xe=class extends st{};var to=class extends st{},sr=class extends st{},xa=class extends st{},ka=class extends st{},Sa=class extends st{},va=class extends st{},Ea=class extends st{},Aa=class extends st{},_a=class extends st{},Bn=class extends st{};var dE={},Xy=fE(globalThis,dE);function fE(e,t){return new Proxy(e,{get(n,r,o){return r in t?t[r]:e[r]},set(n,r,o){return r in t&&delete t[r],e[r]=o,!0},deleteProperty(n,r){let o=!1;return r in t&&(delete t[r],o=!0),r in e&&(delete e[r],o=!0),o},ownKeys(n){let r=Reflect.ownKeys(e),o=Reflect.ownKeys(t),i=new Set(o);return[...r.filter(s=>!i.has(s)),...o]},defineProperty(n,r,o){return r in t&&delete t[r],Reflect.defineProperty(e,r,o),!0},getOwnPropertyDescriptor(n,r){return r in t?Reflect.getOwnPropertyDescriptor(t,r):Reflect.getOwnPropertyDescriptor(e,r)},has(n,r){return r in t||r in e}})}async function hE(){if(Xy!==void 0&&globalThis.crypto!==void 0)return globalThis.crypto.subtle;try{let{webcrypto:e}=await Promise.resolve().then(()=>ug(Yy(),1));return e.subtle}catch(e){throw new Bn(e)}}var en=class{constructor(){Object.defineProperty(this,"_api",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}async _setup(){this._api===void 0&&(this._api=await hE())}};var Dt={Base:0,Psk:1,Auth:2,AuthPsk:3},Ia={NotAssigned:0,DhkemP256HkdfSha256:16,DhkemP384HkdfSha384:17,DhkemP521HkdfSha512:18,DhkemSecp256k1HkdfSha256:19,DhkemX25519HkdfSha256:32,DhkemX448HkdfSha512:33,HybridkemX25519Kyber768:48,MlKem512:64,MlKem768:65,MlKem1024:66,XWing:25722},Na={HkdfSha256:1,HkdfSha384:2,HkdfSha512:3,Sha3256:4,Sha3384:5,Sha3512:6,Shake128:16,Shake256:17,TurboShake128:18,TurboShake256:19},qu={Aes128Gcm:1,Aes256Gcm:2,Chacha20Poly1305:3,ExportOnly:65535};var Ne=new Uint8Array(0);var Gy=new Uint8Array([75,69,77,0,0]);var qy=new Uint8Array([72,80,75,69,45,118,49]);function no(e){return new Uint8Array(ke(e))}function ke(e){return e instanceof ArrayBuffer?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice().buffer:new Uint8Array(e).slice().buffer}var Qu=class extends en{constructor(t){super(),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:Na.HkdfSha256}),Object.defineProperty(this,"hashSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_suiteId",{enumerable:!0,configurable:!0,writable:!0,value:Ne}),Object.defineProperty(this,"algHash",{enumerable:!0,configurable:!0,writable:!0,value:{name:"HMAC",hash:"SHA-256",length:256}}),Object.defineProperty(this,"_fallbackExtract",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._fallbackExtract=t}init(t){this._suiteId=t}buildLabeledIkm(t,n){this._checkInit();let r=new Uint8Array(7+this._suiteId.byteLength+t.byteLength+n.byteLength);return r.set(qy,0),r.set(this._suiteId,7),r.set(t,7+this._suiteId.byteLength),r.set(n,7+this._suiteId.byteLength+t.byteLength),r}buildLabeledInfo(t,n,r){this._checkInit();let o=new Uint8Array(9+this._suiteId.byteLength+t.byteLength+n.byteLength);return o.set(new Uint8Array([0,r]),0),o.set(qy,2),o.set(this._suiteId,9),o.set(t,9+this._suiteId.byteLength),o.set(n,9+this._suiteId.byteLength+t.byteLength),o}async extract(t,n){await this._setup();let r=t.byteLength===0?new ArrayBuffer(this.hashSize):ke(t),o=ke(n);if(r.byteLength!==this.hashSize){if(this._fallbackExtract!==void 0)return this._fallbackExtract(new Uint8Array(r),new Uint8Array(o)).buffer;throw new Xe("The salt length must be the same as the hashSize")}let i=await this._api.importKey("raw",r,this.algHash,!1,["sign"]);return await this._api.sign("HMAC",i,o)}async expand(t,n,r){await this._setup();let o=ke(t),i=await this._api.importKey("raw",o,this.algHash,!1,["sign"]),s=new ArrayBuffer(r),a=new Uint8Array(s),c=Ne,l=no(n),u=new Uint8Array(1);if(r>255*this.hashSize)throw new Error("Entropy limit reached");let f=new Uint8Array(this.hashSize+l.length+1);for(let h=1,m=0;m<a.length;h++)u[0]=h,f.set(c,0),f.set(l,c.length),f.set(u,c.length+l.length),c=new Uint8Array(await this._api.sign("HMAC",i,f.slice(0,c.length+l.length+1))),a.length-m>=c.length?(a.set(c,m),m+=c.length):(a.set(c.slice(0,a.length-m),m),m+=a.length-m);return s}async extractAndExpand(t,n,r,o){await this._setup();let i=ke(n),s=await this._api.importKey("raw",i,"HKDF",!1,["deriveBits"]);return await this._api.deriveBits({name:"HKDF",hash:this.algHash.hash,salt:ke(t),info:ke(r)},s,o*8)}async labeledExtract(t,n,r){return await this.extract(t,this.buildLabeledIkm(n,r))}async labeledExpand(t,n,r,o){return await this.expand(t,this.buildLabeledInfo(n,r,o),o)}_checkInit(){if(this._suiteId===Ne)throw new Error("Not initialized. Call init()")}},ar=class extends Qu{constructor(){super(...arguments),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:Na.HkdfSha256}),Object.defineProperty(this,"hashSize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"algHash",{enumerable:!0,configurable:!0,writable:!0,value:{name:"HMAC",hash:"SHA-256",length:256}})}};var cr=e=>typeof e=="object"&&e!==null&&typeof e.privateKey=="object"&&typeof e.publicKey=="object";function tn(e,t){if(t<=0)throw new Error("i2Osp: too small size");if(e>=256**t)throw new Error("i2Osp: too large integer");let n=new Uint8Array(t);for(let r=0;r<t&&e;r++)n[t-(r+1)]=e%256,e=Math.floor(e/256);return n}function ro(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function Zu(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r}function Ju(e,t){if(e.byteLength!==t.byteLength)throw new Error("xor: different length inputs");let n=new Uint8Array(e.byteLength);for(let r=0;r<e.byteLength;r++)n[r]=e[r]^t[r];return n}var mE=new Uint8Array([101,97,101,95,112,114,107]),wE=new Uint8Array([115,104,97,114,101,100,95,115,101,99,114,101,116]);function yE(e,t,n){let r=new Uint8Array(e.length+t.length+n.length);return r.set(e,0),r.set(t,e.length),r.set(n,e.length+t.length),r}var di=class{constructor(t,n,r){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"secretSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"encSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"publicKeySize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"privateKeySize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_prim",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.id=t,this._prim=n,this._kdf=r;let o=new Uint8Array(Gy);o.set(tn(this.id,2),3),this._kdf.init(o)}async serializePublicKey(t){return await this._prim.serializePublicKey(t)}async deserializePublicKey(t){return await this._prim.deserializePublicKey(ke(t))}async serializePrivateKey(t){return await this._prim.serializePrivateKey(t)}async deserializePrivateKey(t){return await this._prim.deserializePrivateKey(ke(t))}async importKey(t,n,r=!0){return await this._prim.importKey(t,n,r)}async generateKeyPair(){return await this._prim.generateKeyPair()}async deriveKeyPair(t){let n=ke(t);if(n.byteLength>8192)throw new Xe("Too long ikm");return await this._prim.deriveKeyPair(n)}async encap(t){let n;t.ekm===void 0?n=await this.generateKeyPair():cr(t.ekm)?n=t.ekm:n=await this.deriveKeyPair(t.ekm);let r=await this._prim.serializePublicKey(n.publicKey),o=await this._prim.serializePublicKey(t.recipientPublicKey);try{let i;if(t.senderKey===void 0)i=new Uint8Array(await this._prim.dh(n.privateKey,t.recipientPublicKey));else{let c=cr(t.senderKey)?t.senderKey.privateKey:t.senderKey,l=new Uint8Array(await this._prim.dh(n.privateKey,t.recipientPublicKey)),u=new Uint8Array(await this._prim.dh(c,t.recipientPublicKey));i=ro(l,u)}let s;if(t.senderKey===void 0)s=ro(new Uint8Array(r),new Uint8Array(o));else{let c=cr(t.senderKey)?t.senderKey.publicKey:await this._prim.derivePublicKey(t.senderKey),l=await this._prim.serializePublicKey(c);s=yE(new Uint8Array(r),new Uint8Array(o),new Uint8Array(l))}let a=await this._generateSharedSecret(i,s);return{enc:r,sharedSecret:a}}catch(i){throw new xa(i)}}async decap(t){let n=ke(t.enc),r=await this._prim.deserializePublicKey(n),o=cr(t.recipientKey)?t.recipientKey.privateKey:t.recipientKey,i=cr(t.recipientKey)?t.recipientKey.publicKey:await this._prim.derivePublicKey(t.recipientKey),s=await this._prim.serializePublicKey(i);try{let a;if(t.senderPublicKey===void 0)a=new Uint8Array(await this._prim.dh(o,r));else{let l=new Uint8Array(await this._prim.dh(o,r)),u=new Uint8Array(await this._prim.dh(o,t.senderPublicKey));a=ro(l,u)}let c;if(t.senderPublicKey===void 0)c=ro(new Uint8Array(n),new Uint8Array(s));else{let l=await this._prim.serializePublicKey(t.senderPublicKey);c=new Uint8Array(n.byteLength+s.byteLength+l.byteLength),c.set(new Uint8Array(n),0),c.set(new Uint8Array(s),n.byteLength),c.set(new Uint8Array(l),n.byteLength+s.byteLength)}return await this._generateSharedSecret(a,c)}catch(a){throw new ka(a)}}async _generateSharedSecret(t,n){let r=this._kdf.buildLabeledIkm(mE,t),o=this._kdf.buildLabeledInfo(wE,n,this.secretSize);return await this._kdf.extractAndExpand(Ne,r,o,this.secretSize)}};var fi=["deriveBits"],ed=new Uint8Array([100,107,112,95,112,114,107]),td=new Uint8Array([115,107]);function rd(){return new Promise((e,t)=>{t(new Bn("Not supported"))})}var xE=new Uint8Array([115,101,99]),oo=class{constructor(t,n,r){Object.defineProperty(this,"_api",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exporterSecret",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._api=t,this._kdf=n,this.exporterSecret=r}async seal(t,n){return await rd()}async open(t,n){return await rd()}async export(t,n){let r=ke(t);if(r.byteLength>8192)throw new Xe("Too long exporter context");try{return await this._kdf.labeledExpand(this.exporterSecret,xE,new Uint8Array(r),n)}catch(o){throw new Sa(o)}}},Ta=class extends oo{},Pa=class extends oo{constructor(t,n,r,o){super(t,n,r),Object.defineProperty(this,"enc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.enc=o}};var io=class extends oo{constructor(t,n,r){if(super(t,n,r.exporterSecret),Object.defineProperty(this,"_aead",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nK",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nN",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nT",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ctx",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.key===void 0||r.baseNonce===void 0||r.seq===void 0)throw new Error("Required parameters are missing");this._aead=r.aead,this._nK=this._aead.keySize,this._nN=this._aead.nonceSize,this._nT=this._aead.tagSize;let o=this._aead.createEncryptionContext(r.key);this._ctx={key:o,baseNonce:r.baseNonce,seq:r.seq}}computeNonce(t){let n=tn(t.seq,t.baseNonce.byteLength);return Ju(t.baseNonce,n).buffer}incrementSeq(t){if(t.seq>Number.MAX_SAFE_INTEGER)throw new Aa("Message limit reached");t.seq+=1}};var kE=function(e,t,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(e):r?r.value:t.get(e)},SE=function(e,t,n,r,o){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(e,n):o?o.value=n:t.set(e,n),n},Ba,so=class{constructor(){Ba.set(this,Promise.resolve())}async lock(){let t,n=new Promise(o=>{t=o}),r=kE(this,Ba,"f");return SE(this,Ba,n,"f"),await r,t}};Ba=new WeakMap;var Zy=function(e,t,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(e):r?r.value:t.get(e)},vE=function(e,t,n,r,o){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(e,n):o?o.value=n:t.set(e,n),n},pi,Oa=class extends io{constructor(){super(...arguments),pi.set(this,void 0)}async open(t,n=Ne.buffer){vE(this,pi,Zy(this,pi,"f")??new so,"f");let r=await Zy(this,pi,"f").lock(),o;try{o=await this._ctx.key.open(this.computeNonce(this._ctx),ke(t),ke(n))}catch(i){throw new Ea(i)}finally{r()}return this.incrementSeq(this._ctx),o}};pi=new WeakMap;var Jy=function(e,t,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(e):r?r.value:t.get(e)},EE=function(e,t,n,r,o){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(e,n):o?o.value=n:t.set(e,n),n},hi,Ca=class extends io{constructor(t,n,r,o){super(t,n,r),Object.defineProperty(this,"enc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),hi.set(this,void 0),this.enc=o}async seal(t,n=Ne.buffer){EE(this,hi,Jy(this,hi,"f")??new so,"f");let r=await Jy(this,hi,"f").lock(),o;try{o=await this._ctx.key.seal(this.computeNonce(this._ctx),ke(t),ke(n))}catch(i){throw new va(i)}finally{r()}return this.incrementSeq(this._ctx),o}};hi=new WeakMap;var AE=new Uint8Array([98,97,115,101,95,110,111,110,99,101]),_E=new Uint8Array([101,120,112]),IE=new Uint8Array([105,110,102,111,95,104,97,115,104]),NE=new Uint8Array([107,101,121]),TE=new Uint8Array([112,115,107,95,105,100,95,104,97,115,104]),PE=new Uint8Array([115,101,99,114,101,116]),BE=new Uint8Array([72,80,75,69,0,0,0,0,0,0]),Ra=class extends en{constructor(t){if(super(),Object.defineProperty(this,"_kem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_aead",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_suiteId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof t.kem=="number")throw new Xe("KemId cannot be used");if(this._kem=t.kem,typeof t.kdf=="number")throw new Xe("KdfId cannot be used");if(this._kdf=t.kdf,typeof t.aead=="number")throw new Xe("AeadId cannot be used");this._aead=t.aead,this._suiteId=new Uint8Array(BE),this._suiteId.set(tn(this._kem.id,2),4),this._suiteId.set(tn(this._kdf.id,2),6),this._suiteId.set(tn(this._aead.id,2),8),this._kdf.init(this._suiteId)}get kem(){return this._kem}get kdf(){return this._kdf}get aead(){return this._aead}async createSenderContext(t){this._validateInputLength(t),await this._setup();let n=await this._kem.encap(t),r;return t.psk!==void 0?r=t.senderKey!==void 0?Dt.AuthPsk:Dt.Psk:r=t.senderKey!==void 0?Dt.Auth:Dt.Base,await this._keyScheduleS(r,n.sharedSecret,n.enc,t)}async createRecipientContext(t){this._validateInputLength(t),await this._setup();let n=await this._kem.decap(t),r;return t.psk!==void 0?r=t.senderPublicKey!==void 0?Dt.AuthPsk:Dt.Psk:r=t.senderPublicKey!==void 0?Dt.Auth:Dt.Base,await this._keyScheduleR(r,n,t)}async seal(t,n,r=Ne.buffer){let o=await this.createSenderContext(t);return{ct:await o.seal(n,r),enc:o.enc}}async open(t,n,r=Ne.buffer){return await(await this.createRecipientContext(t)).open(n,r)}async _keySchedule(t,n,r){let o=r.psk===void 0?Ne:no(r.psk.id),i=await this._kdf.labeledExtract(Ne,TE,o),s=r.info===void 0?Ne:no(r.info),a=await this._kdf.labeledExtract(Ne,IE,s),c=new Uint8Array(1+i.byteLength+a.byteLength);c.set(new Uint8Array([t]),0),c.set(new Uint8Array(i),1),c.set(new Uint8Array(a),1+i.byteLength);let l=r.psk===void 0?Ne:no(r.psk.key),u=this._kdf.buildLabeledIkm(PE,l),f=this._kdf.buildLabeledInfo(_E,c,this._kdf.hashSize),h=await this._kdf.extractAndExpand(n,u,f,this._kdf.hashSize);if(this._aead.id===qu.ExportOnly)return{aead:this._aead,exporterSecret:h};let m=this._kdf.buildLabeledInfo(NE,c,this._aead.keySize),w=await this._kdf.extractAndExpand(n,u,m,this._aead.keySize),x=this._kdf.buildLabeledInfo(AE,c,this._aead.nonceSize),y=await this._kdf.extractAndExpand(n,u,x,this._aead.nonceSize);return{aead:this._aead,exporterSecret:h,key:w,baseNonce:new Uint8Array(y),seq:0}}async _keyScheduleS(t,n,r,o){let i=await this._keySchedule(t,n,o);return i.key===void 0?new Pa(this._api,this._kdf,i.exporterSecret,r):new Ca(this._api,this._kdf,i,r)}async _keyScheduleR(t,n,r){let o=await this._keySchedule(t,n,r);return o.key===void 0?new Ta(this._api,this._kdf,o.exporterSecret):new Oa(this._api,this._kdf,o)}_validateInputLength(t){if(t.info!==void 0&&t.info.byteLength>268435456)throw new Xe("Too long info");if(t.psk!==void 0){if(t.psk.key.byteLength<32)throw new Xe(`PSK must have at least ${32} bytes`);if(t.psk.key.byteLength>8192)throw new Xe("Too long psk.key");if(t.psk.id.byteLength>8192)throw new Xe("Too long psk.id")}}};var mi=class extends Ra{};var wi=class extends ar{};var Ha=class extends en{constructor(t,n,r,o,i){super(),Object.defineProperty(this,"_hkdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_alg",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nPk",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nSk",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nDh",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pkcs8AlgId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_algName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_basePoint",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._algName=t,this._alg={name:t},this._hkdf=i,this._nPk=n,this._nSk=n,this._nDh=n,this._pkcs8AlgId=r,this._basePoint=o}async serializePublicKey(t){await this._setup();try{return await this._api.exportKey("raw",t)}catch(n){throw new to(n)}}async deserializePublicKey(t){await this._setup();try{return await this._importRawKey(ke(t),!0)}catch(n){throw new sr(n)}}async serializePrivateKey(t){await this._setup();try{let n=await this._api.exportKey("jwk",t);if(!("d"in n))throw new Error("Not private key");return Zu(n.d).buffer}catch(n){throw new to(n)}}async deserializePrivateKey(t){await this._setup();try{return await this._importRawKey(ke(t),!1)}catch(n){throw new sr(n)}}async importKey(t,n,r){await this._setup();try{if(t==="raw")return await this._importRawKey(n,r);if(n instanceof ArrayBuffer)throw new Error("Invalid jwk key format");return await this._importJWK(n,r)}catch(o){throw new sr(o)}}async generateKeyPair(){await this._setup();try{return await this._api.generateKey(this._algName,!0,fi)}catch(t){throw new Bn(t)}}async deriveKeyPair(t){await this._setup();try{let n=ke(t),r=await this._hkdf.labeledExtract(Ne,ed,new Uint8Array(n)),o=await this._hkdf.labeledExpand(r,td,Ne,this._nSk),i=new Uint8Array(o),s=await this._deserializePkcs8Key(i);return i.fill(0),{privateKey:s,publicKey:await this.derivePublicKey(s)}}catch(n){throw new _a(n)}}async derivePublicKey(t){await this._setup();try{let n=await this._api.exportKey("jwk",t);return delete n.d,delete n.key_ops,await this._api.importKey("jwk",n,this._alg,!0,[])}catch{try{let n=await this._api.importKey("raw",this._basePoint.buffer,this._alg,!0,[]),r=await this._api.deriveBits({name:this._algName,public:n},t,this._nPk*8);return await this._api.importKey("raw",r,this._alg,!0,[])}catch(n){throw new sr(n)}}}async dh(t,n){await this._setup();try{return await this._api.deriveBits({name:this._algName,public:n},t,this._nDh*8)}catch(r){throw new to(r)}}async _importRawKey(t,n){if(n&&t.byteLength!==this._nPk)throw new Error("Invalid public key for the ciphersuite");if(!n&&t.byteLength!==this._nSk)throw new Error("Invalid private key for the ciphersuite");return n?await this._api.importKey("raw",t,this._alg,!0,[]):await this._deserializePkcs8Key(new Uint8Array(t))}async _importJWK(t,n){if(typeof t.kty>"u"||t.kty!=="OKP")throw new Error(`Invalid kty: ${t.crv}`);if(typeof t.crv>"u"||t.crv!==this._algName)throw new Error(`Invalid crv: ${t.crv}`);if(n){if(typeof t.d<"u")throw new Error("Invalid key: `d` should not be set");return await this._api.importKey("jwk",t,this._alg,!0,[])}if(typeof t.d>"u")throw new Error("Invalid key: `d` not found");return await this._api.importKey("jwk",t,this._alg,!0,fi)}async _deserializePkcs8Key(t){let n=new Uint8Array(this._pkcs8AlgId.length+t.length);return n.set(this._pkcs8AlgId,0),n.set(t,this._pkcs8AlgId.length),await this._api.importKey("pkcs8",n,this._alg,!0,fi)}};var OE=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),CE=(()=>{let e=new Uint8Array(32);return e[0]=9,e})(),La=class extends Ha{constructor(t){super("X25519",32,OE,CE,t)}};var yi=class extends di{constructor(){let t=new ar;super(Ia.DhkemX25519HkdfSha256,new La(t),t),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:Ia.DhkemX25519HkdfSha256}),Object.defineProperty(this,"secretSize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"encSize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"publicKeySize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"privateKeySize",{enumerable:!0,configurable:!0,writable:!0,value:32})}};var RE={},e0=HE(globalThis,RE);function HE(e,t){return new Proxy(e,{get(n,r,o){return r in t?t[r]:e[r]},set(n,r,o){return r in t&&delete t[r],e[r]=o,!0},deleteProperty(n,r){let o=!1;return r in t&&(delete t[r],o=!0),r in e&&(delete e[r],o=!0),o},ownKeys(n){let r=Reflect.ownKeys(e),o=Reflect.ownKeys(t),i=new Set(o);return[...r.filter(s=>!i.has(s)),...o]},defineProperty(n,r,o){return r in t&&delete t[r],Reflect.defineProperty(e,r,o),!0},getOwnPropertyDescriptor(n,r){return r in t?Reflect.getOwnPropertyDescriptor(t,r):Reflect.getOwnPropertyDescriptor(e,r)},has(n,r){return r in t||r in e}})}var id={Aes128Gcm:1,Aes256Gcm:2,Chacha20Poly1305:3,ExportOnly:65535};var Fa=0n;function at(e){return e instanceof ArrayBuffer?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice().buffer:new Uint8Array(e).slice().buffer}var AN={p:(1n<<521n)-1n,b:0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00n,gx:0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66n,gy:0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650n,coordinateSize:66};function ME(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function It(e,t=""){if(!Number.isSafeInteger(e)||e<0){let n=t&&`"${t}" `;throw new Error(`${n}expected integer >0, got ${e}`)}}function ge(e,t,n=""){let r=ME(e),o=e?.length,i=t!==void 0;if(!r||i&&o!==t){let s=n&&`"${n}" `,a=i?` of length ${t}`:"",c=r?`length=${o}`:`type=${typeof e}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return e}function Ut(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function ao(e,t){ge(e,void 0,"digestInto() output");let n=t.outputLen;if(e.length<n)throw new Error('"digestInto() output" expected to be of length >='+n)}function bt(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Ye(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}var KE=new Uint32Array([287454020]),jE=new Uint8Array(KE.buffer),ld=jE[0]===68;function Da(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function gi(e){It(e,"numberToBigint");let t=e,n=Fa,r=1n;for(;t>0;)t%2===1&&(n+=r),t=Math.floor(t/2),r<<=1n;return n}function nn(e){return Uint8Array.from(e)}function p0(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash must wrapped by utils.createHasher");It(e.outputLen),It(e.blockLen)}var Ua=class{constructor(t,n){if(Object.defineProperty(this,"oHash",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"iHash",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockLen",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputLen",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"finished",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),p0(t),ge(n,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?t.create().update(n).digest():n);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=t.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Ye(o)}update(t){return Ut(this),this.iHash.update(t),this}digestInto(t){Ut(this),ge(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:n,iHash:r,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},h0=(e,t,n)=>new Ua(e,t).update(n).digest();h0.create=(e,t)=>new Ua(e,t);var Ma=0xffffffffn,m0=32n;function WE(e,t=!1){return t?{h:Number(e&Ma),l:Number(e>>m0&Ma)}:{h:Number(e>>m0&Ma)|0,l:Number(e&Ma)|0}}function ud(e,t=!1){let n=e.length,r=new Uint32Array(n),o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=WE(e[i],t);[r[i],o[i]]=[s,a]}return[r,o]}var XE=0n,xi=1n,YE=2n,GE=7n,qE=256n,QE=0x71n,ZE=[],JE=[],w0=[];for(let e=0,t=xi,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],ZE.push(2*(5*r+n)),JE.push((e+1)*(e+2)/2%64);let o=XE;for(let i=0;i<7;i++)t=(t<<xi^(t>>GE)*QE)%qE,t&YE&&(o^=xi<<(xi<<BigInt(i))-xi);w0.push(o)}var y0=ud(w0,!0),CT=y0[0],RT=y0[1];function Ka(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}var b0=(e,t)=>{function n(r,...o){if(ge(r,void 0,"key"),!ld)throw new Error("Non little-endian hardware is not yet supported");if(e.nonceLength!==void 0){let u=o[0];ge(u,e.varSizeNonce?void 0:e.nonceLength,"nonce")}let i=e.tagLength;i&&o[1]!==void 0&&ge(o[1],void 0,"AAD");let s=t(r,...o),a=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");ge(f,void 0,"output")}},c=!1;return{encrypt(u,f){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,ge(u),a(s.encrypt.length,f),s.encrypt(u,f)},decrypt(u,f){if(ge(u),i&&u.length<i)throw new Error('"ciphertext" expected length bigger than tagLength='+i);return a(s.decrypt.length,f),s.decrypt(u,f)}}}return Object.assign(n,e),n};function g0(e,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(e,t)}function x0(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function dd(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(t.length!==e)throw new Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(n&&!tA(t))throw new Error("invalid output, must be aligned");return t}function k0(e,t,n){Ka(n);let r=new Uint8Array(16),o=Da(r);return o.setBigUint64(0,gi(t),n),o.setBigUint64(8,gi(e),n),r}function tA(e){return e.byteOffset%4===0}var v0=e=>Uint8Array.from(e.split("").map(t=>t.charCodeAt(0))),nA=v0("expand 16-byte k"),rA=v0("expand 32-byte k"),oA=bt(nA),iA=bt(rA);function de(e,t){return e<<t|e>>>32-t}function fd(e){return e.byteOffset%4===0}var ja=64,sA=16,E0=2**32-1,S0=Uint32Array.of();function aA(e,t,n,r,o,i,s,a){let c=o.length,l=new Uint8Array(ja),u=bt(l),f=fd(o)&&fd(i),h=f?bt(o):S0,m=f?bt(i):S0;for(let w=0;w<c;s++){if(e(t,n,r,u,s,a),s>=E0)throw new Error("arx: counter overflow");let x=Math.min(ja,c-w);if(f&&x===ja){let y=w/4;if(w%4!==0)throw new Error("arx: invalid block position");for(let k=0,I;k<sA;k++)I=y+k,m[I]=h[I]^u[k];w+=ja;continue}for(let y=0,k;y<x;y++)k=w+y,i[k]=o[k]^l[y];w+=x}}function A0(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:o,counterRight:i,rounds:s}=g0({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return It(o),It(s),Ka(i),Ka(n),(a,c,l,u,f=0)=>{ge(a,void 0,"key"),ge(c,void 0,"nonce"),ge(l,void 0,"data");let h=l.length;if(u===void 0&&(u=new Uint8Array(h)),ge(u,void 0,"output"),It(f),f<0||f>=E0)throw new Error("arx: counter overflow");if(u.length<h)throw new Error(`arx: output (${u.length}) is shorter than data (${h})`);let m=[],w=a.length,x,y;if(w===32)m.push(x=nn(a)),y=iA;else if(w===16&&n)x=new Uint8Array(32),x.set(a),x.set(a,16),y=oA,m.push(x);else throw ge(a,32,"arx key"),new Error("invalid key size");fd(c)||m.push(c=nn(c));let k=bt(x);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(y,k,bt(c.subarray(0,16)),k),c=c.subarray(16)}let I=16-o;if(I!==c.length)throw new Error(`arx: nonce must be ${I} or 16 bytes`);if(I!==12){let P=new Uint8Array(12);P.set(c,i?0:12-c.length),c=P,m.push(c)}let g=bt(c);return aA(e,y,k,g,l,u,f,s),Ye(...m),u}}function Ve(e,t){return e[t++]&255|(e[t++]&255)<<8}var pd=class{constructor(t){Object.defineProperty(this,"blockLen",{enumerable:!0,configurable:!0,writable:!0,value:16}),Object.defineProperty(this,"outputLen",{enumerable:!0,configurable:!0,writable:!0,value:16}),Object.defineProperty(this,"buffer",{enumerable:!0,configurable:!0,writable:!0,value:new Uint8Array(16)}),Object.defineProperty(this,"r",{enumerable:!0,configurable:!0,writable:!0,value:new Uint16Array(10)}),Object.defineProperty(this,"h",{enumerable:!0,configurable:!0,writable:!0,value:new Uint16Array(10)}),Object.defineProperty(this,"pad",{enumerable:!0,configurable:!0,writable:!0,value:new Uint16Array(8)}),Object.defineProperty(this,"pos",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"finished",{enumerable:!0,configurable:!0,writable:!0,value:!1}),t=nn(ge(t,32,"key"));let n=Ve(t,0),r=Ve(t,2),o=Ve(t,4),i=Ve(t,6),s=Ve(t,8),a=Ve(t,10),c=Ve(t,12),l=Ve(t,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|i<<9)&8191,this.r[4]=(i>>>4|s<<12)&255,this.r[5]=s>>>1&8190,this.r[6]=(s>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Ve(t,16+2*u)}process(t,n,r=!1){let o=r?0:2048,{h:i,r:s}=this,a=s[0],c=s[1],l=s[2],u=s[3],f=s[4],h=s[5],m=s[6],w=s[7],x=s[8],y=s[9],k=Ve(t,n+0),I=Ve(t,n+2),g=Ve(t,n+4),P=Ve(t,n+6),E=Ve(t,n+8),B=Ve(t,n+10),p=Ve(t,n+12),b=Ve(t,n+14),S=i[0]+(k&8191),v=i[1]+((k>>>13|I<<3)&8191),H=i[2]+((I>>>10|g<<6)&8191),A=i[3]+((g>>>7|P<<9)&8191),O=i[4]+((P>>>4|E<<12)&8191),D=i[5]+(E>>>1&8191),L=i[6]+((E>>>14|B<<2)&8191),V=i[7]+((B>>>11|p<<5)&8191),U=i[8]+((p>>>8|b<<8)&8191),j=i[9]+(b>>>5|o),F=0,R=F+S*a+v*(5*y)+H*(5*x)+A*(5*w)+O*(5*m);F=R>>>13,R&=8191,R+=D*(5*h)+L*(5*f)+V*(5*u)+U*(5*l)+j*(5*c),F+=R>>>13,R&=8191;let _=F+S*c+v*a+H*(5*y)+A*(5*x)+O*(5*w);F=_>>>13,_&=8191,_+=D*(5*m)+L*(5*h)+V*(5*f)+U*(5*u)+j*(5*l),F+=_>>>13,_&=8191;let N=F+S*l+v*c+H*a+A*(5*y)+O*(5*x);F=N>>>13,N&=8191,N+=D*(5*w)+L*(5*m)+V*(5*h)+U*(5*f)+j*(5*u),F+=N>>>13,N&=8191;let W=F+S*u+v*l+H*c+A*a+O*(5*y);F=W>>>13,W&=8191,W+=D*(5*x)+L*(5*w)+V*(5*m)+U*(5*h)+j*(5*f),F+=W>>>13,W&=8191;let $=F+S*f+v*u+H*l+A*c+O*a;F=$>>>13,$&=8191,$+=D*(5*y)+L*(5*x)+V*(5*w)+U*(5*m)+j*(5*h),F+=$>>>13,$&=8191;let X=F+S*h+v*f+H*u+A*l+O*c;F=X>>>13,X&=8191,X+=D*a+L*(5*y)+V*(5*x)+U*(5*w)+j*(5*m),F+=X>>>13,X&=8191;let Y=F+S*m+v*h+H*f+A*u+O*l;F=Y>>>13,Y&=8191,Y+=D*c+L*a+V*(5*y)+U*(5*x)+j*(5*w),F+=Y>>>13,Y&=8191;let G=F+S*w+v*m+H*h+A*f+O*u;F=G>>>13,G&=8191,G+=D*l+L*c+V*a+U*(5*y)+j*(5*x),F+=G>>>13,G&=8191;let Z=F+S*x+v*w+H*m+A*h+O*f;F=Z>>>13,Z&=8191,Z+=D*u+L*l+V*c+U*a+j*(5*y),F+=Z>>>13,Z&=8191;let ne=F+S*y+v*x+H*w+A*m+O*h;F=ne>>>13,ne&=8191,ne+=D*f+L*u+V*l+U*c+j*a,F+=ne>>>13,ne&=8191,F=(F<<2)+F|0,F=F+R|0,R=F&8191,F=F>>>13,_+=F,i[0]=R,i[1]=_,i[2]=N,i[3]=W,i[4]=$,i[5]=X,i[6]=Y,i[7]=G,i[8]=Z,i[9]=ne}finalize(){let{h:t,pad:n}=this,r=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,r[0]=t[0]+5,o=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=t[a]+o,o=r[a]>>>13,r[a]&=8191;r[9]-=8192;let i=(o^1)-1;for(let a=0;a<10;a++)r[a]&=i;i=~i;for(let a=0;a<10;a++)t[a]=t[a]&i|r[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let s=t[0]+n[0];t[0]=s&65535;for(let a=1;a<8;a++)s=(t[a]+n[a]|0)+(s>>>16)|0,t[a]=s&65535;Ye(r)}update(t){Ut(this),ge(t),t=nn(t);let{buffer:n,blockLen:r}=this,o=t.length;for(let i=0;i<o;){let s=Math.min(r-this.pos,o-i);if(s===r){for(;r<=o-i;i+=r)this.process(t,i);continue}n.set(t.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){Ye(this.h,this.r,this.buffer,this.pad)}digestInto(t){Ut(this),ao(t,this),this.finished=!0;let{buffer:n,h:r}=this,{pos:o}=this;if(o){for(n[o++]=1;o<16;o++)n[o]=0;this.process(n,0,!0)}this.finalize();let i=0;for(let s=0;s<8;s++)t[i++]=r[s]>>>0,t[i++]=r[s]>>>8;return t}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}};function cA(e){let t=(r,o)=>e(o).update(r).digest(),n=e(new Uint8Array(32));return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>e(r),t}var _0=cA(e=>new pd(e));function lA(e,t,n,r,o,i=20){let s=e[0],a=e[1],c=e[2],l=e[3],u=t[0],f=t[1],h=t[2],m=t[3],w=t[4],x=t[5],y=t[6],k=t[7],I=o,g=n[0],P=n[1],E=n[2],B=s,p=a,b=c,S=l,v=u,H=f,A=h,O=m,D=w,L=x,V=y,U=k,j=I,F=g,R=P,_=E;for(let W=0;W<i;W+=2)B=B+v|0,j=de(j^B,16),D=D+j|0,v=de(v^D,12),B=B+v|0,j=de(j^B,8),D=D+j|0,v=de(v^D,7),p=p+H|0,F=de(F^p,16),L=L+F|0,H=de(H^L,12),p=p+H|0,F=de(F^p,8),L=L+F|0,H=de(H^L,7),b=b+A|0,R=de(R^b,16),V=V+R|0,A=de(A^V,12),b=b+A|0,R=de(R^b,8),V=V+R|0,A=de(A^V,7),S=S+O|0,_=de(_^S,16),U=U+_|0,O=de(O^U,12),S=S+O|0,_=de(_^S,8),U=U+_|0,O=de(O^U,7),B=B+H|0,_=de(_^B,16),V=V+_|0,H=de(H^V,12),B=B+H|0,_=de(_^B,8),V=V+_|0,H=de(H^V,7),p=p+A|0,j=de(j^p,16),U=U+j|0,A=de(A^U,12),p=p+A|0,j=de(j^p,8),U=U+j|0,A=de(A^U,7),b=b+O|0,F=de(F^b,16),D=D+F|0,O=de(O^D,12),b=b+O|0,F=de(F^b,8),D=D+F|0,O=de(O^D,7),S=S+v|0,R=de(R^S,16),L=L+R|0,v=de(v^L,12),S=S+v|0,R=de(R^S,8),L=L+R|0,v=de(v^L,7);let N=0;r[N++]=s+B|0,r[N++]=a+p|0,r[N++]=c+b|0,r[N++]=l+S|0,r[N++]=u+v|0,r[N++]=f+H|0,r[N++]=h+A|0,r[N++]=m+O|0,r[N++]=w+D|0,r[N++]=x+L|0,r[N++]=y+V|0,r[N++]=k+U|0,r[N++]=I+j|0,r[N++]=g+F|0,r[N++]=P+R|0,r[N++]=E+_|0}var uA=A0(lA,{counterRight:!1,counterLength:4,allowShortKeys:!1}),dA=new Uint8Array(16),I0=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(dA.subarray(n))},fA=new Uint8Array(32);function N0(e,t,n,r,o){o!==void 0&&ge(o,void 0,"AAD");let i=e(t,n,fA),s=k0(r.length,o?o.length:0,!0),a=_0.create(i);o&&I0(a,o),I0(a,r),a.update(s);let c=a.digest();return Ye(i,s),c}var pA=e=>(t,n,r)=>({encrypt(i,s){let a=i.length;s=dd(a+16,s,!1),s.set(i);let c=s.subarray(0,-16);e(t,n,c,c,1);let l=N0(e,t,n,c,r);return s.set(l,a),Ye(l),s},decrypt(i,s){s=dd(i.length-16,s,!1);let a=i.subarray(0,-16),c=i.subarray(-16),l=N0(e,t,n,a,r);if(!x0(c,l))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),e(t,n,s,s,1),Ye(l),s}}),hd=b0({blockSize:64,nonceLength:12,tagLength:16},pA(uA));var md=class{constructor(t){Object.defineProperty(this,"_key",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._key=new Uint8Array(at(t))}async seal(t,n,r){return await this._seal(at(t),at(n),at(r))}async open(t,n,r){return await this._open(at(t),at(n),at(r))}_seal(t,n,r){return new Promise(o=>{let i=hd(this._key,new Uint8Array(t),new Uint8Array(r)).encrypt(new Uint8Array(n));o(i.buffer)})}_open(t,n,r){return new Promise(o=>{let i=hd(this._key,new Uint8Array(t),new Uint8Array(r)).decrypt(new Uint8Array(n));o(i.buffer)})}},ki=class{constructor(){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:id.Chacha20Poly1305}),Object.defineProperty(this,"keySize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"nonceSize",{enumerable:!0,configurable:!0,writable:!0,value:12}),Object.defineProperty(this,"tagSize",{enumerable:!0,configurable:!0,writable:!0,value:16})}createEncryptionContext(t){return new md(t)}};fe();var hA=e=>new TextEncoder().encode(String(e)),wd=e=>{if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);throw new d("bad-input",{field:"viewEnvelope"})},T0=e=>{let t="0x";for(let n of wd(e))t+=n.toString(16).padStart(2,"0");return t},P0=(e,t,n)=>{let r=String(e??"").replace(/^0x/,"");if(!new RegExp("^[0-9a-fA-F]{"+t*2+"}$").test(r))throw new d("bad-input",{field:n});let o=new Uint8Array(t);for(let i=0;i<t;i+=1)o[i]=parseInt(r.slice(i*2,i*2+2),16);return o},mA=()=>new mi({kem:new yi,kdf:new wi,aead:new ki}),wA="ninsei-relay-view-v1";function B0({termsDigest:e,commitHalf:t,edPoint:n,edViewPointClient:r,edViewPointNode:o}={}){let i=[["termsDigest",e],["commitHalf",t],["edPoint",n],["edViewPointClient",r],["edViewPointNode",o]].map(([l,u])=>P0(u,32,l)),s=hA(wA),a=new Uint8Array(s.length+i.reduce((l,u)=>l+u.length,0));a.set(s,0);let c=s.length;for(let l of i)a.set(l,c),c+=l.length;return a}async function O0({hpkeKey:e,info:t,plaintext:n}={}){let r=P0(e,32,"hpkeKey"),o=wd(n);if(o.length!==32&&o.length!==64)throw new d("bad-input",{field:"plaintext"});if(!(t instanceof Uint8Array))throw new d("bad-input",{field:"info"});let i=mA(),s=null;try{s=await i.kem.deserializePublicKey(r);let a=await i.createSenderContext({recipientPublicKey:s,info:t}),c=wd(await a.seal(o));return{enc:T0(a.enc),ciphertext:T0(c)}}catch(a){throw a instanceof d?a:new d("bad-input",{field:"hpkeKey"})}}fe();var yA="Ninsei Relay",bA="1",gA=["EIP712Domain(","string name,","string version)"],xA=gA.join(""),yd=[["chainId","uint256"],["factory","address"],["locker","address"],["claimer","address"],["amount","uint256"],["readyBy","uint64"],["t1","uint64"],["salt","bytes32"]],R0="FirmOrder("+yd.map(([e,t])=>t+" "+e).join(",")+")",bd=[["market","string"],["side","string"],["maker","address"],["registry","address"],["featuresHash","bytes32"],["xmrNetwork","string"],["order","FirmOrder"],["xmrAmount","uint256"],["claimTip","uint256"]],kA="FirmTerms("+bd.map(([e,t])=>t+" "+e).join(",")+")"+R0,Si=e=>new TextEncoder().encode(String(e)),gd=(...e)=>{let t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n},H0=(e,t)=>{let n=String(e??"").replace(/^0x/,"");if(!/^[0-9a-fA-F]*$/.test(n)||n.length%2)throw new d("bad-input",{field:t});let r=new Uint8Array(n.length/2);for(let o=0;o<r.length;o+=1)r[o]=parseInt(n.slice(o*2,o*2+2),16);return r},C0=(e,t,n)=>{let r=null;try{r=BigInt(String(e??"").trim())}catch{r=null}if(r===null||r<0n||r>=1n<<BigInt(n))throw new d("bad-input",{field:t});let o=new Uint8Array(32);for(let i=31;i>=0&&r>0n;i-=1)o[i]=Number(r&0xffn),r>>=8n;return o},SA=(e,t)=>{let n=String(e??"").trim();if(!/^(0x)?[0-9a-fA-F]{40}$/.test(n))throw new d("bad-input",{field:t});let r=new Uint8Array(32);return r.set(H0(n.replace(/^0x/,""),t),12),r},vA=(e,t)=>{let n=H0(e,t);if(n.length!==32)throw new d("bad-input",{field:t});return n},EA=(e,t,n,r)=>{if(t==="string")return e.keccak256(Si(n??""));if(t==="address")return SA(n,r);if(t==="bytes32")return vA(n,r);if(t==="uint64")return C0(n,r,64);if(t==="uint256")return C0(n,r,256);throw new d("bad-input",{field:r})},L0=(e,t,n,r,o)=>{let i=[e.keccak256(Si(t))];for(let[s,a]of n)if(a==="FirmOrder"){let c=r&&r.order;if(!c||typeof c!="object")throw new d("bad-input",{field:o+".order"});i.push(AA(e,c))}else i.push(EA(e,a,r?r[s]:void 0,o+"."+s));return e.keccak256(gd(...i))};function AA(e,t){return L0(e,R0,yd,t,"terms.order")}function _A(e){return e.keccak256(gd(e.keccak256(Si(xA)),e.keccak256(Si(yA)),e.keccak256(Si(bA))))}function IA({crypto:e,terms:t}={}){if(!e||typeof e.keccak256!="function")throw new d("bad-input",{field:"crypto"});return L0(e,kA,bd,t,"terms")}function F0({crypto:e,terms:t}={}){if(!e||typeof e.keccak256!="function")throw new d("bad-input",{field:"crypto"});return e.keccak256(gd(Uint8Array.from([25,1]),_A(e),IA({crypto:e,terms:t})))}function D0(e){let t=[];if(!e||typeof e!="object")return["terms"];for(let[n]of bd)if(n==="order")if(!e.order||typeof e.order!="object")t.push("order");else for(let[r]of yd){let o=e.order[r];(o==null||o==="")&&t.push("order."+r)}else{let r=e[n];(r==null||r==="")&&t.push(n)}return t}var j0=(e,t,n)=>{let r=String(e??"").replace(/^0x/i,"");if(!new RegExp("^[0-9a-fA-F]{"+n*2+"}$").test(r))throw new d("bad-input",{field:t});let o=new Uint8Array(n);for(let i=0;i<n;i+=1)o[i]=parseInt(r.slice(i*2,i*2+2),16);return o},vi=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},Ke=(e,t,n)=>vi(j0(e,n,t)),W0=(e,t)=>{let n=null;try{n=BigInt(e)}catch{n=null}if(n===null||n<=0n||n>=_e.Point.Fn.ORDER)throw new d("bad-input",{field:t});return n},U0=(e,t)=>{let n=W0(e,t),r=new Uint8Array(32);for(let o=31;o>=0&&n>0n;o-=1)r[o]=Number(n&0xffn),n>>=8n;return r},M0=(e,t)=>vi(_e.Point.BASE.multiply(W0(e,t)).toBytes()),K0=(e,t)=>{let n=j0(e,t,32);try{_e.Point.fromHex(vi(n).slice(2))}catch{throw new d("bad-input",{field:t})}return vi(n)},NA=["XA","XB","pokA","pokB","proofs"];function TA(e){if(!e||typeof e!="object")throw new d("bad-input",{field:"clientHalf.proof"});for(let a of NA)if(e[a]===void 0||e[a]===null||e[a]==="")throw new d("bad-input",{field:"clientHalf.proof."+a});if(!Array.isArray(e.proofs)||e.proofs.length!==253)throw new d("bad-input",{field:"clientHalf.proof.proofs"});let t=Ke(e.XA,33,"clientHalf.proof.XA"),n=Ke(e.XB,32,"clientHalf.proof.XB"),r=(a,c,l)=>{if(!a||typeof a!="object")throw new d("bad-input",{field:"clientHalf.proof."+c});return{R:Ke(a.R,l,"clientHalf.proof."+c+".R"),s:Ke(a.s,32,"clientHalf.proof."+c+".s")}},o=r(e.pokA,"pokA",33),i=r(e.pokB,"pokB",32),s=e.proofs.map((a,c)=>{if(!a||typeof a!="object"||!a.sig)throw new d("bad-input",{field:"clientHalf.proof.proofs."+c});let l={};for(let u of["eA","eB","a0","a1","b0","b1"])l[u]=Ke(a.sig[u],32,"clientHalf.proof.proofs."+c+".sig."+u);return{cA:Ke(a.cA,33,"clientHalf.proof.proofs."+c+".cA"),cB:Ke(a.cB,32,"clientHalf.proof.proofs."+c+".cB"),sig:l}});return{XA:t,XB:n,pokA:o,pokB:i,proofs:s}}async function V0({features:e,terms:t,clientHalf:n,edViewPointClient:r,edViewPointNode:o,nodeViewScalar:i,clientViewScalar:s=null,side:a=null}={}){let c=zy({features:e,terms:t}),l=String(a||t?.side||"");if(l!=="ask"&&l!=="bid")throw new d("bad-input",{field:"side"});if(t?.side!==void 0&&t.side!==l)throw new d("bad-input",{field:"terms.side"});if(!t||typeof t!="object"||!t.order||typeof t.order!="object")throw new d("bad-input",{field:"terms"});if(t.featuresHash!==void 0&&t.featuresHash!==null&&t.featuresHash!==""&&String(t.featuresHash).toLowerCase()!==c.featuresHash)throw new d("quote-refused",{step:"features",why:"hash"});let u=t.order,f=["chainId","factory","locker","claimer","amount","readyBy","t1","salt"];for(let D of f)if(u[D]===void 0||u[D]===null||u[D]==="")throw new d("bad-input",{field:"terms.order."+D});if(String(u.chainId)!==String(t.market||"").split(":")[0])throw new d("bad-input",{field:"terms.market"});let h=n||{},m=Ke(h.commitHalf,32,"clientHalf.commitHalf"),w=Ke(h.edPoint,32,"clientHalf.edPoint"),x=TA(h.proof);if(x.XB!==w)throw new d("bad-input",{field:"clientHalf.edPoint"});let y=Ke(t.maker,20,"terms.maker"),k=Ke(u.locker,20,"terms.order.locker"),I=Ke(u.claimer,20,"terms.order.claimer");if(k===I)throw new d("bad-input",{field:"terms.order.roles"});if(l==="ask"){if(I!==y)throw new d("bad-input",{field:"terms.order.claimer"});if(String(t.claimTip)!=="0")throw new d("bad-input",{field:"terms.claimTip"})}else if(k!==y)throw new d("bad-input",{field:"terms.order.locker"});let g=K0(r,"edViewPointClient"),P=K0(o,"edViewPointNode"),E=U0(i,"nodeViewScalar");if(M0(i,"nodeViewScalar").toLowerCase()!==P.toLowerCase())throw new d("bad-input",{field:"edViewPointNode"});let B=U0(s,"clientViewScalar");if(M0(s,"clientViewScalar").toLowerCase()!==g.toLowerCase())throw new d("bad-input",{field:"edViewPointClient"});let p={market:String(t.market),side:l,maker:Ke(t.maker,20,"terms.maker"),registry:Ke(t.registry,20,"terms.registry"),featuresHash:c.featuresHash,xmrNetwork:String(t.xmrNetwork),order:{chainId:String(u.chainId),factory:Ke(u.factory,20,"terms.order.factory"),locker:Ke(u.locker,20,"terms.order.locker"),claimer:Ke(u.claimer,20,"terms.order.claimer"),amount:String(u.amount),readyBy:Number(u.readyBy),t1:Number(u.t1),salt:Ke(u.salt,32,"terms.order.salt")},xmrAmount:String(t.xmrAmount),claimTip:String(t.claimTip)},b=D0(p);if(b.length)throw new d("bad-input",{field:"terms",missing:b});let S=vi(F0({crypto:{keccak256:Q},terms:p})),v=B0({termsDigest:S,commitHalf:m,edPoint:w,edViewPointClient:g,edViewPointNode:P}),H=new Uint8Array(64);H.set(E,0),H.set(B,32);let A=await O0({hpkeKey:c.hpkeKey,info:v,plaintext:H});return{payload:JSON.stringify({terms:p,clientHalf:{commitHalf:m,edPoint:w,proof:x},edViewPointClient:g,edViewPointNode:P,viewEnvelope:A}),terms:p,viewEnvelope:A,edViewPointClient:g,edViewPointNode:P}}fe();Ee();Ee();var PA={keccak256:Q,secp256k1:Ce};var $0=e=>nw({crypto:PA,quote:e});function z0({side:e,requested:t,signed:n}={}){let r=s=>{if(s==null||s==="")return null;try{let a=BigInt(String(s));return a>=0n?a:null}catch{return null}},o=r(t),i=r(n);return o===null||i===null?{ok:!1,reason:"unreadable"}:e==="ask"?i>=o?{ok:!0,side:e,requested:o.toString(),signed:i.toString()}:{ok:!1,reason:"worse",side:e,requested:o.toString(),signed:i.toString()}:e==="bid"?i<=o?{ok:!0,side:e,requested:o.toString(),signed:i.toString()}:{ok:!1,reason:"worse",side:e,requested:o.toString(),signed:i.toString()}:{ok:!1,reason:"side"}}var BA="Quote(string relayId,address provider,bytes32 session,bytes32 requestId,uint64 counter,bytes32 requestHash,string payload,uint64 time)",OA="EIP712Domain(string name,string version)",CA="Ninsei Relay",RA="1",_i=(e,t)=>{if(typeof e=="string")return e;if(typeof e=="number"&&Number.isFinite(e)||typeof e=="bigint")return String(e);throw new d("bad-input",{field:t})},co=(e,t)=>{let n=null;try{n=Number(e)}catch{n=null}if(!Number.isFinite(n))throw new d("bad-input",{field:t});return n},lo=(e,t="text")=>new TextEncoder().encode(_i(e,t)),uo=(...e)=>{let t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n},Wa=(e,t,n)=>{let r=_i(e??"",t).replace(/^0x/,"");if(!new RegExp("^[0-9a-fA-F]{"+n*2+"}$").test(r))throw new d("bad-input",{field:t});let o=new Uint8Array(n);for(let i=0;i<n;i+=1)o[i]=parseInt(r.slice(i*2,i*2+2),16);return o},xd=(e,t)=>{let n=new Uint8Array(32);return n.set(Wa(e,t,20),12),n},Ei=(e,t)=>Wa(e,t,32),Ai=(e,t)=>{let n=null;try{n=BigInt(e)}catch{n=null}if(n===null||n<0n)throw new d("bad-input",{field:t});let r=new Uint8Array(32);for(let o=31;o>=0&&n>0n;o-=1)r[o]=Number(n&0xffn),n>>=8n;return r},Va=(e,t)=>Q(lo(e??"",t));function HA(e){if(!e||typeof e!="object")throw new d("bad-input",{field:"answer"});return Q(uo(Q(lo(BA)),Va(e.relayId,"answer.relayId"),xd(e.provider,"answer.provider"),Ei(e.session,"answer.session"),Ei(e.requestId,"answer.requestId"),Ai(e.counter,"answer.counter"),Ei(e.requestHash,"answer.requestHash"),Va(e.payload,"answer.payload"),Ai(e.time,"answer.time")))}function G0(){return Q(uo(Q(lo(OA)),Q(lo(CA)),Q(lo(RA))))}function LA(e){return Q(uo(Uint8Array.from([25,1]),G0(),HA(e)))}var FA="QuoteRequest(string relayId,address provider,bytes32 session,bytes32 requestId,uint64 counter,uint64 expiry,string payload,uint256 feeBps,address feeRecipient)";function DA(e){if(!e||typeof e!="object")throw new d("bad-input",{field:"forwarded"});return Q(uo(Q(lo(FA)),Va(e.relayId,"forwarded.relayId"),xd(e.provider,"forwarded.provider"),Ei(e.session,"forwarded.session"),Ei(e.requestId,"forwarded.requestId"),Ai(e.counter,"forwarded.counter"),Ai(e.expiry,"forwarded.expiry"),Va(e.payload,"forwarded.payload"),Ai(e.feeBps,"forwarded.feeBps"),xd(e.feeRecipient,"forwarded.feeRecipient")))}function X0(e){return Q(uo(Uint8Array.from([25,1]),G0(),DA(e)))}function q0({forwarded:e,relayKey:t,payload:n,provider:r,requestHash:o=null}={}){if(!e||typeof e!="object"||e.type!=="quote_request"||co(e.version,"forwarded.version")!==1)throw new d("quote-refused",{step:"answer",why:"forwarded"});if(!/^0x[0-9a-fA-F]{40}$/.test(String(t||"")))throw new d("quote-refused",{step:"relay-info",why:"key"});if(_i(e.payload===void 0||e.payload===null?"":e.payload,"forwarded.payload")!==n)throw new d("quote-refused",{step:"answer",why:"forwarded-payload"});if(!gt(e.provider,r))throw new d("quote-refused",{step:"answer",why:"forwarded-provider"});let i=Z0(X0(e),e.signature);if(i===null||i!==String(t).toLowerCase())throw new d("quote-refused",{step:"answer",why:"forwarded-signature"});if(o!=null){let s=Q0(X0(e));if(!gt(s,o))throw new d("quote-refused",{step:"answer",why:"forwarded-hash"})}return e}var Q0=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t};function Z0(e,t){let n=_i(t??"","signature").replace(/^0x/,"");if(!/^[0-9a-fA-F]{130}$/.test(n))return null;let r=parseInt(n.slice(128,130),16);if(r>=27&&(r-=27),r!==0&&r!==1)return null;try{let o=Ce.Signature.fromBytes(uo(Wa(n.slice(0,64),"signature",32),Wa(n.slice(64,128),"signature",32))).addRecoveryBit(r).recoverPublicKey(e);return Q0(Q(o.toBytes(!1).slice(1)).slice(12))}catch{return null}}function UA(e,t){if(!e||typeof e!="object"||e.type!=="quote"||co(e.version,"answer.version")!==1)throw new d("quote-refused",{step:"answer",why:"frame"});let n=Z0(LA(e),e.signature);if(n===null||n!==String(t||"").toLowerCase())throw new d("quote-refused",{step:"answer",why:"signature"});return e}var MA="0x"+"00".repeat(20),Y0=e=>_i(e??"","field").toLowerCase(),gt=(e,t)=>Y0(e)===Y0(t);function KA(e,t,n){let r=t.order;if(!e||typeof e!="object")throw new d("quote-refused",{step:"answer",why:"quote"});let o=[["chainId",String(r.chainId)],["factory",r.factory],["locker",r.locker],["claimer",r.claimer],["amount",String(r.amount)],["readyBy",String(r.readyBy)],["t1",String(r.t1)],["salt",r.salt],["claimTip",String(t.claimTip)],["provider",t.maker],["registry",t.registry]];for(let[h,m]of o)if(!gt(e[h],m))throw new d("quote-refused",{step:"answer",why:"field",field:h});if(!z0({side:t.side,requested:t.xmrAmount,signed:e.xmrAmount}).ok)throw new d("quote-refused",{step:"answer",why:"field",field:"xmrAmount"});if(gt(e.feeRecipient,MA))throw new d("quote-refused",{step:"answer",why:"fee-recipient"});let s=Number(e.feeBps),a=null,c=null;try{a=BigInt(String(e.fee)),c=BigInt(String(r.amount))}catch{throw new d("quote-refused",{step:"answer",why:"fee"})}if(!Number.isSafeInteger(s)||s<0||s>200)throw new d("quote-refused",{step:"answer",why:"fee"});if(a!==c*BigInt(s)/10000n)throw new d("quote-refused",{step:"answer",why:"fee"});let l=co(e.validUntil,"quote.validUntil");if(!Number.isSafeInteger(l)||l<=n)throw new d("quote-expired",{step:"answer",validUntil:e.validUntil});let u=co(r.readyBy,"order.readyBy"),f=co(r.t1,"order.t1");if(!Number.isSafeInteger(u)||!Number.isSafeInteger(f)||u>=f||l>=u)throw new d("quote-refused",{step:"answer",why:"validity",field:"validUntil"})}function J0({answer:e,features:t,request:n,now:r=null}={}){if(!n||!n.terms)throw new d("bad-input",{field:"request"});if(UA(e,t&&t.quoteKey),!e.relayId||!gt(e.relayId,t&&t.relayId))throw new d("quote-refused",{step:"answer",why:"relay"});let o=null;try{o=JSON.parse(e.payload)}catch{throw new d("quote-refused",{step:"answer",why:"payload"})}if(!o||typeof o!="object"||!o.quote)throw new d("quote-refused",{step:"answer",why:"payload"});if(o.contextVersion!=="ninsei-order-v3"||co(o.quoteVersion,"payload.quoteVersion")!==10)throw new d("quote-refused",{step:"answer",why:"version"});if(!gt(o.factory,n.terms.order.factory))throw new d("quote-refused",{step:"answer",why:"factory"});if(!gt(e.provider,n.terms.maker))throw new d("quote-refused",{step:"answer",why:"provider"});let i={...o.quote,factory:n.terms.order.factory};i.quoteSignature||(i.quoteSignature=o.quoteSignature);let s=null;try{s=xn.orderContextString(n.terms.order)}catch{s=null}if(!s||o.context!==s)throw new d("quote-refused",{step:"context",why:"other-terms"});let a=$0({...i,signature:o.quoteSignature});if(a===null)throw new d("quote-refused",{step:"signature",why:"invalid"});if(!gt(a,i.quoteKey))throw new d("quote-refused",{step:"signature",why:"key"});let c=Math.floor((r===null?Date.now():r)/1e3);KA(i,n.terms,c);let l=n.terms.side,u=l==="ask"?n.edViewPointClient:n.edViewPointNode,f=l==="ask"?n.edViewPointNode:n.edViewPointClient;if(!gt(o.edViewPointLocker,u)||!gt(o.edViewPointClaimer,f))throw new d("quote-refused",{step:"answer",why:"view-points"});let h=o.nodeHalf;if(!h||typeof h!="object"||!h.proof)throw new d("quote-refused",{step:"answer",why:"node-half"});if(l==="ask"&&(!gt(h.commitHalf,i.commitHalfClaimer)||!gt(h.edPoint,i.edPointClaimer)))throw new d("quote-refused",{step:"answer",why:"node-half"});return{quote:i,orderQuote:{...i,factory:o.factory,signature:o.quoteSignature},nodeHalf:h,edViewPointLocker:o.edViewPointLocker,edViewPointClaimer:o.edViewPointClaimer,context:s}}var jA=new Set(["compliance","no_liquidity","size","paused","unavailable","bad_request","price_changed"]),On=(e,t)=>{if(typeof e=="string")return e;if(typeof e=="number"&&Number.isFinite(e)||typeof e=="bigint")return String(e);throw new d("bad-input",{field:t})},WA=(e,t)=>(e==null?"":On(e,"relay"))===(t==null?"":On(t,"relay"));async function eb({relayUrl:e,partner:t=null,fetchImpl:n=null,timeoutMs:r=2e4,retryTimeouts:o=1,...i}={}){let s=String(e??"").trim().replace(/\/+$/,"");if(!s)throw new d("bad-input",{field:"relayUrl"});if(!/^https:\/\//i.test(s))throw new d("bad-input",{field:"relayUrl",why:"not-https"});let a=await V0(i),c=JSON.stringify({version:1,payload:a.payload,...t?{partner:String(t)}:{}}),l=nt({apiBase:s,fetchImpl:n,timeoutMs:r}),u=null;try{let I=await l.tryJson("/v1/relay");if(!I||I.ok!==!0||!I.body||typeof I.body!="object")throw new d("quote-refused",{step:"relay-info",why:"unavailable"});u=I.body}catch(I){throw I instanceof d?I:new d("quote-refused",{step:"relay-info",why:"unavailable"})}let f=()=>l.tryJson("/v1/quote",{method:"POST",headers:{"content-type":"application/json"},body:c}),h;try{h=await f()}catch(I){if(o>0&&I&&I.code==="server-unavailable"&&I.params&&I.params.why==="timeout")h=await f();else throw I}if(!h.ok){let I=h.body&&h.body.code?String(h.body.code):null;throw I&&jA.has(I)?new d("quote-refused",{step:"relay",code:I,status:h.status}):new d("server-unavailable",{step:"relay",status:h.status})}let m=h.body&&h.body.answer,w=null;try{w=h.body?Number(h.body.version):null}catch{w=null}if(!h.body||w!==1||!m)throw new d("quote-refused",{step:"answer",why:"envelope"});if(typeof h.body.relay!="string"||!h.body.relay||!h.body.forwarded||h.body.forwarded.relayId!==h.body.relay)throw new d("quote-refused",{step:"answer",why:"relay"});if(!WA(m.relayId,h.body.relay))throw new d("quote-refused",{step:"answer",why:"relay"});q0({forwarded:h.body.forwarded,relayKey:u.relayKey,payload:a.payload,provider:i.features.provider,requestHash:m.requestHash===void 0||m.requestHash===null?"":m.requestHash});let x=J0({answer:m,features:i.features,request:a}),y=On(u.feeRecipient===void 0||u.feeRecipient===null?"":u.feeRecipient,"relay.feeRecipient").toLowerCase(),k=On(x.quote.feeRecipient===void 0||x.quote.feeRecipient===null?"":x.quote.feeRecipient,"quote.feeRecipient").toLowerCase();if(!y||y!==k)throw new d("quote-refused",{step:"fee",why:"fee-recipient"});if(!t&&On(u.feeBps===void 0||u.feeBps===null?"":u.feeBps,"relay.feeBps")!==On(x.quote.feeBps===void 0||x.quote.feeBps===null?"":x.quote.feeBps,"quote.feeBps"))throw new d("quote-refused",{step:"fee",why:"fee-bps"});if(u.relayId===void 0||u.relayId===null||On(u.relayId,"relay.relayId")!==On(h.body.relay,"relay"))throw new d("quote-refused",{step:"relay-info",why:"relay"});return{...x,relayUrl:s,relay:h.body.relay??null,offered:h.body.offered??null,forwarded:h.body.forwarded??null,answer:m}}fe();var Ii=e=>{let t=Number(e);return Number.isSafeInteger(t)?t:null};function xt(e,{side:t=null,field:n="readyWindow"}={}){if(!e||typeof e!="object"||Array.isArray(e))throw new d("bad-input",{field:n,why:"missing"});let r=Ii(e.readyMinSeconds),o=Ii(e.readyMaxSeconds);if(r===null||o===null||r<=0||o<r)throw new d("bad-input",{field:n,why:"bounds"});if(t!==null&&e.side!==void 0&&String(e.side)!==String(t))throw new d("bad-input",{field:n,why:"side"});return Object.freeze({market:e.market===void 0||e.market===null?null:String(e.market),side:e.side===void 0||e.side===null?null:String(e.side),xmrNetwork:e.xmrNetwork===void 0||e.xmrNetwork===null?null:String(e.xmrNetwork),readyMinSeconds:r,readyMaxSeconds:o,settlementMinSeconds:Ii(e.settlementMinSeconds),settlementMaxSeconds:Ii(e.settlementMaxSeconds),quoteTtlSeconds:Ii(e.quoteTtlSeconds)})}function tb(e){let t=xt(e),n=t.readyMaxSeconds-t.readyMinSeconds;return Math.max(0,Math.min(n,t.readyMinSeconds))}function nb(e){let t=xt(e),n=t.readyMaxSeconds-t.readyMinSeconds,r=t.readyMinSeconds-n;return Math.max(0,r>0?r:t.readyMinSeconds)}function kd(e,t=300){let n=xt(e),r=Number.isFinite(Number(t))&&Number(t)>=0?Number(t):300;return(n.readyMaxSeconds+r)*1e3}function rb({validUntil:e,nowSec:t,marginSec:n=30}={}){let r=Number(e),o=Number(t),i=Number(n);if(!Number.isSafeInteger(r)||!Number.isSafeInteger(o)||!Number.isSafeInteger(i)||i<0)return{ok:!1,code:"quote-too-short",remainingSec:null,marginSec:Number.isSafeInteger(i)?i:null};let s=r-o;return{ok:s>i,code:s>i?null:"quote-too-short",remainingSec:s,marginSec:i}}Ee();var ab=e=>new TextEncoder().encode(String(e)),Ni=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},VA=()=>Ni(Q(ab("providerOf(address)")).slice(0,4)),ob=e=>VA()+"0".repeat(24)+String(e).toLowerCase().replace(/^0x/,""),$A=()=>Ni(Q(ab("factoryOf(address)")).slice(0,4)),zA=e=>$A()+"0".repeat(24)+String(e).toLowerCase().replace(/^0x/,""),ib=e=>{let t=String(e??"").replace(/^0x/,"");if(t.length%2)return null;let n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++){let o=parseInt(t.slice(r*2,r*2+2),16);if(Number.isNaN(o))return null;n[r]=o}return n},fo="0x"+"00".repeat(20),po=(e,t)=>String(e??"").toLowerCase()===String(t??"").toLowerCase(),Sd=e=>{let t=String(e??"").replace(/^0x/,"");return t.length>=40?"0x"+t.slice(-40).toLowerCase():null},XA=e=>{let t=e&&e.settlement&&e.settlement.chain,n=t&&t.escrow&&t.escrow.cashier;return typeof n=="string"&&/^0x[0-9a-fA-F]{40}$/.test(n)?n.toLowerCase():null},YA=(e,t,n)=>{let r=n&&n.settlement&&n.settlement.chain,o=XA(n);if(!o&&!r)return;let i=String(e&&e.cashier||"").toLowerCase();o||z("quote-cashier-mismatch",{step:t,why:"no-pinned-cashier",got:i||null}),i!==o&&z("quote-cashier-mismatch",{step:t,got:i||null,want:o})},GA=e=>{if(!e||typeof e!="object")return 0n;let t=e.priorityFeePerGas!==void 0&&e.priorityFeePerGas!==null?e.priorityFeePerGas:e.maxPriorityFeePerGas!==void 0&&e.maxPriorityFeePerGas!==null?e.maxPriorityFeePerGas:null;if(t!==null)return t;let n=e.baseFeePerGas!==void 0?e.baseFeePerGas:e.baseFeeWei;if(e.gasPrice===void 0||e.gasPrice===null||n===void 0||n===null)return 0n;try{let r=BigInt(e.gasPrice),o=BigInt(n);return r>o?r-o:0n}catch{return 0n}};function sb({claimTipWei:e=0,baseFeeWei:t=null,priorityFeeWei:n=0,factor:r=2}={}){let o=0n;try{o=BigInt(e==null||e===""?0:e)}catch{return{ok:!1,code:"quote-tip-unreadable"}}if(o<0n)return{ok:!1,code:"quote-tip-unreadable"};if(o===0n)return{ok:!0,tipWei:"0",ceilingWei:null,estimateWei:null};if(t==null||t==="")return{ok:!1,code:"quote-tip-unchecked",tipWei:o.toString()};let i=hl({baseFeeWei:t,priorityFeeWei:n});if(i===null)return{ok:!1,code:"quote-tip-unchecked",tipWei:o.toString()};let s=BigInt(r),a=i*s;return o>a?{ok:!1,code:"quote-tip-too-large",tipWei:o.toString(),estimateWei:i.toString(),ceilingWei:a.toString()}:{ok:!0,tipWei:o.toString(),estimateWei:i.toString(),ceilingWei:a.toString()}}function vd({config:e,now:t=()=>Date.now(),evmCall:n=null,evmCode:r=null,evmBlock:o=null,providerAllowed:i=null,knownFactoryCodes:s=null,knownImplementationCodes:a=null,denylist:c=null}){let l=Array.isArray(s)&&s.length?s.map(f=>String(f).toLowerCase()).filter(Boolean):null,u=Array.isArray(a)&&a.length?a.map(f=>String(f).toLowerCase()).filter(Boolean):null;return{async firmRelay(f){(!f||typeof f!="object")&&z("bad-input",{field:"request"});let h=f.features,m=f.order&&typeof f.order=="object"?{...f.order}:null;(!h||typeof h!="object")&&z("bad-input",{field:"features"}),m||z("bad-input",{field:"order"});let w=String(f.side||"");w!=="ask"&&w!=="bid"&&z("bad-input",{field:"side"});let x=String(h.provider||"").toLowerCase(),y=String(h.registry||"").toLowerCase();(!/^0x[0-9a-f]{40}$/.test(x)||x===fo)&&z("bad-input",{field:"features.provider"}),(!/^0x[0-9a-f]{40}$/.test(y)||y===fo)&&z("bad-input",{field:"features.registry"});let k=e&&e.settlement&&e.settlement.chain&&e.settlement.chain.escrow&&e.settlement.chain.escrow.registry;k&&!po(y,k)&&z("bad-input",{field:"features.registry",why:"not-the-network-registry"}),(!/^0x[0-9a-f]{40}$/.test(String(h.quoteKey||"").toLowerCase())||String(h.quoteKey).toLowerCase()===fo)&&z("bad-input",{field:"features.quoteKey"}),typeof n!="function"&&z("quote-registry-unchecked",{step:"features",why:"no-chain-read",registry:y});let I=null;try{I=Sd(await n({to:y,data:ob(h.quoteKey)}))}catch{z("quote-registry-unchecked",{step:"features",why:"read-failed",registry:y})}(I===null||I===fo)&&z("quote-key-unknown",{step:"registry",registry:y,quoteKey:h.quoteKey}),po(I,h.provider)||z("quote-provider-mismatch",{step:"registry",got:I,want:h.provider});let g=w==="bid"?m.claimer:m.locker;c&&typeof g=="string"&&c.has(g.toLowerCase())&&z("address-denied",{step:"order-quote"}),w==="ask"?(m.claimer&&!po(m.claimer,x)&&z("bad-input",{field:"order.claimer"}),m.claimer=x):(m.locker&&!po(m.locker,x)&&z("bad-input",{field:"order.locker"}),m.locker=x);let P=Number(m.chainId);(!Number.isSafeInteger(P)||P<=0)&&z("bad-input",{field:"order.chainId"});let E=Array.isArray(h.firmWindows)?h.firmWindows.filter(re=>re&&re.side===w):[],B=[...new Set(E.map(re=>re.market).filter(re=>typeof re=="string"&&re))],p=f.market!==void 0?String(f.market):B.length===1?B[0]:null;p||z("bad-input",{field:"market"});let b=E.find(re=>re.market===p)||null;b||z("quote-refused",{step:"features",why:"window"});let S=xt(b,{side:w,field:"features.firmWindows"}),v=f.xmrNetwork!==void 0?String(f.xmrNetwork):b.xmrNetwork;v||z("bad-input",{field:"xmrNetwork"}),(f.xmrAmount===void 0||f.xmrAmount===null||f.xmrAmount==="")&&z("bad-input",{field:"xmrAmount"});let H=f.claimTip===void 0||f.claimTip===null?"0":String(f.claimTip),A=typeof f.recoveryKey=="string"?f.recoveryKey:f.recoveryKey&&typeof f.recoveryKey.mnemonic=="string"?f.recoveryKey.mnemonic:null;A||z("bad-input",{field:"recoveryKey"});let O=f.recoverySalt!==void 0&&f.recoverySalt!==null;(!m.factory||!/^0x[0-9a-f]{40}$/i.test(String(m.factory)))&&z("bad-input",{field:"order.factory"});let D=null;try{D=Zt(O?f.recoverySalt:m.salt)}catch{z("bad-input",{field:"recoverySalt"})}if(O){let re=null;try{re=Zt(m.salt)}catch{z("bad-input",{field:"recoverySalt",why:"order-salt"})}D!==re&&z("bad-input",{field:"recoverySalt",why:"order-salt"})}let L=ir({mnemonic:A,chainId:P,factory:m.factory,salt:D}),V={kind:"salt-v2",salt:D},U=await Ky(m,{spendHalf:L.spendHalf,viewHalf:L.viewHalf}),j=Ce.Point.fromHex(U.side.proof.XA),F={commitHalf:Ni(Q(j.toBytes(!1).slice(1))),edPoint:U.side.pub.ed,proof:U.side.proof},R=await eb({relayUrl:f.relayUrl,partner:f.partner,fetchImpl:f.fetchImpl,timeoutMs:f.timeoutMs,features:h,terms:{market:p,side:w,maker:x,registry:y,xmrNetwork:v,order:m,xmrAmount:String(f.xmrAmount),claimTip:H},clientHalf:F,edViewPointClient:U.side.viewPub,edViewPointNode:L.makerViewPoint,nodeViewScalar:L.makerViewHalf,clientViewScalar:L.viewHalf,side:w}),_=R.quote,N=Math.floor(Number(t())/1e3),W=rb({validUntil:_.validUntil,nowSec:N});W.ok||z("quote-too-short",{step:"answer",validUntil:Number.isFinite(Number(_.validUntil))?Number(_.validUntil):null,now:N,remainingSec:W.remainingSec,marginSec:W.marginSec}),YA(_,"relay",e);let $=R.nodeHalf;await Xu({context:U.context,side:U.side,counterparty:w==="ask"?{proof:$.proof,edPub:_.edPointClaimer,commitHalfClaimer:_.commitHalfClaimer,viewPoint:R.edViewPointClaimer,viewHalf:L.makerViewHalf}:{proof:$.proof,edPub:$.edPoint,commitHalfClaimer:$.commitHalf,viewPoint:R.edViewPointLocker,viewHalf:L.makerViewHalf}});let X=w==="ask"?_.edPointClaimer:$.edPoint,Y=w==="ask"?R.edViewPointClaimer:R.edViewPointLocker,G=Zr({ownSpendHalf:L.spendHalf,ownViewHalf:L.viewHalf,otherSpendPoint:X,otherViewPoint:Y,network:v}),Z=w==="ask"?{commitHalfLocker:F.commitHalf,edPointLocker:U.side.pub.ed,edViewPointLocker:U.side.viewPub}:{commitHalfLocker:$.commitHalf,edPointLocker:$.edPoint,edViewPointLocker:R.edViewPointLocker},ne=null;try{let re=await n({to:_.factory,data:Ue.encodePredict({...R.orderQuote,...Z,signature:R.orderQuote.signature})});ne=Ue.decodeAddress(re)}catch{z("quote-escrow-unchecked",{step:"factory",why:"predict-failed",factory:_.factory})}i&&i(x)!==!0&&z("quote-provider-not-allowed",{step:"policy",provider:x}),typeof n!="function"&&z("quote-registry-unchecked",{step:"registry",why:"no-chain-read"});let oe=null;try{oe=Sd(await n({to:y,data:ob(_.quoteKey)}))}catch{z("quote-registry-unchecked",{step:"registry",why:"read-failed",registry:y})}(oe===null||oe===fo)&&z("quote-key-unknown",{step:"registry",registry:y,quoteKey:_.quoteKey}),po(oe,_.provider)||z("quote-provider-mismatch",{step:"registry",got:oe,want:_.provider});let T=null;try{T=Sd(await n({to:y,data:zA(_.provider)}))}catch{z("quote-factory-unchecked",{step:"factory",why:"read-failed",registry:y})}if((T===null||T===fo)&&z("quote-factory-unknown",{step:"factory",registry:y,provider:_.provider}),po(T,_.factory)||z("quote-factory-mismatch",{step:"factory",got:_.factory,want:T}),l){typeof r!="function"&&z("quote-factory-unchecked",{step:"factory",why:"no-code-read"});let re=null;try{re=await r(_.factory)}catch{z("quote-factory-unchecked",{step:"factory",why:"code-read-failed",factory:_.factory})}let ae=Ni(Q(ib(re)||new Uint8Array(0)));l.includes(ae)||z("quote-factory-code-unknown",{step:"factory",factory:_.factory,codeHash:ae})}if(u){typeof n!="function"&&z("quote-factory-unchecked",{step:"factory",why:"no-chain-read"}),typeof r!="function"&&z("quote-factory-unchecked",{step:"factory",why:"no-code-read"});let re=await Ue.verifyFactoryImplementationOnChain({factory:_.factory,read:n,code:ae=>r(ae),policy:u,hashCode:ae=>Ni(Q(ib(ae)||new Uint8Array(0)))});if(!re.ok){let ae=re.why==="implementation-code-unknown"||re.why==="implementation-code-mismatch"||re.why==="implementation-has-no-code";z(ae?"quote-factory-code-unknown":"quote-factory-unchecked",{step:"factory",why:re.why,factory:_.factory,implementation:re.implementation||null})}}let K=(()=>{try{return sb({claimTipWei:_.claimTip})}catch{return{ok:!0,tipWei:"0"}}})();if(!K.ok&&K.code==="quote-tip-unreadable"&&z("quote-field-unbound",{step:"claimTip",field:"claimTip"}),K.tipWei!=="0"){typeof o!="function"&&z("quote-tip-unchecked",{step:"claimTip",why:"no-block-read"});let re=null;try{re=await o("latest")}catch{z("quote-tip-unchecked",{step:"claimTip",why:"block-read-failed"})}let ae=re&&(re.baseFeePerGas!==void 0?re.baseFeePerGas:re.baseFeeWei),Ge=GA(re),ie=sb({claimTipWei:_.claimTip,baseFeeWei:ae,priorityFeeWei:Ge});ie.ok||z(ie.code,{step:"claimTip",...ie})}let M=R.orderQuote&&R.orderQuote.xmrAmount!==void 0&&R.orderQuote.xmrAmount!==null?String(R.orderQuote.xmrAmount):null;M||z("quote-field-unbound",{step:"xmrAmount",field:"orderQuote.xmrAmount"});let ee=f.market&&String(f.market).includes(":")?String(f.market).split(":").slice(1).join(":"):null,C=String(m.asset||ee||"").trim(),q={..._,viewHalfClaimer:L.makerViewHalf,xmrAmount:M,readyWindow:S,...C?{asset:C,token:C.toLowerCase()}:{},..._.nonce!==void 0&&_.nonce!==null?{id:String(_.nonce)}:{}},J={proof:$.proof,edPointClaimer:w==="ask"?_.edPointClaimer:$.edPoint,commitHalfClaimer:w==="ask"?_.commitHalfClaimer:$.commitHalf,viewHalfClaimer:L.makerViewHalf,viewPoint:w==="ask"?R.edViewPointClaimer:R.edViewPointLocker},le={...m,xmrAmount:M};return{...R,quote:q,order:le,readyWindow:S,startRequest:{quote:q,order:le,orderQuote:R.orderQuote,counterparty:J,recoveryKey:f.recoveryKey,recoverySalt:m.salt},counterparty:J,viewHalfClaimer:L.makerViewHalf,viewHalfPoint:L.makerViewPoint,jointAddress:G.address,escrow:ne,recovery:V}}}}var qA=e=>{let t=e&&typeof e=="object"?e:{},{reason:n,kind:r,ok:o,checked:i,blocks:s,...a}=t;return{code:Gm(r),ok:o===!0,checked:i!==!1,blocks:s===!0,kind:typeof r=="string"?r:"unknown",params:a}},cb=(...e)=>e.some(t=>t!=null&&t!==""),Nt=(e,t)=>{try{return e(t)}catch(n){return{ok:!1,checked:!1,blocks:!1,kind:"unchecked",error:String(n&&n.message?n.message:n)}}};function lb({config:e,wallet:t,limits:n={}}){return async function(o={},i={}){let s=ce.SIGNING_GUARDS||{},a=Number.isFinite(i.nowMs)?i.nowMs:Date.now(),c=o&&typeof o=="object"?o:{},l=!!i.tokenIsNative,u=e.evmNetwork,h=[Nt(we.quoteFreshnessVerdict,{at:Number.isFinite(c.at)?c.at:null,ttlMs:Number.isFinite(c.ttlMs)?c.ttlMs:null,expiresAt:Number.isFinite(c.expiresAt)?c.expiresAt:null,nowMs:a}),Nt(we.deadlineVerdict,{nowSec:Math.floor(a/1e3),readyBy:Number.isFinite(c.readyBy)?c.readyBy:null,t1:Number.isFinite(c.t1)?c.t1:null,minReadyLeadSec:s.minReadyLeadSec??null,minClaimWindowSec:s.minClaimWindowSec??null}),Nt(we.rangeVerdict,{size:Number.isFinite(c.amount)?c.amount:null,unit:c.token||null,min:Number.isFinite(c.min)?c.min:n.minAmount??null,max:Number.isFinite(c.max)?c.max:n.maxAmount??null,step:Number.isFinite(c.step)?c.step:n.stepAmount??null,quoteUnit:c.token||null}),Nt(we.payBalanceVerdict,{payBalanceWei:i.payBalanceWei??null,payAmountWei:i.payAmountWei??null,symbol:l?u.nativeSymbol:c.token||null,decimals:Number.isFinite(i.decimals)?i.decimals:18}),Nt(we.gasReserveVerdict,{nativeBalanceWei:i.nativeBalanceWei??null,requiredNativeWei:i.requiredNativeWei??null,gasReserveWei:i.gasReserveWei??null,symbol:u.nativeSymbol,decimals:18}),Nt(we.allowanceVerdict,{tokenIsNative:l,allowanceWei:i.allowanceWei??null,amountWei:i.payAmountWei??null,consent:i.allowanceConsent===!0,symbol:c.token||null,decimals:Number.isFinite(i.decimals)?i.decimals:18}),Nt(we.networkGateVerdict,{walletChainId:t.status().chainId,selectedChainId:u.chainId,settlementChainId:u.chainId,selectedChainName:u.name}),Nt(we.counterpartyVerdict,{standIn:i.standIn===!0,liveChain:i.liveChain===!0,network:e.evmNetwork.id,chainId:u.chainId}),Nt(we.escrowStateVerdict,{status:i.escrowStatus??null,error:null,address:i.escrowAddress??null}),...cb(i.point,i.commit)?[Nt(we.escrowPointsVerdict,{role:i.pointsRole??null,what:i.pointsWhat??null,point:i.point??null,onchainPoint:i.onchainPoint??null,commit:i.commit??null,onchainCommit:i.onchainCommit??null,readError:i.pointsReadError??null})]:[],...cb(i.slots)?[Nt(we.liveOrderSlotsVerdict,{slots:i.slots??null,expect:i.slotsExpect??null,readError:i.slotsReadError??null})]:[]].map(qA),m=[...new Set(h.filter(w=>w.blocks).map(w=>w.code))];return{ok:m.length===0,blockedBy:m,checks:h}}}fe();var ub=e=>typeof e=="string"?e:e&&typeof e.contents=="string"?e.contents:null;function Ed(){return{async open(e,t){let n=ub(e);if(n===null)throw new d("bad-input",{field:"file"});let r;try{r=JSON.parse(n)}catch{throw new d("recovery-failed",{stage:"parse"})}let o;try{o=await vs.restoreFromFile(r,t)}catch{throw new d("recovery-failed",{stage:"restore"})}let i=o.payload||{},s=o.wallet||{},a=Number(i.version)>=3;return{address:typeof s.address=="string"?s.address:null,spendable:!a,swapId:typeof i.swapId=="string"?i.swapId:null}},async restoreHeight(e={}){let t=ub(e.file);if(t===null)throw new d("bad-input",{field:"file"});if(typeof e.passphrase!="string")throw new d("bad-input",{field:"passphrase"});let n;try{n=JSON.parse(t)}catch{throw new d("recovery-failed",{stage:"parse"})}let r;try{r=await rt.decryptFile(n,e.passphrase),rt.validatePayload(r)}catch{throw new d("recovery-failed",{stage:"restore"})}let o=r.moneroWallet||{},i=typeof o.address=="string"&&o.address?o.address:null,s=Number(o.restoreHeight)||0,a=s,c=s>0?"file":"none";return{address:i,height:a,source:c,fileHeight:s,appHeight:0,appAsked:!1,appProblem:c==="none"?"no-height":null}}}}fe();var $a=Object.keys(ce.SCENARIO_LABELS||{});function db(){let e=$a[0]||null,t=1,n=0;return{scenarios:()=>$a.slice(),apply(r){$a.includes(r)||z("bad-input",{field:"scenario",known:$a}),e=r},speed(r){let o=Number(r);(!Number.isFinite(o)||o<=0)&&z("bad-input",{field:"speed"}),t=o},advance(r){let o=Number(r);Number.isFinite(o)||z("bad-input",{field:"ms"}),n+=o},debug:()=>({scenario:e,speed:t,advancedMs:n})}}fe();var QA=["connect","disconnect","address","chainId","subscribe","driver"],fb=e=>e&&Kr.includes(e.code)?e.code:"unknown",Ad="monero",Ti={token:"xmr",symbol:"XMR",decimals:12},ZA=2;function pb({settlement:e,leg:t}){let n=null,r={connected:!1,address:null,chainId:null,chainMatches:!1},o=new Set,i=null,s=async(c=!0)=>{if(!n)return r;let[l,u]=await Promise.all([Promise.resolve(n.address()).catch(()=>null),Promise.resolve(n.chainId()).catch(()=>null)]),f=typeof l=="string"&&l.length>0;if(r={connected:f,address:f?l:null,chainId:u===void 0?null:u,chainMatches:f&&t.sameChain(u,e)},c)for(let h of o)h(r);return r},a=()=>{typeof i=="function"&&i(),i=null};return{use(c){(!c||typeof c!="object")&&z("bad-input",{field:"adapter"});let l=QA.filter(f=>typeof c[f]!="function");l.length&&z("bad-input",{field:"adapter",missing:l}),(typeof c.vm!="string"||!c.vm)&&z("bad-input",{field:"adapter.vm"});let u=[e.vm,Ad];u.includes(c.vm)||z("bad-input",{field:"adapter.vm",expected:e.vm,accepted:u,got:c.vm}),a(),n=c,i=n.subscribe(()=>{s().catch(()=>{})}),r={connected:!1,address:null,chainId:null,chainMatches:!1},s().catch(()=>{})},status:()=>r,async connect({chainId:c=null}={}){n||z("wallet-not-connected");try{let l=c===null&&n.vm===e.vm?t.walletChainId(e):c;await n.connect(l===null?{}:{chainId:l})}catch(l){throw new d(fb(l),{vm:n.vm})}return s()},async disconnect(){return n&&await Promise.resolve(n.disconnect()).catch(()=>{}),a(),n=null,void await s()},address:()=>r.address,async switchChain(c){n||z("wallet-not-connected"),Number.isFinite(Number(c))||z("bad-input",{field:"chainId"}),(n.vm!==e.vm||typeof n.switchChain!="function")&&z("not-implemented",{surface:"wallet.switchChain",vm:n.vm,stage:ZA});try{await n.switchChain(Number(c))}catch(u){throw new d(fb(u),{vm:n.vm})}let l=await s();return l.chainMatches||z("wrong-chain",{got:l.chainId,want:t.walletChainId(e)}),l},async balances(c){n||z("wallet-not-connected");let l=r.connected?r:await s(!1);if(l.connected||z("wallet-not-connected"),n.vm===Ad){let w=(Array.isArray(c)&&c.length?c.map(y=>String(y).toLowerCase()):[Ti.token]).find(y=>y!==Ti.token);w!==void 0&&z("bad-input",{field:"tokens",unknown:w}),typeof n.unlockedBalance!="function"&&z("not-implemented",{surface:"wallet.balances",vm:Ad});let x=BigInt(await n.unlockedBalance()).toString();return[{token:Ti.token,symbol:Ti.symbol,decimals:Ti.decimals,amount:x}]}l.chainMatches||z("wrong-chain",{got:l.chainId,want:t.walletChainId(e)}),typeof t.balances!="function"&&z("not-implemented",{surface:"wallet.balances",vm:e.vm});let u=e.tokens||[],f=Array.isArray(c)&&c.length?c.map(m=>String(m).toLowerCase()):u.map(m=>m.id),h=[];for(let m of f){let w=u.find(x=>x.id===m);w||z("bad-input",{field:"tokens",unknown:m}),h.push(w)}return t.balances({driver:n.driver(),address:l.address,tokens:h})},subscribe(c){return typeof c!="function"&&z("bad-input",{field:"handler"}),o.add(c),()=>o.delete(c)},driver:()=>n?n.driver():null}}fe();fe();Ee();function JA(e=null,t=null){if(t&&t.spendHalf&&t.viewHalf)return My(e,t).side;if(e!=null)return Wu(e).side;let n=Yt.createHalves(Xt),r=n.newHalf(),o=n.newHalf();return{half:r,viewHalf:o,pub:n.publicHalves(r),viewPub:n.publicHalves(o).ed}}function _d(e,{order:t=null,side:n=null,store:r=null}={}){if(!e||typeof e!="object")throw new d("bad-input",{field:"input"});let o=n||JA(t),i=null;try{i=ue.createSwap(e,r)}catch{throw new d("bad-input",{field:"input"})}let s={...i.escrow||{},half:Jt(o.half),viewHalf:Jt(o.viewHalf),edPointLocker:me(o.pub.ed),edViewPointLocker:me(o.viewPub)};if(e.expectedAtomic!==void 0&&e.expectedAtomic!==null){let l;try{l=BigInt(String(e.expectedAtomic))}catch{throw new d("bad-input",{field:"expectedAtomic"})}if(l<=0n)throw new d("bad-input",{field:"expectedAtomic"});s.expectedAtomic=l.toString()}o.enc&&o.enc.pub&&(s.encPub=me(o.enc.pub));let a={...i,escrow:s},c=e&&e.orderQuoteId;c!=null&&c!==""&&(a.orderQuoteId=c);try{ue.saveSwap(a,r)}catch{throw new d("storage-unavailable",{step:"save-swap"})}return{swap:a,side:o,missing:["counterparty-half"],nextStep:"order"}}fe();fe();Ee();fe();Ee();var t6="Declined",n6=()=>`${t6}(${["address"].join(",")})`,r6=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},ho=r6(Q(n6())),o6="declined",Xa="compliance",rn="declined",i6=["declined","terminal","code","source","at","checked"],hb=e=>{let t={};for(let n of i6)t[n]=e[n]===void 0?null:e[n];return t},mb=({source:e=null,at:t=null}={})=>hb({declined:!0,terminal:rn,code:Xa,source:e,at:t,checked:!0}),za=({source:e=null,at:t=null,checked:n=!0}={})=>hb({declined:!1,terminal:null,code:null,source:e,at:t,checked:n});function Id(e,{escrow:t=null,at:n=null}={}){if(!Array.isArray(e))throw new d("bad-input",{field:"logs",why:"not-array"});let r=typeof t=="string"&&t?t.toLowerCase():null;for(let o of e){if(!o||typeof o!="object"||r&&typeof o.address=="string"&&o.address&&o.address.toLowerCase()!==r)continue;let i=Array.isArray(o.topics)?o.topics:[];if(String(i[0]||"").toLowerCase()===ho)return mb({source:"event",at:n})}return za({source:"event",at:n})}function s6(e,{at:t=null}={}){if(!e||typeof e!="object")return za({source:"status",at:t,checked:!1});for(let n of[e,e.userStatus])if(!(!n||typeof n!="object")&&String(n.status||"")===o6&&String(n.code||"")===Xa)return mb({source:"status",at:t});return za({source:"status",at:t})}function wb({logs:e=void 0,status:t=void 0,escrow:n=null,at:r=null}={}){let o=Array.isArray(e)?Id(e,{escrow:n,at:r}):null;if(o&&o.declined)return o;let i=t&&typeof t=="object"?s6(t,{at:r}):null;return i&&i.declined?i:o||i||za({checked:!1,at:r})}async function a6({address:e,topics:t=[ho],fromBlock:n="earliest",toBlock:r="latest"}={}){if(typeof e!="string"||!/^0x[0-9a-fA-F]{40}$/.test(e))throw new d("bad-input",{field:"logs.address"});let o=null;try{o=typeof Ue.currentProvider=="function"?Ue.currentProvider():null}catch{o=null}if(!o||typeof o.request!="function")throw new d("bad-input",{field:"evmLogs",why:"no-provider"});let i=await o.request({method:"eth_getLogs",params:[{address:e,topics:t,fromBlock:n,toBlock:r}]});if(!Array.isArray(i))throw new d("server-unavailable",{step:"logs",why:"bad-response"});return i}var Ya=e=>typeof e=="function"?e:a6,Ga=(e,t="earliest")=>{let n=Number(e);return!Number.isFinite(n)||n<0?t:"0x"+Math.trunc(n).toString(16)};var{chainById:mO,DEFAULT_CHAIN:wO,MONERO:yO}=ce,{fundOrderLive:bO,newSecret:gO,sendTransaction:Nd,readContract:Pi}=Ue,{encodeClaim:c6,encodeRefund:l6,encodeMarkReady:yb,encodeStatus:u6,encodeT1:d6,encodeTermsHash:f6,encodeRead:qa,decodeUint64:bb,decodeBytes32:Td,decodeStatus:p6}=Fr,{liveOrderSlotsVerdict:h6,counterpartyVerdict:xO}=we,{orderContextString:kO}=xn,{requestOrderQuote:SO,checkOrderQuoteShape:vO}=$s,{CLAIM_GAS_LIMIT:m6}=_s;async function ur(e,t={}){if(!e)throw new d("bad-input",{field:"escrow"});let r=await(t.call||Pi)({to:e,data:u6(),block:t.blockTag||"latest"});return p6(r)}async function xb(e,t={}){if(typeof e!="string"||!e)throw new d("bad-input",{field:"escrow"});let n=Ya(t.logs),r=t.fromBlock===void 0?"earliest":Ga(t.fromBlock),o=await n({address:e,topics:[ho],fromBlock:r,toBlock:"latest"});return Id(o,{escrow:e,at:Number.isFinite(Number(t.at))?Number(t.at):null})}async function dr(e,t={}){if(!e)throw new d("bad-input",{field:"escrow"});let n=t.call||Pi,r=t.blockTag||"latest",[o,i,s]=await Promise.all([n({to:e,data:d6(),block:r}),n({to:e,data:f6(),block:r}),n({to:e,data:qa("readyBy"),block:r})]);for(let[a,c]of[[o,"t1()"]])if(String(a||"").replace(/^0x/,"").length===0)throw new d("bad-input",{field:"escrow",why:"no-contract"});return{t1:bb(o,"t1()"),termsHash:Td(i,"termsHash()"),readyBy:bb(s,"readyBy()")}}async function w6(e,t={}){let n=t.call||Pi;if(!e)throw new d("bad-input",{field:"escrow"});let r=["edPointLocker","edPointClaimer","edViewPointLocker","commitHalfLocker","commitHalfClaimer"];try{let o=t.blockTag||"latest",i=await Promise.all(r.map(a=>n({to:e,data:qa(a),block:o}))),s={};return r.forEach((a,c)=>{s[a]=Td(i[c],a+"()")}),{slots:s}}catch(o){return{error:String(o&&o.message||o)}}}async function Bi(e,t,n="signature",r={}){if(!t)throw new d("bad-input",{field:"expect"});let o=await w6(e,r),i=h6({slots:o.slots,readError:o.error,expect:t});if(i.blocks)throw new d("contract-reverted",{step:n,why:"slots-mismatch"});return i}async function Pd(e,t,n){let r=await ur(e,n);if(!r.isFunded||r.isClaimed||r.isRefunded)throw new d("contract-reverted",{step:t,why:"closed"})}async function Bd(e,t,n,r=null){if(typeof n.blockTime!="function")return;let o=n.call||Pi,i=n.blockTag||"latest",[s,a]=await Promise.all([o({to:e,data:qa("ready"),block:i}),dr(e,n)]),c=BigInt(s)!==0n,l=Number(r===null?await n.blockTime():r);if(!Number.isSafeInteger(l)||l<=0)throw new d("contract-reverted",{step:t,why:"clock-unreadable"});let u=60;if(t==="claim"){if(l+u>=Number(a.t1))throw new d("contract-reverted",{step:t,why:"window-closed"});if(!c&&l<Number(a.readyBy))throw new d("contract-reverted",{step:t,why:"not-ready"})}else if(t==="refund"){if(l<Number(a.t1)&&(l+u>=Number(a.readyBy)||c))throw new d("contract-reverted",{step:t,why:"too-early"})}else if(t==="mark-ready"){if(c)throw new d("contract-reverted",{step:t,why:"already-ready"});if(l+u>=Number(a.readyBy))throw new d("contract-reverted",{step:t,why:"ready-window-closed"})}}async function y6(e,t,n,r){let o=r.call;if(typeof o=="function")try{await o({to:e,data:t,from:r.from})}catch(i){let s=i&&(i.data||i.message),a=String(i&&i.message||"");throw i&&i.code==="contract-reverted"||i&&typeof i.data=="string"&&i.data.startsWith("0x")||/execution reverted|revert/i.test(a)?new d("contract-reverted",{step:n,why:"simulation",detail:typeof s=="string"?s.slice(0,200):null}):i}}var gb=e=>String(e??"").replace(/^0x/i,"").toLowerCase().slice(-40);async function kb(e,t,n,r,o){let i=r==="claim"?"halfClaimer":"halfLocker",s;try{s=gb(Hr(BigInt(t),Ce,Q))}catch{throw new d("bad-input",{field:i})}let a=o.call||Pi,c;try{c=Td(await a({to:e,data:qa(n),block:o.blockTag||"latest"}),n+"()")}catch{throw new d("contract-reverted",{step:r,why:"slots-unreadable"})}if(s!==gb(c))throw new d("contract-reverted",{step:r,why:"half-mismatch"})}async function Sb({escrow:e,halfClaimer:t,expect:n,onStep:r,deps:o={}}){if(!e)throw new d("bad-input",{field:"escrow"});if(!t)throw new d("bad-input",{field:"halfClaimer"});return await Pd(e,"claim",o),await Bd(e,"claim",o),await Bi(e,n,"claim",o),await kb(e,t,"commitHalfClaimer","claim",o),r?.("confirm-claim"),{hash:await(o.send||Nd)({to:e,data:c6(t),gas:m6})}}async function vb({escrow:e,halfLocker:t,onStep:n,expect:r=null,deps:o={}}){if(!e)throw new d("bad-input",{field:"escrow"});if(!t)throw new d("bad-input",{field:"halfLocker"});return await Pd(e,"refund",o),await Bd(e,"refund",o),r&&await Bi(e,r,"refund",o),await kb(e,t,"commitHalfLocker","refund",o),n?.("confirm-refund"),{hash:await(o.send||Nd)({to:e,data:l6(t),gas:250000n})}}async function Eb({escrow:e,expect:t,onStep:n,deps:r={}}){if(!e)throw new d("bad-input",{field:"escrow"});return await Pd(e,"mark-ready",r),await Bd(e,"mark-ready",r),await Bi(e,t,"mark-ready",r),await y6(e,yb(),"mark-ready",r),n?.("confirm-mark-ready"),{hash:await(r.send||Nd)({to:e,data:yb(),gas:120000n})}}fe();async function mo(e,t,n="send"){let r=Number(t);if(!Number.isSafeInteger(r)||r<=0)throw new d("bad-input",{field:"chainId",step:n});if(!e||typeof e.chainId!="function")throw new d("bad-input",{field:"wallet.chainId",step:n});let o=null;try{o=Number(await e.chainId())}catch{throw new d("wrong-chain",{vm:"evm",step:n,want:r,got:null,why:"unreadable"})}if(!Number.isSafeInteger(o)||o<=0)throw new d("wrong-chain",{vm:"evm",step:n,want:r,got:null,why:"unreadable"});if(o!==r)throw new d("wrong-chain",{vm:"evm",step:n,want:r,got:o});return r}var b6=["commitHalfLocker","commitHalfClaimer","edPointLocker","edPointClaimer","edViewPointLocker"],g6=e=>typeof e=="string"&&e&&!/^0x/i.test(e)?"0x"+e:e;function Ab(e){if(!e||typeof e!="object")throw new d("bad-input",{field:"request"});let t={...e};for(let n of b6)t[n]=g6(t[n]);return t}function x6(e){if(!e||typeof e!="object")throw new d("bad-input",{field:"request"});let n=["locker","claimer","commitHalfLocker","commitHalfClaimer","edPointLocker","edPointClaimer","amount","readyBy","t1"].filter(r=>e[r]===void 0||e[r]===null||e[r]==="");if(n.length)throw new d("bad-input",{field:"terms",missing:n});try{return Fr.orderTerms(Ab(e))}catch{let o=Math.floor(Date.now()/1e3);throw Number(e.readyBy)<=o?new d("bad-input",{field:"readyBy",why:"not-in-future"}):Number(e.t1)<=Number(e.readyBy)?new d("bad-input",{field:"t1",why:"not-after-readyBy"}):new d("bad-input",{field:"terms"})}}var k6=e=>String(e??"").replace(/0x[0-9a-fA-F]{64}/g,"0x<redacted>").slice(0,200),S6=/fetch failed|network|ECONN|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|socket|timeout|HTTP \d|status \d|non-ok/i,v6=e=>S6.test(e);async function _b(e,t,n={}){if(!e||typeof e!="object")throw new d("bad-input",{field:"request"});if(!t||typeof t.send!="function"||typeof t.receipt!="function")throw new d("bad-input",{field:"wallet",missing:["send","receipt"]});let r=Ab(e);x6({...r,amount:r.amountWei});let o=Ue;await mo(t,r.chainId,"fund-order");let i=typeof n.call=="function"?n.call:o.readContract;try{return await o.fundOrder({...r,call:i,onPredicted:n.onPredicted,send:s=>t.send({...s,chainId:r.chainId,from:r.locker}),receipt:s=>t.receipt(typeof s=="string"?s:s&&typeof s.hash=="string"?s.hash:s)})}catch(s){if(s&&typeof s.code=="string")throw s;let a=k6(s&&s.message||s);throw new d(v6(a)?"server-unavailable":"bad-input",{step:"fund-order",why:a})}}Ee();fe();var A6=(e,t)=>t.filter(n=>e[n]===void 0||e[n]===null||e[n]===""),Cd=e=>{let t=["send","receipt"],n=e?t.filter(r=>typeof e[r]!="function"):t;if(n.length)throw new d("bad-input",{field:"wallet",missing:n});return e};function _6({sender:e=null,claimer:t=null}={}){let n=typeof e=="string"?e.trim().toLowerCase():"",r=typeof t=="string"?t.trim().toLowerCase():"";return r?n?n!==r?{ok:!1,code:"bad-input",field:"wallet",why:"not-the-claimer"}:{ok:!0}:{ok:!1,code:"bad-input",field:"wallet.address"}:{ok:!1,code:"bad-input",field:"claimer"}}var Rd=(e,t)=>{if(!e||typeof e!="object")throw new d("bad-input",{field:"request"});let n=A6(e,["escrow","expect",...t]);if(n.length)throw new d("bad-input",{field:"request",missing:n});return e},Hd=async(e,t)=>{try{return await t()}catch(n){throw n&&typeof n.code=="string"?n:new d("contract-reverted",{step:e})}};function Oi({call:e=null,blockTime:t=null}={}){let n=a=>{try{return a&&typeof a.driver=="function"?a.driver():null}catch{return null}},r=a=>{if(typeof e=="function")return e;let c=n(a);return!c||typeof c.request!="function"?async()=>{throw new d("wallet-not-connected",{surface:"actions.read"})}:async({to:l,data:u,from:f})=>{let h=f?{to:l,data:u,from:f}:{to:l,data:u},m=await c.request({method:"eth_call",params:[h,"latest"]});if(typeof m!="string"||!m.startsWith("0x"))throw new d("contract-reverted",{surface:"actions.read"});return m}},o=a=>typeof t=="function"?t:async()=>{try{let c=n(a);if(!c||typeof c.request!="function")return null;let l=await c.request({method:"eth_getBlockByNumber",params:["latest",!1]}),u=Number(l&&l.timestamp);return Number.isSafeInteger(u)&&u>0?u:null}catch{return null}},i=async(a,c)=>{let l=typeof a.address=="function"?await a.address():null;if(typeof l!="string"||!l.trim())throw new d("bad-input",{field:"wallet.address",step:c});return l},s=(a,c,l)=>({call:r(a),from:l,send:u=>a.send({...u,chainId:c,from:l}),receipt:u=>a.receipt(u),blockTime:o(a)});return{async markReady(a,c){Rd(a,[]),Cd(c);let{escrow:l,expect:u,onStep:f}=a,h=await i(c,"mark-ready");return await mo(c,u.chainId,"mark-ready"),await Hd("mark-ready",()=>Eb({escrow:l,expect:u,onStep:f,deps:s(c,u.chainId,h)}))},async claim(a,c){Rd(a,["halfClaimer"]),Cd(c);let{escrow:l,halfClaimer:u,expect:f,onStep:h}=a,m=await i(c,"claim"),w=_6({sender:m,claimer:a.claimer||f&&f.claimer});if(!w.ok)throw new d(w.code,{field:w.field,why:w.why,surface:"actions.claim"});return await mo(c,f.chainId,"claim"),await Hd("claim",()=>Sb({escrow:l,halfClaimer:u,expect:f,onStep:h,deps:s(c,f.chainId,m)}))},async refund(a,c){Rd(a,["halfLocker"]),Cd(c);let{escrow:l,halfLocker:u,expect:f,onStep:h}=a,m=await i(c,"refund");return await mo(c,f.chainId,"refund"),await Hd("refund",()=>vb({escrow:l,halfLocker:u,expect:f,onStep:h,deps:s(c,f.chainId,m)}))}}}fe();var Cn=e=>typeof e=="string"&&e.length>0,Qa=e=>{let t=Number(e);return Number.isFinite(t)?Math.trunc(t):null},I6=e=>Cn(e)?e.trim().replace(/^0x/,"").toLowerCase():null,Ib=e=>{try{return new URL(e).host}catch{throw new d("bad-input",{field:"nodes.url",unknown:e})}},fr=(e,t)=>{let n=e&&e.params||{},r="network",o=n.why===void 0||n.why===null?"":String(n.why),i=String(n.name||e&&e.name||"");n.status!==void 0&&n.status!==null?r="http":/^(TimeoutError|AbortError)$/.test(i)||/timeout|abort/i.test(o)||/timeout|abort/i.test(i)?r="timeout":(o==="bad-json"||o==="no-height"||o==="no-block"||o==="busy"||o==="partial-transactions")&&(r="bad-answer");let s={url:t.url,operator:t.operator,code:r};return n.status!==void 0&&n.status!==null&&(s.status=n.status),o&&(s.why=o),s};function Pb(e){if(!Array.isArray(e))throw new d("bad-input",{field:"nodes"});let t=[];for(let n of e)if(Cn(n)){let r=n.replace(/\/+$/,"");t.push({url:r,operator:Ib(r)})}else if(n&&typeof n=="object"&&Cn(n.url)){let r=n.url.replace(/\/+$/,""),o={url:r,operator:Cn(n.operator)?n.operator:Ib(r)};if(n.protocol!==void 0&&n.protocol!==null){if(!Cn(n.protocol))throw new d("bad-input",{field:"nodes.protocol"});o.protocol=n.protocol}t.push(o)}else throw new d("bad-input",{field:"nodes",why:"each-node-is-url-or-url+operator"});if(!t.length)throw new d("bad-input",{field:"nodes",why:"empty-list"});return t}async function Za(e,t,n,r,o){let i;try{i=await r(e.url+t,{method:"POST",headers:{"Content-Type":"text/plain"},body:JSON.stringify(n),signal:typeof AbortSignal<"u"&&AbortSignal.timeout?AbortSignal.timeout(o):void 0})}catch(s){throw new d("xmr-no-nodes",{node:e.url,name:String(s&&s.name||""),why:String(s&&s.message||s).slice(0,120)})}if(!i||i.ok!==!0)throw new d("xmr-no-nodes",{node:e.url,status:i?i.status:null});try{return await i.json()}catch(s){let a=String(s&&s.name||""),c=/^(TimeoutError|AbortError)$/.test(a)||/timeout|abort/i.test(a);throw new d("xmr-no-nodes",{node:e.url,name:a,why:c?"timeout":"bad-json"})}}async function Ld(e,t,n){let r=await Za(e,"/json_rpc",{jsonrpc:"2.0",id:"info",method:"get_info"},t,n),o=r&&r.result;if(!o||!Number.isFinite(Number(o.height)))throw new d("xmr-no-nodes",{node:e.url,why:"no-height"});if(o.busy===!0||o.busy_syncing===!0||typeof o.status=="string"&&o.status&&o.status!=="OK")throw new d("xmr-no-nodes",{node:e.url,why:"busy"});return{height:Number(o.height),synced:o.synchronized!==!1,nettype:o.nettype||null}}async function Bb(e,t,n,r){let o=await Za(e,"/json_rpc",{jsonrpc:"2.0",id:"block",method:"get_block",params:{height:t}},n,r),i=o&&o.result;if(!i)throw new d("xmr-no-nodes",{node:e.url,why:"no-block"});let s=i.block_header&&i.block_header.hash||null,a=Array.isArray(i.tx_hashes)?i.tx_hashes:null;if(!a){let c=typeof i.json=="string"?JSON.parse(i.json):i.json;a=c&&c.tx_hashes||[]}return{hash:s,txHashes:a}}async function Dd(e,t,n,r){if(!t.length)return[];let o=await Za(e,"/get_transactions",{txs_hashes:t,decode_as_json:!0},n,r),i=Array.isArray(o.txs)?o.txs:[],s=Array.isArray(o.txs_as_json)?o.txs_as_json:[];if(s.length!==t.length||i.length&&i.length!==t.length)throw new d("xmr-no-nodes",{node:e.url,why:"partial-transactions",want:t.length,got:s.length});let a=s.map((c,l)=>{let u;try{u=typeof c=="string"?JSON.parse(c):c}catch{throw new d("xmr-no-nodes",{node:e.url,why:"bad-json"})}let f=i[l]||{};return u.tx_hash=String(f.tx_hash||u.tx_hash||"").replace(/^0x/,"").toLowerCase(),u.block_height=f.block_height??null,u.confirmations=f.confirmations??null,u}).filter(c=>t.includes(String(c.tx_hash||"").toLowerCase()));if(a.length!==t.length)throw new d("xmr-no-nodes",{node:e.url,why:"partial-transactions",want:t.length,got:a.length});return a}var Ud=e=>e.outputs.reduce((t,n)=>t+(n.amountVerified&&n.amountAtomic||0n),0n);async function N6(e,{expectedAtomic:t,address:n,viewSecret:r,spendPub:o,fromHeight:i,toHeight:s,nowSec:a,fetchImpl:c,timeoutMs:l}){let u=Math.max(0,Qa(i)??0),f=Qa(s);if(!Number.isFinite(f)||f<u)throw new d("bad-input",{field:"fromHeight",got:i});let h=null;for(let m=u;m<=f;m++){let{txHashes:w}=await Bb(e,m,c,l);if(!w.length)continue;let x=await Dd(e,w,c,l);for(let y of x){let k=Ft.matchTransaction(y,[{address:n,viewSecret:r,spendPub:o}],{height:m,tipHeight:Math.max(0,f),nowSec:a});if(!k.length)continue;let I=Ud(k[0]),g=k[0].outputs.every(p=>p.amountVerified===!0),P=k[0].unlock&&k[0].unlock.locked===!0,E=(I>=t?4:0)+(g?2:0)+(P?0:1),B={txid:y.tx_hash,height:m};if(E===7)return B;(!h||E>h.score||E===h.score&&I>h.amountAtomic)&&(h={...B,score:E,amountAtomic:I})}}return h}async function Ci(e){if(!e||typeof e!="object")throw new d("bad-input",{field:"request"});let t=Pb(e.nodes);if(!Cn(e.address))throw new d("bad-input",{field:"address"});if(e.viewSecret===void 0||e.viewSecret===null)throw new d("bad-input",{field:"viewSecret"});if(!Cn(e.spendPub))throw new d("bad-input",{field:"spendPub"});let n;try{n=BigInt(e.expectedAtomic)}catch{throw new d("bad-input",{field:"expectedAtomic"})}if(n<=0n)throw new d("bad-input",{field:"expectedAtomic"});let r=Math.max(1,Qa(e.minConfirmations)??1),o=typeof e.fetch=="function"?e.fetch:globalThis.fetch;if(typeof o!="function")throw new d("bad-input",{field:"fetch"});let i=Number.isFinite(Number(e.nowSec))?Number(e.nowSec):Math.floor(Date.now()/1e3),s=Number.isFinite(Number(e.timeoutMs))&&Number(e.timeoutMs)>0?Number(e.timeoutMs):2e4,a=I6(e.txid),c;try{c=ei.decodeAddressKeys(e.address)}catch{throw new d("bad-input",{field:"address",why:"not-a-monero-address"})}if(!c.network)throw new d("bad-input",{field:"address",why:"subaddress-not-supported"});let l=String(e.spendPub).replace(/^0x/,"").toLowerCase();if(!c.spendPub||l!==String(c.spendPub).toLowerCase())throw new d("xmr-address-mismatch",{field:"spendPub",address:e.address});let u=Ft.viewKeyFormForAddress(e.viewSecret,c.viewPub);if(!u)throw new d("xmr-address-mismatch",{field:"viewSecret",address:e.address});let f=Ft.viewSecretCandidates(e.viewSecret).find(([A])=>A===u)?.[1]??e.viewSecret,h={address:e.address,viewSecret:f,spendPub:c.spendPub},m=[],w=[];for(let A of t)try{let O=await Ld(A,o,s);m.push({node:A,info:O})}catch(O){w.push(fr(O,A))}if(!m.length)throw new d("xmr-no-nodes",{tried:t.map(A=>A.url),nodes:w});let x=Math.max(...m.map(A=>A.info.height)),y=Math.max(0,x-1),k=null,I=new Set;for(let{node:A,info:O}of m){if(!O.synced){w.push({url:A.url,operator:A.operator,code:"stale",why:"not-synchronized"});continue}try{k=await N6(A,{expectedAtomic:n,address:e.address,viewSecret:f,spendPub:l,fromHeight:e.fromHeight,toHeight:y,nowSec:i,fetchImpl:o,timeoutMs:s}),k||I.add(A.operator)}catch(D){w.push(fr(D,A)),k=null}if(k)break}if(!k){if(!I.size){if(m.some(A=>!A.info.synced))return{seen:!1,state:"pending",absent:!1,txid:a,tip:x,completedOperators:[],checked:m.map(A=>({url:A.node.url,operator:A.node.operator,height:A.info.height,synchronized:A.info.synced})),failed:w};throw new d("xmr-no-nodes",{tried:t.map(A=>A.url),nodes:w})}return{seen:!1,state:"pending",absent:I.size>=2,txid:a,tip:x,completedOperators:[...I],checked:m.map(A=>({url:A.node.url,operator:A.node.operator,height:A.info.height})),failed:w}}let g=[];for(let A of t){let O={url:A.url,operator:A.operator},D;try{D=await Ld(A,o,s)}catch(j){O.state="down",O.failure=fr(j,A),w.push(O.failure),g.push(O);continue}if(!D.synced||D.height<k.height){O.state="stale",O.height=D.height,g.push(O);continue}O.height=D.height;let L;try{L=await Bb(A,k.height,o,s)}catch(j){O.state="down",O.failure=fr(j,A),w.push(O.failure),g.push(O);continue}if(O.blockHash=L.hash,!L.hash||!L.txHashes.includes(k.txid)){O.state="no-tx",g.push(O);continue}let V=null;try{V=(await Dd(A,L.txHashes,o,s)).find(j=>j.tx_hash===k.txid)||null}catch(j){O.state="down",O.failure=fr(j,A),w.push(O.failure),g.push(O);continue}if(!V){O.state="no-tx",g.push(O);continue}let U=Ft.matchTransaction(V,[h],{height:k.height,tipHeight:Math.max(0,D.height-1),nowSec:i});if(!U.length){O.state="no-output",g.push(O);continue}if(O.state="ok",O.amountAtomic=Ud(U[0]),O.amountVerified=U[0].outputs.every(j=>j.amountVerified===!0),O.outputs=U[0].outputs.map(j=>({index:j.index,key:String(j.key||"").replace(/^0x/,"").toLowerCase(),amountAtomic:j.amountVerified?String(j.amountAtomic??null):null,amountVerified:j.amountVerified===!0})),O.unlock=U[0].unlock,O.confirmations=Number.isFinite(Number(V.confirmations))?Number(V.confirmations):D.height-k.height,!O.amountVerified){O.state="amount-unverified",g.push(O);continue}O.observation={txid:k.txid,blockHash:String(L.hash||"").replace(/^0x/,"").toLowerCase(),outputs:O.outputs,unlock:O.unlock?{locked:O.unlock.locked===!0,untilHeight:O.unlock.untilHeight??null,untilTime:O.unlock.untilTime??null}:null},g.push(O)}let P=g.filter(A=>A.state==="no-tx"||A.state==="no-output"||A.state==="amount-unverified");if(P.length)throw new d("xmr-nodes-disagree",{txid:k.txid,height:k.height,nodes:P.map(A=>({url:A.url,operator:A.operator,blockHash:A.blockHash||null,why:A.state,outputs:A.outputs||null})),agreed:g.filter(A=>A.state==="ok").map(A=>({url:A.url,operator:A.operator,blockHash:A.blockHash})),failed:w});let E=g.filter(A=>A.state==="ok");if(!E.length)return{seen:!1,state:"pending",txid:k.txid,height:k.height,checked:g,failed:w};let B=new Map;for(let A of E){let O=JSON.stringify(A.observation);B.has(O)||B.set(O,{observation:A.observation,operators:new Set,nodes:[]});let D=B.get(O);D.operators.add(A.operator),D.nodes.push(A)}if(B.size>1)throw new d("xmr-nodes-disagree",{txid:k.txid,height:k.height,nodes:E.map(A=>({url:A.url,operator:A.operator,blockHash:A.blockHash||null,outputs:A.outputs,why:"observation"})),agreed:[],failed:w});let p=[...B.values()][0],b=Math.min(...p.nodes.map(A=>A.confirmations)),S=p.nodes[0].amountAtomic,v=p.nodes.map(A=>({url:A.url,operator:A.operator,blockHash:A.blockHash,confirmations:A.confirmations})),H=p.nodes.find(A=>A.unlock&&A.unlock.locked);if(H){let A=H.unlock;throw new d("xmr-locked",{txid:k.txid,height:k.height,address:e.address,untilHeight:A.untilHeight??null,untilTime:A.untilTime??null,failed:w})}if(S<n)throw new d("xmr-underpaid",{txid:k.txid,height:k.height,got:S.toString(),want:n.toString(),failed:w});return p.operators.size<2?{seen:!1,state:"one-node",txid:k.txid,height:k.height,blockHash:p.observation.blockHash,amountAtomic:S.toString(),confirmations:b,operators:[...p.operators],agreedBy:v,checked:g,failed:w}:b<r?{seen:!1,state:"pending",why:"confirmations",txid:k.txid,height:k.height,blockHash:p.observation.blockHash,amountAtomic:S.toString(),confirmations:b,needConfirmations:r,agreedBy:v,checked:g,failed:w}:{seen:!0,state:"arrived",txid:k.txid,height:k.height,blockHash:p.observation.blockHash,amountAtomic:S.toString(),confirmations:b,needConfirmations:r,operators:[...p.operators],agreedBy:v,checked:g,failed:w}}var pr=20;function Nb(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<0)throw new d("bad-input",{field:"height"});return Math.floor(t/pr)}function Fd(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<0)throw new d("bad-input",{field:"slice"});return t*pr}function T6(e){return Fd(e)+pr-1}var Tb=e=>{let t=String(e||"").replace(/^0x/,"").toLowerCase();return/^[0-9a-f]{64}$/.test(t)?t:null};function P6(e,{network:t,index:n}){if(!e||typeof e!="object")throw new d("xmr-no-nodes",{why:"bad-witness-slice"});if(Number(e.version)!==1)throw new d("xmr-no-nodes",{why:"bad-witness-version"});if(String(e.network)!==String(t))throw new d("xmr-no-nodes",{why:"witness-network"});if(Number(e.grid)!==pr)throw new d("xmr-no-nodes",{why:"witness-grid"});if(Number(e.slice)!==n)throw new d("xmr-no-nodes",{why:"witness-slice"});if(Number(e.from)!==Fd(n)||Number(e.to)!==T6(n))throw new d("xmr-no-nodes",{why:"witness-bounds"});if(!Array.isArray(e.blocks)||e.blocks.length!==pr)throw new d("xmr-no-nodes",{why:"witness-block-count"});let r=e.blocks.map((o,i)=>{if(!o||Number(o.height)!==Fd(n)+i)throw new d("xmr-no-nodes",{why:"witness-height"});let s=Tb(o.hash);if(!s)throw new d("xmr-no-nodes",{why:"witness-hash"});if(!Array.isArray(o.txids))throw new d("xmr-no-nodes",{why:"witness-txids"});let a=o.txids.map(c=>{let l=Tb(c);if(!l)throw new d("xmr-no-nodes",{why:"witness-txid"});return l});return{height:Number(o.height),hash:s,txids:a}});return{version:1,network:String(t),grid:pr,slice:n,from:e.from,to:e.to,blocks:r}}async function B6(e,t,{network:n,fetchImpl:r,timeoutMs:o}){if(e.protocol!=="witness-v1")throw new d("xmr-no-nodes",{node:e.url,why:"no-slice-witness"});let i=await Za(e,"/v1/witness/slice",{version:1,network:n,grid:pr,slice:t},r,o);return P6(i,{network:n,index:t})}async function O6(e,t,{fetchImpl:n,timeoutMs:r}){let o=[...new Set(t.blocks.flatMap(s=>s.txids))];if(!o.length)return new Map;if(o.length>4096)throw new d("xmr-no-nodes",{node:e.url,why:"slice-too-large",count:o.length});let i=await Dd(e,o,n,r);return new Map(i.map(s=>[String(s.tx_hash||"").toLowerCase(),s]))}async function C6(e,{expectedAtomic:t,address:n,viewSecret:r,spendPub:o,fromHeight:i,toHeight:s,nowSec:a,network:c,fetchImpl:l,timeoutMs:u}){let f=Nb(i),h=Nb(s),m=null,w=!0;for(let x=f;x<=h;x++){let y=await B6(e,x,{network:c,fetchImpl:l,timeoutMs:u}),k=await O6(e,y,{fetchImpl:l,timeoutMs:u});for(let I of y.blocks)for(let g of I.txids){let P=k.get(g);if(!P)continue;let E=Ft.matchTransaction(P,[{address:n,viewSecret:r,spendPub:o}],{height:I.height,tipHeight:Math.max(0,s),nowSec:a});if(!E.length)continue;let B=Ud(E[0]),p=E[0].outputs.every(H=>H.amountVerified===!0),b=E[0].unlock&&E[0].unlock.locked===!0,S=(B>=t?4:0)+(p?2:0)+(b?0:1),v={txid:g,height:I.height,blockHash:I.hash,amountAtomic:B,score:S};(!m||S>m.score||S===m.score&&B>m.amountAtomic)&&(m=v)}if(m&&m.score===7){w=x===h;break}}return{located:m,completed:w}}async function Ob(e){if(!e||typeof e!="object")throw new d("bad-input",{field:"request"});if(e.witnessNodes===void 0||e.witnessNodes===null)throw new d("bad-input",{field:"witnessNodes",why:"required"});let t=Pb(e.witnessNodes);if(!t.some(E=>E.protocol==="witness-v1"))throw new d("bad-input",{field:"witnessNodes",why:"no-witness-v1"});let n;try{n=ei.decodeAddressKeys(e.address)}catch{throw new d("bad-input",{field:"address",why:"not-a-monero-address"})}if(!n.network)throw new d("bad-input",{field:"address",why:"subaddress-not-supported"});let r=e.network||n.network,o=typeof e.fetch=="function"?e.fetch:globalThis.fetch;if(typeof o!="function")throw new d("bad-input",{field:"fetch"});let i=Number.isFinite(Number(e.timeoutMs))&&Number(e.timeoutMs)>0?Number(e.timeoutMs):2e4,s=Number.isFinite(Number(e.nowSec))?Number(e.nowSec):Math.floor(Date.now()/1e3),a=Number(e.fromHeight);if(!Number.isSafeInteger(a)||a<=0)throw new d("bad-input",{field:"fromHeight"});let c;try{c=BigInt(e.expectedAtomic)}catch{throw new d("bad-input",{field:"expectedAtomic"})}if(c<=0n)throw new d("bad-input",{field:"expectedAtomic"});if(!Cn(e.spendPub))throw new d("bad-input",{field:"spendPub"});if(e.viewSecret===void 0||e.viewSecret===null)throw new d("bad-input",{field:"viewSecret"});let l=String(e.spendPub).replace(/^0x/,"").toLowerCase();if(l!==String(n.spendPub).toLowerCase())throw new d("xmr-address-mismatch",{field:"spendPub",address:e.address});let u=Ft.viewKeyFormForAddress(e.viewSecret,n.viewPub);if(!u)throw new d("xmr-address-mismatch",{field:"viewSecret",address:e.address});let f=Ft.viewSecretCandidates(e.viewSecret).find(([E])=>E===u)?.[1]??e.viewSecret,h=null,m=null;try{h=await Ci(e)}catch(E){m={code:E&&E.code?E.code:"unknown",params:E&&E.params||{}}}let w=[],x=[],y=null,k=!1;for(let E of t){if(E.protocol!=="witness-v1"){x.push({url:E.url,operator:E.operator,code:"no-slice-witness"});continue}let B;try{B=await Ld(E,o,i)}catch(b){x.push(fr(b,E)),w.push({url:E.url,operator:E.operator,state:"down"});continue}if(!B.synced){x.push({url:E.url,operator:E.operator,code:"stale",why:"not-synchronized"}),w.push({url:E.url,operator:E.operator,state:"stale",height:B.height});continue}let p=Math.max(0,B.height-1);w.push({url:E.url,operator:E.operator,state:"ok",height:B.height});try{let b=await C6(E,{expectedAtomic:c,address:e.address,viewSecret:f,spendPub:l,fromHeight:a,toHeight:p,nowSec:s,network:r,fetchImpl:o,timeoutMs:i});k=k||b.completed,b.located&&(!y||b.located.score>y.score)&&(y=b.located,y.operator=E.operator,y.url=E.url)}catch(b){x.push(fr(b,E))}}let I=y?{state:"seen",txid:y.txid,height:y.height,blockHash:y.blockHash,amountAtomic:y.amountAtomic.toString(),operator:y.operator,url:y.url,completed:k,checked:w,failed:x}:{state:"pending",txid:null,height:null,blockHash:null,amountAtomic:null,completed:k,checked:w,failed:x},g=[],P=null;return m&&g.push("exact:"+m.code),y&&h&&h.txid?(String(h.txid).toLowerCase()!==y.txid&&g.push("txid"),Number(h.height)!==y.height&&g.push("height"),String(h.blockHash||"").toLowerCase()!==y.blockHash&&g.push("blockHash"),String(h.amountAtomic??"")!==y.amountAtomic.toString()&&g.push("amount"),P=g.length===0):y?(g.push("exact:no-transaction"),P=!1):h&&h.absent===!0&&(I.completed&&I.failed.length===0?P=!0:(P=!1,g.push("witness:not-completed"))),{exact:h,exactError:m,witness:I,agrees:P,problems:g}}function Md({readyBySec:e,nowSec:t,minConfirmations:n,blockTimeSec:r,minLeadSec:o=null}={}){let i=Number(e),s=Number.isFinite(Number(t))?Number(t):Math.floor(Date.now()/1e3),a=Math.max(1,Qa(n)??1),c=Number.isFinite(Number(r))&&Number(r)>0?Number(r):120;if(!Number.isFinite(i)||i<=0)return null;let l=Number.isFinite(Number(o))&&Number(o)>0?Number(o):0,u=Math.max(a*c,l),f=Math.floor(i-s);if(f<u)throw new d("xmr-too-late",{needSec:u,leftSec:f,minConfirmations:a,readyBy:Math.floor(i)});return f}fe();var Cb=/^0x[0-9a-f]{40}$/,H6=/^[0-9a-f]{64}$/,L6=/^0x[0-9a-f]{64}$/,F6=/^(0|[1-9][0-9]*)$/;function wo(e){let t=String(e??"").trim().replace(/\/+$/,"");if(!t)throw new d("bad-input",{field:"relayUrl"});if(!/^https:\/\//i.test(t))throw new d("bad-input",{field:"relayUrl",why:"not-https"});return t}function ct(e,t){let n=String(e??"").trim().toLowerCase();if(!Cb.test(n))throw new d("bad-input",{field:t});return n}function Kd(e){let t=String(e??"").trim().toLowerCase().replace(/^0x/,"");if(!H6.test(t))throw new d("bad-input",{field:"halfClaimer",why:"not-in-record"});return"0x"+t}async function Rb({relayUrl:e,provider:t,escrow:n,halfClaimer:r,expectedTipWei:o,fetchImpl:i=null,timeoutMs:s=2e4}={}){let a=wo(e),c=ct(t,"provider"),l=ct(n,"escrow"),u=Kd(r),f=nt({apiBase:a,fetchImpl:i,timeoutMs:s}),h=JSON.stringify({version:1,halfClaimer:u}),m;try{m=await f.tryJson(`/v1/claims/${c}/${l}`,{method:"POST",headers:{"content-type":"application/json"},body:h})}catch(B){throw B instanceof d&&B.code==="bad-input"?B:new d("claim-unknown",{step:"relay-claim",why:B&&B.params&&B.params.why||"answer-lost",outcome:"unknown"})}let w=m.body&&typeof m.body=="object"?m.body:null,x=w?Number(w.version):null,y=w&&typeof w.code=="string"&&w.code?w.code:null;if(!m.ok)throw y==="claim-unknown"||y==="claim_unknown"?new d("claim-unknown",{step:"relay-claim",why:"relay-timeout",code:y,status:m.status,outcome:"unknown"}):y&&x===1?new d("quote-refused",{step:"relay-claim",code:y,status:m.status}):new d("claim-unknown",{step:"relay-claim",why:"answer-status",status:m.status,outcome:"unknown"});if(!w||x!==1)throw new d("claim-unknown",{step:"relay-claim",why:"answer",outcome:"unknown"});if(y)throw new d("quote-refused",{step:"relay-claim",code:y,status:m.status});let k=String(w.txid===void 0||w.txid===null?"":w.txid).trim().toLowerCase();if(!L6.test(k))throw new d("claim-unknown",{step:"relay-claim",why:"answer-txid",outcome:"unknown"});let I=String(w.from===void 0||w.from===null?"":w.from).trim().toLowerCase();if(!Cb.test(I))throw new d("claim-unknown",{step:"relay-claim",why:"answer-from",outcome:"unknown"});let g=String(w.tipWei===void 0||w.tipWei===null?"":w.tipWei).trim();if(!F6.test(g))throw new d("claim-unknown",{step:"relay-claim",why:"answer-tip",outcome:"unknown"});let P=String(w.provider===void 0||w.provider===null?"":w.provider).trim().toLowerCase(),E=String(w.escrow===void 0||w.escrow===null?"":w.escrow).trim().toLowerCase();if(!P||!E)throw new d("claim-unknown",{step:"relay-claim",why:"answer-binding",outcome:"unknown"});if(P!==c)throw new d("quote-refused",{step:"relay-claim",why:"answer-provider"});if(E!==l)throw new d("quote-refused",{step:"relay-claim",why:"answer-escrow"});if(BigInt(g)!==BigInt(o))throw new d("quote-refused",{step:"relay-claim",why:"tip",tipWei:g,expectedTipWei:String(o)});return{txid:k,from:I,tipWei:g}}var U6={success:"success",refund_eth:"refunded_eth",[rn]:rn},Rn=e=>{if(e==null||e==="")return null;let t=Number(e);return Number.isFinite(t)?t:null};function M6(e){let t=e&&e.escrow||{};if(typeof t.viewHalf!="string"||!t.viewHalf)throw new d("bad-input",{field:"viewHalf"});if(typeof t.counterViewHalf!="string"||!t.counterViewHalf)throw new d("bad-input",{field:"counterViewHalf"});try{return Yt.createHalves(Xt).combineHalves(BigInt(t.viewHalf),BigInt(t.counterViewHalf)).toString(16).padStart(64,"0")}catch{throw new d("bad-input",{field:"viewKey"})}}function Hb(e){if(!e||typeof e!="object"||!e.id)throw new d("bad-input",{field:"swap"});let t=ue.derive(e),n=[],r=Array.isArray(t.steps)?t.steps:[],o=r.find(u=>u.key==="funded")||null;n.push({code:"awaiting_funding",done:!!(o&&o.done),active:!(o&&o.done),at:null});for(let u of r)n.push({code:u.key,done:!!u.done,active:!!u.active,failed:!!u.failed,at:t.simulated&&t.simulated.evm?u.atSim??null:null});let i=n.find(u=>u.active)||[...n].reverse().find(u=>u.done)||n[0],s=t.terminal?U6[t.terminal.kind]??"closed":null,a=s===rn,c=e.network||e.chain||null,l=c&&Nu(c)||"unknown";return{id:e.id,direction:e.side==="sell"?"sell":"buy",createdAt:e.createdAt??null,maker:{id:e.makerId!==void 0&&e.makerId!==null?e.makerId:(e.maker&&e.maker.id)??null,name:e.makerName!==void 0&&e.makerName!==null?e.makerName:(e.maker&&e.maker.name)??null},phase:t.phase||null,phaseLabel:t.phaseLabel||null,settled:!!e.settlement,funds:{receivedXmr:e.xmrSession!==null&&e.xmrSession!==void 0||e.xmr&&(e.xmr.received!==void 0||e.xmr.arrived!==void 0)?Rn(t.xmrAmount&&t.xmrAmount.seen):null,escrowLocked:!!(e.escrow&&(e.escrow.fundTx||e.escrow.secret))},pay:{token:e.payToken||"eth",amount:Rn(e.payAmount)},get:{xmr:Rn(e.xmrAmount)},step:i.code,steps:n,deadlines:{readyBy:t.deadlines&&t.deadlines.readyBy!==void 0?Rn(t.deadlines.readyBy):null,t1:t.deadlines&&t.deadlines.t1!==void 0?Rn(t.deadlines.t1):null},xmr:{confirmations:Rn(t.xmr&&(t.xmr.confirmations!==void 0?t.xmr.confirmations:t.conf))??0,target:Rn(t.xmr&&t.xmr.confTarget)??Rn(t.confTarget)??0,txid:t.xmr&&Array.isArray(t.xmr.txids)&&t.xmr.txids[0]||null,amount:{expected:t.xmrAmount?t.xmrAmount.expected??null:null,seen:t.xmrAmount?t.xmrAmount.seen??null:null}},counterparty:{chain:c,vm:l,leg:e.escrow&&(e.escrow.address||e.escrow.leg)||null,status:t.phase||null,txs:e.escrow&&(e.escrow.txids||e.escrow.txs)||[]},actions:a?{markReady:!1,sweep:!1,refund:!1}:{markReady:!!(t.can&&t.can.ready),sweep:!!(t.can&&t.can.sweep),refund:!!(t.can&&t.can.refund)},simulated:{evm:!!(t.simulated&&t.simulated.evm),xmr:!!(t.simulated&&t.simulated.xmr)},terminal:s}}var Lb=12,Fb=(e,t=null)=>{let n=e&&e.quote&&typeof e.quote=="object"?e.quote:{},r=s=>s==null||s===""?void 0:s,o=e&&e.order&&e.order.xmrAmount!==void 0&&e.order.xmrAmount!==null?String(e.order.xmrAmount):null,i=e&&e.orderQuote&&e.orderQuote.xmrAmount!==void 0&&e.orderQuote.xmrAmount!==null?String(e.orderQuote.xmrAmount):null;if(o!==null&&i!==null&&o!==i)throw new d("bad-input",{field:"xmrAmount",why:"order-vs-quote"});return{side:e.side||"buy",network:n.chain?n.chain:void 0,moneroNetwork:e.moneroNetwork||t||void 0,payToken:n.asset?String(n.asset).toLowerCase():void 0,payAmount:n.amount!==void 0?n.amount:void 0,xmrAmount:n.size!==void 0?n.size:void 0,expectedAtomic:i!==null?i:o!==null?o:void 0,orderQuoteId:r(n.id),receiveAddress:r(e.receiveTo),makerId:r(n.makerId),makerName:r(n.makerName),makerSpread:r(n.makerSpread),quoteSignature:r(n.signature),fee:r(n.ninseiFee),dexSpread:r(n.dexSpread),gasUsd:r(n.gasUsd),rate:r(n.rate)}};async function K6({nodes:e=[],network:t=null,fetchImpl:n=globalThis.fetch}={}){let r=(Array.isArray(e)?e:[]).map(a=>typeof a=="string"?a:a&&a.url).filter(Boolean),o=await Promise.all(r.map(async a=>{try{return await Ty({url:a,fetchImpl:n})}catch{return{ok:!1,why:"unreachable"}}})),i=o.filter(a=>a.ok===!0&&(!t||a.network===t));if(i.length){let a=i.map(u=>Number(u.height)).filter(u=>Number.isSafeInteger(u)&&u>=0);if(!a.length)throw new d("xmr-no-nodes",{step:"restore-height",network:t||null,why:"no-height"});let c=Math.min(...a),l=Math.max(...a);if(l-c>100)throw new d("xmr-no-nodes",{step:"restore-height",network:t||null,why:"disagree",low:c,high:l});return c}let s=o.find(a=>a.ok===!0)?"network":o[0]&&o[0].why||"no-node";throw new d("xmr-no-nodes",{step:"restore-height",network:t||null,why:s})}var j6=300;function W6({configuredMs:e=12e5,readyBySec:t=null,nowSec:n=Math.floor(Date.now()/1e3)}={}){let r=Number.isFinite(Number(e))&&Number(e)>0?Number(e):12e5,o=Number(t),i=Number(n);return!Number.isSafeInteger(o)||!Number.isSafeInteger(i)||o<=i?r:Math.max(r,(o-i+j6)*1e3)}function V6(e,t,n){if(!e||!(e.fundingPending===!0||e.escrow&&e.escrow.fundingPending===!0))return!1;let r=String(t||""),o=String(n||"").replace(/^0x/i,"").toLowerCase();if(!r&&!o)return!1;let i=String(e.orderQuoteId||""),s=String(e.escrow&&e.escrow.salt||e.recoverySalt||"").replace(/^0x/i,"").toLowerCase();return!!(o&&s===o)}function $6(e,t,n){if(!!!(e&&(e.fundingPending===!0||e.escrow&&e.escrow.fundingPending===!0)))return"not-pending";let o=String(t||""),i=String(n||"").replace(/^0x/i,"").toLowerCase();return o&&String(e.orderQuoteId||"")===o&&!i?"salt-required":V6(e,o,i)?"resume":"different"}function z6(e,t){try{let n=e.loadState(),r=String(t||"").toLowerCase();for(let o of Object.values(n&&n.swaps||{}))if(o&&o.escrow&&String(o.escrow.address||"").toLowerCase()===r)return o}catch{}return null}function jd({preflight:e,createRecord:t,mode:n=null,xmrNetwork:r=null,call:o=null,now:i=null,evmBlock:s=null,store:a=Xn,config:c=null,denylist:l=null,watch:u=null,logs:f=null}={}){let h=typeof o=="function"?o:Ue.readContract,m=async(p=null)=>{let b=null;if(typeof s=="function")b=await s("latest");else if(p&&typeof p.driver=="function"){let H=p.driver();if(H&&typeof H.request=="function"){let A=await H.request({method:"eth_blockNumber"});typeof A=="string"&&/^0x[0-9a-f]+$/i.test(A)&&(b=await H.request({method:"eth_getBlockByNumber",params:[A,!1]}))}}let S=b&&Number(b.number),v=b&&Number(b.timestamp);return!Number.isSafeInteger(S)||S<0||!Number.isFinite(v)||v<=0?null:{blockTag:"0x"+S.toString(16),timestamp:v}},w=Ya(f),x=Oi({call:typeof o=="function"?o:null}),y=(p,b)=>{let S=c&&c.limits?c.limits[p]:null;return Number.isFinite(Number(S))&&Number(S)>0?Number(S):b};async function k(p,b){let S=Number(p.restoreHeight);if(Number.isSafeInteger(S)&&S>0)return S;let v=Array.isArray(p.xmrNodes)?p.xmrNodes:c&&typeof c.nodesFor=="function"?c.nodesFor(b):[];return K6({nodes:v,network:b,fetchImpl:p.fetchImpl||(typeof fetch=="function"?fetch:null)})}let I=()=>{let p=a.loadState();return Object.values(p&&p.swaps||{}).filter(S=>S&&S.id).sort((S,v)=>Number(v.createdAt||0)-Number(S.createdAt||0))},g=(p,b)=>{let S=String(p||""),v=String(b||"").replace(/^0x/i,"").toLowerCase();if(!S&&!v)return null;for(let H of I()){let A=$6(H,S,v);if(A==="salt-required")throw new d("bad-input",{field:"recoverySalt",why:"required-for-pending-funding"});if(A==="resume")return H}return null};async function P(p,b){let S=p.swap||p,v=S.escrow&&typeof S.escrow=="object"?S.escrow:{},H=v.fundTx||S.fundTx||null,A=null;if(v.address)try{A=await ur(v.address,{call:h})}catch(U){/short .*status\(\)/.test(String(U&&U.message||U))?A={isFunded:!1,absent:!0}:A=null}if(!H&&A&&!A.isFunded&&v.fundingReason==="not-sent"){delete S.fundingPending,S.escrow={...v,fundingPending:!1,fundingReason:"send-not-started"};try{ue.saveSwap(S,a)}catch{throw new d("storage-unavailable",{step:"save-pending"})}return null}if(!H&&!(A&&A.isFunded))return{id:S.id||null,escrow:v.address||null,address:p.swapWallet&&p.swapWallet.address||null,step:"funding-pending",txHash:null,reason:"no-transaction-hash",next:"receipt"};let O=b.wallet,D=null;if(H&&O&&typeof O.receipt=="function")try{D=await O.receipt(H)}catch{D=null}let L=b.order&&typeof b.order=="object"?b.order:{},V=Ds(D,{factory:L.factory||b.orderQuote&&b.orderQuote.factory||null,expectedEscrow:v.address||null});if(V.status==="reverted")throw new d("contract-reverted",{step:"funding"});if(V.status==="funded"||A&&A.isFunded){let U=V.status==="funded"?V.escrow:v.address;if(!U)throw new d("funding-pending",{reason:"no-escrow-address"});S.escrow={...v,address:U,fundingPending:!1,evmBirthBlock:Number(V.birthBlock)>0?Number(V.birthBlock):v.evmBirthBlock??null},delete S.fundingPending;try{ue.saveSwap(S,a)}catch{throw new d("storage-unavailable",{step:"save-escrow"})}return{id:S.id||null,escrow:U,address:p.swapWallet&&p.swapWallet.address||null,step:"xmr-incoming",next:"watch"}}return{id:S.id||null,escrow:v.address||null,address:p.swapWallet&&p.swapWallet.address||null,step:"funding-pending",txHash:H,reason:V.reason||"no-receipt",next:"receipt"}}async function E(p){let b=p.order&&typeof p.order=="object"?p.order:{},S=b.amount,v=S==null||S===""?null:String(S),H=Number(b.chainId),A=Number.isFinite(H)?ce.chainByChainId(H):null,O=A?ce.tokensOf(A.id):[],D=String(p.quote&&(p.quote.token||p.quote.asset)||"").toLowerCase(),L=O.find(F=>String(F.symbol).toLowerCase()===D)||null,V=O.find(F=>!F.address)||null,U=!!(L&&!L.address),j={tokenIsNative:U,standIn:!p.counterparty&&n!=="live",liveChain:!!(A&&A.escrow&&A.escrow.mode==="live"&&!A.testnet)};v!==null&&(j.payAmountWei=v,j.requiredNativeWei=v);try{let F=p.wallet,R=F&&typeof F.driver=="function"?F.driver():null,_=F&&typeof F.address=="function"?await F.address():null,N=Qr("evm"),W=X=>String(X.symbol).toLowerCase(),$=[];if(V&&$.push({id:W(V),symbol:V.symbol,decimals:V.decimals,address:null}),L&&L.address&&$.push({id:W(L),symbol:L.symbol,decimals:L.decimals,address:L.address}),R&&_&&N&&typeof N.balances=="function"&&$.length){let X=await N.balances({driver:R,address:_,tokens:$}),Y=ne=>{let oe=ne?X.find(T=>T.token===W(ne)):null;return oe&&oe.amount!==null?oe.amount:null},G=V?Y(V):null;G!==null&&(j.nativeBalanceWei=G);let Z=U?G:Y(L);Z!==null&&(j.payBalanceWei=Z)}}catch{}return j}async function B(p,b,S=null){if(!p||!b)throw new d("bad-input",{field:"escrow"});let v=null;try{v=await m(S)}catch{throw new d("quote-refused",{step:"send-xmr",why:"block-unreadable"})}let H={call:h,blockTag:v?v.blockTag:"latest"},A=v?v.timestamp:Math.floor((typeof i=="function"?i():Date.now())/1e3),O=null;try{O=await ur(p,H)}catch{throw new d("quote-refused",{step:"send-xmr",why:"escrow-unreadable"})}if(!O||O.isFunded!==!0||O.isClaimed===!0||O.isRefunded===!0)throw new d("quote-refused",{step:"send-xmr",why:"escrow-not-open"});let D=null;try{D=await dr(p,H)}catch{throw new d("quote-refused",{step:"send-xmr",why:"deadline-unreadable"})}if(Number(D.readyBy)!==Number(b.readyBy)||Number(D.t1)!==Number(b.t1))throw new d("quote-refused",{step:"send-xmr",why:"terms-mismatch"});let L=Math.max(1,Number(y("xmrConfirmations",10))),V=Math.max(1,Number(y("xmrBlockTimeSec",120))),U=Number(y("sellReadyLeadSec",0)),j=Number.isFinite(U)&&U>0?U:L*V;if(A+j>=Number(D.readyBy))throw new d("quote-refused",{step:"send-xmr",why:"deadline-too-close"});try{await Bi(p,b,"send-xmr",H)}catch(F){throw F&&F.code==="contract-reverted"?F:new d("quote-refused",{step:"send-xmr",why:"slots-unreadable"})}}return{async list(){return I().map(Hb)},async get(p){if(typeof p!="string"||!p)throw new d("bad-input",{field:"id"});let b=I().find(S=>S.id===p);return b?Hb(b):null},async progress(p){if(typeof p!="string"||!p)throw new d("bad-input",{field:"id"});let b=ue.getSwap(p,a);return b?{id:String(b.id||p),swap:b,swapWallet:ue.halvesWalletOf(b),view:ue.derive(b)}:null},async confirmReady(p){if(typeof p!="string"||!p)throw new d("bad-input",{field:"id"});return ue.confirmReady(p,a)},async refundEth(p,b="you"){if(typeof p!="string"||!p)throw new d("bad-input",{field:"id"});return ue.refundEth(p,b,a)},async sweepNow(p){if(typeof p!="string"||!p)throw new d("bad-input",{field:"id"});return ue.sweepNow(p,a)},async setDestination(p,b){if(typeof p!="string"||!p)throw new d("bad-input",{field:"id"});if(typeof b!="string"||!b)throw new d("bad-input",{field:"address"});let S=ue.getSwap(p,a);return S?(S.receiveAddress=b,ue.saveSwap(S,a)):null},async addressNetwork(p){if(typeof p!="string"||!p)return null;try{return mn.networkFromShape(p)}catch{return null}},async forget(p){if(typeof p!="string"||!p)throw new d("bad-input",{field:"id"});let b=null;try{b=a.loadState()}catch{throw new d("storage-unavailable",{step:"forget"})}let S=b&&b.swaps;if(!S||!S[p])return!1;delete S[p];try{a.saveState(b)}catch{throw new d("storage-unavailable",{step:"forget"})}return!0},verifyArrival:p=>Ci(p),verifyArrivalShadow:p=>Ob(p),assertTimeForConfirmations:p=>Md(p),async refundIfXmrMissing(p={},b={}){let S=typeof b.verify=="function"?b.verify:Ci,v=typeof b.refund=="function"?b.refund:x.refund,H=typeof b.now=="function"?b.now:()=>Math.floor(Date.now()/1e3);if(!p||typeof p!="object")throw new d("bad-input",{field:"request"});let A=p.swap&&typeof p.swap=="object"?p.swap:null,O=A&&A.escrow||{},D=p.escrow||O.address||null;if(!D)throw new d("bad-input",{field:"escrow"});let L=p.halfLocker||O.half||null;if(!L)throw new d("bad-input",{field:"halfLocker"});if(!p.expect||typeof p.expect!="object")throw new d("bad-input",{field:"expect"});let V=p.address||O.moneroAddress||null;if(!V)throw new d("bad-input",{field:"address"});let U=p.viewSecret!==void 0&&p.viewSecret!==null?p.viewSecret:A?M6(A):null;if(U==null)throw new d("bad-input",{field:"viewSecret"});let j=p.spendPub||O.moneroSpendPub||null;if(!j)throw new d("bad-input",{field:"spendPub"});let F=p.expectedAtomic!==void 0&&p.expectedAtomic!==null?p.expectedAtomic:O.expectedAtomic!==void 0&&O.expectedAtomic!==null?O.expectedAtomic:null;if(F===null)throw new d("bad-input",{field:"expectedAtomic",why:"unsigned-amount"});let R=Number(p.readyBySec!==void 0&&p.readyBySec!==null?p.readyBySec:O.readyBy);if(!Number.isFinite(R)||R<=0)throw new d("bad-input",{field:"readyBySec"});let _=Number.isFinite(Number(p.minConfirmations))&&Number(p.minConfirmations)>0?Math.trunc(Number(p.minConfirmations)):y("xmrConfirmations",10),N=Number.isFinite(Number(p.leadSec))&&Number(p.leadSec)>=0?Number(p.leadSec):(()=>{let Z=p.readyWindow||A&&(A.readyWindow||A.sellWindow);if(!Z)throw new d("bad-input",{field:"readyWindow",why:"not-in-record"});return tb(xt(Z,{field:"readyWindow"}))})(),W=p.fromHeight!==void 0&&p.fromHeight!==null?Number(p.fromHeight):Number(A&&(A.restoreHeight??O.moneroRestoreHeight??O.restoreHeight));if(!Number.isSafeInteger(W)||W<=0)throw new d("bad-input",{field:"fromHeight",why:"missing"});let $=Number.isFinite(Number(p.nowSec))?Number(p.nowSec):H(),X=Math.floor(R-$);if(X<=0)return{refunded:!1,state:"claim-window",leftSec:X,readyBy:R,nowSec:$};if(X>N)return{refunded:!1,state:"waiting",leftSec:X,needSec:N,readyBy:R,nowSec:$};let Y=null;try{Y=await S({nodes:p.nodes,address:V,viewSecret:U,spendPub:j,expectedAtomic:F,minConfirmations:_,txid:p.txid||null,fromHeight:W,timeoutMs:p.timeoutMs,nowSec:$})}catch(Z){if(Z&&Z.code==="xmr-underpaid")return{refunded:!1,state:"arrival-underpaid",leftSec:X,verdict:null,error:Z.params||null};if(Z&&Z.code==="xmr-locked")return{refunded:!1,state:"arrival-locked",leftSec:X,verdict:null,error:Z.params||null};throw Z}if(Y.seen)return{refunded:!1,state:"arrived",leftSec:X,verdict:Y};if(!Y||Y.absent!==!0)return{refunded:!1,state:"arrival-pending",leftSec:X,verdict:Y};let G=await v({escrow:D,halfLocker:L,expect:p.expect,onStep:p.onStep},p.wallet);return{refunded:!0,state:"refunded",hash:G&&G.hash||null,leftSec:X,verified:Y}},async start(p){if(!p||typeof p!="object")throw new d("bad-input",{field:"request"});if(p.side==="sell")throw new d("bad-input",{field:"side",why:"sell-not-supported",surface:"swaps.start"});if(!p.quote||typeof p.quote!="object")throw new d("bad-input",{field:"quote"});if(p.recoveryKey===void 0||p.recoveryKey===null)throw new d("bad-input",{field:"recoveryKey",why:"required"});if(!p.receiveTo||typeof p.receiveTo!="string")throw new d("bad-input",{field:"receiveTo"});if(!Fb(p,r).expectedAtomic)throw new d("bad-input",{field:"expectedAtomic",why:"signed-amount-missing"});let b=p.orderQuote&&p.orderQuote.id||p.quote&&p.quote.id||null,S=p.recoverySalt||p.order&&p.order.salt||p.orderQuote&&p.orderQuote.salt||null,v=g(b,S);if(v){let C=await P(v,p);if(C)return C}if(p.recoverySalt===void 0||p.recoverySalt===null){if(!p.order||typeof p.order!="object")throw new d("bad-input",{field:"order"});(p.order.salt===void 0||p.order.salt===null||p.order.salt==="")&&(p.order={...p.order,salt:Ly()}),p.recoverySalt=p.order.salt}let H=await E(p),A=e?await e(p.quote,H):null,D=(A&&(A.checks||A.results)||[]).filter(C=>C&&C.blocks===!0);if(D.length){let C=D[0];throw new d(C.code||"bad-input",{...C.params||{},kind:C.kind,surface:"swaps.start"})}let L=null,V=null,U=typeof t=="function"?t:async C=>_d(Fb(C,r),{order:C.order,side:L,store:a}),j=typeof p.passphrase=="string"?p.passphrase:"";if(typeof j!="string")throw new d("bad-input",{field:"passphrase"});if(j.length>0&&j.length<Lb)throw new d("bad-input",{field:"passphrase",min:Lb});let F=_t(p.order),R=null;{let C=a.storage(),q=typeof p.recoveryKey=="string"?p.recoveryKey:p.recoveryKey&&typeof p.recoveryKey.mnemonic=="string"?p.recoveryKey.mnemonic:null,J=Mu(C);if(J&&q&&J.mnemonic!==q)throw new d("bad-input",{field:"recoveryKey",why:"different-key"});if(!J&&!q)throw new d("bad-input",{field:"recoveryKey"});let le=J||Lu(q);J||ui(C,{...le,backupConfirmed:!1});let re=p.order.chainId;if(typeof p.order.factory!="string"||!p.order.factory)throw new d("bad-input",{field:"order.factory"});let ae;try{ae=Zt(p.recoverySalt)}catch{throw new d("bad-input",{field:"recoverySalt"})}let Ge;try{Ge=Zt(p.order.salt)}catch{throw new d("bad-input",{field:"recoverySalt",why:"order-salt"})}if(ae!==Ge)throw new d("bad-input",{field:"recoverySalt",why:"order-salt"});let ie=ir({mnemonic:le.mnemonic,chainId:re,factory:p.order.factory,salt:ae});R={storage:C,key:le,salt:ae,derivation:"salt-v2",newKey:!J||J.backupConfirmed!==!0},L=zu(p.order,{spendHalf:ie.spendHalf,viewHalf:ie.viewHalf}).side,V={half:ie.makerViewHalf,point:ie.makerViewPoint}}if(V){let C=p.counterparty&&typeof p.counterparty=="object"?p.counterparty:null,q=ju(C);if(q.half===null)throw new d("quote-field-unbound",{step:"viewHalfClaimer",field:"viewHalfClaimer"});let J=!1;try{J=BigInt(q.half)===BigInt(V.half)}catch{J=!1}if(!J)throw new d("quote-refused",{step:"viewHalfClaimer",why:"not-the-derived-half"});if(q.point!==null&&String(q.point).replace(/^0x/,"").toLowerCase()!==String(V.point).replace(/^0x/,"").toLowerCase())throw new d("quote-refused",{step:"viewHalfClaimer",why:"point-mismatch"})}let _=null;try{_=await U(p)}catch(C){throw C&&typeof C.code=="string"?C:new d("storage-unavailable",{step:"create-record"})}if(!_||!_.swap)throw new d("bad-input",{field:"record"});let N=_,W=p.readyWindow||p.quote&&p.quote.readyWindow||null,$=null;W&&($=xt(W,{side:"ask",field:"readyWindow"}),N.swap.readyWindow=$);let X=null;if(!N.swapWallet){let C=await jy({order:p.order,side:_.side||null,counterparty:p.counterparty||null,standIn:n!=="live",network:N.swap.moneroNetwork||r||null}),q=N.swap.escrow&&typeof N.swap.escrow=="object"?N.swap.escrow:{};N.swap.escrow={...q,half:C.wallet.spendHalf,viewHalf:C.wallet.viewHalf,edPointLocker:C.own.spendPoint,edViewPointLocker:C.own.viewPoint,edPointClaimer:C.wallet.otherSpendPoint,counterViewPoint:C.wallet.otherViewPoint,counterViewHalf:C.wallet.otherViewHalf,moneroAddress:C.wallet.address,moneroSpendPub:C.wallet.spendPub,moneroViewPub:C.wallet.viewPub,moneroNetwork:C.wallet.network,standIn:C.counterparty.standIn,providerId:C.counterparty.providerId,orderContext:C.context};try{ue.saveSwap(N.swap,a)}catch{throw new d("storage-unavailable",{step:"save-swap"})}if(N={...N,swapWallet:ue.halvesWalletOf(N.swap)},!N.swapWallet)throw new d("bad-input",{field:"swapWallet"});X=C}let Y=await k(p,N.swap.moneroNetwork||r||null);N.swap.restoreHeight=Y,N.restoreHeight=Y,N.swap.escrow={...N.swap.escrow||{},moneroRestoreHeight:Y};try{ue.saveSwap(N.swap,a)}catch{throw new d("storage-unavailable",{step:"save-restore-height"})}let G=null;if(R.newKey){if(typeof p.onRecoveryKey!="function")throw new d("bad-input",{field:"onRecoveryKey"});try{G={name:Du(R.key),contents:await Uu({mnemonic:R.key.mnemonic,createdAt:R.key.createdAt,passphrase:j})}}catch{throw new d("recovery-failed",{step:"encrypt-key"})}if(await p.onRecoveryKey(G)!==!0)throw new d("recovery-declined",{key:R.key.fingerprint});try{ui(R.storage,{...R.key,backupConfirmed:!0}),R.key={...R.key,backupConfirmed:!0}}catch{throw new d("storage-unavailable",{step:"save-recovery-key"})}}let Z=p.wallet;if(!Z||typeof Z.send!="function"||typeof Z.receipt!="function")throw new d("bad-input",{field:"wallet",missing:["send","receipt"],surface:"swaps.start",step:"lock"});if(l){let C=typeof Z.address=="function"?await Z.address():null;if(typeof C!="string"||!C)throw new d("bad-input",{field:"wallet",missing:["address"],surface:"swaps.start",step:"lock"});if(l.has(C.toLowerCase()))throw new d("address-denied",{step:"lock"})}let ne=X?{commitHalfLocker:X.wallet.commitHalfLocker,commitHalfClaimer:X.wallet.commitHalfClaimer,edPointLocker:X.own.spendPoint,edPointClaimer:X.wallet.otherSpendPoint,edViewPointLocker:X.own.viewPoint}:{},oe={...p.order,...ne,amountWei:p.order.amount};if(p.orderQuote&&(X||p.counterparty)){let C=le=>String(le??"").replace(/^0x/i,"").toLowerCase(),q=X?X.wallet.commitHalfClaimer:p.counterparty.commitHalfClaimer||null,J=X?X.wallet.otherSpendPoint:p.counterparty.edPointClaimer||p.counterparty.edPub||null;if(!q||!J||C(p.orderQuote.commitHalfClaimer)!==C(q)||C(p.orderQuote.edPointClaimer)!==C(J))throw new d("quote-refused",{step:"quote-binding",why:"counterparty-half"})}let T=p.orderQuote&&p.orderQuote.validUntil!==void 0?p.orderQuote.validUntil:void 0;if(T!=null){let C=Number(T),q=typeof i=="function"?Number(i()):Date.now(),J=Math.floor(q/1e3);if(!Number.isSafeInteger(C)||!Number.isSafeInteger(J)||C<=J+30)throw new d("quote-expired",{validUntil:Number.isFinite(C)?C:null,now:Number.isFinite(J)?J:null,marginSec:30,step:"lock"})}oe.quote=p.orderQuote||null;let K=async({escrow:C,salt:q})=>{if(!C||!/^0x[0-9a-fA-F]{40}$/.test(String(C)))return;let J=N.swap.escrow&&typeof N.swap.escrow=="object"?N.swap.escrow:{};N.swap.fundingPending=!0,N.swap.escrow={...J,address:C,salt:q||J.salt||null,fundingPending:!0,fundingReason:"not-sent"};try{ue.saveSwap(N.swap,a)}catch{throw new d("storage-unavailable",{step:"save-pending"})}},M=null;try{M=await _b(oe,Z,{call:h,onPredicted:K})}catch(C){if(N.swap.escrow&&N.swap.escrow.fundingReason==="not-sent"){delete N.swap.fundingPending,N.swap.escrow={...N.swap.escrow,fundingPending:!1,fundingReason:"send-rejected"};try{ue.saveSwap(N.swap,a)}catch{}}throw C&&typeof C.code=="string"?C:new d("server-unavailable",{step:"lock"})}if(M&&M.pending){let C=M.createHash||null,q=M.predictedEscrow||null,J=N.swap.escrow&&typeof N.swap.escrow=="object"?N.swap.escrow:{};N.swap.fundingPending=!0,N.swap.escrow={...J,address:q||J.address||null,fundTx:C||J.fundTx||null,fundingPending:!0,fundingReason:M.pendingReason||"no-receipt"};try{ue.saveSwap(N.swap,a)}catch{throw new d("storage-unavailable",{step:"save-pending"})}return{id:N.swap.id||null,escrow:N.swap.escrow.address||null,address:N.swapWallet&&N.swapWallet.address||null,step:"funding-pending",txHash:C,reason:M.pendingReason||"no-receipt",predictedEscrow:q,next:"receipt",readyWindow:$}}let ee=M&&M.escrow||null;if(ee){let C=N.swap.escrow&&typeof N.swap.escrow=="object"?N.swap.escrow:{};N.swap.escrow={...C,address:ee,evmBirthBlock:Number(M.birthBlock)>0?Number(M.birthBlock):C.evmBirthBlock??C.birthHeight??null};try{ue.saveSwap(N.swap,a)}catch{throw new d("storage-unavailable",{step:"save-escrow"})}}return{id:N.swap.id||null,escrow:ee,address:N.swapWallet&&N.swapWallet.address||null,step:"xmr-incoming",next:"watch",readyWindow:$}},async watch(p){if(!p||typeof p!="object")throw new d("bad-input",{field:"request"});let b=typeof p.id=="string"&&p.id?p.id:null;if(!b)throw new d("bad-input",{field:"id"});let S=p.expect!==void 0&&p.expect!==null,v=p.wallet!==void 0&&p.wallet!==null;if(S!==v)throw new d("bad-input",{field:S?"wallet":"expect"});if(S&&!(p.escrow||p.address))throw new d("bad-input",{field:"escrow"});let H=(()=>{try{return ue.getSwap(b,a)}catch{return null}})(),A=p.readyWindow||H&&(H.readyWindow||H.sellWindow)||null,O=Number.isFinite(Number(p.pollMs))&&Number(p.pollMs)>0?Number(p.pollMs):y("watchPollMs",5e3),D=Number.isFinite(Number(p.timeoutMs))&&Number(p.timeoutMs)>0?Number(p.timeoutMs):y("watchTimeoutMs",12e5),L=Number.isFinite(Number(p.minConfirmations))&&Number(p.minConfirmations)>0?Math.trunc(Number(p.minConfirmations)):y("xmrConfirmations",10),V=p.verify&&typeof p.verify=="object"?{...p.verify,nodes:Array.isArray(p.verify.nodes)?p.verify.nodes:c&&typeof c.nodesFor=="function"?c.nodesFor(p.verify.network||p.network||r):[],minConfirmations:L}:null;if(V){if(!A)throw new d("bad-input",{field:"readyWindow",why:"not-in-record"});let Y=xt(A,{side:"ask",field:"readyWindow"}),G=p.readyBySec!==void 0&&p.readyBySec!==null?Number(p.readyBySec):p.deadline&&p.deadline.readyBy!==void 0?Number(p.deadline.readyBy):null;G&&Md({readyBySec:G,nowSec:Math.floor(Date.now()/1e3),minConfirmations:L,blockTimeSec:y("xmrBlockTimeSec",120),minLeadSec:nb(Y)})}if(!V)throw new d("bad-input",{field:"verify",why:"required"});let U=Date.now(),j=null;try{j=ue.getSwap(b,a)}catch{j=null}let F=p.escrow||j&&j.escrow&&j.escrow.address||null,R=Ga(j&&j.escrow?j.escrow.evmBirthBlock??j.escrow.birthHeight:null),_={checked:!1,error:null,logs:void 0},N=async()=>{if(_.checked=!1,_.error=null,_.logs=void 0,!F){_.error="no-escrow";return}try{_.logs=await w({address:F,topics:[ho],fromBlock:R,toBlock:"latest"}),_.checked=!0}catch(Y){_.error=Y&&Y.code||"logs-unread"}},W=(Y,G)=>{if(!(!Y||Y.settlement)){Y.settlement={kind:rn,phase:rn,at:G};try{ue.saveSwap(Y,a)}catch{throw new d("storage-unavailable",{step:"decline"})}}},$=({source:Y,at:G,waitedMs:Z,address:ne,chainChecked:oe,chainError:T})=>({id:b,escrow:F,address:ne||null,seen:!1,declined:!0,terminal:rn,code:Xa,source:Y,at:G,waitedMs:Z,chain:{checked:!!oe,error:T||null}});if(j&&j.settlement&&j.settlement.kind===rn){let Y=Number(j.settlement.at);return $({source:"record",at:Number.isFinite(Y)?Y:Date.now(),waitedMs:0,address:null,chainChecked:!1,chainError:null})}let X=null;for(;;){await N(),X={address:p.address||F,expectedXmr:p.expectedXmr??null,status:null};let Y=wb({logs:_.logs,escrow:F,at:Date.now()});if(Y.declined)return W(j,Y.at),$({source:Y.source,at:Y.at,waitedMs:Date.now()-U,address:X&&X.address,chainChecked:_.checked,chainError:_.error});if(V){let G=await Ci({...V,nowSec:Math.floor(Date.now()/1e3)});if(X.verify=G,!G.seen){if(Date.now()-U>=D)throw new d("xmr-timeout",{id:b,address:X.address,expectedXmr:X.expectedXmr,state:G.state,confirmations:G.confirmations??0,waitedMs:Date.now()-U,timeoutMs:D,pollMs:O});await new Promise(ne=>setTimeout(ne,O));continue}let Z={seen:!0,id:b,address:X.address,status:X.status,expectedXmr:X.expectedXmr,receivedXmr:Number(G.amountAtomic)/1e12,confirmations:G.confirmations,txids:[G.txid],at:Date.now(),verified:{height:G.height,blockHash:G.blockHash,operators:G.operators,agreedBy:G.agreedBy},source:"client"};return S&&v?Z.marked=await x.markReady({escrow:p.escrow||X.address,expect:p.expect,onStep:p.onStep},p.wallet):Z.next="mark-ready",Z}}},async startSell(p){if(!p||typeof p!="object")throw new d("bad-input",{field:"request"});let b=p.offer&&typeof p.offer=="object"?p.offer:null;if(!b)throw new d("bad-input",{field:"offer"});let S=b.order&&typeof b.order=="object"?b.order:null,v=b.quote&&typeof b.quote=="object"?b.quote:null;if(!S||!v)throw new d("bad-input",{field:"offer",missing:["order","quote"]});if(typeof b.jointAddress!="string"||!b.jointAddress)throw new d("bad-input",{field:"offer.jointAddress"});if(typeof b.escrow!="string"||!b.escrow)throw new d("bad-input",{field:"offer.escrow"});let H=b.relayUrl===void 0||b.relayUrl===null||b.relayUrl===""?null:wo(b.relayUrl),A=b.readyWindow||v&&v.readyWindow||null,O=A?xt(A,{side:"bid",field:"offer.readyWindow"}):null,D=(K,M)=>String(K||"").replace(/^0x/,"").toLowerCase()===String(M||"").replace(/^0x/,"").toLowerCase();if(!D(v.locker,S.locker)||!D(v.claimer,S.claimer)||!D(v.provider,S.locker)||!D(v.factory,S.factory)||Number(v.chainId)!==Number(S.chainId))throw new d("quote-refused",{step:"sell-record",why:"terms"});let L=ct(v.provider,"provider"),V=v.quoteKey===void 0||v.quoteKey===null||String(v.quoteKey).trim()===""?null:ct(v.quoteKey,"quoteKey"),U=p.claimSender===void 0||p.claimSender===null||String(p.claimSender).trim()===""?null:ct(p.claimSender,"claimSender");if(U&&U===L)throw new d("bad-input",{field:"claimSender",why:"is-deal-maker"});if(U&&V&&U===V)throw new d("bad-input",{field:"claimSender",why:"is-quote-key"});let j=v.id||v.nonce||null,F=I().find(K=>K.side==="sell"&&(K.escrow&&String(K.escrow.address||"").toLowerCase()===String(b.escrow).toLowerCase()||j!==null&&String(K.orderQuoteId||"")===String(j)));if(F){let K=F.quote&&typeof F.quote=="object"?F.quote:{},M=(J,le)=>String(J||"").replace(/^0x/,"").toLowerCase()===String(le||"").replace(/^0x/,"").toLowerCase();if(!M(K.commitHalfClaimer,v.commitHalfClaimer)||!M(K.edPointClaimer,v.edPointClaimer)||!M(F.escrow&&F.escrow.moneroAddress,b.jointAddress))throw new d("quote-refused",{step:"sell-record",why:"offer-changed"});let ee=F.claimSender?ct(F.claimSender,"claimSender"):null;if(U&&ee&&U!==ee)throw new d("quote-refused",{step:"sell-record",why:"claim-sender-changed"});let C=F.relayUrl?wo(F.relayUrl):null;if(H&&C&&H!==C)throw new d("quote-refused",{step:"sell-record",why:"relay-changed"});if(await B(F.escrow&&F.escrow.address||b.escrow,F.expect||null,p.wallet),H&&!C){F.relayUrl=H;try{ue.saveSwap(F,a)}catch{throw new d("storage-unavailable",{step:"save-relay"})}}if(U&&!ee){F.claimSender=U;try{ue.saveSwap(F,a)}catch{throw new d("storage-unavailable",{step:"save-claim-sender"})}}let q=F.readyWindow||F.sellWindow||null;if(O&&q){let J=xt(q,{side:"bid",field:"readyWindow"});if(J.readyMinSeconds!==O.readyMinSeconds||J.readyMaxSeconds!==O.readyMaxSeconds)throw new d("quote-refused",{step:"sell-record",why:"window-changed"})}if(O&&!q){F.readyWindow=O;try{ue.saveSwap(F,a)}catch{throw new d("storage-unavailable",{step:"save-window"})}}return{id:F.id,side:"sell",escrow:F.escrow&&F.escrow.address||b.escrow,address:F.escrow&&F.escrow.moneroAddress||b.jointAddress,xmrAmount:F.escrow&&F.escrow.xmrAmount||v.xmrAmount,claimTip:F.claimTip||v.claimTip,orderQuote:F.orderQuote||b.orderQuote,claimSender:F.claimSender||null,readyWindow:F.readyWindow||F.sellWindow||null,resumed:!0,next:"send-xmr"}}let R=a.storage(),_=typeof p.recoveryKey=="string"?p.recoveryKey:p.recoveryKey&&typeof p.recoveryKey.mnemonic=="string"?p.recoveryKey.mnemonic:null,N=Mu(R);if(N&&_&&N.mnemonic!==_)throw new d("bad-input",{field:"recoveryKey",why:"different-key"});if(!N&&!_)throw new d("bad-input",{field:"recoveryKey"});let W=N||Lu(_);if(N||ui(R,{...W,backupConfirmed:!1}),!N||N.backupConfirmed!==!0){if(typeof p.onRecoveryKey!="function")throw new d("bad-input",{field:"onRecoveryKey"});let K=null;try{K={name:Du(W),contents:await Uu({mnemonic:W.mnemonic,createdAt:W.createdAt,passphrase:p.passphrase})}}catch{throw new d("recovery-failed",{step:"encrypt-key"})}if(await p.onRecoveryKey(K)!==!0)throw new d("recovery-declined",{key:W.fingerprint});try{ui(R,{...W,backupConfirmed:!0})}catch{throw new d("storage-unavailable",{step:"save-recovery-key"})}}let $=Number(S.chainId);if(!Number.isSafeInteger($)||$<=0)throw new d("bad-input",{field:"order.chainId"});if(!S.factory||S.salt===void 0||S.salt===null)throw new d("bad-input",{field:"order"});let X=null;try{X=Zt(b.recovery&&b.recovery.salt?b.recovery.salt:S.salt)}catch{throw new d("bad-input",{field:"offer.recovery"})}let Y=ir({mnemonic:W.mnemonic,chainId:$,factory:S.factory,salt:X}),G=zu(S,{spendHalf:Y.spendHalf,viewHalf:Y.viewHalf}),Z=G.commitHalf,ne=K=>String(K||"").replace(/^0x/,"").toLowerCase();if(!Z||ne(Z)!==ne(v.commitHalfClaimer))throw new d("quote-refused",{step:"sell-record",why:"commitment"});if(String(G.spendPoint).toLowerCase()!==String(v.edPointClaimer||"").toLowerCase())throw new d("quote-refused",{step:"sell-record",why:"spend-point"});if(b.edViewPointClaimer&&String(G.viewPoint).toLowerCase()!==String(b.edViewPointClaimer).toLowerCase())throw new d("quote-refused",{step:"sell-record",why:"view-point"});let T=_d({side:"sell",network:String(S.chainId),moneroNetwork:r||void 0,payToken:S.asset||v.asset||void 0,payAmount:v.amount,xmrAmount:Number(v.xmrAmount)/1e12,orderQuoteId:j||void 0,receiveAddress:S.claimer,makerId:v.provider||null},{order:S,side:G.side,store:a}).swap;T.side="sell",T.order=S,T.orderQuote=b.orderQuote||null,T.quote=v,T.claimTip=v.claimTip||null,U&&(T.claimSender=U),T.expect={chainId:$,factory:S.factory,locker:S.locker,claimer:S.claimer,amount:String(S.amount),readyBy:S.readyBy,t1:S.t1,salt:S.salt,commitHalfLocker:b.nodeHalf&&b.nodeHalf.commitHalf||null,edPointLocker:b.nodeHalf&&b.nodeHalf.edPoint||null,edViewPointLocker:b.edViewPointLocker||null,commitHalfClaimer:v.commitHalfClaimer||null,edPointClaimer:v.edPointClaimer||null},T.escrow={...T.escrow||{},address:b.escrow,moneroAddress:b.jointAddress,half:Jt(G.side.half),viewHalf:Jt(G.side.viewHalf),edPointClaimer:G.spendPoint,edViewPointClaimer:me(G.side.viewPub),commitHalfClaimer:v.commitHalfClaimer,edPointLocker:b.nodeHalf&&b.nodeHalf.edPoint||null,edViewPointLocker:b.edViewPointLocker||null,commitHalfLocker:b.nodeHalf&&b.nodeHalf.commitHalf||null,orderContext:b.context||null,xmrAmount:v.xmrAmount||null},H&&(T.relayUrl=H),O&&(T.readyWindow=O);try{await B(b.escrow,T.expect,p.wallet)}catch(K){try{ue.forgetSwap(T.id,a)}catch{}throw K}try{ue.saveSwap(T,a)}catch{throw new d("storage-unavailable",{step:"save-swap"})}return{id:T.id,side:"sell",escrow:b.escrow,address:b.jointAddress,xmrAmount:v.xmrAmount,claimTip:v.claimTip||null,orderQuote:b.orderQuote||null,claimSender:T.claimSender||null,readyWindow:T.readyWindow||null,resumed:!1,next:"send-xmr"}},async sellClaim(p,b){if(!p||typeof p!="object")throw new d("bad-input",{field:"request"});let S=String(p.id||"").trim();if(!S)throw new d("bad-input",{field:"id"});let v=null;try{v=ue.getSwap(S,a)}catch{v=null}if(!v||v.side!=="sell")throw new d("bad-input",{field:"id",why:"sell-not-found"});let H=p.escrow||v.escrow&&v.escrow.address||null,A=p.halfClaimer||v.escrow&&v.escrow.half||null;if(!H||!A)throw new d("bad-input",{field:"escrow",missing:["escrow","halfClaimer"]});let O=p.expect||v.expect||null;if(!O)throw new d("bad-input",{field:"expect",why:"not-in-record"});return x.claim({escrow:H,halfClaimer:A,claimer:v.order&&v.order.claimer,expect:O,onStep:p.onStep},b)},async claimViaRelay(p={}){if(!p||typeof p!="object")throw new d("bad-input",{field:"request"});let b=String(p.id===void 0||p.id===null?"":p.id).trim();if(!b)throw new d("bad-input",{field:"id"});let S=null;try{S=ue.getSwap(b,a)}catch{S=null}if(!S||S.side!=="sell")throw new d("bad-input",{field:"id",why:"sell-not-found"});let v=0n;try{v=BigInt(S.claimTip===void 0||S.claimTip===null||S.claimTip===""?0:S.claimTip)}catch{throw new d("bad-input",{field:"claimTip",why:"unreadable"})}if(v<=0n)throw new d("bad-input",{field:"claimTip",why:"not-positive"});let H=S.quote&&typeof S.quote=="object"?S.quote:{},A=S.order&&typeof S.order=="object"?S.order:{},O=S.escrow&&typeof S.escrow=="object"?S.escrow:{},D=H.provider!==void 0&&H.provider!==null?H.provider:O.providerId!==void 0&&O.providerId!==null?O.providerId:A.locker;if(D==null||D==="")throw new d("bad-input",{field:"provider",why:"not-in-record"});let L=ct(D,"provider");for(let[G,Z]of[["order.locker",A.locker],["quote.locker",H.locker]])if(Z!=null&&String(Z)!==""&&ct(Z,G)!==L)throw new d("quote-refused",{step:"relay-claim",why:"provider"});let V=S.claimSender===void 0||S.claimSender===null||String(S.claimSender).trim()===""?null:S.claimSender,U=p.claimSender===void 0||p.claimSender===null||String(p.claimSender).trim()===""?null:p.claimSender,j=V?ct(V,"claimSender"):null,F=U?ct(U,"claimSender"):null;if(j&&F&&j!==F)throw new d("bad-input",{field:"claimSender",why:"different-from-record"});let R=j||F;if(!R)throw new d("bad-input",{field:"claimSender",why:"not-in-record"});if(R===L)throw new d("bad-input",{field:"claimSender",why:"is-deal-maker"});let _=H.quoteKey===void 0||H.quoteKey===null||String(H.quoteKey).trim()===""?null:ct(H.quoteKey,"quoteKey");if(_&&R===_)throw new d("bad-input",{field:"claimSender",why:"is-quote-key"});if(!j&&F){S.claimSender=F;try{ue.saveSwap(S,a)}catch{throw new d("storage-unavailable",{step:"save-claim-sender"})}}if(O.address===void 0||O.address===null||O.address==="")throw new d("bad-input",{field:"escrow",why:"not-in-record"});let N=ct(O.address,"escrow"),W=Kd(O.half);if(S.relayUrl===void 0||S.relayUrl===null||S.relayUrl==="")throw new d("bad-input",{field:"relayUrl",why:"not-in-record"});let $=wo(S.relayUrl);if(p.relayUrl!==void 0&&p.relayUrl!==null&&String(p.relayUrl).trim()!==""&&wo(p.relayUrl)!==$)throw new d("bad-input",{field:"relayUrl",why:"foreign-relay"});let X=Number.isFinite(Number(p.timeoutMs))&&Number(p.timeoutMs)>0?Number(p.timeoutMs):2e4,Y=await Rb({relayUrl:$,provider:R,escrow:N,halfClaimer:W,expectedTipWei:v,fetchImpl:p.fetchImpl||null,timeoutMs:X});return{id:b,provider:R,claimSender:R,escrow:N,relayUrl:$,txid:Y.txid,from:Y.from,tipWei:Y.tipWei}},async sellWatch(p){if(!p||typeof p!="object")throw new d("bad-input",{field:"request"});let b=String(p.escrow||"").trim();if(!b)throw new d("bad-input",{field:"escrow"});let S=z6(a,b),v=p.readyWindow||S&&(S.readyWindow||S.sellWindow)||null,H=Number.isFinite(Number(p.pollMs))&&Number(p.pollMs)>0?Number(p.pollMs):y("watchPollMs",6e3),A=Number.isFinite(Number(p.timeoutMs))&&Number(p.timeoutMs)>0,O=!A&&v?xt(v,{side:"bid",field:"readyWindow"}):null;if(!O&&!A)throw new d("bad-input",{field:"readyWindow",why:"not-in-record"});let D=A?Number(p.timeoutMs):null;if(!A)try{let R=await dr(b,{call:h});D=W6({configuredMs:kd(O),readyBySec:R.readyBy})}catch{D=kd(O)}let L=null;try{L=await dr(b,{call:h})}catch{}let V=()=>{let R=typeof i=="function"?Number(i()):Date.now();return Number.isFinite(R)?Math.floor(R/1e3):null},U=Date.now(),j=null,F=null;for(;;){try{j=await ur(b,{call:h})}catch(R){F=R&&R.code||"status-unread",j=null}if(j&&(j.isClaimed||j.isRefunded))return{escrow:b,state:j.isClaimed?"claimed":"refunded",funded:j.isFunded,claimed:j.isClaimed,refunded:j.isRefunded,ready:null,claimOpen:!1,balanceWei:String(j.balance),waitedMs:Date.now()-U};if(j&&j.isFunded){let R=null;try{let _=await h({to:b,data:Ue.encodeRead("ready")}),N=String(_||"").replace(/^0x/,"");R=N.length>0&&BigInt("0x"+N)!==0n}catch(_){F=_&&_.code||"ready-unread"}if(R===!0)return{escrow:b,state:"ready",funded:!0,claimed:!1,refunded:!1,ready:!0,claimOpen:!1,balanceWei:String(j.balance),waitedMs:Date.now()-U}}if(j&&j.isFunded&&L&&Number.isSafeInteger(Number(L.readyBy))){let R=V();if(R!==null&&R>=Number(L.readyBy))return{escrow:b,state:"claim-open",funded:!0,claimed:!1,refunded:!1,ready:!1,claimOpen:!0,balanceWei:String(j.balance),waitedMs:Date.now()-U}}if(Date.now()-U>=D)throw new d("sell-timeout",{escrow:b,waitedMs:Date.now()-U,timeoutMs:D,status:j,error:F});await new Promise(R=>setTimeout(R,H))}}}}fe();fe();var X6=/^0x[0-9a-fA-F]{40}$/,Y6=/^0x[0-9a-fA-F]{64}$/,G6=/^\d+$/,Ja=e=>typeof e=="string"&&X6.test(e)?e.toLowerCase():null,hr=e=>typeof e=="string"&&Y6.test(e)?e.toLowerCase():null;function Db({order:e=null,chainId:t=null,half:n=null}={}){if(!e||typeof e!="object")throw new d("bad-input",{field:"order"});let r=Number(t);if(!Number.isSafeInteger(r)||r<=0)throw new d("bad-input",{field:"chainId"});let o=e.side;if(o!=="locker"&&o!=="claimer")throw new d("bad-input",{field:"order.side"});let i=Ja(e.escrow),s=Ja(e.locker),a=Ja(e.claimer),c=Ja(e.factory),l=hr(e.salt),u=hr(e.commitHalfLocker),f=hr(e.commitHalfClaimer),h=hr(e.edPointLocker),m=hr(e.edPointClaimer),w=hr(e.edViewPointLocker),x=hr(n),y=typeof e.amount=="string"?e.amount:typeof e.amount=="bigint"?e.amount.toString():null,k=Number(e.readyBy),I=Number(e.t1),g=[];if(i||g.push("escrow"),s||g.push("locker"),a||g.push("claimer"),c||g.push("factory"),l||g.push("salt"),u||g.push("commitHalfLocker"),f||g.push("commitHalfClaimer"),h||g.push("edPointLocker"),m||g.push("edPointClaimer"),w||g.push("edViewPointLocker"),x||g.push("half"),(!y||!G6.test(y)||BigInt(y)<=0n)&&g.push("amount"),(!Number.isSafeInteger(k)||k<=0)&&g.push("readyBy"),(!Number.isSafeInteger(I)||I<=0)&&g.push("t1"),g.length)throw new d("bad-input",{field:"order",missing:g});return Object.freeze({side:o,kind:o==="locker"?"refund":"claim",escrow:i,half:x,claimer:a,expect:Object.freeze({chainId:r,factory:c,locker:s,claimer:a,amount:y,readyBy:k,t1:I,salt:l,commitHalfLocker:u,commitHalfClaimer:f,edPointLocker:h,edPointClaimer:m,edViewPointLocker:w})})}Ee();fe();var q6=2,Q6=10,yo=(e,t)=>{try{return BigInt(e)}catch{throw new d("bad-input",{field:t})}},Z6=e=>{if(!e||typeof e.driver!="function")throw new d("bad-input",{field:"wallet.driver"});let t=e.driver();if(!t||typeof t!="object")throw new d("bad-input",{field:"wallet.driver"});let n=["setRestoreHeight","getBalance"].filter(r=>typeof t[r]!="function");if(n.length)throw new d("bad-input",{field:"wallet.driver",missing:n});return t},Tt=async(e,t)=>{try{return await t()}catch(n){throw n instanceof d?n:new d("wallet-rejected",{surface:e,why:String(n&&n.message||n)})}},Ub=async(e,t)=>{if(typeof e[t]!="function")return null;try{let n=await e[t](),r=Number(n);return Number.isFinite(r)?r:null}catch{return null}},Mb=async(e,{syncError:t=null,rescanError:n=null,spentChecked:r=!0}={})=>{let o=await Ub(e,"getHeight"),i=await Ub(e,"getDaemonHeight"),s=null;return n?s="rescan-failed":t?s="sync-failed":o===null||i===null?s="no-heights":o<i?s="behind-node":r||(s="spent-status-unavailable"),{scanComplete:s===null,...s===null?{}:{scanIncompleteReason:s},walletHeight:o,nodeHeight:i}};async function J6({nodeUrl:e,fromHeight:t,toHeight:n,fetchImpl:r=globalThis.fetch,sleep:o=e_,attempts:i=3}={}){let s=typeof e=="string"?e.trim():"";for(;s.endsWith("/");)s=s.slice(0,-1);let a=Number(t),c=Number(n);if(!s)throw new d("bad-input",{field:"window.nodeUrl"});if(!Number.isSafeInteger(a)||a<0)throw new d("bad-input",{field:"window.fromHeight"});if(!Number.isSafeInteger(c)||c<a)throw new d("bad-input",{field:"window.toHeight"});if(typeof r!="function")throw new d("bad-input",{field:"fetchImpl"});let l=Math.max(1,Math.min(5,Number(i)||3)),u=[];for(let f=a;f<=c;f+=1){let h=null,m=null;for(let k=1;k<=l;k+=1){try{h=await r(s+"/json_rpc",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:"block",method:"get_block",params:{height:f}}),signal:typeof AbortSignal<"u"&&AbortSignal.timeout?AbortSignal.timeout(8e3):void 0})}catch{if(h=null,m=new d("wallet-rejected",{surface:"window-blocks",height:f,why:"transport"}),k<l){await o(Kb(k));continue}throw m}if(h&&h.ok===!0){m=null;break}let I=h?h.status:null;if(m=new d("wallet-rejected",{surface:"window-blocks",height:f,status:I}),(I===429||I!==null&&I>=500)&&k<l){await o(t_(h)??Kb(k));continue}throw m}if(!h||h.ok!==!0)throw m||new d("wallet-rejected",{surface:"window-blocks",height:f});let w=null;try{w=await h.json()}catch{throw new d("wallet-rejected",{surface:"window-blocks",height:f,why:"not-json"})}if(!w||w.error||!w.result)throw new d("wallet-rejected",{surface:"window-blocks",height:f,why:"rpc"});let x=w.result,y=Array.isArray(x.tx_hashes)?x.tx_hashes:null;if(!y&&typeof x.json=="string")try{let k=JSON.parse(x.json);y=Array.isArray(k.tx_hashes)?k.tx_hashes:null}catch{y=null}if(!y)throw new d("wallet-rejected",{surface:"window-blocks",height:f,why:"no-tx-hashes"});u.push(...y.map(String))}return u}var e_=e=>new Promise(t=>setTimeout(t,e)),Kb=e=>Math.min(4e3,250*2**Math.max(0,e-1));function t_(e){try{let t=e&&e.headers&&typeof e.headers.get=="function"?e.headers.get("retry-after"):null;if(t==null||t==="")return null;let n=Number(t);if(Number.isFinite(n)&&n>=0)return Math.min(5e3,Math.floor(n*1e3));let r=Date.parse(String(t));if(Number.isFinite(r))return Math.min(5e3,Math.max(0,r-Date.now()))}catch{}return null}async function jb(e={}){let t=e.wallet;if(!t||typeof t!="object")throw new d("bad-input",{field:"wallet"});let n=["sync","unlockedBalance"].filter(g=>typeof t[g]!="function");if(n.length)throw new d("bad-input",{field:"wallet",missing:n});let r=Number(e.fromHeight);if(!Number.isFinite(r)||r<=0)throw new d("bad-input",{field:"restoreHeight"});let o=Number.isFinite(Number(e.scanBack))&&Number(e.scanBack)>=0?Math.floor(Number(e.scanBack)):Q6,i=Math.max(0,Math.floor(r)-o),s=Z6(t),a=e.window&&typeof e.window=="object"?e.window:null,c=null,l=0n,u=0n;if(a){let g=Number(a.tipHeight);if(!Number.isSafeInteger(g)||g<=0)throw new d("bad-input",{field:"window.tipHeight"});c={used:!1,skipped:null,fallback:!1,fromHeight:r,toHeight:Number(a.toHeight),blocks:Math.max(0,Number(a.toHeight)-r+1),txs:0};let P=Array.isArray(a.txHashes)?a.txHashes.map(String):null;if(P===null)try{P=await J6({nodeUrl:a.nodeUrl,fromHeight:r,toHeight:a.toHeight,fetchImpl:e.fetchImpl})}catch(E){if(E&&E.code==="bad-input")throw E;c.fallback=!0,c.fallbackWhy="window-read",c.error={code:E&&E.code?E.code:"wallet-rejected",surface:E&&E.params&&E.params.surface?E.params.surface:"window-blocks",status:E&&E.params&&E.params.status!==void 0?E.params.status:null,height:E&&E.params&&E.params.height!==void 0?E.params.height:null,why:E&&E.params&&E.params.why?E.params.why:null},P=[]}if(c.txs=P.length,P.length&&typeof s.scanTxs=="function"){let E=null;try{await Tt("setRestoreHeight",()=>s.setRestoreHeight(g)),await Tt("scanTxs",()=>s.scanTxs(P));try{await t.sync()}catch(B){E=B}l=yo(await Tt("getBalance",()=>s.getBalance()),"balance"),u=yo(await Tt("unlockedBalance",()=>t.unlockedBalance()),"unlockedBalance"),c.used=!0}catch(B){if(B&&B.code==="bad-input")throw B;l=0n,u=0n,c.fallback=!0,c.fallbackWhy="window-scan",c.error={code:B&&B.code?B.code:"wallet-rejected",surface:B&&B.params&&B.params.surface?B.params.surface:"scanTxs",status:null,height:null,why:B&&B.params&&B.params.why?B.params.why:null}}if(c.used&&a.nodeUrl&&a.trustedNode===!0&&typeof s.getKeyImages=="function")try{let B=await s.getKeyImages(),b=(Array.isArray(B)?B:B&&typeof B.getKeyImages=="function"?B.getKeyImages():[]).map(S=>typeof S=="string"?S:S&&typeof S.getHex=="function"?S.getHex():S&&S.hex).filter(Boolean);if(b.length){let S=String(a.nodeUrl);for(;S.endsWith("/");)S=S.slice(0,-1);let v=await(e.fetchImpl||globalThis.fetch)(S+"/is_key_image_spent",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({key_images:b}),signal:typeof AbortSignal<"u"&&AbortSignal.timeout?AbortSignal.timeout(8e3):void 0}),H=v&&v.ok===!0?await v.json():null;H&&Array.isArray(H.spent_status)?(c.spent=H.spent_status.filter(A=>A===!0||A===1).length,c.keyImages=b.length):c.spent=null}else c.spent=null,c.spentWhy="no-key-images"}catch{c.spent=null,c.spentWhy="check-failed"}else c.used&&a.nodeUrl&&(c.spent=null,c.spentWhy=a.trustedNode===!0?"no-key-images":"untrusted-node");if(c.used&&(l>0n||u>0n||a.fallback===!1)){let B=await Mb(s,{syncError:E,spentChecked:c.spent!==null&&c.spent!==void 0});return{total:l.toString(),unlocked:u.toString(),scanHeight:i,...B,passes:1,lockedPass:!1,window:c}}}else P.length&&(c.skipped="no-scan-txs")}if(c&&(c.fallback=!0,c.fallbackWhy||(c.fallbackWhy="empty-window")),await Tt("setRestoreHeight",()=>s.setRestoreHeight(i)),typeof s.rescanBlockchain!="function")throw new d("bad-input",{field:"wallet.driver.rescanBlockchain"});let f=null;try{await Tt("rescanBlockchain",()=>s.rescanBlockchain())}catch(g){f=g}let h=null;try{await t.sync()}catch(g){h=g}let m=yo(await Tt("getBalance",()=>s.getBalance()),"balance"),w=yo(await Tt("unlockedBalance",()=>t.unlockedBalance()),"unlockedBalance"),x=1,y=!1;if(e.rescanWhenLocked!==!1&&m>0n&&w===0n&&typeof s.rescanSpent=="function"&&x<q6){y=!0,await Tt("rescanSpent",()=>s.rescanSpent());try{await t.sync()}catch(g){h=g}m=yo(await Tt("getBalance",()=>s.getBalance()),"balance"),w=yo(await Tt("unlockedBalance",()=>t.unlockedBalance()),"unlockedBalance"),x+=1}let I=await Mb(s,{syncError:h,rescanError:f});return{total:m.toString(),unlocked:w.toString(),scanHeight:i,...I,passes:x,lockedPass:y,window:c}}fe();function Wb(e){let t=Array.isArray(e)?e:[e];if(!t.length)return null;let n=0n;for(let r of t){if(!r||typeof r.getFee!="function")return null;let o;try{o=r.getFee()}catch{return null}if(o==null)return null;let i;try{i=BigInt(o)}catch{return null}if(i<0n)return null;n+=i}return n.toString()}var bo="monero",n_="ninsei-wallet-session",r_=["mainnet","stagenet","testnet","fakechain"],o_=()=>{let e=ce.XMR_NETWORKS||{};return[...new Set([...Object.values(e).filter(t=>typeof t=="string"&&t),...r_])].sort()};function Vb({createWallet:e=null,network:t=null,serverUri:n=null,password:r=n_,keys:o={},restoreHeight:i=0,expectedAddress:s=null}={}){let a=null,c=null,l=new Set,u=()=>{for(let w of l)try{w()}catch{}},f=w=>{if(a===null)throw new d("wallet-not-connected",{vm:bo,surface:w});return a},h=()=>{if(typeof o.seed=="string"&&o.seed)return{seed:o.seed};if(o.privateSpendKey||o.privateViewKey){if(!o.primaryAddress)throw new d("bad-input",{field:"primaryAddress",why:"required-with-private-keys"});let w={};return o.privateSpendKey&&(w.privateSpendKey=o.privateSpendKey),o.privateViewKey&&(w.privateViewKey=o.privateViewKey),w.primaryAddress=o.primaryAddress,w}throw new d("bad-input",{field:"keys",missing:["seed","privateSpendKey"]})},m=async()=>{if(a===null)return;let w=a;a=null,c=null;try{await w.close()}catch{}};return{vm:bo,id:bo,async connect(){if(typeof e!="function")throw new d("bad-input",{field:"createWallet"});let w=o_();if(typeof t!="string"||!t)throw new d("bad-input",{field:"network",known:w});if(w.length&&!w.includes(t))throw new d("bad-input",{field:"network",known:w,got:t});if(typeof n!="string"||!n)throw new d("bad-input",{field:"serverUri"});let x=h(),y=Number(i);if(!Number.isFinite(y)||y<=0)throw new d("bad-input",{field:"restoreHeight",got:i});await m(),a=await e({networkType:t,server:{uri:n},password:r,restoreHeight:y,...x}),c=String(await a.getAddress(0,0));let I=typeof mn.networkFromShape=="function"?mn.networkFromShape(c):null;if(I&&I!==t)throw await m(),new d("wrong-chain",{got:I,want:t});if(s&&c!==s)throw await m(),new d("recovery-failed",{step:"address"});await a.setRestoreHeight(y),u()},async disconnect(){return await m()},async close(){return await m()},address(){return f("address"),c},chainId(){return t},async unlockedBalance(){return await f("unlockedBalance").getUnlockedBalance()},async sync(){await f("sync").sync(),u()},async open(w){if(a===null)throw new d("wallet-not-connected",{vm:bo,surface:"open"});let x=w&&w.address?String(w.address):null;if(x&&c!==x)throw new d("recovery-failed",{step:"address"})},async sweepUnlocked(w){return await f("sweepUnlocked").sweepUnlocked({address:w.address,relay:w.relay})},async relay(w){return await f("relay").relayTxs(w)},async fee(w){return Wb(w)},subscribe(w){if(typeof w!="function")throw new d("bad-input",{field:"handler"});return l.add(w),()=>l.delete(w)},async send(){throw new d("not-implemented",{surface:"adapter.send",vm:bo})},async receipt(){throw new d("not-implemented",{surface:"adapter.receipt",vm:bo})},driver(){return a}}}Vn();var i_=e=>typeof e=="string"?e.trim():"";function s_(e){let t=e&&e.receive;return(t&&typeof t.address=="string"?t.address.trim():"")||null}async function $b(e,t){let n=i_(t),r=s_(e),o=e&&e.moneroWallet&&e.moneroWallet.network||null;if(!n)return{ok:!1,dest:n,promised:r,matches:r===null?null:!1,network:o,verified:!1,reason:"no address"};let i=await Jc(n,o?{expectNetwork:o}:{});return{ok:i.ok===!0,dest:n,promised:r,matches:r===null?null:n===r,network:o,verified:i.verified===!0,reason:i.reason||null}}var a_=/^[0-9a-f]{64}$/;function zb(e){let t=String(e??"").trim(),n=(t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t).toLowerCase();return!a_.test(n)||/^0+$/.test(n)?null:"0x"+n}var Xb=10n**BigInt(12);function Yb(e,{trim:t=!0}={}){let n;try{n=BigInt(e)}catch{throw new RangeError("formatXmr: expected whole atomic units")}if(typeof e=="number"&&!Number.isInteger(e))throw new RangeError("formatXmr: expected whole atomic units");let r=n<0n,o=r?-n:n,i=o/Xb,s=(o%Xb).toString().padStart(12,"0"),a=t?s.replace(/0+$/,""):s,c=a?`${i}.${a}`:`${i}`;return r?`-${c}`:c}var c_=e=>{if(e==null||e==="")return null;let t=String(e);if(/^\d+$/.test(t))return Yb(BigInt(t));let n=Number(t);return Number.isFinite(n)&&n>0?t:null},ec=12,l_=["unlock","sync","sweep","relay"],u_=10000000000n;function d_({feeAtomic:e=null,amountAtomic:t=null,maxFeeAtomic:n=u_}={}){if(e==null)return{ok:!1,code:"sweep-fee-unknown",checked:!1,fee:null,limit:String(n)};let r,o,i;try{r=BigInt(e),o=t==null?null:BigInt(t),i=BigInt(n)}catch{return{ok:!1,code:"sweep-fee-too-high",why:"unreadable",fee:String(e),limit:String(n)}}return r<0n||i<0n?{ok:!1,code:"sweep-fee-too-high",why:"negative",fee:r.toString(),limit:i.toString()}:r>i?{ok:!1,code:"sweep-fee-too-high",why:"ceiling",fee:r.toString(),limit:i.toString(),amount:o===null?null:o.toString()}:{ok:!0,checked:!0,fee:r.toString(),limit:i.toString(),amount:o===null?null:o.toString()}}var f_="0x3f267bb6",Wd=e=>typeof e=="string"?e:e&&typeof e.contents=="string"?e.contents:null,go=e=>String(e??"").replace(/^0x/i,"").toLowerCase(),p_=async e=>{let t=e&&e.order;if(!t||typeof t!="object")throw new d("bad-input",{field:"order"});if(typeof e.mnemonic!="string"||!e.mnemonic.trim())throw new d("bad-input",{field:"mnemonic"});let n=Number(e.chainId);if(!Number.isSafeInteger(n)||n<=0)throw new d("bad-input",{field:"chainId"});let r=typeof e.network=="string"?e.network.trim():"",o=typeof e.moneroNetwork=="string"?e.moneroNetwork.trim():"";if(!r)throw new d("bad-input",{field:"network"});if(!o)throw new d("bad-input",{field:"moneroNetwork"});let i=typeof e.passphrase=="string"?e.passphrase:"";if(i&&i.length<ec)throw new d("bad-input",{field:"passphrase",min:ec});let s=t.side==="locker"?"buy":t.side==="claimer"?"sell":null;if(!s)throw new d("bad-input",{field:"order.side"});if(typeof t.factory!="string"||!/^0x[0-9a-fA-F]{40}$/.test(t.factory))throw new d("bad-input",{field:"order.factory"});let a=ir({mnemonic:e.mnemonic,chainId:n,factory:t.factory,salt:t.salt}),c=s==="buy";if(go(c?t.edPointLocker:t.edPointClaimer)!==go(a.spendPoint))throw new d("bad-input",{field:"order",why:"spend-point"});if(go(t.edViewPointLocker)!==go(c?a.viewPoint:a.makerViewPoint))throw new d("bad-input",{field:"order",why:c?"own-view-point":"maker-view-point"});let l="0x"+go(c?t.edPointClaimer:t.edPointLocker),u="0x"+go(a.makerViewPoint),f=Zr({ownSpendHalf:a.spendHalf,ownViewHalf:a.viewHalf,otherSpendPoint:l,otherViewPoint:u,network:o}),h=(()=>{try{let y=BigInt(String(t.xmrAmount));return y>0n?y.toString():null}catch{return null}})(),m={address:t.escrow,readyBy:t.readyBy,t1:t.t1,...h?{expectedAtomic:h}:{}},w=rt.buildPayload({swap:{id:t.escrow,side:s,network:r,moneroNetwork:o,createdAt:t.blockTime?Number(t.blockTime)*1e3:null,payToken:null,payAmount:null,xmrAmount:c_(t.xmrAmount),rate:null,maker:null,quoteSignature:null,escrow:m,timeline:null},swapWallet:{source:"halves",network:o,address:f.address,spendHalf:a.spendHalf,viewHalf:a.viewHalf,otherSpendPoint:l,otherViewPoint:u,otherViewHalf:a.makerViewHalf,escrowAddress:t.escrow},escrow:m,receiveAddress:null,restoreHeight:Number(t.startHeight)>0?Number(t.startHeight):null}),x=Db({order:t,chainId:n,half:a.spendHalf});return{payload:w,contents:await rt.createRecoveryFile(w,i),address:f.address,...x}},Gb=async(e,t)=>{try{return await t()}catch(n){throw n instanceof d?n:new d("wallet-rejected",{surface:e,why:String(n&&n.message||n)})}},h_=async(e,t)=>{if(!e||typeof e.fee!="function")return null;let n;try{n=await e.fee(t)}catch{return null}if(n==null)return null;let r=String(n);return/^\d+$/.test(r)?r:null};function qb({call:e=null}){let t=new Map,n=0,r={mainnet:"MAINNET",stagenet:"STAGENET",testnet:"TESTNET"},o={async fromOrder(i={}){return await p_(i)},wallet(i={}){let s=i.moneroTs;if(!s||typeof s!="object")throw new d("bad-input",{field:"moneroTs"});if(typeof s.createWalletFull!="function")throw new d("bad-input",{field:"moneroTs.createWalletFull"});let a=String(i.network||"").trim().toLowerCase(),c=r[a]||null,l=c&&s.MoneroNetworkType?s.MoneroNetworkType[c]:void 0;if(l==null)throw new d("bad-input",{field:"network",known:Object.keys(r),got:i.network});if(typeof i.serverUri!="string"||!i.serverUri)throw new d("bad-input",{field:"serverUri"});return Vb({createWallet:u=>s.createWalletFull({...u,networkType:l}),network:a,serverUri:i.serverUri,password:i.password,keys:i.keys||{},restoreHeight:i.restoreHeight,expectedAddress:i.expectedAddress||null})},async destination(i={}){let s=Wd(i.file);if(!s)throw new d("bad-input",{field:"file"});if(typeof i.passphrase!="string")throw new d("bad-input",{field:"passphrase"});if(typeof i.dest!="string"||!i.dest.trim())throw new d("bad-input",{field:"dest"});let a=null;try{a=await rt.decryptFile(JSON.parse(s),i.passphrase)}catch{throw new d("recovery-failed",{step:"decrypt"})}try{rt.validatePayload(a)}catch{throw new d("recovery-failed",{step:"validate"})}return $b(a,i.dest)},async plan(i){if(!i||typeof i!="object")throw new d("bad-input",{field:"request"});let s=Wd(i.file);if(!s)throw new d("bad-input",{field:"file"});if(typeof i.passphrase!="string"||i.passphrase.length>0&&i.passphrase.length<ec)throw new d("bad-input",{field:"passphrase",min:ec});let a=null;try{a=JSON.parse(s)}catch{throw new d("recovery-failed",{step:"parse"})}let c=null;try{c=await rt.decryptFile(a,i.passphrase)}catch{throw new d("recovery-failed",{step:"decrypt"})}try{rt.validatePayload(c)}catch{throw new d("recovery-failed",{step:"validate"})}let l=c.moneroWallet||{},u=l.address||null;if(!u)throw new d("recovery-failed",{step:"address"});let f=[],h=!!l.spendHalf;h||f.push("spendable");let m=Number(l.restoreHeight)||0;m>0||f.push("restore-height");let w=!1,x=null,y=l.escrowAddress||c.escrow&&c.escrow.address||null;if(y&&typeof e=="function")try{let k=String(await e({to:y,data:f_})||""),I=zb(k);I!==null&&(w=!0,x=I)}catch{w=!1}return w||f.push("revealed-half"),{swapId:c.swapId||null,address:u,spendable:h,restoreHeight:m,steps:l_,revealedHalf:w,half:x,missing:f}},async keys(i){let s=await o.plan(i);if(!s.half)throw new d("bad-input",{field:"revealedHalf",why:"not-revealed"});let a=Wd(i.file),c=null;try{c=await rt.decryptFile(JSON.parse(a),i.passphrase)}catch{throw new d("recovery-failed",{step:"decrypt"})}let l=c.moneroWallet||{},f=["spendHalf","viewHalf","otherSpendPoint","otherViewHalf"].filter(h=>l[h]===void 0||l[h]===null||l[h]==="");if(f.length)throw new d("bad-input",{field:"payload",missing:f});try{let h=Yt.createHalves(Xt),m=zs.spendKeysFromRevealedHalf({halves:h,ownSpendHalf:l.spendHalf,ownViewHalf:l.viewHalf,otherSpendPoint:l.otherSpendPoint,otherViewHalf:l.otherViewHalf,revealedHalf:s.half});return{privateSpendKey:m.privateSpendKey,privateViewKey:m.privateViewKey,address:s.address}}catch{throw new d("bad-input",{field:"revealedHalf",step:"verify"})}},async restore(i){return await jb(i||{})},async sign(i){let s=await o.plan(i);if(!i||typeof i.to!="string"||!i.to)throw new d("bad-input",{field:"to"});let a=i.wallet!==void 0&&i.wallet!==null?i.wallet:typeof i.connectWallet=="function"?await i.connectWallet(s):(()=>{throw new d("bad-input",{field:"connectWallet"})})(),l=["open","sync","unlockedBalance","sweepUnlocked","relay","close"].filter(u=>!a||typeof a[u]!="function");if(l.length)throw new d("bad-input",{field:"wallet",missing:l});await a.open(s);try{try{await a.sync()}catch{}let u=BigInt(await Gb("unlockedBalance",()=>a.unlockedBalance()));if(u<=0n)throw new d("insufficient-funds",{unlocked:u.toString()});let f=await Gb("sweepUnlocked",()=>a.sweepUnlocked({address:i.to,relay:!1})),h=await h_(a,f),m=h===null?null:BigInt(h),w=d_({feeAtomic:h,amountAtomic:u,...i.maxFeeAtomic===void 0||i.maxFeeAtomic===null?{}:{maxFeeAtomic:i.maxFeeAtomic}});if(!w.ok)throw new d(w.code,{fee:w.fee,limit:w.limit,amount:w.amount,why:w.why});let x="sweep-"+ ++n;return t.set(x,{wallet:a,plan:s,signed:f}),{token:x,amount:u.toString(),fee:h,receive:m===null||m>=u?null:(u-m).toString(),to:i.to,swept:s.address}}catch(u){try{await a.close()}catch{}throw u}},async relay(i){if(!i||typeof i.token!="string"||!i.token)throw new d("bad-input",{field:"token"});let s=t.get(i.token);if(!s)throw new d("bad-input",{field:"token",why:"no-open-session"});t.delete(i.token);let{wallet:a,plan:c,signed:l}=s;try{let u=await a.relay(l);return{txids:Array.isArray(u)?u:[],swept:c.address}}finally{await a.close()}},async run(i){let s=await o.sign(i);return await o.relay({token:s.token})}};return o}fe();var m_=e=>{let t=e&&typeof e=="object"?e:{},n=t.settlement&&typeof t.settlement=="object"?t.settlement:null;(!n||typeof n.chain!="string"||!n.chain)&&z("bad-input",{field:"settlement.chain"}),n.vm!==void 0&&(typeof n.vm!="string"||!n.vm)&&z("bad-input",{field:"settlement.vm"}),(typeof t.xmrNetwork!="string"||!t.xmrNetwork)&&z("bad-input",{field:"xmrNetwork"});let r=t.mode===void 0?"live":t.mode;if(r!=="live"&&r!=="sim"&&z("bad-input",{field:"mode",known:["live","sim"]}),t.storage!==void 0){let o=t.storage;o&&typeof o.get=="function"&&typeof o.set=="function"&&typeof o.remove=="function"||z("bad-input",{field:"storage"})}t.fetch!==void 0&&typeof t.fetch!="function"&&z("bad-input",{field:"fetch"}),t.now!==void 0&&typeof t.now!="function"&&z("bad-input",{field:"now"});for(let o of["apiBase","routes","serverAuth"])t[o]!==void 0&&z("bad-input",{field:o,why:"retired"});if(t.routing!==void 0){let o=t.routing;(!o||typeof o!="object"||o.prefer!==void 0&&!Array.isArray(o.prefer))&&z("bad-input",{field:"routing"})}if(t.endpoints!==void 0&&(!t.endpoints||typeof t.endpoints!="object"||Array.isArray(t.endpoints))&&z("bad-input",{field:"endpoints"}),t.nodes!==void 0&&!Array.isArray(t.nodes)&&(!t.nodes||typeof t.nodes!="object")&&z("bad-input",{field:"nodes"}),t.addNodes!==void 0&&!Array.isArray(t.addNodes)&&z("bad-input",{field:"addNodes"}),t.evmCall!==void 0&&typeof t.evmCall!="function"&&z("bad-input",{field:"evmCall"}),t.evmCode!==void 0&&typeof t.evmCode!="function"&&z("bad-input",{field:"evmCode"}),t.evmLogs!==void 0&&typeof t.evmLogs!="function"&&z("bad-input",{field:"evmLogs"}),t.evmBlock!==void 0&&typeof t.evmBlock!="function"&&z("bad-input",{field:"evmBlock"}),t.allowedProviders!==void 0&&t.allowedProviders!==null){let o=t.allowedProviders;!Array.isArray(o)&&typeof o!="function"&&z("bad-input",{field:"allowedProviders"})}if(t.knownFactoryCodes!==void 0&&t.knownFactoryCodes!==null&&!Array.isArray(t.knownFactoryCodes)&&z("bad-input",{field:"knownFactoryCodes"}),t.knownImplementationCodes!==void 0&&t.knownImplementationCodes!==null&&!Array.isArray(t.knownImplementationCodes)&&z("bad-input",{field:"knownImplementationCodes"}),t.denylist!==void 0&&t.denylist!==null&&(!Array.isArray(t.denylist)||t.denylist.some(o=>typeof o!="string"))&&z("bad-input",{field:"denylist"}),t.createRecord!==void 0&&typeof t.createRecord!="function"&&z("bad-input",{field:"createRecord"}),t.watch!==void 0){let o=t.watch;(!o||typeof o!="object"||Array.isArray(o))&&z("bad-input",{field:"watch"});for(let i of["pollMs","timeoutMs"])o[i]!==void 0&&!(Number.isFinite(Number(o[i]))&&Number(o[i])>0)&&z("bad-input",{field:"watch."+i})}return{settlement:{chain:n.chain,vm:n.vm},xmrNetwork:t.xmrNetwork,assetsBase:typeof t.assetsBase=="string"&&t.assetsBase?t.assetsBase:"/",mode:r,storage:t.storage||null,fetch:t.fetch||null,now:t.now||null,routing:t.routing||null,endpoints:t.endpoints||null,nodes:t.nodes===void 0?null:t.nodes,addNodes:t.addNodes===void 0?null:t.addNodes,evmCall:t.evmCall||null,evmCode:t.evmCode||null,evmLogs:t.evmLogs||null,evmBlock:t.evmBlock||null,allowedProviders:t.allowedProviders===void 0?null:t.allowedProviders,knownFactoryCodes:t.knownFactoryCodes===void 0?null:t.knownFactoryCodes,knownImplementationCodes:t.knownImplementationCodes===void 0?null:t.knownImplementationCodes,denylist:t.denylist===void 0?null:t.denylist,watch:t.watch||null,createRecord:t.createRecord||null}};function w_(e){let t=m_(e),n=yy({settlement:t.settlement,xmrNetwork:t.xmrNetwork,assetsBase:t.assetsBase,mode:t.mode,routing:t.routing,endpoints:t.endpoints,watch:t.watch,nodes:t.nodes,addNodes:t.addNodes}),r=by({chain:n.settlement.chain,knownFactoryCodes:t.knownFactoryCodes}),o=gy({chain:n.settlement.chain,knownImplementationCodes:t.knownImplementationCodes}),i=Qr(n.settlement.vm),s=pb({settlement:n.settlement.chain,leg:i}),a=lb({config:{...n,evmNetwork:n.settlement.chain},wallet:s,limits:n.limits}),c=t.mode==="sim"?db():null,l=Xn.createStore(t.storage||Xn.storage()),u=(()=>{let y=t.allowedProviders;if(y==null)return null;if(typeof y=="function")return I=>y(I)===!0;let k=new Set(y.map(I=>String(I).toLowerCase()));return I=>k.has(String(I).toLowerCase())})(),f=Array.isArray(t.denylist)&&t.denylist.length?new Set(t.denylist.map(y=>String(y).toLowerCase())):null,h=vd({config:n,now:t.now||(()=>Date.now()),evmCall:t.evmCall||null,evmCode:t.evmCode||null,evmBlock:t.evmBlock||null,providerAllowed:u,knownFactoryCodes:r,knownImplementationCodes:o,denylist:f}),m=Oi({call:t.evmCall}),w=typeof t.evmCall=="function"?{call:t.evmCall}:{},x=typeof t.evmLogs=="function"?{logs:t.evmLogs}:{};return Object.freeze({config:n,wallet:s,preflight:a,recovery:Ed(),actions:m,order:{context:y=>_t(y),verifyCounterparty:y=>Uy(y),jointAddress:y=>Zr(y),escrowNativeWei:y=>Ue.escrowNativeWei(y),status:y=>ur(y,w),deadlines:y=>dr(y,w),decline:(y,k={})=>xb(y,{...x,...k||{}})},sim:c,quotes:{firmRelay:y=>h.firmRelay(y)},swaps:jd({preflight:a,mode:t.mode,xmrNetwork:t.xmrNetwork,call:t.evmCall,now:t.now||null,evmBlock:t.evmBlock||null,store:l,logs:t.evmLogs||null,config:n,denylist:f,watch:t.watch,createRecord:t.createRecord}),sweep:qb({call:t.evmCall})})}fe();var Vd=e=>typeof e=="string"&&/^0x[0-9a-f]+$/i.test(e)?Number.parseInt(e,16):null,$d=/^0x[0-9a-fA-F]{40}$/,Qb=e=>"0x"+Number(e).toString(16),y_=4902,b_=e=>(e&&(e.code||e.data&&e.data.originalError&&e.data.originalError.code))===y_||/unrecognized chain|not added/i.test(String(e&&e.message||"")),Zb=e=>e&&e.code===4001||/rejected|denied/i.test(String(e&&e.message||""));function g_(e,{id:t="evm"}={}){let n=[];return{vm:"evm",id:t,async connect({chainId:r=null}={}){try{await e.request({method:"eth_requestAccounts"})}catch(o){let i=o&&(o.code===4001||o.code==="ACTION_REJECTED"),s=new Error(i?"wallet-rejected":"wallet-not-connected");throw s.code=i?"wallet-rejected":"wallet-not-connected",s}Number.isFinite(r)&&Vd(await e.request({method:"eth_chainId"}).catch(()=>null))!==Number(r)&&await this.switchChain(r)},async disconnect(){for(;n.length;){let[r,o]=n.pop();typeof e.removeListener=="function"&&e.removeListener(r,o)}},async address(){let r=await e.request({method:"eth_accounts"}).catch(()=>null),o=Array.isArray(r)?r[0]:null;return typeof o=="string"&&$d.test(o)?o:null},async chainId(){return Vd(await e.request({method:"eth_chainId"}).catch(()=>null))},subscribe(r){if(typeof e.on!="function")return()=>{};for(let o of["accountsChanged","chainChanged"]){let i=()=>r();e.on(o,i),n.push([o,i])}return()=>{}},async switchChain(r){let o=Number(r),i=Qb(o);try{await e.request({method:"wallet_switchEthereumChain",params:[{chainId:i}]})}catch(s){if(!b_(s))throw new d(Zb(s)?"wallet-rejected":"wrong-chain",{vm:"evm"});let a=typeof ce.chainByChainId=="function"?ce.chainByChainId(o):null;if(!a)throw new d("wrong-chain",{vm:"evm",chainId:o});try{await e.request({method:"wallet_addEthereumChain",params:[{chainId:i,chainName:a.name,nativeCurrency:{name:a.native.symbol,symbol:a.native.symbol,decimals:a.native.decimals},rpcUrls:[a.rpcUrl],blockExplorerUrls:[a.explorerAddr]}]})}catch(c){throw new d(Zb(c)?"wallet-rejected":"wrong-chain",{vm:"evm"})}}},async send({to:r,data:o="0x",value:i=0n,gas:s=null,chainId:a=null,from:c=null}){if(typeof r!="string"||!r)throw new d("bad-input",{field:"send.to"});let l=x=>"0x"+BigInt(x).toString(16),u=Vd(await e.request({method:"eth_chainId"}).catch(()=>null));if(!Number.isSafeInteger(u)||u<=0)throw new d("wrong-chain",{vm:"evm",step:"send",want:a==null?null:Number(a),got:null,why:"unreadable"});let f=a==null?u:Number(a);if(!Number.isSafeInteger(f)||f<=0||u!==f)throw new d("wrong-chain",{vm:"evm",step:"send",want:f,got:u});let h=await e.request({method:"eth_accounts"}),m=Array.isArray(h)?h[0]:null;if(typeof m!="string"||!$d.test(m))throw new d("wallet-not-connected",{step:"send"});if(c!=null){let x=String(c).toLowerCase();if(!$d.test(x))throw new d("bad-input",{field:"send.from"});if(m.toLowerCase()!==x)throw new d("wrong-account",{vm:"evm",step:"send",want:x,got:m})}let w={from:m,to:r,data:o,value:l(i),chainId:Qb(u)};return s!=null&&(w.gas=l(s)),await e.request({method:"eth_sendTransaction",params:[w]})},async receipt(r){if(typeof r!="string"||!r)throw new d("bad-input",{field:"receipt.txHash"});return await e.request({method:"eth_getTransactionReceipt",params:[r]})},async signTypedData(r){if(!r||typeof r!="object")throw new d("bad-input",{field:"signTypedData"});let o=await e.request({method:"eth_accounts"}),i=Array.isArray(o)?o[0]:null;if(!i)throw new d("wallet-not-connected",{step:"signTypedData"});let s=await e.request({method:"eth_signTypedData_v4",params:[i,JSON.stringify(r)]});if(typeof s!="string"||!/^0x[0-9a-fA-F]{130}$/.test(s))throw new d("wallet-rejected",{step:"signTypedData",why:"bad-signature-shape"});return s},driver(){return e}}}function x_(e="ninsei.sdk"){let t=n=>e+"."+n;return{get(n){return localStorage.getItem(t(n))},set(n,r){localStorage.setItem(t(n),String(r))},remove(n){localStorage.removeItem(t(n))}}}function k_(e={}){let t=new Map(Object.entries(e));return{get:n=>t.has(n)?t.get(n):null,set:(n,r)=>t.set(n,String(r)),remove:n=>t.delete(n)}}export{Js as CHECK_CODES,Kr as ERROR_CODES,Zs as STEP_CODES,d as SdkError,Oi as createActions,w_ as createNinsei,vd as createQuotes,Ed as createRecovery,jd as createSwaps,g_ as evmWallet,x_ as localStorageAdapter,k_ as memoryAdapter};
|
|
2054
2055
|
/*! Bundled license information:
|
|
2055
2056
|
|
|
2056
2057
|
@noble/curves/utils.js:
|