@ninsei-labs/sdk 0.57.2 → 0.59.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 +22 -0
- package/README.md +82 -32
- package/THIRD_PARTY_NOTICES.md +7 -4
- package/assets/vendors/MANIFEST.json +1 -9
- package/assets/vendors/sdk/sdk-browser.js +4 -6
- package/engine/core/config.js +5 -24
- package/engine/core/deployments.generated.js +33 -0
- package/engine/core/rfqSource.js +6 -133
- package/engine/core/swap.js +1 -1
- package/engine/evm/index.js +3 -2
- package/engine/evm/session.js +46 -277
- 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 +79 -17
- package/engine/monero/wallet.js +31 -68
- package/engine/monero/wordlist.en.js +210 -0
- package/engine/recovery/restore.js +1 -1
- package/engine/sdk/bridge.js +7 -182
- package/engine/ui/walletModal.js +7 -27
- package/index.d.ts +248 -254
- package/package.json +6 -7
- package/src/codes.mjs +12 -0
- package/src/config.mjs +16 -54
- package/src/engine.mjs +3 -0
- package/src/index.mjs +25 -46
- package/src/order.mjs +2 -2
- package/src/public/networks.d.ts +9 -0
- package/src/public/networks.mjs +1 -0
- package/src/public/recovery.d.ts +17 -1
- package/src/public/recovery.mjs +1 -0
- package/src/public/xmr.d.ts +8 -0
- package/src/public/xmr.mjs +1 -1
- package/src/quotePolicy.mjs +58 -0
- package/src/quotes.mjs +30 -753
- package/src/readyWindow.mjs +76 -0
- package/src/record.mjs +4 -0
- package/src/recovery-key.mjs +39 -2
- package/src/recovery.mjs +11 -28
- package/src/relayClaim.mjs +132 -0
- package/src/relayFirmClient.mjs +3 -0
- package/src/relayQuote.mjs +5 -1
- package/src/swap-flow.mjs +49 -5
- package/src/swaps.mjs +530 -317
- package/src/sweep-action.mjs +73 -0
- package/src/sweep.mjs +7 -1
- package/src/version.mjs +1 -1
- package/src/witness-slice.mjs +84 -0
- package/src/xmr-arrival.mjs +378 -9
- package/src/xmrAmountPolicy.mjs +35 -0
- 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
|
@@ -1,5 +1,5 @@
|
|
|
1
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 yx=Object.defineProperty;var se=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Le=(e,t)=>{for(var n in t)yx(e,n,{get:t[n],enumerable:!0})};function Cc(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(Or).find(n=>Number(n.chainRef)===Number(t))??null:Or[t]??Object.values(Or).find(n=>n.caip2===t)??null}var ls,Oc,Or,tp,np,rp=se(()=>{ls=e=>{if(e&&typeof e=="object"){Object.freeze(e);for(let t of Object.values(e))ls(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"]}},Or=ls(Oc),tp=ls(Object.keys(Oc).sort()),np=ls([...new Set(Object.values(Oc).map(e=>e.vm))].sort())});var ue={};Le(ue,{ALLOWED_PROVIDERS:()=>ip,API:()=>an,APP:()=>Vo,ASYNC_ROUTE_PROVIDERS:()=>ds,CHAINS:()=>Yt,DEFAULT_CHAIN:()=>Rt,DEMO:()=>cn,DEPLOYMENTS:()=>Or,DEPLOYMENT_CHAINS:()=>tp,DEPLOYMENT_VMS:()=>np,DEX_ASSETS:()=>op,DEX_CHAINS:()=>xx,DEX_HUBS:()=>kx,DEX_PRICE_GATE:()=>vx,DEX_ROUTES:()=>Sx,ENDPOINTS:()=>us,EVM:()=>rr,KNOWN_FACTORY_CODES:()=>sp,MONERO:()=>Te,SCENARIO_LABELS:()=>Ix,SIGNING_DOMAIN:()=>gx,SIGNING_GUARDS:()=>$o,SWEEP:()=>Hc,TEST_CLAIMER:()=>_x,TIMING:()=>Ht,XMR_NETWORKS:()=>cp,allowedProvidersFor:()=>Lc,chainByChainId:()=>Mc,chainById:()=>it,deploymentFor:()=>Cc,knownFactoryCodesFor:()=>Fc,knownImplementationCodesFor:()=>Dc,nativeOf:()=>ap,sweepOrigin:()=>Nx,tokenById:()=>Ax,tokensOf:()=>Uc,wrappedNativeOf:()=>Ex});function Lc(e){let t=typeof e=="string"?e:e&&e.id,n=ip[t];return!Array.isArray(n)||n.length===0?null:n.map(r=>String(r).toLowerCase())}function Fc(e){let t=typeof e=="string"?e:e&&e.id,n=sp[t];return!Array.isArray(n)||n.length===0?null:n.map(r=>String(r).toLowerCase())}function Dc(e){let t=typeof e=="string"?e:e&&e.id,n=Yt.find(o=>o.id===t)||it(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 it(e){return Yt.find(t=>t.id===e)||Yt.find(t=>t.id===Rt)||Yt[0]}function Mc(e){return Yt.find(t=>t.chainId===Number(e))||null}function Uc(e){let t=it(e);return[ap(e),...t.tokens]}function ap(e){let t=it(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 Ex(e){return(it(e).tokens||[]).find(n=>n&&n.peg==="native")||null}function Ax(e,t){let n=e,r=t;typeof e=="string"&&e.includes(":")&&([n,r]=e.split(":"));let o=Uc(n);return o.find(i=>i.symbol===String(r).toUpperCase())||o[0]}function Nx(){let e=typeof location<"u"?location.hostname:"";return/^(localhost|127\.0\.0\.1|\[::1\])$/.test(e)||/\.local$/.test(e)?Hc.localOrigin:Hc.origin}var Cr,Rr,Rc,us,bx,gx,Vo,xx,op,kx,vx,$o,Sx,ds,Yt,Rt,ip,sp,_x,Te,an,cp,Hc,rr,Ht,cn,Ix,kt=se(()=>{rp();Cr=typeof window<"u"&&window.NINSEI_DEPLOY?window.NINSEI_DEPLOY:null,Rr=typeof process<"u"&&process.env?process.env:null,Rc=Object.freeze({moneroNode:"http://127.0.0.1:38081",evmRpc:"http://127.0.0.1:8545",sweepOrigin:"http://localhost:5195"}),us=Object.freeze({moneroNode:Cr&&Cr.moneroNode||Rr&&Rr.NINSEI_MONERO_NODE||Rc.moneroNode,evmRpc:Cr&&Cr.evmRpc||Rr&&Rr.NINSEI_EVM_RPC||Rc.evmRpc,sweepOrigin:Cr&&Cr.sweepOrigin||Rr&&Rr.NINSEI_SWEEP_ORIGIN||Rc.sweepOrigin}),bx=typeof location<"u"?location.origin:"",gx=Object.freeze({name:"NinseiEscrowFactory",version:"1"}),Vo={name:"NinseiSwap",version:"0.1.0",demo:!0,storageKey:"ninsei.demo.v1"},xx=["arbitrum-sepolia","arbitrum","mainnet"],op=["USDT","USDC","DAI","USDS","USDe","PyUSD"],kx=["USDC","USDT","DAI"],vx={maxDeviationPct:2,stableBandPct:1,stables:op},$o={minReadyLeadSec:600,minClaimWindowSec:600,maxDeadlineSec:259200,readyLeadWarnSec:600},Sx={"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}}},ds={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"}}}},Yt=[{id:"arbitrum-sepolia",name:"Arbitrum Sepolia",vm:"evm",chainId:421614,caip2:"eip155:421614",testnet:!0,native:{symbol:"ETH",decimals:18,usd:3212.4},rpcUrl:us.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:Cc("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"}]}],Rt="arbitrum-sepolia",ip={"local-anvil":["0x60af2ad4963c738aa6ac16d6cb0af1982508ba21"]};sp=Object.freeze(Object.fromEntries(Object.values(Or).filter(e=>e.status==="live"&&e.knownFactoryCodes.length>0).map(e=>[e.network,[...e.knownFactoryCodes]])));_x="0xc14C7841C7d6350859474dD6DF8dC9672047A6A0",Te={networkType:"stagenet",confirmTarget:10,blockTimeSim:12e4,blockTimeReal:12e4,node:us.moneroNode,nodePollMs:3e4},an={base:null,xmrSource:"app",pollMs:5e3,maxProviders:5,timeoutMs:6e4},cp={app:"stagenet",mock:"stagenet",fakechain:"fakechain"};Hc={origin:us.sweepOrigin,localOrigin:"http://localhost:5195"},rr={projectId:"18c13c05b6c0ab011ffff7cee0700e2d",metadata:{name:"NinseiSwap",description:"Non-custodial XMR <-> EVM atomic swap. Demo build: real wallet, real balances, no real funds move.",url:bx,icons:[]}},Ht={quoteValid:12e3,quoteRefresh:5e3,fundingMined:6e3,makerLock:3e4,xmrConfirm:Te.blockTimeSim,readyWindow:60*6e4,makerClaim:45e3,sweep:3e4,t0Refund:20*6e4,t1Refund:40*6e4,watchtowerGrace:5*6e4,makerReclaim:10*6e4},cn={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:Rt},Ix={happy:"happy path",maker_no_lock:"maker never locks XMR",user_no_ready:"user never confirms",maker_stall:"maker stalls after ready"}});var Se={};Le(Se,{allowanceVerdict:()=>Cx,counterpartyVerdict:()=>Hx,deadlineVerdict:()=>Kc,escrowPointsVerdict:()=>jc,escrowStateVerdict:()=>Wc,gasReserveVerdict:()=>Px,liveOrderSlotsVerdict:()=>Lx,networkGateVerdict:()=>Rx,payBalanceVerdict:()=>Bx,quoteFreshnessVerdict:()=>Ox,rangeVerdict:()=>Tx,signingGateVerdict:()=>Fx,signingGateWords:()=>Dx});function Tx({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=Me(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:Me(n),max:Me(r),step:Me(o),unit:s};let l=Me(n),u=Me(r),d=Me(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 ${vt(c)} ${s} is below the provider minimum ${vt(l)} ${s} - short by ${vt(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 ${vt(c)} ${s} is above the provider maximum ${vt(u)} ${s} - over by ${vt(c-u)} ${s}: the provider does not take this size`};if(d!==null&&d>0){let h=l!==null?l:0,w=(c-h)/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 ${vt(c)} ${s} does not sit on the ${vt(d)} ${s} step from ${vt(h)} ${s}`}}return{ok:!0,checked:!0,blocks:!1,kind:"in-range",...p,reason:`the order size ${vt(c)} ${s} is inside the provider range ${l===null?"?":vt(l)}..${u===null?"?":vt(u)} ${s}`}}function Bx({payBalanceWei:e=null,payAmountWei:t=null,symbol:n=null,decimals:r=18}={}){let o=or(e),i=or(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 ${tt(o,r)} ${n} but the order locks ${tt(i,r)} ${n} - short by ${tt(i-o,r)} ${n}`}:{ok:!0,checked:!0,blocks:!1,kind:"balance-enough",haveWei:o.toString(),needWei:i.toString(),reason:`the wallet holds ${tt(o,r)} ${n} for the order's ${tt(i,r)} ${n}`}}function Px({nativeBalanceWei:e=null,requiredNativeWei:t=null,gasReserveWei:n=null,symbol:r=null,decimals:o=18}={}){let i=or(t),s=or(n),a=or(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 ${tt(i,o)} ${r} plus ${tt(s,o)} ${r} of gas, but the wallet holds ${tt(a,o)} ${r} - short by ${tt(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 ${tt(a,o)} ${r}: ${tt(i,o)} for the order and ${tt(s,o)} for gas`}}function Ox({at:e=null,ttlMs:t=null,expiresAt:n=null,nowMs:r=null}={}){let o=Me(r)===null?Date.now():Number(r),i=Me(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=Me(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=Me(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 Kc({nowSec:e=null,readyBy:t=null,t1:n=null,minReadyLeadSec:r=null,minClaimWindowSec:o=null,maxDeadlineSec:i=null}={}){let s=Me(e)===null?Math.floor(Date.now()/1e3):Number(e),a=Me(t),c=Me(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=Me(r),u=Me(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=Me(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 Wc({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 Cx({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=or(n),a=or(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 ${tt(a,i)} ${o||""} but the swap spends ${tt(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 ${tt(a,i)} ${o||""} covers the swap of ${tt(s,i)} ${o||""}`}}function Rx({walletChainId:e=null,selectedChainId:t=null,settlementChainId:n=null,selectedChainName:r=null}={}){let o=Me(e),i=Me(t),s=Me(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 Hx({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 jc({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(et(n)){if(c=!0,!et(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(et(n)!==et(r))return{ok:!1,checked:!0,blocks:!0,kind:"point-mismatch",reason:`${a} in the escrow (0x${et(r)}) is NOT the point DLEQ proved (0x${et(n)}): the Monero address would be assembled from other halves and the XMR could not be swept after claim`}}if(et(o)){if(c=!0,!et(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(et(o)!==et(i))return{ok:!1,checked:!0,blocks:!0,kind:"commit-mismatch",reason:`${a} in the escrow (0x${et(i)}) is NOT the one we hold (0x${et(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${et(n)&&et(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 Lx({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(!et(t&&t[s]))continue;if(!et(e[s])){i.push(a);continue}let l=jc(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 Fx(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 Dx(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 or,vt,Me,tt,et,Vc=se(()=>{or=e=>{if(e==null||e==="")return null;try{let t=BigInt(e);return t>=0n?t:null}catch{return null}},vt=e=>String(Number(Number(e).toFixed(4))),Me=e=>e==null||e===""?null:Number.isFinite(Number(e))?Number(e):null,tt=(e,t=18)=>{let n=Number(e)/10**Number(t);return Number.isFinite(n)?String(Number(n.toFixed(6))):String(e)};et=e=>e==null?"":String(e).replace(/^0x/i,"").toLowerCase()});function fs(e=16){let t=new Uint8Array(e);return crypto.getRandomValues(t),ln(t)}function ln(e){let t=e instanceof Uint8Array?e:Uint8Array.from(e||[]);return Array.from(t,n=>n.toString(16).padStart(2,"0")).join("")}function $c(){return fs(8)}var ps=se(()=>{});var En={};Le(En,{PREFIX_BY_NETWORK:()=>pp,addressForNetwork:()=>Wx,addressFromKeys:()=>ir,addressPayload:()=>gp,checkAddress:()=>Yc,decodeMoneroBase58:()=>yp,encodeMoneroBase58:()=>bp,formatCheck:()=>Xc,isStagenetShaped:()=>jx,networkFromShape:()=>Hr,prefixFor:()=>hp});function hp(e,t="primary"){let n=pp[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 Xc(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 Hr(e){let t=String(e||"").trim();return Xc(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 jx(e){return Hr(e)==="stagenet"}async function mp(){if(hs)return hs;if(up)return null;try{let e=await import("/assets/vendors/monero/monero-js-browser.js?v=05c682ea");return hs=e.default||e,hs}catch{return up=!0,null}}function dp(e){let t=0n;for(let r of e)t=t<<8n|BigInt(r);let n="";for(;t>0n;)n=wp[Number(t%58n)]+n,t/=58n;return n}function fp(e,t){let n=0n;for(let o of e){let i=Kx.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 yp(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(fp(t.slice(u,u+11),8));s.push(fp(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 bp(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=dp(t.slice(c,c+8));s+="1".repeat(Math.max(0,lp[8]-l.length))+l}let a=dp(t.slice(i));return s+="1".repeat(Math.max(0,lp[o]-a.length))+a,s}function gp({network:e,kind:t="primary",spendPub:n,viewPub:r,paymentId:o}){let i=hp(e,t),s=zc(n,32,"public spend key"),a=zc(r,32,"public view key"),c=[i,...s,...a];if(t==="integrated"){let l=zc(o,8,"payment id");c.push(...l)}return Uint8Array.from(c)}function zc(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 ir({network:e,kind:t="primary",spendPub:n,viewPub:r,paymentId:o},i){if(!i?.keccak256)throw new Error("addressFromKeys needs { keccak256 }");let s=gp({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),bp(c)}async function Yc(e,t={}){let n=String(e||"").trim();if(!Xc(n))return{ok:!1,reason:"Not a Monero address (expected 95 or 106 base58 characters)"};let r=Hr(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 mp();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=yp(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((h,w)=>h===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=Ux[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 Wx({network:e,kind:t="primary",spendPub:n,viewPub:r}){let o=await mp();if(!o)throw new Error("monero-js bundle is not available");return ir({network:e,kind:t,spendPub:n,viewPub:r},{keccak256:o.keccak256,Buffer:o.Buffer})}var lp,Mx,Ux,pp,hs,up,wp,Kx,sr=se(()=>{lp={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},Ux={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"}},pp={mainnet:{primary:18,integrated:19,subaddress:42},stagenet:{primary:24,integrated:25,subaddress:36},testnet:{primary:53,integrated:54,subaddress:63}};hs=null,up=!1;wp="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Kx=(()=>{let e=new Map;return[...wp].forEach((t,n)=>e.set(t,BigInt(n))),e})()});async function xp(){if(ms)return ms;if(ws)throw new Error(ws);try{let e=await import("/assets/vendors/monero/monero-js-browser.js?v=05c682ea");return ms=e.default||e,ms}catch(e){throw ws="monero-js unavailable: "+e.message+" (run npm run build:vendor; for CSP see the deploy notes)",new Error(ws)}}async function Vx({mnemonic:e,network:t=Te.networkType}={}){let n=await xp();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=ln(i.publicSpendKey),l=ln(i.publicViewKey),u=i.subaddress(1,0),d=ir({network:s,kind:"primary",spendPub:c,viewPub:l},a),p=ir({network:s,kind:"subaddress",spendPub:ln(u.publicSpendKey),viewPub:ln(u.publicViewKey)},a);return{source:"monero-js",library:"ebellocchia/monero-js (MIT)",network:s,mnemonic:r,mnemonicWords:r.split(" ").length,seedHex:ln(o),privateSpendKey:ln(i.privateSpendKey),privateViewKey:ln(i.privateViewKey),publicSpendKey:c,publicViewKey:l,address:d,subaddress:p,addressMainnet:i.primaryAddress().encode(),createdAt:Date.now()}}async function ys({network:e=Te.networkType,seed:t}={}){return Vx({mnemonic:t,network:e})}async function kp(){try{return await(await xp()).wallet.initEcc(),{available:!0,info:"mnemonic + keys + addresses ("+Te.networkType+")"}}catch(e){return{available:!1,reason:e.message}}}function vp(e=Te.networkType){return{mainnet:"Monero mainnet",stagenet:"Monero stagenet",testnet:"Monero testnet"}[e]||e}var ms,ws,Gc=se(()=>{kt();ps();sr();ms=null,ws=null});var yt={};Le(yt,{ALG_NONE:()=>gs,ENVELOPE_VERSION:()=>Ap,FILE_MAGIC:()=>Jc,PAYLOAD_VERSION:()=>Xx,UNENCRYPTED_ENVELOPE_VERSION:()=>el,buildPayload:()=>qx,createRecoveryFile:()=>Zx,decryptFile:()=>nl,encryptPayload:()=>Np,envelopeAad:()=>tl,isEncrypted:()=>Qx,recoveryFileName:()=>Jx,scanStartHeight:()=>Gx,validatePayload:()=>xs});function Qc(e){return btoa(String.fromCharCode(...new Uint8Array(e)))}function Zc(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))}function tl(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 _p(e,t,n){let r=await crypto.subtle.importKey("raw",bs.encode(e),qc.name,!1,["deriveKey"]);return crypto.subtle.deriveKey({name:qc.name,salt:t,iterations:n,hash:qc.hash},r,{name:An.name,length:An.keyBits},!1,["encrypt","decrypt"])}function Gx({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:Jc,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 xs(e){let t=i=>{throw new Error("Corrupt recovery file: "+i)};(!e||typeof e!="object")&&t("the content is not an object"),e.magic!==Jc&&t("foreign file (no Ninsei mark)"),Sp.includes(e.version)||t(`payload version ${e.version} is not supported (we support ${Sp.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;Yx.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 Np(e,t){let n=()=>({id:e.swapId,side:e.side,createdAt:e.createdAt,termsHash:e.termsHash||null});if(t==="")return{v:el,alg:gs,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 _p(t,r,6e5),s={id:e.swapId,side:e.side,createdAt:e.createdAt,termsHash:e.termsHash||null},a={v:Ap,alg:Ep,iter:6e5,salt:Qc(r),iv:Qc(o)},c=await crypto.subtle.encrypt({name:An.name,iv:o,tagLength:An.tagLength,additionalData:bs.encode(tl({...a,meta:s}))},i,bs.encode(JSON.stringify(e,Ip)));return{...a,ciphertext:Qc(c),meta:s}}function Qx(e){return!!(e&&typeof e=="object"&&e.alg!==gs)}async function nl(e,t){if(!e||typeof e!="object")throw new Error("Not a recovery file (expecting JSON)");if(!zx.includes(e.v))throw new Error(`Unsupported recovery file version: ${e.v}`);if(e.v===el){if(e.alg!==gs)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!==Ep)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=Zc(e.salt),o=Zc(e.iv),i=await _p(t,r,n),s=e.v>=2?bs.encode(tl(e)):void 0,a=s?{name:An.name,iv:o,tagLength:An.tagLength,additionalData:s}:{name:An.name,iv:o,tagLength:An.tagLength},c;try{c=await crypto.subtle.decrypt(a,i,Zc(e.ciphertext))}catch{throw new Error("Could not decrypt the file: wrong password or the file was altered")}let l;try{l=JSON.parse($x.decode(c))}catch{throw new Error("It decrypted, but the content is not JSON - the file is corrupt")}if(xs(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 Zx(e,t){let n=await Np(e,t);return JSON.stringify(n,Ip,2)}function Jx(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 Ep,An,qc,bs,$x,Jc,Ap,el,gs,zx,Xx,Sp,Yx,Ip,rl=se(()=>{Ep="AES-GCM-256/PBKDF2-SHA256",An=Object.freeze({name:"AES-GCM",tagLength:128,keyBits:256}),qc=Object.freeze({name:"PBKDF2",hash:"SHA-256"}),bs=new TextEncoder,$x=new TextDecoder,Jc="NINSEI-SWAP-RECOVERY",Ap=2,el=3,gs="NONE",zx=[1,2,3],Xx=3,Sp=[1,2,3],Yx=["mainnet","stagenet","testnet","fakechain"];Ip=(e,t)=>typeof t=="bigint"?"0x"+t.toString(16):t});function ks({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[h,w]of Object.entries({ownSpendHalf:r,ownViewHalf:o,otherSpendPoint:i,otherViewPoint:s}))if(w==null||w==="")throw new Error("not set: "+h);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 Tp({halves:e,ownViewHalf:t,otherViewHalf:n}){return"0x"+e.combineHalves(t,BigInt(n)).toString(16).padStart(64,"0")}var ol=se(()=>{});function ek(e,t=!1){return t?{h:Number(e&vs),l:Number(e>>Bp&vs)}:{h:Number(e>>Bp&vs)|0,l:Number(e&vs)|0}}function Ss(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}=ek(e[i],t);[r[i],o[i]]=[s,a]}return[r,o]}function Pp(e,t,n,r){let o=tk(n),i=nk(n);e.setUint32(t,r?i:o,r),e.setUint32(t+4,r?o:i,r)}function Gt(e,t,n,r){let o=(t>>>0)+(r>>>0);return{h:e+n+(o/2**32|0)|0,l:o|0}}var vs,Bp,tk,nk,il,sl,ar,cr,zo,Xo,Op,Cp,Rp,Hp,Lp,Fp,Es=se(()=>{vs=BigInt(4294967295),Bp=BigInt(32);tk=e=>e/2**32|0,nk=e=>e>>>0;il=(e,t,n)=>e>>>n,sl=(e,t,n)=>e<<32-n|t>>>n,ar=(e,t,n)=>e>>>n|t<<32-n,cr=(e,t,n)=>e<<32-n|t>>>n,zo=(e,t,n)=>e<<64-n|t>>>n-32,Xo=(e,t,n)=>e>>>n-32|t<<64-n;Op=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Cp=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Rp=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Hp=(e,t,n,r,o)=>t+n+r+o+(e/2**32|0)|0,Lp=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Fp=(e,t,n,r,o,i)=>t+n+r+o+i+(e/2**32|0)|0});function As(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Fe(e,t=""){if(typeof e!="number")throw new TypeError(_s(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(_s(t)+"expected integer >= 0, got "+e);return e}function Up(e,t=""){if(typeof e!="boolean")throw new TypeError(_s(t)+"expected boolean, got type="+typeof e);return e}function We(e,t,n=""){if(As(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Fe(t,"length");let r=As(e),o=t!==void 0?` of length ${t}`:"",i=r?`length=${e.length}`:`type=${typeof e}`,s=_s(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(Fe(e.outputLen),Fe(e.blockLen),e.outputLen<1||e.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}function un(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){We(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function al(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function st(...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 Lt(e,t){return e<<32-t|e>>>t}function sk(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function ak(e){for(let t=0;t<e.length;t++)e[t]=sk(e[t]);return e}function Ns(e){if(We(e),jp)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=ck[e[n]];return t}function Mp(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Is(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(jp)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=Mp(e.charCodeAt(i)),a=Mp(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 lk(e){if(typeof e!="string")throw new TypeError("string expected");let t=new TextEncoder().encode(e);try{return new Uint8Array(t)}finally{st(t)}}function ll(e,t=""){return typeof e=="string"?lk(e):We(e,void 0,t)}function ul(...e){let t=0;for(let r=0;r<e.length;r++){let o=e[r];We(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 Ts(e,t,n="opts"){return Dp(e,"defaults"),t!==void 0&&Dp(t,n),Object.assign(Object.create(null),e,t)}function Yo(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=Ts({},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 dl(e=32){Fe(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 _s,ok,Dp,ik,cl,jp,ck,Go,qt=se(()=>{_s=e=>e?`"${e}" `:"";ok=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},Dp=(e,t)=>{ok(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`)};ik=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;cl=ik?e=>e:ak,jp=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ck=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));Go=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])})});function Kp(e,t,n){return e&t^~e&n}function Wp(e,t,n){return e&t^e&n^t&n}var qo,Vp,$p,zp=se(()=>{Es();qt();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){un(this),We(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){un(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)),Pp(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()}},Vp=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),$p=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});var uk,_n,fl,pl,Xp,dk,fk,Nn,In,hl,ml,Bs,Qo,Ps=se(()=>{zp();Es();qt();uk=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]),_n=new Uint32Array(64),fl=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)_n[d]=t.getUint32(n,!1);for(let d=16;d<64;d++){let p=_n[d-15],h=_n[d-2],w=Lt(p,7)^Lt(p,18)^p>>>3,y=Lt(h,17)^Lt(h,19)^h>>>10;_n[d]=y+_n[d-7]+w+_n[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=Lt(a,6)^Lt(a,11)^Lt(a,25),h=u+p+Kp(a,c,l)+uk[d]+_n[d]|0,y=(Lt(r,2)^Lt(r,13)^Lt(r,22))+Wp(r,o,i)|0;u=l,l=c,c=a,a=s+h|0,s=i,i=o,o=r,r=h+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(){st(_n)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),st(this.buffer)}},pl=class extends fl{constructor(){super(32,Vp)}},Xp=Ss(["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))),dk=Xp[0],fk=Xp[1],Nn=new Uint32Array(80),In=new Uint32Array(80),hl=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:h,Gl:w,Hh:y,Hl:k}=this;return[t,n,r,o,i,s,a,c,l,u,d,p,h,w,y,k]}set(t,n,r,o,i,s,a,c,l,u,d,p,h,w,y,k){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=h|0,this.Gl=w|0,this.Hh=y|0,this.Hl=k|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let v=0;v<16;v++,n+=4)Nn[v]=t.getUint32(n),In[v]=t.getUint32(n+=4);for(let v=16;v<80;v++){let H=Nn[v-15]|0,b=In[v-15]|0,I=ar(H,b,1)^ar(H,b,8)^il(H,b,7),O=cr(H,b,1)^cr(H,b,8)^sl(H,b,7),S=Nn[v-2]|0,T=In[v-2]|0,N=ar(S,T,19)^zo(S,T,61)^il(S,T,6),V=cr(S,T,19)^Xo(S,T,61)^sl(S,T,6),X=Rp(O,V,In[v-7],In[v-16]),m=Hp(X,I,N,Nn[v-7],Nn[v-16]);Nn[v]=m|0,In[v]=X|0}let{Ah:r,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:p,Fh:h,Fl:w,Gh:y,Gl:k,Hh:x,Hl:_}=this;for(let v=0;v<80;v++){let H=ar(d,p,14)^ar(d,p,18)^zo(d,p,41),b=cr(d,p,14)^cr(d,p,18)^Xo(d,p,41),I=d&h^~d&y,O=p&w^~p&k,S=Lp(_,b,O,fk[v],In[v]),T=Fp(S,x,H,I,dk[v],Nn[v]),N=S|0,V=ar(r,o,28)^zo(r,o,34)^zo(r,o,39),X=cr(r,o,28)^Xo(r,o,34)^Xo(r,o,39),m=r&i^r&a^i&a,g=o&s^o&c^s&c;x=y|0,_=k|0,y=h|0,k=w|0,h=d|0,w=p|0,{h:d,l:p}=Gt(l|0,u|0,T|0,N|0),l=a|0,u=c|0,a=i|0,c=s|0,i=r|0,s=o|0;let E=Op(N,X,g);r=Cp(E,T,V,m),o=E|0}({h:r,l:o}=Gt(this.Ah|0,this.Al|0,r|0,o|0)),{h:i,l:s}=Gt(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Gt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Gt(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:p}=Gt(this.Eh|0,this.El|0,d|0,p|0),{h,l:w}=Gt(this.Fh|0,this.Fl|0,h|0,w|0),{h:y,l:k}=Gt(this.Gh|0,this.Gl|0,y|0,k|0),{h:x,l:_}=Gt(this.Hh|0,this.Hl|0,x|0,_|0),this.set(r,o,i,s,a,c,l,u,d,p,h,w,y,k,x,_)}roundClean(){st(Nn,In)}destroy(){this.destroyed=!0,st(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},ml=class extends hl{constructor(){super(64,$p)}},Bs=Yo(()=>new pl,Go(1)),Qo=Yo(()=>new ml,Go(3))});function Cs(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 Gp(e,t=""){if(typeof e!="string"){let n=t&&`"${t}" `;throw new TypeError(n+"expected string, got type="+typeof e)}return e}function Tn(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 lr(e,t){if(typeof e!="function")throw new TypeError(`"${t}" is invalid: expected function, got ${typeof e}`);return e}function ut(e,t=""){if(typeof e!="boolean")throw new TypeError(pk(t)+"expected boolean, got type="+typeof e);return e}function Rs(e){if(typeof e=="bigint"){if(!Bn(e))throw new RangeError("positive bigint expected, got "+e)}else wl(e);return e}function dn(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 Jo(e){let t=Rs(e).toString(16);return t.length&1?"0"+t:t}function qp(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?Os:BigInt("0x"+e)}function Qt(e){return qp(Ns(e))}function dr(e){return qp(Ns(ei(We(e)).reverse()))}function Hs(e,t){if(Fe(t),t===0)throw new Error("zero output length is invalid");e=Rs(e);let n=t*2,r=e.toString(16);if(r.length>n)throw new RangeError("number is too large");return Is(r.padStart(n,"0"))}function yl(e,t){return Hs(e,t).reverse()}function ei(e){return Uint8Array.from(ye(e))}function Bn(e){return typeof e=="bigint"&&Os<=e}function bl(e,t,n){return Bn(e)&&Bn(t)&&Bn(n)&&t<=e&&e<n}function Ur(e,t,n,r){if(!bl(t,n,r))throw new RangeError("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function jr(e){if(e<Os)throw new Error("expected non-negative bigint, got "+e);return e===Os?0:e.toString(2).length}function Qp(e,t,n){if(Fe(e,"hashLen"),Fe(t,"qByteLen"),typeof n!="function")throw new TypeError("hmacFn must be a function");let r=k=>new Uint8Array(k),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=(...k)=>n(l,St(c,...k)),h=(k=o)=>{l=p(i,k),c=p(),k.length!==0&&(l=p(s,k),c=p())},w=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let k=0,x=[];for(;k<t;){c=p();let _=c.slice();x.push(_),k+=c.length}return St(...x)};return(k,x)=>{d(),h(k);let _;for(;(_=x(w()))===void 0;)h();return d(),_}}function dt(e,t={},n={},r="object"){Tn(e,r),Tn(t,"fields"),Tn(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 ye,wl,Zo,St,Mr,Pn,ur,Os,Yp,pk,ti,Kr=se(()=>{qt();ye=(e,t,n)=>We(e,t,n),wl=Fe;Zo=Ns,St=(...e)=>ul(...e),Mr=e=>Is(e),Pn=As,ur=e=>dl(e),Os=BigInt(0),Yp=BigInt(1),pk=e=>e?`"${e}" `:"";ti=e=>(dn(e,"n"),(Yp<<BigInt(e))-Yp)});function Pe(e,t){if(t<=je)throw new Error("mod: expected positive modulus, got "+t);let n=e%t;return n>=je?n:t+n}function oh(e,t,n){if(n<=be)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<je)throw new Error("invalid exponent, negatives unsupported");if(t===je)return be;if(t===be)return e;let r=e%n;if(r<je&&(r+=n),t<yk){let a=be;for(;t>je;)t&be&&(a=a*r%n),r=r*r%n,t>>=be;return a}let o=[];for(;t>je;)o.push(Number(t&wk)),t>>=gl;let i=new Array(16);i[0]=be,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 Be(e,t,n){if(n<=be)throw new Error("pow2: expected modulus > 1, got "+n);if(t<je)throw new Error("pow2: expected non-negative exponent, got "+t);let r=e;for(;t-- >je;)r*=r,r%=n;return r}function Zp(e,t){if(e===je)throw new Error("invert: expected non-zero number");if(t<=be)throw new Error("invert: expected modulus > 1, got "+t);let n=Pe(e,t),r=t,o=je,i=be;for(;n!==je;){let a=r/n,c=r-n*a,l=o-i*a;r=n,n=c,o=i,i=l}if(r!==be)throw new Error("invert: does not exist");return Pe(o,t)}function ih(e,t){if(t<=be)throw new Error("invertCt: expected prime modulus > 1, got "+t);let n=Pe(e,t);if(n===je)throw new Error("invertCt: expected non-zero number");let r=oh(n,t-On,t);if(Pe(n*r,t)!==be)throw new Error("invertCt: does not exist");return r}function xl(e,t,n){let r=e;if(!r.eql(r.sqr(t),n))throw new Error("Cannot find square root")}function kl(e,t){if((e&be)===je)throw new Error(t+": expected odd modulus, got "+e)}function sh(e,t){let n=e,r=(n.ORDER+be)/gl,o=n.pow(t,r);return xl(n,o,t),o}function bk(e,t){let n=e,r=(n.ORDER-th)/nh,o=n.mul(t,On),i=n.pow(o,r),s=n.mul(t,i),a=n.mul(n.mul(s,On),i),c=n.mul(s,n.sub(a,n.ONE));return xl(n,c,t),c}function gk(e){let t=Vr(e),n=ah(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+hk)/rh;return((a,c)=>{let l=a,u=l.pow(c,s),d=l.mul(u,r),p=l.mul(u,o),h=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(h,p,y);let k=l.eql(l.sqr(d),c),x=l.cmov(u,d,k);return xl(l,x,c),x})}function ah(e){if(e<eh)throw new Error("sqrt is not defined for small field");kl(e,"tonelliShanks");let t=e-be,n=0;for(;t%On===je;)t/=On,n++;let r=On,o=Vr(e);for(;ni(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return sh;let i=o.pow(r,t),s=(t+be)/On;return function(c,l){let u=c;if(u.is0(l))return l;if(ni(u,l)!==1)throw new Error("Cannot find square root");let d=n,p=u.mul(u.ONE,i),h=u.pow(l,t),w=u.pow(l,s);for(;!u.eql(h,u.ONE);){if(u.is0(h))throw new Error("Cannot find square root: probably non-prime P");let y=1,k=u.sqr(h);for(;!u.eql(k,u.ONE);)if(y++,k=u.sqr(k),y===d)throw new Error("Cannot find square root");let x=be<<BigInt(d-y-1),_=u.pow(p,x);d=y,p=u.sqr(_),h=u.mul(h,p),w=u.mul(w,_)}return w}}function xk(e){return kl(e,"Fp.sqrt"),e%gl===eh?sh:e%nh===th?bk:e%rh===mk?gk(e):ah(e)}function Wr(e){if(Tn(e,"field"),typeof e.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof e.ORDER);dn(e.BYTES,"BYTES"),dn(e.BITS,"BITS");for(let t of kk)lr(e[t],"field."+t);if(e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=be)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function Fs(e,t,n=!1){Wr(e),Cs(t,"nums"),ut(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 ni(e,t){Wr(e);let n=e;kl(n.ORDER,"FpLegendre");let r=(n.ORDER-be)/On,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 vk(e,t){if(t!==void 0&&wl(t),e<=je)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}}function Vr(e,t={}){return Object.freeze(Ls.prototype),new Ls(e,t)}function lh(e){if(typeof e!="bigint")throw new Error("field order must be bigint");if(e<=be)throw new Error("field order must be greater than 1");let t=jr(e-be);return Math.ceil(t/8)}function Ds(e){let t=lh(e);return t+Math.ceil(t/2)}function Ms(e,t,n=!1){ye(e);let r=e.length,o=lh(t),i=Math.max(Ds(t),16);if(r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let s=n?dr(e):Qt(e),a=Pe(s,t-be)+be;return n?yl(a,o):Hs(a,o)}var je,be,On,eh,gl,th,hk,nh,mk,wk,rh,yk,ch,kk,Jp,Ls,$r=se(()=>{Kr();je=BigInt(0),be=BigInt(1),On=BigInt(2),eh=BigInt(3),gl=BigInt(4),th=BigInt(5),hk=BigInt(7),nh=BigInt(8),mk=BigInt(9),wk=BigInt(15),rh=BigInt(16),yk=BigInt("0x10000000000000000");ch=(e,t)=>(Pe(e,t)&be)===be,kk=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];Jp=new WeakMap,Ls=class{ORDER;BITS;BYTES;isLE;ZERO=je;ONE=be;_lengths;_mod;constructor(t,n={}){if(t<=be)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}=vk(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 Pe(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof t);return je<=t&&t<this.ORDER}is0(t){return t===je}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&be)===be}neg(t){return Pe(-t,this.ORDER)}eql(t,n){return t===n}sqr(t){return Pe(t*t,this.ORDER)}add(t,n){return Pe(t+n,this.ORDER)}sub(t,n){return Pe(t-n,this.ORDER)}mul(t,n){return Pe(t*n,this.ORDER)}pow(t,n){return oh(t,n,this.ORDER)}div(t,n){return Pe(t*Zp(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 Zp(t,this.ORDER)}sqrt(t){let n=Jp.get(this);return n||Jp.set(this,n=xk(this.ORDER)),n(this,t)}toBytes(t){return this.isLE?yl(t,this.BYTES):Hs(t,this.BYTES)}fromBytes(t,n=!1){ye(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?dr(t):Qt(t);if(a&&(c=Pe(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return Fs(this,t,!0)}cmov(t,n,r){return ut(r,"condition"),r?n:t}}});function Cn(e){let t=e;if(typeof t!="function")throw new TypeError('"Point" expected constructor, got type='+typeof e);lr(t.fromAffine,"Point.fromAffine"),lr(t.fromBytes,"Point.fromBytes"),lr(t.fromHex,"Point.fromHex"),Tn(t.BASE,"Point.BASE"),Tn(t.ZERO,"Point.ZERO"),Wr(t.Fp),Wr(t.Fn)}function Us(e,t){Cn(e),ph(t,e);let n=Fs(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function Ak(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 _k(e,t){let n=e*(4*t+128);if(n>dh)throw new Error("invalid window size: table would need ~"+Math.ceil(n/2**20)+" MiB, max "+dh/2**20+" MiB")}function Al(e,t){if(e!==void 0){lr(e,"randomBytes");try{let n=e(t);if(!Pn(n)||n.length!==t)return}catch{return}return e}}function ph(e,t){Cs(e,"points"),e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function Nk(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):Bn(r)&&r<n))throw new Error("invalid scalar at index "+o)})}function Sl(e){return hh.get(e)||1}function Ik(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 Tk(e,t){let n=2**t,r=n/2,o=BigInt(n-1),i=[];for(;e>El;){let s=0;e&ri&&(s=Number(e&o),s>=r&&(s-=n),e-=BigInt(s)),i.push(s),e>>=ri}return i}function Bk(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+=ri),a.push(l)}if(e!==El)throw new Error("invalid wnaf");return a}function Pk(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 js(e,t,n,r=!1){if(Cn(e),ph(t,e),ut(r,"allowOversized"),Nk(n,e.Fn,r?e.Fn.ORDER**Sk:void 0),t.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=t.map(s=>Ik(s,4)),i=n.map(s=>Tk(s,4));return Pk(e.ZERO,o,i)}function fh(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Wr(t),t}else return Vr(e,{isLE:n})}function Ks(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`);dt(n);for(let c of["p","n","h"]){let l=t[c];if(!(Bn(l)&&l!==El))throw new Error(`CURVE.${c} must be positive bigint`)}let o=fh(t.p,n.Fp,r),i=fh(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 Ws(e,t){return function(r){let o=e(r);return{secretKey:o,publicKey:t(o)}}}var El,ri,Sk,vl,uh,Ek,dh,hh,zr,_l=se(()=>{Kr();$r();El=BigInt(0),ri=BigInt(1),Sk=BigInt(4),vl=16,uh=128,Ek=5,dh=2**31;hh=new WeakMap;zr=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(t,n){Cn(t),this.randomBytes=Al(n,vl),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=Bk(n,r,o),c=this.ZERO,l=this.BASE;for(let u=0;u<o;u++){let d=a[u],p=u*s,h=Math.abs(d)-1,w=i[p];for(let k=1;k<s;k++)w=k===h?i[p+k]: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),!bl(n,ri,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(t,n,r,o){let i=Sl(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+uh,i=this.randomBytes(vl);if(!Pn(i)||i.length!==vl)throw new Error("randomBytes returned invalid byte array");i[0]=i[0]&63|128;let s=n+Qt(i)*this.Point.Fn.ORDER;return this.runCT(t,s,o,r)}fixedWindowCT(t,n,r){let o=Ek,i=1<<o,s=ti(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 h=0;h<o;h++)l=l.double();let d=Number(n>>BigInt(u*o)&s),p=a[0];for(let h=1;h<i;h++)p=h===d?a[h]:p;l=l.add(p)}return{p:l,f:l}}shouldBlind(t,n){return this.randomBytes===void 0?!1:n===ri?!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),!Bn(n))throw new Error("invalid scalar");let o=Sl(t);if(o===1||n>=this.Point.Fn.ORDER)return js(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),Ak(n,this.bits);let r=Math.ceil((this.bits+uh)/n)+1;_k(r*2**(n-1),this.Point.Fp.BYTES),hh.set(t,n),this.wnafPrecomputes.delete(t)}hasWindowSize(t){return Sl(t)!==1}}});function Ck(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 wh(e,t={}){dt(t,{},{},"extraOpts");let n=t,r=Ks("edwards",e,n,n.FpFnLE),{Fp:o,Fn:i}=r,s=r.CURVE,{h:a}=s;if(ni(o,s.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(ni(o,s.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");dt(n,{},{uvRatio:"function",randomBytes:"function"});let c=n.randomBytes===void 0?ur:n.randomBytes,l=zs<<BigInt(o.BYTES*8)-$s;function u(_){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(_)}let d=n.uvRatio===void 0?(_,v)=>{try{return{isValid:!0,value:o.sqrt(o.div(_,v))}}catch{return{isValid:!1,value:Vs}}}:n.uvRatio;if(!Ck(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");let p=o.eql(s.a,o.neg(o.ONE))?_=>o.neg(_):o.eql(s.a,o.ONE)?_=>_:_=>o.mul(s.a,_);function h(_,v,H=!1){let b=H?$s:Vs;return Ur("coordinate "+_,v,b,l),v}function w(_){if(!(_ 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(v,H,b,I){this.X=h("x",v),this.Y=h("y",H),this.Z=h("z",b,!0),this.T=h("t",I),Object.freeze(this)}static CURVE(){return s}static fromAffine(v){if(v instanceof y)throw new Error("extended point not allowed");let{x:H,y:b}=v||{};return h("x",H),h("y",b),new y(H,b,o.ONE,o.mul(H,b))}static fromBytes(v,H=!1){let b=o.BYTES,{a:I,d:O}=s;v=ei(ye(v,b,"point")),ut(H,"zip215");let S=ei(v),T=v[b-1];S[b-1]=T&-129;let N=dr(S),V=H?l:o.ORDER;Ur("point.y",N,Vs,V);let X=o.sqr(N),m=o.sub(X,o.ONE),g=o.sub(o.mulN(O,X),I),{isValid:E,value:C}=d(m,g);if(!E)throw new Error("bad point: invalid y coordinate");let M=u(C),$=(T&128)!==0;if(!H&&o.is0(C)&&$)throw new Error("bad point: x=0 and x_0=1");return $!==M&&(C=o.neg(C)),y.fromAffine({x:C,y:N})}static fromHex(v,H=!1){return y.fromBytes(Mr(v),H)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=6,H=!0){return x.setWindowSize(this,v),H||this.multiply(zs),this}assertValidity(){let v=this,{a:H,d:b}=s;if(v.is0())throw new Error("bad point: ZERO");let{X:I,Y:O,Z:S,T}=v,N=o.sqr(I),V=o.sqr(O),X=o.sqr(S),m=o.sqr(X),g=o.mul(N,H),E=o.mul(o.add(g,V),X),C=o.add(m,o.mul(b,o.mul(N,V)));if(!o.eql(E,C))throw new Error("bad point: equation left != right (1)");let M=o.mul(I,O),$=o.mul(S,T);if(!o.eql(M,$))throw new Error("bad point: equation left != right (2)")}equals(v){w(v);let{X:H,Y:b,Z:I}=this,{X:O,Y:S,Z:T}=v,N=o.mul(H,T),V=o.mul(O,I),X=o.mul(b,T),m=o.mul(S,I);return o.eql(N,V)&&o.eql(X,m)}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:v,Y:H,Z:b}=this,I=o.sqr(v),O=o.sqr(H),S=o.mul(o.sqr(b),zs),T=p(I),N=o.addN(v,H),V=o.sub(o.subN(o.sqr(N),I),O),X=o.addN(T,O),m=o.subN(X,S),g=o.subN(T,O),E=o.mul(V,m),C=o.mul(X,g),M=o.mul(V,g),$=o.mul(m,X);return new y(E,C,$,M)}add(v){w(v);let{d:H}=s,{X:b,Y:I,Z:O,T:S}=this,{X:T,Y:N,Z:V,T:X}=v,m=o.mul(b,T),g=o.mul(I,N),E=o.mul(o.mulN(S,H),X),C=o.mul(O,V),M=o.sub(o.subN(o.mulN(o.addN(b,I),o.addN(T,N)),m),g),$=o.subN(C,E),L=o.addN(C,E),F=o.sub(g,p(m)),B=o.mul(M,$),P=o.mul(L,F),D=o.mul(M,F),U=o.mul($,L);return new y(B,P,U,D)}subtract(v){return w(v),this.add(v.negate())}multiply(v){if(!i.isValidNot0(v))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:H,f:b}=x.mulSecret(this,v,a,k);return k([H,b])[0]}multiplyUnsafe(v){if(!i.isValid(v))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return v===Vs?y.ZERO:this.is0()||v===$s?this:x.mulUnsafe(this,v,k)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return x.mulUnsafe(this,s.n).is0()}toAffine(v){let H=this,b=v;if(b!=null&&typeof b!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof b);let{X:I,Y:O,Z:S}=H,T=H.is0();b==null&&(b=T?o.create(mh):o.inv(S));let N=o.mul(I,b),V=o.mul(O,b),X=o.mul(S,b);if(T)return{x:o.ZERO,y:o.ONE};if(!o.eql(X,o.ONE))throw new Error("invZ was invalid");return{x:N,y:V}}clearCofactor(){return a===$s?this:a===zs?this.double():a===Ok?this.double().double():a===mh?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:v,y:H}=this.toAffine(),b=o.toBytes(H);return b[b.length-1]|=u(v)?128:0,b}toHex(){return Zo(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let k=_=>Us(y,_),x=new zr(y,c);return x.bits>=6&&y.BASE.precompute(6),Object.freeze(y.prototype),Object.freeze(y),y}function yh(e,t,n={}){if(Cn(e),typeof t!="function")throw new Error('"hash" function param is required');let r=t,o=n;dt(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&&(dn(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let d=o.randomBytes===void 0?ur:o.randomBytes,p=o.toMontgomery,h=o.toMontgomerySecret,w=o.adjustScalarBytes===void 0?g=>g:o.adjustScalarBytes,y=o.domain===void 0?(g,E,C)=>{if(ut(C,"phflag"),E.length||C)throw new Error("Contexts/pre-hash are not supported");return g}:o.domain;function k(g){return c.create(dr(g))}function x(g){let E=T.secretKey;ye(g,T.secretKey,"secretKey");let C=ye(r(g),2*E,"hashedSecretKey"),M=w(C.slice(0,E)),$=C.slice(E,2*E),L=k(M);return{head:M,prefix:$,scalar:L}}function _(g){let{head:E,prefix:C,scalar:M}=x(g),$=s.multiply(M),L=$.toBytes();return{head:E,prefix:C,scalar:M,point:$,pointBytes:L}}function v(g){return _(g).pointBytes}function H(g=Uint8Array.of(),...E){let C=St(...E);return k(r(y(C,ye(g,void 0,"context"),!!i)))}function b(g,E,C={}){dt(C,{},{},"options"),g=ei(ye(g,void 0,"message")),i&&(g=i(g));let{prefix:M,scalar:$,pointBytes:L}=_(E),F=H(C.context,M,g),B=s.multiply(F).toBytes(),P=H(C.context,B,L,g),D=c.create(F+P*$);if(!c.isValid(D))throw new Error("sign failed: invalid s");let U=St(B,c.toBytes(D));return ye(U,T.signature,"result")}let I={zip215:o.zip215};function O(g,E,C,M=I){dt(M);let{context:$}=M,L=M.zip215===void 0?!!I.zip215:M.zip215,F=T.signature;g=ye(g,F,"signature"),E=ye(E,void 0,"message"),C=ye(C,T.publicKey,"publicKey"),L!==void 0&&ut(L,"zip215"),i&&(E=i(E));let B=F/2,P=g.subarray(0,B),D=dr(g.subarray(B,F)),U,q,W;try{U=e.fromBytes(C,L),q=e.fromBytes(P,L),W=s.multiplyUnsafe(D)}catch{return!1}if(!L&&U.isSmallOrder())return!1;let G=H($,P,C,E);return q.add(U.multiplyUnsafe(G)).subtract(W).clearCofactor().is0()}let S=a.BYTES,T={secretKey:S,publicKey:S,signature:2*S,seed:S};function N(g){return g=g===void 0?d(T.seed):g,ye(g,T.seed,"seed")}function V(g){return Pn(g)&&g.length===T.secretKey}function X(g,E){try{return!!e.fromBytes(g,E===void 0?I.zip215:E)}catch{return!1}}let m={getExtendedPublicKey:_,randomSecretKey:N,isValidSecretKey:V,isValidPublicKey:X,toMontgomery(g){if(p===void 0)throw new Error("Montgomery conversion is not supported for this curve");return p(e.fromBytes(g))},toMontgomerySecret(g){if(h===void 0)throw new Error("Montgomery conversion is not supported for this curve");return h(g)}};return Object.freeze(T),Object.freeze(m),Object.freeze({keygen:Ws(N,v),getPublicKey:v,sign:b,verify:O,utils:m,Point:e,lengths:T})}var Vs,$s,zs,Ok,mh,bh=se(()=>{Kr();_l();$r();Vs=BigInt(0),$s=BigInt(1),zs=BigInt(2),Ok=BigInt(4),mh=BigInt(8)});function Fk(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=Il,a=e*e%i*e%i,c=Be(a,gh,i)*a%i,l=Be(c,Nl,i)*e%i,u=Be(l,Rk,i)*l%i,d=Be(u,t,i)*u%i,p=Be(d,n,i)*d%i,h=Be(p,r,i)*p%i,w=Be(h,o,i)*h%i,y=Be(w,o,i)*h%i,k=Be(y,t,i)*u%i;return{pow_p_5_8:Be(k,gh,i)*e%i,b2:a}}function vh(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function Dk(e,t){let n=Il,r=Pe(t*t*t,n),o=Pe(r*r*t,n),i=Fk(e*o).pow_p_5_8,s=Pe(e*r*i,n),a=Pe(t*s*s,n),c=s,l=Pe(s*xh,n),u=a===e,d=a===Pe(-e,n),p=a===Pe(-e*xh,n);return u&&(s=c),(d||p)&&(s=l),ch(s,n)&&(s=Pe(-s,n)),{isValid:u||d,value:s}}function Mk(e){let{y:t}=e;return kh.toBytes(kh.div(Nl+t,Nl-t))}function Uk(e){let t=Tl.Fp.BYTES;return We(e,t),vh(Qo(e.subarray(0,t))).subarray(0,t)}function jk(e){return yh(Tl,Qo,Object.assign({adjustScalarBytes:vh,toMontgomery:Mk,toMontgomerySecret:Uk,zip215:!0},e))}var Nl,gh,Rk,Hk,Il,Lk,xh,Tl,kh,Ge,Bl=se(()=>{Ps();qt();bh();$r();Nl=BigInt(1),gh=BigInt(2),Rk=BigInt(5),Hk=BigInt(8),Il=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Lk={p:Il,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Hk,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};xh=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");Tl=wh(Lk,{uvRatio:Dk}),kh=Tl.Fp;Ge=jk({})});var Xs,Ys,Pl=se(()=>{qt();Xs=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(t,n){if(Lr(t),We(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),st(o)}update(t){return un(this),this.iHash.update(t),this}digestInto(t){un(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()}},Ys=(()=>{let e=((t,n,r)=>new Xs(t,n).update(r).digest());return e.create=(t,n)=>new Xs(t,n),e})()});var Kk,Ol,fn,Gs,Sh=se(()=>{Kr();Kk=BigInt(0),Ol=class extends Error{constructor(t=""){super(t)}},fn={Err:Ol,_tlv:{encode:(e,t)=>{let{Err:n}=fn;if(dn(e,"tag"),e<0||e>255)throw new n("tlv.encode: wrong tag");if(Gp(t,"data"),t.length&1)throw new n("tlv.encode: unpadded data");let r=t.length/2,o=Jo(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");let i=r>127?Jo(o.length/2|128):"";return Jo(e)+i+o+t},decode(e,t){let{Err:n}=fn;t=ye(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}=fn;if(Rs(e),e<Kk)throw new t("integer: negative integers are not allowed");let n=Jo(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}=fn;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 Qt(e)}},toSig(e,t){let{Err:n,_int:r,_tlv:o}=fn;if(t!==void 0&&(dn(t,"maxScalarBytes"),t<1))throw new n("invalid signature: maxScalarBytes must be positive");let i=ye(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}=fn;dt(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)}},Gs=(Object.freeze(fn._tlv),Object.freeze(fn._int),Object.freeze(fn))});function Wk(e,t,n){Ur("scalar",e,pn,n);let[[r,o],[i,s]]=t,a=Eh(s*e,n),c=Eh(-o*e,n),l=e-a*r-c*i,u=-a*o-c*s,d=l<pn,p=u<pn;d&&(l=-l),p&&(u=-u);let h=ti(Math.ceil(jr(n)/2))+fr;if(l<pn||l>=h||u<pn||u>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:d,k1:l,k2neg:p,k2:u}}function Hl(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function Cl(e,t){dt(e);let n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return ut(n.lowS,"lowS"),ut(n.prehash,"prehash"),n.format!==void 0&&Hl(n.format),n}function _h(e,t={}){let n=Ks("weierstrass",e,t),r=n.Fp,o=n.Fn,i=n.CURVE,{h:s,n:a}=i;dt(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:h}=t,w=t.randomBytes===void 0?ur: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(F=>[...F])}:void 0,k=Ih(r,o);function x(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function _(F,B,P){if(B.is0()){if(!l)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:D,y:U}=B.toAffine(),q=r.toBytes(D);if(ut(P,"isCompressed"),P){x();let W=!r.isOdd(U);return St(Nh(W),q)}else return St(Uint8Array.of(4),q,r.toBytes(U))}function v(F){ye(F,void 0,"Point");let{publicKey:B,publicKeyUncompressed:P}=k,D=F.length,U=F[0],q=F.subarray(1);if(l&&D===1&&U===0)return{x:r.ZERO,y:r.ZERO};if(D===B&&(U===2||U===3)){let W=r.fromBytes(q);if(!r.isValid(W))throw new Error("bad point: is not on curve, wrong x");let G=S(W),z;try{z=r.sqrt(G)}catch(A){let j=A instanceof Error?": "+A.message:"";throw new Error("bad point: is not on curve, sqrt error"+j)}x();let ee=r.isOdd(z);return(U&1)===1!==ee&&(z=r.neg(z)),{x:W,y:z}}else if(D===P&&U===4){let W=r.BYTES,G=r.fromBytes(q.subarray(0,W)),z=r.fromBytes(q.subarray(W,W*2));if(!T(G,z))throw new Error("bad point: is not on curve");return{x:G,y:z}}else throw new Error(`bad point: got length ${D}, expected compressed=${B} or uncompressed=${P}`)}let H=h===void 0?_:h,b=p===void 0?v:p,I=r.mul(i.b,Rl),O=r.is0(i.a)?F=>r.ZERO:F=>r.mul(i.a,F);function S(F){let B=r.sqr(F),P=r.mul(B,F);return r.add(r.add(P,r.mul(F,i.a)),i.b)}function T(F,B){let P=r.sqr(B),D=S(F);return r.eql(P,D)}if(!T(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let N=r.mul(r.pow(i.a,Rl),Vk),V=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(N,V)))throw new Error("bad curve params: a or b");function X(F,B,P=!1){if(!r.isValid(B)||P&&r.is0(B))throw new Error(`bad point coordinate ${F}`);return typeof B=="object"&&B!==null?r.create(B):B}function m(F){if(!(F instanceof M))throw new Error("Weierstrass Point expected")}function g(F){if(!y||!y.basises)throw new Error("no endo");return Wk(F,y.basises,o.ORDER)}function E(F,B,P,D){if(!o.isValid(D))throw new RangeError("invalid scalar: out of range");if(y){let{k1neg:U,k1:q,k2neg:W,k2:G}=g(D),z=new M(r.mul(P.X,y.beta),P.Y,P.Z);F.push(U?P.negate():P,W?z.negate():z),B.push(q,G)}else F.push(P),B.push(D)}let C=new WeakSet;class M{static BASE=new M(i.Gx,i.Gy,r.ONE);static ZERO=new M(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=o;X;Y;Z;constructor(B,P,D){this.X=X("x",B),this.Y=X("y",P,!0),this.Z=X("z",D),Object.freeze(this)}static CURVE(){return i}static fromAffine(B){let{x:P,y:D}=B||{};if(!B||!r.isValid(P)||!r.isValid(D))throw new Error("invalid affine point");if(B instanceof M)throw new Error("projective point not allowed");return r.is0(P)&&r.is0(D)?M.ZERO:new M(P,D,r.ONE)}static fromBytes(B){let P=M.fromAffine(b(ye(B,void 0,"point")));return P.assertValidity(),P}static fromHex(B){return M.fromBytes(Mr(B))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(B=6,P=!0){return L.setWindowSize(this,B),P||this.multiply(Rl),this}assertValidity(){let B=this;if(B.is0()){if(l&&r.is0(B.X)&&r.eql(B.Y,r.ONE)&&r.is0(B.Z))return;throw new Error("bad point: ZERO")}if(C.has(B))return;let{x:P,y:D}=B.toAffine();if(!r.isValid(P)||!r.isValid(D))throw new Error("bad point: x or y not field elements");if(!T(P,D))throw new Error("bad point: equation left != right");if(!B.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");C.add(B)}hasEvenY(){let{y:B}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(B)}equals(B){m(B);let{X:P,Y:D,Z:U}=this,{X:q,Y:W,Z:G}=B,z=r.eql(r.mul(P,G),r.mul(q,U)),ee=r.eql(r.mul(D,G),r.mul(W,U));return z&&ee}negate(){return new M(this.X,r.neg(this.Y),this.Z)}double(){let{X:B,Y:P,Z:D}=this,U=r.ZERO,q=r.ZERO,W=r.ZERO,G=r.mul(B,B),z=r.mul(P,P),ee=r.mul(D,D),Q=r.mul(B,P);return Q=r.add(Q,Q),W=r.mul(B,D),W=r.add(W,W),U=O(W),q=r.mul(I,ee),q=r.add(U,q),U=r.sub(z,q),q=r.add(z,q),q=r.mul(U,q),U=r.mul(Q,U),W=r.mul(I,W),ee=O(ee),Q=r.sub(G,ee),Q=O(Q),Q=r.add(Q,W),W=r.add(G,G),G=r.add(W,G),G=r.add(G,ee),G=r.mul(G,Q),q=r.add(q,G),ee=r.mul(P,D),ee=r.add(ee,ee),G=r.mul(ee,Q),U=r.sub(U,G),W=r.mul(ee,z),W=r.add(W,W),W=r.add(W,W),new M(U,q,W)}add(B){m(B);let{X:P,Y:D,Z:U}=this,{X:q,Y:W,Z:G}=B,z=r.ZERO,ee=r.ZERO,Q=r.ZERO,A=r.mul(P,q),j=r.mul(D,W),K=r.mul(U,G),Z=r.add(P,D),Y=r.add(q,W);Z=r.mul(Z,Y),Y=r.add(A,j),Z=r.sub(Z,Y),Y=r.add(P,U);let ne=r.add(q,G);return Y=r.mul(Y,ne),ne=r.add(A,K),Y=r.sub(Y,ne),ne=r.add(D,U),z=r.add(W,G),ne=r.mul(ne,z),z=r.add(j,K),ne=r.sub(ne,z),Q=O(Y),z=r.mul(I,K),Q=r.add(z,Q),z=r.sub(j,Q),Q=r.add(j,Q),ee=r.mul(z,Q),j=r.add(A,A),j=r.add(j,A),K=O(K),Y=r.mul(I,Y),j=r.add(j,K),K=r.sub(A,K),K=O(K),Y=r.add(Y,K),A=r.mul(j,Y),ee=r.add(ee,A),A=r.mul(ne,Y),z=r.mul(Z,z),z=r.sub(z,A),A=r.mul(Z,j),Q=r.mul(ne,Q),Q=r.add(Q,A),new M(z,ee,Q)}subtract(B){return m(B),this.add(B.negate())}is0(){return this.equals(M.ZERO)}multiply(B){if(!o.isValidNot0(B))throw new RangeError("invalid scalar: out of range");let{p:P,f:D}=L.mulSecret(this,B,s,$);return $([P,D])[0]}multiplyUnsafe(B){let P=this,D=B;if(!o.isValid(D))throw new RangeError("invalid scalar: out of range");if(D===pn||P.is0())return M.ZERO;if(D===fr)return P;if(L.hasWindowSize(this))return L.mulUnsafe(P,D,$);let U=[],q=[];return E(U,q,P,D),js(M,U,q)}mulAddUnsafe(B,P,D){m(P);let U=[],q=[];return E(U,q,this,B),E(U,q,P,D),js(M,U,q)}toAffine(B){let P=this,D=B;if(D!=null&&!r.isValid(D))throw new RangeError('"invertedZ" expected valid field element');let{X:U,Y:q,Z:W}=P;if(r.eql(W,r.ONE))return{x:U,y:q};let G=P.is0();D==null&&(D=G?r.ONE:r.inv(W));let z=r.mul(U,D),ee=r.mul(q,D),Q=r.mul(W,D);if(G)return{x:r.ZERO,y:r.ZERO};if(!r.eql(Q,r.ONE))throw new Error("invZ was invalid");return{x:z,y:ee}}isTorsionFree(){return s===fr?!0:d?d(M,this):L.mulUnsafe(this,a).is0()}clearCofactor(){return s===fr?this:u?u(M,this):this.multiplyUnsafe(s)}isSmallOrder(){return s===fr?this.is0():this.clearCofactor().is0()}toBytes(B=!0){return ut(B,"isCompressed"),this.assertValidity(),H(M,this,B)}toHex(B=!0){return Zo(this.toBytes(B))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let $=F=>Us(M,F),L=new zr(M,w);return L.bits>=6&&M.BASE.precompute(6),Object.freeze(M.prototype),Object.freeze(M),M}function Nh(e){return Uint8Array.of(e?2:3)}function Ih(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function $k(e,t={}){Cn(e);let{Fn:n}=e,r=t.randomBytes===void 0?ur:t.randomBytes,o=Object.assign(Ih(e.Fp,n),{seed:Math.max(Ds(n.ORDER),16)});function i(h){try{let w=n.fromBytes(h);return n.isValidNot0(w)}catch{return!1}}function s(h,w){let{publicKey:y,publicKeyUncompressed:k}=o;try{let x=h.length;return w===!0&&x!==y||w===!1&&x!==k?!1:!e.fromBytes(h).is0()}catch{return!1}}function a(h){return h=h===void 0?r(o.seed):h,Ms(ye(h,o.seed,"seed"),n.ORDER)}function c(h,w=!0){return e.BASE.multiply(n.fromBytes(h)).toBytes(w)}function l(h){let{secretKey:w,publicKey:y,publicKeyUncompressed:k}=o,x=n._lengths;if(!Pn(h))return;let _=ye(h,void 0,"key").length,v=_===y||_===k,H=_===w||!!x?.includes(_);if(!(v&&H))return v}function u(h,w,y=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(w)===!1)throw new Error("second arg must be public key");let k=n.fromBytes(h),x=e.fromBytes(w);if(x.is0())throw new Error("invalid public key: point at infinity");return x.multiply(k).toBytes(y)}let d={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},p=Ws(a,c);return Object.freeze(d),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:p,Point:e,utils:d,lengths:o})}function Th(e,t,n={}){Cn(e);let r=t;Lr(r),dt(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let o=Object.assign({},n),i=o.randomBytes===void 0?ur:o.randomBytes,s=o.hmac===void 0?(F,B)=>Ys(r,F,B):o.hmac,{Fp:a,Fn:c}=e,{ORDER:l,BITS:u}=c,d=Ds(l),p=Al(i,d),{keygen:h,getPublicKey:w,getSharedSecret:y,utils:k,lengths:x}=$k(e,o),_={prehash:!0,lowS:typeof o.lowS=="boolean"?o.lowS:!0,format:"compact",extraEntropy:!1},v=l*Ah+fr<a.ORDER;function H(F){let B=l>>fr;return F>B}function b(F,B){if(!c.isValidNot0(B))throw new Error(`invalid signature ${F}: out of range 1..Point.Fn.ORDER`);return B}function I(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function O(F,B,P){return I(),(F===P?0:2)|Number(a.isOdd(B))}function S(){if(v)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function T(F,B){Hl(B);let P=x.signature,D=B==="compact"?P:B==="recovered"?P+1:void 0;return ye(F,D)}class N{r;s;recovery;constructor(B,P,D){if(this.r=b("r",B),this.s=b("s",P),D!=null){if(S(),![0,1,2,3].includes(D))throw new Error("invalid recovery id");this.recovery=D}Object.freeze(this)}static fromBytes(B,P=_.format){T(B,P);let D;if(P==="der"){if(B.length>2*c.BYTES+16)throw new Gs.Err("invalid signature: DER signature too long");let{r:G,s:z}=Gs.toSig(ye(B),c.BYTES+1);return new N(G,z)}P==="recovered"&&(D=B[0],P="compact",B=B.subarray(1));let U=x.signature/2,q=B.subarray(0,U),W=B.subarray(U,U*2);return new N(c.fromBytes(q),c.fromBytes(W),D)}static fromHex(B,P){return this.fromBytes(Mr(B),P)}assertRecovery(){let{recovery:B}=this;if(B==null)throw new Error("invalid recovery id: must be present");return B}addRecoveryBit(B){return new N(this.r,this.s,B)}recoverPublicKey(B){let{r:P,s:D}=this,U=this.assertRecovery(),q=U===2||U===3?P+l:P;if(!a.isValid(q))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let W=a.toBytes(q),G=e.fromBytes(St(Nh((U&1)===0),W)),z=c.inv(q),ee=X(ye(B,void 0,"msgHash")),Q=c.create(-ee*z),A=c.create(D*z),j=e.BASE.mulAddUnsafe(Q,G,A);if(j.is0())throw new Error("invalid recovery: point at infinify");return j.assertValidity(),j}hasHighS(){return H(this.s)}toBytes(B=_.format){if(Hl(B),B==="der")return Mr(Gs.hexFromSig(this));let{r:P,s:D}=this,U=c.toBytes(P),q=c.toBytes(D);return B==="recovered"?(S(),St(Uint8Array.of(this.assertRecovery()),U,q)):St(U,q)}toHex(B){return Zo(this.toBytes(B))}}Object.freeze(N.prototype),Object.freeze(N);let V=o.bits2int===void 0?function(B){if(B.length>8192)throw new Error("input is too large");let P=Qt(B),D=B.length*8-u;return D>0?P>>BigInt(D):P}:o.bits2int,X=o.bits2int_modN===void 0?function(B){return c.create(V(B))}:o.bits2int_modN,m=ti(u);function g(F){return Ur("num < 2^"+u,F,pn,m),c.toBytes(F)}function E(F,B){return ye(F,void 0,"message"),B?ye(r(F),void 0,"prehashed message"):F}function C(F,B,P){let{lowS:D,prehash:U,extraEntropy:q}=Cl(P,_);F=E(F,U);let W=X(F),G=c.fromBytes(B);if(!c.isValidNot0(G))throw new Error("invalid private key");let z=[g(G),g(W)];if(q!=null&&q!==!1){let j=q===!0?i(x.secretKey):q;z.push(ye(j,void 0,"extraEntropy"))}let ee=St(...z),Q=W;function A(j){let K=V(j);if(!c.isValidNot0(K))return;let Z=e.BASE.multiply(K).toAffine(),Y=c.create(Z.x);if(Y===pn)return;let ne;if(p!==void 0){let ke=Qt(Ms(p(d),l)),we=c.inv(c.mul(ke,K)),re=c.mul(ke,Q),ie=c.mul(ke,G);ne=c.create(we*c.create(re+ie*Y))}else{let ke=ih(K,l);ne=c.create(ke*c.create(Q+Y*G))}if(ne===pn)return;let oe=O(Z.x,Z.y,Y),pe=ne;return D&&H(ne)&&(pe=c.neg(ne),oe^=1),new N(Y,pe,v?void 0:oe)}return{seed:ee,k2sig:A}}function M(F,B,P={}){let{seed:D,k2sig:U}=C(F,B,P);return Qp(r.outputLen,c.BYTES,s)(D,U).toBytes(P.format)}function $(F,B,P,D={}){let{lowS:U,prehash:q,format:W}=Cl(D,_);if(P=ye(P,void 0,"publicKey"),B=E(B,q),!Pn(F)){let G=F instanceof N?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+G)}T(F,W);try{let G=N.fromBytes(F,W),z=e.fromBytes(P);if(z.is0()||U&&G.hasHighS())return!1;let{r:ee,s:Q}=G,A=X(B),j=c.inv(Q),K=c.create(A*j),Z=c.create(ee*j),Y=e.BASE.mulAddUnsafe(K,z,Z);if(Y.is0())return!1;let ne=Y.toAffine();return!(c.create(ne.x)!==ee||W==="recovered"&&G.recovery!==O(ne.x,ne.y,ee))}catch{return!1}}function L(F,B,P={}){let{prehash:D}=Cl(P,_);return B=E(B,D),N.fromBytes(F,"recovered").recoverPublicKey(B).toBytes()}return Object.freeze({keygen:h,getPublicKey:w,getSharedSecret:y,utils:k,lengths:x,Point:e,sign:M,verify:$,recoverPublicKey:L,Signature:N,hash:r})}var Eh,pn,fr,Ah,Rl,Vk,Bh=se(()=>{Pl();qt();Kr();_l();Sh();$r();Eh=(e,t)=>(e+(e>=0?t:-t)/Ah)/t;pn=BigInt(0),fr=BigInt(1),Ah=BigInt(2),Rl=BigInt(3),Vk=BigInt(4)});function Xk(e){let t=Fl.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=Be(u,n,t)*u%t,p=Be(d,n,t)*u%t,h=Be(p,Ph,t)*l%t,w=Be(h,o,t)*h%t,y=Be(w,i,t)*w%t,k=Be(y,a,t)*y%t,x=Be(k,c,t)*k%t,_=Be(x,a,t)*y%t,v=Be(_,n,t)*u%t,H=Be(v,s,t)*w%t,b=Be(H,r,t)*l%t,I=Be(b,Ph,t);if(!Ll.eql(Ll.sqr(I),e))throw new Error("Cannot find square root");return I}var Fl,zk,Ph,Ll,Yk,Ve,Oh=se(()=>{Ps();$r();Bh();Fl={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},zk={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Ph=BigInt(2);Ll=Vr(Fl.p,{sqrt:Xk}),Yk=_h(Fl,{Fp:Ll,endo:zk}),Ve=Th(Yk,Bs)});function s1(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(Fe(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++)Xr[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=Xr[a],l=Xr[a+1],u=Ch(c,l,1)^Xr[s],d=Rh(c,l,1)^Xr[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=Lh[i],a=Ch(r,o,s),c=Rh(r,o,s),l=Hh[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]^=e1[n],e[1]^=t1[n]}st(Xr)}var Gk,oi,qk,Qk,Zk,Jk,Hh,Lh,Fh,Dh,e1,t1,n1,r1,o1,i1,Ch,Rh,Xr,Dl,Mh,Ml,qs,Ul=se(()=>{Es();qt();Gk=BigInt(0),oi=BigInt(1),qk=BigInt(2),Qk=BigInt(7),Zk=BigInt(256),Jk=BigInt(113),Hh=[],Lh=[],Fh=[];for(let e=0,t=oi,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],Hh.push(2*(5*r+n)),Lh.push((e+1)*(e+2)/2%64);let o=Gk;for(let i=0;i<7;i++)t=(t<<oi^(t>>Qk)*Jk)%Zk,t&qk&&(o^=oi<<(oi<<BigInt(i))-oi);Fh.push(o)}Dh=Ss(Fh,!0),e1=Dh[0],t1=Dh[1],n1=(e,t,n)=>e<<n|t>>>32-n,r1=(e,t,n)=>t<<n|e>>>32-n,o1=(e,t,n)=>t<<n-32|e>>>64-n,i1=(e,t,n)=>e<<n-32|t>>>64-n,Ch=(e,t,n)=>n>32?o1(e,t,n):n1(e,t,n),Rh=(e,t,n)=>n>32?i1(e,t,n):r1(e,t,n),Xr=new Uint32Array(10);Dl=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(Fe(t,"blockLen"),Fe(n,"suffix"),Fe(i,"rounds"),Up(o,"enableXOF"),this.blockLen=t,this.suffix=n,this.outputLen=r,this.enableXOF=o,this.canXOF=o,this.rounds=i,Fe(r,"outputLen"),!(0<t&&t<200))throw new Error('"blockLen" must be 1..199');this.state=new Uint8Array(200),this.state32=al(this.state)}clone(){return this._cloneInto()}keccak(){cl(this.state32),s1(this.state32,this.rounds),cl(this.state32),this.posOut=0,this.pos=0}update(t){un(this),We(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?al(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){un(this,!1),We(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 Fe(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,st(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}},Mh=(e,t,n,r={})=>Yo(()=>new Dl(t,e,n),r),Ml=Mh(6,72,64,Go(10)),qs=Mh(1,136,32)});var f,R,xe=se(()=>{f=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}}},R=(e,t)=>{throw new f(e,t)}});var Uh={};Le(Uh,{ed25519:()=>Ge,keccak256:()=>J,keccak256Bytes:()=>a1,primitives:()=>hn,randomBytes:()=>ii,secp256k1:()=>Ve,sha3_512:()=>Ml});var J,a1,ii,hn,$e=se(()=>{Bl();Oh();Ul();xe();J=e=>{let t=typeof e=="string"?new TextEncoder().encode(e):e;return qs(t)},a1=e=>J(e),ii=e=>{let t=new Uint8Array(e),n=globalThis.crypto;return(!n||typeof n.getRandomValues!="function")&&R("bad-input",{field:"random-bytes",why:"no-source"}),n.getRandomValues(t),t},hn={ed25519:Ge,secp256k1:Ve,keccak256:J,sha3_512:Ml,randomBytes:ii}});var mn={};Le(mn,{createHalves:()=>si});function si({ed25519:e,secp256k1:t,keccak256:n,randomBytes:r}){for(let[x,_]of[["ed25519",e],["secp256k1",t],["keccak256",n],["randomBytes",r]])if(!_)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 _=r(32),v=0n;for(let H of _)v=v<<8n|BigInt(H);if(v>0n&&v<s)return v}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,_,v=c){if(!x||x.length<16)throw new Error("halfFromSeed: secret shorter than 16 bytes");if(!_)throw new Error("halfFromSeed: order binding not set");let H=new TextEncoder().encode(v+"|"+String(_)+"|");for(let b=0;b<256;b++){let I=new Uint8Array(H.length+x.length+4);I.set(H,0),I.set(x,H.length),I[H.length+x.length]=b>>>24&255,I[H.length+x.length+1]=b>>>16&255,I[H.length+x.length+2]=b>>>8&255,I[H.length+x.length+3]=b&255;let O=n(I),S=0n;for(let T of O)S=S<<8n|BigInt(T);if(S>0n&&S<s)return S}throw new Error("halfFromSeed: could not get a scalar in 256 attempts")}function d(x,_){return x.fromHex(_.startsWith("0x")?_.slice(2):_)}function p(x){if(typeof x=="bigint")return x;if(typeof x=="string"){let _=x.trim().replace(/^0x/,"");if(!/^[0-9a-fA-F]{1,64}$/.test(_))throw new Error("half does not look like a number: "+x.slice(0,12));return BigInt("0x"+_)}if(typeof x=="number")return BigInt(x);throw new Error("half of unknown type: "+typeof x)}function h(x){return x.toHex()}function w(x){return{ed:h(e.Point.BASE.multiply(p(x))),secp:h(t.Point.BASE.multiply(p(x)))}}function y(x,_){return(p(x)+p(_))%o}function k(x,_){return h(d(e.Point,x).add(d(e.Point,_)))}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:k}}var ai=se(()=>{});var Qs={};Le(Qs,{assertNoSecretsInShare:()=>Wh,restoreFromFile:()=>c1,restoreFromHalves:()=>Kh,restoreWalletFromPayload:()=>jh,watchOnlyShareFromWallet:()=>l1});async function jh(e,t={}){let{warnings:n}=xs(e),r=e.moneroWallet,o=r.network||e.moneroNetwork;if(e.version>=3)return await Kh(e,n,t);let i=await ys({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 Kh(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(()=>($e(),Uh)),{createHalves:u}=await Promise.resolve().then(()=>(ai(),mn)),{addressFromKeys:d}=await Promise.resolve().then(()=>(sr(),En));return{halves:u(l),addressFromKeys:d,keccak256:l.keccak256}})();if(!i.keccak256)throw new Error("no keccak256: the address cannot be checked without it");let s=ks({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=Tp({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 c1(e,t,n={}){return jh(await nl(e,t),n)}function Wh(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 l1({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 Wh({swapId:e||null,network:t.network,address:t.address,privateViewKey:t.privateViewKey,restoreHeight:Number.isFinite(n)?n:null},t)}var Vh=se(()=>{Gc();rl();ol()});var hr={};Le(hr,{bindStorage:()=>f1,createStore:()=>p1,exportState:()=>w1,loadState:()=>ft,memoryStorage:()=>$h,reset:()=>m1,saveState:()=>Zt,setStorage:()=>d1,storage:()=>Wl,update:()=>h1});function $h(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 d1(e){return Kl(e),Rn=e,Zs=null,Rn}function f1(e){if(Kl(e),Zs&&Zs!==e)throw pr("conflict");return Zs=e,Rn=e,Rn}function zh(e){let t;try{t=e.get(Vo.storageKey)}catch(r){throw pr("read",r)}if(t==null||t==="")return structuredClone(jl);let n;try{n=JSON.parse(t)}catch(r){throw pr("parse",r)}if(!n||typeof n!="object"||Array.isArray(n))throw pr("parse");return{...structuredClone(jl),...n,settings:{...jl.settings,...n.settings||{}}}}function ft(){return zh(Rn)}function Yh(e,t){let n;try{n=JSON.stringify(t,Xh)}catch(r){throw pr("serialize",r)}try{e.set(Vo.storageKey,n)}catch(r){throw pr("write",r)}return t}function Zt(e){return Yh(Rn,e)}function p1(e){return Kl(e),{loadState:()=>zh(e),saveState:t=>Yh(e,t),storage:()=>e}}function h1(e){let t=ft(),n=e(t)||t;return Zt(n),n}function m1(){try{Rn.remove(Vo.storageKey)}catch(e){throw pr("remove",e)}}function w1(){return JSON.stringify(ft(),Xh,2)}var jl,u1,Rn,Zs,Kl,pr,Wl,Xh,Js=se(()=>{kt();jl={version:1,settings:{speed:cn.defaultSpeed,scenario:cn.defaultScenario,chainMode:cn.defaultChainMode,chain:cn.defaultChain,payToken:""},wallet:{connected:!1,address:null,balances:{}},swaps:{},activeSwapId:null};u1=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)}},Rn=u1("localStorage")||$h(),Zs=null,Kl=e=>{if(!(e&&typeof e.get=="function"&&typeof e.set=="function"&&typeof e.remove=="function"))throw new Error("storage must support get/set/remove")},pr=(e,t)=>{let n=new Error("storage-unavailable");return n.code="storage-unavailable",n.params={step:e},t&&(n.cause=t),n};Wl=()=>Rn;Xh=(e,t)=>typeof t=="bigint"?"0x"+t.toString(16):t});function Vl(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 b1(e){return e?e.isMetaMask?"MetaMask":e.isRabby?"Rabby":e.isCoinbaseWallet?"Coinbase Wallet":e.isBraveWallet?"Brave Wallet":e.isFrame?"Frame":"Browser wallet":null}function ci({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(Gh,i),typeof e.dispatchEvent=="function"&&e.dispatchEvent(new Event(y1))),new Promise(s=>{let a=()=>{e&&typeof e.removeEventListener=="function"&&e.removeEventListener(Gh,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:b1(u),icon:null,rdns:null,provider:u,source:"legacy"})}s(n)};t>0&&typeof setTimeout=="function"?setTimeout(a,t):a()})}async function qh(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 Qh(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 Zh(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 Gh,y1,$l=se(()=>{Gh="eip6963:announceProvider",y1="eip6963:requestProvider"});function Oe(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 Jh(e,t=""){let n=document.getElementById("arToasts");if(!n)return;let r=Oe("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 em(e,t="Copied"){let n=()=>Jh(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{Jh("Copy failed","bad")}o.remove()}}var tm=se(()=>{});function nm({title:e="Connect a wallet",subtitle:t="",hint:n=""}={}){let r={},o=Oe("div",{class:"ar-overlay"},[Oe("div",{class:"ar-modal"},[Oe("div",{class:"ar-modal-head"},[Oe("div",{class:"ar-modal-title",text:e}),r.closeBtn=Oe("button",{class:"ar-modal-close",type:"button",title:"Close",text:"\xD7"})]),r.subtitle=Oe("div",{class:"ar-modal-sub",text:t}),r.choices=Oe("div",{class:"ar-modal-choices"}),r.qrBox=Oe("div",{class:"ar-modal-qr",hidden:!0},[r.qr=Oe("img",{alt:"WalletConnect QR code"})]),r.uri=Oe("code",{class:"ar-modal-uri"}),r.status=Oe("div",{class:"ar-modal-status"}),Oe("div",{class:"ar-modal-actions"},[r.copyBtn=Oe("button",{class:"ar-btn-ghost",type:"button",text:"Copy link"}),r.cancelBtn=Oe("button",{class:"ar-btn-ghost",type:"button",text:"Cancel"})]),r.hint=Oe("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&&em(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=Oe("button",{class:"ar-modal-choice",type:"button"},[d.icon?Oe("img",{class:"ar-modal-choice-icon",src:d.icon,alt:""}):Oe("span",{class:"ar-modal-choice-icon ar-modal-choice-icon-empty"}),Oe("span",{class:"ar-modal-choice-text"},[Oe("span",{class:"ar-modal-choice-name",text:d.name}),d.hint?Oe("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:h,hint:w,error:y}={}){if(i.value)return;u&&(r.qr.src=u,r.qrBox.hidden=!1),d!==void 0&&(r.uri.textContent=d||""),h!==void 0&&(r.subtitle.textContent=h||""),w!==void 0&&(r.hint.textContent=w||"");let k=y||p;k!==void 0&&(r.status.className="ar-modal-status"+(y?" ar-modal-status-error":""),r.status.textContent=k||"")}}}var rm=se(()=>{tm()});function om(e,t){return Number(e)/10**t}function g1(e){let t=String(e);return t.includes(".")?t.replace(/0+$/,"").replace(/\.$/,""):t}function x1(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 im(e,t=6){let n=x1(e,t);if(!Number.isFinite(n)||n<=0)return"0";let r=n>=10**-t?t:18;return g1(n.toFixed(r))}var t8,zl=se(()=>{t8=[[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 ta={};Le(ta,{CLAIM_GAS_LIMIT:()=>Xl,CLAIM_TIP_FLOOR_WEI:()=>sm,DEFAULT_GIFT_RESERVE_BPS:()=>cm,claimGasGiftWei:()=>Yl,claimMaxFeePerGasWei:()=>ea,claimRequiredWei:()=>am});function ea({baseFeeWei:e,priorityFeeWei:t=0n,minTipWei:n=sm}={}){let r=Yr(e);if(r===null||r<=0n)return null;let o=Yr(t),i=Yr(n),s=i===null||i<0n?0n:i,a=o!==null&&o>s?o:s;return r*2n+a}function am({gasLimit:e=Xl,maxFeePerGasWei:t}={}){let n=Yr(e),r=Yr(t);return n===null||n<=0n||r===null||r<=0n?null:n*r}function Yl({baseFeeWei:e,priorityFeeWei:t,minTipWei:n,gasLimit:r=Xl,reserveBps:o=cm}={}){let i=ea({baseFeeWei:e,priorityFeeWei:t,minTipWei:n}),s=am({gasLimit:r,maxFeePerGasWei:i});if(s===null)return null;let a=Yr(o),c=a===null||a<0n?0n:a;return s+s*c/10000n}var Xl,sm,Yr,cm,na=se(()=>{Xl=200000n,sm=0n,Yr=e=>{if(e==null||e==="")return null;try{return BigInt(typeof e=="bigint"?e:String(e))}catch{return null}};cm=10000n});function at(){for(let e of Zl)try{e(Hn())}catch(t){console.warn("wallet listener failed",t)}}function Hn(){return{...te,balances:{...te.balances}}}function dm(e){return Zl.add(e),()=>Zl.delete(e)}function fm(){return Hn()}function en(){return te.status==="connected"&&!!te.address}function mr(){return te.address}function pm(){return te.chainId}function li(){return de}function hm(e,t){let n=it(e),r=te.balances[`${n.chainId}:${String(t).toUpperCase()}`];return r===void 0?0:r}async function mm(){return Gl||(Gl=await import("/assets/vendors/walletconnect/wc-browser.js?v=fb64f27c")),Gl}function v1(){let e={};for(let t of Yt)e[t.chainId]=t.rpcUrl;return e}function bt(e="idle",t=null){te.status=e,te.error=t,te.kind=null,te.label=null,te.address=null,te.chainId=null,te.balances={},de=null,at()}function eu(e){e.on("chainChanged",t=>{te.chainId=Number(t),te.error=null,at(),Jt()}),e.on("accountsChanged",t=>{let n=t&&t[0]||null;if(!n){Ae&&Ae.close(),bt("idle",null);return}te.address=n,at(),Jt()}),e.on("disconnect",()=>{Ae&&Ae.close(),bt("idle",null)}),e.on("session_delete",()=>{Ae&&Ae.close(),bt("idle",null)})}async function S1(){if(ql||te.status!=="connected"||te.kind!=="walletconnect"||!de)return;ql=!0;let e=de;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{ql=!1}de=null;try{let t=te.chainId||(Yt.find(o=>o.escrow)||{}).chainId,r=await(await tu(t)).request({method:"eth_accounts"});if(!Array.isArray(r)||!r.length){console.log("[wc] no session left in storage - a new QR is needed"),bt("idle",null);return}te.address=r[0],at(),await Jt(),console.log("[wc] session raised again: "+te.address)}catch(t){console.log("[wc] could not raise the session: "+t.message),bt("idle",null)}}async function tu(e){if(de)return de;let{EthereumProvider:t}=await mm();return de=await t.init({projectId:rr.projectId,chains:[e],optionalChains:Yt.filter(n=>n.escrow).map(n=>n.chainId),showQrModal:!1,rpcMap:v1(),metadata:{...rr.metadata,url:location.origin}}),de.on("display_uri",n=>E1(n)),eu(de),de}async function E1(e){if(!(!Ae||Ae.closed.value))try{let{QRCode:t}=await mm(),n=await t.toDataURL(e,{margin:1,width:440,errorCorrectionLevel:"M",color:{dark:"#0a0d13",light:"#ffffff"}});Ae.update({qrDataUrl:n,uri:e,status:"Waiting for the wallet to approve..."})}catch(t){Ae.update({uri:e,status:"Scan failed to render, copy the link instead",error:!0}),console.warn("qr render failed",t)}}async function ym(){if(A1())return Ql=!0,console.log("[wc] restore skipped: wallet disconnected manually"),Hn();if(Ql||te.status==="connected")return Hn();if(Ql=!0,rr.projectId)try{let e=it(te.chainId||void 0),t=await tu(e.chainId),n=t&&t.accounts||[];n.length&&(te.kind="walletconnect",te.label="WalletConnect",te.address=n[0],te.chainId=Number(t.chainId)||e.chainId,te.status="connected",te.error=null,at(),await Jt(),console.info("WalletConnect: session restored after reload",te.address))}catch(e){console.warn("WalletConnect: could not restore the session",e&&e.message?e.message:e)}return en()?Hn():nu()}async function nu({wallets:e}={}){if(en())return Hn();let t=e||await ci();for(let n of t){let r=await Qh(n.provider);if(r.length){de=n.provider,te.kind="injected",te.label=n.name||"Browser wallet",eu(de),te.address=r[0];try{te.chainId=Number(await de.request({method:"eth_chainId"}))||null}catch{te.chainId=null}return te.status="connected",te.error=null,at(),await Jt(),console.info("Browser wallet restored without a prompt: "+te.address),Hn()}}return Hn()}async function ru({wallet:e,chainSlug:t}={}){if(wm(!1),!e||!e.provider)throw new Error("No wallet extension found in this browser");if(en()&&te.kind==="injected"&&te.label===(e.name||null))return{address:te.address,chainId:te.chainId};let n=it(t||te.chainId||void 0);de=e.provider,te.kind="injected",te.label=e.name||"Browser wallet",te.status="pairing",te.error=null,at(),eu(de);try{let r=await qh(de);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,at(),te.chainId!==n.chainId&&await ou(n),await Jt(),{address:te.address,chainId:te.chainId}}catch(r){let o=te.label||e.name||"Wallet",i=Zh(r,o);if(Vl(r))return console.info("[wallet] user refusal: "+i),bt("idle",null),null;throw console.warn("[wallet] connect did not happen: "+i,r),bt("error",i),new Error(i)}}async function bm({chainSlug:e}={}){if(en())return{address:te.address,chainId:te.chainId};let t=it(e||te.chainId||void 0);te.status="pairing",te.error=null,at();let n=await ci();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)"),Ae=nm({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=>{Ae.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})}));rr.projectId&&a.push({key:"walletconnect",name:"WalletConnect",icon:null,hint:"QR code for a mobile wallet",onClick:()=>s({type:"walletconnect"})}),Ae.setChoices(a),Ae.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 bt("idle",null),null;if(r.type==="injected")try{let s=await ru({wallet:r.wallet,chainSlug:t.id});return Ae&&Ae.close(),s}catch(s){let a=String(s&&s.message||s);throw Ae&&Ae.update({error:a,status:"Try again, or use WalletConnect below."}),s}if(!rr.projectId)throw Ae&&Ae.close(),bt("error","no-project-id"),new Error("WalletConnect projectId is not configured");Ae.update({status:"Preparing the session..."});let o=null,i=new Promise((s,a)=>{o=()=>a(new Error("Connection cancelled"))});Ae.setOnCancel(()=>{let s=de;de=null,s&&Promise.resolve(s.disconnect()).catch(()=>{}),bt("idle",null),o&&o()});try{let s=await tu(t.chainId);return await Promise.race([s.connect({chains:[t.chainId]}),i]),te.kind="walletconnect",te.label="WalletConnect",te.address=s.accounts&&s.accounts[0]||null,te.chainId=Number(s.chainId),te.status="connected",te.error=null,Ae&&Ae.close(),at(),await Jt(),{address:te.address,chainId:te.chainId}}catch(s){let a=s&&s.message?String(s.message):String(s);console.warn("WalletConnect connect failed:",a);let c=Vl(s)||/cancell?ed/i.test(a);if(Ae&&Ae.close(),bt(c?"idle":"error",c?null:a),!c)throw s;return null}}async function gm(e){if(!de||te.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 de.request({method:"personal_sign",params:[t,te.address]})}async function xm(){wm(!0);let e=de,t=te.kind;if(!e){bt("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)}bt("idle",null)}async function ou(e){let t=typeof e=="object"?e:it(e);if(!de||!en())return!1;let n=k1(t.chainId);try{await de.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),at()),!1;try{await de.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),at()),!1}}return te.chainId=t.chainId,at(),await Jt(),!0}async function Ln({to:e,data:t,block:n="latest"}={}){if(!de)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 de.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 ra({address:e}={}){if(!de)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 de.request({method:"eth_getCode",params:[e,"latest"]})}async function iu({hash:e}={}){if(!de)throw new Error("wallet not connected: nothing to read the receipt with");if(!e)throw new Error("no transaction hash given");let t=await de.request({method:"eth_getTransactionReceipt",params:[e]});return!t||typeof t!="object"?null:t}async function su({to:e,data:t,value:n="0x0",gas:r}={}){if(!de)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=mr();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 de.request({method:"eth_getBlockByNumber",params:["latest",!1]}),c=a&&a.baseFeePerGas?BigInt(a.baseFeePerGas):0n,l=0n;try{let d=await de.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=ea({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 de.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 Jt(){if(!en()||!de)return;let e=Mc(te.chainId);if(!e){te.error=`Wallet is on chain ${te.chainId}, which this demo does not support`,at();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 de.request({method:c,params:[t,"latest"]});else{let u="0x70a08231"+t.replace(/^0x/,"").toLowerCase().padStart(64,"0");l=await de.request({method:"eth_call",params:[{to:s,data:u},"latest"]})}return[i,om(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,at()}var Zl,te,de,Ae,Gl,k1,ql,lm,um,Ql,Jl,A1,wm,oa=se(()=>{kt();$l();rm();zl();na();Zl=new Set,te={status:"idle",kind:null,label:null,address:null,chainId:null,balances:{},error:null,lastRefresh:0},de=null,Ae=null,Gl=null;k1=e=>"0x"+Number(e).toString(16);ql=!1;lm=null,um=()=>{clearTimeout(lm),lm=setTimeout(()=>{S1()},400)};typeof window<"u"&&typeof document<"u"&&(window.addEventListener("pageshow",()=>um()),document.addEventListener("visibilitychange",()=>{document.hidden||um()}));Ql=!1,Jl="ninsei.wallet.optOut",A1=()=>{try{return localStorage.getItem(Jl)==="1"}catch{return!1}},wm=e=>{try{e?localStorage.setItem(Jl,"1"):localStorage.removeItem(Jl)}catch{}}});function T1(e){try{return au.get(e)}catch{return null}}function km(e,t){try{t==null?au.remove(e):au.set(e,t)}catch{}}function ia(){return T1(Sm)}async function vm(e,t={}){let n=await fetch(e,t),r=null;try{r=await n.json()}catch{}return{status:n.status,body:r}}async function Em(){if(!en())throw new Error("connect the wallet first");let e=await vm("/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 gm(e.body.message),n=await vm("/api/auth/verify",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({nonce:e.body.nonce,address:mr(),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 km(Sm,n.body.token),km(_1,n.body.address),n.body.address}var Sm,_1,N1,I1,au,cu=se(()=>{oa();Sm="ninsei.auth.token",_1="ninsei.auth.address",N1=()=>{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)}},I1=()=>{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)}},au=N1()||I1()});function _m({poolSeen:e,soft:t=Ft.softSec,hard:n=Ft.hardSec}={}){let r=Am(t,Ft.softSec),o=Am(n,Ft.hardSec),i=Math.min(r,o);return e?i:o}var Ft,Am,Nm=se(()=>{Ft={softSec:600,hardSec:1200},Am=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?Math.floor(n):t}});function Et(){return Date.now()}function ui(e,t=Et()){return Math.max(0,(t-e.realStart)*e.speed)}function wr(e,t){return e.simStartWall+t}var Im=se(()=>{});var hi={};Le(hi,{getInfo:()=>pi,height:()=>lu,lastError:()=>Bm,nodeUrl:()=>L1,snapshot:()=>fi,startPolling:()=>H1});async function C1(e,t={},n="/json_rpc"){let r=new AbortController,o=setTimeout(()=>r.abort(),P1);try{let i=await fetch(Tm+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 fi(){return Fn.data}function Bm(){return Fn.error}async function lu(){let e=await pi();return e?e.height:null}async function pi({force:e=!1}={}){return Fn.data&&Date.now()-Fn.at<O1&&!e?Fn.data:di||(di=C1("get_info").then(n=>(Fn={at:Date.now(),data:R1(n),error:null},Fn.data)).catch(n=>(Fn={at:Date.now(),data:null,error:n.message},null)).finally(()=>{di=null}),di)}function R1(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 H1(e,t=3e4){sa&&clearInterval(sa);let n=async()=>{let r=await pi({force:!0});e&&e(r,Bm())};return n(),sa=setInterval(n,t),()=>clearInterval(sa)}var Tm,P1,O1,Fn,di,sa,L1,mi=se(()=>{kt();Tm=Te.node,P1=8e3,O1=15e3,Fn={at:0,data:null,error:null},di=null;sa=null;L1=Tm});function Gr(...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")+fs(28)}function F1(e){return"0x"+Gr("escrow",e).slice(2,42)}function D1(e){return"8"+Gr("xmrlock",e).slice(2,96)}function Pm({swapId:e,ethAmountUsd:t,ethUsd:n}){return{mock:!0,txHash:Gr("fund",e),escrow:F1(e),ethAmount:n>0?t/n:0,valueUsd:t,gasUsd:.21,method:"simulated funding (no real transaction)",confirmations:1}}function Om({swapId:e,xmrAmount:t}){return{mock:!0,txid:Gr("xmrtx",e),address:D1(e),amount:t,viewKeyVerified:!0,unlocked:"1 of 2 spend key shares revealed (DLEQ bound)"}}function uu({swapId:e}){return{mock:!0,txid:Gr("sweep",e)}}function du({swapId:e,by:t}){return{mock:!0,txHash:Gr("refund",e,t),by:t}}function Cm(e,t){let n=e.timeline.confTarget;if(e.chainMode==="live"){let i=e.xmr&&e.xmr.lockHeight,s=fi();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 fu=se(()=>{ps();mi()});function Mn(e=an.xmrSource){return e==="app"}function U1(e,t){let n=e.timeline&&e.timeline.confTarget||Te.confirmTarget,r=e.timeline?e.timeline.lockAtSim:0,o=r!==null&&t>=r,i=Cm(e,t),s=o?i>=n?Dn.READY:Dn.FUNDED:Dn.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 j1(e){let t=e.timeline&&e.timeline.confTarget||Te.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 Rm(e,t){return Mn(e&&e.xmrSource)?j1(e):U1(e,t)}function Hm(e,t="stagenet"){return e?`https://${t==="mainnet"?"":t+"."}xmrchain.net/tx/${e}`:null}var Dn,Lm=se(()=>{kt();fu();Dn={AWAITING:"awaiting_funding",FUNDED:"funded",LOCKED:"xmr_locked",READY:"ready",SWEPT:"swept",CLOSED:"closed"}});var me={};Le(me,{STEP_LABELS:()=>wu,TERMINAL:()=>qr,activeSwaps:()=>gu,addServerSwaps:()=>W1,allSwaps:()=>Um,confirmReady:()=>ku,createReverseSwap:()=>bu,createSwap:()=>yu,dealSwapIds:()=>Eu,derive:()=>yi,forgetSwap:()=>K1,getSwap:()=>Qr,halvesWalletOf:()=>aa,onNotify:()=>X1,refundEth:()=>Su,refundHalfRevealed:()=>Wm,saveSwap:()=>xu,serverRestoreHeightFor:()=>Au,serverRowToSwap:()=>jm,setLiveFocus:()=>_u,startTicker:()=>Y1,subscribe:()=>$1,sweepNow:()=>vu,tick:()=>$m,xmrAmountCheck:()=>Vm});function yu(e,t=null){let n=t?t.loadState():ft(),r=Date.now(),o={id:$c(),side:e.side||"buy",scenario:e.scenario||"happy",speed:e.speed||60,network:e.network||Rt,moneroNetwork:e.moneroNetwork||Te.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:Ht.makerLock,blockSim:Te.blockTimeSim,confTarget:Te.confirmTarget,t0Sim:Ht.t0Refund},chainMode:e.chainMode||cn.defaultChainMode,xmrSource:e.xmrSource||an.xmrSource,xmrSession:null,xmrSessionError:null,events:[],escrow:null,xmr:null,settlement:null,log:[]};if(o.chainMode!=="live"){let i=Pm({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},wn(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):Zt(n),o}function bu(e={}){let t=ft(),n=Date.now(),r=Number(e.xmrAmount),o={id:$c(),side:"reverse",scenario:"happy",speed:Number(e.speed)||60,network:e.network||Rt,moneroNetwork:e.moneroNetwork||Te.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:Te.blockTimeSim,confTarget:Te.confirmTarget,t0Sim:Ht.t0Refund},chainMode:e.chainMode||cn.defaultChainMode,xmrSource:e.xmrSource||an.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||Te.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,Zt(t),o}function wn(e,t,n,r){e.log.push({atSim:t,wall:wr(e,t),title:n,detail:r||""}),console.log(`[swap ${e.id}] ${n}${r?" - "+r:""}`)}function aa(e){let t=e&&e.escrow||{};return!t.half||!t.viewHalf||!t.counterViewHalf||!t.moneroAddress?null:{source:"halves",library:"monero-js",network:t.moneroNetwork||Te.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 K1(e,t=null){let n=t?t.loadState():ft();return n.swaps[e]?(delete n.swaps[e],t?t.saveState(n):Zt(n),!0):!1}function Qr(e,t=null){return(t?t.loadState():ft()).swaps[e]||null}function Um(){let e=ft();return Object.values(e.swaps).sort((t,n)=>t.realStart<n.realStart?1:-1)}function jm(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 W1(e,t=null){if(!Array.isArray(e)||e.length===0)return 0;let n=t?t.loadState():ft(),r=0;for(let o of e)!o||!o.id||!o.escrow||n.swaps[o.id]||(n.swaps[o.id]=jm(o),r+=1);return r&&(t?t.saveState(n):Zt(n)),r}function gu(){return Um().filter(e=>!e.settlement)}function xu(e,t=null){return ca(e,t)}function ca(e,t=null){let n=t?t.loadState():ft();return n.swaps[e.id]=e,t?t.saveState(n):Zt(n),e}function Fm(e,t,n,r={}){return e.events.push({type:t,atSim:n,...r}),e}function Km(e,t){return e.events.find(n=>n.type===t)||null}function ku(e,t=null){let n=Qr(e,t);if(!n||n.settlement)return n;if(!yi(n).can.ready)throw new Error("ready() is not available in this phase");let o=ui(n);return Fm(n,"ready",o),wn(n,o,"ready() called by you","maker may now claim the ETH escrow"),Km(n,"funded_note")||Fm(n,"funded_note",0),ca(n,t)}function Wm(e){let t=e&&e.escrow||{};return t.revealedHalf||t.counterHalf||null}function vu(e,t=null){let n=Qr(e,t);if(!n||n.settlement&&!(n.settlement.kind==="refund_eth"&&n.side==="reverse"))return n;if(!yi(n).can.sweep)throw new Error("sweep is not available in this phase");let o=ui(n),i=uu({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:qr.success.phase,atSim:o,txid:i.txid,by:"you",...s?{recovered:!0}:{}},wn(n,o,"XMR swept to your address",i.txid),ca(n,t)}function Su(e,t="you",n=null){let r=Qr(e,n);if(!r||r.settlement)return r;if(!yi(r).can.refund)throw new Error("refund is not available in this phase");let i=ui(r),s=du({swapId:r.id,by:t});return r.settlement={kind:"refund_eth",phase:qr.refunded_eth.phase,atSim:i,txHash:s.txHash,by:t},wn(r,i,`ETH refunded to your wallet (${t})`,s.txHash),ca(r,n)}function Dm(e){return((it(e&&e.network||Rt)||{}).escrow||{}).mode==="live"}function Vm(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+Mm<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+Mm?{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 yi(e,t=Et()){let n=ui(e,t),r=e.timeline,i=(E=>Km(e,E))("ready"),s=Mn(e.xmrSource),a=Rm(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,h=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,k=(()=>{if(e.side!=="reverse"||h===null)return null;let E=h-Ft.hardSec*1e3,C=E+Ft.softSec*1e3,M=_m({poolSeen:y,soft:Ft.softSec,hard:Ft.hardSec}),$=!y&&Et()>=C,L=$?E+M*1e3:C;return{startMs:E,atMs:L,leftMs:L-Et(),seen:y,extended:$,softSec:Ft.softSec,hardSec:Ft.hardSec,windowSec:M}})(),x=p!==null&&e.scenario!=="maker_stall"?p+Ht.makerClaim:null,_=x!==null?x+Ht.sweep:null,v=l!==null?l+Ht.readyWindow:null,H=v!==null?v+Ht.makerReclaim:null,b=p!==null?p+Ht.t1Refund:null,I=p===null&&H!==null&&n>=H,O={ready:!1,sweep:!1,refund:!1},S="xmr_locked",T="Waiting",N=null,V=null;if(e.settlement){if(S=e.settlement.phase,T=Object.values(qr).find(E=>E.phase===e.settlement.phase)?.label||"Settled",e.settlement.kind==="refund_eth"&&e.side==="reverse"){let E=Wm(e),C=c>0;O.sweep=!!(E&&C&&aa(e)),V=O.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.":C?"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&&h!==null&&Et()>=h&&(w===null||Et()<w))S="dead_zone",T="Ready deadline passed - the refund opens at T1",O.ready=!1,O.refund=!1,O.refundByAnyone=!1,V="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&&p===null)if(w!==null&&Et()>=w)S="refund_available",T="Claim deadline passed - the refund is open",O.ready=!1,O.refund=!0,O.refundByAnyone=!0,V="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===Dn.LOCKED){S="xmr_unlock_pending",T="XMR is on your address but locked on-chain",O.ready=!1;let E=a.lockedUntil||{},C=E.untilHeight!==null&&E.untilHeight!==void 0?"block "+E.untilHeight:E.untilTime!==null&&E.untilTime!==void 0?new Date(Number(E.untilTime)*1e3).toISOString()+" UTC":"a time the sender set";V="The sender set the transaction's unlock_time: "+(a.locked||0)+" XMR is on your address but cannot be spent until "+C+". Ready stays closed until then - confirming now would let the maker take the ETH behind locked XMR."}else if(!a.received)S="maker_locking",T="Waiting for XMR to arrive",V=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===Dn.READY){S="xmr_locked",T="XMR received and confirmed ("+u+"/"+r.confTarget+")";let E=Vm(e,a);O.ready=E.ok,O.readyAmount=E,V=E.ok?"Confirm that you see the XMR on your address (ready).":E.why}else a.status===Dn.SWEPT?(S="success",T="XMR delivered"):(S="xmr_locked",T="XMR received, waiting for confirmations ("+u+"/"+r.confTarget+")",V="About "+Math.max(1,Math.round((r.confTarget-u)*r.blockSim/6e4))+" min left of confirmations.");else if(l===null)n>=r.t0Sim?(S="refund_available",T="Maker did not lock XMR",N=r.t0Sim,O.refund=!0,V="The maker never locked XMR. You can take your ETH back from the escrow - no permission needed."):(S="maker_locking",T="Waiting for the maker to lock XMR",V="If the maker does not lock XMR by T0, you get a refund button.");else if(!d)S="maker_locking",T="Maker is locking XMR";else if(I)S="xmr_reclaimed",T="XMR returned to the maker",N=H,O.refund=!0,V="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)S="xmr_locked",T=u<r.confTarget?`Waiting for Monero confirmations (${u}/${r.confTarget})`:"XMR locked and verified - waiting for you",O.ready=s?a.status===Dn.READY:u>=r.confTarget,N=v,V=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)S="ready_wait_claim",T="Waiting for the maker to claim ETH",V="The maker claims the escrow and reveals the secret; your swap wallet uses it to sweep the XMR.";else if(x!==null&&n>=x&&_!==null&&n>=_)S="success",T="XMR delivered",O.sweep=!0;else if(x!==null)S="claimed",T="Secret revealed - sweeping XMR",O.sweep=!0;else{S="refund_available",T="Maker did not claim in time",N=b;let E=e.escrow&&e.escrow.t0?e.escrow.t0*1e3:null,C=e.escrow&&e.escrow.t1?e.escrow.t1*1e3:null,M=Et();C!==null?E!==null?(O.refund=M>=E,O.refundByAnyone=M>=C):(O.refund=M>=C,O.refundByAnyone=O.refund):Dm(e)?O.refund=!1:O.refund=n>=b,V=O.refund?O.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.":E!==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 X=u>=r.confTarget,m=x!==null&&n>=x,g=[{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:X&&!I,active:d&&!X,atSim:l},{key:"ready",done:p!==null,active:X&&p===null&&!I,atSim:p},{key:"claimed",done:m,active:p!==null&&!m,atSim:x},{key:"swept",done:!!e.settlement&&e.settlement.kind==="success",active:m&&!e.settlement,atSim:V1(e)}];return{swap:e,sim:n,simWallTime:wr(e,n),phase:S,phaseLabel:T,note:V,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:wr(e,r.t0Sim),t0Sim:r.t0Sim,lockAtSim:l,readyBy:v!==null?wr(e,v):null,readyBySim:v,t1:e.escrow&&e.escrow.t1?e.escrow.t1*1e3:b!==null?wr(e,b):null,t1Sim:b,refundAfterSim:N,refundAfterWall:N!==null?wr(e,N):null},refundLeftSim:N!==null?N-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:Hm(a.txids[0],e.xmrSession&&e.xmrSession.network||"stagenet"),error:a.error,sweepTxid:a.sweepTxid},simulated:{evm:!Dm(e),xmr:!a.live},can:O,readyDeadline:{atMs:h,soonMs:h!==null&&p===null?h-Et():null,soon:h!==null&&p===null&&h-Et()>0&&h-Et()<=Number($o.readyLeadWarnSec||0)*1e3},xmrAmount:{expected:(()=>{let E=Number(e.xmrAmount);return Number.isFinite(E)&&E>0?E:null})(),seen:a.received!==null&&a.received!==void 0?Number(a.received):null},steps:g,sellWindow:k,terminal:e.settlement,xmrReclaimed:I}}function V1(e){return e.settlement&&e.settlement.kind==="success"?e.settlement.atSim:null}function $1(e){return hu.add(e),()=>hu.delete(e)}function z1(){for(let e of hu)try{e()}catch(t){console.error(t)}}function Eu(e){let t=new Set([String(e&&e.id||"")].filter(Boolean)),r=(()=>{try{return aa(e)||{}}catch{return{}}})().address||e&&e.escrow&&e.escrow.moneroAddress||null;if(!r)return[...t];for(let o of Object.values((ft()||{}).swaps||{})){if(!o||!o.id)continue;(()=>{try{return aa(o)||{}}catch{return{}}})().address===r&&t.add(String(o.id))}return[...t]}async function Au(){return null}function _u(e){return new Set(Array.isArray(e)?e.map(String):[]).size}function $m(){let e=ft(),t=!1;for(let n of Object.values(e.swaps)){if(n.settlement)continue;let r=yi(n);if(!Mn(n.xmrSource)&&!n.xmr&&r.deadlines.lockAtSim!==null&&r.sim>=r.deadlines.lockAtSim){let o=Om({swapId:n.id,xmrAmount:n.xmrAmount});if(n.xmr={...o,reclaimed:!1,sweepTxid:null},n.chainMode==="live"){let s=fi();n.xmr.lockHeight=s?s.height:null,n.xmr.lockHeight||pi({force:!0}).then(a=>{if(a&&!n.settlement){let c=ft();c.swaps[n.id]&&(c.swaps[n.id].xmr.lockHeight=a.height,Zt(c))}})}wn(n,r.sim,"Maker locked XMR on the shared address",o.txid);let i=n.id+":lock";tn.has(i)||(tn.add(i),wi(n.xmrAmount.toFixed(4)+" XMR locked; view key verified","ok")),t=!0}if(Mn(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},wn(n,r.sim,"XMR received (backend, "+(n.xmrSession&&n.xmrSession.network||"stagenet")+")",n.xmr.txid||"");let o=n.id+":xmr-in";tn.has(o)||(tn.add(o),wi(r.xmr.received.toFixed(6)+" XMR received; confirmations "+r.xmr.confirmations+"/"+r.xmr.confTarget,"ok")),t=!0}if(!Mn(n.xmrSource)&&r.can.sweep&&r.phase==="success"){let o=r.sim;n.xmr.sweepTxid=uu({swapId:n.id}).txid,n.settlement={kind:"success",phase:qr.success.phase,atSim:o,txid:n.xmr.sweepTxid,by:"your swap wallet"},wn(n,o,"XMR swept to your address",n.xmr.sweepTxid);let i=n.id+":success";tn.has(i)||(tn.add(i),wi("Swap "+n.id+" complete: XMR is on your address","ok")),t=!0;continue}if(!Mn(n.xmrSource)&&r.can.refund&&r.refundLeftSim!==null&&r.refundLeftSim<=-Ht.watchtowerGrace){let o=r.sim,i=du({swapId:n.id,by:"watchtower"});n.settlement={kind:"refund_eth",phase:qr.refunded_eth.phase,atSim:o,txHash:i.txHash,by:"watchtower"},wn(n,o,"Watchtower refunded your ETH",i.txHash);let s=n.id+":refund";tn.has(s)||(tn.add(s),wi("Watchtower refunded the ETH escrow of swap "+n.id,"bad")),t=!0;continue}if(!Mn(n.xmrSource)&&n.xmr&&r.xmrReclaimed&&!n.xmr.reclaimed){n.xmr.reclaimed=!0,wn(n,r.sim,"Maker reclaimed the XMR",n.xmr.txid);let o=n.id+":reclaim";tn.has(o)||(tn.add(o),wi("Maker took the XMR back: no ready() call in time","bad")),t=!0}}t&&Zt(e)}function X1(e){mu.fn=e}function wi(e,t){mu.fn&&mu.fn(e,t)}function Y1(e=400){pu&&clearInterval(pu),pu=setInterval(()=>{try{$m()}catch(t){console.error(t)}z1()},e)}var wu,qr,Mm,pu,hu,tn,mu,bi=se(()=>{kt();Nm();Im();Js();ps();fu();mi();Lm();wu=[["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"]],qr={success:{phase:"success",label:"XMR delivered"},refunded_eth:{phase:"refunded_eth",label:"ETH refunded"}};Mm=1e-6;pu=null,hu=new Set,tn=new Set;mu={fn:null}});function Ee(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 sv(e){for(let n of Iu)if(e[n]===void 0||e[n]===null||e[n]==="")throw new Error("the quote has no field: "+n);for(let n of ov)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 iv)if(!/^(0x)?[0-9a-fA-F]{64}$/.test(String(e[n]).trim()))throw new Error("quote field "+n+" is not bytes32");let t={provider:Ee(e.provider,32),quoteKey:Ee(e.quoteKey,32),registry:Ee(e.registry,32),cashier:Ee(e.cashier,32),locker:Ee(e.locker,32),claimer:Ee(e.claimer,32),amount:Ee(e.amount,32),readyBy:Ee(e.readyBy,32),t1:Ee(e.t1,32),salt:Ee(Zr(e.salt),32),commitHalfClaimer:Ee(Zr(e.commitHalfClaimer),32),edPointClaimer:Ee(Zr(e.edPointClaimer),32),chainId:Ee(e.chainId,32),feeBps:Ee(e.feeBps,32),fee:Ee(e.fee,32),feeRecipient:Ee(e.feeRecipient,32),validUntil:Ee(e.validUntil,32),nonce:Ee(e.nonce,32),xmrAmount:Ee(e.xmrAmount,32),claimTip:Ee(e.claimTip,32),commitHalfLocker:Ee(Zr(e.commitHalfLocker),32),edPointLocker:Ee(Zr(e.edPointLocker),32),edViewPointLocker:Ee(Zr(e.edViewPointLocker),32)};return Iu.map(n=>t[n]).join("")}function av(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),Ee("0x"+n,32)+Ee("0x"+r,32)+Ee(o,32)}function ew(e){return sv(e)+av(e.signature)}function Bu(e){return Tu.predict+ew(e)}function Pu(e){return Tu.createOrderAndFund+ew(e)}function ha(e){return"0x"+tw(e,"predict()").slice(24,64)}function cv(e){let t=fa[e];if(typeof t!="string"||!/^0x[0-9a-f]{8}$/.test(t))throw new Error("no such factory read: "+e);return t}function nw(e){return ha(e)}function rw(e){return"0x"+tw(e,"implementationCodeHash()")}function ow({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 lv({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:fa.implementation}),s=await t({to:e,data:fa.implementationCodeHash})}catch{return{ok:!1,why:"implementation-unreadable",factory:String(e).toLowerCase()}}let a,c;try{a=nw(i),c=rw(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{...ow({implementation:a,implementationCodeHash:c,code:l,hashCode:o,policy:r}),implementation:a,implementationCodeHash:c}}var Tu,pa,Jm,rv,Iu,ov,iv,Zr,tw,fa,Ou=se(()=>{Tu={predict:"0x76e3fdc8",createOrderAndFund:"0x50db6721"},pa="0x09add13cca47b227c377447295bfaa00ef3169bfed0f5513d06f8be04af78aad",Jm="0xa22cdabaed3cce4f51dde71626a108ffe9c7bc4216fd14d5e719f892e2fd8ab0",rv=Object.freeze([pa,Jm]),Iu=["provider","quoteKey","registry","cashier","locker","claimer","amount","readyBy","t1","salt","commitHalfClaimer","edPointClaimer","chainId","feeBps","fee","feeRecipient","validUntil","nonce","xmrAmount","claimTip","commitHalfLocker","edPointLocker","edViewPointLocker"],ov=["provider","quoteKey","registry","cashier","locker","claimer","feeRecipient"],iv=["salt","commitHalfClaimer","edPointClaimer","commitHalfLocker","edPointLocker","edViewPointLocker"];Zr=e=>{let t=String(e??"").trim();return/^[0-9a-fA-F]{64}$/.test(t)?"0x"+t.toLowerCase():t};tw=(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()};fa={implementation:"0x5c60da1b",implementationCodeHash:"0xbc0a3981"}});var Jr={};Le(Jr,{ESCROW_METHODS:()=>yn,decodeBytes32:()=>fw,decodeStatus:()=>wa,decodeUint64:()=>pw,encodeClaim:()=>sw,encodeMarkReady:()=>iw,encodeRead:()=>dw,encodeRefund:()=>cw,encodeStatus:()=>ma,encodeT1:()=>lw,encodeTermsHash:()=>uw,orderTerms:()=>hw});function iw(){return yn.markReady}function sw(e){return yn.claim+aw(e,"secret")}function aw(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 cw(e){return yn.refund+aw(e,"half")}function ma(){return yn.status}function lw(){return yn.t1}function uw(){return yn.termsHash}function dw(e){let t=yn[e];if(typeof t!="string"||!/^0x[0-9a-f]{8}$/.test(t))throw new Error("no such escrow method: "+e);return t}function fw(e,t="value"){return"0x"+Cu(e,t,1)}function pw(e,t="value"){let n=Cu(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 wa(e){let t=Cu(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 hw({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 yn,Cu,ya=se(()=>{yn={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"};Cu=(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 Ru(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 ww(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=Ru(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&&uv(e.feeRecipient))throw new Error("with a non-zero rate the fee recipient must be named");let o=mw(e.locker,e.provider),i=mw(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 eo=a,a}function yw(){return eo}function bw(){return!eo||!Number.isFinite(Number(eo.bps))?null:Number(eo.bps)/1e4}async function gw(){return eo}var mw,uv,eo,ba=se(()=>{mw=(e,t)=>String(e||"").toLowerCase()===String(t||"").toLowerCase(),uv=e=>!e||/^0x0{40}$/i.test(String(e)),eo=null});function ga(){let e=new Uint8Array(32);return crypto.getRandomValues(e),"0x"+Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function xw({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[v,H]of Object.entries({commitHalfLocker:n,commitHalfClaimer:r,edPointLocker:o,edPointClaimer:i,edViewPointLocker:s}))if(!H)throw new Error("order term not set: "+v);let h=Math.floor(Date.now()/1e3),w=d!=null&&d!=="",y=p!=null&&p!=="",k=w?Number(d):h+u,x=y?Number(p):k+l;if(!(x>k))throw new Error("the settlement deadline must be later than the readiness deadline: t1="+x+", readyBy="+k);let _=Kc({nowSec:h,readyBy:k,t1:x,...$o});if(_.blocks)throw new Error("order deadlines are not usable: "+_.reason);return{locker:e,claimer:t,commitHalfLocker:n,commitHalfClaimer:r,edPointLocker:o,edPointClaimer:i,edViewPointLocker:s,amount:String(a),readyBy:String(k),t1:String(x),salt:c}}function xa(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 dv({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=xa(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 vw(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()!==pa||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 ka(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=vw(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 fv(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 Hu({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:h,t1:w,quote:y,call:k,send:x,receipt:_,onStep:v,onPredicted:H}){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 b=c||ga(),I=xw({locker:t,claimer:n,commitHalfLocker:r,commitHalfClaimer:o,edPointLocker:i,edPointClaimer:s,edViewPointLocker:a,amountWei:l,salt:b,claimWindowSeconds:d,readyWindowSeconds:p,readyBy:h,t1:w});v?.("computing the escrow address");let O={...y,commitHalfLocker:I.commitHalfLocker,edPointLocker:I.edPointLocker,edViewPointLocker:I.edViewPointLocker},S=(D,U)=>String(D??"").replace(/^0x/i,"").toLowerCase()===String(U??"").replace(/^0x/i,"").toLowerCase();for(let D of["locker","claimer","amount","readyBy","t1","salt","commitHalfClaimer","edPointClaimer"])if(!S(y[D],I[D]))throw new Error("the quote and the order terms diverge on field "+D);let T=await k({to:e,data:Bu(O)}),N=ha(T);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(T).slice(0,40));v?.("checking the order is not already on chain");let V=null;try{let D=await k({to:N,data:ma()});V=String(D||"").replace(/^0x/,"").length>=256?{status:wa(D)}:{status:null}}catch(D){V={error:String(D&&D.message||D)}}let X=Wc({status:V.status,error:V.error,address:N});if(X.blocks)throw new Error("signature not started: "+X.reason);v?.("reading the escrow fee from the signed quote");let m=ww(y),g=m.totalWei,E=m.feeWei>0n?" (order "+l+" + fee "+m.feeWei+")":"";v?.("locking "+(u||"funds")+E+" in one transaction - confirm in wallet"),typeof H=="function"&&await H({escrow:N,salt:b,terms:I});let C=Pu(O),M=await x({to:e,data:C,value:"0x"+g.toString(16),gas:kw}),$=null,L=null,F={status:"pending",reason:"no-receipt-reader"};if(typeof _=="function"){let D=await fv(_,M);if(F=ka(D,{factory:e,expectedEscrow:N}),F.status==="reverted"){let U=new Error("the funding transaction reverted");throw U.code="contract-reverted",U.receiptStatus=0,U}F.status==="funded"?($=F.escrow,L=F.birthBlock,$!==String(N).toLowerCase()&&(console.warn("[escrow] receipt address "+$+" != predicted "+N+" - using the receipt one"),v?.("receipt address differs from predicted - using the receipt one"))):v?.(D?"receipt has no matching OrderCreated - funding is pending, not funded":"no receipt yet - funding is pending, not funded")}let B=M,P={feeWei:m.feeWei,feeTotalWei:g,feeBps:m.bps,feeWasLegacyFactory:!!m.legacy,predictedEscrow:N,salt:b,terms:I,createHash:M,lockHash:B};return F.status!=="funded"?{...P,escrow:null,birthBlock:null,funded:!1,pending:!0,pendingReason:F.reason}:{...P,escrow:$,escrowMismatch:$!==String(N).toLowerCase(),birthBlock:L,funded:!0,pending:!1}}var kw,to=se(()=>{Ou();ya();ba();Vc();kt();kw=700000n});var Sw,Lu,gi,jn,Ew,pv,hv,Aw,xi,Du,_w,Nw,mv,Fu,va,wv,yv,Iw,Mu,Uu=se(()=>{kt();Sw=["native","wrapped"],Lu="native",gi=Object.freeze({NATIVE:"native",WRAPPED:"wrapped"}),jn=[],Ew=()=>jn.length===0?null:jn.length===1?jn[0]:jn,pv=(e=null)=>(Array.isArray(e)?jn=e.filter(Boolean):e&&typeof e=="object"?jn=[e]:jn=[],Ew()),hv=()=>Ew(),Aw=e=>jn.filter(t=>t&&Number(t.chainId)===Number(e)),xi=e=>e&&ds[e]||null,Du=()=>Object.keys(ds).sort(),_w=e=>Object.keys((xi(e)||{}).networks||{}).map(Number).filter(Number.isFinite).sort((t,n)=>t-n),Nw=e=>{let t=xi(e);return t?t.settles===void 0?null:t.settles:null},mv=(e,t={})=>t.settles?t.settles:Nw(e),Fu=(e,t,n,r={})=>{let o=xi(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:mv(e,r)}},va=e=>{let t=Number(e),n=new Map;for(let r of Du()){let o=xi(r),i=o.networks&&o.networks[t];i&&n.set(r,Fu(r,t,i))}for(let r of Aw(t))n.set(r.id,Fu(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))},wv=(e,t=null)=>{let n=Number(e);if(t){let o=Aw(n).find(i=>i.id===t);return o?Fu(o.id,n,{slug:o.slug,orderbook:o.orderbook,contract:o.contract},{settles:o.settles,venue:o.venue,shape:o.shape}):va(n).find(i=>i.id===t)||null}let r=va(n);return r.length?r[0]:null},yv=e=>_w(e||Du()[0]||null),Iw=({chainId:e=null,providerId:t=null,need:n=Lu}={})=>{let r=Number(e),o=Number.isFinite(r),i=Sw.includes(n)?n:Lu,s=o?va(r):[];if(!s.length)return{ok:!1,reason:"no-async-provider",chainId:o?r:null,need:i,provider:t||null,known:yv(t)};let a=null;if(t&&(a=s.find(h=>h.id===t)||null,!a))return{ok:!1,reason:"no-async-provider",chainId:r,need:i,provider:t,known:s.map(h=>h.id)};let c=a?[a]:s,l=c.filter(h=>h.settles===i);if(l.length){let h=l[0];return{ok:!0,kind:"single",...h,need:i,provider:h.id,legs:[h]}}let u=c.filter(h=>h.settles===gi.WRAPPED),d=s.filter(h=>h.settles===gi.NATIVE);if(i===gi.NATIVE&&u.length&&d.length){let h=u[0],w=d[0];return{ok:!0,kind:"composition",need:i,chainId:r,provider:h.id,venue:h.venue,shape:"async",orderbook:h.orderbook,legs:[h,w]}}return{ok:!1,reason:i===gi.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(h=>h.id)}},Mu=Iw});function bv({owner:e,spender:t,value:n,deadline:r,signature:o}){if(!Ea(e)||!Ea(t))throw new Error("permit: owner and spender must be addresses");let i=_a(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 ki.permit.hex+Aa(e)+Aa(t)+Sa(n)+Sa(r)+Sa(s)+i.slice(0,64)+i.slice(64,128)}function vv({code:e=null,domainSeparator:t=null,nonces:n=null,owner:r=null}={}){let o=_a(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(!Ea(r))return{supported:null,kind:"no-owner",reason:"no owner given - cannot read nonces(owner)"};let i=Tw(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=Tw(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(ki.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 Sv({orchestrator:e=null,permitSupported:t=null,token:n=null,nativeBalanceWei:r=null,gasNeedWei:o=null,asyncProvider:i=null,chainId:s=null}={}){let a=Bw(o),c=i&&typeof i=="object"?i:s==null?null:Mu({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=Bw(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 Ea(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 Pw,ki,_a,Ea,Aa,Sa,Tw,Bw,gv,xv,kv,Ow=se(()=>{Uu();Pw={approve:{hex:"0x095ea7b3",signature:"approve(address,uint256)"},allowance:{hex:"0xdd62ed3e",signature:"allowance(address,address)"},balanceOf:{hex:"0x70a08231",signature:"balanceOf(address)"}},ki={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()"}},_a=e=>String(e??"").replace(/^0x/,""),Ea=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),Aa=e=>_a(e).toLowerCase().padStart(64,"0"),Sa=e=>BigInt(e).toString(16).padStart(64,"0"),Tw=e=>{let t=_a(e);return t.length===0||t.length%2?null:t.length/2},Bw=e=>{if(e==null||e==="")return null;try{return BigInt(typeof e=="bigint"?e:String(e))}catch{return null}};gv=e=>ki.nonces.hex+Aa(e),xv=()=>ki.DOMAIN_SEPARATOR.hex,kv=({spender:e,amountWei:t})=>Pw.approve.hex+Aa(e)+Sa(t)});var Re={};Le(Re,{ASYNC_DEFAULT_NEED:()=>Lu,ASYNC_NEEDS:()=>Sw,ASYNC_SETTLES:()=>gi,EIP2612_METHOD:()=>ki,ERC20_METHOD:()=>Pw,ESCROW_METHODS:()=>yn,FACTORY_METHODS:()=>Tu,FACTORY_READS:()=>fa,GAS_CREATE_ORDER_AND_FUND:()=>kw,ORDER_CREATED_TOPIC:()=>pa,ORDER_CREATED_TOPICS:()=>rv,ORDER_CREATED_TOPIC_V1:()=>Jm,QUOTE_FIELDS:()=>Iu,address:()=>mr,asyncRouteChains:()=>_w,asyncRouteChoice:()=>Iw,asyncRouteForChain:()=>wv,asyncRouteInjection:()=>hv,asyncRouteProvider:()=>xi,asyncRouteProviderIds:()=>Du,asyncRouteProviderSettles:()=>Nw,asyncRouteProvidersForChain:()=>va,asyncRouteVerdict:()=>Mu,balanceOf:()=>hm,chainIdOf:()=>pm,connect:()=>bm,connectInjected:()=>ru,currentProvider:()=>li,decodeAddress:()=>ha,decodeBytes32:()=>fw,decodeImplementation:()=>nw,decodeImplementationCodeHash:()=>rw,decodeStatus:()=>wa,decodeUint64:()=>pw,disconnect:()=>xm,encodeApprove:()=>kv,encodeClaim:()=>sw,encodeCreateOrderAndFund:()=>Pu,encodeDomainSeparator:()=>xv,encodeFactoryRead:()=>cv,encodeMarkReady:()=>iw,encodeNonces:()=>gv,encodePermit:()=>bv,encodePredict:()=>Bu,encodeRead:()=>dw,encodeRefund:()=>cw,encodeStatus:()=>ma,encodeT1:()=>lw,encodeTermsHash:()=>uw,escrowFromReceipt:()=>vw,escrowNativeWei:()=>dv,fundOrder:()=>Hu,fundOrderLive:()=>_v,fundingReceiptVerdict:()=>ka,isConnected:()=>en,newSecret:()=>ga,orderTerms:()=>hw,permitSupportVerdict:()=>vv,readCode:()=>ra,readContract:()=>Ln,readReceipt:()=>iu,refreshBalances:()=>Jt,restore:()=>ym,restoreInjected:()=>nu,sendTransaction:()=>su,setAsyncRouteInjection:()=>pv,simulateEscrowFunding:()=>Av,status:()=>fm,subscribe:()=>dm,switchChain:()=>ou,testOrderTerms:()=>xw,toWei:()=>xa,usdcWithoutEthVerdict:()=>Sv,verifyFactoryImplementation:()=>ow,verifyFactoryImplementationOnChain:()=>lv,wallets:()=>Ev,word:()=>Ee});function Ev(){return ci()}async function Av(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 _v({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:h,t1:w,quote:y,onStep:k}){return Hu({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:h,t1:w,call:Ln,send:su,receipt:iu,onStep:k})}var ju=se(()=>{oa();$l();to();Ou();ya();to();Ow();Uu();oa()});var pt={};Le(pt,{DEX_METHOD:()=>bn,declaredRoutePath:()=>Rw,decodeQuoteExactInput:()=>Vu,dexLegVerdict:()=>$u,encodeGetPool:()=>Mw,encodePath:()=>Wu,encodeQuoteExactInput:()=>Kw,encodeQuoteExactInputSingle:()=>Dw,encodeQuoteExactOutputSingle:()=>Uw,feeTierLabel:()=>ro,feeTierPct:()=>Ww,noRouteWords:()=>Gw,poolAddress:()=>Vw,poolState:()=>Cv,priceGateVerdict:()=>Yw,quoteDexOut:()=>zu,quoteExactOutPath:()=>jw,quoteExactOutSingle:()=>Bv,quotePath:()=>zw,quoteTier:()=>$w,resetDexCache:()=>Tv,routeLabel:()=>Hw,routeSignature:()=>Xw,routeSteps:()=>Lw,unwrapLeg:()=>Rv});function Rw({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 Hw(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]+" "+ro(e.fees[n]);return t}function Lw(e){return!e||!e.symbols?[]:e.fees.map((t,n)=>({from:e.symbols[n],to:e.symbols[n+1],fee:t,feeLabel:ro(t)}))}function Iv(e){let t=Ku.get(e);if(t&&Date.now()-t.at<Nv)return t.value}function Cw(e,t){return Ku.set(e,{at:Date.now(),value:t}),t}function Tv(){Ku.clear()}async function Kn(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 no(e){let t=Na(e),n=[];for(let r=0;r+64<=t.length;r+=64)n.push(BigInt("0x"+t.slice(r,r+64)));return n}function Dw({tokenIn:e,tokenOut:t,amountInWei:n,fee:r,sqrtPriceLimitX96:o=0}){return bn.quoteExactInputSingle.hex+Wn(e)+Wn(t)+_t(n)+_t(r)+_t(o)}function Mw({tokenA:e,tokenB:t,fee:n}){return bn.getPool.hex+Wn(e)+Wn(t)+_t(n)}function Uw({tokenIn:e,tokenOut:t,amountOutWei:n,fee:r,sqrtPriceLimitX96:o=0}){return bn.quoteExactOutputSingle.hex+Wn(e)+Wn(t)+_t(n)+_t(r)+_t(o)}async function Bv(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=Uw({tokenIn:t,tokenOut:n,amountOutWei:r,fee:o}),c=await Kn(e,"eth_call",[{to:s.quoter,data:a},"latest"],i);if(!c.ok)return{ok:!1,why:c.why};let l=no(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 jw(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=Wu({tokens:i,fees:s}),c=bn.quoteExactOutput.hex+_t(64)+_t(n)+_t(a.bytes)+a.packed.padEnd(Math.ceil(a.packed.length/64)*64,"0"),l=await Kn(e,"eth_call",[{to:o.quoter,data:c},"latest"],r);if(!l.ok)return{ok:!1,why:l.why};let u=Vu(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 Wu({tokens:e,fees:t}){let n=[];for(let o=0;o<e.length;o++)n.push(Na(e[o]).toLowerCase().padStart(40,"0")),o<t.length&&n.push(Na(Number(t[o]).toString(16)).toLowerCase().padStart(6,"0"));let r=n.join("");return{packed:r,bytes:r.length/2}}function Kw({tokens:e,fees:t,amountInWei:n}){let{packed:r,bytes:o}=Wu({tokens:e,fees:t}),i=r.padEnd(Math.ceil(o/32)*64,"0");return bn.quoteExactInput.hex+Fw("0x40")+_t(n)+_t(o)+i}function Ww(e){let t=Number(e);return Number.isFinite(t)?t/1e4:null}function ro(e){let t=Ww(e);return t===null?String(e):String(Number(t.toFixed(4)))+"%"}async function Vw(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 Kn(e,"eth_call",[{to:i.factory,data:Mw({tokenA:t,tokenB:n,fee:r})},"latest"],o);if(!s.ok)return{ok:!1,why:s.why};let a=no(s.result),c=Pv(a[0]);return!c||c===Ov?{ok:!0,pool:null}:{ok:!0,pool:c}}async function Cv(e,t,{tokenIn:n,tokenOut:r},o={}){if(!t)return null;let[i,s,a]=await Promise.all([Kn(e,"eth_call",[{to:t,data:bn.liquidity.hex},"latest"],o),Kn(e,"eth_call",[{to:n,data:bn.balanceOf.hex+Wn(t)},"latest"],o),Kn(e,"eth_call",[{to:r,data:bn.balanceOf.hex+Wn(t)},"latest"],o)]),c=l=>l.ok?no(l.result)[0]??null:null;return{liquidity:i.ok?BigInt(no(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 $w(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=Dw({tokenIn:t,tokenOut:n,amountInWei:r,fee:o}),c=await Kn(e,"eth_call",[{to:s.quoter,data:a},"latest"],i);if(!c.ok)return{fee:o,ok:!1,why:c.why};let l=no(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 Vu(e){let t=no(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 zw(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=Kw({tokens:t.tokens,fees:t.fees,amountInWei:n}),s=await Kn(e,"eth_call",[{to:o.quoter,data:i},"latest"],r);if(!s.ok)return{...t,ok:!1,why:s.why};let a=Vu(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 Xw(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 Yw({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(O=>{let S={from:O.from,to:O.to,fee:O.fee,feeLabel:ro(O.fee),inWei:O.inWei||null,outWei:O.outWei||null,exactAmount:!!O.exact,quoted:!!O.ok,ok:!1,ratio:null,deviationPct:null,why:null};if(!O.ok)return S.why="the 1:1 step could not be quoted ("+(O.why||"no answer")+")",d.push(S.why),S;let T=Number(O.inWei)/10**Number(O.inDecimals),N=Number(O.outWei)/10**Number(O.outDecimals);return!(T>0)||!(N>0)?(S.why="the 1:1 step answered with a number that cannot be read",d.push(S.why),S):(S.ratio=N/T,S.deviationPct=Math.abs(1-S.ratio)*100,u===null?(S.why="the 1:1 band is not declared for this step, so this step cannot be checked",d.push(S.why),S):S.deviationPct>u?(S.why=`${S.from}\u2192${S.to} at ${S.feeLabel} pays ${S.ratio.toFixed(6)} ${S.to} per 1 ${S.from} - ${S.deviationPct.toFixed(2)}% off 1:1, and the band is ${u}%`,d.push(S.why),S):(S.ok=!0,S))}),h=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=h!==null&&Number(o)>0?h*Number(o):null,k=y!==null&&w!==null&&w>0?y/w:null,x=Number(i)>0?Number(i):null,_=k!==null&&x!==null?Math.abs(k-x)/x*100:null,v=_!==null&&l!==null&&_>l;v?d.push(`the route implies the native coin at $${k.toFixed(2)} while the reference price is $${x.toFixed(2)} - ${_.toFixed(1)}% apart, and the limit is ${l}%: this is not the market price`):_===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 H=_!==null&&l!==null,b=v||p.some(O=>!O.ok);return{checked:H,bad:b,tolerated:!!a,blocks:a?!1:b||!H,why:d.length?d.join("; "):null,impliedUsd:k,referenceUsd:x,deviationPct:_,maxDeviationPct:l,stableBandPct:u,tokenUsd:Number(o)>0?Number(o):null,stable:p}}function Gw({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 $u(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 zu(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 h=o||null,w=String(e&&e.dexPriceGate||"")==="tolerated",y=h?{steps:(Array.isArray(h.steps)?h.steps:[]).map(N=>({to:N.to,fee:N.fee,pool:N.pool||null,verified:N.verified||null})),why:h.why||null,unwrap:!!h.unwrap}:null;if(!h||!Array.isArray(h.steps)||!h.steps.length)return h&&h.unwrap?{ok:!1,why:"this is the wrapped native coin: no pool needed, it unwraps 1:1",unwrap:!0}:{ok:!1,why:Gw({paySymbol:t.symbol,wrappedSymbol:d.symbol,chainName:p,route:h}),declared:!0,declaration:y,steps:[]};let k=Rw({token:t,tokens:i,wrapped:d,route:h});if(!k||k.error)return{ok:!1,declared:!0,dataError:!0,declaration:y,why:"the declared route for "+t.symbol+" on "+p+" cannot be built: "+(k&&k.error||"unknown reason")};let x=new Map((Array.isArray(i)?i:[]).filter(N=>N&&N.address).map(N=>[String(N.address).toLowerCase(),N])),_=N=>{if(String(N).toLowerCase()===String(t.address).toLowerCase())return t.decimals;if(String(N).toLowerCase()===String(d.address).toLowerCase())return d.decimals;let V=x.get(String(N).toLowerCase());return V&&Number.isFinite(Number(V.decimals))?Number(V.decimals):null},v=[e.id,t.symbol,u.toString(),Xw(h)].join("|"),H=Iv(v);if(H===void 0){let N=await zw(e,{route:{tokens:k.tokens,fees:k.fees,symbols:k.symbols,via:null},amountInWei:u},c);if(!N.ok)return Cw(v,{ok:!1,why:N.why,declared:!0});H={ok:!0,quote:N},Cw(v,H)}if(!H.ok)return{...H,declaration:y};let b=H.quote;if(H.hops===void 0){let N=[];for(let V=0;V<k.fees.length;V++){let X=k.fees[V],m=k.tokens[V],g=k.tokens[V+1],E=h.steps&&h.steps[V]||{},C=await Vw(e,{tokenIn:m,tokenOut:g,fee:X},c),M=C.ok?C.pool:null,$=E.pool||null;N.push({step:V+1,from:k.symbols[V],to:k.symbols[V+1],fee:X,feeLabel:ro(X),decimals:[_(m),_(g)],pool:M,declaredPool:$,poolMatchesDeclared:M&&$?String(M).toLowerCase()===String($).toLowerCase():null,verified:E.verified||null})}H.hops=N}let I=H.hops;if(H.stableSteps===void 0){let N=(a&&Array.isArray(a.stables)?a.stables:[]).map(X=>String(X).toUpperCase()),V=[];for(let X=0;X<k.fees.length;X++){let m=String(k.symbols[X]).toUpperCase(),g=String(k.symbols[X+1]).toUpperCase();if(!N.includes(m)||!N.includes(g))continue;let E=await $w(e,{tokenIn:k.tokens[X],tokenOut:k.tokens[X+1],amountInWei:u,fee:k.fees[X]},c);V.push({from:k.symbols[X],to:k.symbols[X+1],fee:k.fees[X],inWei:u.toString(),outWei:E.ok?E.amountOutWei:null,inDecimals:_(k.tokens[X]),outDecimals:_(k.tokens[X+1]),ok:!!E.ok,why:E.ok?null:E.why,exact:X===0})}H.stableSteps=V}let O=Yw({amountInWei:u,amountOutWei:b.amountOutWei,inDecimals:t.decimals,outDecimals:d.decimals,tokenUsd:Number(t.usd)>0?Number(t.usd):null,referenceUsd:s,stableSteps:H.stableSteps,tolerated:w,gates:a}),S=null;if(r!=null&&Number(r)>0){let N=await jw(e,{route:b,amountOutWei:BigInt(r)},c);S=N.ok?{ok:!0,amountInWei:N.amountInWei,gasEstimate:N.gasEstimate,enough:BigInt(N.amountInWei)<=u,enteredWei:u.toString(),spareInWei:(BigInt(N.amountInWei)<=u?u-BigInt(N.amountInWei):0n).toString(),shortInWei:(BigInt(N.amountInWei)<=u?0n:BigInt(N.amountInWei)-u).toString()}:{ok:!1,why:N.why}}let T=r!=null&&Number(r)>0?(()=>{let N=BigInt(r),V=BigInt(b.amountOutWei);return{outWei:N.toString(),getsWei:V.toString(),covers:V>=N,shortfallWei:(V>=N?0n:N-V).toString()}})():null;return{ok:!0,leg:"pool",venue:"Uniswap v3",payToken:t.symbol,wrapped:d,declaredRoute:y,route:{symbols:b.symbols.slice(),fees:b.fees.slice(),pools:k.pools.slice(),via:null,hops:b.fees.length},routeLabel:Hw(b),steps:Lw(b),fee:b.fees[b.fees.length-1],feeLabel:b.fees.map(N=>ro(N)).join(" / "),amountInWei:u.toString(),amountOutWei:b.amountOutWei,gasEstimate:b.gasEstimate,required:T,price:O,exactOut:S,hopsDetail:I,pool:I.length?I[0].pool:null,at:Date.now()}}function Rv(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 bn,Nv,Ku,Na,Fw,Wn,_t,Pv,Ov,Xu=se(()=>{bn={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)"}};Nv=2e4,Ku=new Map;Na=e=>String(e||"").replace(/^0x/,""),Fw=e=>Na(e).toLowerCase().padStart(64,"0"),Wn=e=>Fw(e),_t=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")};Pv=e=>e==null?null:"0x"+e.toString(16).padStart(40,"0"),Ov="0x"+"0".repeat(40)});function qw(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 Qw=se(()=>{});function ty(e,t){let n=ey.get(e);if(n&&Date.now()-n.at<t)return n.value}function oo(e,t){return ey.set(e,{at:Date.now(),value:t}),t}async function vi(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 Dv(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 ny(e,{force:t=!1}={}){let n=e&&e.priceFeed;if(!n||!n.address)return null;let r=e.id+":usd";if(!t){let o=ty(r,Hv);if(o!==void 0)return o}try{let[o,i]=await Promise.all([vi(e,"eth_call",[{to:n.address,data:Zw.description},"latest"]),vi(e,"eth_call",[{to:n.address,data:Zw.latestRoundData},"latest"])]),s=Dv(o),a=Jw(i,1),c=Number(Jw(i,3))*1e3,l=Number(n.decimals||8),u=Number(a)/10**l,d=c>0&&Date.now()-c<Fv,p=u>=(n.min||.01)&&u<=(n.max||1e7);return s!==n.pair||!d||!p?oo(r,null):oo(r,{usd:u,updatedAt:c,source:"chainlink",pair:s})}catch{return oo(r,null)}}async function Mv(e,{from:t=null,payToken:n=null,amountWei:r=null}={}){let o=e.id+":gas",i=ty(o,Lv);if(i!==void 0)return i;let s=await ny(e);if(!s)return oo(o,null);try{let a=BigInt(await vi(e,"eth_gasPrice")),c=null,l=!1;try{let p=!!(n&&!n.native);if(p&&t){let h=String(t||"").replace(/^0x/,"").padStart(64,"0"),w=BigInt(r||1).toString(16).padStart(64,"0");c=BigInt(await vi(e,"eth_estimateGas",[{from:t,to:n.address,data:"0xa9059cbb"+h+w}])),l=!0}else t?(c=BigInt(await vi(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 oo(o,{usd:d,gasLimit:c.toString(),gasPrice:a.toString(),native:s,source:"rpc",measured:l})}catch{return oo(o,null)}}async function ry(e,t={}){if(!e||!e.rpcUrl)return{nativeUsd:null,gasUsd:null,source:"none"};let[n,r]=await Promise.all([ny(e),Mv(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 oy(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 Zw,Hv,Lv,Fv,ey,Jw,iy=se(()=>{Zw={description:"0x7284e416",latestRoundData:"0xfeaf968c"},Hv=6e4,Lv=3e4,Fv=1440*60*1e3,ey=new Map;Jw=(e,t)=>BigInt("0x"+String(e).slice(2).slice(t*64,(t+1)*64))});function Uv({gasPriceWei:e,readyGasLimit:t=sy,refundGasLimit:n=ay,depositGasLimit:r=0n,extraFeeWei:o=0n}={}){let i=nn(e);if(i===null||i<=0n)return null;let s=nn(t),a=nn(n),c=nn(r),l=nn(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 jv({reserveWei:e,nativeUsd:t,decimals:n=18}={}){let r=nn(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 Kv({nativeBalanceWei:e,reserveWei:t}={}){let n=nn(t);if(n===null||n<=0n)return{measured:!1,enough:null,show:!1,balanceUnread:!1};let r=nn(e);return r===null?{measured:!0,enough:!1,show:!0,balanceUnread:!0}:{measured:!0,enough:r>=n,show:r<n,balanceUnread:!1}}function cy({gasPriceWei:e=null,nativeBalanceWei:t=null,nativeUsd:n=null,decimals:r=18,depositGasLimit:o=0n,extraFeeWei:i=0n}={}){let s=Uv({gasPriceWei:e,depositGasLimit:o,extraFeeWei:i}),a=nn(o),c=nn(i),l=s===null?null:jv({reserveWei:s,nativeUsd:n,decimals:r}),u=Kv({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 sy,ay,o5,nn,ly=se(()=>{sy=120000n,ay=250000n,o5=sy+ay,nn=e=>{if(e==null||e==="")return null;try{return BigInt(typeof e=="bigint"?e:String(e))}catch{return null}}});var fy={};Le(fy,{STEP_LABELS:()=>wu,activeSwaps:()=>gu,amountInputValue:()=>im,cachedFeeRate:()=>bw,cachedFeeTerms:()=>yw,claimOrder:()=>Gv,createReverseSwap:()=>bu,createSwap:()=>yu,createSwapWallet:()=>ys,dealSwapIds:()=>Eu,dexLegVerdict:()=>$u,ensureFeeTerms:()=>gw,evm:()=>Re,feeWeiFor:()=>Ru,markReadyOrder:()=>Yv,moneroNode:()=>hi,networkFromShape:()=>Hr,networkLabel:()=>vp,nodeHeight:()=>wS,orderDeadlines:()=>mS,orderGasReservePlan:()=>cy,orderStatus:()=>hS,priceLabel:()=>oy,probeMode:()=>kp,quoteDexOut:()=>zu,refreshChainPrices:()=>ry,refundOrder:()=>qv,sdkAddressNetwork:()=>vS,sdkAutoRefund:()=>Qv,sdkBook:()=>iS,sdkBookSnapshot:()=>sS,sdkBookUse:()=>tS,sdkBundle:()=>qu,sdkConfirmReady:()=>bS,sdkCoreModules:()=>br,sdkForgetSwap:()=>pS,sdkGetSwap:()=>cS,sdkListSwaps:()=>aS,sdkOpenRecovery:()=>Zv,sdkOrderQuote:()=>lS,sdkOrderTerms:()=>Qu,sdkProgress:()=>yS,sdkQuotesSnapshot:()=>eS,sdkRefundEth:()=>gS,sdkSetDestination:()=>kS,sdkStartSwap:()=>uS,sdkSweepNow:()=>xS,sdkSyncSwaps:()=>fS,sdkWatchQuotes:()=>Jv,sdkWatchSwap:()=>dS,serverRestoreHeightFor:()=>Au,setLiveFocus:()=>_u,swapCore:()=>me,toWei:()=>xa,useStartSwap:()=>Vv});function Vv(e=null){return Ta=typeof e=="function"?e:null,!!Ta}async function qu(){return Yu||(Yu=(async()=>{try{return await import(Wv)}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 br(){let e=await qu();return e?{actions:{createActions:e.createActions},wallet:{evmWallet:e.evmWallet},recovery:{createRecovery:e.createRecovery}}:null}async function $v(){let e=await qu();return e?{factory:e.createNinsei}:null}function zv(e){return e&&e.escrow&&e.escrow.mode==="live"?"live":"sim"}function Xv(e){return{settlement:{chain:e.id},xmrNetwork:e.monero&&e.monero.networkType||Te.networkType,assetsBase:"/",mode:zv(e),storage:Wl(),serverAuth:async()=>{if(ia())return ia();try{await Em()}catch{return null}return ia()},evmCall:t=>Ln(t),evmCode:t=>ra({address:t}),allowedProviders:Lc(e),knownFactoryCodes:Fc(e),knownImplementationCodes:Dc(e)}}async function Ke(e){let t=await $v();if(!t)return null;let n=it(e||Rt);return Gu.has(n.id)||Gu.set(n.id,t.factory(Xv(n))),{chain:n,sdk:Gu.get(n.id)}}function Si(e){let t=typeof li=="function"?li():null;return t?e.wallet.evmWallet(t):null}async function Yv({escrow:e,expect:t}={}){let n=await br(),r=n?Si(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=>Ln(o)}).markReady({escrow:e,expect:t},r)}async function Gv({escrow:e,halfClaimer:t,expect:n}={}){let r=await br(),o=r?Si(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=>Ln(i)}).claim({escrow:e,halfClaimer:t,expect:n},o)}async function qv({escrow:e,halfLocker:t}={}){let n=await br(),r=n?Si(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=>Ln(o)}).refund({escrow:e,halfLocker:t},r)}async function Qv(e){let t=await Ke(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||Te.networkType)),!n.wallet){let r=await br(),o=r?Si(r):null;o&&(n.wallet=o)}return t.sdk.swaps.refundIfXmrMissing(n)}async function Zv(e,t){let n=await br();return n?await n.recovery.createRecovery().open(e,t):null}async function Jv(e,t){let n=await Ke(e&&e.chain);return n?n.sdk.quotes.watch(e,t):null}async function eS(e){let t=await Ke(e);return t?t.sdk.quotes.snapshot():null}function tS(e){if(uy=e||null,yr=null,Ia=null,Vn=null,Dt)try{Dt()}catch{}Dt=null}function dy(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 rS(e){return{...dy(e),code:e.code,kind:nS[e.code]||e.code,why:e.why}}function oS(e){if(!e)return{ok:!1,error:null,data:null,at:0,fetching:!1};let t=(Array.isArray(e.offers)?e.offers:[]).map(dy),n=(Array.isArray(e.refused)?e.refused:[]).map(rS),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 iS({chain:e,direction:t,token:n,size:r}={}){let o=uy,i="injected";if(!o){let l=await Ke(e);if(!l){if(Dt){try{Dt()}catch{}Dt=null}return Ia=null,Vn=null,yr=null,null}o=l.sdk.quotes,i=l.chain.id}let s=t==="sell"?"sell":"buy",a=i+"|"+s+"|"+String(n||"")+"|"+String(r??"");if(Dt&&Ia===a)return yr;if(Dt){try{Dt()}catch{}Dt=null}Ia=a,Vn=null;let c=new Promise(l=>{Vn=l});try{Dt=o.watch({direction:s,token:n,size:r},l=>{if(yr=l,Vn){let u=Vn;Vn=null,u()}})}catch(l){return Vn=null,yr=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,yr}function sS(){return oS(yr)}async function aS(e){let t=await Ke(e);return t?t.sdk.swaps.list():null}async function cS(e,t){let n=await Ke(t);return n?n.sdk.swaps.get(e):null}function Qu({chain:e,amountWei:t,finality:n=null,salt:r=null,asset:o="XMR"}={}){let i=qw(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:mr(),amount:String(t),asset:String(o||"XMR"),readyBy:String(s+i.readyWindowSeconds),t1:String(s+i.claimWindowSeconds),salt:r||ga()}}async function lS({chain:e,providerId:t,amountWei:n,finality:r=null,salt:o=null,asset:i="XMR"}={}){let s=await Ke(e);if(!s)return null;let a=Qu({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 uS(e){if(Ta)return Ta({...e||{}});let t=await Ke(e&&e.chain);if(!t)return null;let n={...e||{}};if(!n.wallet){let r=await br(),o=r?Si(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=Qu({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 dS(e){let t=await Ke(e&&e.chain);return t?t.sdk.swaps.watch(e):null}async function fS(e){let t=await Ke(e);return t?t.sdk.swaps.sync():null}async function pS(e,t){let n=await Ke(t);return n?n.sdk.swaps.forget(e):null}async function hS(e){let t=await Ke(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 mS(e){let t=await Ke(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 wS(){return lu()}async function yS(e,t){let n=await Ke(t);return n?n.sdk.swaps.progress(e):null}async function bS(e){let t=await Ke(void 0);return t?t.sdk.swaps.confirmReady(e):ku(e)}async function gS(e,t="you"){let n=await Ke(void 0);return n?n.sdk.swaps.refundEth(e,t):Su(e,t)}async function xS(e){let t=await Ke(void 0);return t?t.sdk.swaps.sweepNow(e):vu(e)}async function kS(e,t){let n=await Ke(void 0);if(n)return n.sdk.swaps.setDestination(e,t);let r=Qr(e);return r?(r.receiveAddress=t,xu(r)):null}async function vS(e){let t=await Ke(void 0);if(t)return t.sdk.swaps.addressNetwork(e);try{return Hr(e)}catch{return null}}var Wv,Ta,Yu,Gu,Dt,Ia,yr,Vn,uy,nS,py=se(()=>{kt();Js();cu();ju();Qw();to();bi();ba();sr();mi();Gc();zl();iy();ly();Xu();to();ba();bi();bi();mi();Wv=new URL("../../assets/vendors/sdk/sdk-browser.js?v=fa7dc71a",import.meta.url).href,Ta=null;Yu=null;Gu=new Map;Dt=null,Ia=null,yr=null,Vn=null,uy=null;nS={disabled:"off"}});kt();Vc();Vh();Js();cu();bi();rl();ai();var At={};Le(At,{ORDER_CONTEXT_VERSION:()=>Xm,orderContextString:()=>Q1});var Xm="ninsei-order-v3",G1=e=>String(e??"").trim().toLowerCase(),q1=e=>{if(typeof e=="bigint")return e.toString(10);if(typeof e=="number")return String(Math.trunc(e));let t=G1(e);return t.startsWith("0x")?BigInt(t).toString(10):t},zm=["chainId","factory","locker","claimer","amount","readyBy","t1","salt"];function Q1(e){if(!e||typeof e!="object")throw new Error("order context needs an object with the order fields");let t=zm.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 Xm+"|"+zm.map(n=>q1(e[n])).join("|")}var da={};Le(da,{createOrderBuilder:()=>nv});ai();function la(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 Ym({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=A=>{let j=String(A??""),K=[];for(let Z=0;Z<j.length;Z++){let Y=j.codePointAt(Z);Y>65535&&Z++,Y<128?K.push(Y):Y<2048?K.push(192|Y>>6,128|Y&63):Y<65536?K.push(224|Y>>12,128|Y>>6&63,128|Y&63):K.push(240|Y>>18,128|Y>>12&63,128|Y>>6&63,128|Y&63)}return new Uint8Array(K)},u=A=>typeof A=="string"?A:A.toHex?A.toHex():String(A);function d(A){let j=A.replace(/^0x/i,""),K=new Uint8Array(j.length/2);for(let Z=0;Z<K.length;Z++)K[Z]=parseInt(j.substr(Z*2,2),16);return K}let p=A=>A.toString(16).padStart(64,"0");function h(A){let j=0n;for(let K of A)j=j<<8n|BigInt(K);return j}function w(A){let j=0n;for(let K=A.length-1;K>=0;K--)j=j<<8n|BigInt(A[K]);return j}function y(A){let j=A.reduce((Y,ne)=>Y+ne.length,0),K=new Uint8Array(j),Z=0;for(let Y of A)K.set(Y,Z),Z+=Y.length;return K}function k(A,j){let K=r(y(j.map(Z=>typeof Z=="string"?d(Z):Z)));if(K.length!==64)throw new Error("challenge: sha3_512 returned "+K.length+" bytes instead of 64");return w(K)%A.order}function x(A){let j=w(o(64))%A.order;return j===0n?1n:j}function _(A,j){return A>>BigInt(j)&1n}function v(A,j,K){let Y=((typeof K=="bigint"?K:BigInt(K))%A.order+A.order)%A.order;return Y===0n?A.P.ZERO:j===A.Galt?j.multiply(Y):j.multiplyUnsafe(Y)}function H(A,j,K){return v(A,K||A.G,typeof j=="bigint"?j:BigInt(j))}let b=(A,j)=>A.add(j),I=(A,j)=>A.subtract(j),O=A=>d(A.toHex()),S=A=>d(p(A));function T(A){let j=A.next();for(;!j.done;)j=A.next();return j.value}let N=async A=>typeof A=="function"?await A():globalThis.scheduler&&typeof globalThis.scheduler.yield=="function"?await globalThis.scheduler.yield():await new Promise(j=>setTimeout(j,0));function*V(A,j){let K=[],Z=[],Y=0n,ne=1n;for(let oe=0;oe<a;oe++){if(oe===a-1){let ke=m(ne,A.order);K[oe]=(A.order-Y%A.order)*ke%A.order}else K[oe]=x(A),Y=(Y+K[oe]*ne)%A.order,ne=ne*2n%A.order;let pe=_(j,oe);Z.push(b(H(A,pe),H(A,K[oe],A.Galt))),yield oe+1}return{rs:K,cs:Z}}function X(A,j){return T(V(A,j))}function m(A,j){let[K,Z]=[A%j,j],[Y,ne]=[1n,0n];for(;Z!==0n;){let oe=K/Z;[K,Z]=[Z,K-oe*Z],[Y,ne]=[ne,Y-oe*ne]}if(K!==1n)throw new Error("modInv: not invertible");return(Y%j+j)%j}function*g(A,j){let K=j[0];for(let Z=1;Z<j.length;Z++)K=b(K,H(A,2n**BigInt(Z)%A.order,j[Z])),yield{phase:"sum",done:Z,total:j.length};return K}function E(A,j){return T(g(A,j))}function C(A,j,K,Z,Y,ne,oe){let pe=x(c.A),ke=x(c.B),we=(Je,lt)=>[l(oe),O(K),O(Z),O(Je),O(lt)],re=k(c.A,we(H(c.A,pe,c.A.Galt),H(c.B,ke,c.B.Galt)),oe),ie=k(c.B,we(H(c.A,pe,c.A.Galt),H(c.B,ke,c.B.Galt)),oe);if((A===1n||A===1?1n:0n)===0n){let Je=x(c.A),lt=x(c.B),Uo=I(K,c.A.G),jo=I(Z,c.B.G),Ko=k(c.A,we(I(H(c.A,Je,c.A.Galt),v(c.A,Uo,re)),I(H(c.B,lt,c.B.Galt),v(c.B,jo,ie))),oe),Wo=k(c.B,we(I(H(c.A,Je,c.A.Galt),v(c.A,Uo,re)),I(H(c.B,lt,c.B.Galt),v(c.B,jo,ie))),oe);return{eA:Ko,eB:Wo,a0:Je,a1:(pe+Ko*Y)%c.A.order,b0:lt,b1:(ke+Wo*ne)%c.B.order}}let ve=x(c.A),Xt=x(c.B),ae=k(c.A,we(I(H(c.A,ve,c.A.Galt),v(c.A,K,re)),I(H(c.B,Xt,c.B.Galt),v(c.B,Z,ie))),oe),Ue=k(c.B,we(I(H(c.A,ve,c.A.Galt),v(c.A,K,re)),I(H(c.B,Xt,c.B.Galt),v(c.B,Z,ie))),oe);return{eA:re,eB:ie,a0:(pe+ae*Y)%c.A.order,a1:ve,b0:(ke+Ue*ne)%c.B.order,b1:Xt}}let M=A=>({eA:p(A.eA),eB:p(A.eB),a0:p(A.a0),a1:p(A.a1),b0:p(A.b0),b1:p(A.b1)});function $(A,j,K,Z,Y){let ne=x(A),oe=H(A,ne),pe=k(A,[l(Z),l("ninsei-dleq-pok|"+Y),O(K),O(oe)]);return{R:u(oe),s:p((ne+pe*j)%A.order)}}function L(A,j,K,Z,Y){if(!K||typeof K!="object"||typeof K.R!="string"||typeof K.s!="string")return!1;let ne,oe;try{ne=A.P.fromHex(K.R.replace(/^0x/i,"")),oe=BigInt(String(K.s).startsWith("0X")?"0x"+String(K.s).slice(2):String(K.s).startsWith("0x")?K.s:"0x"+K.s)}catch{return!1}let pe=k(A,[l(Z),l("ninsei-dleq-pok|"+Y),O(j),O(ne)]);return H(A,oe).equals(b(ne,v(A,j,pe)))}function*F(A,j){A=typeof A=="bigint"?A:BigInt(A);let K=H(c.A,A),Z=H(c.B,A);yield{phase:"prepare",done:0,total:a};let Y=V(c.A,A),ne=V(c.B,A);for(let we=0;we<a;we++){let re=Y.next(),ie=ne.next();if(re.done||ie.done)throw new Error("prepareProof: commitments ended early");yield{phase:"prepare",done:we+1,total:a}}let oe=Y.next().value,pe=ne.next().value,ke=[];for(let we=0;we<a;we++)ke.push({i:we,bit:_(A,we)===1n?1:0,cA:u(oe.cs[we]),cB:u(pe.cs[we]),rA:p(oe.rs[we]),rB:p(pe.rs[we])});return yield{phase:"know",done:a,total:a},{XA:u(K),XB:u(Z),context:String(j??""),pokA:$(c.A,A,K,j,"A"),pokB:$(c.B,A,Z,j,"B"),bits:ke}}function B(A,j){return T(F(A,j))}async function P(A,j,K={}){let Z=Number.isSafeInteger(K.chunkBits)&&K.chunkBits>0?Math.min(K.chunkBits,a):8,Y=F(A,j),ne=0;for(;;){let oe=Y.next();if(oe.done)return oe.value;ne+=1,typeof K.onPrepare=="function"&&K.onPrepare(oe.value),ne%Z===0&&await N(K.yieldTo)}}function D(A,j){let K=C(A.bit===1?1n:0n,A.i,c.A.P.fromHex(String(A.cA).replace(/^0x/,"")),c.B.P.fromHex(String(A.cB).replace(/^0x/,"")),BigInt("0x"+String(A.rA).replace(/^0x/,"")),BigInt("0x"+String(A.rB).replace(/^0x/,"")),j);return{i:A.i,cA:A.cA,cB:A.cB,sig:M(K)}}function U(A,j){let K=new Map(j.map(Y=>[Y.i,Y])),Z=[];for(let Y=0;Y<a;Y++){let ne=K.get(Y);if(!ne)throw new Error("assembleProof: no part for bit "+Y);Z.push({cA:ne.cA,cB:ne.cB,sig:ne.sig})}return{XA:A.XA,XB:A.XB,pokA:A.pokA,pokB:A.pokB,proofs:Z}}function q(A,j,K){let Z=B(A,j),Y=[];for(let ne=0;ne<a;ne++)K&&(ne%16===0||ne===a-1)&&K(ne+1,a),Y.push(D(Z.bits[ne],Z.context));return U(Z,Y)}async function W(A,j,K={}){let Z=Number.isSafeInteger(K.chunkBits)&&K.chunkBits>0?Math.min(K.chunkBits,a):4,Y=await P(A,j,{chunkBits:Number.isSafeInteger(K.prepareChunkBits)&&K.prepareChunkBits>0?K.prepareChunkBits:8,yieldTo:K.yieldTo,onPrepare:K.onPrepare}),ne=[];for(let oe=0;oe<a;oe++)ne.push(D(Y.bits[oe],Y.context)),((oe+1)%Z===0||oe===a-1)&&(typeof K.onBit=="function"&&K.onBit(oe+1,a),await N(K.yieldTo));return U(Y,ne)}function G(A,j){if(A.name!=="ed25519")return!0;try{return j.isTorsionFree()===!0}catch{return!1}}function*z(A,j,K={}){if(!A||typeof A!="object")return{ok:!1,reason:"proof: an object is expected"};if(typeof A.XA!="string"||typeof A.XB!="string")return{ok:!1,reason:"proof: no XA or XB"};if(!Array.isArray(A.proofs))return{ok:!1,reason:"proof: no parts list"};if(A.proofs.length!==a)return{ok:!1,reason:"proof: "+A.proofs.length+" parts, expected "+a};let Z=K.requireKnowledge!==!1,Y=(ie,ce)=>ie.P.fromHex(String(ce).replace(/^0x/i,"")),ne,oe,pe,ke;try{if(ne=Y(c.A,A.XA),oe=Y(c.B,A.XB),oe.equals(c.B.P.ZERO))return{ok:!1,reason:"proof: the subject point is the identity"};if(!G(c.B,oe))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(Z)try{if(!L(c.A,ne,A.pokA,j,"A"))return{ok:!1,reason:"proof: the secp256k1 knowledge proof did not verify"};if(!L(c.B,oe,A.pokB,j,"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{pe=A.proofs.map((ie,ce)=>{try{return Y(c.A,ie.cA)}catch(ve){throw new Error("bit "+ce+": "+String(ve&&ve.message||ve))}}),ke=A.proofs.map((ie,ce)=>{try{return Y(c.B,ie.cB)}catch(ve){throw new Error("bit "+ce+": "+String(ve&&ve.message||ve))}})}catch(ie){return{ok:!1,reason:"proof: "+String(ie&&ie.message||ie)}}if(!(yield*g(c.A,pe)).equals(ne))return{ok:!1,reason:"the commitment sum does not give X on secp256k1"};if(!(yield*g(c.B,ke)).equals(oe))return{ok:!1,reason:"the commitment sum does not give X on ed25519"};for(let ie=0;ie<A.proofs.length;ie++){let ce=A.proofs[ie];try{if(!G(c.B,ke[ie]))return{ok:!1,reason:"bit "+ie+": the commitment is not in the prime-order subgroup"};let ve=ce.cA,Xt=ce.cB,ae={};for(let cs of["eA","eB","a0","a1","b0","b1"]){let Bc=ce.sig[cs],Pc=String(Bc);ae[cs]=BigInt(/^0x/i.test(Pc)?Pc:"0x"+Pc)}let Ue=Y(c.A,ve),Je=Y(c.B,Xt),lt=(cs,Bc)=>[l(j),O(Ue),O(Je),O(cs),O(Bc)],Uo=H(c.A,ae.a1,c.A.Galt),jo=v(c.A,Ue,ae.eA),Ko=H(c.B,ae.b1,c.B.Galt),Wo=v(c.B,Je,ae.eB),px=k(c.A,lt(I(Uo,jo),I(Ko,Wo)),j),hx=k(c.B,lt(I(Uo,jo),I(Ko,Wo)),j),Qf=H(c.A,ae.a0,c.A.Galt),Zf=v(c.A,I(Ue,c.A.G),px),Jf=H(c.B,ae.b0,c.B.Galt),ep=v(c.B,I(Je,c.B.G),hx),mx=k(c.A,lt(I(Qf,Zf),I(Jf,ep)),j),wx=k(c.B,lt(I(Qf,Zf),I(Jf,ep)),j);if(mx!==ae.eA||wx!==ae.eB)return{ok:!1,reason:"bit "+ie+": challenges did not match"}}catch(ve){return{ok:!1,reason:"bit "+ie+": fields are unparsable ("+String(ve&&ve.message||ve)+")"}}yield{phase:"verify",done:ie+1,total:A.proofs.length}}return{ok:!0}}function ee(A,j,K={}){return T(z(A,j,K))}async function Q(A,j,K={}){let Z=z(A,j,K),Y=null,ne=0;for(;;){let oe=Z.next();if(oe.done)return oe.value;let pe=oe.value&&oe.value.phase?oe.value.phase:null;pe!==Y&&(Y=pe,ne=0),ne+=1,typeof K.onProgress=="function"&&K.onProgress(oe.value);let ke=Y==="sum"?16:Number.isSafeInteger(K.verifyChunkBits)&&K.verifyChunkBits>0?Math.min(K.verifyChunkBits,a):2;ne%ke===0&&await N(K.yieldTo)}}return{BITS:a,curves:c,prove:q,proveChunked:W,verify:ee,verifyChunked:Q,prepareProof:B,prepareProofChunked:P,proveBit:D,assembleProof:U,torsionFree:G}}var Gm="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 qm(){return globalThis.ARRAKIS_ALLOW_HALFENC===!0}function Qm({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 k=0n;for(let x of y)k=k<<8n|BigInt(x);return k}function c(y){for(let k=0;k<256;k++){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,k){let x=n(Uint8Array.from(Buffer.concat([Buffer.from(y.replace(/^0x/,""),"hex"),Buffer.from(k||"","utf8")])));return a(x)%s}function p(y,k,x){if(!qm())throw new Error(Gm);if(!(y>0n&&y<s))throw new Error("seal: half outside min(l, n)");let _=e.Point.fromHex(k.replace(/^0x/,"")),v=c(i),H=e.Point.BASE.multiply(v),b=_.multiply(v),I=d(b.toHex(),x),O=S=>"0x"+String(S).replace(/^0x/i,"").toLowerCase();return{recipient:O(k),ephemeral:O(H.toHex()),masked:"0x"+l((y+I)%s),context:x||""}}function h(y,k,x){if(!qm())return{ok:!1,reason:Gm};if(!y||!y.ephemeral||!y.masked)return{ok:!1,reason:"incomplete envelope"};let v=e.Point.fromHex(y.ephemeral.replace(/^0x/,"")).multiply(k),H=d(v.toHex(),y.context),b=(BigInt(y.masked)-H+s)%s;if(b===0n)return{ok:!1,reason:"restored zero"};if(!x)return{ok:!0,x:b};let I=t.Point.BASE.multiply(b).toHex(),O=t.Point.fromHex(x.startsWith("0x")?x.slice(2):x).toHex();return I!==O?{ok:!1,reason:"the ciphertext holds a different half"}:{ok:!0,x:b}}function w(y){let k=n(ua(y));return"0x"+Un(k)}return{LIMIT:s,recipientKeyPair:u,seal:p,open:h,packSealed:Nu,unpackSealed:ev,sealedCommitmentOf:w}}var Zm=1;function Un(e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}function Z1(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 J1(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 ua=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 Nu(e){if(!e||!e.recipient||!e.ephemeral||!e.masked)throw new Error("packSealed: incomplete envelope");let t=ua(e.recipient),n=ua(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=Z1(e.context);if(o.length>255)throw new Error("packSealed: context longer than 255 bytes");return"0x"+Un(Uint8Array.of(Zm))+Un(t)+Un(n)+r+o.length.toString(16).padStart(2,"0")+Un(o)}function ev(e){let t=ua(e);if(t.length<100)throw new Error("unpackSealed: envelope shorter than 100 bytes");if(t[0]!==Zm)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"+Un(t.slice(1,34)),ephemeral:"0x"+Un(t.slice(34,67)),masked:"0x"+Un(t.slice(67,99)),context:J1(t.slice(100))}}sr();ol();function nv({ed25519:e,secp256k1:t,keccak256:n,sha3_512:r,randomBytes:o}){let i=si({ed25519:e,secp256k1:t,keccak256:n,randomBytes:o}),s=Ym({ed25519:e,secp256k1:t,keccak256:n,sha3_512:r,randomBytes:o}),a=Qm({secp256k1:t,ed25519:e,keccak256:n,randomBytes:o});function c(v,H=!1,b){let I=i.newHalf(),O=i.publicHalves(I),S=i.newHalf(),T=i.publicHalves(S).ed,N=a.recipientKeyPair(),V=s.prove(I,v,b);return{half:I,pub:O,viewHalf:S,viewPub:T,enc:N,proof:V,standIn:H}}async function l(v,H=!1,b={}){let I=i.newHalf(),O=i.publicHalves(I),S=i.newHalf(),T=i.publicHalves(S).ed,N=a.recipientKeyPair(),V=await s.proveChunked(I,v,b);return{half:I,pub:O,viewHalf:S,viewPub:T,enc:N,proof:V,standIn:H}}function u(v,H,b,I,O){if(!O.ok)return{ok:!1,reason:"counterparty DLEQ failed: "+O.reason};if(v.pub&&v.pub.ed&&String(v.proof.XB).toLowerCase()!==String(v.pub.ed).toLowerCase())return{ok:!1,reason:"the proven ed25519 point does not match the declared one: "+v.proof.XB+" vs "+v.pub.ed};if(v.commitHalfClaimer){let S=null;try{let V=t.Point.fromHex(String(v.proof.XA).replace(/^0x/,"")).toBytes(!1).slice(1);S="0x"+Array.from(n(V),X=>X.toString(16).padStart(2,"0")).join("")}catch{S=null}let T=N=>String(N||"").replace(/^0x/,"").toLowerCase().slice(-40);if(!S||T(S)!==T(v.commitHalfClaimer))return{ok:!1,reason:"the proven secp256k1 point does not match commitHalfClaimer: "+(S||"unparsed")+" vs "+v.commitHalfClaimer}}else return{ok:!1,reason:"the counterparty side carries no commitHalfClaimer"};if(b&&I){let S=a.open(a.unpackSealed(b),I,v.pub.ed);if(!S.ok)return{ok:!1,reason:"the counterparty envelope does not confirm the half: "+S.reason}}return{ok:!0}}function d(v,H,b,I){return u(v,H,b,I,s.verify(v.proof,H))}async function p(v,H,b,I,O={}){let S=await s.verifyChunked(v.proof,H,O);return u(v,H,b,I,S)}function h(v,H,b){let I=a.seal(H,v.enc.pub,b),O=Nu(I);return{sealed:I,bytes:O,commitment:a.sealedCommitmentOf(O)}}function w(v,H,b){return a.open(a.unpackSealed(v),H,b)}function y(v){return la(v,t,n)}function k(v,H){return i.combinePublic(v.pub.ed,H.pub.ed)}function x(v){return i.publicHalves(typeof v=="bigint"?v:BigInt(v)).ed}function _({ownSpendHalf:v,ownViewHalf:H,otherSpendPoint:b,otherViewPoint:I,network:O}){return ks({halves:i,addressFromKeys:ir,deps:{keccak256:n},ownSpendHalf:v,ownViewHalf:H,otherSpendPoint:b,otherViewPoint:I,network:O})}return{halves:i,dleq:s,enc:a,newSide:c,newSideChunked:l,verifySide:d,verifySideChunked:p,sealFor:h,openFrom:w,jointAddressPoint:k,pointOf:x,jointAddress:_,halfCommitment:y}}ju();Xu();var Ba={};Le(Ba,{checkOrderQuoteShape:()=>ES,pairAsset:()=>PS,pairCurrency:()=>OS,pairFacingUser:()=>BS,quoteNetworksFit:()=>RS,refreshRfq:()=>Zu,requestOrderQuote:()=>SS,rfqOffers:()=>CS,rfqQuery:()=>IS,rfqSnapshot:()=>TS,setRfqQuery:()=>NS,startRfqPolling:()=>HS});kt();async function SS({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(_S()+"/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 ES(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 AS=null,_S=()=>AS||an.base,Nt={size:1,side:"buy",chain:Rt,token:null};function NS(e){e&&((e.side==="buy"||e.side==="sell")&&(Nt.side=e.side),e.size!==null&&e.size!==void 0&&Number(e.size)>0?Nt.size=Number(e.size):Nt.size=1,typeof e.chain=="string"&&e.chain&&(Nt.chain=e.chain),typeof e.token=="string"&&e.token&&(Nt.token=e.token))}function IS(){return{...Nt}}var qe={ok:!1,error:null,data:null,at:0,fetching:!1};function TS(){return qe}function BS(e=Nt.side,t="ETH"){return e==="sell"?t.toUpperCase()+"/XMR":"XMR/"+t.toUpperCase()}function PS(e){return String(e||"").split("/")[0].toUpperCase()}function OS(e){return String(e||"").split("/")[1]?String(e).split("/")[1].toUpperCase():""}function CS(){let e=qe.ok&&qe.data?qe.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 RS(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 Zu(){if(qe.fetching)return qe;qe.fetching=!0;try{let e=await Promise.resolve().then(()=>(py(),fy));await e.sdkBook({chain:Nt.chain,direction:Nt.side,token:Nt.token,size:Nt.size});let t=e.sdkBookSnapshot();qe.ok=t.ok,qe.error=t.error,qe.data=t.data,qe.at=t.at||Date.now()}catch(e){qe.ok=!1,qe.error=String(e&&e.message||e),qe.data=null,qe.at=Date.now()}finally{qe.fetching=!1}return qe}var hy=null;function HS(e=null,t=an.pollMs){typeof e=="string"&&e&&(Nt.chain=e),!hy&&(Zu(),hy=setInterval(()=>Zu(),t))}na();ya();var Pa={};Le(Pa,{scalarFromMoneroHex:()=>FS,spendKeysFromRevealedHalf:()=>LS});function LS({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"),h=w=>p(w).match(/../g).reverse().join("");return{privateSpendKey:h(a),privateViewKey:h(d)}}function FS(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(""))}sr();var my=5e8;function Ju(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 Oa(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 Ei={};Le(Ei,{ED_ORDER:()=>It,PEDERSEN_H:()=>by,UNLOCK_TIME_BLOCK_MAX:()=>my,amountMaskCommitment:()=>gy,bytesToHex:()=>xr,decodeAmount:()=>Ey,decodeMask:()=>ed,derivedOutputKey:()=>ky,fetchBlock:()=>Ny,fetchTransactions:()=>Iy,findOurOutputs:()=>Ay,hashToScalar:()=>io,hexToBytes:()=>gr,keccak:()=>td,keyDerivation:()=>Ra,laterBoundary:()=>Oa,matchTransaction:()=>Ty,scalarFromBytesLE:()=>Ha,scalarFromHexLE:()=>nd,scalarToBytesLE:()=>Ca,scanRange:()=>WS,txKeysFromExtra:()=>id,txPublicKeyFromExtra:()=>jS,unlockStateOf:()=>Ju,varint:()=>rd,viewKeyFormForAddress:()=>US,viewSecretCandidates:()=>od});Bl();Ul();function td(e){return qs(e)}var It=Ge.Point.CURVE().n,by="8b655970153799af2aeadc9ff1add0ea6c7251d54154cfa92c173a0dd39c1f94",MS=Ge.Point.fromHex(by);function wy(e,t){let n=(BigInt(t)%It+It)%It;return n===0n?Ge.Point.ZERO:e.multiply(n)}function gy(e,t){let n=BigInt(e);if(n<0n)throw new Error("the amount must not be negative");return wy(Ge.Point.BASE,t).add(wy(MS,n)).toHex()}function gr(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 xr(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function Ha(e){let t=Uint8Array.from(e).reverse();return BigInt("0x"+xr(t))}function nd(e){return Ha(gr(e))}function Ca(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 io(...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 Ha(td(n))%It}function rd(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 xy(e){return Ge.Point.fromHex(String(e).replace(/^0x/,""))}function od(e){if(typeof e=="bigint")return[["number",e%It]];let t=String(e).replace(/^0x/,"");return/^[0-9a-fA-F]{64}$/.test(t)?[["BE-number",BigInt("0x"+t)%It],["LE-bytes",nd(t)%It]]:[["unparsed",null]]}function US(e,t){let n=String(t||"").toLowerCase();if(!n)return null;for(let[r,o]of od(e))if(o!==null&&Ge.Point.BASE.multiply(o).toHex().toLowerCase()===n)return r;return!1}function Ra(e,t){let n=xy(e),r=(typeof t=="bigint"?t:nd(String(t).replace(/^0x/,"")))%It,o=n.multiply(r);return gr(o.multiply(8n).toHex())}function ky(e,t,n){let r=io(e,rd(t));return Ge.Point.BASE.multiply(r).add(xy(n)).toHex()}function yy(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 id(e){let t=Array.isArray(e)?Uint8Array.from(e):gr(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(xr(t.subarray(o,o+32))),o+=32;continue}if(i===2||i===3){let s=yy(t,o);if(!s||s.value>BigInt(t.length-s.next))break;o=s.next+Number(s.value);continue}if(i===4){let s=yy(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(xr(t.subarray(o,o+32))),o+=32;continue}break}return{txPublicKeys:n,additionalPublicKeys:r}}function jS(e){return id(e).txPublicKeys[0]||null}function vy(e){return Number(e)>=4}function KS(e,t){let n=io(e);return t==="mask"?n:io(gr(n.toString(16).padStart(64,"0")))}function Sy(e,t,n,r){if(vy(n)){if(r==="mask")return io(new TextEncoder().encode("commitment_mask"),t);let s=gr(e),a=new TextEncoder().encode(r),c=new Uint8Array(a.length+t.length);c.set(a,0),c.set(t,a.length);let l=td(c),u=s.slice();for(let d=0;d<u.length&&d<l.length;d++)u[d]^=l[d];return Ha(u)}let o=gr(e);return(BigInt("0x"+xr(o))%It-KS(t,r)+It)%It}function Ey(e,t,n){return Sy(e,t,n,"amount")}function ed(e,t,n){return Sy(e,t,n,"mask")}function Ay({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]:[],d=Array.isArray(n)?n:[];if(!u.length&&!d.length)throw new Error("the transaction has no public key (extra tag 0x01/0x04) - nothing to parse");let p=od(r).filter(([,w])=>w!==null),h=p[0]||["unparsed",null];for(let[w,y]of p){let k=u.map(_=>Ra(_,y)),x=[];for(let _ of i){let v=k.slice();d[_.index]&&v.push(Ra(d[_.index],y));for(let H of v){let b=io(H,rd(_.index));if(ky(H,_.index,o).toLowerCase()!==String(_.key).toLowerCase())continue;let O=s[_.index]?Ey(s[_.index],Ca(b),l):null,S=vy(l)?ed(null,Ca(b),l):a[_.index]?ed(a[_.index],Ca(b),l):null,T=!1;if(O!==null&&S!==null&&c[_.index])try{T=gy(O,S).toLowerCase()===String(c[_.index]).replace(/^0x/,"").toLowerCase()}catch{T=!1}x.push({index:_.index,key:_.key,amountAtomic:O,maskAtomic:S,amountVerified:T,derivation:xr(H)});break}}if(x.length)return{derivation:x[0].derivation,outputs:x,viewKeyForm:w}}return{derivation:h[1]===null||!u.length?null:xr(Ra(u[0],h[1])),outputs:[],viewKeyForm:h[0]}}var _y=e=>{let t=String(e);for(;t.endsWith("/");)t=t.slice(0,-1);return t};async function Ny(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(`${_y(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 Iy(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(`${_y(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(h=>String(h).replace(/^0x/,"").toLowerCase()))],u=new Map;for(let h of a){let w=String(h&&h.tx_hash||"").replace(/^0x/,"").toLowerCase();if(w){if(u.has(w))throw new Error("transactions-duplicate: "+w);u.set(w,h)}}let d=l.filter(h=>!u.has(h));if(d.length)throw new Error("transactions-missing: "+d.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 p=new Map(a.map((h,w)=>[String(h&&h.tx_hash||"").replace(/^0x/,"").toLowerCase(),w]));return l.map(h=>{let w=u.get(h)||{},y=c[p.get(h)],k=typeof y=="string"?JSON.parse(y):y;return k.tx_hash=w.tx_hash||k.tx_hash||null,k.block_height=w.block_height??null,k.confirmations=w.confirmations??null,k.in_pool=w.in_pool??null,k})}function Ty(e,t,{height:n=null,tipHeight:r=null,nowSec:o=null}={}){let i=[],s=id(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=Ju(e.unlock_time,{height:c,nowSec:o}),u=x=>((x.target||{}).tagged_key||x.target||{}).key,d=(e.vout||[]).map((x,_)=>({index:_,key:u(x)})),p=(e.rct_signatures||{}).ecdhInfo||[],h=p.map(x=>x.amount),w=p.map(x=>x.mask),y=(e.rct_signatures||{}).outPk||[],k=(e.rct_signatures||{}).type||2;for(let x of t){let _=Ay({txPublicKeys:s.txPublicKeys,additionalPublicKeys:s.additionalPublicKeys,viewSecretHex:x.viewSecret,spendPubHex:x.spendPub,outputs:d,ecdhAmounts:h,ecdhMasks:w,outPk:y,rctVersion:Number(k)||1});_.outputs.length&&i.push({address:x.address,index:x.index??null,outputs:_.outputs,derivation:_.derivation,viewKeyForm:_.viewKeyForm,unlockTime:Number(e.unlock_time)||0,unlock:l})}return i}async function WS({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 h=[],w=0,y=async()=>{for(;w<p.length;){let x=p[w++];try{let _=await Ny(e,x,c),v=_.json?(typeof _.json=="string"?JSON.parse(_.json):_.json).tx_hashes||[]:[];if(!v.length)continue;let H=await Iy(e,v,c);for(let b of H)for(let I of Ty(b,r,{height:x,tipHeight:a??u,nowSec:s})){let O=d.get(I.address);if(!O)continue;I.viewKeyForm&&(O.viewKeyForm=I.viewKeyForm);let S=!!(I.unlock&&I.unlock.locked),T=String(b.tx_hash||"").replace(/^0x/,"");for(let N of I.outputs){let V=N.amountVerified&&N.amountAtomic||0n;S?(O.lockedAtomic+=V,T&&!O.lockedTxids.includes(T)&&O.lockedTxids.push(T),Oa(I.unlock)>Oa(O.lockedUntil)&&(O.lockedUntil=I.unlock)):(O.receivedAtomic+=V,O.outputs+=1),T&&!O.txids.includes(T)&&O.txids.push(T),(O.bestHeight===null||x>O.bestHeight)&&(O.bestHeight=x)}}}catch(_){h.push(x),o({event:"indexer_block_error",height:x,error:String(_.message).slice(0,160)})}}};await Promise.all(Array.from({length:Math.max(1,Math.min(i,p.length))},y));let k=[...new Set(h)].sort((x,_)=>x-_);return{fromHeight:l,toHeight:u,results:Array.from(d.values()),complete:k.length===0,missingHeights:k,...k.length?{incompleteReason:"blocks-unreadable"}:{}}}var La=["awaiting_funding","funded","maker_locking","xmr_locked","ready","claimed","swept"];var Fa=["balance","gas","allowance","consent","network","settlement-network","stale","deadline","range","size","escrow-state","escrow-points","counterparty","slots","unchecked","unknown"],so=["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","quote-cashier-mismatch","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","sweep-fee-unknown","gas-refused-by-maker","gas-not-arrived","gas-too-little","unknown"];var VS=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"},"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"},"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"},"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"}}),$S={"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"},By=e=>$S[e]||"unknown";xe();var Fd={};Le(Fd,{ASYNC:()=>ze,BALANCE_OF_SELECTOR:()=>W0,SETTLES:()=>Ld,SYNC:()=>Ai,balances:()=>DE,carriesNativeVerdict:()=>KE,providerSettles:()=>$0,requireAsyncProvider:()=>UE,requireProvider:()=>jE,requireSyncProvider:()=>ME,routeProviderFor:()=>Ja,routeProviders:()=>wo,sameChain:()=>LE,vm:()=>HE,walletChainId:()=>K0});var Ai="sync",ze="async";var sd=e=>!e||typeof e!="object"?{ok:!1,reason:"provider-absent"}:e.shape!==Ai&&e.shape!==ze?{ok:!1,reason:"provider-shape-unknown",shape:e.shape===void 0?null:e.shape}:e.shape===ze&&typeof e.settled!="function"?{ok:!1,reason:"provider-incomplete",shape:ze,missing:"settled"}:{ok:!0,shape:e.shape};$e();var Py="NinseiEscrowFactory";var zS=["EIP712Domain(","string name,","string version,","uint256 chainId,","address verifyingContract)"],Oy=zS.join(""),Ma=[["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"]],Cy="OrderQuote("+Ma.map(e=>e[1]+" "+e[0]).join(",")+")",$n=e=>{throw new Error(e)},Da=e=>new TextEncoder().encode(String(e)),Ua=(...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&&$n("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)&&$n("eip712-bad-hex"),n[r]=o}return n},XS=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},YS=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("eip712-bad-number")},ad=(e,t)=>{let n=YS(e);n<0n&&$n("eip712-negative"),n>=1n<<BigInt(t)&&$n("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},Ry=e=>{let t=String(e??"").trim();/^(0x)?[0-9a-fA-F]{40}$/.test(t)||$n("eip712-bad-address");let n=new Uint8Array(32);return n.set(cd(t.replace(/^0x/,"")),12),n},GS=e=>{let t=String(e??"").trim();return/^(0x)?[0-9a-fA-F]{64}$/.test(t)||$n("eip712-bad-bytes32"),cd(t.replace(/^0x/,""))},qS=(e,t)=>{if(e==="address")return Ry(t);if(e==="bytes32")return GS(t);if(e==="uint64")return ad(t,64);if(e==="uint256")return ad(t,256);$n("eip712-bad-type")},ld=e=>{let t=[];for(let[n]of Ma){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 QS({crypto:e,quote:t}){return e.keccak256(Ua(e.keccak256(Da(Oy)),e.keccak256(Da(Py)),e.keccak256(Da("1")),ad(t.chainId,256),Ry(t.factory)))}function ZS({crypto:e,quote:t}){let n=[e.keccak256(Da(Cy))];for(let[r,o]of Ma)n.push(qS(o,t?t[r]:void 0));return e.keccak256(Ua(...n))}function Hy({crypto:e,quote:t}){return e.keccak256(Ua(Uint8Array.from([25,1]),QS({crypto:e,quote:t}),ZS({crypto:e,quote:t})))}function Ly({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=Hy({crypto:e,quote:t}),s=e.secp256k1.Signature.fromBytes(Ua(n.slice(0,32),n.slice(32,64))).addRecoveryBit(r).recoverPublicKey(o).toBytes(!1);return XS(e.keccak256(s.slice(1)).slice(12))}catch{return null}}var Fy=["Gnosis","Protocol"].join(" "),Dy="v2",kr="0x9008D19f58AAbD9eD0D60971565AA8510560ab41",My="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",JS=["EIP712Domain(","string name,","string version,","uint256 chainId,","address verifyingContract)"],e2=JS.join(""),ao=[["sellToken","address"],["buyToken","address"],["receiver","address"],["sellAmount","uint256"],["buyAmount","uint256"],["validTo","uint32"],["appData","bytes32"],["feeAmount","uint256"],["kind","string"],["partiallyFillable","bool"],["sellTokenBalance","string"],["buyTokenBalance","string"]],t2="Order("+ao.map(e=>e[1]+" "+e[0]).join(",")+")";var Mt=e=>{throw new Error(e)},_i=e=>new TextEncoder().encode(String(e)),Wa=(...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},ja=e=>{let t=String(e).replace(/^0x/,"");t.length%2&&Mt("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)&&Mt("cow-bad-hex"),n[r]=o}return n},Uy=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},n2=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);Mt("cow-bad-number")},Ka=(e,t)=>{let n=n2(e);n<0n&&Mt("cow-negative"),n>=1n<<BigInt(t)&&Mt("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},jy=e=>{let t=String(e??"").trim();/^(0x)?[0-9a-fA-F]{40}$/.test(t)||Mt("cow-bad-address");let n=new Uint8Array(32);return n.set(ja(t.replace(/^0x/,"")),12),n},r2=e=>{let t=String(e??"").trim();return/^(0x)?[0-9a-fA-F]{64}$/.test(t)||Mt("cow-bad-bytes32"),ja(t.replace(/^0x/,""))},o2=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:Mt("cow-bad-bool"),t},i2=e=>J(_i(e)),s2=(e,t)=>{if(e==="address")return jy(t);if(e==="bytes32")return r2(t);if(e==="uint32")return Ka(t,32);if(e==="uint256")return Ka(t,256);if(e==="bool")return o2(t);if(e==="string")return i2(t);Mt("cow-bad-type")},Ky=e=>{let t=[];for(let[n]of ao){let r=e?e[n]:void 0;(r==null||r==="")&&t.push(n)}return t},a2=({chainId:e,settlement:t=kr})=>J(Wa(J(_i(e2)),J(_i(Fy)),J(_i(Dy)),Ka(e,256),jy(t))),c2=e=>{let t=[J(_i(t2))];for(let[n,r]of ao)t.push(s2(r,e?e[n]:void 0));return J(Wa(...t))},l2=({order:e,chainId:t,settlement:n=kr})=>J(Wa(Uint8Array.from([25,1]),a2({chainId:t,settlement:n}),c2(e))),Wy=e=>Uy(l2(e)),Vy=({digest:e,owner:t,validTo:n})=>{let r=ja(e);r.length!==32&&Mt("cow-bad-digest");let o=ja(t);o.length!==20&&Mt("cow-bad-owner");let i=Ka(n,32).slice(28);return Uy(Wa(r,o,i))},$y=({order:e,chainId:t,settlement:n=kr})=>({domain:{name:Fy,version:Dy,chainId:Number(t),verifyingContract:n},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],Order:ao.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)}});xe();var u2=()=>typeof fetch=="function"?fetch:null;function ht({apiBase:e,fetchImpl:t=null,timeoutMs:n=2e4}){let r=t||u2();return{async json(o,{signal:i=null,method:s="GET",headers:a=null,body:c=null}={}){if(!e)throw new f("server-unavailable",{why:"no-api-base"});if(typeof r!="function")throw new f("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 h=await r(e+o,p);if(!h||typeof h.ok!="boolean")throw new f("server-unavailable",{why:"bad-response"});if(!h.ok)throw new f("server-unavailable",{status:h.status});return await h.json()}catch(p){throw p instanceof f?p:new f("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 f("server-unavailable",{why:"no-api-base"});if(typeof r!="function")throw new f("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 h=await r(e+o,p);if(!h||typeof h.ok!="boolean")throw new f("server-unavailable",{why:"bad-response"});let w=null;try{w=await h.json()}catch{throw new f("server-unavailable",{why:"body"})}return{ok:h.ok,status:h.status,body:w}}catch(p){throw p instanceof f?p:new f("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"}}),d2=["presignaturePending","open","fulfilled","cancelled","expired"],zy=["fulfilled","cancelled","expired"],Xy="fulfilled";var Ce=(e,t={})=>({ok:!1,code:e,params:t}),dd=e=>{let t=ud[Number(e)];return t?t.orderbook:null},Va=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),f2=e=>/^(0x)?[0-9a-fA-F]{64}$/.test(String(e||""));function Yy(e={}){let t=Number(e.chainId);if(dd(t)===null)return{...Ce("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=Ky(o);if(Va(n)||i.push("owner"),f2(o.appData)||i.push("appData"),(!Va(o.sellToken)||!Va(o.buyToken)||!Va(o.receiver))&&i.push("token"),i.length)return Ce("cow-bad-order",{missing:[...new Set(i)]});try{let s=Wy({order:o,chainId:t,settlement:kr}),a=Vy({digest:s,owner:n,validTo:o.validTo}),c=$y({order:o,chainId:t,settlement:kr});return{ok:!0,chainId:t,owner:n,order:o,digest:s,uid:a,typedData:c}}catch(s){return Ce("cow-bad-order",{why:String(s&&s.message?s.message:s)})}}function p2({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 h2(e={}){let t=Yy(e);return t.ok?{ok:!0,provider:"cowswap",venue:"CoWSwap",shape:ze,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:Xy,final:[...zy],endpoint:"/api/v1/orders/{uid}"}}:t}async function m2({typedData:e,wallet:t,address:n=null}={}){if(!e||typeof e!="object")return Ce("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)?Ce("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)?Ce("cow-sign-failed",{why:"bad-signature-shape"}):{ok:!0,signature:i}}return Ce("cow-sign-failed",{why:"no-wallet"})}catch(r){return Ce("cow-sign-failed",{why:String(r&&r.code||r&&r.message||r)})}}async function w2({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 Ce("cow-unknown-network",{chainId:Number(r)});if(typeof t!="string"||!/^0x[0-9a-fA-F]{130}$/.test(t))return Ce("cow-bad-order",{field:"signature"});let l=ht({apiBase:c,fetchImpl:o,timeoutMs:i}),u=JSON.stringify(p2({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 Ce("cow-unreachable",{why:String(p&&p.params&&p.params.why||p&&p.code||p)})}return!d||typeof d.ok!="boolean"?Ce("cow-bad-response",{where:"submit"}):d.ok?typeof d.body!="string"||!/^0x[0-9a-fA-F]{112}$/.test(d.body)?Ce("cow-bad-response",{where:"submit",got:typeof d.body}):{ok:!0,uid:d.body}:Ce("cow-refused",{status:d.status,reason:d.body&&d.body.errorType?d.body.errorType:null})}async function Gy({uid:e,chainId:t,fetchImpl:n=null,timeoutMs:r=2e4}={}){let o=dd(t);if(o===null)return Ce("cow-unknown-network",{chainId:Number(t)});if(typeof e!="string"||!/^0x[0-9a-fA-F]{112}$/.test(e))return Ce("cow-bad-order",{field:"uid"});let i=ht({apiBase:o,fetchImpl:n,timeoutMs:r}),s;try{s=await i.tryJson("/api/v1/orders/"+e)}catch(c){return Ce("cow-unreachable",{why:String(c&&c.params&&c.params.why||c&&c.code||c)})}if(!s||typeof s.ok!="boolean")return Ce("cow-bad-response",{where:"status"});if(s.status===404)return Ce("cow-order-unknown",{uid:e});if(!s.ok)return Ce("cow-refused",{status:s.status});let a=s.body&&s.body.status;return typeof a!="string"||!d2.includes(a)?Ce("cow-bad-response",{where:"status",got:typeof a=="string"?a:null}):{ok:!0,status:a,order:s.body}}async function y2(e={},t={}){let{uid:n,chainId:r}=e;if(typeof n!="string"||!/^0x[0-9a-fA-F]{112}$/.test(n))return Ce("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 Gy({uid:n,chainId:r,fetchImpl:t.fetchImpl,timeoutMs:t.requestTimeoutMs});if(!u.ok)return u;if(l=u.status,zy.includes(l))return{ok:!0,done:!0,settled:l===Xy,status:l,uid:n};if(o()-c>=a)return Ce("cow-not-settled",{uid:n,status:l,waitedMs:o()-c});await i(s)}}function b2({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:h=null}={}){if(!e)return{ok:!1,blocked:!0,reason:"cow-no-order",checks:[]};let w=pt.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}},k=pt.dexLegVerdict(y,t),x={ok:!k.blocked,checked:k.kind!=="unchecked"&&k.kind!=="unquoted",blocks:k.blocked===!0,kind:k.kind,reason:k.reason},_=Se.allowanceVerdict({tokenIsNative:d,allowanceWei:l,amountWei:e.sellAmount,consent:u===!0,symbol:p,decimals:Number.isFinite(Number(h))?Number(h):18});return{...Se.signingGateVerdict([x,_]),price:w,coverage:k,allowance:_}}var qy=Object.freeze({id:"cowswap",kind:"cow",venue:"CoWSwap",shape:ze,settles:"native",networks:ud,settlement:kr,buyEthAddress:My,orderFields:ao,plan:h2,settled:y2,buildIntent:Yy,sign:m2,submit:w2,status:Gy,gate:b2});$e();var g2=["Kyber","DSLO","Protocol"].join(" "),x2="1",Qe="0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C",k2=["EIP712Domain(","string name,","string version,","uint256 chainId,","address verifyingContract)"],v2=k2.join(""),co=[["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"]],S2="Order("+co.map(e=>e[1]+" "+e[0]).join(",")+")";var E2=[["orderHash","bytes32"],["opExpireTime","uint32"]],M5="DSOrder("+E2.map(e=>e[1]+" "+e[0]).join(",")+")";var zn=e=>{throw new Error(e)},$a=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&&zn("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)&&zn("kyber-bad-hex"),n[r]=o}return n},A2=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},_2=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);zn("kyber-bad-number")},fd=(e,t)=>{let n=_2(e);n<0n&&zn("kyber-negative"),n>=1n<<BigInt(t)&&zn("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},Qy=e=>{let t=String(e??"").trim();/^(0x)?[0-9a-fA-F]{40}$/.test(t)||zn("kyber-bad-address");let n=new Uint8Array(32);return n.set(hd(t.replace(/^0x/,"")),12),n},N2=e=>{let t=String(e??"").trim();return/^(0x)?[0-9a-fA-F]{64}$/.test(t)||zn("kyber-bad-bytes32"),hd(t.replace(/^0x/,""))},I2=e=>J(hd(e)),T2=(e,t)=>{if(e==="address")return Qy(t);if(e==="bytes32")return N2(t);if(e==="uint32")return fd(t,32);if(e==="uint256")return fd(t,256);if(e==="bytes")return I2(t);zn("kyber-bad-type")},Zy=e=>{let t=[];for(let[n,r]of co){let o=e?e[n]:void 0;(o==null||r!=="bytes"&&o==="")&&t.push(n)}return t},B2=({chainId:e,contract:t=Qe})=>J(pd(J($a(v2)),J($a(g2)),J($a(x2)),fd(e,256),Qy(t))),P2=e=>{let t=[J($a(S2))];for(let[n,r]of co)t.push(T2(r,e?e[n]:void 0));return J(pd(...t))},O2=({order:e,chainId:t,contract:n=Qe})=>J(pd(Uint8Array.from([25,1]),B2({chainId:t,contract:n}),P2(e))),Jy=e=>A2(O2(e));var gt="https://limit-order.kyberswap.com",t0=["KyberSwap","Limit","Order"].join(" "),za=Object.freeze({1:{orderbook:gt,contract:Qe},10:{orderbook:gt,contract:Qe},56:{orderbook:gt,contract:Qe},137:{orderbook:gt,contract:Qe},250:{orderbook:gt,contract:Qe},324:{orderbook:gt,contract:Qe},5e3:{orderbook:gt,contract:Qe},8453:{orderbook:gt,contract:Qe},42161:{orderbook:gt,contract:Qe},43114:{orderbook:gt,contract:Qe},59144:{orderbook:gt,contract:Qe},534352:{orderbook:gt,contract:Qe},81457:{orderbook:gt,contract:Qe}}),C2="/write/api/v1/orders/sign-message",R2="/write/api/v1/orders",n0="/read-ks/api/v1/orders";var H2=["active","open","partially_filled","cancelling","closed","filled","cancelled","expired"],r0=["filled","cancelled","expired"],o0="filled";var L2=["active","closed"];var le=(e,t={})=>({ok:!1,code:e,params:t}),Ii=e=>{let t=za[Number(e)];return t?t.orderbook:null},i0=e=>{let t=za[Number(e)];return t?t.contract:null},Ni=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),e0=e=>{try{return BigInt(String(e))>0n}catch{return!1}};function F2(e={}){let t=Number(e.chainId);if(Ii(t)===null)return{...le("kyber-unknown-network",{chainId:Number.isFinite(t)?t:null}),known:Object.keys(za).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 Ni(n)||i.push("maker"),Ni(o.makerAsset)||i.push("makerAsset"),Ni(o.takerAsset)||i.push("takerAsset"),Ni(o.receiver)||i.push("receiver"),e0(o.makingAmount)||i.push("makingAmount"),e0(o.takingAmount)||i.push("takingAmount"),Number.isInteger(Number(o.expiredAt))||i.push("expiredAt"),i.length?le("kyber-bad-order",{missing:[...new Set(i)]}):{ok:!0,chainId:t,orderbook:Ii(t),contract:i0(t),maker:n,params:o,expectedOutWei:String(o.takingAmount)}}function D2(e={}){let t=F2(e);return t.ok?{ok:!0,provider:"kyberswap",venue:t0,shape:ze,route:"kyberswap",expectedOutWei:t.expectedOutWei,params:t.params,owner:t.maker,endsWith:{kind:"order-status",settledWhen:o0,final:[...r0],endpoint:n0}}:t}async function M2({params:e,chainId:t=null,fetchImpl:n=null,timeoutMs:r=2e4,clientId:o=null}={}){let i=Number(t!==null?t:e&&e.chainId),s=Ii(i);if(s===null)return le("kyber-unknown-network",{chainId:Number.isFinite(i)?i:null});if(!e||typeof e!="object")return le("kyber-bad-order",{field:"params"});let a=ht({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(C2,{method:"POST",headers:c,body:JSON.stringify(e)})}catch(b){return le("kyber-unreachable",{why:String(b&&b.params&&b.params.why||b&&b.code||b)})}if(!l||typeof l.ok!="boolean")return le("kyber-bad-response",{where:"sign-message"});if(!l.ok)return le("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 le("kyber-bad-response",{where:"sign-message"});let d=u.domain||{},p=u.message||{},h=u.types&&Array.isArray(u.types.Order)?u.types.Order.map(b=>(b?b.name:"")+":"+(b?b.type:"")).join(","):null,w=co.map(([b,I])=>b+":"+I).join(","),y=i0(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 le("kyber-bad-response",{where:"sign-message",field:"domain"});if(h!==w)return le("kyber-bad-response",{where:"sign-message",field:"types"});let x=Zy(p);if(x.length)return le("kyber-bad-response",{where:"sign-message",missing:x});let _=["maker","makerAsset","takerAsset","receiver"];for(let b of _)if(String(p[b]||"").toLowerCase()!==String(e[b]||"").toLowerCase())return le("kyber-bad-response",{where:"sign-message",field:b});for(let b of["makingAmount","takingAmount"])if(String(p[b])!==String(e[b]))return le("kyber-bad-response",{where:"sign-message",field:b});let v=e.allowedSenders===void 0||e.allowedSenders===null?null:(Array.isArray(e.allowedSenders)?e.allowedSenders:[e.allowedSenders]).map(b=>String(b||"").toLowerCase());if(v&&v.length&&!v.includes(String(p.allowedSender||"").toLowerCase()))return le("kyber-bad-response",{where:"sign-message",field:"allowedSender"});let H;try{H=Jy({order:p,chainId:i,contract:y})}catch(b){return le("kyber-bad-response",{where:"sign-message",why:String(b&&b.message?b.message:b)})}return{ok:!0,chainId:i,orderbook:s,contract:y,salt:String(p.salt),message:p,digest:H,typedData:{domain:d,types:u.types,primaryType:u.primaryType||"Order",message:p}}}async function U2({typedData:e,wallet:t,address:n=null}={}){if(!e||typeof e!="object")return le("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)?le("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)?le("kyber-sign-failed",{why:"bad-signature-shape"}):{ok:!0,signature:i}}return le("kyber-sign-failed",{why:"no-wallet"})}catch(r){return le("kyber-sign-failed",{why:String(r&&r.code||r&&r.message||r)})}}async function j2({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=Ii(a);if(c===null)return le("kyber-unknown-network",{chainId:Number.isFinite(a)?a:null});if(!e||typeof e!="object")return le("kyber-bad-order",{field:"params"});if(typeof n!="string"||!/^0x[0-9a-fA-F]{130}$/.test(n))return le("kyber-bad-order",{field:"signature"});if(t==null||t==="")return le("kyber-bad-order",{field:"salt"});let l=ht({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(R2,{method:"POST",headers:u,body:d})}catch(y){return le("kyber-unreachable",{why:String(y&&y.params&&y.params.why||y&&y.code||y)})}if(!p||typeof p.ok!="boolean")return le("kyber-bad-response",{where:"submit"});if(!p.ok)return le("kyber-refused",{status:p.status,stage:"submit",reason:p.body&&p.body.message?p.body.message:null});let h=p.body&&p.body.data,w=h&&h.id;return!Number.isInteger(Number(w))||Number(w)<=0?le("kyber-bad-response",{where:"submit",got:typeof w}):{ok:!0,id:Number(w)}}async function s0({id:e,chainId:t,maker:n,fetchImpl:r=null,timeoutMs:o=2e4}={}){let i=Number(t),s=Ii(i);if(s===null)return le("kyber-unknown-network",{chainId:Number.isFinite(i)?i:null});if(!Number.isInteger(Number(e))||Number(e)<=0)return le("kyber-bad-order",{field:"id"});if(!Ni(n))return le("kyber-bad-order",{field:"maker"});let a=ht({apiBase:s,fetchImpl:r,timeoutMs:o});for(let c of L2){let l=n0+"?chainId="+i+"&maker="+n+"&status="+c,u;try{u=await a.tryJson(l)}catch(h){return le("kyber-unreachable",{why:String(h&&h.params&&h.params.why||h&&h.code||h)})}if(!u||typeof u.ok!="boolean")return le("kyber-bad-response",{where:"orders"});if(!u.ok)return le("kyber-refused",{status:u.status,stage:"orders"});let d=u.body&&u.body.data&&u.body.data.orders;if(!Array.isArray(d))return le("kyber-bad-response",{where:"orders"});let p=d.find(h=>h&&Number(h.id)===Number(e))||null;if(p){let h=p.status;return typeof h!="string"||!H2.includes(h)?le("kyber-bad-response",{where:"status",got:typeof h=="string"?h:null}):{ok:!0,status:h,order:p,bucket:c}}}return le("kyber-order-unknown",{id:Number(e),maker:n})}async function K2(e={},t={}){let{id:n,chainId:r,maker:o}=e;if(!Number.isInteger(Number(n))||Number(n)<=0)return le("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 s0({id:n,chainId:r,maker:o,fetchImpl:t.fetchImpl,timeoutMs:t.requestTimeoutMs});if(!d.ok)return d;if(u=d.status,r0.includes(u))return{ok:!0,done:!0,settled:u===o0,status:u,id:Number(n)};if(i()-l>=c)return le("kyber-not-settled",{id:Number(n),status:u,waitedMs:i()-l});await s(a)}}function W2({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:h=null}={}){if(!e)return{ok:!1,blocked:!0,reason:"kyber-no-order",checks:[]};let w=pt.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}},k=pt.dexLegVerdict(y,t),x={ok:!k.blocked,checked:k.kind!=="unchecked"&&k.kind!=="unquoted",blocks:k.blocked===!0,kind:k.kind,reason:k.reason},_=Se.allowanceVerdict({tokenIsNative:d,allowanceWei:l,amountWei:e.makingAmount,consent:u===!0,symbol:p,decimals:Number.isFinite(Number(h))?Number(h):18});return{...Se.signingGateVerdict([x,_]),price:w,coverage:k,allowance:_}}var a0=Object.freeze({id:"kyberswap",kind:"kyber",venue:t0,shape:ze,settles:"wrapped",networks:za,settlement:Qe,orderFields:co,plan:D2,settled:K2,unsignedOrder:M2,sign:U2,submit:j2,status:s0,gate:W2});$e();var V2="Permit2",md="0x000000000022D473030F116dDEE9F6B43aC78BA3",wd="0x0000000000000000000000000000000000000000",$2=["EIP712Domain(","string name,","uint256 chainId,","address verifyingContract)"],X5=$2.join(""),yd=[["reactor","address"],["swapper","address"],["nonce","uint256"],["deadline","uint256"],["additionalValidationContract","address"],["additionalValidationData","bytes"]],bd=[["token","address"],["startAmount","uint256"],["endAmount","uint256"],["recipient","address"]],Ti=[["info","OrderInfo"],["cosigner","address"],["baseInputToken","address"],["baseInputStartAmount","uint256"],["baseInputEndAmount","uint256"],["baseOutputs","DutchOutput[]"]],c0=[["permitted","TokenPermissions"],["spender","address"],["nonce","uint256"],["deadline","uint256"],["witness","V2DutchOrder"]],l0=[["token","address"],["amount","uint256"]],Bi=(e,t)=>e+"("+t.map(n=>n[1]+" "+n[0]).join(",")+")",gd=Bi("OrderInfo",yd),xd=Bi("DutchOutput",bd),u0=Bi("V2DutchOrder",Ti),z2=Bi("TokenPermissions",l0),Y5=Bi("PermitWitnessTransferFrom",c0)+xd+gd+z2+u0,X2=u0+xd+gd;var lo=e=>{throw new Error(e)},kd=e=>new TextEncoder().encode(String(e)),Xa=(...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},d0=e=>{let t=String(e).replace(/^0x/,"");t.length%2&&lo("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)&&lo("uniswapx-bad-hex"),n[r]=o}return n},Y2=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},G2=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);lo("uniswapx-bad-number")},uo=(e,t)=>{let n=G2(e);n<0n&&lo("uniswapx-negative"),n>=1n<<BigInt(t)&&lo("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},vr=e=>{let t=String(e??"").trim();/^(0x)?[0-9a-fA-F]{40}$/.test(t)||lo("uniswapx-bad-address");let n=new Uint8Array(32);return n.set(d0(t.replace(/^0x/,"")),12),n},q2=e=>J(d0(e??"0x")),f0=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 Ti){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},Q2=e=>J(Xa(J(kd(gd)),vr(e.reactor),vr(e.swapper),uo(e.nonce,256),uo(e.deadline,256),vr(e.additionalValidationContract),q2(e.additionalValidationData))),Z2=e=>J(Xa(J(kd(xd)),vr(e.token),uo(e.startAmount,256),uo(e.endAmount,256),vr(e.recipient))),J2=e=>J(Xa(...(e||[]).map(Z2))),eE=e=>J(Xa(J(kd(X2)),Q2(e),vr(e.cosigner),vr(e.baseInputToken),uo(e.baseInputStartAmount,256),uo(e.baseInputEndAmount,256),J2(e.baseOutputs))),p0=e=>Y2(eE(e));var h0=({order:e,chainId:t,permit2:n=md})=>({domain:{name:V2,chainId:Number(t),verifyingContract:n},types:{EIP712Domain:[{name:"name",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],PermitWitnessTransferFrom:c0.map(([r,o])=>({name:r,type:o})),TokenPermissions:l0.map(([r,o])=>({name:r,type:o})),V2DutchOrder:Ti.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 tE="https://api.uniswap.org/v2",m0="/orders",w0="UniswapX",nE="0x4449Cd34d1eb1FEDCF02A1Be3834FfDe8E6A6180",rE="0x0000000000000000000000000000000000000000",Pi=Object.freeze({1:{orderbook:tE,reactor:"0x00000011F84B9aa48e5f8aA8B9897600006289Be"}}),y0=["open","expired","error","cancelled","filled","insufficient-funds"],b0=["expired","error","cancelled","filled","insufficient-funds"],g0="filled";var _e=(e,t={})=>({ok:!1,code:e,params:t});var oE=e=>{let t=Pi[Number(e)];return t?t.orderbook:null},fo=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),Ya=e=>{try{return BigInt(String(e))>0n}catch{return!1}},x0=e=>/^0x[0-9a-fA-F]{64}$/.test(String(e||""));function k0(e={}){let t=Number(e.chainId),n=Pi[t];if(!n)return{..._e("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?rE:e.additionalValidationContract,additionalValidationData:e.additionalValidationData===void 0||e.additionalValidationData===null?"0x":e.additionalValidationData,cosigner:e.cosigner===void 0||e.cosigner===null?nE: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=f0(i);if(fo(r)||s.push("swapper"),fo(i.reactor)||s.push("reactor"),fo(i.cosigner)||s.push("cosigner"),fo(i.baseInputToken)||s.push("sellToken"),(!Ya(i.baseInputStartAmount)||!Ya(i.baseInputEndAmount))&&s.push("sellAmountWei"),(!Ya(i.baseOutputs[0].startAmount)||!Ya(i.baseOutputs[0].endAmount))&&s.push("buyAmountWei"),(!fo(i.baseOutputs[0].token)||!fo(i.baseOutputs[0].recipient))&&s.push("buyToken"),Number.isInteger(Number(i.deadline))||s.push("deadline"),s.length)return _e("uniswapx-bad-order",{missing:[...new Set(s)]});try{let a=h0({order:i,chainId:t}),c=p0(i);return{ok:!0,chainId:t,owner:r,reactor:i.reactor,order:i,orderHash:c,typedData:a}}catch(a){return _e("uniswapx-bad-order",{why:String(a&&a.message?a.message:a)})}}function iE(e={}){let t=k0(e);if(!t.ok)return t;let n=t.order.baseOutputs[0];return{ok:!0,provider:"uniswapx",venue:w0,shape:ze,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:g0,final:[...b0],endpoint:m0}}}async function sE({typedData:e,wallet:t,address:n=null}={}){if(!e||typeof e!="object")return _e("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)?_e("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)?_e("uniswapx-sign-failed",{why:"bad-signature-shape"}):{ok:!0,signature:i}}return _e("uniswapx-sign-failed",{why:"no-wallet"})}catch(r){return _e("uniswapx-sign-failed",{why:String(r&&r.code||r&&r.message||r)})}}async function aE({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 _e("uniswapx-bad-order",{field:"signature"});if(!e||typeof e!="object")return _e("uniswapx-bad-order",{field:"quote"});let s=r==null||r===""?null:String(r);if(!s)return _e("uniswapx-no-submitter",{field:"submitter"});let a=ht({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 _e("uniswapx-unreachable",{why:String(p&&p.params&&p.params.why||p&&p.code||p)})}if(!l||typeof l.ok!="boolean")return _e("uniswapx-bad-response",{where:"submit"});if(!l.ok)return _e("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 _e("uniswapx-bad-response",{where:"submit",field:"orderId"});let d=u.orderStatus;return typeof d!="string"||!y0.includes(d)?_e("uniswapx-bad-response",{where:"submit",field:"orderStatus"}):{ok:!0,orderId:u.orderId,orderStatus:d,requestId:typeof u.requestId=="string"?u.requestId:null}}async function v0({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)?oE(i):null;if(!s)return _e("uniswapx-unknown-network",{chainId:Number.isFinite(i)?i:null});if(!x0(e))return _e("uniswapx-bad-order",{field:"orderHash"});let a=ht({apiBase:s,fetchImpl:n,timeoutMs:r}),c;try{c=await a.tryJson(m0+"?orderHash="+e)}catch(p){return _e("uniswapx-unreachable",{why:String(p&&p.params&&p.params.why||p&&p.code||p)})}if(!c||typeof c.ok!="boolean")return _e("uniswapx-bad-response",{where:"orders"});if(!c.ok)return _e("uniswapx-refused",{status:c.status,stage:"orders"});let l=c.body&&c.body.orders;if(!Array.isArray(l))return _e("uniswapx-bad-response",{where:"orders"});let u=l.find(p=>p&&String(p.orderHash||"").toLowerCase()===String(e).toLowerCase())||l[0]||null;if(!u)return _e("uniswapx-order-unknown",{orderHash:e});let d=u.orderStatus;return typeof d!="string"||!y0.includes(d)?_e("uniswapx-bad-response",{where:"orderStatus",got:typeof d=="string"?d:null}):{ok:!0,status:d,order:u}}async function cE(e={},t={}){let{orderHash:n,chainId:r=null}=e;if(!x0(n))return _e("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 v0({orderHash:n,chainId:r,fetchImpl:t.fetchImpl,timeoutMs:t.requestTimeoutMs,api:t.api});if(!u.ok)return u;if(l=u.status,b0.includes(l))return{ok:!0,done:!0,settled:l===g0,status:l,orderHash:n};if(o()-c>=a)return _e("uniswapx-not-settled",{orderHash:n,status:l,waitedMs:o()-c});await i(s)}}function lE({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:h=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,k=pt.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:k,wrapped:{symbol:c,decimals:a}},_=pt.dexLegVerdict(x,t),v={ok:!_.blocked,checked:_.kind!=="unchecked"&&_.kind!=="unquoted",blocks:_.blocked===!0,kind:_.kind,reason:_.reason},H=Se.allowanceVerdict({tokenIsNative:d,allowanceWei:l,amountWei:e.baseInputEndAmount,consent:u===!0,symbol:p,decimals:Number.isFinite(Number(h))?Number(h):18});return{...Se.signingGateVerdict([v,H]),price:k,coverage:_,allowance:H}}var S0=Object.freeze({id:"uniswapx",kind:"uniswapx",venue:w0,shape:ze,settles:"native",networks:Pi,settlement:Pi[1].reactor,permit2:md,nativeToken:wd,orderFields:Ti,plan:iE,settled:cE,buildIntent:k0,sign:sE,submit:aE,status:v0,gate:lE});$e();$e();var uE="Permit2",Ga="0x000000000022D473030F116dDEE9F6B43aC78BA3",vd="0x0000000000000000000000000000000000000000",dE="0x0000000000000000000000000000000000000002",fE="0x24856bc3",E0=Object.freeze({v3SwapExactIn:0,sweep:4,wrapEth:11,unwrapWeth:12}),pE=3,hE=["EIP712Domain(","string name,","uint256 chainId,","address verifyingContract)"],tI=hE.join(""),Sd=[["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"]],qa=[["info","RelayOrderInfo"],["input","Input"],["fee","FeeEscalator"],["universalRouterCalldata","bytes"]],A0=[["token","address"],["amount","uint256"]],_0=[["permitted","TokenPermissions[]"],["spender","address"],["nonce","uint256"],["deadline","uint256"],["witness","RelayOrder"]],ho=(e,t)=>e+"("+t.map(n=>n[1]+" "+n[0]).join(",")+")",_d=ho("RelayOrderInfo",Sd),Nd=ho("Input",Ed),Id=ho("FeeEscalator",Ad),N0=ho("RelayOrder",qa),mE=ho("TokenPermissions",A0),wE=N0+Id+Nd+_d,nI=ho("PermitBatchWitnessTransferFrom",_0)+Id+Nd+N0+_d+mE;var Yn=e=>{throw new Error(e)},Qa=e=>new TextEncoder().encode(String(e)),Xn=(...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},Oi=e=>{let t=String(e).replace(/^0x/,"");t.length%2&&Yn("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)&&Yn("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},I0=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);Yn("uniswaprelay-bad-number")},xt=(e,t)=>{let n=I0(e);return n<0n&&Yn("uniswaprelay-negative"),n>=1n<<BigInt(t)&&Yn("uniswaprelay-overflow"),Oi("0x"+n.toString(16).padStart(64,"0"))},Sr=e=>{let t=String(e??"").trim();/^(0x)?[0-9a-fA-F]{40}$/.test(t)||Yn("uniswaprelay-bad-address");let n=new Uint8Array(32);return n.set(Oi(t.replace(/^0x/,"")),12),n},yE=e=>xt(e?1:0,8);var T0=e=>{let t=[];for(let[n]of Sd){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},bE=e=>J(Xn(J(Qa(_d)),Sr(e.info.reactor),Sr(e.info.swapper),xt(e.info.nonce,256),xt(e.info.deadline,256))),gE=e=>J(Xn(J(Qa(Nd)),Sr(e.token),xt(e.amount,256),Sr(e.recipient))),xE=e=>J(Xn(J(Qa(Id)),Sr(e.token),xt(e.startAmount,256),xt(e.endAmount,256),xt(e.startTime,256),xt(e.endTime,256))),kE=e=>J(Xn(J(Qa(wE)),bE(e),gE(e.input),xE(e.fee),J(Oi(e.universalRouterCalldata)))),B0=e=>Td(kE(e));var P0=({order:e,chainId:t,permit2:n=Ga})=>({domain:{name:uE,chainId:Number(t),verifyingContract:n},types:{EIP712Domain:[{name:"name",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],PermitBatchWitnessTransferFrom:_0.map(([r,o])=>({name:r,type:o})),TokenPermissions:A0.map(([r,o])=>({name:r,type:o})),RelayOrder:qa.map(([r,o])=>({name:r,type:o})),RelayOrderInfo:Sd.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 Bd=e=>{let t=String(e).replace(/^0x/,"").toLowerCase();return t.length%64===0?t:t.padEnd(Math.ceil(t.length/64)*64,"0")},po=e=>I0(e).toString(16).padStart(64,"0");var vE=e=>{let t=e.map(s=>String(s).replace(/^0x/,"")),n=po(t.length),r=[],o=t.length*32;for(let s of t)r.push(po(o)),o+=32+Math.ceil(s.length/64)*32;let i=t.map(s=>po(s.length/2)+Bd(s)).join("");return"0x"+n+r.join("")+i},SE=(e,t)=>{(!Array.isArray(e)||e.length!==t.length+1)&&Yn("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)&&Yn("uniswaprelay-bad-fee"),n+=o.toString(16).padStart(pE*2,"0")}return n+=String(e[e.length-1]).replace(/^0x/,"").toLowerCase(),"0x"+n},EE=({recipient:e,amountInWei:t,amountOutMinimumWei:n,path:r,payerIsUser:o=!1})=>{let i=String(r).replace(/^0x/,""),s=Xn(Sr(e),xt(t,256),xt(n,256),xt(160,256),yE(o)),a=Xn(xt(i.length/2,256),Oi("0x"+Bd(i)));return Td(Xn(s,a))},AE=({recipient:e,amountMinimumWei:t})=>Td(Xn(Sr(e),xt(t,256))),O0=({tokenIn:e,weth:t,fee:n,amountInWei:r,amountOutMinimumWei:o,recipient:i})=>{let s=SE([e,t],[n]),a="0x"+E0.v3SwapExactIn.toString(16).padStart(2,"0")+E0.unwrapWeth.toString(16).padStart(2,"0"),c=EE({recipient:dE,amountInWei:r,amountOutMinimumWei:o,path:s,payerIsUser:!1}),l=AE({recipient:i,amountMinimumWei:o}),u=a.replace(/^0x/,""),d=po(Oi(a).length)+Bd(u),p=vE([c,l]).replace(/^0x/,""),h=64,w=64+d.length/2;return fE+po(h)+po(w)+d+p};var C0="0x0000000000A4e21E2597DCac987455c48b12edBF",R0="0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD",H0=["Uniswap","Relay"].join(" "),Cd=Object.freeze({1:{reactor:C0,universalRouter:R0,permit2:Ga}}),_E=["Relay(","bytes32,","address,","address,","uint256)"],L0=()=>_E.join(""),NE=L0(),Za=(()=>{let e="0x";for(let t of J(L0()))e+=t.toString(16).padStart(2,"0");return e})();var IE=["filled","expired"],Rd="filled";var He=(e,t={})=>({ok:!1,code:e,params:t});var Hd=e=>Cd[Number(e)]||null,mo=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),Pd=e=>{try{return BigInt(String(e))>0n}catch{return!1}},F0=e=>/^0x[0-9a-fA-F]{64}$/.test(String(e||"")),Od=e=>/^0x[0-9a-fA-F]{130}$/.test(String(e||""));function D0(e={}){let t=Number(e.chainId),n=Hd(t);if(!n)return{...He("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(mo(r)||a.push("swapper"),(!mo(o)||String(o).toLowerCase()===vd)&&a.push("recipient"),mo(e.sellToken)||a.push("sellToken"),mo(s)||a.push("wrappedToken"),mo(i)||a.push("universalRouter"),Number.isInteger(Number(e.fee))||a.push("fee"),Pd(e.sellAmountWei)||a.push("sellAmountWei"),Pd(e.buyAmountWei)||a.push("buyAmountWei"),mo(e.feeToken)||a.push("feeToken"),Pd(e.feeEndAmountWei)||a.push("feeEndAmountWei"),Number.isInteger(Number(e.deadline))||a.push("deadline"),a.length)return He("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=O0({tokenIn:e.sellToken,weth:s,fee:e.fee,amountInWei:e.sellAmountWei,amountOutMinimumWei:e.buyAmountWei,recipient:o})}catch(w){return He("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},h=T0(p);if(h.length)return He("uniswap-relay-bad-order",{missing:h});try{let w=P0({order:p,chainId:t}),y=B0(p);return{ok:!0,chainId:t,owner:r,reactor:p.info.reactor,order:p,orderHash:y,calldata:d,typedData:w}}catch(w){return He("uniswap-relay-bad-order",{why:String(w&&w.message?w.message:w)})}}function TE(e={}){let t=D0(e);return t.ok?{ok:!0,provider:"uniswaprelay",venue:H0,shape:ze,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:[...IE],event:NE}}:t}async function BE({typedData:e,wallet:t,address:n=null}={}){if(!e||typeof e!="object")return He("uniswap-relay-bad-order",{field:"typedData"});try{if(t&&typeof t.signTypedData=="function"){let o=await t.signTypedData(e);return Od(o)?{ok:!0,signature:o}:He("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 Od(i)?{ok:!0,signature:i}:He("uniswap-relay-sign-failed",{why:"bad-signature-shape"})}return He("uniswap-relay-sign-failed",{why:"no-wallet"})}catch(r){return He("uniswap-relay-sign-failed",{why:String(r&&r.code||r&&r.message||r)})}}function PE({order:e=null,signature:t=null,chainId:n=null}={}){let r=Number(n);return Hd(r)?!e||typeof e!="object"?He("uniswap-relay-bad-order",{field:"order"}):Od(t)?He("uniswap-relay-no-discovery",{reactorIsPermissionless:!0,documentedSubmissionEndpoint:null,reason:"undocumented"}):He("uniswap-relay-bad-order",{field:"signature"}):He("uniswap-relay-unknown-network",{chainId:Number.isFinite(r)?r:null})}var OE=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:Za})}:e&&typeof e.request=="function"?{ok:!0,logs:await e.request({method:"eth_getLogs",params:[{address:n,fromBlock:o,toBlock:i,topics:[Za,r]}]})}:He("uniswap-relay-unreachable",{why:"no-driver"})}catch(s){return He("uniswap-relay-unreachable",{why:String(s&&s.code||s&&s.message||s)})}};async function M0({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 He("uniswap-relay-unknown-network",{chainId:Number.isFinite(l)?l:null});if(!F0(e))return He("uniswap-relay-bad-order",{field:"orderHash"});let p=await OE({driver:o,getLogs:i,reactor:d,orderHash:e,fromBlock:s,toBlock:a});if(!p.ok)return p;let h=p.logs;if(!Array.isArray(h))return He("uniswap-relay-bad-response",{where:"logs",got:typeof h});let w=h.filter(y=>{if(!y||!Array.isArray(y.topics))return!1;let k=String(y.topics[0]||"").toLowerCase(),x=String(y.topics[1]||"").toLowerCase();return k===Za.toLowerCase()&&x===String(e).toLowerCase()});if(h.length>0&&w.length===0)return He("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 CE(e={},t={}){let{orderHash:n,chainId:r=null,reactor:o=null,deadline:i=null}=e;if(!F0(n))return He("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(h=>setTimeout(h,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 M0({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 He("uniswap-relay-not-settled",{orderHash:n,status:d,waitedMs:s()-u});await a(c)}}function RE({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:h=!1,symbol:w=null,decimals:y=null}={}){if(!e)return{ok:!1,blocked:!0,reason:"uniswap-relay-no-order",checks:[]};let k=t??(e.input?e.input.amount:null),x=n??null,_=pt.priceGateVerdict({amountInWei:k,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}),v={ok:!0,amountOutWei:x===null?null:String(x),price:_,wrapped:{symbol:u,decimals:l}},H=pt.dexLegVerdict(v,r??x),b={ok:!H.blocked,checked:H.kind!=="unchecked"&&H.kind!=="unquoted",blocks:H.blocked===!0,kind:H.kind,reason:H.reason},I=Se.allowanceVerdict({tokenIsNative:h,allowanceWei:d,amountWei:k,consent:p===!0,symbol:w,decimals:Number.isFinite(Number(y))?Number(y):18});return{...Se.signingGateVerdict([b,I]),price:_,coverage:H,allowance:I}}var U0=Object.freeze({id:"uniswaprelay",kind:"uniswaprelay",venue:H0,shape:ze,settles:"native",networks:Cd,settlement:C0,universalRouter:R0,permit2:Ga,nativeToken:vd,eventTopic:Za,orderFields:qa,plan:TE,settled:CE,buildIntent:D0,sign:BE,submit:PE,status:M0,gate:RE});var HE="evm",K0=e=>Number(e.chainId),LE=(e,t)=>{let n=K0(t),r=Number(e);return Number.isFinite(r)&&Number.isFinite(n)&&r===n},W0="0x70a08231",j0=e=>{try{return BigInt(e).toString(10)}catch{return null}},FE=e=>String(e).replace(/^0x/,"").toLowerCase().padStart(64,"0");async function DE({driver:e,address:t,tokens:n}){let r=[];for(let o of n){let i=null;try{if(o.address===null)i=j0(await e.request({method:"eth_getBalance",params:[t,"latest"]}));else{let s=W0+FE(t);i=j0(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 V0={declared:{id:"declared",kind:"declared",shape:Ai,async plan(){return{ok:!1,code:"not-implemented",stage:3}}},cowswap:qy,kyberswap:a0,uniswapx:S0,uniswaprelay:U0},wo=()=>Object.keys(V0).sort(),Ja=e=>V0[e]||null,ME=e=>{let t=Ja(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:wo()}},UE=e=>{let t=Ja(e);if(!t)return{ok:!1,reason:"provider-unknown",provider:typeof e=="string"?e:null,known:wo()};if(t.shape!==ze)return{ok:!1,reason:"provider-not-asynchronous",provider:t.id,shape:t.shape===void 0?null:t.shape};let n=sd(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}},jE=e=>{let t=Ja(e);if(!t)return{ok:!1,reason:"provider-unknown",provider:typeof e=="string"?e:null,known:wo()};let n=sd(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"}),$0=e=>e&&e.settles?e.settles:null,KE=e=>{let t=$0(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 WE=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"})}),z0=e=>WE[e]||null;var X0={evm:Fd},Y0=()=>Object.keys(X0).sort(),yo=e=>X0[e]||null,VE=e=>(ue.CHAINS||[]).find(t=>t&&t.id===e)||null,Dd=e=>{let t=VE(e);return t&&t.vm?t.vm:null},G0=e=>{let t=Dd(e);return t?z0(t):null};var $E=e=>{let t=typeof ue.chainByChainId=="function"?ue.chainByChainId(e):null;t||R("bad-input",{field:"chain.chainId",unknown:e,why:"no-network-with-this-chainId"});let n=ue.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("|")&&R("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:G0(e.id),chainId:e.chainId,nativeSymbol:e.native&&e.native.symbol?e.native.symbol:null,tokens:$E(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,deploymentBlock:Number.isSafeInteger(e.escrow.deploymentBlock)?e.escrow.deploymentBlock:null}:null}),Md=Object.freeze({swaps:"/swaps",swap:"/swaps/{id}",evmSwaps:"/evm-swaps",orderQuote:"/order-quote",orderSell:"/order-sell",revealedHalf:"/escrow/revealed-half",swept:"/swaps/{id}/swept"}),q0=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"}]}),XE=e=>typeof e=="string"&&e||e&&typeof e=="object"&&typeof e.url=="string"&&e.url,Ud=e=>Array.isArray(e)&&e.every(XE),YE=(e,t)=>{let n=e&&e.nodes,r=e&&e.addNodes,o={mainnet:[...q0.mainnet],stagenet:[...q0.stagenet]};if(n!=null)if(Ud(n))t in o||R("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||R("bad-input",{field:"nodes",unknown:i,known:Object.keys(o)}),Ud(n[i])||R("bad-input",{field:"nodes."+i}),o[i]=[...n[i]];else R("bad-input",{field:"nodes"});return r!=null&&(Ud(r)||R("bad-input",{field:"addNodes"}),t in o||R("bad-input",{field:"addNodes",network:t}),o[t]=[...o[t],...r]),o},GE=(e,t)=>e.replace(/\{([a-z]+)\}/g,(n,r)=>{let o=t?t[r]:void 0;return(o==null||o==="")&&R("bad-input",{field:"route.param",param:r}),encodeURIComponent(String(o))}),qE=e=>{let t=e&&e.routes||{};for(let n of Object.keys(t))n in Md||R("bad-input",{field:"routes",unknown:n,known:Object.keys(Md)}),(typeof t[n]!="string"||!t[n])&&R("bad-input",{field:"routes."+n});return{...Md,...t}},jd=e=>Number.isFinite(Number(e))&&Number(e)>0?Number(e):null,QE=e=>{let t=e&&e.watch||{},n=t.pollMs===void 0?jd(ue.API&&ue.API.pollMs)||5e3:Number(t.pollMs);(!Number.isFinite(n)||n<=0)&&R("bad-input",{field:"watch.pollMs"});let r=ue.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)&&R("bad-input",{field:"watch.timeoutMs"}),{pollMs:n,timeoutMs:i}},ZE=(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 Q0(e){let t=ue.CHAINS.map(zE),n=t.find(y=>y.id===e.settlement.chain)||null;n||R("bad-input",{field:"settlement.chain",known:t.map(y=>y.id)});let r=ue.CHAINS.find(y=>y.id===e.settlement.chain)||{},o=qE(e),i=QE(e),s=ZE(r,e),a=YE(e,e.xmrNetwork),c=e.settlement.vm||n.vm;c||R("bad-input",{field:"settlement.vm"}),c!==n.vm&&R("bad-input",{field:"settlement.vm",chain:n.id,vm:n.vm,got:c}),yo(c)||R("not-implemented",{surface:"settlement.vm",vm:c,implemented:Y0()});let u=wo(),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)||R("bad-input",{field:"routing.prefer",unknown:y,known:u});let p=["mainnet","stagenet","testnet","fakechain"],h=[...new Set([...Object.values(ue.XMR_NETWORKS||{}),...p])];h.includes(e.xmrNetwork)||R("bad-input",{field:"xmrNetwork",known:h});let w=ue.SIGNING_GUARDS||{};return{settlement:{chain:n,vm:c},chains:t,xmrNetworks:h,assetsBase:e.assetsBase,apiBase:e.apiBase,mode:e.mode,limits:{minAmount:null,maxAmount:null,stepAmount:null,xmrConfirmTarget:ue.MONERO.confirmTarget??null,watchPollMs:i.pollMs,watchTimeoutMs:i.timeoutMs,xmrConfirmations:ue.MONERO.confirmTarget??10,xmrBlockTimeSec:Math.round((ue.MONERO.blockTimeReal??12e4)/1e3),readyLeadWarnSec:w.readyLeadWarnSec??null,quotePollMs:ue.API.pollMs??5e3,httpTimeoutMs:ue.API.timeoutMs??2e4},routing:{providers:u,prefer:d},routes:{...o},endpoints:s,xmrNodes:a,nodesFor:y=>a&&a[y]?a[y]:[],route:(y,k)=>(y in o||R("bad-input",{field:"route",unknown:y,known:Object.keys(o)}),GE(o[y],k)),codes:{steps:La,checks:Fa,errors:so}}}function Z0({chain:e,knownFactoryCodes:t}={}){return t??ue.knownFactoryCodesFor(e)}function J0({chain:e,knownImplementationCodes:t}={}){if(t!=null)return t;let n=typeof e=="string"?e:e&&e.id,r=n?ue.chainById(n):null;return!r||String(r.id)!==String(n)?null:ue.knownImplementationCodesFor(e)}xe();var bo="0.57.2";$e();var JE={keccak256:J,secp256k1:Ve};var Kd=e=>ld(e);var Ci=e=>Ly({crypto:JE,quote:e});na();var Wd=10n**BigInt(12);function eb(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 tb(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"))}Pl();qt();function eA(e,t,n,r){Lr(e);let o=Ts({dkLen:32,asyncTick:10},r),{c:i,dkLen:s,asyncTick:a}=o;if(Fe(i,"c"),Fe(s,"dkLen"),Fe(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=ll(t,"password");try{let l=ll(n,"salt");try{let u=new Uint8Array(s),{iHash:d,oHash:p,outputLen:h}=Ys.create(e,c),w=new Uint8Array(h),y=tA(d,p,l,w);return{c:i,dkLen:s,asyncTick:a,DK:u,outputLen:h,eng:y}}finally{typeof n=="string"&&st(l)}}finally{typeof t=="string"&&st(c)}}function tA(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 h=0;h<d.length;h++)d[h]^=r[h]}},output:u=>(e.destroy(),t.destroy(),s.destroy(),a.destroy(),st(r),u)}}function nb(e,t,n,r){let{c:o,dkLen:i,DK:s,outputLen:a,eng:c}=eA(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)}Ps();qt();function rb(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 ob(e){if(typeof e!="string")throw new TypeError("invalid mnemonic type: "+typeof e);if(!rb(e))throw new TypeError("expected well-formed Unicode string");return e.normalize("NFKD")}function ib(e){let t=ob(e),n=t.split(" ");if(![12,15,18,21,24].includes(n.length))throw new Error("Invalid mnemonic");return{nfkd:t,words:n}}function nA(e){if(We(e),![16,20,24,28,32].includes(e.length))throw new RangeError("invalid entropy length")}var rA=e=>{let t=8-e.length/4;return Bs(e)[0]>>t<<t};function oA(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(!rb(t))throw new TypeError("wordlist: expected well-formed Unicode string")})}function iA(e,t){oA(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]!==rA(a))throw new Error("Invalid checksum");return Uint8Array.from(a)}function sA(e,t){let{words:n}=ib(e),r=iA(n,t);return nA(r),r}function sb(e,t){try{sA(e,t)}catch{return!1}return!0}var aA=e=>{if(typeof e!="string")throw new TypeError("invalid passphrase type: "+typeof e);return ob("mnemonic"+e)};function ab(e,t=""){return nb(Qo,ib(e).nfkd,aA(t),{c:2048,dkLen:64})}var cb=Object.freeze(`abandon
|
|
2
|
+
var Ag=Object.create;var za=Object.defineProperty;var Ng=Object.getOwnPropertyDescriptor;var _g=Object.getOwnPropertyNames;var Ig=Object.getPrototypeOf,Tg=Object.prototype.hasOwnProperty;var je=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Bg=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},Fe=(e,t)=>{for(var n in t)za(e,n,{get:t[n],enumerable:!0})},Cg=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of _g(t))!Tg.call(e,o)&&o!==n&&za(e,o,{get:()=>t[o],enumerable:!(r=Ng(t,o))||r.enumerable});return e};var Og=(e,t,n)=>(n=e!=null?Ag(Ig(e)):{},Cg(t||!e||!e.__esModule?za(n,"default",{value:e,enumerable:!0}):n,e));function rb(e,t=!1){return t?{h:Number(e&Ri),l:Number(e>>Du&Ri)}:{h:Number(e>>Du&Ri)|0,l:Number(e&Ri)|0}}function Pi(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}=rb(e[i],t);[r[i],o[i]]=[s,a]}return[r,o]}function Mu(e,t,n,r){let o=ob(n),i=ib(n);e.setUint32(t,r?i:o,r),e.setUint32(t+4,r?o:i,r)}function Ht(e,t,n,r){let o=(t>>>0)+(r>>>0);return{h:e+n+(o/2**32|0)|0,l:o|0}}var Ri,Du,ob,ib,rc,oc,Dn,Mn,_o,Io,Uu,ju,Wu,Ku,Vu,$u,Hi=je(()=>{Ri=BigInt(4294967295),Du=BigInt(32);ob=e=>e/2**32|0,ib=e=>e>>>0;rc=(e,t,n)=>e>>>n,oc=(e,t,n)=>e<<32-n|t>>>n,Dn=(e,t,n)=>e>>>n|t<<32-n,Mn=(e,t,n)=>e<<32-n|t>>>n,_o=(e,t,n)=>e<<64-n|t>>>n-32,Io=(e,t,n)=>e>>>n-32|t<<64-n;Uu=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),ju=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Wu=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Ku=(e,t,n,r,o)=>t+n+r+o+(e/2**32|0)|0,Vu=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),$u=(e,t,n,r,o,i)=>t+n+r+o+i+(e/2**32|0)|0});function Fi(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Ce(e,t=""){if(typeof e!="number")throw new TypeError(Li(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Li(t)+"expected integer >= 0, got "+e);return e}function Yu(e,t=""){if(typeof e!="boolean")throw new TypeError(Li(t)+"expected boolean, got type="+typeof e);return e}function We(e,t,n=""){if(Fi(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Ce(t,"length");let r=Fi(e),o=t!==void 0?` of length ${t}`:"",i=r?`length=${e.length}`:`type=${typeof e}`,s=Li(n)+"expected Uint8Array"+o+", got "+i;throw r?new RangeError(s):new TypeError(s)}function kr(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")}function Kt(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function Sr(e,t){We(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function ic(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Je(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function vr(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Nt(e,t){return e<<32-t|e>>>t}function lb(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function db(e){for(let t=0;t<e.length;t++)e[t]=lb(e[t]);return e}function Di(e){if(We(e),Gu)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=ub[e[n]];return t}function Xu(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Mi(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(Gu)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=Xu(e.charCodeAt(i)),a=Xu(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 fb(e){if(typeof e!="string")throw new TypeError("string expected");let t=new TextEncoder().encode(e);try{return new Uint8Array(t)}finally{Je(t)}}function ac(e,t=""){return typeof e=="string"?fb(e):We(e,void 0,t)}function cc(...e){let t=0;for(let r=0;r<e.length;r++){let o=e[r];We(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 Ui(e,t,n="opts"){return zu(e,"defaults"),t!==void 0&&zu(t,n),Object.assign(Object.create(null),e,t)}function To(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=Ui({},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 lc(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 Li,ab,zu,cb,sc,Gu,ub,Bo,Ft=je(()=>{Li=e=>e?`"${e}" `:"";ab=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},zu=(e,t)=>{ab(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`)};cb=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;sc=cb?e=>e:db,Gu=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ub=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 Qu(e,t,n){return e&t^~e&n}function Zu(e,t,n){return e&t^e&n^t&n}var Co,qu,Ju,ef=je(()=>{Hi();Ft();Co=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=vr(this.buffer)}update(t){Kt(this),We(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=vr(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){Kt(this),Sr(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)),Mu(r,o-8,this.length*8,i),this.process(r,0),this.roundClean();let a=t===n?r:vr(t),c=this.outputLen,l=c/4,d=this.get();if(c%4||l>d.length)throw new Error("invalid outputLen");for(let f=0;f<l;f++)a.setUint32(4*f,d[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()}},qu=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ju=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});var pb,sn,dc,uc,tf,mb,hb,an,cn,fc,pc,ji,Oo,Wi=je(()=>{ef();Hi();Ft();pb=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),dc=class extends Co{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 p=sn[f-15],h=sn[f-2],w=Nt(p,7)^Nt(p,18)^p>>>3,b=Nt(h,17)^Nt(h,19)^h>>>10;sn[f]=b+sn[f-7]+w+sn[f-16]|0}let{A:r,B:o,C:i,D:s,E:a,F:c,G:l,H:d}=this;for(let f=0;f<64;f++){let p=Nt(a,6)^Nt(a,11)^Nt(a,25),h=d+p+Qu(a,c,l)+pb[f]+sn[f]|0,b=(Nt(r,2)^Nt(r,13)^Nt(r,22))+Zu(r,o,i)|0;d=l,l=c,c=a,a=s+h|0,s=i,i=o,o=r,r=h+b|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,d=d+this.H|0,this.set(r,o,i,s,a,c,l,d)}roundClean(){Je(sn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Je(this.buffer)}},uc=class extends dc{constructor(){super(32,qu)}},tf=Pi(["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))),mb=tf[0],hb=tf[1],an=new Uint32Array(80),cn=new Uint32Array(80),fc=class extends Co{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:d,Fh:f,Fl:p,Gh:h,Gl:w,Hh:b,Hl:y}=this;return[t,n,r,o,i,s,a,c,l,d,f,p,h,w,b,y]}set(t,n,r,o,i,s,a,c,l,d,f,p,h,w,b,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=d|0,this.Fh=f|0,this.Fl=p|0,this.Gh=h|0,this.Gl=w|0,this.Hh=b|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 T=an[g-15]|0,A=cn[g-15]|0,B=Dn(T,A,1)^Dn(T,A,8)^rc(T,A,7),P=Mn(T,A,1)^Mn(T,A,8)^oc(T,A,7),O=an[g-2]|0,j=cn[g-2]|0,D=Dn(O,j,19)^_o(O,j,61)^rc(O,j,6),X=Mn(O,j,19)^Io(O,j,61)^oc(O,j,6),H=Wu(P,X,cn[g-7],cn[g-16]),m=Ku(H,B,D,an[g-7],an[g-16]);an[g]=m|0,cn[g]=H|0}let{Ah:r,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:d,Eh:f,El:p,Fh:h,Fl:w,Gh:b,Gl:y,Hh:v,Hl:I}=this;for(let g=0;g<80;g++){let T=Dn(f,p,14)^Dn(f,p,18)^_o(f,p,41),A=Mn(f,p,14)^Mn(f,p,18)^Io(f,p,41),B=f&h^~f&b,P=p&w^~p&y,O=Vu(I,A,P,hb[g],cn[g]),j=$u(O,v,T,B,mb[g],an[g]),D=O|0,X=Dn(r,o,28)^_o(r,o,34)^_o(r,o,39),H=Mn(r,o,28)^Io(r,o,34)^Io(r,o,39),m=r&i^r&a^i&a,k=o&s^o&c^s&c;v=b|0,I=y|0,b=h|0,y=w|0,h=f|0,w=p|0,{h:f,l:p}=Ht(l|0,d|0,j|0,D|0),l=a|0,d=c|0,a=i|0,c=s|0,i=r|0,s=o|0;let x=Uu(D,H,k);r=ju(x,j,X,m),o=x|0}({h:r,l:o}=Ht(this.Ah|0,this.Al|0,r|0,o|0)),{h:i,l:s}=Ht(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Ht(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=Ht(this.Dh|0,this.Dl|0,l|0,d|0),{h:f,l:p}=Ht(this.Eh|0,this.El|0,f|0,p|0),{h,l:w}=Ht(this.Fh|0,this.Fl|0,h|0,w|0),{h:b,l:y}=Ht(this.Gh|0,this.Gl|0,b|0,y|0),{h:v,l:I}=Ht(this.Hh|0,this.Hl|0,v|0,I|0),this.set(r,o,i,s,a,c,l,d,f,p,h,w,b,y,v,I)}roundClean(){Je(an,cn)}destroy(){this.destroyed=!0,Je(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},pc=class extends fc{constructor(){super(64,Ju)}},ji=To(()=>new uc,Bo(1)),Oo=To(()=>new pc,Bo(3))});function Vi(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 rf(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 tt(e,t=""){if(typeof e!="boolean")throw new TypeError(wb(t)+"expected boolean, got type="+typeof e);return e}function $i(e){if(typeof e=="bigint"){if(!dn(e))throw new RangeError("positive bigint expected, got "+e)}else mc(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 Po(e){let t=$i(e).toString(16);return t.length&1?"0"+t:t}function of(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?Ki:BigInt("0x"+e)}function Lt(e){return of(Di(e))}function Wn(e){return of(Di(Ho(We(e)).reverse()))}function zi(e,t){if(Ce(t),t===0)throw new Error("zero output length is invalid");e=$i(e);let n=t*2,r=e.toString(16);if(r.length>n)throw new RangeError("number is too large");return Mi(r.padStart(n,"0"))}function hc(e,t){return zi(e,t).reverse()}function Ho(e){return Uint8Array.from(ye(e))}function dn(e){return typeof e=="bigint"&&Ki<=e}function wc(e,t,n){return dn(e)&&dn(t)&&dn(n)&&t<=e&&e<n}function Ar(e,t,n,r){if(!wc(t,n,r))throw new RangeError("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Nr(e){if(e<Ki)throw new Error("expected non-negative bigint, got "+e);return e===Ki?0:e.toString(2).length}function sf(e,t,n){if(Ce(e,"hashLen"),Ce(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),d=0,f=()=>{c.fill(1),l.fill(0),d=0},p=(...y)=>n(l,mt(c,...y)),h=(y=o)=>{l=p(i,y),c=p(),y.length!==0&&(l=p(s,y),c=p())},w=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,v=[];for(;y<t;){c=p();let I=c.slice();v.push(I),y+=c.length}return mt(...v)};return(y,v)=>{f(),h(y);let I;for(;(I=v(w()))===void 0;)h();return f(),I}}function nt(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)}"`,d=e[s];if(!Object.hasOwn(e,s)&&(c?d!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(c&&d===void 0)return;let f=typeof d;if(f!==a||d===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 ye,mc,Ro,mt,Er,un,jn,Ki,nf,wb,Fo,_r=je(()=>{Ft();ye=(e,t,n)=>We(e,t,n),mc=Ce;Ro=Di,mt=(...e)=>cc(...e),Er=e=>Mi(e),un=Fi,jn=e=>lc(e),Ki=BigInt(0),nf=BigInt(1),wb=e=>e?`"${e}" `:"";Fo=e=>(Vt(e,"n"),(nf<<BigInt(e))-nf)});function Ne(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 pf(e,t,n){if(n<=ge)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 ge;if(t===ge)return e;let r=e%n;if(r<De&&(r+=n),t<xb){let a=ge;for(;t>De;)t&ge&&(a=a*r%n),r=r*r%n,t>>=ge;return a}let o=[];for(;t>De;)o.push(Number(t&bb)),t>>=yc;let i=new Array(16);i[0]=ge,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 Ae(e,t,n){if(n<=ge)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 af(e,t){if(e===De)throw new Error("invert: expected non-zero number");if(t<=ge)throw new Error("invert: expected modulus > 1, got "+t);let n=Ne(e,t),r=t,o=De,i=ge;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!==ge)throw new Error("invert: does not exist");return Ne(o,t)}function mf(e,t){if(t<=ge)throw new Error("invertCt: expected prime modulus > 1, got "+t);let n=Ne(e,t);if(n===De)throw new Error("invertCt: expected non-zero number");let r=pf(n,t-fn,t);if(Ne(n*r,t)!==ge)throw new Error("invertCt: does not exist");return r}function gc(e,t,n){let r=e;if(!r.eql(r.sqr(t),n))throw new Error("Cannot find square root")}function bc(e,t){if((e&ge)===De)throw new Error(t+": expected odd modulus, got "+e)}function hf(e,t){let n=e,r=(n.ORDER+ge)/yc,o=n.pow(t,r);return gc(n,o,t),o}function kb(e,t){let n=e,r=(n.ORDER-df)/uf,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 gc(n,c,t),c}function Sb(e){let t=Tr(e),n=wf(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+yb)/ff;return((a,c)=>{let l=a,d=l.pow(c,s),f=l.mul(d,r),p=l.mul(d,o),h=l.mul(d,i),w=l.eql(l.sqr(f),c),b=l.eql(l.sqr(p),c);d=l.cmov(d,f,w),f=l.cmov(h,p,b);let y=l.eql(l.sqr(f),c),v=l.cmov(d,f,y);return gc(l,v,c),v})}function wf(e){if(e<lf)throw new Error("sqrt is not defined for small field");bc(e,"tonelliShanks");let t=e-ge,n=0;for(;t%fn===De;)t/=fn,n++;let r=fn,o=Tr(e);for(;Lo(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return hf;let i=o.pow(r,t),s=(t+ge)/fn;return function(c,l){let d=c;if(d.is0(l))return l;if(Lo(d,l)!==1)throw new Error("Cannot find square root");let f=n,p=d.mul(d.ONE,i),h=d.pow(l,t),w=d.pow(l,s);for(;!d.eql(h,d.ONE);){if(d.is0(h))throw new Error("Cannot find square root: probably non-prime P");let b=1,y=d.sqr(h);for(;!d.eql(y,d.ONE);)if(b++,y=d.sqr(y),b===f)throw new Error("Cannot find square root");let v=ge<<BigInt(f-b-1),I=d.pow(p,v);f=b,p=d.sqr(I),h=d.mul(h,p),w=d.mul(w,I)}return w}}function vb(e){return bc(e,"Fp.sqrt"),e%yc===lf?hf:e%uf===df?kb:e%ff===gb?Sb(e):wf(e)}function Ir(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 Eb)Un(e[t],"field."+t);if(e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=ge)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function Yi(e,t,n=!1){Ir(e),Vi(t,"nums"),tt(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 Lo(e,t){Ir(e);let n=e;bc(n.ORDER,"FpLegendre");let r=(n.ORDER-ge)/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 Ab(e,t){if(t!==void 0&&mc(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=Nr(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 Tr(e,t={}){return Object.freeze(Xi.prototype),new Xi(e,t)}function gf(e){if(typeof e!="bigint")throw new Error("field order must be bigint");if(e<=ge)throw new Error("field order must be greater than 1");let t=Nr(e-ge);return Math.ceil(t/8)}function Gi(e){let t=gf(e);return t+Math.ceil(t/2)}function Qi(e,t,n=!1){ye(e);let r=e.length,o=gf(t),i=Math.max(Gi(t),16);if(r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let s=n?Wn(e):Lt(e),a=Ne(s,t-ge)+ge;return n?hc(a,o):zi(a,o)}var De,ge,fn,lf,yc,df,yb,uf,gb,bb,ff,xb,yf,Eb,cf,Xi,Br=je(()=>{_r();De=BigInt(0),ge=BigInt(1),fn=BigInt(2),lf=BigInt(3),yc=BigInt(4),df=BigInt(5),yb=BigInt(7),uf=BigInt(8),gb=BigInt(9),bb=BigInt(15),ff=BigInt(16),xb=BigInt("0x10000000000000000");yf=(e,t)=>(Ne(e,t)&ge)===ge,Eb=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];cf=new WeakMap,Xi=class{ORDER;BITS;BYTES;isLE;ZERO=De;ONE=ge;_lengths;_mod;constructor(t,n={}){if(t<=ge)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}=Ab(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 Ne(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&ge)===ge}neg(t){return Ne(-t,this.ORDER)}eql(t,n){return t===n}sqr(t){return Ne(t*t,this.ORDER)}add(t,n){return Ne(t+n,this.ORDER)}sub(t,n){return Ne(t-n,this.ORDER)}mul(t,n){return Ne(t*n,this.ORDER)}pow(t,n){return pf(t,n,this.ORDER)}div(t,n){return Ne(t*af(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 af(t,this.ORDER)}sqrt(t){let n=cf.get(this);return n||cf.set(this,n=vb(this.ORDER)),n(this,t)}toBytes(t){return this.isLE?hc(t,this.BYTES):zi(t,this.BYTES)}fromBytes(t,n=!1){ye(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?Wn(t):Lt(t);if(a&&(c=Ne(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return Yi(this,t,!0)}cmov(t,n,r){return tt(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"),Ir(t.Fp),Ir(t.Fn)}function Zi(e,t){pn(e),Sf(t,e);let n=Yi(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function Ib(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 Tb(e,t){let n=e*(4*t+128);if(n>xf)throw new Error("invalid window size: table would need ~"+Math.ceil(n/2**20)+" MiB, max "+xf/2**20+" MiB")}function vc(e,t){if(e!==void 0){Un(e,"randomBytes");try{let n=e(t);if(!un(n)||n.length!==t)return}catch{return}return e}}function Sf(e,t){Vi(e,"points"),e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function Bb(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):dn(r)&&r<n))throw new Error("invalid scalar at index "+o)})}function kc(e){return vf.get(e)||1}function Cb(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 Ob(e,t){let n=2**t,r=n/2,o=BigInt(n-1),i=[];for(;e>Sc;){let s=0;e&Do&&(s=Number(e&o),s>=r&&(s-=n),e-=BigInt(s)),i.push(s),e>>=Do}return i}function Rb(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+=Do),a.push(l)}if(e!==Sc)throw new Error("invalid wnaf");return a}function Pb(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 qi(e,t,n,r=!1){if(pn(e),Sf(t,e),tt(r,"allowOversized"),Bb(n,e.Fn,r?e.Fn.ORDER**Nb:void 0),t.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=t.map(s=>Cb(s,4)),i=n.map(s=>Ob(s,4));return Pb(e.ZERO,o,i)}function kf(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ir(t),t}else return Tr(e,{isLE:n})}function Ji(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`);nt(n);for(let c of["p","n","h"]){let l=t[c];if(!(dn(l)&&l!==Sc))throw new Error(`CURVE.${c} must be positive bigint`)}let o=kf(t.p,n.Fp,r),i=kf(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 es(e,t){return function(r){let o=e(r);return{secretKey:o,publicKey:t(o)}}}var Sc,Do,Nb,xc,bf,_b,xf,vf,Cr,Ec=je(()=>{_r();Br();Sc=BigInt(0),Do=BigInt(1),Nb=BigInt(4),xc=16,bf=128,_b=5,xf=2**31;vf=new WeakMap;Cr=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(t,n){pn(t),this.randomBytes=vc(n,xc),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 d=0;d<i;d++)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=Rb(n,r,o),c=this.ZERO,l=this.BASE;for(let d=0;d<o;d++){let f=a[d],p=d*s,h=Math.abs(f)-1,w=i[p];for(let y=1;y<s;y++)w=y===h?i[p+y]:w;let b=w.negate();f===0?l=l.add(i[p]):c=c.add(f<0?b: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),!wc(n,Do,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(t,n,r,o){let i=kc(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+bf,i=this.randomBytes(xc);if(!un(i)||i.length!==xc)throw new Error("randomBytes returned invalid byte array");i[0]=i[0]&63|128;let s=n+Lt(i)*this.Point.Fn.ORDER;return this.runCT(t,s,o,r)}fixedWindowCT(t,n,r){let o=_b,i=1<<o,s=Fo(o),a=new Array(i);a[0]=this.ZERO;for(let d=1;d<i;d++)a[d]=a[d-1].add(t);let c=Math.ceil(r/o),l=this.ZERO;for(let d=c-1;d>=0;d--){if(d!==c-1)for(let h=0;h<o;h++)l=l.double();let f=Number(n>>BigInt(d*o)&s),p=a[0];for(let h=1;h<i;h++)p=h===f?a[h]:p;l=l.add(p)}return{p:l,f:l}}shouldBlind(t,n){return this.randomBytes===void 0?!1:n===Do?!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),!dn(n))throw new Error("invalid scalar");let o=kc(t);if(o===1||n>=this.Point.Fn.ORDER)return qi(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),Ib(n,this.bits);let r=Math.ceil((this.bits+bf)/n)+1;Tb(r*2**(n-1),this.Point.Fp.BYTES),vf.set(t,n),this.wnafPrecomputes.delete(t)}hasWindowSize(t){return kc(t)!==1}}});function Fb(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 Af(e,t={}){nt(t,{},{},"extraOpts");let n=t,r=Ji("edwards",e,n,n.FpFnLE),{Fp:o,Fn:i}=r,s=r.CURVE,{h:a}=s;if(Lo(o,s.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Lo(o,s.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");nt(n,{},{uvRatio:"function",randomBytes:"function"});let c=n.randomBytes===void 0?jn:n.randomBytes,l=rs<<BigInt(o.BYTES*8)-ns;function d(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:ts}}}:n.uvRatio;if(!Fb(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 h(I,g,T=!1){let A=T?ns:ts;return Ar("coordinate "+I,g,A,l),g}function w(I){if(!(I instanceof b))throw new Error("EdwardsPoint expected")}class b{static BASE=new b(s.Gx,s.Gy,o.ONE,o.mul(s.Gx,s.Gy));static ZERO=new b(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=i;X;Y;Z;T;constructor(g,T,A,B){this.X=h("x",g),this.Y=h("y",T),this.Z=h("z",A,!0),this.T=h("t",B),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){if(g instanceof b)throw new Error("extended point not allowed");let{x:T,y:A}=g||{};return h("x",T),h("y",A),new b(T,A,o.ONE,o.mul(T,A))}static fromBytes(g,T=!1){let A=o.BYTES,{a:B,d:P}=s;g=Ho(ye(g,A,"point")),tt(T,"zip215");let O=Ho(g),j=g[A-1];O[A-1]=j&-129;let D=Wn(O),X=T?l:o.ORDER;Ar("point.y",D,ts,X);let H=o.sqr(D),m=o.sub(H,o.ONE),k=o.sub(o.mulN(P,H),B),{isValid:x,value:C}=f(m,k);if(!x)throw new Error("bad point: invalid y coordinate");let U=d(C),W=(j&128)!==0;if(!T&&o.is0(C)&&W)throw new Error("bad point: x=0 and x_0=1");return W!==U&&(C=o.neg(C)),b.fromAffine({x:C,y:D})}static fromHex(g,T=!1){return b.fromBytes(Er(g),T)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=6,T=!0){return v.setWindowSize(this,g),T||this.multiply(rs),this}assertValidity(){let g=this,{a:T,d:A}=s;if(g.is0())throw new Error("bad point: ZERO");let{X:B,Y:P,Z:O,T:j}=g,D=o.sqr(B),X=o.sqr(P),H=o.sqr(O),m=o.sqr(H),k=o.mul(D,T),x=o.mul(o.add(k,X),H),C=o.add(m,o.mul(A,o.mul(D,X)));if(!o.eql(x,C))throw new Error("bad point: equation left != right (1)");let U=o.mul(B,P),W=o.mul(O,j);if(!o.eql(U,W))throw new Error("bad point: equation left != right (2)")}equals(g){w(g);let{X:T,Y:A,Z:B}=this,{X:P,Y:O,Z:j}=g,D=o.mul(T,j),X=o.mul(P,B),H=o.mul(A,j),m=o.mul(O,B);return o.eql(D,X)&&o.eql(H,m)}is0(){return this.equals(b.ZERO)}negate(){return new b(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:g,Y:T,Z:A}=this,B=o.sqr(g),P=o.sqr(T),O=o.mul(o.sqr(A),rs),j=p(B),D=o.addN(g,T),X=o.sub(o.subN(o.sqr(D),B),P),H=o.addN(j,P),m=o.subN(H,O),k=o.subN(j,P),x=o.mul(X,m),C=o.mul(H,k),U=o.mul(X,k),W=o.mul(m,H);return new b(x,C,W,U)}add(g){w(g);let{d:T}=s,{X:A,Y:B,Z:P,T:O}=this,{X:j,Y:D,Z:X,T:H}=g,m=o.mul(A,j),k=o.mul(B,D),x=o.mul(o.mulN(O,T),H),C=o.mul(P,X),U=o.sub(o.subN(o.mulN(o.addN(A,B),o.addN(j,D)),m),k),W=o.subN(C,x),Y=o.addN(C,x),N=o.sub(k,p(m)),S=o.mul(U,W),_=o.mul(Y,N),R=o.mul(U,N),M=o.mul(W,Y);return new b(S,_,M,R)}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:T,f:A}=v.mulSecret(this,g,a,y);return y([T,A])[0]}multiplyUnsafe(g){if(!i.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===ts?b.ZERO:this.is0()||g===ns?this:v.mulUnsafe(this,g,y)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return v.mulUnsafe(this,s.n).is0()}toAffine(g){let T=this,A=g;if(A!=null&&typeof A!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof A);let{X:B,Y:P,Z:O}=T,j=T.is0();A==null&&(A=j?o.create(Ef):o.inv(O));let D=o.mul(B,A),X=o.mul(P,A),H=o.mul(O,A);if(j)return{x:o.ZERO,y:o.ONE};if(!o.eql(H,o.ONE))throw new Error("invZ was invalid");return{x:D,y:X}}clearCofactor(){return a===ns?this:a===rs?this.double():a===Hb?this.double().double():a===Ef?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:g,y:T}=this.toAffine(),A=o.toBytes(T);return A[A.length-1]|=d(g)?128:0,A}toHex(){return Ro(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let y=I=>Zi(b,I),v=new Cr(b,c);return v.bits>=6&&b.BASE.precompute(6),Object.freeze(b.prototype),Object.freeze(b),b}function Nf(e,t,n={}){if(pn(e),typeof t!="function")throw new Error('"hash" function param is required');let r=t,o=n;nt(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,d=2*a.BYTES;if(l!==void 0&&(Vt(l,"hash.outputLen"),l!==d))throw new Error(`hash.outputLen must be ${d}, got ${l}`);let f=o.randomBytes===void 0?jn:o.randomBytes,p=o.toMontgomery,h=o.toMontgomerySecret,w=o.adjustScalarBytes===void 0?k=>k:o.adjustScalarBytes,b=o.domain===void 0?(k,x,C)=>{if(tt(C,"phflag"),x.length||C)throw new Error("Contexts/pre-hash are not supported");return k}:o.domain;function y(k){return c.create(Wn(k))}function v(k){let x=j.secretKey;ye(k,j.secretKey,"secretKey");let C=ye(r(k),2*x,"hashedSecretKey"),U=w(C.slice(0,x)),W=C.slice(x,2*x),Y=y(U);return{head:U,prefix:W,scalar:Y}}function I(k){let{head:x,prefix:C,scalar:U}=v(k),W=s.multiply(U),Y=W.toBytes();return{head:x,prefix:C,scalar:U,point:W,pointBytes:Y}}function g(k){return I(k).pointBytes}function T(k=Uint8Array.of(),...x){let C=mt(...x);return y(r(b(C,ye(k,void 0,"context"),!!i)))}function A(k,x,C={}){nt(C,{},{},"options"),k=Ho(ye(k,void 0,"message")),i&&(k=i(k));let{prefix:U,scalar:W,pointBytes:Y}=I(x),N=T(C.context,U,k),S=s.multiply(N).toBytes(),_=T(C.context,S,Y,k),R=c.create(N+_*W);if(!c.isValid(R))throw new Error("sign failed: invalid s");let M=mt(S,c.toBytes(R));return ye(M,j.signature,"result")}let B={zip215:o.zip215};function P(k,x,C,U=B){nt(U);let{context:W}=U,Y=U.zip215===void 0?!!B.zip215:U.zip215,N=j.signature;k=ye(k,N,"signature"),x=ye(x,void 0,"message"),C=ye(C,j.publicKey,"publicKey"),Y!==void 0&&tt(Y,"zip215"),i&&(x=i(x));let S=N/2,_=k.subarray(0,S),R=Wn(k.subarray(S,N)),M,K,G;try{M=e.fromBytes(C,Y),K=e.fromBytes(_,Y),G=s.multiplyUnsafe(R)}catch{return!1}if(!Y&&M.isSmallOrder())return!1;let Z=T(W,_,C,x);return K.add(M.multiplyUnsafe(Z)).subtract(G).clearCofactor().is0()}let O=a.BYTES,j={secretKey:O,publicKey:O,signature:2*O,seed:O};function D(k){return k=k===void 0?f(j.seed):k,ye(k,j.seed,"seed")}function X(k){return un(k)&&k.length===j.secretKey}function H(k,x){try{return!!e.fromBytes(k,x===void 0?B.zip215:x)}catch{return!1}}let m={getExtendedPublicKey:I,randomSecretKey:D,isValidSecretKey:X,isValidPublicKey:H,toMontgomery(k){if(p===void 0)throw new Error("Montgomery conversion is not supported for this curve");return p(e.fromBytes(k))},toMontgomerySecret(k){if(h===void 0)throw new Error("Montgomery conversion is not supported for this curve");return h(k)}};return Object.freeze(j),Object.freeze(m),Object.freeze({keygen:es(D,g),getPublicKey:g,sign:A,verify:P,utils:m,Point:e,lengths:j})}var ts,ns,rs,Hb,Ef,_f=je(()=>{_r();Ec();Br();ts=BigInt(0),ns=BigInt(1),rs=BigInt(2),Hb=BigInt(4),Ef=BigInt(8)});function Ub(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=Nc,a=e*e%i*e%i,c=Ae(a,If,i)*a%i,l=Ae(c,Ac,i)*e%i,d=Ae(l,Lb,i)*l%i,f=Ae(d,t,i)*d%i,p=Ae(f,n,i)*f%i,h=Ae(p,r,i)*p%i,w=Ae(h,o,i)*h%i,b=Ae(w,o,i)*h%i,y=Ae(b,t,i)*d%i;return{pow_p_5_8:Ae(y,If,i)*e%i,b2:a}}function Cf(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function jb(e,t){let n=Nc,r=Ne(t*t*t,n),o=Ne(r*r*t,n),i=Ub(e*o).pow_p_5_8,s=Ne(e*r*i,n),a=Ne(t*s*s,n),c=s,l=Ne(s*Tf,n),d=a===e,f=a===Ne(-e,n),p=a===Ne(-e*Tf,n);return d&&(s=c),(f||p)&&(s=l),yf(s,n)&&(s=Ne(-s,n)),{isValid:d||f,value:s}}function Wb(e){let{y:t}=e;return Bf.toBytes(Bf.div(Ac+t,Ac-t))}function Kb(e){let t=_c.Fp.BYTES;return We(e,t),Cf(Oo(e.subarray(0,t))).subarray(0,t)}function Vb(e){return Nf(_c,Oo,Object.assign({adjustScalarBytes:Cf,toMontgomery:Wb,toMontgomerySecret:Kb,zip215:!0},e))}var Ac,If,Lb,Db,Nc,Mb,Tf,_c,Bf,Te,Ic=je(()=>{Wi();Ft();_f();Br();Ac=BigInt(1),If=BigInt(2),Lb=BigInt(5),Db=BigInt(8),Nc=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Mb={p:Nc,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Db,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};Tf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");_c=Af(Mb,{uvRatio:jb}),Bf=_c.Fp;Te=Vb({})});var os,is,Tc=je(()=>{Ft();os=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(t,n){if(kr(t),We(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),Je(o)}update(t){return Kt(this),this.iHash.update(t),this}digestInto(t){Kt(this),Sr(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()}},is=(()=>{let e=((t,n,r)=>new os(t,n).update(r).digest());return e.create=(t,n)=>new os(t,n),e})()});var $b,Bc,$t,ss,Of=je(()=>{_r();$b=BigInt(0),Bc=class extends Error{constructor(t=""){super(t)}},$t={Err:Bc,_tlv:{encode:(e,t)=>{let{Err:n}=$t;if(Vt(e,"tag"),e<0||e>255)throw new n("tlv.encode: wrong tag");if(rf(t,"data"),t.length&1)throw new n("tlv.encode: unpadded data");let r=t.length/2,o=Po(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");let i=r>127?Po(o.length/2|128):"";return Po(e)+i+o+t},decode(e,t){let{Err:n}=$t;t=ye(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 d of l)s=s<<8|d;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($i(e),e<$b)throw new t("integer: negative integers are not allowed");let n=Po(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 Lt(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=ye(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:d,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||d.length>t))throw new n("invalid signature: integer too large");return{r:r.decode(c),s:r.decode(d)}},hexFromSig(e){let{_tlv:t,_int:n}=$t;nt(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)}},ss=(Object.freeze($t._tlv),Object.freeze($t._int),Object.freeze($t))});function zb(e,t,n){Ar("scalar",e,zt,n);let[[r,o],[i,s]]=t,a=Rf(s*e,n),c=Rf(-o*e,n),l=e-a*r-c*i,d=-a*o-c*s,f=l<zt,p=d<zt;f&&(l=-l),p&&(d=-d);let h=Fo(Math.ceil(Nr(n)/2))+Kn;if(l<zt||l>=h||d<zt||d>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:l,k2neg:p,k2:d}}function Rc(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function Cc(e,t){nt(e);let n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return tt(n.lowS,"lowS"),tt(n.prehash,"prehash"),n.format!==void 0&&Rc(n.format),n}function Hf(e,t={}){let n=Ji("weierstrass",e,t),r=n.Fp,o=n.Fn,i=n.CURVE,{h:s,n:a}=i;nt(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:l,clearCofactor:d,isTorsionFree:f,fromBytes:p,toBytes:h}=t,w=t.randomBytes===void 0?jn: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 b=c?{beta:c.beta,basises:c.basises.map(N=>[...N])}:void 0,y=Lf(r,o);function v(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function I(N,S,_){if(S.is0()){if(!l)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:R,y:M}=S.toAffine(),K=r.toBytes(R);if(tt(_,"isCompressed"),_){v();let G=!r.isOdd(M);return mt(Ff(G),K)}else return mt(Uint8Array.of(4),K,r.toBytes(M))}function g(N){ye(N,void 0,"Point");let{publicKey:S,publicKeyUncompressed:_}=y,R=N.length,M=N[0],K=N.subarray(1);if(l&&R===1&&M===0)return{x:r.ZERO,y:r.ZERO};if(R===S&&(M===2||M===3)){let G=r.fromBytes(K);if(!r.isValid(G))throw new Error("bad point: is not on curve, wrong x");let Z=O(G),V;try{V=r.sqrt(Z)}catch(E){let F=E instanceof Error?": "+E.message:"";throw new Error("bad point: is not on curve, sqrt error"+F)}v();let J=r.isOdd(V);return(M&1)===1!==J&&(V=r.neg(V)),{x:G,y:V}}else if(R===_&&M===4){let G=r.BYTES,Z=r.fromBytes(K.subarray(0,G)),V=r.fromBytes(K.subarray(G,G*2));if(!j(Z,V))throw new Error("bad point: is not on curve");return{x:Z,y:V}}else throw new Error(`bad point: got length ${R}, expected compressed=${S} or uncompressed=${_}`)}let T=h===void 0?I:h,A=p===void 0?g:p,B=r.mul(i.b,Oc),P=r.is0(i.a)?N=>r.ZERO:N=>r.mul(i.a,N);function O(N){let S=r.sqr(N),_=r.mul(S,N);return r.add(r.add(_,r.mul(N,i.a)),i.b)}function j(N,S){let _=r.sqr(S),R=O(N);return r.eql(_,R)}if(!j(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let D=r.mul(r.pow(i.a,Oc),Xb),X=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(D,X)))throw new Error("bad curve params: a or b");function H(N,S,_=!1){if(!r.isValid(S)||_&&r.is0(S))throw new Error(`bad point coordinate ${N}`);return typeof S=="object"&&S!==null?r.create(S):S}function m(N){if(!(N instanceof U))throw new Error("Weierstrass Point expected")}function k(N){if(!b||!b.basises)throw new Error("no endo");return zb(N,b.basises,o.ORDER)}function x(N,S,_,R){if(!o.isValid(R))throw new RangeError("invalid scalar: out of range");if(b){let{k1neg:M,k1:K,k2neg:G,k2:Z}=k(R),V=new U(r.mul(_.X,b.beta),_.Y,_.Z);N.push(M?_.negate():_,G?V.negate():V),S.push(K,Z)}else N.push(_),S.push(R)}let C=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(S,_,R){this.X=H("x",S),this.Y=H("y",_,!0),this.Z=H("z",R),Object.freeze(this)}static CURVE(){return i}static fromAffine(S){let{x:_,y:R}=S||{};if(!S||!r.isValid(_)||!r.isValid(R))throw new Error("invalid affine point");if(S instanceof U)throw new Error("projective point not allowed");return r.is0(_)&&r.is0(R)?U.ZERO:new U(_,R,r.ONE)}static fromBytes(S){let _=U.fromAffine(A(ye(S,void 0,"point")));return _.assertValidity(),_}static fromHex(S){return U.fromBytes(Er(S))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(S=6,_=!0){return Y.setWindowSize(this,S),_||this.multiply(Oc),this}assertValidity(){let S=this;if(S.is0()){if(l&&r.is0(S.X)&&r.eql(S.Y,r.ONE)&&r.is0(S.Z))return;throw new Error("bad point: ZERO")}if(C.has(S))return;let{x:_,y:R}=S.toAffine();if(!r.isValid(_)||!r.isValid(R))throw new Error("bad point: x or y not field elements");if(!j(_,R))throw new Error("bad point: equation left != right");if(!S.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");C.add(S)}hasEvenY(){let{y:S}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(S)}equals(S){m(S);let{X:_,Y:R,Z:M}=this,{X:K,Y:G,Z}=S,V=r.eql(r.mul(_,Z),r.mul(K,M)),J=r.eql(r.mul(R,Z),r.mul(G,M));return V&&J}negate(){return new U(this.X,r.neg(this.Y),this.Z)}double(){let{X:S,Y:_,Z:R}=this,M=r.ZERO,K=r.ZERO,G=r.ZERO,Z=r.mul(S,S),V=r.mul(_,_),J=r.mul(R,R),re=r.mul(S,_);return re=r.add(re,re),G=r.mul(S,R),G=r.add(G,G),M=P(G),K=r.mul(B,J),K=r.add(M,K),M=r.sub(V,K),K=r.add(V,K),K=r.mul(M,K),M=r.mul(re,M),G=r.mul(B,G),J=P(J),re=r.sub(Z,J),re=P(re),re=r.add(re,G),G=r.add(Z,Z),Z=r.add(G,Z),Z=r.add(Z,J),Z=r.mul(Z,re),K=r.add(K,Z),J=r.mul(_,R),J=r.add(J,J),Z=r.mul(J,re),M=r.sub(M,Z),G=r.mul(J,V),G=r.add(G,G),G=r.add(G,G),new U(M,K,G)}add(S){m(S);let{X:_,Y:R,Z:M}=this,{X:K,Y:G,Z}=S,V=r.ZERO,J=r.ZERO,re=r.ZERO,E=r.mul(_,K),F=r.mul(R,G),L=r.mul(M,Z),z=r.add(_,R),$=r.add(K,G);z=r.mul(z,$),$=r.add(E,F),z=r.sub(z,$),$=r.add(_,M);let ee=r.add(K,Z);return $=r.mul($,ee),ee=r.add(E,L),$=r.sub($,ee),ee=r.add(R,M),V=r.add(G,Z),ee=r.mul(ee,V),V=r.add(F,L),ee=r.sub(ee,V),re=P($),V=r.mul(B,L),re=r.add(V,re),V=r.sub(F,re),re=r.add(F,re),J=r.mul(V,re),F=r.add(E,E),F=r.add(F,E),L=P(L),$=r.mul(B,$),F=r.add(F,L),L=r.sub(E,L),L=P(L),$=r.add($,L),E=r.mul(F,$),J=r.add(J,E),E=r.mul(ee,$),V=r.mul(z,V),V=r.sub(V,E),E=r.mul(z,F),re=r.mul(ee,re),re=r.add(re,E),new U(V,J,re)}subtract(S){return m(S),this.add(S.negate())}is0(){return this.equals(U.ZERO)}multiply(S){if(!o.isValidNot0(S))throw new RangeError("invalid scalar: out of range");let{p:_,f:R}=Y.mulSecret(this,S,s,W);return W([_,R])[0]}multiplyUnsafe(S){let _=this,R=S;if(!o.isValid(R))throw new RangeError("invalid scalar: out of range");if(R===zt||_.is0())return U.ZERO;if(R===Kn)return _;if(Y.hasWindowSize(this))return Y.mulUnsafe(_,R,W);let M=[],K=[];return x(M,K,_,R),qi(U,M,K)}mulAddUnsafe(S,_,R){m(_);let M=[],K=[];return x(M,K,this,S),x(M,K,_,R),qi(U,M,K)}toAffine(S){let _=this,R=S;if(R!=null&&!r.isValid(R))throw new RangeError('"invertedZ" expected valid field element');let{X:M,Y:K,Z:G}=_;if(r.eql(G,r.ONE))return{x:M,y:K};let Z=_.is0();R==null&&(R=Z?r.ONE:r.inv(G));let V=r.mul(M,R),J=r.mul(K,R),re=r.mul(G,R);if(Z)return{x:r.ZERO,y:r.ZERO};if(!r.eql(re,r.ONE))throw new Error("invZ was invalid");return{x:V,y:J}}isTorsionFree(){return s===Kn?!0:f?f(U,this):Y.mulUnsafe(this,a).is0()}clearCofactor(){return s===Kn?this:d?d(U,this):this.multiplyUnsafe(s)}isSmallOrder(){return s===Kn?this.is0():this.clearCofactor().is0()}toBytes(S=!0){return tt(S,"isCompressed"),this.assertValidity(),T(U,this,S)}toHex(S=!0){return Ro(this.toBytes(S))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let W=N=>Zi(U,N),Y=new Cr(U,w);return Y.bits>=6&&U.BASE.precompute(6),Object.freeze(U.prototype),Object.freeze(U),U}function Ff(e){return Uint8Array.of(e?2:3)}function Lf(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Yb(e,t={}){pn(e);let{Fn:n}=e,r=t.randomBytes===void 0?jn:t.randomBytes,o=Object.assign(Lf(e.Fp,n),{seed:Math.max(Gi(n.ORDER),16)});function i(h){try{let w=n.fromBytes(h);return n.isValidNot0(w)}catch{return!1}}function s(h,w){let{publicKey:b,publicKeyUncompressed:y}=o;try{let v=h.length;return w===!0&&v!==b||w===!1&&v!==y?!1:!e.fromBytes(h).is0()}catch{return!1}}function a(h){return h=h===void 0?r(o.seed):h,Qi(ye(h,o.seed,"seed"),n.ORDER)}function c(h,w=!0){return e.BASE.multiply(n.fromBytes(h)).toBytes(w)}function l(h){let{secretKey:w,publicKey:b,publicKeyUncompressed:y}=o,v=n._lengths;if(!un(h))return;let I=ye(h,void 0,"key").length,g=I===b||I===y,T=I===w||!!v?.includes(I);if(!(g&&T))return g}function d(h,w,b=!0){if(l(h)===!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(h),v=e.fromBytes(w);if(v.is0())throw new Error("invalid public key: point at infinity");return v.multiply(y).toBytes(b)}let f={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},p=es(a,c);return Object.freeze(f),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:p,Point:e,utils:f,lengths:o})}function Df(e,t,n={}){pn(e);let r=t;kr(r),nt(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let o=Object.assign({},n),i=o.randomBytes===void 0?jn:o.randomBytes,s=o.hmac===void 0?(N,S)=>is(r,N,S):o.hmac,{Fp:a,Fn:c}=e,{ORDER:l,BITS:d}=c,f=Gi(l),p=vc(i,f),{keygen:h,getPublicKey:w,getSharedSecret:b,utils:y,lengths:v}=Yb(e,o),I={prehash:!0,lowS:typeof o.lowS=="boolean"?o.lowS:!0,format:"compact",extraEntropy:!1},g=l*Pf+Kn<a.ORDER;function T(N){let S=l>>Kn;return N>S}function A(N,S){if(!c.isValidNot0(S))throw new Error(`invalid signature ${N}: out of range 1..Point.Fn.ORDER`);return S}function B(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function P(N,S,_){return B(),(N===_?0:2)|Number(a.isOdd(S))}function O(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function j(N,S){Rc(S);let _=v.signature,R=S==="compact"?_:S==="recovered"?_+1:void 0;return ye(N,R)}class D{r;s;recovery;constructor(S,_,R){if(this.r=A("r",S),this.s=A("s",_),R!=null){if(O(),![0,1,2,3].includes(R))throw new Error("invalid recovery id");this.recovery=R}Object.freeze(this)}static fromBytes(S,_=I.format){j(S,_);let R;if(_==="der"){if(S.length>2*c.BYTES+16)throw new ss.Err("invalid signature: DER signature too long");let{r:Z,s:V}=ss.toSig(ye(S),c.BYTES+1);return new D(Z,V)}_==="recovered"&&(R=S[0],_="compact",S=S.subarray(1));let M=v.signature/2,K=S.subarray(0,M),G=S.subarray(M,M*2);return new D(c.fromBytes(K),c.fromBytes(G),R)}static fromHex(S,_){return this.fromBytes(Er(S),_)}assertRecovery(){let{recovery:S}=this;if(S==null)throw new Error("invalid recovery id: must be present");return S}addRecoveryBit(S){return new D(this.r,this.s,S)}recoverPublicKey(S){let{r:_,s:R}=this,M=this.assertRecovery(),K=M===2||M===3?_+l:_;if(!a.isValid(K))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let G=a.toBytes(K),Z=e.fromBytes(mt(Ff((M&1)===0),G)),V=c.inv(K),J=H(ye(S,void 0,"msgHash")),re=c.create(-J*V),E=c.create(R*V),F=e.BASE.mulAddUnsafe(re,Z,E);if(F.is0())throw new Error("invalid recovery: point at infinify");return F.assertValidity(),F}hasHighS(){return T(this.s)}toBytes(S=I.format){if(Rc(S),S==="der")return Er(ss.hexFromSig(this));let{r:_,s:R}=this,M=c.toBytes(_),K=c.toBytes(R);return S==="recovered"?(O(),mt(Uint8Array.of(this.assertRecovery()),M,K)):mt(M,K)}toHex(S){return Ro(this.toBytes(S))}}Object.freeze(D.prototype),Object.freeze(D);let X=o.bits2int===void 0?function(S){if(S.length>8192)throw new Error("input is too large");let _=Lt(S),R=S.length*8-d;return R>0?_>>BigInt(R):_}:o.bits2int,H=o.bits2int_modN===void 0?function(S){return c.create(X(S))}:o.bits2int_modN,m=Fo(d);function k(N){return Ar("num < 2^"+d,N,zt,m),c.toBytes(N)}function x(N,S){return ye(N,void 0,"message"),S?ye(r(N),void 0,"prehashed message"):N}function C(N,S,_){let{lowS:R,prehash:M,extraEntropy:K}=Cc(_,I);N=x(N,M);let G=H(N),Z=c.fromBytes(S);if(!c.isValidNot0(Z))throw new Error("invalid private key");let V=[k(Z),k(G)];if(K!=null&&K!==!1){let F=K===!0?i(v.secretKey):K;V.push(ye(F,void 0,"extraEntropy"))}let J=mt(...V),re=G;function E(F){let L=X(F);if(!c.isValidNot0(L))return;let z=e.BASE.multiply(L).toAffine(),$=c.create(z.x);if($===zt)return;let ee;if(p!==void 0){let de=Lt(Qi(p(f),l)),ie=c.inv(c.mul(de,L)),q=c.mul(de,re),oe=c.mul(de,Z);ee=c.create(ie*c.create(q+oe*$))}else{let de=mf(L,l);ee=c.create(de*c.create(re+$*Z))}if(ee===zt)return;let ne=P(z.x,z.y,$),le=ee;return R&&T(ee)&&(le=c.neg(ee),ne^=1),new D($,le,g?void 0:ne)}return{seed:J,k2sig:E}}function U(N,S,_={}){let{seed:R,k2sig:M}=C(N,S,_);return sf(r.outputLen,c.BYTES,s)(R,M).toBytes(_.format)}function W(N,S,_,R={}){let{lowS:M,prehash:K,format:G}=Cc(R,I);if(_=ye(_,void 0,"publicKey"),S=x(S,K),!un(N)){let Z=N instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+Z)}j(N,G);try{let Z=D.fromBytes(N,G),V=e.fromBytes(_);if(V.is0()||M&&Z.hasHighS())return!1;let{r:J,s:re}=Z,E=H(S),F=c.inv(re),L=c.create(E*F),z=c.create(J*F),$=e.BASE.mulAddUnsafe(L,V,z);if($.is0())return!1;let ee=$.toAffine();return!(c.create(ee.x)!==J||G==="recovered"&&Z.recovery!==P(ee.x,ee.y,J))}catch{return!1}}function Y(N,S,_={}){let{prehash:R}=Cc(_,I);return S=x(S,R),D.fromBytes(N,"recovered").recoverPublicKey(S).toBytes()}return Object.freeze({keygen:h,getPublicKey:w,getSharedSecret:b,utils:y,lengths:v,Point:e,sign:U,verify:W,recoverPublicKey:Y,Signature:D,hash:r})}var Rf,zt,Kn,Pf,Oc,Xb,Mf=je(()=>{Tc();Ft();_r();Ec();Of();Br();Rf=(e,t)=>(e+(e>=0?t:-t)/Pf)/t;zt=BigInt(0),Kn=BigInt(1),Pf=BigInt(2),Oc=BigInt(3),Xb=BigInt(4)});function Qb(e){let t=Hc.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,d=l*l*e%t,f=Ae(d,n,t)*d%t,p=Ae(f,n,t)*d%t,h=Ae(p,Uf,t)*l%t,w=Ae(h,o,t)*h%t,b=Ae(w,i,t)*w%t,y=Ae(b,a,t)*b%t,v=Ae(y,c,t)*y%t,I=Ae(v,a,t)*b%t,g=Ae(I,n,t)*d%t,T=Ae(g,s,t)*w%t,A=Ae(T,r,t)*l%t,B=Ae(A,Uf,t);if(!Pc.eql(Pc.sqr(B),e))throw new Error("Cannot find square root");return B}var Hc,Gb,Uf,Pc,Zb,Pe,jf=je(()=>{Wi();Br();Mf();Hc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Gb={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Uf=BigInt(2);Pc=Tr(Hc.p,{sqrt:Qb}),Zb=Hf(Hc,{Fp:Pc,endo:Gb}),Pe=Df(Zb,ji)});function lx(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++)Or[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=Or[a],l=Or[a+1],d=Wf(c,l,1)^Or[s],f=Kf(c,l,1)^Or[s+1];for(let p=0;p<50;p+=10)e[i+p]^=d,e[i+p+1]^=f}let r=e[2],o=e[3];for(let i=0;i<24;i++){let s=$f[i],a=Wf(r,o,s),c=Kf(r,o,s),l=Vf[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]^=ox[n]}Je(Or)}var qb,Mo,Jb,ex,tx,nx,Vf,$f,zf,Xf,rx,ox,ix,sx,ax,cx,Wf,Kf,Or,Fc,Yf,Lc,as,Dc=je(()=>{Hi();Ft();qb=BigInt(0),Mo=BigInt(1),Jb=BigInt(2),ex=BigInt(7),tx=BigInt(256),nx=BigInt(113),Vf=[],$f=[],zf=[];for(let e=0,t=Mo,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],Vf.push(2*(5*r+n)),$f.push((e+1)*(e+2)/2%64);let o=qb;for(let i=0;i<7;i++)t=(t<<Mo^(t>>ex)*nx)%tx,t&Jb&&(o^=Mo<<(Mo<<BigInt(i))-Mo);zf.push(o)}Xf=Pi(zf,!0),rx=Xf[0],ox=Xf[1],ix=(e,t,n)=>e<<n|t>>>32-n,sx=(e,t,n)=>t<<n|e>>>32-n,ax=(e,t,n)=>t<<n-32|e>>>64-n,cx=(e,t,n)=>e<<n-32|t>>>64-n,Wf=(e,t,n)=>n>32?ax(e,t,n):ix(e,t,n),Kf=(e,t,n)=>n>32?cx(e,t,n):sx(e,t,n),Or=new Uint32Array(10);Fc=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"),Yu(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=ic(this.state)}clone(){return this._cloneInto()}keccak(){sc(this.state32),lx(this.state32,this.rounds),sc(this.state32),this.posOut=0,this.pos=0}update(t){Kt(this),We(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?ic(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,p=l/4;f<a;f++)o[f]^=c[p+f];l+=n,this.pos=n,this.keccak();continue}let d=Math.min(n-this.pos,i-l);for(let f=0;f<d;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){Kt(this,!1),We(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(Sr(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,Je(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}},Yf=(e,t,n,r={})=>To(()=>new Fc(t,e,n),r),Lc=Yf(6,72,64,Bo(10)),as=Yf(1,136,32)});var u,Q,me=je(()=>{u=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}}},Q=(e,t)=>{throw new u(e,t)}});var Gf={};Fe(Gf,{ed25519:()=>Te,keccak256:()=>te,keccak256Bytes:()=>dx,primitives:()=>Xt,randomBytes:()=>Vn,secp256k1:()=>Pe,sha3_512:()=>Lc});var te,dx,Vn,Xt,_e=je(()=>{Ic();jf();Dc();me();te=e=>{let t=typeof e=="string"?new TextEncoder().encode(e):e;return as(t)},dx=e=>te(e),Vn=e=>{let t=new Uint8Array(e),n=globalThis.crypto;return(!n||typeof n.getRandomValues!="function")&&Q("bad-input",{field:"random-bytes",why:"no-source"}),n.getRandomValues(t),t},Xt={ed25519:Te,secp256k1:Pe,keccak256:te,sha3_512:Lc,randomBytes:Vn}});var hn={};Fe(hn,{PREFIX_BY_NETWORK:()=>ls,addressForNetwork:()=>hx,addressFromKeys:()=>mn,addressPayload:()=>np,checkAddress:()=>Wc,decodeMoneroBase58:()=>ds,encodeMoneroBase58:()=>tp,formatCheck:()=>Uc,isStagenetShaped:()=>px,networkFromShape:()=>jc,prefixFor:()=>Jf});function Jf(e,t="primary"){let n=ls[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 Uc(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 jc(e){let t=String(e||"").trim();return Uc(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 px(e){return jc(e)==="stagenet"}function Zf(e){let t=0n;for(let r of e)t=t<<8n|BigInt(r);let n="";for(;t>0n;)n=ep[Number(t%58n)]+n,t/=58n;return n}function qf(e,t){let n=0n;for(let o of e){let i=mx.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 ds(e){let t=String(e),n=t.length,r=n%cs,o=r===0?cs:r,i=ux[o];if(!i)throw new Error("Invalid Monero base58 length");let s=[],a=n-o;for(let d=0;d<a;d+=cs)s.push(qf(t.slice(d,d+cs),8));s.push(qf(t.slice(a),i));let c=new Uint8Array(s.reduce((d,f)=>d+f.length,0)),l=0;for(let d of s)c.set(d,l),l+=d.length;return c}function tp(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=Zf(t.slice(c,c+8));s+="1".repeat(Math.max(0,Qf[8]-l.length))+l}let a=Zf(t.slice(i));return s+="1".repeat(Math.max(0,Qf[o]-a.length))+a,s}function np({network:e,kind:t="primary",spendPub:n,viewPub:r,paymentId:o}){let i=Jf(e,t),s=Mc(n,32,"public spend key"),a=Mc(r,32,"public view key"),c=[i,...s,...a];if(t==="integrated"){let l=Mc(o,8,"payment id");c.push(...l)}return Uint8Array.from(c)}function Mc(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 mn({network:e,kind:t="primary",spendPub:n,viewPub:r,paymentId:o},i){if(!i?.keccak256)throw new Error("addressFromKeys needs { keccak256 }");let s=np({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),tp(l)}async function Wc(e,t={}){let n=String(e||"").trim();if(!Uc(n))return{ok:!1,reason:"Not a Monero address (expected 95 or 106 base58 characters)"};let r=jc(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=ds(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(te(s));if(!(a.length===4&&a.every((p,h)=>p===c[h])))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=s[0],f=fx[d]||{network:"unknown",kind:"unknown"};return f.network==="unknown"?{ok:!1,reason:`Unsupported address prefix ${d}`}: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 hx({network:e,kind:t="primary",spendPub:n,viewPub:r}){return mn({network:e,kind:t,spendPub:n,viewPub:r},{keccak256:te})}var cs,Qf,ux,fx,ls,ep,mx,$n=je(()=>{_e();cs=11,Qf={1:2,2:3,3:5,4:6,5:7,6:9,7:10,8:11},ux={2:1,3:2,5:3,6:4,7:5,9:6,10:7,11:8},fx={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"}},ls={mainnet:{primary:18,integrated:19,subaddress:42},stagenet:{primary:24,integrated:25,subaddress:36},testnet:{primary:53,integrated:54,subaddress:63}};ep="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",mx=(()=>{let e=new Map;return[...ep].forEach((t,n)=>e.set(t,BigInt(n))),e})()});var Yt={};Fe(Yt,{createHalves:()=>Wo});function Wo({ed25519:e,secp256k1:t,keccak256:n,randomBytes:r}){for(let[v,I]of[["ed25519",e],["secp256k1",t],["keccak256",n],["randomBytes",r]])if(!I)throw new Error("createHalves: not passed "+v);let o=e.Point.Fn.ORDER,i=t.Point.Fn.ORDER,s=o<i?o:i;function a(){for(let v=0;v<256;v++){let I=r(32),g=0n;for(let T of I)g=g<<8n|BigInt(T);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 d(v,I,g=c){if(!v||v.length<16)throw new Error("halfFromSeed: secret shorter than 16 bytes");if(!I)throw new Error("halfFromSeed: order binding not set");let T=new TextEncoder().encode(g+"|"+String(I)+"|");for(let A=0;A<256;A++){let B=new Uint8Array(T.length+v.length+4);B.set(T,0),B.set(v,T.length),B[T.length+v.length]=A>>>24&255,B[T.length+v.length+1]=A>>>16&255,B[T.length+v.length+2]=A>>>8&255,B[T.length+v.length+3]=A&255;let P=n(B),O=0n;for(let j of P)O=O<<8n|BigInt(j);if(O>0n&&O<s)return O}throw new Error("halfFromSeed: could not get a scalar in 256 attempts")}function f(v,I){return v.fromHex(I.startsWith("0x")?I.slice(2):I)}function p(v){if(typeof v=="bigint")return v;if(typeof v=="string"){let I=v.trim().replace(/^0x/,"");if(!/^[0-9a-fA-F]{1,64}$/.test(I))throw new Error("half does not look like a number: "+v.slice(0,12));return BigInt("0x"+I)}if(typeof v=="number")return BigInt(v);throw new Error("half of unknown type: "+typeof v)}function h(v){return v.toHex()}function w(v){return{ed:h(e.Point.BASE.multiply(p(v))),secp:h(t.Point.BASE.multiply(p(v)))}}function b(v,I){return(p(v)+p(I))%o}function y(v,I){return h(f(e.Point,v).add(f(e.Point,I)))}return{LIMIT:s,ED_ORDER:o,SECP_ORDER:i,HALF_DOMAIN:c,VIEW_HALF_DOMAIN:l,newHalf:a,halfFromSeed:d,publicHalves:w,combineHalves:b,combinePublic:y}}var Ko=je(()=>{});var Hy=Bg(()=>{});var pe={};Fe(pe,{ALLOWED_PROVIDERS:()=>Pu,API:()=>on,APP:()=>Ao,ASYNC_ROUTE_PROVIDERS:()=>Ci,CHAINS:()=>xr,DEFAULT_CHAIN:()=>Fn,DEMO:()=>jt,DEPLOYMENTS:()=>yr,DEPLOYMENT_CHAINS:()=>Bu,DEPLOYMENT_VMS:()=>Cu,DEX_ASSETS:()=>Ru,DEX_CHAINS:()=>Hg,DEX_HUBS:()=>Fg,DEX_PRICE_GATE:()=>Lg,DEX_ROUTES:()=>Dg,ENDPOINTS:()=>Bi,FACTORY_HISTORY:()=>Ou,KNOWN_FACTORY_CODES:()=>Hu,MONERO:()=>Le,SCENARIO_LABELS:()=>zg,SIGNING_DOMAIN:()=>Pg,SIGNING_GUARDS:()=>No,SWEEP:()=>Qa,TEST_CLAIMER:()=>Vg,TIMING:()=>At,XMR_NETWORKS:()=>Lu,allowedProvidersFor:()=>Mg,chainByChainId:()=>Za,chainById:()=>ft,deploymentFor:()=>Ya,knownFactoryCodesFor:()=>Ug,knownImplementationCodesFor:()=>jg,nativeOf:()=>Fu,sweepOrigin:()=>$g,tokenById:()=>Kg,tokensOf:()=>qa,wrappedNativeOf:()=>Wg});var Eo=e=>{if(e&&typeof e=="object"){Object.freeze(e);for(let t of Object.values(e))Eo(t)}return e},Xa={"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"]}},Rg={"arbitrum-sepolia":[{address:"0x3ee25f12758ec28e5b3045d16132d89cd0bf341f",deploymentBlock:318911595,release:{tag:"contracts-testnet-2026.10.21"},status:"retired"},{address:"0x69b5a6878b542960af4d239ecc60ad1c9e3e6932",deploymentBlock:323014007,release:{tag:"contracts-testnet-2026.10.26"},status:"retired"},{address:"0x245d3a4ac4b98d713f6c5130b56cd5d550f8cefe",deploymentBlock:326005419,release:{tag:"contracts-testnet-2026.11.04",commit:"930366a387c0c696bda6f5c038f23617447ebb78",toolchain:"0.8.38",deployedAt:"2026-11-04T15:00:55.822Z"},status:"live"}]},yr=Eo(Xa),Bu=Eo(Object.keys(Xa).sort()),Cu=Eo([...new Set(Object.values(Xa).map(e=>e.vm))].sort()),Ou=Eo(Rg);function Ya(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(yr).find(n=>Number(n.chainRef)===Number(t))??null:yr[t]??Object.values(yr).find(n=>n.caip2===t)??null}var gr=typeof window<"u"&&window.NINSEI_DEPLOY?window.NINSEI_DEPLOY:null,br=typeof process<"u"&&process.env?process.env:null,Ga=Object.freeze({moneroNode:"http://127.0.0.1:38081",evmRpc:"http://127.0.0.1:8545",sweepOrigin:"http://localhost:5195"}),Bi=Object.freeze({moneroNode:gr&&gr.moneroNode||br&&br.NINSEI_MONERO_NODE||Ga.moneroNode,evmRpc:gr&&gr.evmRpc||br&&br.NINSEI_EVM_RPC||Ga.evmRpc,sweepOrigin:gr&&gr.sweepOrigin||br&&br.NINSEI_SWEEP_ORIGIN||Ga.sweepOrigin}),Pg=Object.freeze({name:"NinseiEscrowFactory",version:"1"}),Ao={name:"NinseiSwap",version:"0.1.0",demo:!0,storageKey:"ninsei.demo.v1"},Hg=["arbitrum-sepolia","arbitrum","mainnet"],Ru=["USDT","USDC","DAI","USDS","USDe","PyUSD"],Fg=["USDC","USDT","DAI"],Lg={maxDeviationPct:2,stableBandPct:1,stables:Ru},No={minReadyLeadSec:600,minClaimWindowSec:600,maxDeadlineSec:259200,readyLeadWarnSec:600},Dg={"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}}},Ci={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"}}}},xr=[{id:"arbitrum-sepolia",name:"Arbitrum Sepolia",vm:"evm",chainId:421614,caip2:"eip155:421614",testnet:!0,native:{symbol:"ETH",decimals:18,usd:3212.4},rpcUrl:Bi.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:Ya("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"}]}],Fn="arbitrum-sepolia",Pu={"local-anvil":["0x60af2ad4963c738aa6ac16d6cb0af1982508ba21"]};function Mg(e){let t=typeof e=="string"?e:e&&e.id,n=Pu[t];return!Array.isArray(n)||n.length===0?null:n.map(r=>String(r).toLowerCase())}var Hu=Object.freeze(Object.fromEntries(Object.values(yr).filter(e=>e.status==="live"&&e.knownFactoryCodes.length>0).map(e=>[e.network,[...e.knownFactoryCodes]])));function Ug(e){let t=typeof e=="string"?e:e&&e.id,n=Hu[t];return!Array.isArray(n)||n.length===0?null:n.map(r=>String(r).toLowerCase())}function jg(e){let t=typeof e=="string"?e:e&&e.id,n=xr.find(o=>o.id===t)||ft(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 ft(e){return xr.find(t=>t.id===e)||xr.find(t=>t.id===Fn)||xr[0]}function Za(e){return xr.find(t=>t.chainId===Number(e))||null}function qa(e){let t=ft(e);return[Fu(e),...t.tokens]}function Fu(e){let t=ft(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 Wg(e){return(ft(e).tokens||[]).find(n=>n&&n.peg==="native")||null}function Kg(e,t){let n=e,r=t;typeof e=="string"&&e.includes(":")&&([n,r]=e.split(":"));let o=qa(n);return o.find(i=>i.symbol===String(r).toUpperCase())||o[0]}var Vg="0xc14C7841C7d6350859474dD6DF8dC9672047A6A0",Le={networkType:"stagenet",confirmTarget:10,blockTimeSim:12e4,blockTimeReal:12e4,node:Bi.moneroNode,nodePollMs:3e4},on={base:null,xmrSource:"app",pollMs:5e3,maxProviders:5,timeoutMs:6e4},Lu={app:"stagenet",mock:"stagenet",fakechain:"fakechain"};function $g(){let e=typeof location<"u"?location.hostname:"";return/^(localhost|127\.0\.0\.1|\[::1\])$/.test(e)||/\.local$/.test(e)?Qa.localOrigin:Qa.origin}var Qa={origin:Bi.sweepOrigin,localOrigin:"http://localhost:5195"},At={quoteValid:12e3,quoteRefresh:5e3,fundingMined:6e3,makerLock:3e4,xmrConfirm:Le.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:Fn},zg={happy:"happy path",maker_no_lock:"maker never locks XMR",user_no_ready:"user never confirms",maker_stall:"maker stalls after ready"};var ke={};Fe(ke,{allowanceVerdict:()=>Zg,counterpartyVerdict:()=>Jg,deadlineVerdict:()=>ec,escrowPointsVerdict:()=>Ja,escrowStateVerdict:()=>tc,gasReserveVerdict:()=>Gg,liveOrderSlotsVerdict:()=>eb,networkGateVerdict:()=>qg,payBalanceVerdict:()=>Yg,quoteFreshnessVerdict:()=>Qg,rangeVerdict:()=>Xg,signingGateVerdict:()=>tb,signingGateWords:()=>nb});var Ln=e=>{if(e==null||e==="")return null;try{let t=BigInt(e);return t>=0n?t:null}catch{return null}},pt=e=>String(Number(Number(e).toFixed(4))),Re=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 Xg({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=Re(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:Re(n),max:Re(r),step:Re(o),unit:s};let l=Re(n),d=Re(r),f=Re(o);if(l===null&&d===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 p={size:c,min:l,max:d,step:f,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 ${pt(c)} ${s} is below the provider minimum ${pt(l)} ${s} - short by ${pt(l-c)} ${s}: the provider does not take this size`};if(d!==null&&c>d)return{ok:!1,checked:!0,blocks:!0,kind:"above-max",...p,reason:`the order size ${pt(c)} ${s} is above the provider maximum ${pt(d)} ${s} - over by ${pt(c-d)} ${s}: the provider does not take this size`};if(f!==null&&f>0){let h=l!==null?l:0,w=(c-h)/f;if(Math.abs(w-Math.round(w))>1e-6)return{ok:!1,checked:!0,blocks:!0,kind:"off-step",...p,reason:`the order size ${pt(c)} ${s} does not sit on the ${pt(f)} ${s} step from ${pt(h)} ${s}`}}return{ok:!0,checked:!0,blocks:!1,kind:"in-range",...p,reason:`the order size ${pt(c)} ${s} is inside the provider range ${l===null?"?":pt(l)}..${d===null?"?":pt(d)} ${s}`}}function Yg({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 Gg({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 Qg({at:e=null,ttlMs:t=null,expiresAt:n=null,nowMs:r=null}={}){let o=Re(r)===null?Date.now():Number(r),i=Re(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=Re(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=Re(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 ec({nowSec:e=null,readyBy:t=null,t1:n=null,minReadyLeadSec:r=null,minClaimWindowSec:o=null,maxDeadlineSec:i=null}={}){let s=Re(e)===null?Math.floor(Date.now()/1e3):Number(e),a=Re(t),c=Re(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=Re(r),d=Re(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(d!==null&&c-a<d)return{ok:!1,checked:!0,blocks:!0,kind:"claim-window-too-short",readyBy:a,t1:c,minClaimWindowSec:d,reason:`the claim window is ${Math.round(c-a)}s while at least ${d}s is needed to take the funds before the refund opens`};let f=Re(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 tc({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 Zg({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 qg({walletChainId:e=null,selectedChainId:t=null,settlementChainId:n=null,selectedChainName:r=null}={}){let o=Re(e),i=Re(t),s=Re(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 Jg({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 Qe=e=>e==null?"":String(e).replace(/^0x/i,"").toLowerCase();function Ja({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(Qe(n)){if(c=!0,!Qe(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(Qe(n)!==Qe(r))return{ok:!1,checked:!0,blocks:!0,kind:"point-mismatch",reason:`${a} in the escrow (0x${Qe(r)}) is NOT the point DLEQ proved (0x${Qe(n)}): the Monero address would be assembled from other halves and the XMR could not be swept after claim`}}if(Qe(o)){if(c=!0,!Qe(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(Qe(o)!==Qe(i))return{ok:!1,checked:!0,blocks:!0,kind:"commit-mismatch",reason:`${a} in the escrow (0x${Qe(i)}) is NOT the one we hold (0x${Qe(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${Qe(n)&&Qe(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 eb({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(!Qe(t&&t[s]))continue;if(!Qe(e[s])){i.push(a);continue}let l=Ja(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 tb(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 nb(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 ys={};Fe(ys,{assertNoSecretsInShare:()=>Ep,restoreFromFile:()=>Ux,restoreFromHalves:()=>vp,restoreWalletFromPayload:()=>Sp,watchOnlyShareFromWallet:()=>jx});function Oi(e=16){let t=new Uint8Array(e);return crypto.getRandomValues(t),Wt(t)}function Wt(e){let t=e instanceof Uint8Array?e:Uint8Array.from(e||[]);return Array.from(t,n=>n.toString(16).padStart(2,"0")).join("")}function nc(){return Oi(8)}_e();$n();_e();var zn=["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 us=24,rp=25,Kc=32,wx=3,fs=new Map(zn.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 bx(e,t,n){let r=zn.length,o=fs.get(e),i=fs.get(t),s=fs.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 xx(e){let t=zn.length,n=e%t,r=(Math.floor(e/t)+n)%t,o=(Math.floor(Math.floor(e/t)/t)+r)%t;return[zn[n],zn[r],zn[o]]}function op(e){let t=e.map(n=>n.slice(0,wx)).join("");return e[gx(new TextEncoder().encode(t))%e.length]}function kx(e){return(e.length===us||e.length===rp)&&e.every(t=>fs.has(t))}function Sx(e){let t=e instanceof Uint8Array?e:Uint8Array.from(e);if(t.length!==Kc)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(...xx(n.getUint32(o,!0)));return r.join(" ")}function vx(e){let t=Sx(e).split(" ");return t.push(op(t)),t.join(" ")}function ip(){return vx(Vn(Kc))}function sp(e){let t=String(e||"").trim().split(/\s+/).filter(Boolean);if(!kx(t))throw new Error("invalid mnemonic phrase (length or words)");if(t.length===rp){let i=t.slice(0,us);if(t[us]!==op(i))throw new Error("invalid mnemonic checksum")}let n=new Uint8Array(Kc),r=new DataView(n.buffer),o=Math.min(t.length,us);for(let i=0;i<o/3;i+=1)r.setUint32(i*4,bx(t[i*3],t[i*3+1],t[i*3+2]),!0);return n}function ap(e){try{return sp(e),!0}catch{return!1}}function cp(e){return sp(e)}_e();var up=Te.Point.Fn.ORDER,Rr=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 Ax(e,t=Rr){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 zc(e){if(e.length>64)throw new Error("scalar is longer than 64 bytes");let t=new Uint8Array(64);return t.set(e),Ax(jo(t)%up)}function Nx(e){return e instanceof Uint8Array?e:e&&e.buffer instanceof ArrayBuffer?new Uint8Array(e):Uint8Array.from(e||[])}function _x(e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}function lp(e){return Te.Point.fromHex(_x(e))}function Vc(e){return Te.Point.BASE.multiply(jo(e)).toBytes()}function dp(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 Uo=new TextEncoder().encode("SubAddr\0");function Ix({privateView:e,publicSpend:t},n,r){if(n===0&&r===0)return{publicSpendKey:t,publicViewKey:Vc(e)};let o=new Uint8Array(Uo.length+Rr+8);o.set(Uo,0),o.set(e,Uo.length),o.set(dp(r),Uo.length+Rr),o.set(dp(n),Uo.length+Rr+4);let i=zc(te(o)),s=lp(t).add(Te.Point.BASE.multiply(jo(i))).toBytes(),a=lp(s).multiply(jo(e)).toBytes();return{publicSpendKey:s,publicViewKey:a}}var $c=class{#n;#e;#t;#r;constructor(t){if(!(t instanceof Uint8Array)||t.length!==Rr)throw new Error("invalid private spend key");if(jo(t)>=up)throw new Error("invalid private spend key");this.#n=t,this.#e=zc(te(t)),this.#t=Vc(t),this.#r=Vc(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 Ix({privateView:this.#e,publicSpend:this.#t},t,n)}};function fp(e){let t=Nx(e);return new $c(zc(t.length===Rr?t:te(t)))}async function pp(){}async function Bx({mnemonic:e,network:t=Le.networkType}={}){await pp();let n;if(e){if(!ap(e))throw new Error("the mnemonic failed its checksum check (file or form corrupted?)");n=String(e).trim()}else n=ip();let r=cp(n),o=fp(r),i=t||"mainnet",s={keccak256:te},a=Wt(o.publicSpendKey),c=Wt(o.publicViewKey),l=o.subaddress(1,0),d=mn({network:i,kind:"primary",spendPub:a,viewPub:c},s),f=mn({network:i,kind:"subaddress",spendPub:Wt(l.publicSpendKey),viewPub:Wt(l.publicViewKey)},s),p=mn({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:Wt(r),privateSpendKey:Wt(o.privateSpendKey),privateViewKey:Wt(o.privateViewKey),publicSpendKey:a,publicViewKey:c,address:d,subaddress:f,addressMainnet:p,createdAt:Date.now()}}async function mp({network:e=Le.networkType,seed:t}={}){return Bx({mnemonic:t,network:e})}var at={};Fe(at,{ALG_NONE:()=>ms,ENVELOPE_VERSION:()=>yp,FILE_MAGIC:()=>Qc,PAYLOAD_VERSION:()=>Rx,UNENCRYPTED_ENVELOPE_VERSION:()=>Zc,buildPayload:()=>Fx,createRecoveryFile:()=>Dx,decryptFile:()=>Jc,encryptPayload:()=>bp,envelopeAad:()=>qc,isEncrypted:()=>Lx,recoveryFileName:()=>Mx,scanStartHeight:()=>Hx,validatePayload:()=>hs});var wp="AES-GCM-256/PBKDF2-SHA256",wn=Object.freeze({name:"AES-GCM",tagLength:128,keyBits:256}),Xc=Object.freeze({name:"PBKDF2",hash:"SHA-256"}),ps=new TextEncoder,Cx=new TextDecoder,Qc="NINSEI-SWAP-RECOVERY",yp=2,Zc=3,ms="NONE",Ox=[1,2,3],Rx=3,hp=[1,2,3],Px=["mainnet","stagenet","testnet","fakechain"];function Yc(e){return btoa(String.fromCharCode(...new Uint8Array(e)))}function Gc(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))}function qc(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 gp(e,t,n){let r=await crypto.subtle.importKey("raw",ps.encode(e),Xc.name,!1,["deriveKey"]);return crypto.subtle.deriveKey({name:Xc.name,salt:t,iterations:n,hash:Xc.hash},r,{name:wn.name,length:wn.keyBits},!1,["encrypt","decrypt"])}function Hx({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 Fx({swap:e,swapWallet:t,escrow:n,receiveAddress:r,restoreHeight:o=null}){return{magic:Qc,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 hs(e){let t=i=>{throw new Error("Corrupt recovery file: "+i)};(!e||typeof e!="object")&&t("the content is not an object"),e.magic!==Qc&&t("foreign file (no Ninsei mark)"),hp.includes(e.version)||t(`payload version ${e.version} is not supported (we support ${hp.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;Px.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 bp(e,t){let n=()=>({id:e.swapId,side:e.side,createdAt:e.createdAt,termsHash:e.termsHash||null});if(t==="")return{v:Zc,alg:ms,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 gp(t,r,6e5),s={id:e.swapId,side:e.side,createdAt:e.createdAt,termsHash:e.termsHash||null},a={v:yp,alg:wp,iter:6e5,salt:Yc(r),iv:Yc(o)},c=await crypto.subtle.encrypt({name:wn.name,iv:o,tagLength:wn.tagLength,additionalData:ps.encode(qc({...a,meta:s}))},i,ps.encode(JSON.stringify(e,xp)));return{...a,ciphertext:Yc(c),meta:s}}function Lx(e){return!!(e&&typeof e=="object"&&e.alg!==ms)}async function Jc(e,t){if(!e||typeof e!="object")throw new Error("Not a recovery file (expecting JSON)");if(!Ox.includes(e.v))throw new Error(`Unsupported recovery file version: ${e.v}`);if(e.v===Zc){if(e.alg!==ms)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!==wp)throw new Error(`Unknown algorithm: ${e.alg}`);for(let d of["salt","iv","ciphertext"])if(typeof e[d]!="string"||!e[d])throw new Error(`Recovery file is missing "${d}"`);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=Gc(e.salt),o=Gc(e.iv),i=await gp(t,r,n),s=e.v>=2?ps.encode(qc(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,Gc(e.ciphertext))}catch{throw new Error("Could not decrypt the file: wrong password or the file was altered")}let l;try{l=JSON.parse(Cx.decode(c))}catch{throw new Error("It decrypted, but the content is not JSON - the file is corrupt")}if(hs(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 xp=(e,t)=>typeof t=="bigint"?"0x"+t.toString(16):t;async function Dx(e,t){let n=await bp(e,t);return JSON.stringify(n,xp,2)}function Mx(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 ws({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[h,w]of Object.entries({ownSpendHalf:r,ownViewHalf:o,otherSpendPoint:i,otherViewPoint:s}))if(w==null||w==="")throw new Error("not set: "+h);let c=e.publicHalves(r).ed,l=e.publicHalves(o).ed,d=e.combinePublic(c,i),f=e.combinePublic(l,s);return{address:t({network:a,kind:"primary",spendPub:d,viewPub:f},n),spendPub:d,viewPub:f,ownSpendPub:c,ownViewPub:l}}function kp({halves:e,ownViewHalf:t,otherViewHalf:n}){return"0x"+e.combineHalves(t,BigInt(n)).toString(16).padStart(64,"0")}async function Sp(e,t={}){let{warnings:n}=hs(e),r=e.moneroWallet,o=r.network||e.moneroNetwork;if(e.version>=3)return await vp(e,n,t);let i=await mp({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 vp(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(()=>(_e(),Gf)),{createHalves:d}=await Promise.resolve().then(()=>(Ko(),Yt)),{addressFromKeys:f}=await Promise.resolve().then(()=>($n(),hn));return{halves:d(l),addressFromKeys:f,keccak256:l.keccak256}})();if(!i.keccak256)throw new Error("no keccak256: the address cannot be checked without it");let s=ws({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=kp({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 Ux(e,t,n={}){return Sp(await Jc(e,t),n)}function Ep(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 jx({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 Ep({swapId:e||null,network:t.network,address:t.address,privateViewKey:t.privateViewKey,restoreHeight:Number.isFinite(n)?n:null},t)}var Yn={};Fe(Yn,{bindStorage:()=>Vx,createStore:()=>zx,exportState:()=>Gx,loadState:()=>rt,memoryStorage:()=>Ap,reset:()=>Yx,saveState:()=>Dt,setStorage:()=>Kx,storage:()=>$x,update:()=>Xx});var el={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};function Ap(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 Wx=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=Wx("localStorage")||Ap(),gs=null,tl=e=>{if(!(e&&typeof e.get=="function"&&typeof e.set=="function"&&typeof e.remove=="function"))throw new Error("storage must support get/set/remove")},Xn=(e,t)=>{let n=new Error("storage-unavailable");return n.code="storage-unavailable",n.params={step:e},t&&(n.cause=t),n};function Kx(e){return tl(e),yn=e,gs=null,yn}function Vx(e){if(tl(e),gs&&gs!==e)throw Xn("conflict");return gs=e,yn=e,yn}var $x=()=>yn;function Np(e){let t;try{t=e.get(Ao.storageKey)}catch(r){throw Xn("read",r)}if(t==null||t==="")return structuredClone(el);let n;try{n=JSON.parse(t)}catch(r){throw Xn("parse",r)}if(!n||typeof n!="object"||Array.isArray(n))throw Xn("parse");return{...structuredClone(el),...n,settings:{...el.settings,...n.settings||{}}}}function rt(){return Np(yn)}var _p=(e,t)=>typeof t=="bigint"?"0x"+t.toString(16):t;function Ip(e,t){let n;try{n=JSON.stringify(t,_p)}catch(r){throw Xn("serialize",r)}try{e.set(Ao.storageKey,n)}catch(r){throw Xn("write",r)}return t}function Dt(e){return Ip(yn,e)}function zx(e){return tl(e),{loadState:()=>Np(e),saveState:t=>Ip(e,t),storage:()=>e}}function Xx(e){let t=rt(),n=e(t)||t;return Dt(n),n}function Yx(){try{yn.remove(Ao.storageKey)}catch(e){throw Xn("remove",e)}}function Gx(){return JSON.stringify(rt(),_p,2)}var Tp="eip6963:announceProvider",Qx="eip6963:requestProvider";function Bp(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 Zx(e){return e?e.isMetaMask?"MetaMask":e.isRabby?"Rabby":e.isCoinbaseWallet?"Coinbase Wallet":e.isBraveWallet?"Brave Wallet":e.isFrame?"Frame":"Browser wallet":null}function Vo({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(Tp,i),typeof e.dispatchEvent=="function"&&e.dispatchEvent(new Event(Qx))),new Promise(s=>{let a=()=>{e&&typeof e.removeEventListener=="function"&&e.removeEventListener(Tp,i);let c=e&&e.ethereum;if(!n.length&&c){let l=Array.isArray(c.providers)&&c.providers.length?c.providers:[c];for(let d of l)o({name:Zx(d),icon:null,rdns:null,provider:d,source:"legacy"})}s(n)};t>0&&typeof setTimeout=="function"?setTimeout(a,t):a()})}async function Cp(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 Op(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 Rp(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 Ke(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 Pp({title:e="Connect a wallet",subtitle:t="",hint:n=""}={}){let r={},o=Ke("div",{class:"ar-overlay"},[Ke("div",{class:"ar-modal"},[Ke("div",{class:"ar-modal-head"},[Ke("div",{class:"ar-modal-title",text:e}),r.closeBtn=Ke("button",{class:"ar-modal-close",type:"button",title:"Close",text:"\xD7"})]),r.subtitle=Ke("div",{class:"ar-modal-sub",text:t}),r.choices=Ke("div",{class:"ar-modal-choices"}),r.status=Ke("div",{class:"ar-modal-status"}),Ke("div",{class:"ar-modal-actions"},[r.cancelBtn=Ke("button",{class:"ar-btn-ghost",type:"button",text:"Cancel"})]),r.hint=Ke("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",d=>{d.target===o&&c()});function l(d){r.choices.innerHTML="",r.choices.hidden=!d||!d.length;for(let f of d||[]){let p=Ke("button",{class:"ar-modal-choice",type:"button"},[f.icon?Ke("img",{class:"ar-modal-choice-icon",src:f.icon,alt:""}):Ke("span",{class:"ar-modal-choice-icon ar-modal-choice-icon-empty"}),Ke("span",{class:"ar-modal-choice-text"},[Ke("span",{class:"ar-modal-choice-name",text:f.name}),f.hint?Ke("span",{class:"ar-modal-choice-hint",text:f.hint}):null])]);p.addEventListener("click",()=>{i.value||f.onClick()}),r.choices.appendChild(p)}return r.choices}return{closed:i,setChoices:l,close:a,cancel:c,setOnCancel(d){s=d},update({status:d,subtitle:f,hint:p,error:h}={}){if(i.value)return;f!==void 0&&(r.subtitle.textContent=f||""),p!==void 0&&(r.hint.textContent=p||"");let w=h||d;w!==void 0&&(r.status.className="ar-modal-status"+(h?" ar-modal-status-error":""),r.status.textContent=w||"")}}}function Hp(e,t){return Number(e)/10**t}var ON=[[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 xs={};Fe(xs,{CLAIM_GAS_LIMIT:()=>nl,CLAIM_TIP_FLOOR_WEI:()=>Fp,DEFAULT_GIFT_RESERVE_BPS:()=>Dp,claimGasGiftWei:()=>rl,claimMaxFeePerGasWei:()=>bs,claimRequiredWei:()=>Lp});var nl=200000n,Fp=0n,Pr=e=>{if(e==null||e==="")return null;try{return BigInt(typeof e=="bigint"?e:String(e))}catch{return null}};function bs({baseFeeWei:e,priorityFeeWei:t=0n,minTipWei:n=Fp}={}){let r=Pr(e);if(r===null||r<=0n)return null;let o=Pr(t),i=Pr(n),s=i===null||i<0n?0n:i,a=o!==null&&o>s?o:s;return r*2n+a}function Lp({gasLimit:e=nl,maxFeePerGasWei:t}={}){let n=Pr(e),r=Pr(t);return n===null||n<=0n||r===null||r<=0n?null:n*r}var Dp=10000n;function rl({baseFeeWei:e,priorityFeeWei:t,minTipWei:n,gasLimit:r=nl,reserveBps:o=Dp}={}){let i=bs({baseFeeWei:e,priorityFeeWei:t,minTipWei:n}),s=Lp({gasLimit:r,maxFeePerGasWei:i});if(s===null)return null;let a=Pr(o),c=a===null||a<0n?0n:a;return s+s*c/10000n}var il=new Set,ae={status:"idle",kind:null,label:null,address:null,chainId:null,balances:{},error:null,lastRefresh:0},Ee=null,ht=null;function wt(){for(let e of il)try{e(Gn())}catch(t){console.warn("wallet listener failed",t)}}function Gn(){return{...ae,balances:{...ae.balances}}}function Mp(e){return il.add(e),()=>il.delete(e)}function Up(){return Gn()}function qn(){return ae.status==="connected"&&!!ae.address}function al(){return ae.address}function jp(){return ae.chainId}function Wp(){return Ee}function Kp(e,t){let n=ft(e),r=ae.balances[`${n.chainId}:${String(t).toUpperCase()}`];return r===void 0?0:r}var qx=e=>"0x"+Number(e).toString(16);function Qn(e="idle",t=null){ae.status=e,ae.error=t,ae.kind=null,ae.label=null,ae.address=null,ae.chainId=null,ae.balances={},Ee=null,wt()}function Vp(e){e.on("chainChanged",t=>{ae.chainId=Number(t),ae.error=null,wt(),Zn()}),e.on("accountsChanged",t=>{let n=t&&t[0]||null;if(!n){ht&&ht.close(),Qn("idle",null);return}ae.address=n,wt(),Zn()}),e.on("disconnect",()=>{ht&&ht.close(),Qn("idle",null)})}var sl="ninsei.wallet.optOut",Jx=()=>{try{return localStorage.getItem(sl)==="1"}catch{return!1}},$p=e=>{try{e?localStorage.setItem(sl,"1"):localStorage.removeItem(sl)}catch{}},ol=!1;async function zp(){return Jx()?(ol=!0,console.log("[wallet] restore skipped: wallet disconnected manually"),Gn()):ol||ae.status==="connected"?Gn():(ol=!0,cl())}async function cl({wallets:e}={}){if(qn())return Gn();let t=e||await Vo();for(let n of t){let r=await Op(n.provider);if(r.length){Ee=n.provider,ae.kind="injected",ae.label=n.name||"Browser wallet",Vp(Ee),ae.address=r[0];try{ae.chainId=Number(await Ee.request({method:"eth_chainId"}))||null}catch{ae.chainId=null}return ae.status="connected",ae.error=null,wt(),await Zn(),console.info("Browser wallet restored without a prompt: "+ae.address),Gn()}}return Gn()}async function ll({wallet:e,chainSlug:t}={}){if($p(!1),!e||!e.provider)throw new Error("No wallet extension found in this browser");if(qn()&&ae.kind==="injected"&&ae.label===(e.name||null))return{address:ae.address,chainId:ae.chainId};let n=ft(t||ae.chainId||void 0);Ee=e.provider,ae.kind="injected",ae.label=e.name||"Browser wallet",ae.status="pairing",ae.error=null,wt(),Vp(Ee);try{let r=await Cp(Ee);if(!r.address)throw new Error("The wallet returned no address");return ae.address=r.address,ae.chainId=r.chainId||n.chainId,ae.status="connected",ae.error=null,wt(),ae.chainId!==n.chainId&&await dl(n),await Zn(),{address:ae.address,chainId:ae.chainId}}catch(r){let o=ae.label||e.name||"Wallet",i=Rp(r,o);if(Bp(r))return console.info("[wallet] user refusal: "+i),Qn("idle",null),null;throw console.warn("[wallet] connect did not happen: "+i,r),Qn("error",i),new Error(i)}}async function Xp({chainSlug:e}={}){if(qn())return{address:ae.address,chainId:ae.chainId};let t=ft(e||ae.chainId||void 0);ae.status="pairing",ae.error=null,wt();let n=await Vo();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"),ht=Pp({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=>{ht.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})}));ht.setChoices(i),ht.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 Qn("idle",null),null;try{let o=await ll({wallet:r.wallet,chainSlug:t.id});return ht&&ht.close(),o}catch(o){let i=String(o&&o.message||o);throw ht&&ht.update({error:i,status:"Try again."}),o}}async function Yp(){$p(!0);let e=Ee;if(!e){Qn("idle",null);return}try{typeof e.revokePermissions=="function"&&await e.request({method:"wallet_revokePermissions",params:[{eth_accounts:{}}]})}catch(t){console.warn("disconnect failed",t)}Qn("idle",null)}async function dl(e){let t=typeof e=="object"?e:ft(e);if(!Ee||!qn())return!1;let n=qx(t.chainId);try{await Ee.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))||(ae.error=String(r&&r.message||r),wt()),!1;try{await Ee.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))||(ae.error=String(s&&s.message||s),wt()),!1}}return ae.chainId=t.chainId,wt(),await Zn(),!0}async function ul({to:e,data:t,block:n="latest"}={}){if(!Ee)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 Ee.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 Gp({address:e}={}){if(!Ee)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 Ee.request({method:"eth_getCode",params:[e,"latest"]})}async function fl({hash:e}={}){if(!Ee)throw new Error("wallet not connected: nothing to read the receipt with");if(!e)throw new Error("no transaction hash given");let t=await Ee.request({method:"eth_getTransactionReceipt",params:[e]});return!t||typeof t!="object"?null:t}async function pl({to:e,data:t,value:n="0x0",gas:r}={}){if(!Ee)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=al();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 Ee.request({method:"eth_getBlockByNumber",params:["latest",!1]}),c=a&&a.baseFeePerGas?BigInt(a.baseFeePerGas):0n,l=0n;try{let f=await Ee.request({method:"eth_gasPrice",params:[]});if(typeof f=="string"&&/^0x[0-9a-fA-F]+$/.test(f)){let p=BigInt(f)-c;p>0n&&(l=p)}}catch{}let d=bs({baseFeeWei:c,priorityFeeWei:l});d!==null&&(i.maxPriorityFeePerGas="0x"+(d-c*2n).toString(16),i.maxFeePerGas="0x"+d.toString(16))}catch(a){console.warn("could not compute the fee, the wallet decides: "+(a&&a.message||a))}let s=await Ee.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 Zn(){if(!qn()||!Ee)return;let e=Za(ae.chainId);if(!e){ae.error=`Wallet is on chain ${ae.chainId}, which this demo does not support`,wt();return}let t=ae.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 Ee.request({method:c,params:[t,"latest"]});else{let d="0x70a08231"+t.replace(/^0x/,"").toLowerCase().padStart(64,"0");l=await Ee.request({method:"eth_call",params:[{to:s,data:d},"latest"]})}return[i,Hp(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);ae.balances={...ae.balances,...n},ae.lastRefresh=Date.now(),ae.error=null,wt()}var fe={};Fe(fe,{STEP_LABELS:()=>dk,TERMINAL:()=>Fr,activeSwaps:()=>hk,addServerSwaps:()=>mk,allSwaps:()=>cm,confirmReady:()=>yk,createReverseSwap:()=>fk,createSwap:()=>uk,dealSwapIds:()=>vk,derive:()=>Yo,forgetSwap:()=>pk,getSwap:()=>vs,halvesWalletOf:()=>Ss,onNotify:()=>Nk,refundEth:()=>bk,refundHalfRevealed:()=>um,saveSwap:()=>wk,serverRestoreHeightFor:()=>Ek,serverRowToSwap:()=>lm,setLiveFocus:()=>Ak,startTicker:()=>_k,subscribe:()=>kk,sweepNow:()=>gk,tick:()=>pm,xmrAmountCheck:()=>fm});var _t={softSec:600,hardSec:1200},Qp=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?Math.floor(n):t};function Zp({poolSeen:e,soft:t=_t.softSec,hard:n=_t.hardSec}={}){let r=Qp(t,_t.softSec),o=Qp(n,_t.hardSec),i=Math.min(r,o);return e?i:o}function yt(){return Date.now()}function $o(e,t=yt()){return Math.max(0,(t-e.realStart)*e.speed)}function Jn(e,t){return e.simStartWall+t}var ek=Le.node,tk=8e3,nk=15e3,er={at:0,data:null,error:null},zo=null;async function rk(e,t={},n="/json_rpc"){let r=new AbortController,o=setTimeout(()=>r.abort(),tk);try{let i=await fetch(ek+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 ks(){return er.data}async function qp({force:e=!1}={}){return er.data&&Date.now()-er.at<nk&&!e?er.data:zo||(zo=rk("get_info").then(n=>(er={at:Date.now(),data:ok(n),error:null},er.data)).catch(n=>(er={at:Date.now(),data:null,error:n.message},null)).finally(()=>{zo=null}),zo)}function ok(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 Hr(...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")+Oi(28)}function ik(e){return"0x"+Hr("escrow",e).slice(2,42)}function sk(e){return"8"+Hr("xmrlock",e).slice(2,96)}function em({swapId:e,ethAmountUsd:t,ethUsd:n}){return{mock:!0,txHash:Hr("fund",e),escrow:ik(e),ethAmount:n>0?t/n:0,valueUsd:t,gasUsd:.21,method:"simulated funding (no real transaction)",confirmations:1}}function tm({swapId:e,xmrAmount:t}){return{mock:!0,txid:Hr("xmrtx",e),address:sk(e),amount:t,viewKeyVerified:!0,unlocked:"1 of 2 spend key shares revealed (DLEQ bound)"}}function ml({swapId:e}){return{mock:!0,txid:Hr("sweep",e)}}function hl({swapId:e,by:t}){return{mock:!0,txHash:Hr("refund",e,t),by:t}}function nm(e,t){let n=e.timeline.confTarget;if(e.chainMode==="live"){let i=e.xmr&&e.xmr.lockHeight,s=ks();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 gn={AWAITING:"awaiting_funding",FUNDED:"funded",LOCKED:"xmr_locked",READY:"ready",SWEPT:"swept",CLOSED:"closed"};function bn(e=on.xmrSource){return e==="app"}function ck(e,t){let n=e.timeline&&e.timeline.confTarget||Le.confirmTarget,r=e.timeline?e.timeline.lockAtSim:0,o=r!==null&&t>=r,i=nm(e,t),s=o?i>=n?gn.READY:gn.FUNDED:gn.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 lk(e){let t=e.timeline&&e.timeline.confTarget||Le.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 rm(e,t){return bn(e&&e.xmrSource)?lk(e):ck(e,t)}function om(e,t="stagenet"){return e?`https://${t==="mainnet"?"":t+"."}xmrchain.net/tx/${e}`:null}var dk=[["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"]],Fr={success:{phase:"success",label:"XMR delivered"},refunded_eth:{phase:"refunded_eth",label:"ETH refunded"}};function uk(e,t=null){let n=t?t.loadState():rt(),r=Date.now(),o={id:nc(),side:e.side||"buy",scenario:e.scenario||"happy",speed:e.speed||60,network:e.network||Fn,moneroNetwork:e.moneroNetwork||Le.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:At.makerLock,blockSim:Le.blockTimeSim,confTarget:Le.confirmTarget,t0Sim:At.t0Refund},chainMode:e.chainMode||jt.defaultChainMode,xmrSource:e.xmrSource||on.xmrSource,xmrSession:null,xmrSessionError:null,events:[],escrow:null,xmr:null,settlement:null,log:[]};if(o.chainMode!=="live"){let i=em({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):Dt(n),o}function fk(e={}){let t=rt(),n=Date.now(),r=Number(e.xmrAmount),o={id:nc(),side:"reverse",scenario:"happy",speed:Number(e.speed)||60,network:e.network||Fn,moneroNetwork:e.moneroNetwork||Le.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:Le.blockTimeSim,confTarget:Le.confirmTarget,t0Sim:At.t0Refund},chainMode:e.chainMode||jt.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||Le.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,Dt(t),o}function Gt(e,t,n,r){e.log.push({atSim:t,wall:Jn(e,t),title:n,detail:r||""}),console.log(`[swap ${e.id}] ${n}${r?" - "+r:""}`)}function Ss(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||Le.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 pk(e,t=null){let n=t?t.loadState():rt();return n.swaps[e]?(delete n.swaps[e],t?t.saveState(n):Dt(n),!0):!1}function vs(e,t=null){return(t?t.loadState():rt()).swaps[e]||null}function cm(){let e=rt();return Object.values(e.swaps).sort((t,n)=>t.realStart<n.realStart?1:-1)}function lm(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 mk(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]=lm(o),r+=1);return r&&(t?t.saveState(n):Dt(n)),r}function hk(){return cm().filter(e=>!e.settlement)}function wk(e,t=null){return Es(e,t)}function Es(e,t=null){let n=t?t.loadState():rt();return n.swaps[e.id]=e,t?t.saveState(n):Dt(n),e}function im(e,t,n,r={}){return e.events.push({type:t,atSim:n,...r}),e}function dm(e,t){return e.events.find(n=>n.type===t)||null}function yk(e,t=null){let n=vs(e,t);if(!n||n.settlement)return n;if(!Yo(n).can.ready)throw new Error("ready() is not available in this phase");let o=$o(n);return im(n,"ready",o),Gt(n,o,"ready() called by you","maker may now claim the ETH escrow"),dm(n,"funded_note")||im(n,"funded_note",0),Es(n,t)}function um(e){let t=e&&e.escrow||{};return t.revealedHalf||t.counterHalf||null}function gk(e,t=null){let n=vs(e,t);if(!n||n.settlement&&!(n.settlement.kind==="refund_eth"&&n.side==="reverse"))return n;if(!Yo(n).can.sweep)throw new Error("sweep is not available in this phase");let o=$o(n),i=ml({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:Fr.success.phase,atSim:o,txid:i.txid,by:"you",...s?{recovered:!0}:{}},Gt(n,o,"XMR swept to your address",i.txid),Es(n,t)}function bk(e,t="you",n=null){let r=vs(e,n);if(!r||r.settlement)return r;if(!Yo(r).can.refund)throw new Error("refund is not available in this phase");let i=$o(r),s=hl({swapId:r.id,by:t});return r.settlement={kind:"refund_eth",phase:Fr.refunded_eth.phase,atSim:i,txHash:s.txHash,by:t},Gt(r,i,`ETH refunded to your wallet (${t})`,s.txHash),Es(r,n)}function sm(e){return((ft(e&&e.network||Fn)||{}).escrow||{}).mode==="live"}var am=1e-6;function fm(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+am<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+am?{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 Yo(e,t=yt()){let n=$o(e,t),r=e.timeline,i=(x=>dm(e,x))("ready"),s=bn(e.xmrSource),a=rm(e,n),c=Number(a.arrived!==void 0&&a.arrived!==null?a.arrived:a.received||0),l=s?c>0?0:null:r.lockAtSim,d=a.confirmations,f=s?c>0:l!==null&&n>=l,p=i?i.atSim:null,h=e.escrow&&e.escrow.readyBy?Number(e.escrow.readyBy)*1e3:null,w=e.escrow&&e.escrow.t1?Number(e.escrow.t1)*1e3:null,b=Number(a.arrived!==void 0&&a.arrived!==null?a.arrived:a.received||0)>0,y=(()=>{if(e.side!=="reverse"||h===null)return null;let x=h-_t.hardSec*1e3,C=x+_t.softSec*1e3,U=Zp({poolSeen:b,soft:_t.softSec,hard:_t.hardSec}),W=!b&&yt()>=C,Y=W?x+U*1e3:C;return{startMs:x,atMs:Y,leftMs:Y-yt(),seen:b,extended:W,softSec:_t.softSec,hardSec:_t.hardSec,windowSec:U}})(),v=p!==null&&e.scenario!=="maker_stall"?p+At.makerClaim:null,I=v!==null?v+At.sweep:null,g=l!==null?l+At.readyWindow:null,T=g!==null?g+At.makerReclaim:null,A=p!==null?p+At.t1Refund:null,B=p===null&&T!==null&&n>=T,P={ready:!1,sweep:!1,refund:!1},O="xmr_locked",j="Waiting",D=null,X=null;if(e.settlement){if(O=e.settlement.phase,j=Object.values(Fr).find(x=>x.phase===e.settlement.phase)?.label||"Settled",e.settlement.kind==="refund_eth"&&e.side==="reverse"){let x=um(e),C=c>0;P.sweep=!!(x&&C&&Ss(e)),X=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.":C?"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&&h!==null&&yt()>=h&&(w===null||yt()<w))O="dead_zone",j="Ready deadline passed - the refund opens at T1",P.ready=!1,P.refund=!1,P.refundByAnyone=!1,X="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&&p===null)if(w!==null&&yt()>=w)O="refund_available",j="Claim deadline passed - the refund is open",P.ready=!1,P.refund=!0,P.refundByAnyone=!0,X="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===gn.LOCKED){O="xmr_unlock_pending",j="XMR is on your address but locked on-chain",P.ready=!1;let x=a.lockedUntil||{},C=x.untilHeight!==null&&x.untilHeight!==void 0?"block "+x.untilHeight:x.untilTime!==null&&x.untilTime!==void 0?new Date(Number(x.untilTime)*1e3).toISOString()+" UTC":"a time the sender set";X="The sender set the transaction's unlock_time: "+(a.locked||0)+" XMR is on your address but cannot be spent until "+C+". Ready stays closed until then - confirming now would let the maker take the ETH behind locked XMR."}else if(!a.received)O="maker_locking",j="Waiting for XMR to arrive",X=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===gn.READY){O="xmr_locked",j="XMR received and confirmed ("+d+"/"+r.confTarget+")";let x=fm(e,a);P.ready=x.ok,P.readyAmount=x,X=x.ok?"Confirm that you see the XMR on your address (ready).":x.why}else a.status===gn.SWEPT?(O="success",j="XMR delivered"):(O="xmr_locked",j="XMR received, waiting for confirmations ("+d+"/"+r.confTarget+")",X="About "+Math.max(1,Math.round((r.confTarget-d)*r.blockSim/6e4))+" min left of confirmations.");else if(l===null)n>=r.t0Sim?(O="refund_available",j="Maker did not lock XMR",D=r.t0Sim,P.refund=!0,X="The maker never locked XMR. You can take your ETH back from the escrow - no permission needed."):(O="maker_locking",j="Waiting for the maker to lock XMR",X="If the maker does not lock XMR by T0, you get a refund button.");else if(!f)O="maker_locking",j="Maker is locking XMR";else if(B)O="xmr_reclaimed",j="XMR returned to the maker",D=T,P.refund=!0,X="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)O="xmr_locked",j=d<r.confTarget?`Waiting for Monero confirmations (${d}/${r.confTarget})`:"XMR locked and verified - waiting for you",P.ready=s?a.status===gn.READY:d>=r.confTarget,D=g,X=d<r.confTarget?`About ${Math.max(1,Math.round((r.confTarget-d)*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(v!==null&&n<v)O="ready_wait_claim",j="Waiting for the maker to claim ETH",X="The maker claims the escrow and reveals the secret; your swap wallet uses it to sweep the XMR.";else if(v!==null&&n>=v&&I!==null&&n>=I)O="success",j="XMR delivered",P.sweep=!0;else if(v!==null)O="claimed",j="Secret revealed - sweeping XMR",P.sweep=!0;else{O="refund_available",j="Maker did not claim in time",D=A;let x=e.escrow&&e.escrow.t0?e.escrow.t0*1e3:null,C=e.escrow&&e.escrow.t1?e.escrow.t1*1e3:null,U=yt();C!==null?x!==null?(P.refund=U>=x,P.refundByAnyone=U>=C):(P.refund=U>=C,P.refundByAnyone=P.refund):sm(e)?P.refund=!1:P.refund=n>=A,X=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.":x!==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 H=d>=r.confTarget,m=v!==null&&n>=v,k=[{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:H&&!B,active:f&&!H,atSim:l},{key:"ready",done:p!==null,active:H&&p===null&&!B,atSim:p},{key:"claimed",done:m,active:p!==null&&!m,atSim:v},{key:"swept",done:!!e.settlement&&e.settlement.kind==="success",active:m&&!e.settlement,atSim:xk(e)}];return{swap:e,sim:n,simWallTime:Jn(e,n),phase:O,phaseLabel:j,note:X,conf:d,confTarget:r.confTarget,confProgress:r.confTarget?d/r.confTarget:0,deadlines:{t0:e.escrow&&e.escrow.t0?e.escrow.t0*1e3:e.escrow?null:Jn(e,r.t0Sim),t0Sim:r.t0Sim,lockAtSim:l,readyBy:g!==null?Jn(e,g):null,readyBySim:g,t1:e.escrow&&e.escrow.t1?e.escrow.t1*1e3:A!==null?Jn(e,A):null,t1Sim:A,refundAfterSim:D,refundAfterWall:D!==null?Jn(e,D):null},refundLeftSim:D!==null?D-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:om(a.txids[0],e.xmrSession&&e.xmrSession.network||"stagenet"),error:a.error,sweepTxid:a.sweepTxid},simulated:{evm:!sm(e),xmr:!a.live},can:P,readyDeadline:{atMs:h,soonMs:h!==null&&p===null?h-yt():null,soon:h!==null&&p===null&&h-yt()>0&&h-yt()<=Number(No.readyLeadWarnSec||0)*1e3},xmrAmount:{expected:(()=>{let x=Number(e.xmrAmount);return Number.isFinite(x)&&x>0?x:null})(),seen:a.received!==null&&a.received!==void 0?Number(a.received):null},steps:k,sellWindow:y,terminal:e.settlement,xmrReclaimed:B}}function xk(e){return e.settlement&&e.settlement.kind==="success"?e.settlement.atSim:null}var wl=null,yl=new Set,Mt=new Set;function kk(e){return yl.add(e),()=>yl.delete(e)}function Sk(){for(let e of yl)try{e()}catch(t){console.error(t)}}function vk(e){let t=new Set([String(e&&e.id||"")].filter(Boolean)),r=(()=>{try{return Ss(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 Ss(o)||{}}catch{return{}}})().address===r&&t.add(String(o.id))}return[...t]}async function Ek(){return null}function Ak(e){return new Set(Array.isArray(e)?e.map(String):[]).size}function pm(){let e=rt(),t=!1;for(let n of Object.values(e.swaps)){if(n.settlement)continue;let r=Yo(n);if(!bn(n.xmrSource)&&!n.xmr&&r.deadlines.lockAtSim!==null&&r.sim>=r.deadlines.lockAtSim){let o=tm({swapId:n.id,xmrAmount:n.xmrAmount});if(n.xmr={...o,reclaimed:!1,sweepTxid:null},n.chainMode==="live"){let s=ks();n.xmr.lockHeight=s?s.height:null,n.xmr.lockHeight||qp({force:!0}).then(a=>{if(a&&!n.settlement){let c=rt();c.swaps[n.id]&&(c.swaps[n.id].xmr.lockHeight=a.height,Dt(c))}})}Gt(n,r.sim,"Maker locked XMR on the shared address",o.txid);let i=n.id+":lock";Mt.has(i)||(Mt.add(i),Xo(n.xmrAmount.toFixed(4)+" XMR locked; view key verified","ok")),t=!0}if(bn(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";Mt.has(o)||(Mt.add(o),Xo(r.xmr.received.toFixed(6)+" XMR received; confirmations "+r.xmr.confirmations+"/"+r.xmr.confTarget,"ok")),t=!0}if(!bn(n.xmrSource)&&r.can.sweep&&r.phase==="success"){let o=r.sim;n.xmr.sweepTxid=ml({swapId:n.id}).txid,n.settlement={kind:"success",phase:Fr.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";Mt.has(i)||(Mt.add(i),Xo("Swap "+n.id+" complete: XMR is on your address","ok")),t=!0;continue}if(!bn(n.xmrSource)&&r.can.refund&&r.refundLeftSim!==null&&r.refundLeftSim<=-At.watchtowerGrace){let o=r.sim,i=hl({swapId:n.id,by:"watchtower"});n.settlement={kind:"refund_eth",phase:Fr.refunded_eth.phase,atSim:o,txHash:i.txHash,by:"watchtower"},Gt(n,o,"Watchtower refunded your ETH",i.txHash);let s=n.id+":refund";Mt.has(s)||(Mt.add(s),Xo("Watchtower refunded the ETH escrow of swap "+n.id,"bad")),t=!0;continue}if(!bn(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";Mt.has(o)||(Mt.add(o),Xo("Maker took the XMR back: no ready() call in time","bad")),t=!0}}t&&Dt(e)}var gl={fn:null};function Nk(e){gl.fn=e}function Xo(e,t){gl.fn&&gl.fn(e,t)}function _k(e=400){wl&&clearInterval(wl),wl=setInterval(()=>{try{pm()}catch(t){console.error(t)}Sk()},e)}Ko();var xn={};Fe(xn,{ORDER_CONTEXT_VERSION:()=>hm,orderContextString:()=>Bk});var hm="ninsei-order-v3",Ik=e=>String(e??"").trim().toLowerCase(),Tk=e=>{if(typeof e=="bigint")return e.toString(10);if(typeof e=="number")return String(Math.trunc(e));let t=Ik(e);return t.startsWith("0x")?BigInt(t).toString(10):t},mm=["chainId","factory","locker","claimer","amount","readyBy","t1","salt"];function Bk(e){if(!e||typeof e!="object")throw new Error("order context needs an object with the order fields");let t=mm.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 hm+"|"+mm.map(n=>Tk(e[n])).join("|")}var Ns={};Fe(Ns,{createOrderBuilder:()=>Hk});Ko();function Lr(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 wm({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=E=>{let F=String(E??""),L=[];for(let z=0;z<F.length;z++){let $=F.codePointAt(z);$>65535&&z++,$<128?L.push($):$<2048?L.push(192|$>>6,128|$&63):$<65536?L.push(224|$>>12,128|$>>6&63,128|$&63):L.push(240|$>>18,128|$>>12&63,128|$>>6&63,128|$&63)}return new Uint8Array(L)},d=E=>typeof E=="string"?E:E.toHex?E.toHex():String(E);function f(E){let F=E.replace(/^0x/i,""),L=new Uint8Array(F.length/2);for(let z=0;z<L.length;z++)L[z]=parseInt(F.substr(z*2,2),16);return L}let p=E=>E.toString(16).padStart(64,"0");function h(E){let F=0n;for(let L of E)F=F<<8n|BigInt(L);return F}function w(E){let F=0n;for(let L=E.length-1;L>=0;L--)F=F<<8n|BigInt(E[L]);return F}function b(E){let F=E.reduce(($,ee)=>$+ee.length,0),L=new Uint8Array(F),z=0;for(let $ of E)L.set($,z),z+=$.length;return L}function y(E,F){let L=r(b(F.map(z=>typeof z=="string"?f(z):z)));if(L.length!==64)throw new Error("challenge: sha3_512 returned "+L.length+" bytes instead of 64");return w(L)%E.order}function v(E){let F=w(o(64))%E.order;return F===0n?1n:F}function I(E,F){return E>>BigInt(F)&1n}function g(E,F,L){let $=((typeof L=="bigint"?L:BigInt(L))%E.order+E.order)%E.order;return $===0n?E.P.ZERO:F===E.Galt?F.multiply($):F.multiplyUnsafe($)}function T(E,F,L){return g(E,L||E.G,typeof F=="bigint"?F:BigInt(F))}let A=(E,F)=>E.add(F),B=(E,F)=>E.subtract(F),P=E=>f(E.toHex()),O=E=>f(p(E));function j(E){let F=E.next();for(;!F.done;)F=E.next();return F.value}let D=async E=>typeof E=="function"?await E():globalThis.scheduler&&typeof globalThis.scheduler.yield=="function"?await globalThis.scheduler.yield():await new Promise(F=>setTimeout(F,0));function*X(E,F){let L=[],z=[],$=0n,ee=1n;for(let ne=0;ne<a;ne++){if(ne===a-1){let de=m(ee,E.order);L[ne]=(E.order-$%E.order)*de%E.order}else L[ne]=v(E),$=($+L[ne]*ee)%E.order,ee=ee*2n%E.order;let le=I(F,ne);z.push(A(T(E,le),T(E,L[ne],E.Galt))),yield ne+1}return{rs:L,cs:z}}function H(E,F){return j(X(E,F))}function m(E,F){let[L,z]=[E%F,F],[$,ee]=[1n,0n];for(;z!==0n;){let ne=L/z;[L,z]=[z,L-ne*z],[$,ee]=[ee,$-ne*ee]}if(L!==1n)throw new Error("modInv: not invertible");return($%F+F)%F}function*k(E,F){let L=F[0];for(let z=1;z<F.length;z++)L=A(L,T(E,2n**BigInt(z)%E.order,F[z])),yield{phase:"sum",done:z,total:F.length};return L}function x(E,F){return j(k(E,F))}function C(E,F,L,z,$,ee,ne){let le=v(c.A),de=v(c.B),ie=(Xe,Pt)=>[l(ne),P(L),P(z),P(Xe),P(Pt)],q=y(c.A,ie(T(c.A,le,c.A.Galt),T(c.B,de,c.B.Galt)),ne),oe=y(c.B,ie(T(c.A,le,c.A.Galt),T(c.B,de,c.B.Galt)),ne);if((E===1n||E===1?1n:0n)===0n){let Xe=v(c.A),Pt=v(c.B),xo=B(L,c.A.G),ko=B(z,c.B.G),So=y(c.A,ie(B(T(c.A,Xe,c.A.Galt),g(c.A,xo,q)),B(T(c.B,Pt,c.B.Galt),g(c.B,ko,oe))),ne),vo=y(c.B,ie(B(T(c.A,Xe,c.A.Galt),g(c.A,xo,q)),B(T(c.B,Pt,c.B.Galt),g(c.B,ko,oe))),ne);return{eA:So,eB:vo,a0:Xe,a1:(le+So*$)%c.A.order,b0:Pt,b1:(de+vo*ee)%c.B.order}}let ce=v(c.A),Me=v(c.B),Ue=y(c.A,ie(B(T(c.A,ce,c.A.Galt),g(c.A,L,q)),B(T(c.B,Me,c.B.Galt),g(c.B,z,oe))),ne),qe=y(c.B,ie(B(T(c.A,ce,c.A.Galt),g(c.A,L,q)),B(T(c.B,Me,c.B.Galt),g(c.B,z,oe))),ne);return{eA:q,eB:oe,a0:(le+Ue*$)%c.A.order,a1:ce,b0:(de+qe*ee)%c.B.order,b1:Me}}let U=E=>({eA:p(E.eA),eB:p(E.eB),a0:p(E.a0),a1:p(E.a1),b0:p(E.b0),b1:p(E.b1)});function W(E,F,L,z,$){let ee=v(E),ne=T(E,ee),le=y(E,[l(z),l("ninsei-dleq-pok|"+$),P(L),P(ne)]);return{R:d(ne),s:p((ee+le*F)%E.order)}}function Y(E,F,L,z,$){if(!L||typeof L!="object"||typeof L.R!="string"||typeof L.s!="string")return!1;let ee,ne;try{ee=E.P.fromHex(L.R.replace(/^0x/i,"")),ne=BigInt(String(L.s).startsWith("0X")?"0x"+String(L.s).slice(2):String(L.s).startsWith("0x")?L.s:"0x"+L.s)}catch{return!1}let le=y(E,[l(z),l("ninsei-dleq-pok|"+$),P(F),P(ee)]);return T(E,ne).equals(A(ee,g(E,F,le)))}function*N(E,F){E=typeof E=="bigint"?E:BigInt(E);let L=T(c.A,E),z=T(c.B,E);yield{phase:"prepare",done:0,total:a};let $=X(c.A,E),ee=X(c.B,E);for(let ie=0;ie<a;ie++){let q=$.next(),oe=ee.next();if(q.done||oe.done)throw new Error("prepareProof: commitments ended early");yield{phase:"prepare",done:ie+1,total:a}}let ne=$.next().value,le=ee.next().value,de=[];for(let ie=0;ie<a;ie++)de.push({i:ie,bit:I(E,ie)===1n?1:0,cA:d(ne.cs[ie]),cB:d(le.cs[ie]),rA:p(ne.rs[ie]),rB:p(le.rs[ie])});return yield{phase:"know",done:a,total:a},{XA:d(L),XB:d(z),context:String(F??""),pokA:W(c.A,E,L,F,"A"),pokB:W(c.B,E,z,F,"B"),bits:de}}function S(E,F){return j(N(E,F))}async function _(E,F,L={}){let z=Number.isSafeInteger(L.chunkBits)&&L.chunkBits>0?Math.min(L.chunkBits,a):8,$=N(E,F),ee=0;for(;;){let ne=$.next();if(ne.done)return ne.value;ee+=1,typeof L.onPrepare=="function"&&L.onPrepare(ne.value),ee%z===0&&await D(L.yieldTo)}}function R(E,F){let L=C(E.bit===1?1n:0n,E.i,c.A.P.fromHex(String(E.cA).replace(/^0x/,"")),c.B.P.fromHex(String(E.cB).replace(/^0x/,"")),BigInt("0x"+String(E.rA).replace(/^0x/,"")),BigInt("0x"+String(E.rB).replace(/^0x/,"")),F);return{i:E.i,cA:E.cA,cB:E.cB,sig:U(L)}}function M(E,F){let L=new Map(F.map($=>[$.i,$])),z=[];for(let $=0;$<a;$++){let ee=L.get($);if(!ee)throw new Error("assembleProof: no part for bit "+$);z.push({cA:ee.cA,cB:ee.cB,sig:ee.sig})}return{XA:E.XA,XB:E.XB,pokA:E.pokA,pokB:E.pokB,proofs:z}}function K(E,F,L){let z=S(E,F),$=[];for(let ee=0;ee<a;ee++)L&&(ee%16===0||ee===a-1)&&L(ee+1,a),$.push(R(z.bits[ee],z.context));return M(z,$)}async function G(E,F,L={}){let z=Number.isSafeInteger(L.chunkBits)&&L.chunkBits>0?Math.min(L.chunkBits,a):4,$=await _(E,F,{chunkBits:Number.isSafeInteger(L.prepareChunkBits)&&L.prepareChunkBits>0?L.prepareChunkBits:8,yieldTo:L.yieldTo,onPrepare:L.onPrepare}),ee=[];for(let ne=0;ne<a;ne++)ee.push(R($.bits[ne],$.context)),((ne+1)%z===0||ne===a-1)&&(typeof L.onBit=="function"&&L.onBit(ne+1,a),await D(L.yieldTo));return M($,ee)}function Z(E,F){if(E.name!=="ed25519")return!0;try{return F.isTorsionFree()===!0}catch{return!1}}function*V(E,F,L={}){if(!E||typeof E!="object")return{ok:!1,reason:"proof: an object is expected"};if(typeof E.XA!="string"||typeof E.XB!="string")return{ok:!1,reason:"proof: no XA or XB"};if(!Array.isArray(E.proofs))return{ok:!1,reason:"proof: no parts list"};if(E.proofs.length!==a)return{ok:!1,reason:"proof: "+E.proofs.length+" parts, expected "+a};let z=L.requireKnowledge!==!1,$=(oe,se)=>oe.P.fromHex(String(se).replace(/^0x/i,"")),ee,ne,le,de;try{if(ee=$(c.A,E.XA),ne=$(c.B,E.XB),ne.equals(c.B.P.ZERO))return{ok:!1,reason:"proof: the subject point is the identity"};if(!Z(c.B,ne))return{ok:!1,reason:"proof: XB is not in the prime-order subgroup"}}catch(oe){return{ok:!1,reason:"proof: XA or XB is unparsable ("+String(oe&&oe.message||oe)+")"}}if(z)try{if(!Y(c.A,ee,E.pokA,F,"A"))return{ok:!1,reason:"proof: the secp256k1 knowledge proof did not verify"};if(!Y(c.B,ne,E.pokB,F,"B"))return{ok:!1,reason:"proof: the ed25519 knowledge proof did not verify"}}catch(oe){return{ok:!1,reason:"proof: the knowledge proof is unparsable ("+String(oe&&oe.message||oe)+")"}}try{le=E.proofs.map((oe,se)=>{try{return $(c.A,oe.cA)}catch(ce){throw new Error("bit "+se+": "+String(ce&&ce.message||ce))}}),de=E.proofs.map((oe,se)=>{try{return $(c.B,oe.cB)}catch(ce){throw new Error("bit "+se+": "+String(ce&&ce.message||ce))}})}catch(oe){return{ok:!1,reason:"proof: "+String(oe&&oe.message||oe)}}if(!(yield*k(c.A,le)).equals(ee))return{ok:!1,reason:"the commitment sum does not give X on secp256k1"};if(!(yield*k(c.B,de)).equals(ne))return{ok:!1,reason:"the commitment sum does not give X on ed25519"};for(let oe=0;oe<E.proofs.length;oe++){let se=E.proofs[oe];try{if(!Z(c.B,de[oe]))return{ok:!1,reason:"bit "+oe+": the commitment is not in the prime-order subgroup"};let ce=se.cA,Me=se.cB,Ue={};for(let Ti of["eA","eB","a0","a1","b0","b1"]){let Va=se.sig[Ti],$a=String(Va);Ue[Ti]=BigInt(/^0x/i.test($a)?$a:"0x"+$a)}let qe=$(c.A,ce),Xe=$(c.B,Me),Pt=(Ti,Va)=>[l(F),P(qe),P(Xe),P(Ti),P(Va)],xo=T(c.A,Ue.a1,c.A.Galt),ko=g(c.A,qe,Ue.eA),So=T(c.B,Ue.b1,c.B.Galt),vo=g(c.B,Xe,Ue.eB),kg=y(c.A,Pt(B(xo,ko),B(So,vo)),F),Sg=y(c.B,Pt(B(xo,ko),B(So,vo)),F),Nu=T(c.A,Ue.a0,c.A.Galt),_u=g(c.A,B(qe,c.A.G),kg),Iu=T(c.B,Ue.b0,c.B.Galt),Tu=g(c.B,B(Xe,c.B.G),Sg),vg=y(c.A,Pt(B(Nu,_u),B(Iu,Tu)),F),Eg=y(c.B,Pt(B(Nu,_u),B(Iu,Tu)),F);if(vg!==Ue.eA||Eg!==Ue.eB)return{ok:!1,reason:"bit "+oe+": challenges did not match"}}catch(ce){return{ok:!1,reason:"bit "+oe+": fields are unparsable ("+String(ce&&ce.message||ce)+")"}}yield{phase:"verify",done:oe+1,total:E.proofs.length}}return{ok:!0}}function J(E,F,L={}){return j(V(E,F,L))}async function re(E,F,L={}){let z=V(E,F,L),$=null,ee=0;for(;;){let ne=z.next();if(ne.done)return ne.value;let le=ne.value&&ne.value.phase?ne.value.phase:null;le!==$&&($=le,ee=0),ee+=1,typeof L.onProgress=="function"&&L.onProgress(ne.value);let de=$==="sum"?16:Number.isSafeInteger(L.verifyChunkBits)&&L.verifyChunkBits>0?Math.min(L.verifyChunkBits,a):2;ee%de===0&&await D(L.yieldTo)}}return{BITS:a,curves:c,prove:K,proveChunked:G,verify:J,verifyChunked:re,prepareProof:S,prepareProofChunked:_,proveBit:R,assembleProof:M,torsionFree:Z}}var ym="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 gm(){return globalThis.ARRAKIS_ALLOW_HALFENC===!0}function bm({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(b){let y=0n;for(let v of b)y=y<<8n|BigInt(v);return y}function c(b){for(let y=0;y<256;y++){let v=a(r(32));if(v>0n&&v<b)return v}throw new Error("randScalar: failed in 256 attempts")}let l=b=>b.toString(16).padStart(64,"0");function d(){let b=c(i);return{priv:b,pub:e.Point.BASE.multiply(b).toHex()}}function f(b,y){let v=n(Uint8Array.from(Buffer.concat([Buffer.from(b.replace(/^0x/,""),"hex"),Buffer.from(y||"","utf8")])));return a(v)%s}function p(b,y,v){if(!gm())throw new Error(ym);if(!(b>0n&&b<s))throw new Error("seal: half outside min(l, n)");let I=e.Point.fromHex(y.replace(/^0x/,"")),g=c(i),T=e.Point.BASE.multiply(g),A=I.multiply(g),B=f(A.toHex(),v),P=O=>"0x"+String(O).replace(/^0x/i,"").toLowerCase();return{recipient:P(y),ephemeral:P(T.toHex()),masked:"0x"+l((b+B)%s),context:v||""}}function h(b,y,v){if(!gm())return{ok:!1,reason:ym};if(!b||!b.ephemeral||!b.masked)return{ok:!1,reason:"incomplete envelope"};let g=e.Point.fromHex(b.ephemeral.replace(/^0x/,"")).multiply(y),T=f(g.toHex(),b.context),A=(BigInt(b.masked)-T+s)%s;if(A===0n)return{ok:!1,reason:"restored zero"};if(!v)return{ok:!0,x:A};let B=t.Point.BASE.multiply(A).toHex(),P=t.Point.fromHex(v.startsWith("0x")?v.slice(2):v).toHex();return B!==P?{ok:!1,reason:"the ciphertext holds a different half"}:{ok:!0,x:A}}function w(b){let y=n(As(b));return"0x"+kn(y)}return{LIMIT:s,recipientKeyPair:d,seal:p,open:h,packSealed:bl,unpackSealed:Rk,sealedCommitmentOf:w}}var xm=1;function kn(e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}function Ck(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 Ok(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 As=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 bl(e){if(!e||!e.recipient||!e.ephemeral||!e.masked)throw new Error("packSealed: incomplete envelope");let t=As(e.recipient),n=As(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=Ck(e.context);if(o.length>255)throw new Error("packSealed: context longer than 255 bytes");return"0x"+kn(Uint8Array.of(xm))+kn(t)+kn(n)+r+o.length.toString(16).padStart(2,"0")+kn(o)}function Rk(e){let t=As(e);if(t.length<100)throw new Error("unpackSealed: envelope shorter than 100 bytes");if(t[0]!==xm)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:Ok(t.slice(100))}}$n();function Hk({ed25519:e,secp256k1:t,keccak256:n,sha3_512:r,randomBytes:o}){let i=Wo({ed25519:e,secp256k1:t,keccak256:n,randomBytes:o}),s=wm({ed25519:e,secp256k1:t,keccak256:n,sha3_512:r,randomBytes:o}),a=bm({secp256k1:t,ed25519:e,keccak256:n,randomBytes:o});function c(g,T=!1,A){let B=i.newHalf(),P=i.publicHalves(B),O=i.newHalf(),j=i.publicHalves(O).ed,D=a.recipientKeyPair(),X=s.prove(B,g,A);return{half:B,pub:P,viewHalf:O,viewPub:j,enc:D,proof:X,standIn:T}}async function l(g,T=!1,A={}){let B=i.newHalf(),P=i.publicHalves(B),O=i.newHalf(),j=i.publicHalves(O).ed,D=a.recipientKeyPair(),X=await s.proveChunked(B,g,A);return{half:B,pub:P,viewHalf:O,viewPub:j,enc:D,proof:X,standIn:T}}function d(g,T,A,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 O=null;try{let X=t.Point.fromHex(String(g.proof.XA).replace(/^0x/,"")).toBytes(!1).slice(1);O="0x"+Array.from(n(X),H=>H.toString(16).padStart(2,"0")).join("")}catch{O=null}let j=D=>String(D||"").replace(/^0x/,"").toLowerCase().slice(-40);if(!O||j(O)!==j(g.commitHalfClaimer))return{ok:!1,reason:"the proven secp256k1 point does not match commitHalfClaimer: "+(O||"unparsed")+" vs "+g.commitHalfClaimer}}else return{ok:!1,reason:"the counterparty side carries no commitHalfClaimer"};if(A&&B){let O=a.open(a.unpackSealed(A),B,g.pub.ed);if(!O.ok)return{ok:!1,reason:"the counterparty envelope does not confirm the half: "+O.reason}}return{ok:!0}}function f(g,T,A,B){return d(g,T,A,B,s.verify(g.proof,T))}async function p(g,T,A,B,P={}){let O=await s.verifyChunked(g.proof,T,P);return d(g,T,A,B,O)}function h(g,T,A){let B=a.seal(T,g.enc.pub,A),P=bl(B);return{sealed:B,bytes:P,commitment:a.sealedCommitmentOf(P)}}function w(g,T,A){return a.open(a.unpackSealed(g),T,A)}function b(g){return Lr(g,t,n)}function y(g,T){return i.combinePublic(g.pub.ed,T.pub.ed)}function v(g){return i.publicHalves(typeof g=="bigint"?g:BigInt(g)).ed}function I({ownSpendHalf:g,ownViewHalf:T,otherSpendPoint:A,otherViewPoint:B,network:P}){return ws({halves:i,addressFromKeys:mn,deps:{keccak256:n},ownSpendHalf:g,ownViewHalf:T,otherSpendPoint:A,otherViewPoint:B,network:P})}return{halves:i,dleq:s,enc:a,newSide:c,newSideChunked:l,verifySide:f,verifySideChunked:p,sealFor:h,openFrom:w,jointAddressPoint:y,pointOf:v,jointAddress:I,halfCommitment:b}}var He={};Fe(He,{ASYNC_DEFAULT_NEED:()=>Nl,ASYNC_NEEDS:()=>Vm,ASYNC_SETTLES:()=>Go,EIP2612_METHOD:()=>Zo,ERC20_METHOD:()=>qm,ESCROW_METHODS:()=>Qt,FACTORY_METHODS:()=>kl,FACTORY_READS:()=>_s,GAS_CREATE_ORDER_AND_FUND:()=>Wm,ORDER_CREATED_TOPIC:()=>Is,ORDER_CREATED_TOPICS:()=>Fk,ORDER_CREATED_TOPIC_V1:()=>km,QUOTE_FIELDS:()=>xl,address:()=>al,asyncRouteChains:()=>Xm,asyncRouteChoice:()=>Gm,asyncRouteForChain:()=>Zk,asyncRouteInjection:()=>Gk,asyncRouteProvider:()=>Qo,asyncRouteProviderIds:()=>Il,asyncRouteProviderSettles:()=>Ym,asyncRouteProvidersForChain:()=>Rs,asyncRouteVerdict:()=>Tl,balanceOf:()=>Kp,chainIdOf:()=>jp,connect:()=>Xp,connectInjected:()=>ll,currentProvider:()=>Wp,decodeAddress:()=>Ts,decodeBytes32:()=>Pm,decodeImplementation:()=>Em,decodeImplementationCodeHash:()=>Am,decodeStatus:()=>Cs,decodeUint64:()=>Hm,disconnect:()=>Yp,encodeApprove:()=>nS,encodeClaim:()=>Im,encodeCreateOrderAndFund:()=>vl,encodeDomainSeparator:()=>tS,encodeFactoryRead:()=>jk,encodeMarkReady:()=>_m,encodeNonces:()=>eS,encodePermit:()=>Jk,encodePredict:()=>Sl,encodeRead:()=>Rm,encodeRefund:()=>Bm,encodeStatus:()=>Bs,encodeT1:()=>Cm,encodeTermsHash:()=>Om,escrowFromReceipt:()=>Km,escrowNativeWei:()=>zk,fundOrder:()=>Al,fundOrderLive:()=>aS,fundingReceiptVerdict:()=>Os,isConnected:()=>qn,newSecret:()=>Mm,orderTerms:()=>Fm,permitSupportVerdict:()=>rS,readCode:()=>Gp,readContract:()=>ul,readReceipt:()=>fl,refreshBalances:()=>Zn,restore:()=>zp,restoreInjected:()=>cl,sendTransaction:()=>pl,setAsyncRouteInjection:()=>Yk,simulateEscrowFunding:()=>sS,status:()=>Up,subscribe:()=>Mp,switchChain:()=>dl,testOrderTerms:()=>Um,toWei:()=>jm,usdcWithoutEthVerdict:()=>oS,verifyFactoryImplementation:()=>Nm,verifyFactoryImplementationOnChain:()=>Wk,wallets:()=>iS,word:()=>Se});var kl={predict:"0x76e3fdc8",createOrderAndFund:"0x50db6721"},Is="0x09add13cca47b227c377447295bfaa00ef3169bfed0f5513d06f8be04af78aad",km="0xa22cdabaed3cce4f51dde71626a108ffe9c7bc4216fd14d5e719f892e2fd8ab0",Fk=Object.freeze([Is,km]),xl=["provider","quoteKey","registry","cashier","locker","claimer","amount","readyBy","t1","salt","commitHalfClaimer","edPointClaimer","chainId","feeBps","fee","feeRecipient","validUntil","nonce","xmrAmount","claimTip","commitHalfLocker","edPointLocker","edViewPointLocker"],Lk=["provider","quoteKey","registry","cashier","locker","claimer","feeRecipient"],Dk=["salt","commitHalfClaimer","edPointClaimer","commitHalfLocker","edPointLocker","edViewPointLocker"];function Se(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 Dr=e=>{let t=String(e??"").trim();return/^[0-9a-fA-F]{64}$/.test(t)?"0x"+t.toLowerCase():t};function Mk(e){for(let n of xl)if(e[n]===void 0||e[n]===null||e[n]==="")throw new Error("the quote has no field: "+n);for(let n of Lk)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 Dk)if(!/^(0x)?[0-9a-fA-F]{64}$/.test(String(e[n]).trim()))throw new Error("quote field "+n+" is not bytes32");let t={provider:Se(e.provider,32),quoteKey:Se(e.quoteKey,32),registry:Se(e.registry,32),cashier:Se(e.cashier,32),locker:Se(e.locker,32),claimer:Se(e.claimer,32),amount:Se(e.amount,32),readyBy:Se(e.readyBy,32),t1:Se(e.t1,32),salt:Se(Dr(e.salt),32),commitHalfClaimer:Se(Dr(e.commitHalfClaimer),32),edPointClaimer:Se(Dr(e.edPointClaimer),32),chainId:Se(e.chainId,32),feeBps:Se(e.feeBps,32),fee:Se(e.fee,32),feeRecipient:Se(e.feeRecipient,32),validUntil:Se(e.validUntil,32),nonce:Se(e.nonce,32),xmrAmount:Se(e.xmrAmount,32),claimTip:Se(e.claimTip,32),commitHalfLocker:Se(Dr(e.commitHalfLocker),32),edPointLocker:Se(Dr(e.edPointLocker),32),edViewPointLocker:Se(Dr(e.edViewPointLocker),32)};return xl.map(n=>t[n]).join("")}function Uk(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),Se("0x"+n,32)+Se("0x"+r,32)+Se(o,32)}function Sm(e){return Mk(e)+Uk(e.signature)}function Sl(e){return kl.predict+Sm(e)}function vl(e){return kl.createOrderAndFund+Sm(e)}var vm=(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 Ts(e){return"0x"+vm(e,"predict()").slice(24,64)}var _s={implementation:"0x5c60da1b",implementationCodeHash:"0xbc0a3981"};function jk(e){let t=_s[e];if(typeof t!="string"||!/^0x[0-9a-f]{8}$/.test(t))throw new Error("no such factory read: "+e);return t}function Em(e){return Ts(e)}function Am(e){return"0x"+vm(e,"implementationCodeHash()")}function Nm({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 Wk({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:_s.implementation}),s=await t({to:e,data:_s.implementationCodeHash})}catch{return{ok:!1,why:"implementation-unreadable",factory:String(e).toLowerCase()}}let a,c;try{a=Em(i),c=Am(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{...Nm({implementation:a,implementationCodeHash:c,code:l,hashCode:o,policy:r}),implementation:a,implementationCodeHash:c}}var Mr={};Fe(Mr,{ESCROW_METHODS:()=>Qt,decodeBytes32:()=>Pm,decodeStatus:()=>Cs,decodeUint64:()=>Hm,encodeClaim:()=>Im,encodeMarkReady:()=>_m,encodeRead:()=>Rm,encodeRefund:()=>Bm,encodeStatus:()=>Bs,encodeT1:()=>Cm,encodeTermsHash:()=>Om,orderTerms:()=>Fm});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 _m(){return Qt.markReady}function Im(e){return Qt.claim+Tm(e,"secret")}function Tm(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 Bm(e){return Qt.refund+Tm(e,"half")}function Bs(){return Qt.status}function Cm(){return Qt.t1}function Om(){return Qt.termsHash}function Rm(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 El=(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 Pm(e,t="value"){return"0x"+El(e,t,1)}function Hm(e,t="value"){let n=El(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 Cs(e){let t=El(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 Fm({locker:e,claimer:t,commitHalfLocker:n,commitHalfClaimer:r,edPointLocker:o,edPointClaimer:i,amount:s,readyBy:a,t1:c}){for(let[l,d]of Object.entries({locker:e,claimer:t,commitHalfLocker:n,commitHalfClaimer:r,edPointLocker:o,edPointClaimer:i,amount:s}))if(d==null||d==="")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 Kk(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 Lm=(e,t)=>String(e||"").toLowerCase()===String(t||"").toLowerCase(),Vk=e=>!e||/^0x0{40}$/i.test(String(e)),$k=null;function Dm(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=Kk(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&&Vk(e.feeRecipient))throw new Error("with a non-zero rate the fee recipient must be named");let o=Lm(e.locker,e.provider),i=Lm(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 $k=a,a}function Mm(){let e=new Uint8Array(32);return crypto.getRandomValues(e),"0x"+Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function Um({locker:e,claimer:t,commitHalfLocker:n,commitHalfClaimer:r,edPointLocker:o,edPointClaimer:i,edViewPointLocker:s,amountWei:a,salt:c,claimWindowSeconds:l=3600,readyWindowSeconds:d=14400,readyBy:f,t1:p}){for(let[g,T]of Object.entries({commitHalfLocker:n,commitHalfClaimer:r,edPointLocker:o,edPointClaimer:i,edViewPointLocker:s}))if(!T)throw new Error("order term not set: "+g);let h=Math.floor(Date.now()/1e3),w=f!=null&&f!=="",b=p!=null&&p!=="",y=w?Number(f):h+d,v=b?Number(p):y+l;if(!(v>y))throw new Error("the settlement deadline must be later than the readiness deadline: t1="+v+", readyBy="+y);let I=ec({nowSec:h,readyBy:y,t1:v,...No});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(v),salt:c}}function jm(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 zk({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=jm(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 Wm=700000n;function Km(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()!==Is||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 Os(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=Km(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 Xk(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 Al({factory:e,locker:t,claimer:n,commitHalfLocker:r,commitHalfClaimer:o,edPointLocker:i,edPointClaimer:s,edViewPointLocker:a,salt:c,amountWei:l,amountLabel:d,claimWindowSeconds:f,readyWindowSeconds:p,readyBy:h,t1:w,quote:b,call:y,send:v,receipt:I,onStep:g,onPredicted:T}){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(!b||typeof b!="object")throw new Error("a signed quote is required: the factory takes a quote, not bare order terms");let A=c||Mm(),B=Um({locker:t,claimer:n,commitHalfLocker:r,commitHalfClaimer:o,edPointLocker:i,edPointClaimer:s,edViewPointLocker:a,amountWei:l,salt:A,claimWindowSeconds:f,readyWindowSeconds:p,readyBy:h,t1:w});g?.("computing the escrow address");let P={...b,commitHalfLocker:B.commitHalfLocker,edPointLocker:B.edPointLocker,edViewPointLocker:B.edViewPointLocker},O=(R,M)=>String(R??"").replace(/^0x/i,"").toLowerCase()===String(M??"").replace(/^0x/i,"").toLowerCase();for(let R of["locker","claimer","amount","readyBy","t1","salt","commitHalfClaimer","edPointClaimer"])if(!O(b[R],B[R]))throw new Error("the quote and the order terms diverge on field "+R);let j=await y({to:e,data:Sl(P)}),D=Ts(j);if(!/^0x[0-9a-fA-F]{40}$/.test(D)||/^0x0{40}$/i.test(D))throw new Error("the factory returned an invalid escrow address: "+String(j).slice(0,40));g?.("checking the order is not already on chain");let X=null;try{let R=await y({to:D,data:Bs()});X=String(R||"").replace(/^0x/,"").length>=256?{status:Cs(R)}:{status:null}}catch(R){X={error:String(R&&R.message||R)}}let H=tc({status:X.status,error:X.error,address:D});if(H.blocks)throw new Error("signature not started: "+H.reason);g?.("reading the escrow fee from the signed quote");let m=Dm(b),k=m.totalWei,x=m.feeWei>0n?" (order "+l+" + fee "+m.feeWei+")":"";g?.("locking "+(d||"funds")+x+" in one transaction - confirm in wallet"),typeof T=="function"&&await T({escrow:D,salt:A,terms:B});let C=vl(P),U=await v({to:e,data:C,value:"0x"+k.toString(16),gas:Wm}),W=null,Y=null,N={status:"pending",reason:"no-receipt-reader"};if(typeof I=="function"){let R=await Xk(I,U);if(N=Os(R,{factory:e,expectedEscrow:D}),N.status==="reverted"){let M=new Error("the funding transaction reverted");throw M.code="contract-reverted",M.receiptStatus=0,M}N.status==="funded"?(W=N.escrow,Y=N.birthBlock,W!==String(D).toLowerCase()&&(console.warn("[escrow] receipt address "+W+" != predicted "+D+" - using the receipt one"),g?.("receipt address differs from predicted - using the receipt one"))):g?.(R?"receipt has no matching OrderCreated - funding is pending, not funded":"no receipt yet - funding is pending, not funded")}let S=U,_={feeWei:m.feeWei,feeTotalWei:k,feeBps:m.bps,feeWasLegacyFactory:!!m.legacy,predictedEscrow:D,salt:A,terms:B,createHash:U,lockHash:S};return N.status!=="funded"?{..._,escrow:null,birthBlock:null,funded:!1,pending:!0,pendingReason:N.reason}:{..._,escrow:W,escrowMismatch:W!==String(D).toLowerCase(),birthBlock:Y,funded:!0,pending:!1}}var Vm=["native","wrapped"],Nl="native",Go=Object.freeze({NATIVE:"native",WRAPPED:"wrapped"}),Sn=[],$m=()=>Sn.length===0?null:Sn.length===1?Sn[0]:Sn,Yk=(e=null)=>(Array.isArray(e)?Sn=e.filter(Boolean):e&&typeof e=="object"?Sn=[e]:Sn=[],$m()),Gk=()=>$m(),zm=e=>Sn.filter(t=>t&&Number(t.chainId)===Number(e)),Qo=e=>e&&Ci[e]||null,Il=()=>Object.keys(Ci).sort(),Xm=e=>Object.keys((Qo(e)||{}).networks||{}).map(Number).filter(Number.isFinite).sort((t,n)=>t-n),Ym=e=>{let t=Qo(e);return t?t.settles===void 0?null:t.settles:null},Qk=(e,t={})=>t.settles?t.settles:Ym(e),_l=(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:Qk(e,r)}},Rs=e=>{let t=Number(e),n=new Map;for(let r of Il()){let o=Qo(r),i=o.networks&&o.networks[t];i&&n.set(r,_l(r,t,i))}for(let r of zm(t))n.set(r.id,_l(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))},Zk=(e,t=null)=>{let n=Number(e);if(t){let o=zm(n).find(i=>i.id===t);return o?_l(o.id,n,{slug:o.slug,orderbook:o.orderbook,contract:o.contract},{settles:o.settles,venue:o.venue,shape:o.shape}):Rs(n).find(i=>i.id===t)||null}let r=Rs(n);return r.length?r[0]:null},qk=e=>Xm(e||Il()[0]||null),Gm=({chainId:e=null,providerId:t=null,need:n=Nl}={})=>{let r=Number(e),o=Number.isFinite(r),i=Vm.includes(n)?n:Nl,s=o?Rs(r):[];if(!s.length)return{ok:!1,reason:"no-async-provider",chainId:o?r:null,need:i,provider:t||null,known:qk(t)};let a=null;if(t&&(a=s.find(h=>h.id===t)||null,!a))return{ok:!1,reason:"no-async-provider",chainId:r,need:i,provider:t,known:s.map(h=>h.id)};let c=a?[a]:s,l=c.filter(h=>h.settles===i);if(l.length){let h=l[0];return{ok:!0,kind:"single",...h,need:i,provider:h.id,legs:[h]}}let d=c.filter(h=>h.settles===Go.WRAPPED),f=s.filter(h=>h.settles===Go.NATIVE);if(i===Go.NATIVE&&d.length&&f.length){let h=d[0],w=f[0];return{ok:!0,kind:"composition",need:i,chainId:r,provider:h.id,venue:h.venue,shape:"async",orderbook:h.orderbook,legs:[h,w]}}return{ok:!1,reason:i===Go.NATIVE&&d.length&&!f.length?"no-native-async-provider":"no-async-provider",chainId:r,need:i,missing:i,provider:(a||d[0]||s[0]).id,known:s.map(h=>h.id)}},Tl=Gm;var qm={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()"}},Ls=e=>String(e??"").replace(/^0x/,""),Hs=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),Fs=e=>Ls(e).toLowerCase().padStart(64,"0"),Ps=e=>BigInt(e).toString(16).padStart(64,"0"),Qm=e=>{let t=Ls(e);return t.length===0||t.length%2?null:t.length/2},Zm=e=>{if(e==null||e==="")return null;try{return BigInt(typeof e=="bigint"?e:String(e))}catch{return null}};function Jk({owner:e,spender:t,value:n,deadline:r,signature:o}){if(!Hs(e)||!Hs(t))throw new Error("permit: owner and spender must be addresses");let i=Ls(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+Fs(e)+Fs(t)+Ps(n)+Ps(r)+Ps(s)+i.slice(0,64)+i.slice(64,128)}var eS=e=>Zo.nonces.hex+Fs(e),tS=()=>Zo.DOMAIN_SEPARATOR.hex,nS=({spender:e,amountWei:t})=>qm.approve.hex+Fs(e)+Ps(t);function rS({code:e=null,domainSeparator:t=null,nonces:n=null,owner:r=null}={}){let o=Ls(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(!Hs(r))return{supported:null,kind:"no-owner",reason:"no owner given - cannot read nonces(owner)"};let i=Qm(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=Qm(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 oS({orchestrator:e=null,permitSupported:t=null,token:n=null,nativeBalanceWei:r=null,gasNeedWei:o=null,asyncProvider:i=null,chainId:s=null}={}){let a=Zm(o),c=i&&typeof i=="object"?i:s==null?null:Tl({chainId:s}),l=!!(c&&c.ok===!0),d=c&&c.ok===!1&&c.reason?String(c.reason):"no-async-provider";if(a!==null&&a>0n){let f=Zm(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 p={checked:!0,nativeBalanceWei:f.toString(),gasNeedWei:a.toString(),shortfallWei:(a-f).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 ("+d+"): there is no path for a purchase without own native coin here"}}return Hs(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 iS(){return Vo()}async function sS(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 aS({factory:e,locker:t,claimer:n,commitHalfLocker:r,commitHalfClaimer:o,edPointLocker:i,edPointClaimer:s,edViewPointLocker:a,salt:c,amountWei:l,amountLabel:d,claimWindowSeconds:f=3600,readyWindowSeconds:p=14400,readyBy:h,t1:w,quote:b,onStep:y}){return Al({factory:e,quote:b,locker:t,claimer:n,commitHalfLocker:r,commitHalfClaimer:o,edPointLocker:i,edPointClaimer:s,edViewPointLocker:a,salt:c,amountLabel:d,amountWei:l,claimWindowSeconds:f,readyWindowSeconds:p,readyBy:h,t1:w,call:ul,send:pl,receipt:fl,onStep:y})}var ot={};Fe(ot,{DEX_METHOD:()=>Zt,declaredRoutePath:()=>eh,decodeQuoteExactInput:()=>Ol,dexLegVerdict:()=>hS,encodeGetPool:()=>ih,encodePath:()=>Cl,encodeQuoteExactInput:()=>ch,encodeQuoteExactInputSingle:()=>oh,encodeQuoteExactOutputSingle:()=>sh,feeTierLabel:()=>jr,feeTierPct:()=>lh,noRouteWords:()=>hh,poolAddress:()=>dh,poolState:()=>mS,priceGateVerdict:()=>mh,quoteDexOut:()=>wS,quoteExactOutPath:()=>ah,quoteExactOutSingle:()=>uS,quotePath:()=>fh,quoteTier:()=>uh,resetDexCache:()=>dS,routeLabel:()=>th,routeSignature:()=>ph,routeSteps:()=>nh,unwrapLeg:()=>yS});var Zt={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 eh({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(d=>[String(d.symbol).toUpperCase(),d])),i=d=>{let f=String(d).toUpperCase();if(n&&f===String(n.symbol).toUpperCase())return n.address;let p=o.get(f);return p&&p.address?p.address:null},s=[e.symbol],a=[e.address],c=[],l=[];for(let d of r.steps){let f=i(d.to);if(!f)return{error:`declared route names a token that this network has no address for: ${d.to}`};a.push(f),s.push(String(d.to).toUpperCase()===String(n&&n.symbol).toUpperCase()?n.symbol:d.to),c.push(Number(d.fee)),l.push(d.pool||null)}return{tokens:a,symbols:s,fees:c,pools:l}}function th(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]+" "+jr(e.fees[n]);return t}function nh(e){return!e||!e.symbols?[]:e.fees.map((t,n)=>({from:e.symbols[n],to:e.symbols[n+1],fee:t,feeLabel:jr(t)}))}var cS=2e4,Bl=new Map;function lS(e){let t=Bl.get(e);if(t&&Date.now()-t.at<cS)return t.value}function Jm(e,t){return Bl.set(e,{at:Date.now(),value:t}),t}function dS(){Bl.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 Ds=e=>String(e||"").replace(/^0x/,""),rh=e=>Ds(e).toLowerCase().padStart(64,"0"),En=e=>rh(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")};function Ur(e){let t=Ds(e),n=[];for(let r=0;r+64<=t.length;r+=64)n.push(BigInt("0x"+t.slice(r,r+64)));return n}function oh({tokenIn:e,tokenOut:t,amountInWei:n,fee:r,sqrtPriceLimitX96:o=0}){return Zt.quoteExactInputSingle.hex+En(e)+En(t)+gt(n)+gt(r)+gt(o)}function ih({tokenA:e,tokenB:t,fee:n}){return Zt.getPool.hex+En(e)+En(t)+gt(n)}function sh({tokenIn:e,tokenOut:t,amountOutWei:n,fee:r,sqrtPriceLimitX96:o=0}){return Zt.quoteExactOutputSingle.hex+En(e)+En(t)+gt(n)+gt(r)+gt(o)}async function uS(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=sh({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=Ur(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 ah(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=Cl({tokens:i,fees:s}),c=Zt.quoteExactOutput.hex+gt(64)+gt(n)+gt(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 d=Ol(l.result);return!d||d.amountOutWei<=0n?{ok:!1,why:"pool cannot serve exactly this output"}:{ok:!0,amountInWei:d.amountOutWei.toString(),gasEstimate:d.gasEstimate.toString(),shapeOk:d.sqrtPriceX96After.length===s.length,reversed:i.map(f=>f).length===s.length+1}}function Cl({tokens:e,fees:t}){let n=[];for(let o=0;o<e.length;o++)n.push(Ds(e[o]).toLowerCase().padStart(40,"0")),o<t.length&&n.push(Ds(Number(t[o]).toString(16)).toLowerCase().padStart(6,"0"));let r=n.join("");return{packed:r,bytes:r.length/2}}function ch({tokens:e,fees:t,amountInWei:n}){let{packed:r,bytes:o}=Cl({tokens:e,fees:t}),i=r.padEnd(Math.ceil(o/32)*64,"0");return Zt.quoteExactInput.hex+rh("0x40")+gt(n)+gt(o)+i}var fS=e=>e==null?null:"0x"+e.toString(16).padStart(40,"0"),pS="0x"+"0".repeat(40);function lh(e){let t=Number(e);return Number.isFinite(t)?t/1e4:null}function jr(e){let t=lh(e);return t===null?String(e):String(Number(t.toFixed(4)))+"%"}async function dh(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:ih({tokenA:t,tokenB:n,fee:r})},"latest"],o);if(!s.ok)return{ok:!1,why:s.why};let a=Ur(s.result),c=fS(a[0]);return!c||c===pS?{ok:!0,pool:null}:{ok:!0,pool:c}}async function mS(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:Zt.liquidity.hex},"latest"],o),vn(e,"eth_call",[{to:n,data:Zt.balanceOf.hex+En(t)},"latest"],o),vn(e,"eth_call",[{to:r,data:Zt.balanceOf.hex+En(t)},"latest"],o)]),c=l=>l.ok?Ur(l.result)[0]??null:null;return{liquidity:i.ok?BigInt(Ur(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 uh(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=oh({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=Ur(c.result);if(l.length<4)return{fee:o,ok:!1,why:"quoter answered "+l.length+" words, expected 4"};let d=l[0];return d<=0n?{fee:o,ok:!1,why:"pool cannot serve this size"}:{fee:o,ok:!0,amountOutWei:d.toString(),gasEstimate:l[3].toString(),sqrtPriceX96After:l[1].toString(),initializedTicksCrossed:l[2].toString()}}function Ol(e){let t=Ur(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 fh(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=ch({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=Ol(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 ph(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 mh({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,d=c&&Number.isFinite(Number(c.stableBandPct))&&Number(c.stableBandPct)>=0?Number(c.stableBandPct):null,f=[],p=(Array.isArray(s)?s:[]).map(P=>{let O={from:P.from,to:P.to,fee:P.fee,feeLabel:jr(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 O.why="the 1:1 step could not be quoted ("+(P.why||"no answer")+")",f.push(O.why),O;let j=Number(P.inWei)/10**Number(P.inDecimals),D=Number(P.outWei)/10**Number(P.outDecimals);return!(j>0)||!(D>0)?(O.why="the 1:1 step answered with a number that cannot be read",f.push(O.why),O):(O.ratio=D/j,O.deviationPct=Math.abs(1-O.ratio)*100,d===null?(O.why="the 1:1 band is not declared for this step, so this step cannot be checked",f.push(O.why),O):O.deviationPct>d?(O.why=`${O.from}\u2192${O.to} at ${O.feeLabel} pays ${O.ratio.toFixed(6)} ${O.to} per 1 ${O.from} - ${O.deviationPct.toFixed(2)}% off 1:1, and the band is ${d}%`,f.push(O.why),O):(O.ok=!0,O))}),h=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,b=h!==null&&Number(o)>0?h*Number(o):null,y=b!==null&&w!==null&&w>0?b/w:null,v=Number(i)>0?Number(i):null,I=y!==null&&v!==null?Math.abs(y-v)/v*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 $${v.toFixed(2)} - ${I.toFixed(1)}% apart, and the limit is ${l}%: this is not the market price`):I===null?f.push(v===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 T=I!==null&&l!==null,A=g||p.some(P=>!P.ok);return{checked:T,bad:A,tolerated:!!a,blocks:a?!1:A||!T,why:f.length?f.join("; "):null,impliedUsd:y,referenceUsd:v,deviationPct:I,maxDeviationPct:l,stableBandPct:d,tokenUsd:Number(o)>0?Number(o):null,stable:p}}function hh({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 hS(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 wS(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 d=BigInt(n||0);if(d<=0n)return{ok:!1,why:"amount not entered"};let f=l.wrapped,p=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 h=o||null,w=String(e&&e.dexPriceGate||"")==="tolerated",b=h?{steps:(Array.isArray(h.steps)?h.steps:[]).map(D=>({to:D.to,fee:D.fee,pool:D.pool||null,verified:D.verified||null})),why:h.why||null,unwrap:!!h.unwrap}:null;if(!h||!Array.isArray(h.steps)||!h.steps.length)return h&&h.unwrap?{ok:!1,why:"this is the wrapped native coin: no pool needed, it unwraps 1:1",unwrap:!0}:{ok:!1,why:hh({paySymbol:t.symbol,wrappedSymbol:f.symbol,chainName:p,route:h}),declared:!0,declaration:b,steps:[]};let y=eh({token:t,tokens:i,wrapped:f,route:h});if(!y||y.error)return{ok:!1,declared:!0,dataError:!0,declaration:b,why:"the declared route for "+t.symbol+" on "+p+" cannot be built: "+(y&&y.error||"unknown reason")};let v=new Map((Array.isArray(i)?i:[]).filter(D=>D&&D.address).map(D=>[String(D.address).toLowerCase(),D])),I=D=>{if(String(D).toLowerCase()===String(t.address).toLowerCase())return t.decimals;if(String(D).toLowerCase()===String(f.address).toLowerCase())return f.decimals;let X=v.get(String(D).toLowerCase());return X&&Number.isFinite(Number(X.decimals))?Number(X.decimals):null},g=[e.id,t.symbol,d.toString(),ph(h)].join("|"),T=lS(g);if(T===void 0){let D=await fh(e,{route:{tokens:y.tokens,fees:y.fees,symbols:y.symbols,via:null},amountInWei:d},c);if(!D.ok)return Jm(g,{ok:!1,why:D.why,declared:!0});T={ok:!0,quote:D},Jm(g,T)}if(!T.ok)return{...T,declaration:b};let A=T.quote;if(T.hops===void 0){let D=[];for(let X=0;X<y.fees.length;X++){let H=y.fees[X],m=y.tokens[X],k=y.tokens[X+1],x=h.steps&&h.steps[X]||{},C=await dh(e,{tokenIn:m,tokenOut:k,fee:H},c),U=C.ok?C.pool:null,W=x.pool||null;D.push({step:X+1,from:y.symbols[X],to:y.symbols[X+1],fee:H,feeLabel:jr(H),decimals:[I(m),I(k)],pool:U,declaredPool:W,poolMatchesDeclared:U&&W?String(U).toLowerCase()===String(W).toLowerCase():null,verified:x.verified||null})}T.hops=D}let B=T.hops;if(T.stableSteps===void 0){let D=(a&&Array.isArray(a.stables)?a.stables:[]).map(H=>String(H).toUpperCase()),X=[];for(let H=0;H<y.fees.length;H++){let m=String(y.symbols[H]).toUpperCase(),k=String(y.symbols[H+1]).toUpperCase();if(!D.includes(m)||!D.includes(k))continue;let x=await uh(e,{tokenIn:y.tokens[H],tokenOut:y.tokens[H+1],amountInWei:d,fee:y.fees[H]},c);X.push({from:y.symbols[H],to:y.symbols[H+1],fee:y.fees[H],inWei:d.toString(),outWei:x.ok?x.amountOutWei:null,inDecimals:I(y.tokens[H]),outDecimals:I(y.tokens[H+1]),ok:!!x.ok,why:x.ok?null:x.why,exact:H===0})}T.stableSteps=X}let P=mh({amountInWei:d,amountOutWei:A.amountOutWei,inDecimals:t.decimals,outDecimals:f.decimals,tokenUsd:Number(t.usd)>0?Number(t.usd):null,referenceUsd:s,stableSteps:T.stableSteps,tolerated:w,gates:a}),O=null;if(r!=null&&Number(r)>0){let D=await ah(e,{route:A,amountOutWei:BigInt(r)},c);O=D.ok?{ok:!0,amountInWei:D.amountInWei,gasEstimate:D.gasEstimate,enough:BigInt(D.amountInWei)<=d,enteredWei:d.toString(),spareInWei:(BigInt(D.amountInWei)<=d?d-BigInt(D.amountInWei):0n).toString(),shortInWei:(BigInt(D.amountInWei)<=d?0n:BigInt(D.amountInWei)-d).toString()}:{ok:!1,why:D.why}}let j=r!=null&&Number(r)>0?(()=>{let D=BigInt(r),X=BigInt(A.amountOutWei);return{outWei:D.toString(),getsWei:X.toString(),covers:X>=D,shortfallWei:(X>=D?0n:D-X).toString()}})():null;return{ok:!0,leg:"pool",venue:"Uniswap v3",payToken:t.symbol,wrapped:f,declaredRoute:b,route:{symbols:A.symbols.slice(),fees:A.fees.slice(),pools:y.pools.slice(),via:null,hops:A.fees.length},routeLabel:th(A),steps:nh(A),fee:A.fees[A.fees.length-1],feeLabel:A.fees.map(D=>jr(D)).join(" / "),amountInWei:d.toString(),amountOutWei:A.amountOutWei,gasEstimate:A.gasEstimate,required:j,price:P,exactOut:O,hopsDetail:B,pool:B.length?B[0].pool:null,at:Date.now()}}function yS(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 Ms={};Fe(Ms,{checkOrderQuoteShape:()=>bS,requestOrderQuote:()=>gS});async function gS({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(kS()+"/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 bS(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 xS=null,kS=()=>xS||on.base;var Us={};Fe(Us,{scalarFromMoneroHex:()=>vS,spendKeysFromRevealedHalf:()=>SS});function SS({halves:e,ownSpendHalf:t,ownViewHalf:n,otherSpendPoint:r,otherViewHalf:o,revealedHalf:i}){if(!e)throw new Error("half maths is required");for(let[w,b]of Object.entries({ownSpendHalf:t,ownViewHalf:n,otherSpendPoint:r,otherViewHalf:o,revealedHalf:i}))if(b==null||b==="")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),d=w=>String(w).replace(/^0x/i,"").toLowerCase();if(d(c)!==d(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)),p=w=>BigInt(w).toString(16).padStart(64,"0"),h=w=>p(w).match(/../g).reverse().join("");return{privateSpendKey:h(a),privateViewKey:h(f)}}function vS(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(""))}$n();var wh=5e8;function Rl(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 js(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 An={};Fe(An,{ED_ORDER:()=>bt,PEDERSEN_H:()=>kh,UNLOCK_TIME_BLOCK_MAX:()=>wh,amountMaskCommitment:()=>Sh,bytesToHex:()=>nr,decodeAmount:()=>Th,decodeMask:()=>Pl,derivedOutputKey:()=>Nh,fetchBlock:()=>Oh,fetchTransactions:()=>Rh,findOurOutputs:()=>Bh,hashToScalar:()=>Wr,hexToBytes:()=>tr,keccak:()=>Hl,keyDerivation:()=>Ks,laterBoundary:()=>js,matchTransaction:()=>BS,scalarFromBytesLE:()=>Vs,scalarFromHexLE:()=>Fl,scalarToBytesLE:()=>Ws,scanRange:()=>CS,txKeysFromExtra:()=>Dl,txPublicKeyFromExtra:()=>IS,unlockStateOf:()=>Rl,varint:()=>Ll,viewKeyFormForAddress:()=>Eh,viewSecretCandidates:()=>$s,watchedAddressVerdict:()=>Ah});Ic();Dc();$n();var AS=Object.fromEntries(Object.entries(ls).map(([e,t])=>[t.primary,e])),yh=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join("");function gh(e){let t=ds(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:yh(t.slice(1,33)),viewPub:yh(t.slice(33,65))}}function Hl(e){return as(e)}var bt=Te.Point.CURVE().n,kh="8b655970153799af2aeadc9ff1add0ea6c7251d54154cfa92c173a0dd39c1f94",_S=Te.Point.fromHex(kh);function bh(e,t){let n=(BigInt(t)%bt+bt)%bt;return n===0n?Te.Point.ZERO:e.multiply(n)}function Sh(e,t){let n=BigInt(e);if(n<0n)throw new Error("the amount must not be negative");return bh(Te.Point.BASE,t).add(bh(_S,n)).toHex()}function tr(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 nr(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function Vs(e){let t=Uint8Array.from(e).reverse();return BigInt("0x"+nr(t))}function Fl(e){return Vs(tr(e))}function Ws(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 Wr(...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 Vs(Hl(n))%bt}function Ll(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 vh(e){return Te.Point.fromHex(String(e).replace(/^0x/,""))}function $s(e){if(typeof e=="bigint")return[["number",e%bt]];let t=String(e).replace(/^0x/,"");return/^[0-9a-fA-F]{64}$/.test(t)?[["BE-number",BigInt("0x"+t)%bt],["LE-bytes",Fl(t)%bt]]:[["unparsed",null]]}function Eh(e,t){let n=String(t||"").toLowerCase();if(!n)return null;for(let[r,o]of $s(e))if(o!==null&&Te.Point.BASE.multiply(o).toHex().toLowerCase()===n)return r;return!1}function Ah({address:e,viewSecret:t,spendPub:n}={}){let r;try{r=gh(e)}catch{return{ok:!1,code:"bad-input",why:"not-a-monero-address",field:"address"}}if(!r.network)return{ok:!1,code:"bad-input",why:"not-a-primary-address",field:"address"};let o=String(n??"").replace(/^0x/,"").toLowerCase();if(!o||o!==r.spendPub.toLowerCase())return{ok:!1,code:"xmr-address-mismatch",field:"spendPub"};let i=Eh(t,r.viewPub);if(!i)return{ok:!1,code:"xmr-address-mismatch",field:"viewSecret"};let s=$s(t).find(([a])=>a===i)?.[1];return s==null?{ok:!1,code:"xmr-address-mismatch",field:"viewSecret"}:{ok:!0,address:e,keys:r,form:i,viewSecret:s,spendPub:r.spendPub}}function Ks(e,t){let n=vh(e),r=(typeof t=="bigint"?t:Fl(String(t).replace(/^0x/,"")))%bt,o=n.multiply(r);return tr(o.multiply(8n).toHex())}function Nh(e,t,n){let r=Wr(e,Ll(t));return Te.Point.BASE.multiply(r).add(vh(n)).toHex()}function xh(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 Dl(e){let t=Array.isArray(e)?Uint8Array.from(e):tr(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(nr(t.subarray(o,o+32))),o+=32;continue}if(i===2||i===3){let s=xh(t,o);if(!s||s.value>BigInt(t.length-s.next))break;o=s.next+Number(s.value);continue}if(i===4){let s=xh(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(nr(t.subarray(o,o+32))),o+=32;continue}break}return{txPublicKeys:n,additionalPublicKeys:r}}function IS(e){return Dl(e).txPublicKeys[0]||null}function _h(e){return Number(e)>=4}function TS(e,t){let n=Wr(e);return t==="mask"?n:Wr(tr(n.toString(16).padStart(64,"0")))}function Ih(e,t,n,r){if(_h(n)){if(r==="mask")return Wr(new TextEncoder().encode("commitment_mask"),t);let s=tr(e),a=new TextEncoder().encode(r),c=new Uint8Array(a.length+t.length);c.set(a,0),c.set(t,a.length);let l=Hl(c),d=s.slice();for(let f=0;f<d.length&&f<l.length;f++)d[f]^=l[f];return Vs(d)}let o=tr(e);return(BigInt("0x"+nr(o))%bt-TS(t,r)+bt)%bt}function Th(e,t,n){return Ih(e,t,n,"amount")}function Pl(e,t,n){return Ih(e,t,n,"mask")}function Bh({txPublicKey:e=null,txPublicKeys:t=null,additionalPublicKeys:n=[],viewSecretHex:r,spendPubHex:o,outputs:i,ecdhAmounts:s=[],ecdhMasks:a=[],outPk:c=[],rctVersion:l=2}){let d=Array.isArray(t)?t.filter(Boolean):e?[e]:[],f=Array.isArray(n)?n:[];if(!d.length&&!f.length)throw new Error("the transaction has no public key (extra tag 0x01/0x04) - nothing to parse");let p=$s(r).filter(([,b])=>b!==null),h=p[0]||["unparsed",null];for(let[b,y]of p){let v=[];for(let g of d)try{v.push(Ks(g,y))}catch{}let I=[];for(let g of i){let T=v.slice();if(f[g.index])try{T.push(Ks(f[g.index],y))}catch{}for(let A of T){let B=Wr(A,Ll(g.index));if(Nh(A,g.index,o).toLowerCase()!==String(g.key).toLowerCase())continue;let O=s[g.index]?Th(s[g.index],Ws(B),l):null,j=_h(l)?Pl(null,Ws(B),l):a[g.index]?Pl(a[g.index],Ws(B),l):null,D=!1;if(O!==null&&j!==null&&c[g.index])try{D=Sh(O,j).toLowerCase()===String(c[g.index]).replace(/^0x/,"").toLowerCase()}catch{D=!1}I.push({index:g.index,key:g.key,amountAtomic:O,maskAtomic:j,amountVerified:D,derivation:nr(A)});break}}if(I.length)return{derivation:I[0].derivation,outputs:I,viewKeyForm:b}}let w=null;if(h[1]!==null&&d.length)try{w=nr(Ks(d[0],h[1]))}catch{w=null}return{derivation:w,outputs:[],viewKeyForm:h[0]}}var Ch=e=>{let t=String(e);for(;t.endsWith("/");)t=t.slice(0,-1);return t};async function Oh(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(`${Ch(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 Rh(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(`${Ch(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(h=>String(h).replace(/^0x/,"").toLowerCase()))],d=new Map;for(let h of a){let w=String(h&&h.tx_hash||"").replace(/^0x/,"").toLowerCase();if(w){if(d.has(w))throw new Error("transactions-duplicate: "+w);d.set(w,h)}}let f=l.filter(h=>!d.has(h));if(f.length)throw new Error("transactions-missing: "+f.length);if(d.size!==l.length)throw new Error("transactions-extra: "+(d.size-l.length));if(c.length!==a.length)throw new Error("transactions-undecoded");let p=new Map(a.map((h,w)=>[String(h&&h.tx_hash||"").replace(/^0x/,"").toLowerCase(),w]));return l.map(h=>{let w=d.get(h)||{},b=c[p.get(h)],y=typeof b=="string"?JSON.parse(b):b;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 Ph(e,t,{height:n=null,tipHeight:r=null,nowSec:o=null}={}){let i=[],s=Dl(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=Rl(e.unlock_time,{height:c,nowSec:o}),d=v=>((v.target||{}).tagged_key||v.target||{}).key,f=(e.vout||[]).map((v,I)=>({index:I,key:d(v)})),p=(e.rct_signatures||{}).ecdhInfo||[],h=p.map(v=>v.amount),w=p.map(v=>v.mask),b=(e.rct_signatures||{}).outPk||[],y=(e.rct_signatures||{}).type||2;for(let{entry:v,bound:I}of t){let g=Bh({txPublicKeys:s.txPublicKeys,additionalPublicKeys:s.additionalPublicKeys,viewSecretHex:I.viewSecret,spendPubHex:I.spendPub,outputs:f,ecdhAmounts:h,ecdhMasks:w,outPk:b,rctVersion:Number(y)||1});g.outputs.length&&i.push({address:v.address,index:v.index??null,outputs:g.outputs,derivation:g.derivation,viewKeyForm:g.viewKeyForm,unlockTime:Number(e.unlock_time)||0,unlock:l})}return i}function Hh(e){let t=[];for(let n of e){let r=Ah(n);r.ok&&t.push({entry:n,bound:r})}return t}function BS(e,t,n={}){return Ph(e,Hh(t),n)}async function CS({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),d=Number(n);if(!(l>=0)||!(d>=l))throw new Error("bad height range: "+t+".."+n);let f=new Map;for(let I of r)f.set(I.address,{address:I.address,receivedAtomic:0n,lockedAtomic:0n,lockedUntil:null,lockedTxids:[],txids:[],bestHeight:null,outputs:0,viewKeyForm:null});let p=Hh(r),h=[];for(let I=l;I<=d;I++)h.push(I);let w=[],b=0,y=async()=>{for(;b<h.length;){let I=h[b++];try{let g=await Oh(e,I,c),T=g.json?(typeof g.json=="string"?JSON.parse(g.json):g.json).tx_hashes||[]:[];if(!T.length)continue;let A=await Rh(e,T,c);for(let B of A)for(let P of Ph(B,p,{height:I,tipHeight:a??d,nowSec:s})){let O=f.get(P.address);if(!O)continue;P.viewKeyForm&&(O.viewKeyForm=P.viewKeyForm);let j=!!(P.unlock&&P.unlock.locked),D=String(B.tx_hash||"").replace(/^0x/,"");for(let X of P.outputs){let H=X.amountVerified&&X.amountAtomic||0n;j?(O.lockedAtomic+=H,D&&!O.lockedTxids.includes(D)&&O.lockedTxids.push(D),js(P.unlock)>js(O.lockedUntil)&&(O.lockedUntil=P.unlock)):(O.receivedAtomic+=H,O.outputs+=1),D&&!O.txids.includes(D)&&O.txids.push(D),(O.bestHeight===null||I>O.bestHeight)&&(O.bestHeight=I)}}}catch(g){w.push(I),o({event:"indexer_block_error",height:I,error:String(g.message).slice(0,160)})}}};await Promise.all(Array.from({length:Math.max(1,Math.min(i,h.length))},y));let v=[...new Set(w)].sort((I,g)=>I-g);return{fromHeight:l,toHeight:d,results:Array.from(f.values()),complete:v.length===0,missingHeights:v,...v.length?{incompleteReason:"blocks-unreadable"}:{}}}var zs=["awaiting_funding","funded","maker_locking","xmr_locked","ready","claimed","swept"];var Xs=["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 OS=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"}}),RS={"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"},Fh=e=>RS[e]||"unknown";me();var hd={};Fe(hd,{ASYNC:()=>Ve,BALANCE_OF_SELECTOR:()=>Qw,SETTLES:()=>md,SYNC:()=>qo,balances:()=>N1,carriesNativeVerdict:()=>B1,providerSettles:()=>qw,requireAsyncProvider:()=>I1,requireProvider:()=>T1,requireSyncProvider:()=>_1,routeProviderFor:()=>la,routeProviders:()=>qr,sameChain:()=>E1,vm:()=>v1,walletChainId:()=>Gw});var qo="sync",Ve="async";var Ml=e=>!e||typeof e!="object"?{ok:!1,reason:"provider-absent"}:e.shape!==qo&&e.shape!==Ve?{ok:!1,reason:"provider-shape-unknown",shape:e.shape===void 0?null:e.shape}:e.shape===Ve&&typeof e.settled!="function"?{ok:!1,reason:"provider-incomplete",shape:Ve,missing:"settled"}:{ok:!0,shape:e.shape};_e();var Lh="NinseiEscrowFactory";var PS=["EIP712Domain(","string name,","string version,","uint256 chainId,","address verifyingContract)"],Dh=PS.join(""),Gs=[["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"]],Mh="OrderQuote("+Gs.map(e=>e[1]+" "+e[0]).join(",")+")",Nn=e=>{throw new Error(e)},Ys=e=>new TextEncoder().encode(String(e)),Qs=(...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&&Nn("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)&&Nn("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},FS=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("eip712-bad-number")},Ul=(e,t)=>{let n=FS(e);n<0n&&Nn("eip712-negative"),n>=1n<<BigInt(t)&&Nn("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},Uh=e=>{let t=String(e??"").trim();/^(0x)?[0-9a-fA-F]{40}$/.test(t)||Nn("eip712-bad-address");let n=new Uint8Array(32);return n.set(jl(t.replace(/^0x/,"")),12),n},LS=e=>{let t=String(e??"").trim();return/^(0x)?[0-9a-fA-F]{64}$/.test(t)||Nn("eip712-bad-bytes32"),jl(t.replace(/^0x/,""))},DS=(e,t)=>{if(e==="address")return Uh(t);if(e==="bytes32")return LS(t);if(e==="uint64")return Ul(t,64);if(e==="uint256")return Ul(t,256);Nn("eip712-bad-type")},jh=e=>{let t=[];for(let[n]of Gs){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 MS({crypto:e,quote:t}){return e.keccak256(Qs(e.keccak256(Ys(Dh)),e.keccak256(Ys(Lh)),e.keccak256(Ys("1")),Ul(t.chainId,256),Uh(t.factory)))}function US({crypto:e,quote:t}){let n=[e.keccak256(Ys(Mh))];for(let[r,o]of Gs)n.push(DS(o,t?t[r]:void 0));return e.keccak256(Qs(...n))}function Wh({crypto:e,quote:t}){return e.keccak256(Qs(Uint8Array.from([25,1]),MS({crypto:e,quote:t}),US({crypto:e,quote:t})))}function Kh({crypto:e,quote:t}){try{if(jh(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=Wh({crypto:e,quote:t}),s=e.secp256k1.Signature.fromBytes(Qs(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 Vh=["Gnosis","Protocol"].join(" "),$h="v2",rr="0x9008D19f58AAbD9eD0D60971565AA8510560ab41",zh="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",jS=["EIP712Domain(","string name,","string version,","uint256 chainId,","address verifyingContract)"],WS=jS.join(""),Vr=[["sellToken","address"],["buyToken","address"],["receiver","address"],["sellAmount","uint256"],["buyAmount","uint256"],["validTo","uint32"],["appData","bytes32"],["feeAmount","uint256"],["kind","string"],["partiallyFillable","bool"],["sellTokenBalance","string"],["buyTokenBalance","string"]],KS="Order("+Vr.map(e=>e[1]+" "+e[0]).join(",")+")";var It=e=>{throw new Error(e)},Jo=e=>new TextEncoder().encode(String(e)),Js=(...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},Zs=e=>{let t=String(e).replace(/^0x/,"");t.length%2&&It("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)&&It("cow-bad-hex"),n[r]=o}return n},Xh=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);It("cow-bad-number")},qs=(e,t)=>{let n=VS(e);n<0n&&It("cow-negative"),n>=1n<<BigInt(t)&&It("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},Yh=e=>{let t=String(e??"").trim();/^(0x)?[0-9a-fA-F]{40}$/.test(t)||It("cow-bad-address");let n=new Uint8Array(32);return n.set(Zs(t.replace(/^0x/,"")),12),n},$S=e=>{let t=String(e??"").trim();return/^(0x)?[0-9a-fA-F]{64}$/.test(t)||It("cow-bad-bytes32"),Zs(t.replace(/^0x/,""))},zS=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:It("cow-bad-bool"),t},XS=e=>te(Jo(e)),YS=(e,t)=>{if(e==="address")return Yh(t);if(e==="bytes32")return $S(t);if(e==="uint32")return qs(t,32);if(e==="uint256")return qs(t,256);if(e==="bool")return zS(t);if(e==="string")return XS(t);It("cow-bad-type")},Gh=e=>{let t=[];for(let[n]of Vr){let r=e?e[n]:void 0;(r==null||r==="")&&t.push(n)}return t},GS=({chainId:e,settlement:t=rr})=>te(Js(te(Jo(WS)),te(Jo(Vh)),te(Jo($h)),qs(e,256),Yh(t))),QS=e=>{let t=[te(Jo(KS))];for(let[n,r]of Vr)t.push(YS(r,e?e[n]:void 0));return te(Js(...t))},ZS=({order:e,chainId:t,settlement:n=rr})=>te(Js(Uint8Array.from([25,1]),GS({chainId:t,settlement:n}),QS(e))),Qh=e=>Xh(ZS(e)),Zh=({digest:e,owner:t,validTo:n})=>{let r=Zs(e);r.length!==32&&It("cow-bad-digest");let o=Zs(t);o.length!==20&&It("cow-bad-owner");let i=qs(n,32).slice(28);return Xh(Js(r,o,i))},qh=({order:e,chainId:t,settlement:n=rr})=>({domain:{name:Vh,version:$h,chainId:Number(t),verifyingContract:n},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],Order:Vr.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)}});me();var qS=()=>typeof fetch=="function"?fetch:null;function it({apiBase:e,fetchImpl:t=null,timeoutMs:n=2e4}){let r=t||qS();return{async json(o,{signal:i=null,method:s="GET",headers:a=null,body:c=null}={}){if(!e)throw new u("server-unavailable",{why:"no-api-base"});if(typeof r!="function")throw new u("bad-input",{field:"fetch"});let l=new AbortController,d=setTimeout(()=>l.abort(),n),f=()=>l.abort();i&&i.addEventListener("abort",f,{once:!0});try{let p={signal:l.signal,method:s,headers:{accept:"application/json",...a||{}}};c!=null&&(p.body=c);let h=await r(e+o,p);if(!h||typeof h.ok!="boolean")throw new u("server-unavailable",{why:"bad-response"});if(!h.ok)throw new u("server-unavailable",{status:h.status});return await h.json()}catch(p){throw p instanceof u?p:new u("server-unavailable",{why:p&&p.name==="AbortError"?"timeout":"fetch"})}finally{clearTimeout(d),i&&i.removeEventListener("abort",f)}},async tryJson(o,{signal:i=null,method:s="GET",headers:a=null,body:c=null}={}){if(!e)throw new u("server-unavailable",{why:"no-api-base"});if(typeof r!="function")throw new u("bad-input",{field:"fetch"});let l=new AbortController,d=setTimeout(()=>l.abort(),n),f=()=>l.abort();i&&i.addEventListener("abort",f,{once:!0});try{let p={signal:l.signal,method:s,headers:{accept:"application/json",...a||{}}};c!=null&&(p.body=c);let h=await r(e+o,p);if(!h||typeof h.ok!="boolean")throw new u("server-unavailable",{why:"bad-response"});let w=null;try{w=await h.json()}catch{throw new u("server-unavailable",{why:"body"})}return{ok:h.ok,status:h.status,body:w}}catch(p){throw p instanceof u?p:new u("server-unavailable",{why:p&&p.name==="AbortError"?"timeout":"fetch"})}finally{clearTimeout(d),i&&i.removeEventListener("abort",f)}}}}var Wl=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"}}),JS=["presignaturePending","open","fulfilled","cancelled","expired"],Jh=["fulfilled","cancelled","expired"],ew="fulfilled";var Ie=(e,t={})=>({ok:!1,code:e,params:t}),Kl=e=>{let t=Wl[Number(e)];return t?t.orderbook:null},ea=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),ev=e=>/^(0x)?[0-9a-fA-F]{64}$/.test(String(e||""));function tw(e={}){let t=Number(e.chainId);if(Kl(t)===null)return{...Ie("cow-unknown-network",{chainId:Number.isFinite(t)?t:null}),known:Object.keys(Wl).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=Gh(o);if(ea(n)||i.push("owner"),ev(o.appData)||i.push("appData"),(!ea(o.sellToken)||!ea(o.buyToken)||!ea(o.receiver))&&i.push("token"),i.length)return Ie("cow-bad-order",{missing:[...new Set(i)]});try{let s=Qh({order:o,chainId:t,settlement:rr}),a=Zh({digest:s,owner:n,validTo:o.validTo}),c=qh({order:o,chainId:t,settlement:rr});return{ok:!0,chainId:t,owner:n,order:o,digest:s,uid:a,typedData:c}}catch(s){return Ie("cow-bad-order",{why:String(s&&s.message?s.message:s)})}}function tv({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 nv(e={}){let t=tw(e);return t.ok?{ok:!0,provider:"cowswap",venue:"CoWSwap",shape:Ve,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:ew,final:[...Jh],endpoint:"/api/v1/orders/{uid}"}}:t}async function rv({typedData:e,wallet:t,address:n=null}={}){if(!e||typeof e!="object")return Ie("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)?Ie("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)?Ie("cow-sign-failed",{why:"bad-signature-shape"}):{ok:!0,signature:i}}return Ie("cow-sign-failed",{why:"no-wallet"})}catch(r){return Ie("cow-sign-failed",{why:String(r&&r.code||r&&r.message||r)})}}async function ov({order:e,signature:t,owner:n,chainId:r,fetchImpl:o=null,timeoutMs:i=2e4,signingScheme:s="eip712",from:a=null}={}){let c=Kl(r);if(c===null)return Ie("cow-unknown-network",{chainId:Number(r)});if(typeof t!="string"||!/^0x[0-9a-fA-F]{130}$/.test(t))return Ie("cow-bad-order",{field:"signature"});let l=it({apiBase:c,fetchImpl:o,timeoutMs:i}),d=JSON.stringify(tv({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:d})}catch(p){return Ie("cow-unreachable",{why:String(p&&p.params&&p.params.why||p&&p.code||p)})}return!f||typeof f.ok!="boolean"?Ie("cow-bad-response",{where:"submit"}):f.ok?typeof f.body!="string"||!/^0x[0-9a-fA-F]{112}$/.test(f.body)?Ie("cow-bad-response",{where:"submit",got:typeof f.body}):{ok:!0,uid:f.body}:Ie("cow-refused",{status:f.status,reason:f.body&&f.body.errorType?f.body.errorType:null})}async function nw({uid:e,chainId:t,fetchImpl:n=null,timeoutMs:r=2e4}={}){let o=Kl(t);if(o===null)return Ie("cow-unknown-network",{chainId:Number(t)});if(typeof e!="string"||!/^0x[0-9a-fA-F]{112}$/.test(e))return Ie("cow-bad-order",{field:"uid"});let i=it({apiBase:o,fetchImpl:n,timeoutMs:r}),s;try{s=await i.tryJson("/api/v1/orders/"+e)}catch(c){return Ie("cow-unreachable",{why:String(c&&c.params&&c.params.why||c&&c.code||c)})}if(!s||typeof s.ok!="boolean")return Ie("cow-bad-response",{where:"status"});if(s.status===404)return Ie("cow-order-unknown",{uid:e});if(!s.ok)return Ie("cow-refused",{status:s.status});let a=s.body&&s.body.status;return typeof a!="string"||!JS.includes(a)?Ie("cow-bad-response",{where:"status",got:typeof a=="string"?a:null}):{ok:!0,status:a,order:s.body}}async function iv(e={},t={}){let{uid:n,chainId:r}=e;if(typeof n!="string"||!/^0x[0-9a-fA-F]{112}$/.test(n))return Ie("cow-bad-order",{field:"uid"});let o=typeof t.now=="function"?t.now:()=>Date.now(),i=typeof t.sleep=="function"?t.sleep:d=>new Promise(f=>setTimeout(f,d)),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 d=await nw({uid:n,chainId:r,fetchImpl:t.fetchImpl,timeoutMs:t.requestTimeoutMs});if(!d.ok)return d;if(l=d.status,Jh.includes(l))return{ok:!0,done:!0,settled:l===ew,status:l,uid:n};if(o()-c>=a)return Ie("cow-not-settled",{uid:n,status:l,waitedMs:o()-c});await i(s)}}function sv({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:d=!1,tokenIsNative:f=!1,symbol:p=null,decimals:h=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}),b={ok:!0,amountOutWei:String(e.buyAmount),price:w,wrapped:{symbol:c,decimals:a}},y=ot.dexLegVerdict(b,t),v={ok:!y.blocked,checked:y.kind!=="unchecked"&&y.kind!=="unquoted",blocks:y.blocked===!0,kind:y.kind,reason:y.reason},I=ke.allowanceVerdict({tokenIsNative:f,allowanceWei:l,amountWei:e.sellAmount,consent:d===!0,symbol:p,decimals:Number.isFinite(Number(h))?Number(h):18});return{...ke.signingGateVerdict([v,I]),price:w,coverage:y,allowance:I}}var rw=Object.freeze({id:"cowswap",kind:"cow",venue:"CoWSwap",shape:Ve,settles:"native",networks:Wl,settlement:rr,buyEthAddress:zh,orderFields:Vr,plan:nv,settled:iv,buildIntent:tw,sign:rv,submit:ov,status:nw,gate:sv});_e();var av=["Kyber","DSLO","Protocol"].join(" "),cv="1",Ye="0xcab2FA2eeab7065B45CBcF6E3936dDE2506b4f6C",lv=["EIP712Domain(","string name,","string version,","uint256 chainId,","address verifyingContract)"],dv=lv.join(""),$r=[["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"]],uv="Order("+$r.map(e=>e[1]+" "+e[0]).join(",")+")";var fv=[["orderHash","bytes32"],["opExpireTime","uint32"]],Z_="DSOrder("+fv.map(e=>e[1]+" "+e[0]).join(",")+")";var _n=e=>{throw new Error(e)},ta=e=>new TextEncoder().encode(String(e)),$l=(...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},zl=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},pv=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},mv=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")},Vl=(e,t)=>{let n=mv(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},ow=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(zl(t.replace(/^0x/,"")),12),n},hv=e=>{let t=String(e??"").trim();return/^(0x)?[0-9a-fA-F]{64}$/.test(t)||_n("kyber-bad-bytes32"),zl(t.replace(/^0x/,""))},wv=e=>te(zl(e)),yv=(e,t)=>{if(e==="address")return ow(t);if(e==="bytes32")return hv(t);if(e==="uint32")return Vl(t,32);if(e==="uint256")return Vl(t,256);if(e==="bytes")return wv(t);_n("kyber-bad-type")},iw=e=>{let t=[];for(let[n,r]of $r){let o=e?e[n]:void 0;(o==null||r!=="bytes"&&o==="")&&t.push(n)}return t},gv=({chainId:e,contract:t=Ye})=>te($l(te(ta(dv)),te(ta(av)),te(ta(cv)),Vl(e,256),ow(t))),bv=e=>{let t=[te(ta(uv))];for(let[n,r]of $r)t.push(yv(r,e?e[n]:void 0));return te($l(...t))},xv=({order:e,chainId:t,contract:n=Ye})=>te($l(Uint8Array.from([25,1]),gv({chainId:t,contract:n}),bv(e))),sw=e=>pv(xv(e));var ct="https://limit-order.kyberswap.com",cw=["KyberSwap","Limit","Order"].join(" "),na=Object.freeze({1:{orderbook:ct,contract:Ye},10:{orderbook:ct,contract:Ye},56:{orderbook:ct,contract:Ye},137:{orderbook:ct,contract:Ye},250:{orderbook:ct,contract:Ye},324:{orderbook:ct,contract:Ye},5e3:{orderbook:ct,contract:Ye},8453:{orderbook:ct,contract:Ye},42161:{orderbook:ct,contract:Ye},43114:{orderbook:ct,contract:Ye},59144:{orderbook:ct,contract:Ye},534352:{orderbook:ct,contract:Ye},81457:{orderbook:ct,contract:Ye}}),kv="/write/api/v1/orders/sign-message",Sv="/write/api/v1/orders",lw="/read-ks/api/v1/orders";var vv=["active","open","partially_filled","cancelling","closed","filled","cancelled","expired"],dw=["filled","cancelled","expired"],uw="filled";var Ev=["active","closed"];var ue=(e,t={})=>({ok:!1,code:e,params:t}),ti=e=>{let t=na[Number(e)];return t?t.orderbook:null},fw=e=>{let t=na[Number(e)];return t?t.contract:null},ei=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),aw=e=>{try{return BigInt(String(e))>0n}catch{return!1}};function Av(e={}){let t=Number(e.chainId);if(ti(t)===null)return{...ue("kyber-unknown-network",{chainId:Number.isFinite(t)?t:null}),known:Object.keys(na).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 ei(n)||i.push("maker"),ei(o.makerAsset)||i.push("makerAsset"),ei(o.takerAsset)||i.push("takerAsset"),ei(o.receiver)||i.push("receiver"),aw(o.makingAmount)||i.push("makingAmount"),aw(o.takingAmount)||i.push("takingAmount"),Number.isInteger(Number(o.expiredAt))||i.push("expiredAt"),i.length?ue("kyber-bad-order",{missing:[...new Set(i)]}):{ok:!0,chainId:t,orderbook:ti(t),contract:fw(t),maker:n,params:o,expectedOutWei:String(o.takingAmount)}}function Nv(e={}){let t=Av(e);return t.ok?{ok:!0,provider:"kyberswap",venue:cw,shape:Ve,route:"kyberswap",expectedOutWei:t.expectedOutWei,params:t.params,owner:t.maker,endsWith:{kind:"order-status",settledWhen:uw,final:[...dw],endpoint:lw}}:t}async function _v({params:e,chainId:t=null,fetchImpl:n=null,timeoutMs:r=2e4,clientId:o=null}={}){let i=Number(t!==null?t:e&&e.chainId),s=ti(i);if(s===null)return ue("kyber-unknown-network",{chainId:Number.isFinite(i)?i:null});if(!e||typeof e!="object")return ue("kyber-bad-order",{field:"params"});let a=it({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(kv,{method:"POST",headers:c,body:JSON.stringify(e)})}catch(A){return ue("kyber-unreachable",{why:String(A&&A.params&&A.params.why||A&&A.code||A)})}if(!l||typeof l.ok!="boolean")return ue("kyber-bad-response",{where:"sign-message"});if(!l.ok)return ue("kyber-refused",{status:l.status,stage:"sign-message",reason:l.body&&l.body.message?l.body.message:null});let d=l.body&&l.body.data;if(!d||typeof d!="object")return ue("kyber-bad-response",{where:"sign-message"});let f=d.domain||{},p=d.message||{},h=d.types&&Array.isArray(d.types.Order)?d.types.Order.map(A=>(A?A.name:"")+":"+(A?A.type:"")).join(","):null,w=$r.map(([A,B])=>A+":"+B).join(","),b=fw(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(b).toLowerCase()))return ue("kyber-bad-response",{where:"sign-message",field:"domain"});if(h!==w)return ue("kyber-bad-response",{where:"sign-message",field:"types"});let v=iw(p);if(v.length)return ue("kyber-bad-response",{where:"sign-message",missing:v});let I=["maker","makerAsset","takerAsset","receiver"];for(let A of I)if(String(p[A]||"").toLowerCase()!==String(e[A]||"").toLowerCase())return ue("kyber-bad-response",{where:"sign-message",field:A});for(let A of["makingAmount","takingAmount"])if(String(p[A])!==String(e[A]))return ue("kyber-bad-response",{where:"sign-message",field:A});let g=e.allowedSenders===void 0||e.allowedSenders===null?null:(Array.isArray(e.allowedSenders)?e.allowedSenders:[e.allowedSenders]).map(A=>String(A||"").toLowerCase());if(g&&g.length&&!g.includes(String(p.allowedSender||"").toLowerCase()))return ue("kyber-bad-response",{where:"sign-message",field:"allowedSender"});let T;try{T=sw({order:p,chainId:i,contract:b})}catch(A){return ue("kyber-bad-response",{where:"sign-message",why:String(A&&A.message?A.message:A)})}return{ok:!0,chainId:i,orderbook:s,contract:b,salt:String(p.salt),message:p,digest:T,typedData:{domain:f,types:d.types,primaryType:d.primaryType||"Order",message:p}}}async function Iv({typedData:e,wallet:t,address:n=null}={}){if(!e||typeof e!="object")return ue("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)?ue("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)?ue("kyber-sign-failed",{why:"bad-signature-shape"}):{ok:!0,signature:i}}return ue("kyber-sign-failed",{why:"no-wallet"})}catch(r){return ue("kyber-sign-failed",{why:String(r&&r.code||r&&r.message||r)})}}async function Tv({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=ti(a);if(c===null)return ue("kyber-unknown-network",{chainId:Number.isFinite(a)?a:null});if(!e||typeof e!="object")return ue("kyber-bad-order",{field:"params"});if(typeof n!="string"||!/^0x[0-9a-fA-F]{130}$/.test(n))return ue("kyber-bad-order",{field:"signature"});if(t==null||t==="")return ue("kyber-bad-order",{field:"salt"});let l=it({apiBase:c,fetchImpl:o,timeoutMs:i}),d={"content-type":"application/json"};s&&(d["X-Client-Id"]=String(s));let f=JSON.stringify({...e,salt:String(t),signature:n}),p;try{p=await l.tryJson(Sv,{method:"POST",headers:d,body:f})}catch(b){return ue("kyber-unreachable",{why:String(b&&b.params&&b.params.why||b&&b.code||b)})}if(!p||typeof p.ok!="boolean")return ue("kyber-bad-response",{where:"submit"});if(!p.ok)return ue("kyber-refused",{status:p.status,stage:"submit",reason:p.body&&p.body.message?p.body.message:null});let h=p.body&&p.body.data,w=h&&h.id;return!Number.isInteger(Number(w))||Number(w)<=0?ue("kyber-bad-response",{where:"submit",got:typeof w}):{ok:!0,id:Number(w)}}async function pw({id:e,chainId:t,maker:n,fetchImpl:r=null,timeoutMs:o=2e4}={}){let i=Number(t),s=ti(i);if(s===null)return ue("kyber-unknown-network",{chainId:Number.isFinite(i)?i:null});if(!Number.isInteger(Number(e))||Number(e)<=0)return ue("kyber-bad-order",{field:"id"});if(!ei(n))return ue("kyber-bad-order",{field:"maker"});let a=it({apiBase:s,fetchImpl:r,timeoutMs:o});for(let c of Ev){let l=lw+"?chainId="+i+"&maker="+n+"&status="+c,d;try{d=await a.tryJson(l)}catch(h){return ue("kyber-unreachable",{why:String(h&&h.params&&h.params.why||h&&h.code||h)})}if(!d||typeof d.ok!="boolean")return ue("kyber-bad-response",{where:"orders"});if(!d.ok)return ue("kyber-refused",{status:d.status,stage:"orders"});let f=d.body&&d.body.data&&d.body.data.orders;if(!Array.isArray(f))return ue("kyber-bad-response",{where:"orders"});let p=f.find(h=>h&&Number(h.id)===Number(e))||null;if(p){let h=p.status;return typeof h!="string"||!vv.includes(h)?ue("kyber-bad-response",{where:"status",got:typeof h=="string"?h:null}):{ok:!0,status:h,order:p,bucket:c}}}return ue("kyber-order-unknown",{id:Number(e),maker:n})}async function Bv(e={},t={}){let{id:n,chainId:r,maker:o}=e;if(!Number.isInteger(Number(n))||Number(n)<=0)return ue("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(p=>setTimeout(p,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(),d=null;for(;;){let f=await pw({id:n,chainId:r,maker:o,fetchImpl:t.fetchImpl,timeoutMs:t.requestTimeoutMs});if(!f.ok)return f;if(d=f.status,dw.includes(d))return{ok:!0,done:!0,settled:d===uw,status:d,id:Number(n)};if(i()-l>=c)return ue("kyber-not-settled",{id:Number(n),status:d,waitedMs:i()-l});await s(a)}}function Cv({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:d=!1,tokenIsNative:f=!1,symbol:p=null,decimals:h=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}),b={ok:!0,amountOutWei:String(e.takingAmount),price:w,wrapped:{symbol:c,decimals:a}},y=ot.dexLegVerdict(b,t),v={ok:!y.blocked,checked:y.kind!=="unchecked"&&y.kind!=="unquoted",blocks:y.blocked===!0,kind:y.kind,reason:y.reason},I=ke.allowanceVerdict({tokenIsNative:f,allowanceWei:l,amountWei:e.makingAmount,consent:d===!0,symbol:p,decimals:Number.isFinite(Number(h))?Number(h):18});return{...ke.signingGateVerdict([v,I]),price:w,coverage:y,allowance:I}}var mw=Object.freeze({id:"kyberswap",kind:"kyber",venue:cw,shape:Ve,settles:"wrapped",networks:na,settlement:Ye,orderFields:$r,plan:Nv,settled:Bv,unsignedOrder:_v,sign:Iv,submit:Tv,status:pw,gate:Cv});_e();var Ov="Permit2",Xl="0x000000000022D473030F116dDEE9F6B43aC78BA3",Yl="0x0000000000000000000000000000000000000000",Rv=["EIP712Domain(","string name,","uint256 chainId,","address verifyingContract)"],iI=Rv.join(""),Gl=[["reactor","address"],["swapper","address"],["nonce","uint256"],["deadline","uint256"],["additionalValidationContract","address"],["additionalValidationData","bytes"]],Ql=[["token","address"],["startAmount","uint256"],["endAmount","uint256"],["recipient","address"]],ni=[["info","OrderInfo"],["cosigner","address"],["baseInputToken","address"],["baseInputStartAmount","uint256"],["baseInputEndAmount","uint256"],["baseOutputs","DutchOutput[]"]],hw=[["permitted","TokenPermissions"],["spender","address"],["nonce","uint256"],["deadline","uint256"],["witness","V2DutchOrder"]],ww=[["token","address"],["amount","uint256"]],ri=(e,t)=>e+"("+t.map(n=>n[1]+" "+n[0]).join(",")+")",Zl=ri("OrderInfo",Gl),ql=ri("DutchOutput",Ql),yw=ri("V2DutchOrder",ni),Pv=ri("TokenPermissions",ww),sI=ri("PermitWitnessTransferFrom",hw)+ql+Zl+Pv+yw,Hv=yw+ql+Zl;var zr=e=>{throw new Error(e)},Jl=e=>new TextEncoder().encode(String(e)),ra=(...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},gw=e=>{let t=String(e).replace(/^0x/,"");t.length%2&&zr("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)&&zr("uniswapx-bad-hex"),n[r]=o}return n},Fv=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},Lv=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);zr("uniswapx-bad-number")},Xr=(e,t)=>{let n=Lv(e);n<0n&&zr("uniswapx-negative"),n>=1n<<BigInt(t)&&zr("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},or=e=>{let t=String(e??"").trim();/^(0x)?[0-9a-fA-F]{40}$/.test(t)||zr("uniswapx-bad-address");let n=new Uint8Array(32);return n.set(gw(t.replace(/^0x/,"")),12),n},Dv=e=>te(gw(e??"0x")),bw=e=>{let t=[];for(let[r,o]of Gl){let i=e?e[r]:void 0;(i==null||o!=="bytes"&&i==="")&&t.push(r)}for(let[r]of ni){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 Ql){let i=r?r[o]:void 0;(i==null||i==="")&&t.push("baseOutputs."+o)}return t},Mv=e=>te(ra(te(Jl(Zl)),or(e.reactor),or(e.swapper),Xr(e.nonce,256),Xr(e.deadline,256),or(e.additionalValidationContract),Dv(e.additionalValidationData))),Uv=e=>te(ra(te(Jl(ql)),or(e.token),Xr(e.startAmount,256),Xr(e.endAmount,256),or(e.recipient))),jv=e=>te(ra(...(e||[]).map(Uv))),Wv=e=>te(ra(te(Jl(Hv)),Mv(e),or(e.cosigner),or(e.baseInputToken),Xr(e.baseInputStartAmount,256),Xr(e.baseInputEndAmount,256),jv(e.baseOutputs))),xw=e=>Fv(Wv(e));var kw=({order:e,chainId:t,permit2:n=Xl})=>({domain:{name:Ov,chainId:Number(t),verifyingContract:n},types:{EIP712Domain:[{name:"name",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],PermitWitnessTransferFrom:hw.map(([r,o])=>({name:r,type:o})),TokenPermissions:ww.map(([r,o])=>({name:r,type:o})),V2DutchOrder:ni.map(([r,o])=>({name:r,type:o})),OrderInfo:Gl.map(([r,o])=>({name:r,type:o})),DutchOutput:Ql.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 Kv="https://api.uniswap.org/v2",Sw="/orders",vw="UniswapX",Vv="0x4449Cd34d1eb1FEDCF02A1Be3834FfDe8E6A6180",$v="0x0000000000000000000000000000000000000000",oi=Object.freeze({1:{orderbook:Kv,reactor:"0x00000011F84B9aa48e5f8aA8B9897600006289Be"}}),Ew=["open","expired","error","cancelled","filled","insufficient-funds"],Aw=["expired","error","cancelled","filled","insufficient-funds"],Nw="filled";var ve=(e,t={})=>({ok:!1,code:e,params:t});var zv=e=>{let t=oi[Number(e)];return t?t.orderbook:null},Yr=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),oa=e=>{try{return BigInt(String(e))>0n}catch{return!1}},_w=e=>/^0x[0-9a-fA-F]{64}$/.test(String(e||""));function Iw(e={}){let t=Number(e.chainId),n=oi[t];if(!n)return{...ve("uniswapx-unknown-network",{chainId:Number.isFinite(t)?t:null}),known:Object.keys(oi).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?$v: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=bw(i);if(Yr(r)||s.push("swapper"),Yr(i.reactor)||s.push("reactor"),Yr(i.cosigner)||s.push("cosigner"),Yr(i.baseInputToken)||s.push("sellToken"),(!oa(i.baseInputStartAmount)||!oa(i.baseInputEndAmount))&&s.push("sellAmountWei"),(!oa(i.baseOutputs[0].startAmount)||!oa(i.baseOutputs[0].endAmount))&&s.push("buyAmountWei"),(!Yr(i.baseOutputs[0].token)||!Yr(i.baseOutputs[0].recipient))&&s.push("buyToken"),Number.isInteger(Number(i.deadline))||s.push("deadline"),s.length)return ve("uniswapx-bad-order",{missing:[...new Set(s)]});try{let a=kw({order:i,chainId:t}),c=xw(i);return{ok:!0,chainId:t,owner:r,reactor:i.reactor,order:i,orderHash:c,typedData:a}}catch(a){return ve("uniswapx-bad-order",{why:String(a&&a.message?a.message:a)})}}function Xv(e={}){let t=Iw(e);if(!t.ok)return t;let n=t.order.baseOutputs[0];return{ok:!0,provider:"uniswapx",venue:vw,shape:Ve,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()===Yl,endsWith:{kind:"order-status",settledWhen:Nw,final:[...Aw],endpoint:Sw}}}async function Yv({typedData:e,wallet:t,address:n=null}={}){if(!e||typeof e!="object")return ve("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)?ve("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)?ve("uniswapx-sign-failed",{why:"bad-signature-shape"}):{ok:!0,signature:i}}return ve("uniswapx-sign-failed",{why:"no-wallet"})}catch(r){return ve("uniswapx-sign-failed",{why:String(r&&r.code||r&&r.message||r)})}}async function Gv({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 ve("uniswapx-bad-order",{field:"signature"});if(!e||typeof e!="object")return ve("uniswapx-bad-order",{field:"quote"});let s=r==null||r===""?null:String(r);if(!s)return ve("uniswapx-no-submitter",{field:"submitter"});let a=it({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 ve("uniswapx-unreachable",{why:String(p&&p.params&&p.params.why||p&&p.code||p)})}if(!l||typeof l.ok!="boolean")return ve("uniswapx-bad-response",{where:"submit"});if(!l.ok)return ve("uniswapx-refused",{status:l.status,stage:"submit"});let d=l.body&&typeof l.body=="object"?l.body:null;if(!d||typeof d.orderId!="string"||d.orderId==="")return ve("uniswapx-bad-response",{where:"submit",field:"orderId"});let f=d.orderStatus;return typeof f!="string"||!Ew.includes(f)?ve("uniswapx-bad-response",{where:"submit",field:"orderStatus"}):{ok:!0,orderId:d.orderId,orderStatus:f,requestId:typeof d.requestId=="string"?d.requestId:null}}async function Tw({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)?zv(i):null;if(!s)return ve("uniswapx-unknown-network",{chainId:Number.isFinite(i)?i:null});if(!_w(e))return ve("uniswapx-bad-order",{field:"orderHash"});let a=it({apiBase:s,fetchImpl:n,timeoutMs:r}),c;try{c=await a.tryJson(Sw+"?orderHash="+e)}catch(p){return ve("uniswapx-unreachable",{why:String(p&&p.params&&p.params.why||p&&p.code||p)})}if(!c||typeof c.ok!="boolean")return ve("uniswapx-bad-response",{where:"orders"});if(!c.ok)return ve("uniswapx-refused",{status:c.status,stage:"orders"});let l=c.body&&c.body.orders;if(!Array.isArray(l))return ve("uniswapx-bad-response",{where:"orders"});let d=l.find(p=>p&&String(p.orderHash||"").toLowerCase()===String(e).toLowerCase())||l[0]||null;if(!d)return ve("uniswapx-order-unknown",{orderHash:e});let f=d.orderStatus;return typeof f!="string"||!Ew.includes(f)?ve("uniswapx-bad-response",{where:"orderStatus",got:typeof f=="string"?f:null}):{ok:!0,status:f,order:d}}async function Qv(e={},t={}){let{orderHash:n,chainId:r=null}=e;if(!_w(n))return ve("uniswapx-bad-order",{field:"orderHash"});let o=typeof t.now=="function"?t.now:()=>Date.now(),i=typeof t.sleep=="function"?t.sleep:d=>new Promise(f=>setTimeout(f,d)),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 d=await Tw({orderHash:n,chainId:r,fetchImpl:t.fetchImpl,timeoutMs:t.requestTimeoutMs,api:t.api});if(!d.ok)return d;if(l=d.status,Aw.includes(l))return{ok:!0,done:!0,settled:l===Nw,status:l,orderHash:n};if(o()-c>=a)return ve("uniswapx-not-settled",{orderHash:n,status:l,waitedMs:o()-c});await i(s)}}function Zv({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:d=!1,tokenIsNative:f=!1,symbol:p=null,decimals:h=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,b=w?w.endAmount:null,y=ot.priceGateVerdict({amountInWei:e.baseInputEndAmount,amountOutWei:b,inDecimals:s,outDecimals:a,tokenUsd:Number(n)>0?Number(n):null,referenceUsd:Number(r)>0?Number(r):null,stableSteps:[],tolerated:!!o,gates:i}),v={ok:!0,amountOutWei:b===null?null:String(b),price:y,wrapped:{symbol:c,decimals:a}},I=ot.dexLegVerdict(v,t),g={ok:!I.blocked,checked:I.kind!=="unchecked"&&I.kind!=="unquoted",blocks:I.blocked===!0,kind:I.kind,reason:I.reason},T=ke.allowanceVerdict({tokenIsNative:f,allowanceWei:l,amountWei:e.baseInputEndAmount,consent:d===!0,symbol:p,decimals:Number.isFinite(Number(h))?Number(h):18});return{...ke.signingGateVerdict([g,T]),price:y,coverage:I,allowance:T}}var Bw=Object.freeze({id:"uniswapx",kind:"uniswapx",venue:vw,shape:Ve,settles:"native",networks:oi,settlement:oi[1].reactor,permit2:Xl,nativeToken:Yl,orderFields:ni,plan:Xv,settled:Qv,buildIntent:Iw,sign:Yv,submit:Gv,status:Tw,gate:Zv});_e();_e();var qv="Permit2",ia="0x000000000022D473030F116dDEE9F6B43aC78BA3",ed="0x0000000000000000000000000000000000000000",Jv="0x0000000000000000000000000000000000000002",e1="0x24856bc3",Cw=Object.freeze({v3SwapExactIn:0,sweep:4,wrapEth:11,unwrapWeth:12}),t1=3,n1=["EIP712Domain(","string name,","uint256 chainId,","address verifyingContract)"],pI=n1.join(""),td=[["reactor","address"],["swapper","address"],["nonce","uint256"],["deadline","uint256"]],nd=[["token","address"],["amount","uint256"],["recipient","address"]],rd=[["token","address"],["startAmount","uint256"],["endAmount","uint256"],["startTime","uint256"],["endTime","uint256"]],sa=[["info","RelayOrderInfo"],["input","Input"],["fee","FeeEscalator"],["universalRouterCalldata","bytes"]],Ow=[["token","address"],["amount","uint256"]],Rw=[["permitted","TokenPermissions[]"],["spender","address"],["nonce","uint256"],["deadline","uint256"],["witness","RelayOrder"]],Qr=(e,t)=>e+"("+t.map(n=>n[1]+" "+n[0]).join(",")+")",od=Qr("RelayOrderInfo",td),id=Qr("Input",nd),sd=Qr("FeeEscalator",rd),Pw=Qr("RelayOrder",sa),r1=Qr("TokenPermissions",Ow),o1=Pw+sd+id+od,mI=Qr("PermitBatchWitnessTransferFrom",Rw)+sd+id+Pw+od+r1;var Tn=e=>{throw new Error(e)},aa=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},ii=e=>{let t=String(e).replace(/^0x/,"");t.length%2&&Tn("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)&&Tn("uniswaprelay-bad-hex"),n[r]=o}return n},ad=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},Hw=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);Tn("uniswaprelay-bad-number")},lt=(e,t)=>{let n=Hw(e);return n<0n&&Tn("uniswaprelay-negative"),n>=1n<<BigInt(t)&&Tn("uniswaprelay-overflow"),ii("0x"+n.toString(16).padStart(64,"0"))},ir=e=>{let t=String(e??"").trim();/^(0x)?[0-9a-fA-F]{40}$/.test(t)||Tn("uniswaprelay-bad-address");let n=new Uint8Array(32);return n.set(ii(t.replace(/^0x/,"")),12),n},i1=e=>lt(e?1:0,8);var Fw=e=>{let t=[];for(let[n]of td){let r=e&&e.info?e.info[n]:void 0;(r==null||r==="")&&t.push("info."+n)}for(let[n]of nd){let r=e&&e.input?e.input[n]:void 0;(r==null||r==="")&&t.push("input."+n)}for(let[n]of rd){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},s1=e=>te(In(te(aa(od)),ir(e.info.reactor),ir(e.info.swapper),lt(e.info.nonce,256),lt(e.info.deadline,256))),a1=e=>te(In(te(aa(id)),ir(e.token),lt(e.amount,256),ir(e.recipient))),c1=e=>te(In(te(aa(sd)),ir(e.token),lt(e.startAmount,256),lt(e.endAmount,256),lt(e.startTime,256),lt(e.endTime,256))),l1=e=>te(In(te(aa(o1)),s1(e),a1(e.input),c1(e.fee),te(ii(e.universalRouterCalldata)))),Lw=e=>ad(l1(e));var Dw=({order:e,chainId:t,permit2:n=ia})=>({domain:{name:qv,chainId:Number(t),verifyingContract:n},types:{EIP712Domain:[{name:"name",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],PermitBatchWitnessTransferFrom:Rw.map(([r,o])=>({name:r,type:o})),TokenPermissions:Ow.map(([r,o])=>({name:r,type:o})),RelayOrder:sa.map(([r,o])=>({name:r,type:o})),RelayOrderInfo:td.map(([r,o])=>({name:r,type:o})),Input:nd.map(([r,o])=>({name:r,type:o})),FeeEscalator:rd.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 cd=e=>{let t=String(e).replace(/^0x/,"").toLowerCase();return t.length%64===0?t:t.padEnd(Math.ceil(t.length/64)*64,"0")},Gr=e=>Hw(e).toString(16).padStart(64,"0");var d1=e=>{let t=e.map(s=>String(s).replace(/^0x/,"")),n=Gr(t.length),r=[],o=t.length*32;for(let s of t)r.push(Gr(o)),o+=32+Math.ceil(s.length/64)*32;let i=t.map(s=>Gr(s.length/2)+cd(s)).join("");return"0x"+n+r.join("")+i},u1=(e,t)=>{(!Array.isArray(e)||e.length!==t.length+1)&&Tn("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)&&Tn("uniswaprelay-bad-fee"),n+=o.toString(16).padStart(t1*2,"0")}return n+=String(e[e.length-1]).replace(/^0x/,"").toLowerCase(),"0x"+n},f1=({recipient:e,amountInWei:t,amountOutMinimumWei:n,path:r,payerIsUser:o=!1})=>{let i=String(r).replace(/^0x/,""),s=In(ir(e),lt(t,256),lt(n,256),lt(160,256),i1(o)),a=In(lt(i.length/2,256),ii("0x"+cd(i)));return ad(In(s,a))},p1=({recipient:e,amountMinimumWei:t})=>ad(In(ir(e),lt(t,256))),Mw=({tokenIn:e,weth:t,fee:n,amountInWei:r,amountOutMinimumWei:o,recipient:i})=>{let s=u1([e,t],[n]),a="0x"+Cw.v3SwapExactIn.toString(16).padStart(2,"0")+Cw.unwrapWeth.toString(16).padStart(2,"0"),c=f1({recipient:Jv,amountInWei:r,amountOutMinimumWei:o,path:s,payerIsUser:!1}),l=p1({recipient:i,amountMinimumWei:o}),d=a.replace(/^0x/,""),f=Gr(ii(a).length)+cd(d),p=d1([c,l]).replace(/^0x/,""),h=64,w=64+f.length/2;return e1+Gr(h)+Gr(w)+f+p};var Uw="0x0000000000A4e21E2597DCac987455c48b12edBF",jw="0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD",Ww=["Uniswap","Relay"].join(" "),ud=Object.freeze({1:{reactor:Uw,universalRouter:jw,permit2:ia}}),m1=["Relay(","bytes32,","address,","address,","uint256)"],Kw=()=>m1.join(""),h1=Kw(),ca=(()=>{let e="0x";for(let t of te(Kw()))e+=t.toString(16).padStart(2,"0");return e})();var w1=["filled","expired"],fd="filled";var Be=(e,t={})=>({ok:!1,code:e,params:t});var pd=e=>ud[Number(e)]||null,Zr=e=>/^0x[0-9a-fA-F]{40}$/.test(String(e||"")),ld=e=>{try{return BigInt(String(e))>0n}catch{return!1}},Vw=e=>/^0x[0-9a-fA-F]{64}$/.test(String(e||"")),dd=e=>/^0x[0-9a-fA-F]{130}$/.test(String(e||""));function $w(e={}){let t=Number(e.chainId),n=pd(t);if(!n)return{...Be("uniswap-relay-unknown-network",{chainId:Number.isFinite(t)?t:null}),known:Object.keys(ud).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(Zr(r)||a.push("swapper"),(!Zr(o)||String(o).toLowerCase()===ed)&&a.push("recipient"),Zr(e.sellToken)||a.push("sellToken"),Zr(s)||a.push("wrappedToken"),Zr(i)||a.push("universalRouter"),Number.isInteger(Number(e.fee))||a.push("fee"),ld(e.sellAmountWei)||a.push("sellAmountWei"),ld(e.buyAmountWei)||a.push("buyAmountWei"),Zr(e.feeToken)||a.push("feeToken"),ld(e.feeEndAmountWei)||a.push("feeEndAmountWei"),Number.isInteger(Number(e.deadline))||a.push("deadline"),a.length)return Be("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,d=e.feeEndTime===void 0||e.feeEndTime===null?e.deadline:e.feeEndTime,f;try{f=Mw({tokenIn:e.sellToken,weth:s,fee:e.fee,amountInWei:e.sellAmountWei,amountOutMinimumWei:e.buyAmountWei,recipient:o})}catch(w){return Be("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(d)},universalRouterCalldata:f},h=Fw(p);if(h.length)return Be("uniswap-relay-bad-order",{missing:h});try{let w=Dw({order:p,chainId:t}),b=Lw(p);return{ok:!0,chainId:t,owner:r,reactor:p.info.reactor,order:p,orderHash:b,calldata:f,typedData:w}}catch(w){return Be("uniswap-relay-bad-order",{why:String(w&&w.message?w.message:w)})}}function y1(e={}){let t=$w(e);return t.ok?{ok:!0,provider:"uniswaprelay",venue:Ww,shape:Ve,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:fd,final:[...w1],event:h1}}:t}async function g1({typedData:e,wallet:t,address:n=null}={}){if(!e||typeof e!="object")return Be("uniswap-relay-bad-order",{field:"typedData"});try{if(t&&typeof t.signTypedData=="function"){let o=await t.signTypedData(e);return dd(o)?{ok:!0,signature:o}:Be("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 dd(i)?{ok:!0,signature:i}:Be("uniswap-relay-sign-failed",{why:"bad-signature-shape"})}return Be("uniswap-relay-sign-failed",{why:"no-wallet"})}catch(r){return Be("uniswap-relay-sign-failed",{why:String(r&&r.code||r&&r.message||r)})}}function b1({order:e=null,signature:t=null,chainId:n=null}={}){let r=Number(n);return pd(r)?!e||typeof e!="object"?Be("uniswap-relay-bad-order",{field:"order"}):dd(t)?Be("uniswap-relay-no-discovery",{reactorIsPermissionless:!0,documentedSubmissionEndpoint:null,reason:"undocumented"}):Be("uniswap-relay-bad-order",{field:"signature"}):Be("uniswap-relay-unknown-network",{chainId:Number.isFinite(r)?r:null})}var x1=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:ca})}:e&&typeof e.request=="function"?{ok:!0,logs:await e.request({method:"eth_getLogs",params:[{address:n,fromBlock:o,toBlock:i,topics:[ca,r]}]})}:Be("uniswap-relay-unreachable",{why:"no-driver"})}catch(s){return Be("uniswap-relay-unreachable",{why:String(s&&s.code||s&&s.message||s)})}};async function zw({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),d=pd(l),f=n||(d?d.reactor:null);if(!f)return Be("uniswap-relay-unknown-network",{chainId:Number.isFinite(l)?l:null});if(!Vw(e))return Be("uniswap-relay-bad-order",{field:"orderHash"});let p=await x1({driver:o,getLogs:i,reactor:f,orderHash:e,fromBlock:s,toBlock:a});if(!p.ok)return p;let h=p.logs;if(!Array.isArray(h))return Be("uniswap-relay-bad-response",{where:"logs",got:typeof h});let w=h.filter(b=>{if(!b||!Array.isArray(b.topics))return!1;let y=String(b.topics[0]||"").toLowerCase(),v=String(b.topics[1]||"").toLowerCase();return y===ca.toLowerCase()&&v===String(e).toLowerCase()});if(h.length>0&&w.length===0)return Be("uniswap-relay-bad-response",{where:"logs",detail:"topics-mismatch"});if(w.length>0)return{ok:!0,status:fd,log:w[0]};if(r!=null){let b=typeof c=="function"?c():Number.isFinite(c)?c:Math.floor(Date.now()/1e3);if(Number(r)<b)return{ok:!0,status:"expired"}}return{ok:!0,status:"open"}}async function k1(e={},t={}){let{orderHash:n,chainId:r=null,reactor:o=null,deadline:i=null}=e;if(!Vw(n))return Be("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(h=>setTimeout(h,p)),c=Number.isFinite(t.pollMs)&&t.pollMs>0?t.pollMs:5e3,l=Number.isFinite(t.timeoutMs)&&t.timeoutMs>0?t.timeoutMs:3e5,d=s(),f=null;for(;;){let p=await zw({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(f=p.status,f===fd)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()-d>=l)return Be("uniswap-relay-not-settled",{orderHash:n,status:f,waitedMs:s()-d});await a(c)}}function S1({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:d=null,allowanceWei:f=null,allowanceConsent:p=!1,tokenIsNative:h=!1,symbol:w=null,decimals:b=null}={}){if(!e)return{ok:!1,blocked:!0,reason:"uniswap-relay-no-order",checks:[]};let y=t??(e.input?e.input.amount:null),v=n??null,I=ot.priceGateVerdict({amountInWei:y,amountOutWei:v,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:v===null?null:String(v),price:I,wrapped:{symbol:d,decimals:l}},T=ot.dexLegVerdict(g,r??v),A={ok:!T.blocked,checked:T.kind!=="unchecked"&&T.kind!=="unquoted",blocks:T.blocked===!0,kind:T.kind,reason:T.reason},B=ke.allowanceVerdict({tokenIsNative:h,allowanceWei:f,amountWei:y,consent:p===!0,symbol:w,decimals:Number.isFinite(Number(b))?Number(b):18});return{...ke.signingGateVerdict([A,B]),price:I,coverage:T,allowance:B}}var Xw=Object.freeze({id:"uniswaprelay",kind:"uniswaprelay",venue:Ww,shape:Ve,settles:"native",networks:ud,settlement:Uw,universalRouter:jw,permit2:ia,nativeToken:ed,eventTopic:ca,orderFields:sa,plan:y1,settled:k1,buildIntent:$w,sign:g1,submit:b1,status:zw,gate:S1});var v1="evm",Gw=e=>Number(e.chainId),E1=(e,t)=>{let n=Gw(t),r=Number(e);return Number.isFinite(r)&&Number.isFinite(n)&&r===n},Qw="0x70a08231",Yw=e=>{try{return BigInt(e).toString(10)}catch{return null}},A1=e=>String(e).replace(/^0x/,"").toLowerCase().padStart(64,"0");async function N1({driver:e,address:t,tokens:n}){let r=[];for(let o of n){let i=null;try{if(o.address===null)i=Yw(await e.request({method:"eth_getBalance",params:[t,"latest"]}));else{let s=Qw+A1(t);i=Yw(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 Zw={declared:{id:"declared",kind:"declared",shape:qo,async plan(){return{ok:!1,code:"not-implemented",stage:3}}},cowswap:rw,kyberswap:mw,uniswapx:Bw,uniswaprelay:Xw},qr=()=>Object.keys(Zw).sort(),la=e=>Zw[e]||null,_1=e=>{let t=la(e);return t?t.shape!==qo?{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()}},I1=e=>{let t=la(e);if(!t)return{ok:!1,reason:"provider-unknown",provider:typeof e=="string"?e:null,known:qr()};if(t.shape!==Ve)return{ok:!1,reason:"provider-not-asynchronous",provider:t.id,shape:t.shape===void 0?null:t.shape};let n=Ml(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}},T1=e=>{let t=la(e);if(!t)return{ok:!1,reason:"provider-unknown",provider:typeof e=="string"?e:null,known:qr()};let n=Ml(t);return n.ok?{ok:!0,provider:t}:{ok:!1,reason:n.reason,provider:t.id,shape:n.shape??null,missing:n.missing??null}},md=Object.freeze({NATIVE:"native",WRAPPED:"wrapped"}),qw=e=>e&&e.settles?e.settles:null,B1=e=>{let t=qw(e),n=e&&e.id?e.id:null;return t===md.NATIVE?{ok:!0,settles:t,provider:n}:t===md.WRAPPED?{ok:!1,reason:"settles-wrapped",settles:t,provider:n}:{ok:!1,reason:"settles-unstated",settles:null,provider:n}};var C1=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"})}),Jw=e=>C1[e]||null;var ey={evm:hd},ty=()=>Object.keys(ey).sort(),Jr=e=>ey[e]||null,O1=e=>(pe.CHAINS||[]).find(t=>t&&t.id===e)||null,wd=e=>{let t=O1(e);return t&&t.vm?t.vm:null},ny=e=>{let t=wd(e);return t?Jw(t):null};var R1=e=>{let t=typeof pe.chainByChainId=="function"?pe.chainByChainId(e):null;t||Q("bad-input",{field:"chain.chainId",unknown:e,why:"no-network-with-this-chainId"});let n=pe.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("|")&&Q("bad-input",{field:"chain.tokens",unknown:e,why:"tokens-belong-to-another-network"}),n},P1=e=>({id:e.id,name:e.name,vm:e.vm||null,settlementProfile:ny(e.id),chainId:e.chainId,nativeSymbol:e.native&&e.native.symbol?e.native.symbol:null,tokens:R1(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}),ry=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"}]}),H1=e=>typeof e=="string"&&e||e&&typeof e=="object"&&typeof e.url=="string"&&e.url,yd=e=>Array.isArray(e)&&e.every(H1),F1=(e,t)=>{let n=e&&e.nodes,r=e&&e.addNodes,o={mainnet:[...ry.mainnet],stagenet:[...ry.stagenet]};if(n!=null)if(yd(n))t in o||Q("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||Q("bad-input",{field:"nodes",unknown:i,known:Object.keys(o)}),yd(n[i])||Q("bad-input",{field:"nodes."+i}),o[i]=[...n[i]];else Q("bad-input",{field:"nodes"});return r!=null&&(yd(r)||Q("bad-input",{field:"addNodes"}),t in o||Q("bad-input",{field:"addNodes",network:t}),o[t]=[...o[t],...r]),o},gd=e=>Number.isFinite(Number(e))&&Number(e)>0?Number(e):null,L1=e=>{let t=e&&e.watch||{},n=t.pollMs===void 0?gd(pe.API&&pe.API.pollMs)||5e3:Number(t.pollMs);(!Number.isFinite(n)||n<=0)&&Q("bad-input",{field:"watch.pollMs"});let r=pe.MONERO||{},o=(gd(r.blockTimeReal)||12e4)*(gd(r.confirmTarget)||10),i=t.timeoutMs===void 0?o:Number(t.timeoutMs);return(!Number.isFinite(i)||i<=0)&&Q("bad-input",{field:"watch.timeoutMs"}),{pollMs:n,timeoutMs:i}},D1=(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 oy(e){let t=pe.CHAINS.map(P1),n=t.find(w=>w.id===e.settlement.chain)||null;n||Q("bad-input",{field:"settlement.chain",known:t.map(w=>w.id)});let r=pe.CHAINS.find(w=>w.id===e.settlement.chain)||{},o=L1(e),i=D1(r,e),s=F1(e,e.xmrNetwork),a=e.settlement.vm||n.vm;a||Q("bad-input",{field:"settlement.vm"}),a!==n.vm&&Q("bad-input",{field:"settlement.vm",chain:n.id,vm:n.vm,got:a}),Jr(a)||Q("not-implemented",{surface:"settlement.vm",vm:a,implemented:ty()});let l=qr(),d=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 d)l.includes(w)||Q("bad-input",{field:"routing.prefer",unknown:w,known:l});let f=["mainnet","stagenet","testnet","fakechain"],p=[...new Set([...Object.values(pe.XMR_NETWORKS||{}),...f])];p.includes(e.xmrNetwork)||Q("bad-input",{field:"xmrNetwork",known:p});let h=pe.SIGNING_GUARDS||{};return{settlement:{chain:n,vm:a},chains:t,xmrNetworks:p,assetsBase:e.assetsBase,mode:e.mode,limits:{minAmount:null,maxAmount:null,stepAmount:null,xmrConfirmTarget:pe.MONERO.confirmTarget??null,watchPollMs:o.pollMs,watchTimeoutMs:o.timeoutMs,xmrConfirmations:pe.MONERO.confirmTarget??10,xmrBlockTimeSec:Math.round((pe.MONERO.blockTimeReal??12e4)/1e3),readyLeadWarnSec:h.readyLeadWarnSec??null},routing:{providers:l,prefer:d},endpoints:i,xmrNodes:s,nodesFor:w=>s&&s[w]?s[w]:[],codes:{steps:zs,checks:Xs,errors:Kr}}}function iy({chain:e,knownFactoryCodes:t}={}){return t??pe.knownFactoryCodesFor(e)}function sy({chain:e,knownImplementationCodes:t}={}){if(t!=null)return t;let n=typeof e=="string"?e:e&&e.id,r=n?pe.chainById(n):null;return!r||String(r.id)!==String(n)?null:pe.knownImplementationCodesFor(e)}me();Tc();Ft();function M1(e,t,n,r){kr(e);let o=Ui({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=ac(t,"password");try{let l=ac(n,"salt");try{let d=new Uint8Array(s),{iHash:f,oHash:p,outputLen:h}=is.create(e,c),w=new Uint8Array(h),b=U1(f,p,l,w);return{c:i,dkLen:s,asyncTick:a,DK:d,outputLen:h,eng:b}}finally{typeof n=="string"&&Je(l)}}finally{typeof t=="string"&&Je(c)}}function U1(e,t,n,r){let o=new Uint8Array(4),i=vr(o),s=e._cloneInto().update(n),a=t._cloneInto(),c=e._cloneInto,l=t._cloneInto;return{u1:(d,f)=>{i.setInt32(0,d,!1),s._cloneInto(a).update(o).digestInto(r),t._cloneInto(a).update(r).digestInto(r),f.set(r.subarray(0,f.length))},rounds:(d,f)=>{for(let p=1;p<d;p++){c.call(e,a).update(r).digestInto(r),l.call(t,a).update(r).digestInto(r);for(let h=0;h<f.length;h++)f[h]^=r[h]}},output:d=>(e.destroy(),t.destroy(),s.destroy(),a.destroy(),Je(r),d)}}function ay(e,t,n,r){let{c:o,dkLen:i,DK:s,outputLen:a,eng:c}=M1(e,t,n,r);for(let l=1,d=0;d<i;l++,d+=a){let f=s.subarray(d,d+a);c.u1(l,f),c.rounds(o,f)}return c.output(s)}Wi();Ft();function cy(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 ly(e){if(typeof e!="string")throw new TypeError("invalid mnemonic type: "+typeof e);if(!cy(e))throw new TypeError("expected well-formed Unicode string");return e.normalize("NFKD")}function dy(e){let t=ly(e),n=t.split(" ");if(![12,15,18,21,24].includes(n.length))throw new Error("Invalid mnemonic");return{nfkd:t,words:n}}function j1(e){if(We(e),![16,20,24,28,32].includes(e.length))throw new RangeError("invalid entropy length")}var W1=e=>{let t=8-e.length/4;return ji(e)[0]>>t<<t};function K1(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(!cy(t))throw new TypeError("wordlist: expected well-formed Unicode string")})}function V1(e,t){K1(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]!==W1(a))throw new Error("Invalid checksum");return Uint8Array.from(a)}function $1(e,t){let{words:n}=dy(e),r=V1(n,t);return j1(r),r}function uy(e,t){try{$1(e,t)}catch{return!1}return!0}var z1=e=>{if(typeof e!="string")throw new TypeError("invalid passphrase type: "+typeof e);return ly("mnemonic"+e)};function fy(e,t=""){return ay(Oo,dy(e).nfkd,z1(t),{c:2048,dkLen:64})}var py=Object.freeze(`abandon
|
|
3
3
|
ability
|
|
4
4
|
able
|
|
5
5
|
about
|
|
@@ -2047,11 +2047,11 @@ zebra
|
|
|
2047
2047
|
zero
|
|
2048
2048
|
zone
|
|
2049
2049
|
zoo`.split(`
|
|
2050
|
-
`));
|
|
2051
|
-
`)}function
|
|
2050
|
+
`));Ko();me();var X1=new Set(["mainnet","stagenet","testnet","fakechain"]);function my(e){let t=String(e&&e.nettype||"").trim().toLowerCase();return X1.has(t)?t:null}var hy=8e3,Y1=e=>typeof e=="string"?e.trim():"";async function wy({url:e,fetchImpl:t=globalThis.fetch,timeoutMs:n=hy}={}){let r=Y1(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)||hy)):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(p){return s&&clearTimeout(s),{ok:!1,why:p&&(p.name==="AbortError"||p.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||{},d=Number(l.height);if(!Number.isInteger(d)||d<0)return{ok:!1,why:"no-height",ms:Date.now()-o};let f=my(l);return f?{ok:!0,url:r,height:d,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}}_e();var Bn=Wo({ed25519:Te,secp256k1:Pe,keccak256:te,randomBytes:Vn}),gy=1,G1=12,by="ninsei.recovery.key.v1",Q1="NINSEI RECOVERY KEY",Z1="ninsei-taker-v2",q1="ninsei-maker-view-v1",J1=1,e2="AES-GCM-256/PBKDF2-SHA256",yy=6e5;var t2=/^0x[0-9a-fA-F]{40}$/,da=new TextEncoder,tT=new TextDecoder,bd=e=>"0x"+BigInt(e).toString(16).padStart(64,"0");var xd=e=>{let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t)};var xt=e=>new u("bad-input",{field:e}),xy=e=>new u("recovery-failed",{stage:e});function ky(e){if(typeof e!="string")throw xt("mnemonic");let t=e.trim().toLowerCase().replace(/\s+/g," ");if(!t||t.split(" ").length!==G1||!uy(t,py))throw xt("mnemonic");return t}function Sy(e){let t=e instanceof Date?e:e?new Date(e):new Date;if(Number.isNaN(t.getTime()))throw xt("createdAt");return t.toISOString()}function Ed(e,{createdAt:t}={}){return ua(e,t)}function ua(e,t){let n=ky(e);return{version:gy,mnemonic:n,fingerprint:Ad(n),createdAt:Sy(t)}}function Ad(e){let t=typeof e=="string"?e.trim().toLowerCase().replace(/\s+/g," "):"";if(!t)throw xt("mnemonic");return Array.from(te(da.encode(t)),n=>n.toString(16).padStart(2,"0")).join("").slice(0,4)}function n2(e){return fy(ky(e))}function r2(e,t){let n=Number(e);if(!Number.isSafeInteger(n)||n<0)throw xt(t);return n}function o2({chainId:e,factory:t,role:n="taker",salt:r}={}){if(typeof t!="string"||!t2.test(t))throw xt("factory");if(typeof n!="string"||!/^[a-z0-9-]{1,32}$/.test(n))throw xt("role");return`${Z1}|${r2(e,"chainId")}|${t.toLowerCase()}|${n}|${qt(r)}`}function sr({mnemonic:e,chainId:t,factory:n,role:r="taker",salt:o}={}){let i=qt(o),s=o2({chainId:t,factory:n,role:r,salt:i});return{...i2(n2(e),s),derivation:"salt-v2",factory:n.toLowerCase(),role:r,salt:i}}function i2(e,t){let n=Bn.halfFromSeed(e,t,Bn.HALF_DOMAIN),r=Bn.halfFromSeed(e,t,Bn.VIEW_HALF_DOMAIN),o=Bn.halfFromSeed(e,t,q1),i=Bn.publicHalves(n),s=Bn.publicHalves(r),a=Bn.publicHalves(o);return{binding:t,spendHalf:bd(n),viewHalf:bd(r),spendPoint:i.ed,viewPoint:s.ed,makerViewHalf:bd(o),makerViewPoint:a.ed,spendCommitment:Lr(n,Pe,te)}}function vy(){return"0x"+Array.from(Vn(32),e=>e.toString(16).padStart(2,"0")).join("")}function qt(e){return typeof e=="bigint"?kd("0x"+e.toString(16).padStart(64,"0")):typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?kd("0x"+BigInt(e).toString(16).padStart(64,"0")):kd(e)}function kd(e){let t=String(e??"").trim().toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(t))throw xt("salt");return t}var Ey=e=>Sy(e).slice(0,10);function Nd({mnemonic:e,fingerprint:t,createdAt:n}={}){let r=t||Ad(e);return`ninsei-recovery-key-DO-NOT-DELETE-${Ey(n)}-${r}.txt`}function s2({fingerprint:e,createdAt:t}){return[Q1,"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 ${Ey(t)}`].join(`
|
|
2051
|
+
`)}function a2({mnemonic:e,createdAt:t}={}){let n=ua(e,t);return`${s2(n)}
|
|
2052
2052
|
|
|
2053
2053
|
${n.mnemonic}
|
|
2054
|
-
`}async function SA(e,t,n){if(!globalThis.crypto||!globalThis.crypto.subtle)throw mb("crypto-unavailable");let r=await crypto.subtle.importKey("raw",ec.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 EA=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 Zd({mnemonic:e,createdAt:t,passphrase:n=""}={}){let r=tc(e,t);if(typeof n!="string")throw Tt("passphrase");if(n==="")return vA(r);if(n.length<12)throw Tt("passphrase");if(!globalThis.crypto||!globalThis.crypto.subtle)throw mb("crypto-unavailable");let o=crypto.getRandomValues(new Uint8Array(16)),i=crypto.getRandomValues(new Uint8Array(12)),s={kind:"ninsei-recovery-key",v:hA,alg:mA,iter:fb,salt:$d(o),iv:$d(i),meta:{fingerprint:r.fingerprint,createdAt:r.createdAt}},a=await SA(n,o,fb),c=await crypto.subtle.encrypt({name:"AES-GCM",iv:i,tagLength:128,additionalData:ec.encode(EA(s))},a,ec.encode(JSON.stringify({mnemonic:r.mnemonic})));return JSON.stringify({...s,ciphertext:$d(new Uint8Array(c))},null,2)}var Ri=e=>new f("storage-unavailable",{step:e}),AA=e=>{if(!e||typeof e.get!="function"||typeof e.set!="function"||typeof e.remove!="function")throw Tt("storage");let t;try{t=e.get(hb)}catch{throw Ri("read")}if(t==null||t==="")return null;let n;try{n=JSON.parse(t)}catch{throw Ri("parse")}if(!n||n.version!==pb||typeof n.mnemonic!="string")throw Ri("parse");return n},_A=(e,t)=>{let n;try{n=JSON.stringify(t)}catch{throw Ri("serialize")}try{e.set(hb,n)}catch{throw Ri("write")}};function Hi(e,t){let n=tc(t&&t.mnemonic,t&&t.createdAt);return _A(e,{...n,backupConfirmed:t.backupConfirmed===!0}),n}function Jd(e){let t=AA(e);return t?{...t,fingerprint:t.fingerprint||qd(t.mnemonic)}:null}var NA=18,IA=45,QI=IA+NA*32;var Xd=e=>"0x"+Array.from(J(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)")}),ZI=new Map([[Yd.halfRevealed,"HalfRevealed"],[Yd.ready,"Ready"],[Yd.declined,"Declined"]]);xe();$e();var ct=()=>da.createOrderBuilder(hn);function Ut(e){if(!e||typeof e!="object")throw new f("bad-input",{field:"order"});try{return At.orderContextString(e)}catch{throw new f("bad-input",{field:"order"})}}function kb({side:e,order:t,sealed:n=null,ownEncPriv:r=null}){if(!e||typeof e!="object")throw new f("bad-input",{field:"side"});let o=Ut(t),i=null;try{i=ct().verifySide(e,o,n,r)}catch{throw new f("bad-input",{field:"side"})}if(!i||i.ok!==!0)throw new f("quote-refused",{step:"proof",why:i&&i.reason?"rejected":"unknown"});return e}function go({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 f("bad-input",{field:"jointAddress",missing:s});try{return ct().jointAddress({ownSpendHalf:e,ownViewHalf:t,otherSpendPoint:n,otherViewPoint:r,network:o})}catch{throw new f("bad-input",{field:"jointAddress"})}}var ge=e=>"0x"+String(e).replace(/^0x/i,"").toLowerCase(),xn=e=>"0x"+BigInt(e).toString(16).padStart(64,"0"),ef=e=>/^0x[0-9a-f]{64}$/.test(String(e)),xb=e=>e&&typeof e=="object"&&e.XB?{...e,XB:ge(e.XB)}:e,nc=e=>typeof e=="string"&&e?ge(e):e;function tf(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 f("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 f("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=nc(o[0]),!ef(i))throw new f("bad-input",{field:"counterparty",why:"view-point"});for(let s of o.slice(1))if(nc(s)!==i)throw new f("bad-input",{field:"counterparty",why:"conflicting-view-point"})}if(r!==null){let s=null;try{s=nc(ct().pointOf(r))}catch{s=null}if(!s)throw new f("bad-input",{field:"counterparty",why:"view-half"});if(i!==null&&i!==s)throw new f("bad-input",{field:"counterparty",why:"view-half-point-mismatch"});i=s}return{half:r===null?null:n[0],point:i}}function nf(e,t){let n=Ut(e),r=ct().newSide(n,!1,t);return{context:n,side:r,spendPoint:ge(r.pub.ed),viewPoint:ge(r.viewPub),encPub:ge(r.enc.pub)}}async function TA(e,t={}){let n=Ut(e),r=await ct().newSideChunked(n,!1,t);return{context:n,side:r,spendPoint:ge(r.pub.ed),viewPoint:ge(r.viewPub),encPub:ge(r.enc.pub)}}function rf(e,{spendHalf:t,viewHalf:n}={}){let r=(s,a)=>{let c=BigInt(s);if(c<=0n||c>=BigInt(e.halves.LIMIT))throw new f("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 of({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:ge(n.ed),viewPoint:ge(r),encPub:ge(o.pub)}}function vb(e,{spendHalf:t,viewHalf:n}={}){let r=Ut(e),o=ct(),i=rf(o,{spendHalf:t,viewHalf:n}),s=o.dleq.prove(i.half,r),{side:a,spendPoint:c,viewPoint:l,encPub:u}=of(i,s);return{context:r,side:a,spendPoint:c,viewPoint:l,encPub:u}}async function Sb(e,{spendHalf:t,viewHalf:n}={},r={}){let o=Ut(e),i=ct(),s=rf(i,{spendHalf:t,viewHalf:n}),a=await i.dleq.proveChunked(s.half,o,r),{side:c,spendPoint:l,viewPoint:u,encPub:d}=of(s,a);return{context:o,side:c,spendPoint:l,viewPoint:u,encPub:d,commitHalf:ge(i.halfCommitment(s.half))}}function sf(e,{spendHalf:t,viewHalf:n}={}){let r=Ut(e),o=ct(),i=rf(o,{spendHalf:t,viewHalf:n}),{side:s,spendPoint:a,viewPoint:c,encPub:l}=of(i,null);return{context:r,side:s,spendPoint:a,viewPoint:c,encPub:l,commitHalf:ge(o.halfCommitment(i.half))}}function BA({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=tf(n);i={proof:xb(n.proof),edPub:nc(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||ct().newSide(e,!0);i={proof:xb(c.proof),edPub:ge(c.pub.ed),viewPoint:ge(c.viewPub),viewHalf:c.viewHalf,half:c.half,commitHalfClaimer:ge(ct().halfCommitment(c.half)),sealed:null,providerId:null,standIn:!0,mock:c}}else throw new f("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 f("bad-input",{field:"counterparty",missing:s});let a=i.sealed&&t&&t.enc?t.enc.priv:null;return{accepted:i,ownEncPriv:a}}async function af({context:e,side:t=null,counterparty:n=null,standIn:r=!1,options:o={}}){let i=n||r!==!0?null:await ct().newSideChunked(e,!0,o),{accepted:s,ownEncPriv:a}=BA({context:e,side:t,counterparty:n,standIn:r,mock:i}),c=null;try{c=await ct().verifySideChunked({proof:s.proof,pub:{ed:s.edPub},commitHalfClaimer:s.commitHalfClaimer},e,s.sealed,a,o)}catch{throw new f("bad-input",{field:"counterparty"})}if(!c||c.ok!==!0)throw new f("quote-refused",{step:"proof",why:c&&c.reason?"rejected":"unknown"});return s}function PA({order:e,side:t,context:n}){return t?{context:n,side:t,spendPoint:ge(t.pub&&t.pub.ed),viewPoint:ge(t.viewPub),encPub:ge(t.enc&&t.enc.pub?t.enc.pub:null)}:nf(e)}function OA(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"),ef(e.spendPoint)||t.push("spendPoint"),ef(e.viewPoint)||t.push("viewPoint"),t.length)throw new f("bad-input",{field:"side",missing:t})}function CA({own:e,other:t,network:n}){let r=t.viewPoint||(t.viewHalf?ge(ct().pointOf(t.viewHalf)):null);if(!r)throw new f("bad-input",{field:"counterparty",missing:["viewPoint"]});let o=null;try{o=ct().jointAddress({ownSpendHalf:e.side.half,ownViewHalf:e.side.viewHalf,otherSpendPoint:t.edPub,otherViewPoint:r,network:n})}catch{throw new f("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:xn(e.side.half),viewHalf:xn(e.side.viewHalf),otherSpendPoint:t.edPub,otherViewPoint:ge(r),otherViewHalf:t.viewHalf?xn(t.viewHalf):null,address:o.address,spendPub:ge(o.spendPub),viewPub:ge(o.viewPub),otherCommitHalf:t.commitHalfClaimer||null,commitHalfLocker:ge(ct().halfCommitment(e.side.half)),commitHalfClaimer:t.commitHalfClaimer||null,network:n||null}}}async function Eb({order:e,side:t=null,counterparty:n=null,standIn:r=!1,network:o=null,options:i={}}){let s=Ut(e),a=t?PA({order:e,side:t,context:s}):await TA(e,i);OA(a);let c=await af({context:a.context,side:a.side,counterparty:n,standIn:r,options:i});return CA({own:a,other:c,network:o})}xe();xe();$e();xe();$e();var RA="Ninsei Relay",HA="1",LA="EIP712Domain(string name,string version)",_b="FirmWindow(string market,string side,string xmrNetwork,uint32 readyMinSeconds,uint32 readyMaxSeconds,uint32 settlementMinSeconds,uint32 settlementMaxSeconds,uint32 quoteTtlSeconds)",FA="NodeFeatures(string relayId,address provider,address quoteKey,address registry,bytes32 hpkeKey,FirmWindow[] firmWindows,uint64 time,bytes32 nonce)"+_b,DA=[["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"]],qn=(e,t)=>{if(typeof e=="string")return e;if(typeof e=="number"&&Number.isFinite(e)||typeof e=="bigint")return String(e);throw new f("bad-input",{field:t})},UA=(e,t)=>{let n=null;try{n=Number(e)}catch{n=null}if(!Number.isFinite(n))throw new f("bad-input",{field:t});return n},xo=(e,t="text")=>new TextEncoder().encode(qn(e,t)),ko=(...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=qn(e??"",t).replace(/^0x/,"");if(!new RegExp("^[0-9a-fA-F]{"+n*2+"}$").test(r))throw new f("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},Nb=(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 f("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=qn(e??"",t).trim();if(!/^(0x)?[0-9a-fA-F]{40}$/.test(n))throw new f("bad-input",{field:t});let r=new Uint8Array(32);return r.set(rc(n,t,20),12),r},cf=(e,t)=>J(xo(e??"",t)),Ab=(e,t,n)=>{if(!Array.isArray(e))throw new f("bad-input",{field:t});let r=e.map(o=>n(o));return J(ko(...r))};function KA(e){if(!e||typeof e!="object")throw new f("bad-input",{field:"firmWindows"});let t=[J(xo(_b))];for(let[n,r]of DA)t.push(r==="string"?cf(e[n],"firmWindows."+n):Nb(e[n],"firmWindows."+n,32));return J(ko(...t))}function WA(e){if(!e||typeof e!="object")throw new f("bad-input",{field:"features"});let t=[J(xo(FA))];for(let[n,r]of MA)if(r==="string")t.push(cf(e[n],"features."+n));else if(r==="address")t.push(jA(e[n],"features."+n));else if(r==="bytes32")t.push(rc(e[n],"features."+n,32));else if(r==="uint64")t.push(Nb(e[n],"features."+n,64));else if(r==="string[]")t.push(Ab(e[n],"features."+n,o=>cf(o,"features."+n)));else if(r==="FirmWindow[]")t.push(Ab(e[n],"features."+n,KA));else throw new f("bad-input",{field:"features."+n});return J(ko(...t))}function VA(){return J(ko(J(xo(LA)),J(xo(RA)),J(xo(HA))))}function $A(e){return J(ko(Uint8Array.from([25,1]),VA(),WA(e)))}var lf=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t};function zA(e,t){let n=qn(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=Ve.Signature.fromBytes(ko(rc(n.slice(0,64),"signature",32),rc(n.slice(64,128),"signature",32))).addRecoveryBit(r).recoverPublicKey(e);return lf(J(o.toBytes(!1).slice(1)).slice(12))}catch{return null}}function Ib({features:e,terms:t=null}={}){if(!e||typeof e!="object")throw new f("bad-input",{field:"features"});if(e.type!=="node_features"||UA(e.version,"features.version")!==1)throw new f("quote-refused",{step:"features",why:"version"});let n=$A(e),r=zA(n,e.signature),o=qn(e.quoteKey===void 0||e.quoteKey===null?"":e.quoteKey,"features.quoteKey").toLowerCase();if(r===null||r!==o)throw new f("quote-refused",{step:"features",why:"signature"});let i=qn(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 f("quote-refused",{step:"features",why:"hpke-key"});if(!Array.isArray(e.firmWindows)||e.firmWindows.length===0)throw new f("quote-refused",{step:"features",why:"windows"});if(t){if(qn(e.provider===void 0||e.provider===null?"":e.provider,"features.provider").toLowerCase()!==String(t.maker||"").toLowerCase()||qn(e.registry===void 0||e.registry===null?"":e.registry,"features.registry").toLowerCase()!==String(t.registry||"").toLowerCase())throw new f("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 f("quote-refused",{step:"features",why:"window"});return{featuresHash:lf(n),hpkeKey:"0x"+i,window:l}}return{featuresHash:lf(n),hpkeKey:"0x"+i,window:null}}var mt=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 mt{};var jt=class extends mt{},Bt=class extends mt{},Li=class extends mt{},Fi=class extends mt{},Di=class extends mt{},Mi=class extends mt{},Ui=class extends mt{},ji=class extends mt{},Qn=class extends mt{},wt=class extends mt{};var XA={},uf=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(uf!==void 0&&globalThis.crypto!==void 0)return globalThis.crypto.subtle;try{let{webcrypto:e}=await import("crypto");return e.subtle}catch(e){throw new wt(e)}}var Pt=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 rn={Base:0,Psk:1,Auth:2,AuthPsk:3},on={NotAssigned:0,DhkemP256HkdfSha256:16,DhkemP384HkdfSha384:17,DhkemP521HkdfSha512:18,DhkemSecp256k1HkdfSha256:19,DhkemX25519HkdfSha256:32,DhkemX448HkdfSha512:33,HybridkemX25519Kyber768:48,MlKem512:64,MlKem768:65,MlKem1024:66,XWing:25722},Ki={HkdfSha256:1,HkdfSha384:2,HkdfSha512:3,Sha3256:4,Sha3384:5,Sha3512:6,Shake128:16,Shake256:17,TurboShake128:18,TurboShake256:19},Zn={Aes128Gcm:1,Aes256Gcm:2,Chacha20Poly1305:3,ExportOnly:65535};var Ne=new Uint8Array(0),oc=0n;var ic=new Uint8Array([75,69,77,0,0]);var Bb=new Uint8Array([72,80,75,69,45,118,49]);function vo(e){return new Uint8Array(fe(e))}function fe(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 df=class extends Pt{constructor(){super(),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:Ki.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}})}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(Bb,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(Bb,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):fe(t);if(r.byteLength!==this.hashSize)throw new Xe("The salt length must be the same as the hashSize");let o=fe(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=fe(t),i=await this._api.importKey("raw",o,this.algHash,!1,["sign"]),s=new ArrayBuffer(r),a=new Uint8Array(s),c=Ne,l=vo(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,h=0;h<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-h>=c.length?(a.set(c,h),h+=c.length):(a.set(c.slice(0,a.length-h),h),h+=a.length-h);return s}async extractAndExpand(t,n,r,o){await this._setup();let i=fe(n),s=await this._api.importKey("raw",i,"HKDF",!1,["deriveBits"]);return await this._api.deriveBits({name:"HKDF",hash:this.algHash.hash,salt:fe(t),info:fe(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()")}},Jn=class extends df{constructor(){super(...arguments),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:Ki.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 er=e=>typeof e=="object"&&e!==null&&typeof e.privateKey=="object"&&typeof e.publicKey=="object";function Kt(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 Ar(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function So(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 ff(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 _r=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(ic);o.set(Kt(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(fe(t))}async serializePrivateKey(t){return await this._prim.serializePrivateKey(t)}async deserializePrivateKey(t){return await this._prim.deserializePrivateKey(fe(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=fe(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():er(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=er(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=Ar(l,u)}let s;if(t.senderKey===void 0)s=Ar(new Uint8Array(r),new Uint8Array(o));else{let c=er(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 Li(i)}}async decap(t){let n=fe(t.enc),r=await this._prim.deserializePublicKey(n),o=er(t.recipientKey)?t.recipientKey.privateKey:t.recipientKey,i=er(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=Ar(l,u)}let c;if(t.senderPublicKey===void 0)c=Ar(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 Fi(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(Ne,r,o,this.secretSize)}};var tr=["deriveBits"],Ir=new Uint8Array([100,107,112,95,112,114,107]),Eo=new Uint8Array([115,107]);var F4={p:(1n<<521n)-1n,b:0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00n,gx:0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66n,gy:0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650n,coordinateSize:66};function e6(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Wt(e,t=""){if(!Number.isSafeInteger(e)||e<0){let n=t&&`"${t}" `;throw new Error(`${n}expected integer >0, got ${e}`)}}function Ie(e,t,n=""){let r=e6(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 sn(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){Ie(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 Ot(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function nt(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}var t6=new Uint32Array([287454020]),n6=new Uint8Array(t6.buffer),pf=n6[0]===68;function sc(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Wi(e){Wt(e,"numberToBigint");let t=e,n=oc,r=1n;for(;t>0;)t%2===1&&(n+=r),t=Math.floor(t/2),r<<=1n;return n}function kn(e){return Uint8Array.from(e)}function Ob(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Wt(e.outputLen),Wt(e.blockLen)}var ac=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}),Ob(t),Ie(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),nt(o)}update(t){return sn(this),this.iHash.update(t),this}digestInto(t){sn(this),Ie(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()}},Cb=(e,t,n)=>new ac(e,t).update(n).digest();Cb.create=(e,t)=>new ac(e,t);var cc=0xffffffffn,Rb=32n;function r6(e,t=!1){return t?{h:Number(e&cc),l:Number(e>>Rb&cc)}:{h:Number(e>>Rb&cc)|0,l:Number(e&cc)|0}}function hf(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}=r6(e[i],t);[r[i],o[i]]=[s,a]}return[r,o]}var a6=0n,Vi=1n,c6=2n,l6=7n,u6=256n,d6=0x71n,f6=[],p6=[],Hb=[];for(let e=0,t=Vi,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],f6.push(2*(5*r+n)),p6.push((e+1)*(e+2)/2%64);let o=a6;for(let i=0;i<7;i++)t=(t<<Vi^(t>>l6)*d6)%u6,t&c6&&(o^=Vi<<(Vi<<BigInt(i))-Vi);Hb.push(o)}var Lb=hf(Hb,!0),$T=Lb[0],zT=Lb[1];function yf(){return new Promise((e,t)=>{t(new wt("Not supported"))})}var y6=new Uint8Array([115,101,99]),_o=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 yf()}async open(t,n){return await yf()}async export(t,n){let r=fe(t);if(r.byteLength>8192)throw new Xe("Too long exporter context");try{return await this._kdf.labeledExpand(this.exporterSecret,y6,new Uint8Array(r),n)}catch(o){throw new Di(o)}}},lc=class extends _o{},uc=class extends _o{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 No=class extends _o{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=Kt(t.seq,t.baseNonce.byteLength);return ff(t.baseNonce,n).buffer}incrementSeq(t){if(t.seq>Number.MAX_SAFE_INTEGER)throw new ji("Message limit reached");t.seq+=1}};var b6=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)},g6=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},dc,Io=class{constructor(){dc.set(this,Promise.resolve())}async lock(){let t,n=new Promise(o=>{t=o}),r=b6(this,dc,"f");return g6(this,dc,n,"f"),await r,t}};dc=new WeakMap;var Mb=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)},x6=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,fc=class extends No{constructor(){super(...arguments),$i.set(this,void 0)}async open(t,n=Ne.buffer){x6(this,$i,Mb(this,$i,"f")??new Io,"f");let r=await Mb(this,$i,"f").lock(),o;try{o=await this._ctx.key.open(this.computeNonce(this._ctx),fe(t),fe(n))}catch(i){throw new Ui(i)}finally{r()}return this.incrementSeq(this._ctx),o}};$i=new WeakMap;var Ub=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)},k6=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},zi,pc=class extends No{constructor(t,n,r,o){super(t,n,r),Object.defineProperty(this,"enc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),zi.set(this,void 0),this.enc=o}async seal(t,n=Ne.buffer){k6(this,zi,Ub(this,zi,"f")??new Io,"f");let r=await Ub(this,zi,"f").lock(),o;try{o=await this._ctx.key.seal(this.computeNonce(this._ctx),fe(t),fe(n))}catch(i){throw new Mi(i)}finally{r()}return this.incrementSeq(this._ctx),o}};zi=new WeakMap;var v6=new Uint8Array([98,97,115,101,95,110,111,110,99,101]),S6=new Uint8Array([101,120,112]),E6=new Uint8Array([105,110,102,111,95,104,97,115,104]),A6=new Uint8Array([107,101,121]),_6=new Uint8Array([112,115,107,95,105,100,95,104,97,115,104]),N6=new Uint8Array([115,101,99,114,101,116]),I6=new Uint8Array([72,80,75,69,0,0,0,0,0,0]),hc=class extends Pt{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(I6),this._suiteId.set(Kt(this._kem.id,2),4),this._suiteId.set(Kt(this._kdf.id,2),6),this._suiteId.set(Kt(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?rn.AuthPsk:rn.Psk:r=t.senderKey!==void 0?rn.Auth:rn.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?rn.AuthPsk:rn.Psk:r=t.senderPublicKey!==void 0?rn.Auth:rn.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:vo(r.psk.id),i=await this._kdf.labeledExtract(Ne,_6,o),s=r.info===void 0?Ne:vo(r.info),a=await this._kdf.labeledExtract(Ne,E6,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:vo(r.psk.key),u=this._kdf.buildLabeledIkm(N6,l),d=this._kdf.buildLabeledInfo(S6,c,this._kdf.hashSize),p=await this._kdf.extractAndExpand(n,u,d,this._kdf.hashSize);if(this._aead.id===Zn.ExportOnly)return{aead:this._aead,exporterSecret:p};let h=this._kdf.buildLabeledInfo(A6,c,this._aead.keySize),w=await this._kdf.extractAndExpand(n,u,h,this._aead.keySize),y=this._kdf.buildLabeledInfo(v6,c,this._aead.nonceSize),k=await this._kdf.extractAndExpand(n,u,y,this._aead.nonceSize);return{aead:this._aead,exporterSecret:p,key:w,baseNonce:new Uint8Array(k),seq:0}}async _keyScheduleS(t,n,r,o){let i=await this._keySchedule(t,n,o);return i.key===void 0?new uc(this._api,this._kdf,i.exporterSecret,r):new pc(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 lc(this._api,this._kdf,o.exporterSecret):new fc(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 Xi=class extends hc{};var Yi=class extends Jn{};var Gi="X25519",T6=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),B6=(()=>{let e=new Uint8Array(32);return e[0]=9,e})(),mc=class extends Pt{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:Gi},this._hkdf=t,this._nPk=32,this._nSk=32,this._nDh=32,this._pkcs8AlgId=T6}async serializePublicKey(t){await this._setup();try{return await this._api.exportKey("raw",t)}catch(n){throw new jt(n)}}async deserializePublicKey(t){await this._setup();try{return await this._importRawKey(fe(t),!0)}catch(n){throw new Bt(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 So(n.d).buffer}catch(n){throw new jt(n)}}async deserializePrivateKey(t){await this._setup();try{return await this._importRawKey(fe(t),!1)}catch(n){throw new Bt(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 Bt(o)}}async generateKeyPair(){await this._setup();try{return await this._api.generateKey(Gi,!0,tr)}catch(t){throw new wt(t)}}async deriveKeyPair(t){await this._setup();try{let n=fe(t),r=await this._hkdf.labeledExtract(Ne,Ir,new Uint8Array(n)),o=await this._hkdf.labeledExpand(r,Eo,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 Qn(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",B6.buffer,this._alg,!0,[]),r=await this._api.deriveBits({name:Gi,public:n},t,this._nPk*8);return await this._api.importKey("raw",r,this._alg,!0,[])}catch(n){throw new Bt(n)}}}async dh(t,n){await this._setup();try{return await this._api.deriveBits({name:Gi,public:n},t,this._nDh*8)}catch(r){throw new jt(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!==Gi)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,tr)}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,tr)}};var qi=class extends _r{constructor(){let t=new Jn;super(on.DhkemX25519HkdfSha256,new mc(t),t),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:on.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 FP=new Uint8Array([48,70,2,1,0,48,5,6,3,43,101,111,4,58,4,56]);function wc(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}var jb=(e,t)=>{function n(r,...o){if(Ie(r,void 0,"key"),!pf)throw new Error("Non little-endian hardware is not yet supported");if(e.nonceLength!==void 0){let u=o[0];Ie(u,e.varSizeNonce?void 0:e.nonceLength,"nonce")}let i=e.tagLength;i&&o[1]!==void 0&&Ie(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");Ie(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,Ie(u),a(s.encrypt.length,d),s.encrypt(u,d)},decrypt(u,d){if(Ie(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 Kb(e,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(e,t)}function Wb(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 bf(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&&!P6(t))throw new Error("invalid output, must be aligned");return t}function Vb(e,t,n){wc(n);let r=new Uint8Array(16),o=sc(r);return o.setBigUint64(0,Wi(t),n),o.setBigUint64(8,Wi(e),n),r}function P6(e){return e.byteOffset%4===0}var zb=e=>Uint8Array.from(e.split("").map(t=>t.charCodeAt(0))),O6=zb("expand 16-byte k"),C6=zb("expand 32-byte k"),R6=Ot(O6),H6=Ot(C6);function he(e,t){return e<<t|e>>>32-t}function gf(e){return e.byteOffset%4===0}var yc=64,L6=16,Xb=2**32-1,$b=Uint32Array.of();function F6(e,t,n,r,o,i,s,a){let c=o.length,l=new Uint8Array(yc),u=Ot(l),d=gf(o)&&gf(i),p=d?Ot(o):$b,h=d?Ot(i):$b;for(let w=0;w<c;s++){if(e(t,n,r,u,s,a),s>=Xb)throw new Error("arx: counter overflow");let y=Math.min(yc,c-w);if(d&&y===yc){let k=w/4;if(w%4!==0)throw new Error("arx: invalid block position");for(let x=0,_;x<L6;x++)_=k+x,h[_]=p[_]^u[x];w+=yc;continue}for(let k=0,x;k<y;k++)x=w+k,i[x]=o[x]^l[k];w+=y}}function Yb(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:o,counterRight:i,rounds:s}=Kb({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return Wt(o),Wt(s),wc(i),wc(n),(a,c,l,u,d=0)=>{Ie(a,void 0,"key"),Ie(c,void 0,"nonce"),Ie(l,void 0,"data");let p=l.length;if(u===void 0&&(u=new Uint8Array(p)),Ie(u,void 0,"output"),Wt(d),d<0||d>=Xb)throw new Error("arx: counter overflow");if(u.length<p)throw new Error(`arx: output (${u.length}) is shorter than data (${p})`);let h=[],w=a.length,y,k;if(w===32)h.push(y=kn(a)),k=H6;else if(w===16&&n)y=new Uint8Array(32),y.set(a),y.set(a,16),k=R6,h.push(y);else throw Ie(a,32,"arx key"),new Error("invalid key size");gf(c)||h.push(c=kn(c));let x=Ot(y);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(k,x,Ot(c.subarray(0,16)),x),c=c.subarray(16)}let _=16-o;if(_!==c.length)throw new Error(`arx: nonce must be ${_} or 16 bytes`);if(_!==12){let H=new Uint8Array(12);H.set(c,i?0:12-c.length),c=H,h.push(c)}let v=Ot(c);return F6(e,k,x,v,l,u,d,s),nt(...h),u}}function Ze(e,t){return e[t++]&255|(e[t++]&255)<<8}var xf=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=kn(Ie(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],h=s[6],w=s[7],y=s[8],k=s[9],x=Ze(t,n+0),_=Ze(t,n+2),v=Ze(t,n+4),H=Ze(t,n+6),b=Ze(t,n+8),I=Ze(t,n+10),O=Ze(t,n+12),S=Ze(t,n+14),T=i[0]+(x&8191),N=i[1]+((x>>>13|_<<3)&8191),V=i[2]+((_>>>10|v<<6)&8191),X=i[3]+((v>>>7|H<<9)&8191),m=i[4]+((H>>>4|b<<12)&8191),g=i[5]+(b>>>1&8191),E=i[6]+((b>>>14|I<<2)&8191),C=i[7]+((I>>>11|O<<5)&8191),M=i[8]+((O>>>8|S<<8)&8191),$=i[9]+(S>>>5|o),L=0,F=L+T*a+N*(5*k)+V*(5*y)+X*(5*w)+m*(5*h);L=F>>>13,F&=8191,F+=g*(5*p)+E*(5*d)+C*(5*u)+M*(5*l)+$*(5*c),L+=F>>>13,F&=8191;let B=L+T*c+N*a+V*(5*k)+X*(5*y)+m*(5*w);L=B>>>13,B&=8191,B+=g*(5*h)+E*(5*p)+C*(5*d)+M*(5*u)+$*(5*l),L+=B>>>13,B&=8191;let P=L+T*l+N*c+V*a+X*(5*k)+m*(5*y);L=P>>>13,P&=8191,P+=g*(5*w)+E*(5*h)+C*(5*p)+M*(5*d)+$*(5*u),L+=P>>>13,P&=8191;let D=L+T*u+N*l+V*c+X*a+m*(5*k);L=D>>>13,D&=8191,D+=g*(5*y)+E*(5*w)+C*(5*h)+M*(5*p)+$*(5*d),L+=D>>>13,D&=8191;let U=L+T*d+N*u+V*l+X*c+m*a;L=U>>>13,U&=8191,U+=g*(5*k)+E*(5*y)+C*(5*w)+M*(5*h)+$*(5*p),L+=U>>>13,U&=8191;let q=L+T*p+N*d+V*u+X*l+m*c;L=q>>>13,q&=8191,q+=g*a+E*(5*k)+C*(5*y)+M*(5*w)+$*(5*h),L+=q>>>13,q&=8191;let W=L+T*h+N*p+V*d+X*u+m*l;L=W>>>13,W&=8191,W+=g*c+E*a+C*(5*k)+M*(5*y)+$*(5*w),L+=W>>>13,W&=8191;let G=L+T*w+N*h+V*p+X*d+m*u;L=G>>>13,G&=8191,G+=g*l+E*c+C*a+M*(5*k)+$*(5*y),L+=G>>>13,G&=8191;let z=L+T*y+N*w+V*h+X*p+m*d;L=z>>>13,z&=8191,z+=g*u+E*l+C*c+M*a+$*(5*k),L+=z>>>13,z&=8191;let ee=L+T*k+N*y+V*w+X*h+m*p;L=ee>>>13,ee&=8191,ee+=g*d+E*u+C*l+M*c+$*a,L+=ee>>>13,ee&=8191,L=(L<<2)+L|0,L=L+F|0,F=L&8191,L=L>>>13,B+=L,i[0]=F,i[1]=B,i[2]=P,i[3]=D,i[4]=U,i[5]=q,i[6]=W,i[7]=G,i[8]=z,i[9]=ee}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;nt(r)}update(t){sn(this),Ie(t),t=kn(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(){nt(this.h,this.r,this.buffer,this.pad)}digestInto(t){sn(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 D6(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 Gb=D6(e=>new xf(e));function M6(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],h=t[3],w=t[4],y=t[5],k=t[6],x=t[7],_=o,v=n[0],H=n[1],b=n[2],I=s,O=a,S=c,T=l,N=u,V=d,X=p,m=h,g=w,E=y,C=k,M=x,$=_,L=v,F=H,B=b;for(let D=0;D<i;D+=2)I=I+N|0,$=he($^I,16),g=g+$|0,N=he(N^g,12),I=I+N|0,$=he($^I,8),g=g+$|0,N=he(N^g,7),O=O+V|0,L=he(L^O,16),E=E+L|0,V=he(V^E,12),O=O+V|0,L=he(L^O,8),E=E+L|0,V=he(V^E,7),S=S+X|0,F=he(F^S,16),C=C+F|0,X=he(X^C,12),S=S+X|0,F=he(F^S,8),C=C+F|0,X=he(X^C,7),T=T+m|0,B=he(B^T,16),M=M+B|0,m=he(m^M,12),T=T+m|0,B=he(B^T,8),M=M+B|0,m=he(m^M,7),I=I+V|0,B=he(B^I,16),C=C+B|0,V=he(V^C,12),I=I+V|0,B=he(B^I,8),C=C+B|0,V=he(V^C,7),O=O+X|0,$=he($^O,16),M=M+$|0,X=he(X^M,12),O=O+X|0,$=he($^O,8),M=M+$|0,X=he(X^M,7),S=S+m|0,L=he(L^S,16),g=g+L|0,m=he(m^g,12),S=S+m|0,L=he(L^S,8),g=g+L|0,m=he(m^g,7),T=T+N|0,F=he(F^T,16),E=E+F|0,N=he(N^E,12),T=T+N|0,F=he(F^T,8),E=E+F|0,N=he(N^E,7);let P=0;r[P++]=s+I|0,r[P++]=a+O|0,r[P++]=c+S|0,r[P++]=l+T|0,r[P++]=u+N|0,r[P++]=d+V|0,r[P++]=p+X|0,r[P++]=h+m|0,r[P++]=w+g|0,r[P++]=y+E|0,r[P++]=k+C|0,r[P++]=x+M|0,r[P++]=_+$|0,r[P++]=v+L|0,r[P++]=H+F|0,r[P++]=b+B|0}var U6=Yb(M6,{counterRight:!1,counterLength:4,allowShortKeys:!1}),j6=new Uint8Array(16),qb=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(j6.subarray(n))},K6=new Uint8Array(32);function Qb(e,t,n,r,o){o!==void 0&&Ie(o,void 0,"AAD");let i=e(t,n,K6),s=Vb(r.length,o?o.length:0,!0),a=Gb.create(i);o&&qb(a,o),qb(a,r),a.update(s);let c=a.digest();return nt(i,s),c}var W6=e=>(t,n,r)=>({encrypt(i,s){let a=i.length;s=bf(a+16,s,!1),s.set(i);let c=s.subarray(0,-16);e(t,n,c,c,1);let l=Qb(e,t,n,c,r);return s.set(l,a),nt(l),s},decrypt(i,s){s=bf(i.length-16,s,!1);let a=i.subarray(0,-16),c=i.subarray(-16),l=Qb(e,t,n,a,r);if(!Wb(c,l))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),e(t,n,s,s,1),nt(l),s}}),kf=jb({blockSize:64,nonceLength:12,tagLength:16},W6(U6));var vf=class{constructor(t){Object.defineProperty(this,"_key",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._key=new Uint8Array(fe(t))}async seal(t,n,r){return await this._seal(fe(t),fe(n),fe(r))}async open(t,n,r){return await this._open(fe(t),fe(n),fe(r))}_seal(t,n,r){return new Promise(o=>{let i=kf(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=kf(this._key,new Uint8Array(t),new Uint8Array(r)).decrypt(new Uint8Array(n));o(i.buffer)})}},Qi=class{constructor(){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:Zn.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 vf(t)}};xe();var V6=e=>new TextEncoder().encode(String(e)),Sf=e=>{if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);throw new f("bad-input",{field:"viewEnvelope"})},Zb=e=>{let t="0x";for(let n of Sf(e))t+=n.toString(16).padStart(2,"0");return t},Jb=(e,t,n)=>{let r=String(e??"").replace(/^0x/,"");if(!new RegExp("^[0-9a-fA-F]{"+t*2+"}$").test(r))throw new f("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},$6=()=>new Xi({kem:new qi,kdf:new Yi,aead:new Qi}),z6="ninsei-relay-view-v1";function eg({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])=>Jb(u,32,l)),s=V6(z6),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 tg({hpkeKey:e,info:t,plaintext:n}={}){let r=Jb(e,32,"hpkeKey"),o=Sf(n);if(o.length!==32&&o.length!==64)throw new f("bad-input",{field:"plaintext"});if(!(t instanceof Uint8Array))throw new f("bad-input",{field:"info"});let i=$6(),s=null;try{s=await i.kem.deserializePublicKey(r);let a=await i.createSenderContext({recipientPublicKey:s,info:t}),c=Sf(await a.seal(o));return{enc:Zb(a.enc),ciphertext:Zb(c)}}catch(a){throw a instanceof f?a:new f("bad-input",{field:"hpkeKey"})}}xe();var X6="Ninsei Relay",Y6="1",G6=["EIP712Domain(","string name,","string version)"],q6=G6.join(""),Ef=[["chainId","uint256"],["factory","address"],["locker","address"],["claimer","address"],["amount","uint256"],["readyBy","uint64"],["t1","uint64"],["salt","bytes32"]],rg="FirmOrder("+Ef.map(([e,t])=>t+" "+e).join(",")+")",Af=[["market","string"],["side","string"],["maker","address"],["registry","address"],["featuresHash","bytes32"],["xmrNetwork","string"],["order","FirmOrder"],["xmrAmount","uint256"],["claimTip","uint256"]],Q6="FirmTerms("+Af.map(([e,t])=>t+" "+e).join(",")+")"+rg,Zi=e=>new TextEncoder().encode(String(e)),_f=(...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},og=(e,t)=>{let n=String(e??"").replace(/^0x/,"");if(!/^[0-9a-fA-F]*$/.test(n)||n.length%2)throw new f("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},ng=(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 f("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},Z6=(e,t)=>{let n=String(e??"").trim();if(!/^(0x)?[0-9a-fA-F]{40}$/.test(n))throw new f("bad-input",{field:t});let r=new Uint8Array(32);return r.set(og(n.replace(/^0x/,""),t),12),r},J6=(e,t)=>{let n=og(e,t);if(n.length!==32)throw new f("bad-input",{field:t});return n},e_=(e,t,n,r)=>{if(t==="string")return e.keccak256(Zi(n??""));if(t==="address")return Z6(n,r);if(t==="bytes32")return J6(n,r);if(t==="uint64")return ng(n,r,64);if(t==="uint256")return ng(n,r,256);throw new f("bad-input",{field:r})},ig=(e,t,n,r,o)=>{let i=[e.keccak256(Zi(t))];for(let[s,a]of n)if(a==="FirmOrder"){let c=r&&r.order;if(!c||typeof c!="object")throw new f("bad-input",{field:o+".order"});i.push(t_(e,c))}else i.push(e_(e,a,r?r[s]:void 0,o+"."+s));return e.keccak256(_f(...i))};function t_(e,t){return ig(e,rg,Ef,t,"terms.order")}function n_(e){return e.keccak256(_f(e.keccak256(Zi(q6)),e.keccak256(Zi(X6)),e.keccak256(Zi(Y6))))}function r_({crypto:e,terms:t}={}){if(!e||typeof e.keccak256!="function")throw new f("bad-input",{field:"crypto"});return ig(e,Q6,Af,t,"terms")}function sg({crypto:e,terms:t}={}){if(!e||typeof e.keccak256!="function")throw new f("bad-input",{field:"crypto"});return e.keccak256(_f(Uint8Array.from([25,1]),n_(e),r_({crypto:e,terms:t})))}function ag(e){let t=[];if(!e||typeof e!="object")return["terms"];for(let[n]of Af)if(n==="order")if(!e.order||typeof e.order!="object")t.push("order");else for(let[r]of Ef){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 dg=(e,t,n)=>{let r=String(e??"").replace(/^0x/i,"");if(!new RegExp("^[0-9a-fA-F]{"+n*2+"}$").test(r))throw new f("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},Ji=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},Ye=(e,t,n)=>Ji(dg(e,n,t)),fg=(e,t)=>{let n=null;try{n=BigInt(e)}catch{n=null}if(n===null||n<=0n||n>=Ge.Point.Fn.ORDER)throw new f("bad-input",{field:t});return n},cg=(e,t)=>{let n=fg(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},lg=(e,t)=>Ji(Ge.Point.BASE.multiply(fg(e,t)).toBytes()),ug=(e,t)=>{let n=dg(e,t,32);try{Ge.Point.fromHex(Ji(n).slice(2))}catch{throw new f("bad-input",{field:t})}return Ji(n)},o_=["XA","XB","pokA","pokB","proofs"];function i_(e){if(!e||typeof e!="object")throw new f("bad-input",{field:"clientHalf.proof"});for(let a of o_)if(e[a]===void 0||e[a]===null||e[a]==="")throw new f("bad-input",{field:"clientHalf.proof."+a});if(!Array.isArray(e.proofs)||e.proofs.length!==253)throw new f("bad-input",{field:"clientHalf.proof.proofs"});let t=Ye(e.XA,33,"clientHalf.proof.XA"),n=Ye(e.XB,32,"clientHalf.proof.XB"),r=(a,c,l)=>{if(!a||typeof a!="object")throw new f("bad-input",{field:"clientHalf.proof."+c});return{R:Ye(a.R,l,"clientHalf.proof."+c+".R"),s:Ye(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 f("bad-input",{field:"clientHalf.proof.proofs."+c});let l={};for(let u of["eA","eB","a0","a1","b0","b1"])l[u]=Ye(a.sig[u],32,"clientHalf.proof.proofs."+c+".sig."+u);return{cA:Ye(a.cA,33,"clientHalf.proof.proofs."+c+".cA"),cB:Ye(a.cB,32,"clientHalf.proof.proofs."+c+".cB"),sig:l}});return{XA:t,XB:n,pokA:o,pokB:i,proofs:s}}async function pg({features:e,terms:t,clientHalf:n,edViewPointClient:r,edViewPointNode:o,nodeViewScalar:i,clientViewScalar:s=null,side:a=null}={}){let c=Ib({features:e,terms:t}),l=String(a||t?.side||"");if(l!=="ask"&&l!=="bid")throw new f("bad-input",{field:"side"});if(t?.side!==void 0&&t.side!==l)throw new f("bad-input",{field:"terms.side"});if(!t||typeof t!="object"||!t.order||typeof t.order!="object")throw new f("bad-input",{field:"terms"});if(t.featuresHash!==void 0&&t.featuresHash!==null&&t.featuresHash!==""&&String(t.featuresHash).toLowerCase()!==c.featuresHash)throw new f("quote-refused",{step:"features",why:"hash"});let u=t.order,d=["chainId","factory","locker","claimer","amount","readyBy","t1","salt"];for(let g of d)if(u[g]===void 0||u[g]===null||u[g]==="")throw new f("bad-input",{field:"terms.order."+g});if(String(u.chainId)!==String(t.market||"").split(":")[0])throw new f("bad-input",{field:"terms.market"});let p=n||{},h=Ye(p.commitHalf,32,"clientHalf.commitHalf"),w=Ye(p.edPoint,32,"clientHalf.edPoint"),y=i_(p.proof);if(y.XB!==w)throw new f("bad-input",{field:"clientHalf.edPoint"});let k=Ye(t.maker,20,"terms.maker"),x=Ye(u.locker,20,"terms.order.locker"),_=Ye(u.claimer,20,"terms.order.claimer");if(x===_)throw new f("bad-input",{field:"terms.order.roles"});if(l==="ask"){if(_!==k)throw new f("bad-input",{field:"terms.order.claimer"});if(String(t.claimTip)!=="0")throw new f("bad-input",{field:"terms.claimTip"})}else if(x!==k)throw new f("bad-input",{field:"terms.order.locker"});let v=ug(r,"edViewPointClient"),H=ug(o,"edViewPointNode"),b=cg(i,"nodeViewScalar");if(lg(i,"nodeViewScalar").toLowerCase()!==H.toLowerCase())throw new f("bad-input",{field:"edViewPointNode"});let I=cg(s,"clientViewScalar");if(lg(s,"clientViewScalar").toLowerCase()!==v.toLowerCase())throw new f("bad-input",{field:"edViewPointClient"});let O={market:String(t.market),side:l,maker:Ye(t.maker,20,"terms.maker"),registry:Ye(t.registry,20,"terms.registry"),featuresHash:c.featuresHash,xmrNetwork:String(t.xmrNetwork),order:{chainId:String(u.chainId),factory:Ye(u.factory,20,"terms.order.factory"),locker:Ye(u.locker,20,"terms.order.locker"),claimer:Ye(u.claimer,20,"terms.order.claimer"),amount:String(u.amount),readyBy:Number(u.readyBy),t1:Number(u.t1),salt:Ye(u.salt,32,"terms.order.salt")},xmrAmount:String(t.xmrAmount),claimTip:String(t.claimTip)},S=ag(O);if(S.length)throw new f("bad-input",{field:"terms",missing:S});let T=Ji(sg({crypto:{keccak256:J},terms:O})),N=eg({termsDigest:T,commitHalf:h,edPoint:w,edViewPointClient:v,edViewPointNode:H}),V=new Uint8Array(64);V.set(b,0),V.set(I,32);let X=await tg({hpkeKey:c.hpkeKey,info:N,plaintext:V});return{payload:JSON.stringify({terms:O,clientHalf:{commitHalf:h,edPoint:w,proof:y},edViewPointClient:v,edViewPointNode:H,viewEnvelope:X}),terms:O,viewEnvelope:X,edViewPointClient:v,edViewPointNode:H}}xe();$e();var s_="Quote(string relayId,address provider,bytes32 session,bytes32 requestId,uint64 counter,bytes32 requestHash,string payload,uint64 time)",a_="EIP712Domain(string name,string version)",c_="Ninsei Relay",l_="1",ns=(e,t)=>{if(typeof e=="string")return e;if(typeof e=="number"&&Number.isFinite(e)||typeof e=="bigint")return String(e);throw new f("bad-input",{field:t})},To=(e,t)=>{let n=null;try{n=Number(e)}catch{n=null}if(!Number.isFinite(n))throw new f("bad-input",{field:t});return n},Bo=(e,t="text")=>new TextEncoder().encode(ns(e,t)),Po=(...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},bc=(e,t,n)=>{let r=ns(e??"",t).replace(/^0x/,"");if(!new RegExp("^[0-9a-fA-F]{"+n*2+"}$").test(r))throw new f("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},Nf=(e,t)=>{let n=new Uint8Array(32);return n.set(bc(e,t,20),12),n},es=(e,t)=>bc(e,t,32),ts=(e,t)=>{let n=null;try{n=BigInt(e)}catch{n=null}if(n===null||n<0n)throw new f("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},gc=(e,t)=>J(Bo(e??"",t));function u_(e){if(!e||typeof e!="object")throw new f("bad-input",{field:"answer"});return J(Po(J(Bo(s_)),gc(e.relayId,"answer.relayId"),Nf(e.provider,"answer.provider"),es(e.session,"answer.session"),es(e.requestId,"answer.requestId"),ts(e.counter,"answer.counter"),es(e.requestHash,"answer.requestHash"),gc(e.payload,"answer.payload"),ts(e.time,"answer.time")))}function wg(){return J(Po(J(Bo(a_)),J(Bo(c_)),J(Bo(l_))))}function d_(e){return J(Po(Uint8Array.from([25,1]),wg(),u_(e)))}var f_="QuoteRequest(string relayId,address provider,bytes32 session,bytes32 requestId,uint64 counter,uint64 expiry,string payload,uint256 feeBps,address feeRecipient)";function p_(e){if(!e||typeof e!="object")throw new f("bad-input",{field:"forwarded"});return J(Po(J(Bo(f_)),gc(e.relayId,"forwarded.relayId"),Nf(e.provider,"forwarded.provider"),es(e.session,"forwarded.session"),es(e.requestId,"forwarded.requestId"),ts(e.counter,"forwarded.counter"),ts(e.expiry,"forwarded.expiry"),gc(e.payload,"forwarded.payload"),ts(e.feeBps,"forwarded.feeBps"),Nf(e.feeRecipient,"forwarded.feeRecipient")))}function hg(e){return J(Po(Uint8Array.from([25,1]),wg(),p_(e)))}function yg({forwarded:e,relayKey:t,payload:n,provider:r,requestHash:o=null}={}){if(!e||typeof e!="object"||e.type!=="quote_request"||To(e.version,"forwarded.version")!==1)throw new f("quote-refused",{step:"answer",why:"forwarded"});if(!/^0x[0-9a-fA-F]{40}$/.test(String(t||"")))throw new f("quote-refused",{step:"relay-info",why:"key"});if(ns(e.payload===void 0||e.payload===null?"":e.payload,"forwarded.payload")!==n)throw new f("quote-refused",{step:"answer",why:"forwarded-payload"});if(!Ct(e.provider,r))throw new f("quote-refused",{step:"answer",why:"forwarded-provider"});let i=gg(hg(e),e.signature);if(i===null||i!==String(t).toLowerCase())throw new f("quote-refused",{step:"answer",why:"forwarded-signature"});if(o!=null){let s=bg(hg(e));if(!Ct(s,o))throw new f("quote-refused",{step:"answer",why:"forwarded-hash"})}return e}var bg=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t};function gg(e,t){let n=ns(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=Ve.Signature.fromBytes(Po(bc(n.slice(0,64),"signature",32),bc(n.slice(64,128),"signature",32))).addRecoveryBit(r).recoverPublicKey(e);return bg(J(o.toBytes(!1).slice(1)).slice(12))}catch{return null}}function h_(e,t){if(!e||typeof e!="object"||e.type!=="quote"||To(e.version,"answer.version")!==1)throw new f("quote-refused",{step:"answer",why:"frame"});let n=gg(d_(e),e.signature);if(n===null||n!==String(t||"").toLowerCase())throw new f("quote-refused",{step:"answer",why:"signature"});return e}var m_="0x"+"00".repeat(20),mg=e=>ns(e??"","field").toLowerCase(),Ct=(e,t)=>mg(e)===mg(t);function w_(e,t,n){let r=t.order;if(!e||typeof e!="object")throw new f("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[d,p]of o)if(!Ct(e[d],p))throw new f("quote-refused",{step:"answer",why:"field",field:d});if(Ct(e.feeRecipient,m_))throw new f("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 f("quote-refused",{step:"answer",why:"fee"})}if(!Number.isSafeInteger(i)||i<0||i>200)throw new f("quote-refused",{step:"answer",why:"fee"});if(s!==a*BigInt(i)/10000n)throw new f("quote-refused",{step:"answer",why:"fee"});let c=To(e.validUntil,"quote.validUntil");if(!Number.isSafeInteger(c)||c<=n)throw new f("quote-expired",{step:"answer",validUntil:e.validUntil});let l=To(r.readyBy,"order.readyBy"),u=To(r.t1,"order.t1");if(!Number.isSafeInteger(l)||!Number.isSafeInteger(u)||l>=u||c>=l)throw new f("quote-refused",{step:"answer",why:"validity",field:"validUntil"})}function xg({answer:e,features:t,request:n,now:r=null}={}){if(!n||!n.terms)throw new f("bad-input",{field:"request"});if(h_(e,t&&t.quoteKey),!e.relayId||!Ct(e.relayId,t&&t.relayId))throw new f("quote-refused",{step:"answer",why:"relay"});let o=null;try{o=JSON.parse(e.payload)}catch{throw new f("quote-refused",{step:"answer",why:"payload"})}if(!o||typeof o!="object"||!o.quote)throw new f("quote-refused",{step:"answer",why:"payload"});if(o.contextVersion!=="ninsei-order-v3"||To(o.quoteVersion,"payload.quoteVersion")!==10)throw new f("quote-refused",{step:"answer",why:"version"});if(!Ct(o.factory,n.terms.order.factory))throw new f("quote-refused",{step:"answer",why:"factory"});if(!Ct(e.provider,n.terms.maker))throw new f("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=At.orderContextString(n.terms.order)}catch{s=null}if(!s||o.context!==s)throw new f("quote-refused",{step:"context",why:"other-terms"});let a=Ci({...i,signature:o.quoteSignature});if(a===null)throw new f("quote-refused",{step:"signature",why:"invalid"});if(!Ct(a,i.quoteKey))throw new f("quote-refused",{step:"signature",why:"key"});let c=Math.floor((r===null?Date.now():r)/1e3);w_(i,n.terms,c);let l=n.terms.side,u=l==="ask"?n.edViewPointClient:n.edViewPointNode,d=l==="ask"?n.edViewPointNode:n.edViewPointClient;if(!Ct(o.edViewPointLocker,u)||!Ct(o.edViewPointClaimer,d))throw new f("quote-refused",{step:"answer",why:"view-points"});let p=o.nodeHalf;if(!p||typeof p!="object"||!p.proof)throw new f("quote-refused",{step:"answer",why:"node-half"});if(l==="ask"&&(!Ct(p.commitHalf,i.commitHalfClaimer)||!Ct(p.edPoint,i.edPointClaimer)))throw new f("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 y_=new Set(["compliance","no_liquidity","size","paused","unavailable","bad_request","price_changed"]),nr=(e,t)=>{if(typeof e=="string")return e;if(typeof e=="number"&&Number.isFinite(e)||typeof e=="bigint")return String(e);throw new f("bad-input",{field:t})},b_=(e,t)=>(e==null?"":nr(e,"relay"))===(t==null?"":nr(t,"relay"));async function kg({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 f("bad-input",{field:"relayUrl"});if(!/^https:\/\//i.test(s))throw new f("bad-input",{field:"relayUrl",why:"not-https"});let a=await pg(i),c=JSON.stringify({version:1,payload:a.payload,...t?{partner:String(t)}:{}}),l=ht({apiBase:s,fetchImpl:n,timeoutMs:r}),u=null;try{let _=await l.tryJson("/v1/relay");if(!_||_.ok!==!0||!_.body||typeof _.body!="object")throw new f("quote-refused",{step:"relay-info",why:"unavailable"});u=_.body}catch(_){throw _ instanceof f?_:new f("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(_){if(o>0&&_&&_.code==="server-unavailable"&&_.params&&_.params.why==="timeout")p=await d();else throw _}if(!p.ok){let _=p.body&&p.body.code?String(p.body.code):null;throw _&&y_.has(_)?new f("quote-refused",{step:"relay",code:_,status:p.status}):new f("server-unavailable",{step:"relay",status:p.status})}let h=p.body&&p.body.answer,w=null;try{w=p.body?Number(p.body.version):null}catch{w=null}if(!p.body||w!==1||!h)throw new f("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 f("quote-refused",{step:"answer",why:"relay"});if(!b_(h.relayId,p.body.relay))throw new f("quote-refused",{step:"answer",why:"relay"});yg({forwarded:p.body.forwarded,relayKey:u.relayKey,payload:a.payload,provider:i.features.provider,requestHash:h.requestHash===void 0||h.requestHash===null?"":h.requestHash});let y=xg({answer:h,features:i.features,request:a}),k=nr(u.feeRecipient===void 0||u.feeRecipient===null?"":u.feeRecipient,"relay.feeRecipient").toLowerCase(),x=nr(y.quote.feeRecipient===void 0||y.quote.feeRecipient===null?"":y.quote.feeRecipient,"quote.feeRecipient").toLowerCase();if(!k||k!==x)throw new f("quote-refused",{step:"fee",why:"fee-recipient"});if(!t&&nr(u.feeBps===void 0||u.feeBps===null?"":u.feeBps,"relay.feeBps")!==nr(y.quote.feeBps===void 0||y.quote.feeBps===null?"":y.quote.feeBps,"quote.feeBps"))throw new f("quote-refused",{step:"fee",why:"fee-bps"});if(u.relayId===void 0||u.relayId===null||nr(u.relayId,"relay.relayId")!==nr(p.body.relay,"relay"))throw new f("quote-refused",{step:"relay-info",why:"relay"});return{...y,relay:p.body.relay??null,offered:p.body.offered??null,forwarded:p.body.forwarded??null,answer:h}}$e();var vg=e=>new TextEncoder().encode(String(e)),vn=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},g_=()=>vn(J(vg("providerOf(address)")).slice(0,4)),xc=e=>g_()+"0".repeat(24)+String(e).toLowerCase().replace(/^0x/,""),x_=()=>vn(J(vg("factoryOf(address)")).slice(0,4)),If=e=>x_()+"0".repeat(24)+String(e).toLowerCase().replace(/^0x/,""),Oo=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},rt="0x"+"00".repeat(20),Co=(e,t)=>String(e??"").toLowerCase()===String(t??"").toLowerCase(),Tr=e=>{let t=String(e??"").replace(/^0x/,"");return t.length>=40?"0x"+t.slice(-40).toLowerCase():null},k_=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},Tf=(e,t,n)=>{let r=n&&n.settlement&&n.settlement.chain,o=k_(n);if(!o&&!r)return;let i=String(e&&e.cashier||"").toLowerCase();o||R("quote-cashier-mismatch",{step:t,why:"no-pinned-cashier",got:i||null}),i!==o&&R("quote-cashier-mismatch",{step:t,got:i||null,want:o})},ot=e=>e==null||e===""?null:Number.isFinite(Number(e))?Number(e):null,v_=e=>String(e||"").split("/")[0].toUpperCase(),S_=e=>String(e||"").split("/")[1]?String(e).split("/")[1].toUpperCase():"";function E_(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=v_(i),l=S_(i),u=ot(o.rateQuote),d=ot(o.rate),p=u!==null?u:d,h=null;u!==null?h=d:p!==null&&(h=l==="XMR"?p>0?1/p:null:p);let w=s&&s!==c||a&&a!==l,y=ot(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:h,claimTip:(()=>{if(o.claimTip===void 0||o.claimTip===null||o.claimTip==="")return"0";try{let k=BigInt(o.claimTip);return k<0n?"0":k.toString()}catch{return"0"}})(),min:ot(o.min),max:ot(o.max),step:ot(o.step),ttlMs:ot(o.ttlMs)&&ot(o.ttlMs)>0?ot(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:ot(o.seq)!==null?ot(o.seq):ot(n.seq)!==null?ot(n.seq):ot(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 A_(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 __(e,t=Date.now()){let n=e&&e.quotes,r=[],o=(l,u,d)=>{let p=E_(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 Sg(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 N_(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=Sg(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 Eg=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}}),I_=e=>({...Eg(e),code:e.code,why:e.why}),Bf=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 rs({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=Yl({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 Pf({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(b=>String(b).toLowerCase()).filter(Boolean):null,d=Array.isArray(c)&&c.length?c.map(b=>String(b).toLowerCase()).filter(Boolean):null,p=new Set,h=null,w=1,y=null,k={direction:"buy",token:null,amount:null},x=!1,_=()=>{for(let b of p)b(y)},v=async()=>{if(!x){x=!0;try{let b=Number.isFinite(Number(k.size))&&Number(k.size)>0,I=b?Number(k.size):w,O=await t.json("/rate?amount="+encodeURIComponent(I)+"&side="+encodeURIComponent(k.direction)),S=__(O,n()),T=Number.isFinite(Number(k.amount))?Number(k.amount):null,V=A_(S.offers,{direction:k.direction,amount:T}).best||S.best,X=V&&T!==null&&!b?N_(V,k.direction,T,n()):null;X&&X.size!==null&&(w=X.size);let m=V&&String(V.currency||"").toUpperCase()||null,g=b&&V?Sg(I,V):null;y={direction:k.direction,token:k.token,amount:T,size:b?I:w,unit:b?k.direction==="sell"?m:"XMR":X?X.unit:null,rate:b?V?Number(V.rate):null:X?X.rate:null,xmr:X?X.xmr:null,at:n(),providerId:V?V.providerId:null,sizeOk:b?!!(g&&g.code===null):!!(X&&X.code===null),sizeCode:b?g?g.code:"no-offer":X?X.code:"no-offer",seq:S.offers.length?(S.offers.find(E=>E.seq!==null)||{}).seq??null:null,best:O&&O.best&&typeof O.best=="object"?{providerId:String(O.best.providerId||""),pair:String(O.best.pair||"")}:null,offers:S.offers.map(Eg),refused:S.refused.map(I_),references:Array.isArray(O&&O.references)?O.references.map(E=>({source:E.source,value:ot(E.value),at:ot(E.at)})):[],ok:S.offers.length>0},_()}catch(b){y={...y||{direction:k.direction,token:k.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:b&&b.code==="server-unavailable"?"quote-unavailable":"unknown"}},_()}finally{x=!1}}},H=()=>{h&&clearInterval(h),h=null,p.size>0&&(v(),h=setInterval(()=>{v()},e.limits.quotePollMs))};return{watch(b,I){typeof I!="function"&&R("bad-input",{field:"onSnapshot"});let O=b&&b.direction==="sell"?"sell":"buy",S=b&&typeof b.token=="string"&&b.token?b.token.toLowerCase():e.settlement.chain.nativeSymbol.toLowerCase();return k={direction:O,token:S,amount:b&&b.amount!==void 0?b.amount:null,size:b&&Number.isFinite(Number(b.size))&&Number(b.size)>0?Number(b.size):null},w=1,y=null,p.add(I),H(),()=>{p.delete(I),p.size===0&&(h&&clearInterval(h),h=null)}},snapshot:()=>y,async sale(b){(!b||typeof b!="object")&&R("bad-input",{field:"request"});let I=b.request&&typeof b.request=="object"?b.request:b,O={...b.request&&typeof b.request=="object"?b:{request:b},sdkVersion:bo},S=null;try{S=await t.tryJson(e.route("orderSell"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(O)})}catch(W){if(W&&W.code==="bad-input")throw W;R("server-unavailable",{step:"order-sell"})}(!S||S.ok!==!0||!S.body||S.body.ok!==!0)&&R("quote-refused",{step:"order-sell"});let T=S.body,N=T.handoff&&T.handoff.quote||T.quote||null;(!N||typeof N!="object")&&R("quote-field-unbound",{step:"order-sell",field:"quote"}),Tf(N,"order-sell",e);let V=Kd(N);V.length&&R("quote-field-unbound",{step:"signature",missing:V});let X=Number(N.validUntil),m=Math.floor(n()/1e3);(!Number.isSafeInteger(X)||X<=m)&&R("quote-expired",{step:"signature",validUntil:N.validUntil});let g=Ci(N);g===null&&R("quote-signature-invalid",{step:"signature"});let E=String(N.quoteKey).toLowerCase();g!==E&&R("quote-key-mismatch",{step:"signature",got:g,want:E});let C=String(N.registry||"").toLowerCase();(!/^0x[0-9a-f]{40}$/.test(C)||C===rt)&&R("quote-field-unbound",{step:"registry",field:"registry"});let M=String(N.provider||"").toLowerCase();(!/^0x[0-9a-f]{40}$/.test(M)||M===rt)&&R("quote-field-unbound",{step:"registry",field:"provider"}),typeof r!="function"&&R("quote-registry-unchecked",{step:"registry",why:"no-chain-read"});let $=null;try{$=Tr(await r({to:C,data:xc(E)}))}catch{R("quote-registry-unchecked",{step:"registry",why:"read-failed",registry:C})}($===null||$===rt)&&R("quote-key-unknown",{step:"registry",registry:C,quoteKey:E}),$!==M&&R("quote-provider-mismatch",{step:"registry",got:$,want:M}),typeof s=="function"&&s(M)!==!0&&R("quote-provider-not-allowed",{step:"policy",provider:M});let L=String(N.factory||"").toLowerCase();(!/^0x[0-9a-f]{40}$/.test(L)||L===rt)&&R("quote-field-unbound",{step:"factory",field:"factory"});let F=null;try{F=Tr(await r({to:C,data:If(M)}))}catch{R("quote-factory-unchecked",{step:"factory",why:"read-failed",registry:C})}if((F===null||F===rt)&&R("quote-factory-unknown",{step:"factory",registry:C,provider:M}),F!==L&&R("quote-factory-mismatch",{step:"factory",got:L,want:F}),u){typeof o!="function"&&R("quote-factory-unchecked",{step:"factory",why:"no-code-read"});let W=null;try{W=await o(L)}catch{R("quote-factory-unchecked",{step:"factory",why:"code-read-failed",factory:L})}let G=Oo(W),z=vn(J(G||new Uint8Array(0)));u.includes(z)||R("quote-factory-code-unknown",{step:"factory",factory:L,codeHash:z})}if(d){typeof r!="function"&&R("quote-factory-unchecked",{step:"factory",why:"no-chain-read"}),typeof o!="function"&&R("quote-factory-unchecked",{step:"factory",why:"no-code-read"});let W=await Re.verifyFactoryImplementationOnChain({factory:L,read:r,code:G=>o(G),policy:d,hashCode:G=>vn(J(Oo(G)||new Uint8Array(0)))});if(!W.ok){let G=W.why==="implementation-code-unknown"||W.why==="implementation-code-mismatch"||W.why==="implementation-has-no-code";R(G?"quote-factory-code-unknown":"quote-factory-unchecked",{step:"factory",why:W.why,factory:L,implementation:W.implementation||null})}}let B=String(I&&I.claimer||N.claimer||"").toLowerCase();B&&l&&l.has(B)&&R("address-denied",{step:"order-sell"}),I&&I.claimer&&N.claimer&&String(I.claimer).toLowerCase()!==String(N.claimer).toLowerCase()&&R("quote-refused",{step:"order-sell",why:"claimer-not-bound"});let P=I&&(I.xmr!==void 0?I.xmr:I.xmrAmount!==void 0?I.xmrAmount:null);if(P!=null){let W=null;try{W=BigInt(String(P))}catch{W=null}if(W===null||W<10n**12n)try{W=tb(String(P))}catch{W=null}let G=null;try{G=N.xmrAmount===void 0||N.xmrAmount===null||N.xmrAmount===""?null:BigInt(String(N.xmrAmount))}catch{G=null}(G===null||W===null||W!==G)&&R("quote-refused",{step:"order-sell",why:"xmr-amount"})}if(T.order&&typeof T.order=="object"){let W=(G,z)=>String(G??"").replace(/^0x/i,"").toLowerCase()===String(z??"").replace(/^0x/i,"").toLowerCase();for(let G of["locker","claimer","amount","readyBy","t1","salt"])W(T.order[G],N[G])||R("quote-refused",{step:"order-sell",why:"other-terms",field:G});if(N.context){let G=null;try{G=At.orderContextString(T.order)}catch{G=null}G!==null&&String(N.context)!==G&&R("quote-refused",{step:"order-sell",why:"other-terms",field:"context"})}}let D=T.claimTip&&T.claimTip.wei!==void 0&&T.claimTip.wei!==null?String(T.claimTip.wei):null;D===null&&R("quote-field-unbound",{step:"claimTip",field:"claimTip"}),T.claimTip.signed!==!0&&R("quote-field-unbound",{step:"claimTip",field:"signed"});let U=null;try{U=N.claimTip===void 0||N.claimTip===null||N.claimTip===""?"0":BigInt(N.claimTip).toString()}catch{R("quote-field-unbound",{step:"claimTip",field:"claimTip"})}let q=null;try{q=BigInt(D)}catch{R("quote-tip-unreadable",{step:"claimTip"})}if((U===null||q<0n||BigInt(U)!==q)&&R("quote-refused",{step:"claimTip",why:"not-the-signed-tip"}),q>0n){typeof i!="function"&&R("quote-tip-unchecked",{step:"claimTip",why:"no-block-read"});let W=null;try{W=await i("latest")}catch{R("quote-tip-unchecked",{step:"claimTip",why:"block-read-failed"})}let G=W&&(W.baseFeePerGas!==void 0?W.baseFeePerGas:W.baseFeeWei),z=Bf(W),ee=rs({claimTipWei:q,baseFeeWei:G,priorityFeeWei:z});ee.ok||R(ee.code,{step:"claimTip",...ee})}return T},async firm(b){(!b||typeof b!="object")&&R("bad-input",{field:"request"}),(typeof b.providerId!="string"||!b.providerId)&&R("bad-input",{field:"providerId"}),(!b.order||typeof b.order!="object")&&R("bad-input",{field:"order"}),l&&typeof b.order.locker=="string"&&l.has(b.order.locker.toLowerCase())&&R("address-denied",{step:"order-quote"});let I=null,O=b.viewHalfClaimer===void 0||b.viewHalfClaimer===null||b.viewHalfClaimer===""?null:String(b.viewHalfClaimer);try{I=await t.tryJson(e.route("orderQuote"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({providerId:b.providerId,order:b.order,...O===null?{}:{viewHalfClaimer:O},sdkVersion:bo})})}catch(U){if(U&&U.code==="bad-input")throw U;R("server-unavailable",{step:"order-quote"})}(I&&I.body&&typeof I.body.code=="string"?I.body.code:null)==="denied-address"&&R("address-denied",{step:"order-quote"}),(!I||I.ok!==!0||!I.body||I.body.ok!==!0||!I.body.quote)&&R("quote-refused",{step:"order-quote"});let N=I.body.quote;if(Tf(N,"order-quote",e),O!==null){let U=N.viewHalfClaimer;(U==null||U==="")&&R("quote-field-unbound",{step:"viewHalfClaimer",field:"viewHalfClaimer"}),String(U).toLowerCase()!==O.toLowerCase()&&R("quote-refused",{step:"viewHalfClaimer",why:"not-echoed"})}let V=Kd(N);V.length&&R("quote-field-unbound",{step:"signature",missing:V});let X=Number(N.validUntil),m=Math.floor(n()/1e3);(!Number.isSafeInteger(X)||X<=m)&&R("quote-expired",{step:"signature",validUntil:N.validUntil});let g=Ci(N);g===null&&R("quote-signature-invalid",{step:"signature"});let E=String(N.quoteKey).toLowerCase();g!==E&&R("quote-key-mismatch",{step:"signature",got:g,want:E});let C=String(N.registry||"").toLowerCase();(!/^0x[0-9a-f]{40}$/.test(C)||C===rt)&&R("quote-field-unbound",{step:"registry",field:"registry"});let M=String(N.provider||"").toLowerCase();(!/^0x[0-9a-f]{40}$/.test(M)||M===rt)&&R("quote-field-unbound",{step:"registry",field:"provider"}),typeof r!="function"&&R("quote-registry-unchecked",{step:"registry",why:"no-chain-read"});let $=null;try{$=Tr(await r({to:C,data:xc(E)}))}catch{R("quote-registry-unchecked",{step:"registry",why:"read-failed",registry:C})}($===null||$===rt)&&R("quote-key-unknown",{step:"registry",registry:C,quoteKey:E}),$!==M&&R("quote-provider-mismatch",{step:"registry",got:$,want:M}),typeof s=="function"&&s(M)!==!0&&R("quote-provider-not-allowed",{step:"policy",provider:M});let L=String(N.factory||"").toLowerCase();(!/^0x[0-9a-f]{40}$/.test(L)||L===rt)&&R("quote-field-unbound",{step:"factory",field:"factory"});let F=null;try{F=Tr(await r({to:C,data:If(M)}))}catch{R("quote-factory-unchecked",{step:"factory",why:"read-failed",registry:C})}if((F===null||F===rt)&&R("quote-factory-unknown",{step:"factory",registry:C,provider:M}),F!==L&&R("quote-factory-mismatch",{step:"factory",got:L,want:F}),u){typeof o!="function"&&R("quote-factory-unchecked",{step:"factory",why:"no-code-read"});let U=null;try{U=await o(L)}catch{R("quote-factory-unchecked",{step:"factory",why:"code-read-failed",factory:L})}let q=Oo(U),W=vn(J(q||new Uint8Array(0)));u.includes(W)||R("quote-factory-code-unknown",{step:"factory",factory:L,codeHash:W})}if(d){typeof r!="function"&&R("quote-factory-unchecked",{step:"factory",why:"no-chain-read"}),typeof o!="function"&&R("quote-factory-unchecked",{step:"factory",why:"no-code-read"});let U=await Re.verifyFactoryImplementationOnChain({factory:L,read:r,code:q=>o(q),policy:d,hashCode:q=>vn(J(Oo(q)||new Uint8Array(0)))});if(!U.ok){let q=U.why==="implementation-code-unknown"||U.why==="implementation-code-mismatch"||U.why==="implementation-has-no-code";R(q?"quote-factory-code-unknown":"quote-factory-unchecked",{step:"factory",why:U.why,factory:L,implementation:U.implementation||null})}}let B=null;try{B=At.orderContextString(b.order)}catch{B=null}if(B===null){let U=N&&N.claimer;if(U)try{B=At.orderContextString({...b.order,claimer:U})}catch{R("bad-input",{field:"order"})}else R("bad-input",{field:"order"})}let P=N.context||"";String(P)!==B&&R("quote-refused",{step:"context",why:P?"other-terms":"not-reported"});let D=(()=>{try{return rs({claimTipWei:N.claimTip})}catch{return{ok:!0,tipWei:"0"}}})();if(!D.ok&&D.code==="quote-tip-unreadable"&&R("quote-field-unbound",{step:"claimTip",field:"claimTip"}),D.tipWei!=="0"){typeof i!="function"&&R("quote-tip-unchecked",{step:"claimTip",why:"no-block-read"});let U=null;try{U=await i("latest")}catch{R("quote-tip-unchecked",{step:"claimTip",why:"block-read-failed"})}let q=U&&(U.baseFeePerGas!==void 0?U.baseFeePerGas:U.baseFeeWei),W=Bf(U),G=rs({claimTipWei:N.claimTip,baseFeeWei:q,priorityFeeWei:W});G.ok||R(G.code,{step:"claimTip",...G})}return N},async firmRelay(b){(!b||typeof b!="object")&&R("bad-input",{field:"request"});let I=b.features,O=b.order&&typeof b.order=="object"?{...b.order}:null;(!I||typeof I!="object")&&R("bad-input",{field:"features"}),O||R("bad-input",{field:"order"});let S=String(b.side||"");S!=="ask"&&S!=="bid"&&R("bad-input",{field:"side"});let T=String(I.provider||"").toLowerCase(),N=String(I.registry||"").toLowerCase();(!/^0x[0-9a-f]{40}$/.test(T)||T===rt)&&R("bad-input",{field:"features.provider"}),(!/^0x[0-9a-f]{40}$/.test(N)||N===rt)&&R("bad-input",{field:"features.registry"});let V=e&&e.settlement&&e.settlement.chain&&e.settlement.chain.escrow&&e.settlement.chain.escrow.registry;V&&!Co(N,V)&&R("bad-input",{field:"features.registry",why:"not-the-network-registry"}),(!/^0x[0-9a-f]{40}$/.test(String(I.quoteKey||"").toLowerCase())||String(I.quoteKey).toLowerCase()===rt)&&R("bad-input",{field:"features.quoteKey"}),typeof r!="function"&&R("quote-registry-unchecked",{step:"features",why:"no-chain-read",registry:N});let X=null;try{X=Tr(await r({to:N,data:xc(I.quoteKey)}))}catch{R("quote-registry-unchecked",{step:"features",why:"read-failed",registry:N})}(X===null||X===rt)&&R("quote-key-unknown",{step:"registry",registry:N,quoteKey:I.quoteKey}),Co(X,I.provider)||R("quote-provider-mismatch",{step:"registry",got:X,want:I.provider});let m=S==="bid"?O.claimer:O.locker;l&&typeof m=="string"&&l.has(m.toLowerCase())&&R("address-denied",{step:"order-quote"}),S==="ask"?(O.claimer&&!Co(O.claimer,T)&&R("bad-input",{field:"order.claimer"}),O.claimer=T):(O.locker&&!Co(O.locker,T)&&R("bad-input",{field:"order.locker"}),O.locker=T);let g=Number(O.chainId);(!Number.isSafeInteger(g)||g<=0)&&R("bad-input",{field:"order.chainId"});let E=Array.isArray(I.firmWindows)?I.firmWindows.filter(ae=>ae&&ae.side===S):[],C=[...new Set(E.map(ae=>ae.market).filter(ae=>typeof ae=="string"&&ae))],M=b.market!==void 0?String(b.market):C.length===1?C[0]:null;M||R("bad-input",{field:"market"});let $=E.find(ae=>ae.market===M)||null;$||R("quote-refused",{step:"features",why:"window"});let L=b.xmrNetwork!==void 0?String(b.xmrNetwork):$.xmrNetwork;L||R("bad-input",{field:"xmrNetwork"}),(b.xmrAmount===void 0||b.xmrAmount===null||b.xmrAmount==="")&&R("bad-input",{field:"xmrAmount"});let F=b.claimTip===void 0||b.claimTip===null?"0":String(b.claimTip),B=typeof b.recoveryKey=="string"?b.recoveryKey:b.recoveryKey&&typeof b.recoveryKey.mnemonic=="string"?b.recoveryKey.mnemonic:null;B||R("bad-input",{field:"recoveryKey"});let P=b.recoverySalt!==void 0&&b.recoverySalt!==null;(!O.factory||!/^0x[0-9a-f]{40}$/i.test(String(O.factory)))&&R("bad-input",{field:"order.factory"});let D=null;try{D=gn(P?b.recoverySalt:O.salt)}catch{R("bad-input",{field:"recoverySalt"})}if(P){let ae=null;try{ae=gn(O.salt)}catch{R("bad-input",{field:"recoverySalt",why:"order-salt"})}D!==ae&&R("bad-input",{field:"recoverySalt",why:"order-salt"})}let U=Er({mnemonic:B,chainId:g,factory:O.factory,salt:D}),q={kind:"salt-v2",salt:D},W=await Sb(O,{spendHalf:U.spendHalf,viewHalf:U.viewHalf}),G=Ve.Point.fromHex(W.side.proof.XA),z={commitHalf:vn(J(G.toBytes(!1).slice(1))),edPoint:W.side.pub.ed,proof:W.side.proof},ee=await kg({relayUrl:b.relayUrl,partner:b.partner,fetchImpl:b.fetchImpl,timeoutMs:b.timeoutMs,features:I,terms:{market:M,side:S,maker:T,registry:N,xmrNetwork:L,order:O,xmrAmount:String(b.xmrAmount),claimTip:F},clientHalf:z,edViewPointClient:W.side.viewPub,edViewPointNode:U.makerViewPoint,nodeViewScalar:U.makerViewHalf,clientViewScalar:U.viewHalf,side:S}),Q=ee.quote;Tf(Q,"relay",e);let A=ee.nodeHalf;await af({context:W.context,side:W.side,counterparty:S==="ask"?{proof:A.proof,edPub:Q.edPointClaimer,commitHalfClaimer:Q.commitHalfClaimer,viewPoint:ee.edViewPointClaimer,viewHalf:U.makerViewHalf}:{proof:A.proof,edPub:A.edPoint,commitHalfClaimer:A.commitHalf,viewPoint:ee.edViewPointLocker,viewHalf:U.makerViewHalf}});let j=S==="ask"?Q.edPointClaimer:A.edPoint,K=S==="ask"?ee.edViewPointClaimer:ee.edViewPointLocker,Z=go({ownSpendHalf:U.spendHalf,ownViewHalf:U.viewHalf,otherSpendPoint:j,otherViewPoint:K,network:L}),Y=S==="ask"?{commitHalfLocker:z.commitHalf,edPointLocker:W.side.pub.ed,edViewPointLocker:W.side.viewPub}:{commitHalfLocker:A.commitHalf,edPointLocker:A.edPoint,edViewPointLocker:ee.edViewPointLocker},ne=null;try{let ae=await r({to:Q.factory,data:Re.encodePredict({...ee.orderQuote,...Y,signature:ee.orderQuote.signature})});ne=Re.decodeAddress(ae)}catch{R("quote-escrow-unchecked",{step:"factory",why:"predict-failed",factory:Q.factory})}s&&s(T)!==!0&&R("quote-provider-not-allowed",{step:"policy",provider:T}),typeof r!="function"&&R("quote-registry-unchecked",{step:"registry",why:"no-chain-read"});let oe=null;try{oe=Tr(await r({to:N,data:xc(Q.quoteKey)}))}catch{R("quote-registry-unchecked",{step:"registry",why:"read-failed",registry:N})}(oe===null||oe===rt)&&R("quote-key-unknown",{step:"registry",registry:N,quoteKey:Q.quoteKey}),Co(oe,Q.provider)||R("quote-provider-mismatch",{step:"registry",got:oe,want:Q.provider});let pe=null;try{pe=Tr(await r({to:N,data:If(Q.provider)}))}catch{R("quote-factory-unchecked",{step:"factory",why:"read-failed",registry:N})}if((pe===null||pe===rt)&&R("quote-factory-unknown",{step:"factory",registry:N,provider:Q.provider}),Co(pe,Q.factory)||R("quote-factory-mismatch",{step:"factory",got:Q.factory,want:pe}),u){typeof o!="function"&&R("quote-factory-unchecked",{step:"factory",why:"no-code-read"});let ae=null;try{ae=await o(Q.factory)}catch{R("quote-factory-unchecked",{step:"factory",why:"code-read-failed",factory:Q.factory})}let Ue=vn(J(Oo(ae)||new Uint8Array(0)));u.includes(Ue)||R("quote-factory-code-unknown",{step:"factory",factory:Q.factory,codeHash:Ue})}if(d){typeof r!="function"&&R("quote-factory-unchecked",{step:"factory",why:"no-chain-read"}),typeof o!="function"&&R("quote-factory-unchecked",{step:"factory",why:"no-code-read"});let ae=await Re.verifyFactoryImplementationOnChain({factory:Q.factory,read:r,code:Ue=>o(Ue),policy:d,hashCode:Ue=>vn(J(Oo(Ue)||new Uint8Array(0)))});if(!ae.ok){let Ue=ae.why==="implementation-code-unknown"||ae.why==="implementation-code-mismatch"||ae.why==="implementation-has-no-code";R(Ue?"quote-factory-code-unknown":"quote-factory-unchecked",{step:"factory",why:ae.why,factory:Q.factory,implementation:ae.implementation||null})}}let ke=(()=>{try{return rs({claimTipWei:Q.claimTip})}catch{return{ok:!0,tipWei:"0"}}})();if(!ke.ok&&ke.code==="quote-tip-unreadable"&&R("quote-field-unbound",{step:"claimTip",field:"claimTip"}),ke.tipWei!=="0"){typeof i!="function"&&R("quote-tip-unchecked",{step:"claimTip",why:"no-block-read"});let ae=null;try{ae=await i("latest")}catch{R("quote-tip-unchecked",{step:"claimTip",why:"block-read-failed"})}let Ue=ae&&(ae.baseFeePerGas!==void 0?ae.baseFeePerGas:ae.baseFeeWei),Je=Bf(ae),lt=rs({claimTipWei:Q.claimTip,baseFeeWei:Ue,priorityFeeWei:Je});lt.ok||R(lt.code,{step:"claimTip",...lt})}let we=ee.orderQuote&&ee.orderQuote.xmrAmount!==void 0&&ee.orderQuote.xmrAmount!==null?String(ee.orderQuote.xmrAmount):null;we||R("quote-field-unbound",{step:"xmrAmount",field:"orderQuote.xmrAmount"});let re=b.market&&String(b.market).includes(":")?String(b.market).split(":").slice(1).join(":"):null,ie=String(O.asset||re||"").trim(),ce={...Q,viewHalfClaimer:U.makerViewHalf,xmrAmount:we,...ie?{asset:ie,token:ie.toLowerCase()}:{},...Q.nonce!==void 0&&Q.nonce!==null?{id:String(Q.nonce)}:{}},ve={proof:A.proof,edPointClaimer:S==="ask"?Q.edPointClaimer:A.edPoint,commitHalfClaimer:S==="ask"?Q.commitHalfClaimer:A.commitHalf,viewHalfClaimer:U.makerViewHalf,viewPoint:S==="ask"?ee.edViewPointClaimer:ee.edViewPointLocker},Xt={...O,xmrAmount:we};return{...ee,quote:ce,order:Xt,startRequest:{quote:ce,order:Xt,orderQuote:ee.orderQuote,counterparty:ve,recoveryKey:b.recoveryKey,recoverySalt:O.salt},counterparty:ve,viewHalfClaimer:U.makerViewHalf,viewHalfPoint:U.makerViewPoint,jointAddress:Z.address,escrow:ne,recovery:q}}}}var T_=e=>{let t=e&&typeof e=="object"?e:{},{reason:n,kind:r,ok:o,checked:i,blocks:s,...a}=t;return{code:By(r),ok:o===!0,checked:i!==!1,blocks:s===!0,kind:typeof r=="string"?r:"unknown",params:a}},Ag=(...e)=>e.some(t=>t!=null&&t!==""),Vt=(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 _g({config:e,wallet:t,limits:n={}}){return async function(o={},i={}){let s=ue.SIGNING_GUARDS||{},a=Number.isFinite(i.nowMs)?i.nowMs:Date.now(),c=o&&typeof o=="object"?o:{},l=!!i.tokenIsNative,u=e.evmNetwork,p=[Vt(Se.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}),Vt(Se.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}),Vt(Se.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}),Vt(Se.payBalanceVerdict,{payBalanceWei:i.payBalanceWei??null,payAmountWei:i.payAmountWei??null,symbol:l?u.nativeSymbol:c.token||null,decimals:Number.isFinite(i.decimals)?i.decimals:18}),Vt(Se.gasReserveVerdict,{nativeBalanceWei:i.nativeBalanceWei??null,requiredNativeWei:i.requiredNativeWei??null,gasReserveWei:i.gasReserveWei??null,symbol:u.nativeSymbol,decimals:18}),Vt(Se.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}),Vt(Se.networkGateVerdict,{walletChainId:t.status().chainId,selectedChainId:u.chainId,settlementChainId:u.chainId,selectedChainName:u.name}),Vt(Se.counterpartyVerdict,{standIn:i.standIn===!0,liveChain:i.liveChain===!0,network:e.evmNetwork.id,chainId:u.chainId}),Vt(Se.escrowStateVerdict,{status:i.escrowStatus??null,error:null,address:i.escrowAddress??null}),...Ag(i.point,i.commit)?[Vt(Se.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})]:[],...Ag(i.slots)?[Vt(Se.liveOrderSlotsVerdict,{slots:i.slots??null,expect:i.slotsExpect??null,readError:i.slotsReadError??null})]:[]].map(T_),h=[...new Set(p.filter(w=>w.blocks).map(w=>w.code))];return{ok:h.length===0,blockedBy:h,checks:p}}}xe();var Ng=e=>typeof e=="string"?e:e&&typeof e.contents=="string"?e.contents:null;function Of({http:e=null,config:t=null}={}){return{async open(n,r){let o=Ng(n);if(o===null)throw new f("bad-input",{field:"file"});let i;try{i=JSON.parse(o)}catch{throw new f("recovery-failed",{stage:"parse"})}let s;try{s=await Qs.restoreFromFile(i,r)}catch{throw new f("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=Ng(n.file);if(r===null)throw new f("bad-input",{field:"file"});if(typeof n.passphrase!="string")throw new f("bad-input",{field:"passphrase"});let o;try{o=JSON.parse(r)}catch{throw new f("recovery-failed",{stage:"parse"})}let i;try{i=await yt.decryptFile(o,n.passphrase),yt.validatePayload(i)}catch{throw new f("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")),k=(Array.isArray(w)?w:w&&w.swaps||[]).find(x=>String(x&&x.address||"")===String(a))||null;l=Number(k&&k.restoreHeight)||0,k||(d="no-row")}catch{d="unreachable"}}let p=l>0?l:c,h=l>0?"app":c>0?"file":"none";return{address:a,height:p,source:h,fileHeight:c,appHeight:l,appAsked:u,appProblem:h==="none"?d||"no-height":null}}}}xe();var kc=Object.keys(ue.SCENARIO_LABELS||{});function Ig(){let e=kc[0]||null,t=1,n=0;return{scenarios:()=>kc.slice(),apply(r){kc.includes(r)||R("bad-input",{field:"scenario",known:kc}),e=r},speed(r){let o=Number(r);(!Number.isFinite(o)||o<=0)&&R("bad-input",{field:"speed"}),t=o},advance(r){let o=Number(r);Number.isFinite(o)||R("bad-input",{field:"ms"}),n+=o},debug:()=>({scenario:e,speed:t,advancedMs:n})}}xe();var B_=["connect","disconnect","address","chainId","subscribe","driver"],Tg=e=>e&&so.includes(e.code)?e.code:"unknown",Cf="monero",os={token:"xmr",symbol:"XMR",decimals:12},P_=2;function Bg({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")&&R("bad-input",{field:"adapter"});let l=B_.filter(d=>typeof c[d]!="function");l.length&&R("bad-input",{field:"adapter",missing:l}),(typeof c.vm!="string"||!c.vm)&&R("bad-input",{field:"adapter.vm"});let u=[e.vm,Cf];u.includes(c.vm)||R("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||R("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 f(Tg(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||R("wallet-not-connected"),Number.isFinite(Number(c))||R("bad-input",{field:"chainId"}),(n.vm!==e.vm||typeof n.switchChain!="function")&&R("not-implemented",{surface:"wallet.switchChain",vm:n.vm,stage:P_});try{await n.switchChain(Number(c))}catch(u){throw new f(Tg(u),{vm:n.vm})}let l=await s();return l.chainMatches||R("wrong-chain",{got:l.chainId,want:t.walletChainId(e)}),l},async balances(c){n||R("wallet-not-connected");let l=r.connected?r:await s(!1);if(l.connected||R("wallet-not-connected"),n.vm===Cf){let w=(Array.isArray(c)&&c.length?c.map(k=>String(k).toLowerCase()):[os.token]).find(k=>k!==os.token);w!==void 0&&R("bad-input",{field:"tokens",unknown:w}),typeof n.unlockedBalance!="function"&&R("not-implemented",{surface:"wallet.balances",vm:Cf});let y=BigInt(await n.unlockedBalance()).toString();return[{token:os.token,symbol:os.symbol,decimals:os.decimals,amount:y}]}l.chainMatches||R("wrong-chain",{got:l.chainId,want:t.walletChainId(e)}),typeof t.balances!="function"&&R("not-implemented",{surface:"wallet.balances",vm:e.vm});let u=e.tokens||[],d=Array.isArray(c)&&c.length?c.map(h=>String(h).toLowerCase()):u.map(h=>h.id),p=[];for(let h of d){let w=u.find(y=>y.id===h);w||R("bad-input",{field:"tokens",unknown:h}),p.push(w)}return t.balances({driver:n.driver(),address:l.address,tokens:p})},subscribe(c){return typeof c!="function"&&R("bad-input",{field:"handler"}),o.add(c),()=>o.delete(c)},driver:()=>n?n.driver():null}}xe();xe();$e();function O_(e=null,t=null){if(t&&t.spendHalf&&t.viewHalf)return vb(e,t).side;if(e!=null)return nf(e).side;let n=mn.createHalves(hn),r=n.newHalf(),o=n.newHalf();return{half:r,viewHalf:o,pub:n.publicHalves(r),viewPub:n.publicHalves(o).ed}}function Rf(e,{order:t=null,side:n=null,store:r=null}={}){if(!e||typeof e!="object")throw new f("bad-input",{field:"input"});let o=n||O_(t),i=null;try{i=me.createSwap(e,r)}catch{throw new f("bad-input",{field:"input"})}let s={...i.escrow||{},half:xn(o.half),viewHalf:xn(o.viewHalf),edPointLocker:ge(o.pub.ed),edViewPointLocker:ge(o.viewPub)};if(e.expectedAtomic!==void 0&&e.expectedAtomic!==null){let l;try{l=BigInt(String(e.expectedAtomic))}catch{throw new f("bad-input",{field:"expectedAtomic"})}if(l<=0n)throw new f("bad-input",{field:"expectedAtomic"});s.expectedAtomic=l.toString()}o.enc&&o.enc.pub&&(s.encPub=ge(o.enc.pub));let a={...i,escrow:s},c=e&&e.orderQuoteId;c!=null&&c!==""&&(a.orderQuoteId=c);try{me.saveSwap(a,r)}catch{throw new f("storage-unavailable",{step:"save-swap"})}return{swap:a,side:o,missing:["counterparty-half"],nextStep:"order"}}xe();xe();xe();$e();var R_="Declined",H_=()=>`${R_}(${["address"].join(",")})`,L_=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},Ro=L_(J(H_())),F_="declined",Sc="compliance",Sn="declined",D_=["declined","terminal","code","source","at","checked"],Pg=e=>{let t={};for(let n of D_)t[n]=e[n]===void 0?null:e[n];return t},Og=({source:e=null,at:t=null}={})=>Pg({declined:!0,terminal:Sn,code:Sc,source:e,at:t,checked:!0}),vc=({source:e=null,at:t=null,checked:n=!0}={})=>Pg({declined:!1,terminal:null,code:null,source:e,at:t,checked:n});function Hf(e,{escrow:t=null,at:n=null}={}){if(!Array.isArray(e))throw new f("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()===Ro)return Og({source:"event",at:n})}return vc({source:"event",at:n})}function M_(e,{at:t=null}={}){if(!e||typeof e!="object")return vc({source:"status",at:t,checked:!1});for(let n of[e,e.userStatus])if(!(!n||typeof n!="object")&&String(n.status||"")===F_&&String(n.code||"")===Sc)return Og({source:"status",at:t});return vc({source:"status",at:t})}function Cg({logs:e=void 0,status:t=void 0,escrow:n=null,at:r=null}={}){let o=Array.isArray(e)?Hf(e,{escrow:n,at:r}):null;if(o&&o.declined)return o;let i=t&&typeof t=="object"?M_(t,{at:r}):null;return i&&i.declined?i:o||i||vc({checked:!1,at:r})}async function U_({address:e,topics:t=[Ro],fromBlock:n="earliest",toBlock:r="latest"}={}){if(typeof e!="string"||!/^0x[0-9a-fA-F]{40}$/.test(e))throw new f("bad-input",{field:"logs.address"});let o=null;try{o=typeof Re.currentProvider=="function"?Re.currentProvider():null}catch{o=null}if(!o||typeof o.request!="function")throw new f("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 f("server-unavailable",{step:"logs",why:"bad-response"});return i}var Ec=e=>typeof e=="function"?e:U_,Ac=(e,t="earliest")=>{let n=Number(e);return!Number.isFinite(n)||n<0?t:"0x"+Math.trunc(n).toString(16)};var{chainById:mC,DEFAULT_CHAIN:wC,MONERO:yC}=ue,{fundOrderLive:bC,newSecret:gC,sendTransaction:Lf,readContract:_c}=Re,{encodeClaim:Rg,encodeRefund:Hg,encodeMarkReady:Lg,encodeStatus:j_,encodeT1:K_,encodeTermsHash:W_,encodeRead:Ff,decodeUint64:Fg,decodeBytes32:Dg,decodeStatus:V_}=Jr,{liveOrderSlotsVerdict:$_,counterpartyVerdict:xC}=Se,{orderContextString:kC}=At,{requestOrderQuote:vC,checkOrderQuoteShape:SC}=Ba,{CLAIM_GAS_LIMIT:z_}=ta;async function Br(e,t={}){if(!e)throw new f("bad-input",{field:"escrow"});let r=await(t.call||_c)({to:e,data:j_(),block:t.blockTag||"latest"});return V_(r)}async function Mg(e,t={}){if(typeof e!="string"||!e)throw new f("bad-input",{field:"escrow"});let n=Ec(t.logs),r=t.fromBlock===void 0?"earliest":Ac(t.fromBlock),o=await n({address:e,topics:[Ro],fromBlock:r,toBlock:"latest"});return Hf(o,{escrow:e,at:Number.isFinite(Number(t.at))?Number(t.at):null})}async function Pr(e,t={}){if(!e)throw new f("bad-input",{field:"escrow"});let n=t.call||_c,r=t.blockTag||"latest",[o,i,s]=await Promise.all([n({to:e,data:K_(),block:r}),n({to:e,data:W_(),block:r}),n({to:e,data:Ff("readyBy"),block:r})]);for(let[a,c]of[[o,"t1()"]])if(String(a||"").replace(/^0x/,"").length===0)throw new f("bad-input",{field:"escrow",why:"no-contract"});return{t1:Fg(o,"t1()"),termsHash:Dg(i,"termsHash()"),readyBy:Fg(s,"readyBy()")}}async function X_(e,t={}){let n=t.call||_c;if(!e)throw new f("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:Ff(a),block:o}))),s={};return r.forEach((a,c)=>{s[a]=Dg(i[c],a+"()")}),{slots:s}}catch(o){return{error:String(o&&o.message||o)}}}async function is(e,t,n="signature",r={}){if(!t)throw new f("bad-input",{field:"expect"});let o=await X_(e,r),i=$_({slots:o.slots,readError:o.error,expect:t});if(i.blocks)throw new f("contract-reverted",{step:n,why:"slots-mismatch"});return i}async function Df(e,t,n){let r=await Br(e,n);if(!r.isFunded||r.isClaimed||r.isRefunded)throw new f("contract-reverted",{step:t,why:"closed"})}async function Mf(e,t,n,r=null){if(typeof n.blockTime!="function")return;let o=n.call||_c,i=n.blockTag||"latest",[s,a]=await Promise.all([o({to:e,data:Ff("ready"),block:i}),Pr(e,n)]),c=BigInt(s)!==0n,l=Number(r===null?await n.blockTime():r);if(!Number.isSafeInteger(l)||l<=0)throw new f("contract-reverted",{step:t,why:"clock-unreadable"});let u=60;if(t==="claim"){if(l+u>=Number(a.t1))throw new f("contract-reverted",{step:t,why:"window-closed"});if(!c&&l<Number(a.readyBy))throw new f("contract-reverted",{step:t,why:"not-ready"})}else if(t==="refund"){if(l<Number(a.t1)&&(l+u>=Number(a.readyBy)||c))throw new f("contract-reverted",{step:t,why:"too-early"})}else if(t==="mark-ready"){if(c)throw new f("contract-reverted",{step:t,why:"already-ready"});if(l+u>=Number(a.readyBy))throw new f("contract-reverted",{step:t,why:"ready-window-closed"})}}async function Uf(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 f("contract-reverted",{step:n,why:"simulation",detail:typeof s=="string"?s.slice(0,200):null}):i}}async function Ug({escrow:e,halfClaimer:t,expect:n,onStep:r,deps:o={}}){if(!e)throw new f("bad-input",{field:"escrow"});if(!t)throw new f("bad-input",{field:"halfClaimer"});return await Df(e,"claim",o),await Mf(e,"claim",o),await is(e,n,"claim",o),await Uf(e,Rg(t),"claim",o),r?.("confirm-claim"),{hash:await(o.send||Lf)({to:e,data:Rg(t),gas:z_})}}async function jg({escrow:e,halfLocker:t,onStep:n,expect:r=null,deps:o={}}){if(!e)throw new f("bad-input",{field:"escrow"});if(!t)throw new f("bad-input",{field:"halfLocker"});return await Df(e,"refund",o),await Mf(e,"refund",o),r&&await is(e,r,"refund",o),await Uf(e,Hg(t),"refund",o),n?.("confirm-refund"),{hash:await(o.send||Lf)({to:e,data:Hg(t),gas:250000n})}}async function Kg({escrow:e,expect:t,onStep:n,deps:r={}}){if(!e)throw new f("bad-input",{field:"escrow"});return await Df(e,"mark-ready",r),await Mf(e,"mark-ready",r),await is(e,t,"mark-ready",r),await Uf(e,Lg(),"mark-ready",r),n?.("confirm-mark-ready"),{hash:await(r.send||Lf)({to:e,data:Lg(),gas:120000n})}}xe();async function Ho(e,t,n="send"){let r=Number(t);if(!Number.isSafeInteger(r)||r<=0)throw new f("bad-input",{field:"chainId",step:n});if(!e||typeof e.chainId!="function")throw new f("bad-input",{field:"wallet.chainId",step:n});let o=null;try{o=Number(await e.chainId())}catch{throw new f("wrong-chain",{vm:"evm",step:n,want:r,got:null,why:"unreadable"})}if(!Number.isSafeInteger(o)||o<=0)throw new f("wrong-chain",{vm:"evm",step:n,want:r,got:null,why:"unreadable"});if(o!==r)throw new f("wrong-chain",{vm:"evm",step:n,want:r,got:o});return r}var Y_=["commitHalfLocker","commitHalfClaimer","edPointLocker","edPointClaimer","edViewPointLocker"],G_=e=>typeof e=="string"&&e&&!/^0x/i.test(e)?"0x"+e:e;function Wg(e){if(!e||typeof e!="object")throw new f("bad-input",{field:"request"});let t={...e};for(let n of Y_)t[n]=G_(t[n]);return t}function q_(e){if(!e||typeof e!="object")throw new f("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 f("bad-input",{field:"terms",missing:n});try{return Jr.orderTerms(Wg(e))}catch{let o=Math.floor(Date.now()/1e3);throw Number(e.readyBy)<=o?new f("bad-input",{field:"readyBy",why:"not-in-future"}):Number(e.t1)<=Number(e.readyBy)?new f("bad-input",{field:"t1",why:"not-after-readyBy"}):new f("bad-input",{field:"terms"})}}var Q_=e=>String(e??"").replace(/0x[0-9a-fA-F]{64}/g,"0x<redacted>").slice(0,200),Z_=/fetch failed|network|ECONN|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|socket|timeout|HTTP \d|status \d|non-ok/i,J_=e=>Z_.test(e);async function Vg(e,t,n={}){if(!e||typeof e!="object")throw new f("bad-input",{field:"request"});if(!t||typeof t.send!="function"||typeof t.receipt!="function")throw new f("bad-input",{field:"wallet",missing:["send","receipt"]});let r=Wg(e);q_({...r,amount:r.amountWei});let o=Re;await Ho(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=Q_(s&&s.message||s);throw new f(J_(a)?"server-unavailable":"bad-input",{step:"fund-order",why:a})}}to();$e();xe();var t3=(e,t)=>t.filter(n=>e[n]===void 0||e[n]===null||e[n]===""),Kf=e=>{let t=["send","receipt"],n=e?t.filter(r=>typeof e[r]!="function"):t;if(n.length)throw new f("bad-input",{field:"wallet",missing:n});return e};function n3({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 Wf=(e,t)=>{if(!e||typeof e!="object")throw new f("bad-input",{field:"request"});let n=t3(e,["escrow","expect",...t]);if(n.length)throw new f("bad-input",{field:"request",missing:n});return e},Vf=async(e,t)=>{try{return await t()}catch(n){throw n&&typeof n.code=="string"?n:new f("contract-reverted",{step:e})}};function ss({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 f("wallet-not-connected",{surface:"actions.read"})}:async({to:l,data:u,from:d})=>{let p=d?{to:l,data:u,from:d}:{to:l,data:u},h=await c.request({method:"eth_call",params:[p,"latest"]});if(typeof h!="string"||!h.startsWith("0x"))throw new f("contract-reverted",{surface:"actions.read"});return h}},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 f("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){Wf(a,[]),Kf(c);let{escrow:l,expect:u,onStep:d}=a,p=await i(c,"mark-ready");return await Ho(c,u.chainId,"mark-ready"),await Vf("mark-ready",()=>Kg({escrow:l,expect:u,onStep:d,deps:s(c,u.chainId,p)}))},async claim(a,c){Wf(a,["halfClaimer"]),Kf(c);let{escrow:l,halfClaimer:u,expect:d,onStep:p}=a,h=await i(c,"claim"),w=n3({sender:h,claimer:a.claimer||d&&d.claimer});if(!w.ok)throw new f(w.code,{field:w.field,why:w.why,surface:"actions.claim"});return await Ho(c,d.chainId,"claim"),await Vf("claim",()=>Ug({escrow:l,halfClaimer:u,expect:d,onStep:p,deps:s(c,d.chainId,h)}))},async refund(a,c){Wf(a,["halfLocker"]),Kf(c);let{escrow:l,halfLocker:u,expect:d,onStep:p}=a,h=await i(c,"refund");return await Ho(c,d.chainId,"refund"),await Vf("refund",()=>jg({escrow:l,halfLocker:u,expect:d,onStep:p,deps:s(c,d.chainId,h)}))}}}xe();var Lo=e=>typeof e=="string"&&e.length>0,Nc=e=>{let t=Number(e);return Number.isFinite(t)?Math.trunc(t):null},r3=e=>Lo(e)?e.trim().replace(/^0x/,"").toLowerCase():null,$g=e=>{try{return new URL(e).host}catch{throw new f("bad-input",{field:"nodes.url",unknown:e})}},as=(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 o3(e){if(!Array.isArray(e))throw new f("bad-input",{field:"nodes"});let t=[];for(let n of e)if(Lo(n)){let r=n.replace(/\/+$/,"");t.push({url:r,operator:$g(r)})}else if(n&&typeof n=="object"&&Lo(n.url)){let r=n.url.replace(/\/+$/,"");t.push({url:r,operator:Lo(n.operator)?n.operator:$g(r)})}else throw new f("bad-input",{field:"nodes",why:"each-node-is-url-or-url+operator"});if(!t.length)throw new f("bad-input",{field:"nodes",why:"empty-list"});return t}async function $f(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 f("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 f("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 f("xmr-no-nodes",{node:e.url,name:a,why:c?"timeout":"bad-json"})}}async function zg(e,t,n){let r=await $f(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 f("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 f("xmr-no-nodes",{node:e.url,why:"busy"});return{height:Number(o.height),synced:o.synchronized!==!1,nettype:o.nettype||null}}async function Xg(e,t,n,r){let o=await $f(e,"/json_rpc",{jsonrpc:"2.0",id:"block",method:"get_block",params:{height:t}},n,r),i=o&&o.result;if(!i)throw new f("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 Yg(e,t,n,r){if(!t.length)return[];let o=await $f(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 f("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 f("xmr-no-nodes",{node:e.url,why:"bad-json"})}let d=i[l]||{};return u.tx_hash=String(d.tx_hash||u.tx_hash||"").replace(/^0x/,"").toLowerCase(),u.block_height=d.block_height??null,u.confirmations=d.confirmations??null,u}).filter(c=>t.includes(String(c.tx_hash||"").toLowerCase()));if(a.length!==t.length)throw new f("xmr-no-nodes",{node:e.url,why:"partial-transactions",want:t.length,got:a.length});return a}var Gg=e=>e.outputs.reduce((t,n)=>t+(n.amountVerified&&n.amountAtomic||0n),0n);async function i3(e,{expectedAtomic:t,address:n,viewSecret:r,spendPub:o,fromHeight:i,toHeight:s,nowSec:a,fetchImpl:c,timeoutMs:l}){let u=Math.max(0,Nc(i)??0),d=Nc(s);if(!Number.isFinite(d)||d<u)throw new f("bad-input",{field:"fromHeight",got:i});let p=null;for(let h=u;h<=d;h++){let{txHashes:w}=await Xg(e,h,c,l);if(!w.length)continue;let y=await Yg(e,w,c,l);for(let k of y){let x=Ei.matchTransaction(k,[{address:n,viewSecret:r,spendPub:o}],{height:h,tipHeight:Math.max(0,d),nowSec:a});if(!x.length)continue;let _=Gg(x[0]),v=x[0].outputs.every(O=>O.amountVerified===!0),H=x[0].unlock&&x[0].unlock.locked===!0,b=(_>=t?4:0)+(v?2:0)+(H?0:1),I={txid:k.tx_hash,height:h};if(b===7)return I;(!p||b>p.score||b===p.score&&_>p.amountAtomic)&&(p={...I,score:b,amountAtomic:_})}}return p}async function Ic(e){if(!e||typeof e!="object")throw new f("bad-input",{field:"request"});let t=o3(e.nodes);if(!Lo(e.address))throw new f("bad-input",{field:"address"});if(e.viewSecret===void 0||e.viewSecret===null)throw new f("bad-input",{field:"viewSecret"});if(!Lo(e.spendPub))throw new f("bad-input",{field:"spendPub"});let n;try{n=BigInt(e.expectedAtomic)}catch{throw new f("bad-input",{field:"expectedAtomic"})}if(n<=0n)throw new f("bad-input",{field:"expectedAtomic"});let r=Math.max(1,Nc(e.minConfirmations)??1),o=typeof e.fetch=="function"?e.fetch:globalThis.fetch;if(typeof o!="function")throw new f("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=r3(e.txid),c={address:e.address,viewSecret:e.viewSecret,spendPub:e.spendPub},l=[],u=[];for(let S of t)try{let T=await zg(S,o,s);l.push({node:S,info:T})}catch(T){u.push(as(T,S))}if(!l.length)throw new f("xmr-no-nodes",{tried:t.map(S=>S.url),nodes:u});let d=Math.max(...l.map(S=>S.info.height)),p=Math.max(0,d-1),h=null,w=new Set;for(let{node:S}of l){try{h=await i3(S,{expectedAtomic:n,address:e.address,viewSecret:e.viewSecret,spendPub:e.spendPub,fromHeight:e.fromHeight,toHeight:p,nowSec:i,fetchImpl:o,timeoutMs:s}),h||w.add(S.operator)}catch(T){u.push(as(T,S)),h=null}if(h)break}if(!h){if(!w.size)throw new f("xmr-no-nodes",{tried:t.map(S=>S.url),nodes:u});return{seen:!1,state:"pending",absent:w.size>=2,txid:a,tip:d,completedOperators:[...w],checked:l.map(S=>({url:S.node.url,operator:S.node.operator,height:S.info.height})),failed:u}}let y=[];for(let S of t){let T={url:S.url,operator:S.operator},N;try{N=await zg(S,o,s)}catch(g){T.state="down",T.failure=as(g,S),u.push(T.failure),y.push(T);continue}if(!N.synced||N.height<h.height){T.state="stale",T.height=N.height,y.push(T);continue}T.height=N.height;let V;try{V=await Xg(S,h.height,o,s)}catch(g){T.state="down",T.failure=as(g,S),u.push(T.failure),y.push(T);continue}if(T.blockHash=V.hash,!V.hash||!V.txHashes.includes(h.txid)){T.state="no-tx",y.push(T);continue}let X=null;try{X=(await Yg(S,V.txHashes,o,s)).find(g=>g.tx_hash===h.txid)||null}catch(g){T.state="down",T.failure=as(g,S),u.push(T.failure),y.push(T);continue}if(!X){T.state="no-tx",y.push(T);continue}let m=Ei.matchTransaction(X,[c],{height:h.height,tipHeight:Math.max(0,N.height-1),nowSec:i});if(!m.length){T.state="no-output",y.push(T);continue}if(T.state="ok",T.amountAtomic=Gg(m[0]),T.amountVerified=m[0].outputs.every(g=>g.amountVerified===!0),T.outputs=m[0].outputs.map(g=>({index:g.index,key:String(g.key||"").replace(/^0x/,"").toLowerCase(),amountAtomic:g.amountVerified?String(g.amountAtomic??null):null,amountVerified:g.amountVerified===!0})),T.unlock=m[0].unlock,T.confirmations=Number.isFinite(Number(X.confirmations))?Number(X.confirmations):N.height-h.height,!T.amountVerified){T.state="amount-unverified",y.push(T);continue}T.observation={txid:h.txid,blockHash:String(V.hash||"").replace(/^0x/,"").toLowerCase(),outputs:T.outputs,unlock:T.unlock?{locked:T.unlock.locked===!0,untilHeight:T.unlock.untilHeight??null,untilTime:T.unlock.untilTime??null}:null},y.push(T)}let k=y.filter(S=>S.state==="no-tx"||S.state==="no-output"||S.state==="amount-unverified");if(k.length)throw new f("xmr-nodes-disagree",{txid:h.txid,height:h.height,nodes:k.map(S=>({url:S.url,operator:S.operator,blockHash:S.blockHash||null,why:S.state,outputs:S.outputs||null})),agreed:y.filter(S=>S.state==="ok").map(S=>({url:S.url,operator:S.operator,blockHash:S.blockHash})),failed:u});let x=y.filter(S=>S.state==="ok");if(!x.length)return{seen:!1,state:"pending",txid:h.txid,height:h.height,checked:y,failed:u};let _=new Map;for(let S of x){let T=JSON.stringify(S.observation);_.has(T)||_.set(T,{observation:S.observation,operators:new Set,nodes:[]});let N=_.get(T);N.operators.add(S.operator),N.nodes.push(S)}if(_.size>1)throw new f("xmr-nodes-disagree",{txid:h.txid,height:h.height,nodes:x.map(S=>({url:S.url,operator:S.operator,blockHash:S.blockHash||null,outputs:S.outputs,why:"observation"})),agreed:[],failed:u});let v=[..._.values()][0],H=Math.min(...v.nodes.map(S=>S.confirmations)),b=v.nodes[0].amountAtomic,I=v.nodes.map(S=>({url:S.url,operator:S.operator,blockHash:S.blockHash,confirmations:S.confirmations})),O=v.nodes.find(S=>S.unlock&&S.unlock.locked);if(O){let S=O.unlock;throw new f("xmr-locked",{txid:h.txid,height:h.height,address:e.address,untilHeight:S.untilHeight??null,untilTime:S.untilTime??null,failed:u})}if(b<n)throw new f("xmr-underpaid",{txid:h.txid,height:h.height,got:b.toString(),want:n.toString(),failed:u});return v.operators.size<2?{seen:!1,state:"one-node",txid:h.txid,height:h.height,blockHash:v.observation.blockHash,amountAtomic:b.toString(),confirmations:H,operators:[...v.operators],agreedBy:I,checked:y,failed:u}:H<r?{seen:!1,state:"pending",why:"confirmations",txid:h.txid,height:h.height,blockHash:v.observation.blockHash,amountAtomic:b.toString(),confirmations:H,needConfirmations:r,agreedBy:I,checked:y,failed:u}:{seen:!0,state:"arrived",txid:h.txid,height:h.height,blockHash:v.observation.blockHash,amountAtomic:b.toString(),confirmations:H,needConfirmations:r,operators:[...v.operators],agreedBy:I,checked:y,failed:u}}function zf({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,Nc(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 f("xmr-too-late",{needSec:c,leftSec:l,minConfirmations:s,readyBy:Math.floor(o)});return l}var a3={success:"success",refund_eth:"refunded_eth",[Sn]:Sn},$t=e=>{if(e==null||e==="")return null;let t=Number(e);return Number.isFinite(t)?t:null},c3="xmr_locked",l3=["id","network","escrow","quoteId","providerId","hashlock","amount","t0","t1","sdkVersion"],u3=["swapId","network","address","viewKey","expectedAmountXmr","restoreHeight","chain"];function d3(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:bo}}function qg(e){let t=e&&e.escrow||{};if(typeof t.viewHalf!="string"||!t.viewHalf)throw new f("bad-input",{field:"viewHalf"});if(typeof t.counterViewHalf!="string"||!t.counterViewHalf)throw new f("bad-input",{field:"counterViewHalf"});try{return mn.createHalves(hn).combineHalves(BigInt(t.viewHalf),BigInt(t.counterViewHalf)).toString(16).padStart(64,"0")}catch{throw new f("bad-input",{field:"viewKey"})}}function Qg(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===c3,o=$t(e.lockedXmr);return{id:e.id||null,address:e.address||null,status:e.status||null,expectedXmr:$t(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 Zg(e){if(!e||typeof e!="object"||!e.id)throw new f("bad-input",{field:"swap"});let t=me.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?a3[t.terminal.kind]??"closed":null,a=s===Sn,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:e.xmrSession!==null&&e.xmrSession!==void 0||e.xmr&&(e.xmr.received!==void 0||e.xmr.arrived!==void 0)?$t(t.xmrAmount&&t.xmrAmount.seen):null,escrowLocked:!!(e.escrow&&(e.escrow.fundTx||e.escrow.secret))},pay:{token:e.payToken||"eth",amount:$t(e.payAmount)},get:{xmr:$t(e.xmrAmount)},step:i.code,steps:n,deadlines:{readyBy:t.deadlines&&t.deadlines.readyBy!==void 0?$t(t.deadlines.readyBy):null,t1:t.deadlines&&t.deadlines.t1!==void 0?$t(t.deadlines.t1):null},xmr:{confirmations:$t(t.xmr&&(t.xmr.confirmations!==void 0?t.xmr.confirmations:t.conf))??0,target:$t(t.xmr&&t.xmr.confTarget)??$t(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 Jg=12,ex=(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 f("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 f3({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 db({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 f("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 f("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 f("xmr-no-nodes",{step:"restore-height",network:t||null,why:s})}var p3=300;function h3({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+p3)*1e3)}function Xf({preflight:e,http:t,createRecord:n,mode:r=null,xmrNetwork:o=null,call:i=null,now:s=null,evmBlock:a=null,store:c=hr,config:l=null,auth:u=null,denylist:d=null,watch:p=null,logs:h=null}={}){let w=typeof i=="function"?i:Re.readContract,y=async(m=null)=>{let g=null;if(typeof a=="function")g=await a("latest");else if(m&&typeof m.driver=="function"){let M=m.driver();if(M&&typeof M.request=="function"){let $=await M.request({method:"eth_blockNumber"});typeof $=="string"&&/^0x[0-9a-f]+$/i.test($)&&(g=await M.request({method:"eth_getBlockByNumber",params:[$,!1]}))}}let E=g&&Number(g.number),C=g&&Number(g.timestamp);return!Number.isSafeInteger(E)||E<0||!Number.isFinite(C)||C<=0?null:{blockTag:"0x"+E.toString(16),timestamp:C}},k=Ec(h),x=ss({call:typeof i=="function"?i:null}),_=(m,g)=>{if(!l||typeof l.route!="function")throw new f("bad-input",{field:"config",step:"server"});return l.route(m,g)},v=(m,g)=>{let E=l&&l.limits?l.limits[m]:null;return Number.isFinite(Number(E))&&Number(E)>0?Number(E):g};async function H(m,g){let E=Number(m.restoreHeight);if(Number.isSafeInteger(E)&&E>0)return E;let C=Array.isArray(m.xmrNodes)?m.xmrNodes:l&&typeof l.nodesFor=="function"?l.nodesFor(g):[];return f3({nodes:C,network:g,fetchImpl:m.fetchImpl||(typeof fetch=="function"?fetch:null)})}let b=()=>{let m=c.loadState();return Object.values(m&&m.swaps||{}).filter(E=>E&&E.id).sort((E,C)=>Number(C.createdAt||0)-Number(E.createdAt||0))},I=(m,g)=>{let E=String(m||""),C=String(g||"").replace(/^0x/i,"").toLowerCase();return!E&&!C?null:b().find(M=>{if(!(M.fundingPending===!0||M.escrow&&M.escrow.fundingPending===!0))return!1;if(E&&String(M.orderQuoteId||"")===E)return!0;let $=String(M.escrow&&M.escrow.salt||M.recoverySalt||"").replace(/^0x/i,"").toLowerCase();return!!(C&&$===C)})||null};async function O(m,g){let E=m.swap||m,C=E.escrow&&typeof E.escrow=="object"?E.escrow:{},M=C.fundTx||E.fundTx||null,$=null;if(C.address)try{$=await Br(C.address,{call:w})}catch(D){/short .*status\(\)/.test(String(D&&D.message||D))?$={isFunded:!1,absent:!0}:$=null}if(!M&&$&&!$.isFunded&&C.fundingReason==="not-sent"){delete E.fundingPending,E.escrow={...C,fundingPending:!1,fundingReason:"send-not-started"};try{me.saveSwap(E,c)}catch{throw new f("storage-unavailable",{step:"save-pending"})}return null}if(!M&&!($&&$.isFunded))return{id:E.id||null,escrow:C.address||null,address:m.swapWallet&&m.swapWallet.address||null,step:"funding-pending",txHash:null,reason:"no-transaction-hash",next:"receipt"};let L=g.wallet,F=null;if(M&&L&&typeof L.receipt=="function")try{F=await L.receipt(M)}catch{F=null}let B=g.order&&typeof g.order=="object"?g.order:{},P=ka(F,{factory:B.factory||g.orderQuote&&g.orderQuote.factory||null,expectedEscrow:C.address||null});if(P.status==="reverted")throw new f("contract-reverted",{step:"funding"});if(P.status==="funded"||$&&$.isFunded){let D=P.status==="funded"?P.escrow:C.address;if(!D)throw new f("funding-pending",{reason:"no-escrow-address"});E.escrow={...C,address:D,fundingPending:!1,evmBirthBlock:Number(P.birthBlock)>0?Number(P.birthBlock):C.evmBirthBlock??null},delete E.fundingPending;try{me.saveSwap(E,c)}catch{throw new f("storage-unavailable",{step:"save-escrow"})}return{id:E.id||null,escrow:D,address:m.swapWallet&&m.swapWallet.address||null,step:"xmr-incoming",server:null,watch:null,next:"watch"}}return{id:E.id||null,escrow:C.address||null,address:m.swapWallet&&m.swapWallet.address||null,step:"funding-pending",txHash:M,reason:P.reason||"no-receipt",next:"receipt"}}async function S(m){let g=m.order&&typeof m.order=="object"?m.order:{},E=g.amount,C=E==null||E===""?null:String(E),M=Number(g.chainId),$=Number.isFinite(M)?ue.chainByChainId(M):null,L=$?ue.tokensOf($.id):[],F=String(m.quote&&(m.quote.token||m.quote.asset)||"").toLowerCase(),B=L.find(q=>String(q.symbol).toLowerCase()===F)||null,P=L.find(q=>!q.address)||null,D=!!(B&&!B.address),U={tokenIsNative:D,standIn:!m.counterparty&&r!=="live",liveChain:!!($&&$.escrow&&$.escrow.mode==="live"&&!$.testnet)};C!==null&&(U.payAmountWei=C,U.requiredNativeWei=C);try{let q=m.wallet,W=q&&typeof q.driver=="function"?q.driver():null,G=q&&typeof q.address=="function"?await q.address():null,z=yo("evm"),ee=A=>String(A.symbol).toLowerCase(),Q=[];if(P&&Q.push({id:ee(P),symbol:P.symbol,decimals:P.decimals,address:null}),B&&B.address&&Q.push({id:ee(B),symbol:B.symbol,decimals:B.decimals,address:B.address}),W&&G&&z&&typeof z.balances=="function"&&Q.length){let A=await z.balances({driver:W,address:G,tokens:Q}),j=Y=>{let ne=Y?A.find(oe=>oe.token===ee(Y)):null;return ne&&ne.amount!==null?ne.amount:null},K=P?j(P):null;K!==null&&(U.nativeBalanceWei=K);let Z=D?K:j(B);Z!==null&&(U.payBalanceWei=Z)}}catch{}return U}async function T(m,g,E){if(!t||typeof t.tryJson!="function")throw new f("bad-input",{field:"http",step:"mark"});let C=d3(m,g,E),M=JSON.stringify(Object.fromEntries(l3.map(F=>[F,C[F]]))),$={"content-type":"application/json"};if(typeof u=="function"){let F=null;try{F=await u()}catch{F=null}typeof F=="string"&&F&&($.authorization="Bearer "+F)}let L=null;try{L=await t.tryJson(_("evmSwaps"),{method:"POST",headers:$,body:M})}catch(F){throw new f("server-unavailable",{step:"mark",why:F&&F.code||"fetch"})}if(!L||L.ok!==!0)throw new f("server-refused",{step:"mark",status:L?L.status:null,why:L&&L.body&&(L.body.error||L.body.detail)||null});return{marked:!0,httpStatus:L.status,orderBinding:L.body&&L.body.orderBinding||null}}async function N(m,g){if(!t||typeof t.tryJson!="function")throw new f("bad-input",{field:"http",step:"watch"});let E=m&&m.escrow||{},C=E.moneroAddress||m.swapWallet&&m.swapWallet.address||null;if(!C)throw new f("bad-input",{field:"moneroAddress"});let M=$t(g&&g.xmrAmount!==void 0?g.xmrAmount:m.xmrAmount);if(!(M>0))throw new f("bad-input",{field:"expectedAmountXmr"});let $=m.moneroNetwork||o||null;if(!$)throw new f("bad-input",{field:"moneroNetwork"});let L=Number(m.restoreHeight)>0?Number(m.restoreHeight):Number(E.moneroRestoreHeight)>0?Number(E.moneroRestoreHeight):null;if(!(L>0))throw new f("bad-input",{field:"restoreHeight",step:"watch"});let F={swapId:m.id||null,network:$,address:C,viewKey:qg(m),expectedAmountXmr:M,restoreHeight:L,chain:m.network||m.chain||null},B={sdkVersion:bo};for(let U of u3)F[U]!==void 0&&F[U]!==null&&(B[U]=F[U]);p&&p.sendViewKeyToServer===!1&&delete B.viewKey;let P=null;try{P=await t.tryJson(_("swaps"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(B)})}catch(U){throw new f("server-unavailable",{step:"watch",why:U&&U.code||"fetch"})}if(!P||P.ok!==!0)throw new f("server-refused",{step:"watch",status:P?P.status:null,why:P&&P.body&&(P.body.error||P.body.detail)||null});let D=Qg(P.body);if(!D)throw new f("server-unavailable",{step:"watch",why:"bad-response"});return{registered:!0,httpStatus:P.status,...D,expectedXmr:D.expectedXmr!==null?D.expectedXmr:M}}async function V(m){if(!t||typeof t.tryJson!="function")throw new f("bad-input",{field:"http",step:"watch"});let g=null;try{g=await t.tryJson(_("swap",{id:m}),{method:"GET"})}catch(E){throw new f("server-unavailable",{step:"watch",why:E&&E.code||"fetch"})}if(!g||g.ok!==!0)throw new f("server-refused",{step:"watch",status:g?g.status:null,id:m,why:g&&g.body&&(g.body.error||g.body.detail)||null});return g.body}async function X(m,g,E=null){if(!m||!g)throw new f("bad-input",{field:"escrow"});let C=null;try{C=await y(E)}catch{throw new f("quote-refused",{step:"send-xmr",why:"block-unreadable"})}let M={call:w,blockTag:C?C.blockTag:"latest"},$=C?C.timestamp:Math.floor((typeof s=="function"?s():Date.now())/1e3),L=null;try{L=await Br(m,M)}catch{throw new f("quote-refused",{step:"send-xmr",why:"escrow-unreadable"})}if(!L||L.isFunded!==!0||L.isClaimed===!0||L.isRefunded===!0)throw new f("quote-refused",{step:"send-xmr",why:"escrow-not-open"});let F=null;try{F=await Pr(m,M)}catch{throw new f("quote-refused",{step:"send-xmr",why:"deadline-unreadable"})}if(Number(F.readyBy)!==Number(g.readyBy)||Number(F.t1)!==Number(g.t1))throw new f("quote-refused",{step:"send-xmr",why:"terms-mismatch"});let B=Math.max(1,Number(v("xmrConfirmations",10))),P=Math.max(1,Number(v("xmrBlockTimeSec",120))),D=Number(v("sellReadyLeadSec",0)),U=Number.isFinite(D)&&D>0?D:B*P;if($+U>=Number(F.readyBy))throw new f("quote-refused",{step:"send-xmr",why:"deadline-too-close"});try{await is(m,g,"send-xmr",M)}catch(q){throw q&&q.code==="contract-reverted"?q:new f("quote-refused",{step:"send-xmr",why:"slots-unreadable"})}}return{async list(){return b().map(Zg)},async get(m){if(typeof m!="string"||!m)throw new f("bad-input",{field:"id"});let g=b().find(E=>E.id===m);return g?Zg(g):null},async progress(m){if(typeof m!="string"||!m)throw new f("bad-input",{field:"id"});let g=me.getSwap(m,c);return g?{id:String(g.id||m),swap:g,swapWallet:me.halvesWalletOf(g),view:me.derive(g)}:null},async confirmReady(m){if(typeof m!="string"||!m)throw new f("bad-input",{field:"id"});return me.confirmReady(m,c)},async refundEth(m,g="you"){if(typeof m!="string"||!m)throw new f("bad-input",{field:"id"});return me.refundEth(m,g,c)},async sweepNow(m){if(typeof m!="string"||!m)throw new f("bad-input",{field:"id"});return me.sweepNow(m,c)},async setDestination(m,g){if(typeof m!="string"||!m)throw new f("bad-input",{field:"id"});if(typeof g!="string"||!g)throw new f("bad-input",{field:"address"});let E=me.getSwap(m,c);return E?(E.receiveAddress=g,me.saveSwap(E,c)):null},async addressNetwork(m){if(typeof m!="string"||!m)return null;try{return En.networkFromShape(m)}catch{return null}},async forget(m){if(typeof m!="string"||!m)throw new f("bad-input",{field:"id"});let g=null;try{g=c.loadState()}catch{throw new f("storage-unavailable",{step:"forget"})}let E=g&&g.swaps;if(!E||!E[m])return!1;delete E[m];try{c.saveState(g)}catch{throw new f("storage-unavailable",{step:"forget"})}return!0},async sync(){if(!t||typeof t.tryJson!="function")throw new f("bad-input",{field:"http",step:"sync"});let m={};if(typeof u=="function"){let M=null;try{M=await u()}catch{M=null}typeof M=="string"&&M&&(m.authorization="Bearer "+M)}let g=null;try{g=await t.tryJson(_("evmSwaps"),{method:"GET",headers:m})}catch(M){throw new f("server-unavailable",{step:"sync",why:M&&M.code||"fetch"})}if(!g||g.ok!==!0)throw new f("server-refused",{step:"sync",status:g?g.status:null,why:g&&g.body&&(g.body.error||g.body.detail)||null});let E=g.body;if(!E||!Array.isArray(E.swaps))throw new f("server-unavailable",{step:"sync",why:"bad-response"});return{ok:!0,added:me.addServerSwaps(E.swaps,c),seen:E.swaps.length}},verifyArrival:m=>Ic(m),assertTimeForConfirmations:m=>zf(m),async refundIfXmrMissing(m={},g={}){let E=typeof g.verify=="function"?g.verify:Ic,C=typeof g.refund=="function"?g.refund:x.refund,M=typeof g.now=="function"?g.now:()=>Math.floor(Date.now()/1e3);if(!m||typeof m!="object")throw new f("bad-input",{field:"request"});let $=m.swap&&typeof m.swap=="object"?m.swap:null,L=$&&$.escrow||{},F=m.escrow||L.address||null;if(!F)throw new f("bad-input",{field:"escrow"});let B=m.halfLocker||L.half||null;if(!B)throw new f("bad-input",{field:"halfLocker"});if(!m.expect||typeof m.expect!="object")throw new f("bad-input",{field:"expect"});let P=m.address||L.moneroAddress||null;if(!P)throw new f("bad-input",{field:"address"});let D=m.viewSecret!==void 0&&m.viewSecret!==null?m.viewSecret:$?qg($):null;if(D==null)throw new f("bad-input",{field:"viewSecret"});let U=m.spendPub||L.moneroSpendPub||null;if(!U)throw new f("bad-input",{field:"spendPub"});let q=m.expectedAtomic!==void 0&&m.expectedAtomic!==null?m.expectedAtomic:L.expectedAtomic!==void 0&&L.expectedAtomic!==null?L.expectedAtomic:null;if(q===null)throw new f("bad-input",{field:"expectedAtomic",why:"unsigned-amount"});let W=Number(m.readyBySec!==void 0&&m.readyBySec!==null?m.readyBySec:L.readyBy);if(!Number.isFinite(W)||W<=0)throw new f("bad-input",{field:"readyBySec"});let G=Number.isFinite(Number(m.minConfirmations))&&Number(m.minConfirmations)>0?Math.trunc(Number(m.minConfirmations)):v("xmrConfirmations",10),z=Number.isFinite(Number(m.blockTimeSec))&&Number(m.blockTimeSec)>0?Number(m.blockTimeSec):v("xmrBlockTimeSec",120),ee=Number.isFinite(Number(m.leadSec))&&Number(m.leadSec)>=0?Number(m.leadSec):G*z,Q=m.fromHeight!==void 0&&m.fromHeight!==null?Number(m.fromHeight):Number($&&($.restoreHeight??L.moneroRestoreHeight??L.restoreHeight));if(!Number.isSafeInteger(Q)||Q<=0)throw new f("bad-input",{field:"fromHeight",why:"missing"});let A=Number.isFinite(Number(m.nowSec))?Number(m.nowSec):M(),j=Math.floor(W-A);if(j<=0)return{refunded:!1,state:"claim-window",leftSec:j,readyBy:W,nowSec:A};if(j>ee)return{refunded:!1,state:"waiting",leftSec:j,needSec:ee,readyBy:W,nowSec:A};let K=null;try{K=await E({nodes:m.nodes,address:P,viewSecret:D,spendPub:U,expectedAtomic:q,minConfirmations:G,txid:m.txid||null,fromHeight:Q,timeoutMs:m.timeoutMs,nowSec:A})}catch(Y){if(Y&&Y.code==="xmr-underpaid")return{refunded:!1,state:"arrival-underpaid",leftSec:j,verdict:null,error:Y.params||null};if(Y&&Y.code==="xmr-locked")return{refunded:!1,state:"arrival-locked",leftSec:j,verdict:null,error:Y.params||null};throw Y}if(K.seen)return{refunded:!1,state:"arrived",leftSec:j,verdict:K};if(!K||K.absent!==!0)return{refunded:!1,state:"arrival-pending",leftSec:j,verdict:K};let Z=await C({escrow:F,halfLocker:B,expect:m.expect,onStep:m.onStep},m.wallet);return{refunded:!0,state:"refunded",hash:Z&&Z.hash||null,leftSec:j,verified:K}},async start(m){if(!m||typeof m!="object")throw new f("bad-input",{field:"request"});if(m.side==="sell")throw new f("bad-input",{field:"side",why:"sell-not-supported",surface:"swaps.start"});if(!m.quote||typeof m.quote!="object")throw new f("bad-input",{field:"quote"});if(m.recoveryKey===void 0||m.recoveryKey===null)throw new f("bad-input",{field:"recoveryKey",why:"required"});if(!m.receiveTo||typeof m.receiveTo!="string")throw new f("bad-input",{field:"receiveTo"});if(!ex(m,o).expectedAtomic)throw new f("bad-input",{field:"expectedAtomic",why:"signed-amount-missing"});let g=m.orderQuote&&m.orderQuote.id||m.quote&&m.quote.id||null,E=m.recoverySalt||m.order&&m.order.salt||m.orderQuote&&m.orderQuote.salt||null,C=I(g,E);if(C){let re=await O(C,m);if(re)return re}if(m.recoverySalt===void 0||m.recoverySalt===null){if(!m.order||typeof m.order!="object")throw new f("bad-input",{field:"order"});(m.order.salt===void 0||m.order.salt===null||m.order.salt==="")&&(m.order={...m.order,salt:bb()}),m.recoverySalt=m.order.salt}let M=await S(m),$=e?await e(m.quote,M):null,F=($&&($.checks||$.results)||[]).filter(re=>re&&re.blocks===!0);if(F.length){let re=F[0];throw new f(re.code||"bad-input",{...re.params||{},kind:re.kind,surface:"swaps.start"})}let B=null,P=null,D=typeof n=="function"?n:async re=>Rf(ex(re,o),{order:re.order,side:B,store:c}),U=typeof m.passphrase=="string"?m.passphrase:"";if(typeof U!="string")throw new f("bad-input",{field:"passphrase"});if(U.length>0&&U.length<Jg)throw new f("bad-input",{field:"passphrase",min:Jg});let q=Ut(m.order),W=null;{let re=c.storage(),ie=typeof m.recoveryKey=="string"?m.recoveryKey:m.recoveryKey&&typeof m.recoveryKey.mnemonic=="string"?m.recoveryKey.mnemonic:null,ce=Jd(re);if(ce&&ie&&ce.mnemonic!==ie)throw new f("bad-input",{field:"recoveryKey",why:"different-key"});if(!ce&&!ie)throw new f("bad-input",{field:"recoveryKey"});let ve=ce||Gd(ie);ce||Hi(re,{...ve,backupConfirmed:!1});let Xt=m.order.chainId;if(typeof m.order.factory!="string"||!m.order.factory)throw new f("bad-input",{field:"order.factory"});let ae;try{ae=gn(m.recoverySalt)}catch{throw new f("bad-input",{field:"recoverySalt"})}let Ue;try{Ue=gn(m.order.salt)}catch{throw new f("bad-input",{field:"recoverySalt",why:"order-salt"})}if(ae!==Ue)throw new f("bad-input",{field:"recoverySalt",why:"order-salt"});let Je=Er({mnemonic:ve.mnemonic,chainId:Xt,factory:m.order.factory,salt:ae});W={storage:re,key:ve,salt:ae,derivation:"salt-v2",newKey:!ce||ce.backupConfirmed!==!0},B=sf(m.order,{spendHalf:Je.spendHalf,viewHalf:Je.viewHalf}).side,P={half:Je.makerViewHalf,point:Je.makerViewPoint}}if(P){let re=m.counterparty&&typeof m.counterparty=="object"?m.counterparty:null,ie=tf(re);if(ie.half===null)throw new f("quote-field-unbound",{step:"viewHalfClaimer",field:"viewHalfClaimer"});let ce=!1;try{ce=BigInt(ie.half)===BigInt(P.half)}catch{ce=!1}if(!ce)throw new f("quote-refused",{step:"viewHalfClaimer",why:"not-the-derived-half"});if(ie.point!==null&&String(ie.point).replace(/^0x/,"").toLowerCase()!==String(P.point).replace(/^0x/,"").toLowerCase())throw new f("quote-refused",{step:"viewHalfClaimer",why:"point-mismatch"})}let G=null;try{G=await D(m)}catch(re){throw re&&typeof re.code=="string"?re:new f("storage-unavailable",{step:"create-record"})}if(!G||!G.swap)throw new f("bad-input",{field:"record"});let z=G,ee=null;if(!z.swapWallet){let re=await Eb({order:m.order,side:G.side||null,counterparty:m.counterparty||null,standIn:r!=="live",network:z.swap.moneroNetwork||o||null}),ie=z.swap.escrow&&typeof z.swap.escrow=="object"?z.swap.escrow:{};z.swap.escrow={...ie,half:re.wallet.spendHalf,viewHalf:re.wallet.viewHalf,edPointLocker:re.own.spendPoint,edViewPointLocker:re.own.viewPoint,edPointClaimer:re.wallet.otherSpendPoint,counterViewPoint:re.wallet.otherViewPoint,counterViewHalf:re.wallet.otherViewHalf,moneroAddress:re.wallet.address,moneroSpendPub:re.wallet.spendPub,moneroViewPub:re.wallet.viewPub,moneroNetwork:re.wallet.network,standIn:re.counterparty.standIn,providerId:re.counterparty.providerId,orderContext:re.context};try{me.saveSwap(z.swap,c)}catch{throw new f("storage-unavailable",{step:"save-swap"})}if(z={...z,swapWallet:me.halvesWalletOf(z.swap)},!z.swapWallet)throw new f("bad-input",{field:"swapWallet"});ee=re}let Q=await H(m,z.swap.moneroNetwork||o||null);z.swap.restoreHeight=Q,z.restoreHeight=Q,z.swap.escrow={...z.swap.escrow||{},moneroRestoreHeight:Q};try{me.saveSwap(z.swap,c)}catch{throw new f("storage-unavailable",{step:"save-restore-height"})}let A=null;if(W.newKey){if(typeof m.onRecoveryKey!="function")throw new f("bad-input",{field:"onRecoveryKey"});try{A={name:Qd(W.key),contents:await Zd({mnemonic:W.key.mnemonic,createdAt:W.key.createdAt,passphrase:U})}}catch{throw new f("recovery-failed",{step:"encrypt-key"})}if(await m.onRecoveryKey(A)!==!0)throw new f("recovery-declined",{key:W.key.fingerprint});try{Hi(W.storage,{...W.key,backupConfirmed:!0}),W.key={...W.key,backupConfirmed:!0}}catch{throw new f("storage-unavailable",{step:"save-recovery-key"})}}let j=m.wallet;if(!j||typeof j.send!="function"||typeof j.receipt!="function")throw new f("bad-input",{field:"wallet",missing:["send","receipt"],surface:"swaps.start",step:"lock"});if(d){let re=typeof j.address=="function"?await j.address():null;if(typeof re!="string"||!re)throw new f("bad-input",{field:"wallet",missing:["address"],surface:"swaps.start",step:"lock"});if(d.has(re.toLowerCase()))throw new f("address-denied",{step:"lock"})}let K=ee?{commitHalfLocker:ee.wallet.commitHalfLocker,commitHalfClaimer:ee.wallet.commitHalfClaimer,edPointLocker:ee.own.spendPoint,edPointClaimer:ee.wallet.otherSpendPoint,edViewPointLocker:ee.own.viewPoint}:{},Z={...m.order,...K,amountWei:m.order.amount};if(m.orderQuote&&(ee||m.counterparty)){let re=ve=>String(ve??"").replace(/^0x/i,"").toLowerCase(),ie=ee?ee.wallet.commitHalfClaimer:m.counterparty.commitHalfClaimer||null,ce=ee?ee.wallet.otherSpendPoint:m.counterparty.edPointClaimer||m.counterparty.edPub||null;if(!ie||!ce||re(m.orderQuote.commitHalfClaimer)!==re(ie)||re(m.orderQuote.edPointClaimer)!==re(ce))throw new f("quote-refused",{step:"quote-binding",why:"counterparty-half"})}let Y=m.orderQuote&&m.orderQuote.validUntil!==void 0?m.orderQuote.validUntil:void 0;if(Y!=null){let re=Number(Y),ie=typeof s=="function"?Number(s()):Date.now(),ce=Math.floor(ie/1e3);if(!Number.isSafeInteger(re)||!Number.isSafeInteger(ce)||re<=ce+30)throw new f("quote-expired",{validUntil:Number.isFinite(re)?re:null,now:Number.isFinite(ce)?ce:null,marginSec:30,step:"lock"})}Z.quote=m.orderQuote||null;let ne=async({escrow:re,salt:ie})=>{if(!re||!/^0x[0-9a-fA-F]{40}$/.test(String(re)))return;let ce=z.swap.escrow&&typeof z.swap.escrow=="object"?z.swap.escrow:{};z.swap.fundingPending=!0,z.swap.escrow={...ce,address:re,salt:ie||ce.salt||null,fundingPending:!0,fundingReason:"not-sent"};try{me.saveSwap(z.swap,c)}catch{throw new f("storage-unavailable",{step:"save-pending"})}},oe=null;try{oe=await Vg(Z,j,{call:w,onPredicted:ne})}catch(re){if(z.swap.escrow&&z.swap.escrow.fundingReason==="not-sent"){delete z.swap.fundingPending,z.swap.escrow={...z.swap.escrow,fundingPending:!1,fundingReason:"send-rejected"};try{me.saveSwap(z.swap,c)}catch{}}throw re&&typeof re.code=="string"?re:new f("server-unavailable",{step:"lock"})}if(oe&&oe.pending){let re=oe.createHash||null,ie=oe.predictedEscrow||null,ce=z.swap.escrow&&typeof z.swap.escrow=="object"?z.swap.escrow:{};z.swap.fundingPending=!0,z.swap.escrow={...ce,address:ie||ce.address||null,fundTx:re||ce.fundTx||null,fundingPending:!0,fundingReason:oe.pendingReason||"no-receipt"};try{me.saveSwap(z.swap,c)}catch{throw new f("storage-unavailable",{step:"save-pending"})}return{id:z.swap.id||null,escrow:z.swap.escrow.address||null,address:z.swapWallet&&z.swapWallet.address||null,step:"funding-pending",txHash:re,reason:oe.pendingReason||"no-receipt",predictedEscrow:ie,next:"receipt"}}let pe=oe&&oe.escrow||null;if(pe){let re=z.swap.escrow&&typeof z.swap.escrow=="object"?z.swap.escrow:{};z.swap.escrow={...re,address:pe,evmBirthBlock:Number(oe.birthBlock)>0?Number(oe.birthBlock):re.evmBirthBlock??re.birthHeight??null};try{me.saveSwap(z.swap,c)}catch{throw new f("storage-unavailable",{step:"save-escrow"})}}let ke=null,we=null;return l&&l.apiBase&&(ke=await T(z.swap,pe,m.order),we=await N(z.swap,m.order)),{id:z.swap.id||null,escrow:pe,address:we&&we.address||z.swapWallet&&z.swapWallet.address||null,step:"xmr-incoming",server:ke,watch:we,next:"watch"}},async watch(m){if(!m||typeof m!="object")throw new f("bad-input",{field:"request"});let g=typeof m.id=="string"&&m.id?m.id:null;if(!g)throw new f("bad-input",{field:"id"});let E=m.expect!==void 0&&m.expect!==null,C=m.wallet!==void 0&&m.wallet!==null;if(E!==C)throw new f("bad-input",{field:E?"wallet":"expect"});if(E&&!(m.escrow||m.address))throw new f("bad-input",{field:"escrow"});let M=Number.isFinite(Number(m.pollMs))&&Number(m.pollMs)>0?Number(m.pollMs):v("watchPollMs",5e3),$=Number.isFinite(Number(m.timeoutMs))&&Number(m.timeoutMs)>0?Number(m.timeoutMs):v("watchTimeoutMs",12e5),L=Number.isFinite(Number(m.minConfirmations))&&Number(m.minConfirmations)>0?Math.trunc(Number(m.minConfirmations)):v("xmrConfirmations",10),F=m.verify&&typeof m.verify=="object"?{...m.verify,nodes:Array.isArray(m.verify.nodes)?m.verify.nodes:l&&typeof l.nodesFor=="function"?l.nodesFor(m.verify.network||m.network||o):[],minConfirmations:L}:null;if(F){let A=m.readyBySec!==void 0&&m.readyBySec!==null?Number(m.readyBySec):m.deadline&&m.deadline.readyBy!==void 0?Number(m.deadline.readyBy):null;A&&zf({readyBySec:A,nowSec:Math.floor(Date.now()/1e3),minConfirmations:L,blockTimeSec:v("xmrBlockTimeSec",120)})}let B=!!(l&&l.apiBase);if(!F&&!B)throw new f("bad-input",{field:"verify",why:"no-backend"});let P=Date.now(),D=null;try{D=me.getSwap(g,c)}catch{D=null}let U=m.escrow||D&&D.escrow&&D.escrow.address||null,q=Ac(D&&D.escrow?D.escrow.evmBirthBlock??D.escrow.birthHeight:null),W={checked:!1,error:null,logs:void 0},G=async()=>{if(W.checked=!1,W.error=null,W.logs=void 0,!U){W.error="no-escrow";return}try{W.logs=await k({address:U,topics:[Ro],fromBlock:q,toBlock:"latest"}),W.checked=!0}catch(A){W.error=A&&A.code||"logs-unread"}},z=(A,j)=>{if(!(!A||A.settlement)){A.settlement={kind:Sn,phase:Sn,at:j};try{me.saveSwap(A,c)}catch{throw new f("storage-unavailable",{step:"decline"})}}},ee=({source:A,at:j,waitedMs:K,address:Z,chainChecked:Y,chainError:ne})=>({id:g,escrow:U,address:Z||null,seen:!1,declined:!0,terminal:Sn,code:Sc,source:A,at:j,waitedMs:K,chain:{checked:!!Y,error:ne||null}});if(D&&D.settlement&&D.settlement.kind===Sn){let A=Number(D.settlement.at);return ee({source:"record",at:Number.isFinite(A)?A:Date.now(),waitedMs:0,address:null,chainChecked:!1,chainError:null})}let Q=null;for(;;){await G();let A=F?{}:await V(g);Q=F?{address:m.address||U,expectedXmr:m.expectedXmr??null,status:null}:Qg(A);let j=Cg({logs:W.logs,escrow:U,at:Date.now()});if(j.declined)return z(D,j.at),ee({source:j.source,at:j.at,waitedMs:Date.now()-P,address:A&&A.address,chainChecked:W.checked,chainError:W.error});if(!Q)throw new f("server-unavailable",{step:"watch",why:"bad-response",id:g});if(Q.locked){let K=Q.lockedUntil||{};throw new f("xmr-locked",{id:g,address:Q.address,status:Q.status,expectedXmr:Q.expectedXmr,receivedXmr:Q.receivedXmr,lockedXmr:Q.lockedXmr,untilHeight:K.untilHeight??null,untilTime:K.untilTime??null,waitedMs:Date.now()-P})}if(F){let K=await Ic({...F,nowSec:Math.floor(Date.now()/1e3)});if(Q.verify=K,!K.seen){if(Date.now()-P>=$)throw new f("xmr-timeout",{id:g,address:Q.address,expectedXmr:Q.expectedXmr,state:K.state,confirmations:K.confirmations??0,waitedMs:Date.now()-P,timeoutMs:$,pollMs:M});await new Promise(Y=>setTimeout(Y,M));continue}let Z={seen:!0,id:g,address:Q.address,status:Q.status,expectedXmr:Q.expectedXmr,receivedXmr:Number(K.amountAtomic)/1e12,confirmations:K.confirmations,txids:[K.txid],at:Date.now(),verified:{height:K.height,blockHash:K.blockHash,operators:K.operators,agreedBy:K.agreedBy},source:"client"};return E&&C?Z.marked=await x.markReady({escrow:m.escrow||Q.address,expect:m.expect,onStep:m.onStep},m.wallet):Z.next="mark-ready",Z}if(Q.seen)return{seen:!1,observed:{id:Q.id,address:Q.address,status:Q.status,expectedXmr:Q.expectedXmr,receivedXmr:Q.receivedXmr,confirmations:Q.confirmations,txids:Q.txids},id:g,address:Q.address,expectedXmr:Q.expectedXmr,next:"verify",source:"service"};if(Date.now()-P>=$)throw new f("xmr-timeout",{id:g,address:Q.address,expectedXmr:Q.expectedXmr,receivedXmr:Q.receivedXmr,confirmations:Q.confirmations,waitedMs:Date.now()-P,timeoutMs:$,pollMs:M});await new Promise(K=>setTimeout(K,M))}},async startSell(m){if(!m||typeof m!="object")throw new f("bad-input",{field:"request"});let g=m.offer&&typeof m.offer=="object"?m.offer:null;if(!g)throw new f("bad-input",{field:"offer"});let E=g.order&&typeof g.order=="object"?g.order:null,C=g.quote&&typeof g.quote=="object"?g.quote:null;if(!E||!C)throw new f("bad-input",{field:"offer",missing:["order","quote"]});if(typeof g.jointAddress!="string"||!g.jointAddress)throw new f("bad-input",{field:"offer.jointAddress"});if(typeof g.escrow!="string"||!g.escrow)throw new f("bad-input",{field:"offer.escrow"});let M=(j,K)=>String(j||"").replace(/^0x/,"").toLowerCase()===String(K||"").replace(/^0x/,"").toLowerCase();if(!M(C.locker,E.locker)||!M(C.claimer,E.claimer)||!M(C.provider,E.locker)||!M(C.factory,E.factory)||Number(C.chainId)!==Number(E.chainId))throw new f("quote-refused",{step:"sell-record",why:"terms"});let $=C.id||C.nonce||null,L=b().find(j=>j.side==="sell"&&(j.escrow&&String(j.escrow.address||"").toLowerCase()===String(g.escrow).toLowerCase()||$!==null&&String(j.orderQuoteId||"")===String($)));if(L){let j=L.quote&&typeof L.quote=="object"?L.quote:{},K=(Z,Y)=>String(Z||"").replace(/^0x/,"").toLowerCase()===String(Y||"").replace(/^0x/,"").toLowerCase();if(!K(j.commitHalfClaimer,C.commitHalfClaimer)||!K(j.edPointClaimer,C.edPointClaimer)||!K(L.escrow&&L.escrow.moneroAddress,g.jointAddress))throw new f("quote-refused",{step:"sell-record",why:"offer-changed"});return await X(L.escrow&&L.escrow.address||g.escrow,L.expect||null,m.wallet),{id:L.id,side:"sell",escrow:L.escrow&&L.escrow.address||g.escrow,address:L.escrow&&L.escrow.moneroAddress||g.jointAddress,xmrAmount:L.escrow&&L.escrow.xmrAmount||C.xmrAmount,claimTip:L.claimTip||C.claimTip,orderQuote:L.orderQuote||g.orderQuote,resumed:!0,next:"send-xmr"}}let F=c.storage(),B=typeof m.recoveryKey=="string"?m.recoveryKey:m.recoveryKey&&typeof m.recoveryKey.mnemonic=="string"?m.recoveryKey.mnemonic:null,P=Jd(F);if(P&&B&&P.mnemonic!==B)throw new f("bad-input",{field:"recoveryKey",why:"different-key"});if(!P&&!B)throw new f("bad-input",{field:"recoveryKey"});let D=P||Gd(B);if(P||Hi(F,{...D,backupConfirmed:!1}),!P||P.backupConfirmed!==!0){if(typeof m.onRecoveryKey!="function")throw new f("bad-input",{field:"onRecoveryKey"});let j=null;try{j={name:Qd(D),contents:await Zd({mnemonic:D.mnemonic,createdAt:D.createdAt,passphrase:m.passphrase})}}catch{throw new f("recovery-failed",{step:"encrypt-key"})}if(await m.onRecoveryKey(j)!==!0)throw new f("recovery-declined",{key:D.fingerprint});try{Hi(F,{...D,backupConfirmed:!0})}catch{throw new f("storage-unavailable",{step:"save-recovery-key"})}}let U=Number(E.chainId);if(!Number.isSafeInteger(U)||U<=0)throw new f("bad-input",{field:"order.chainId"});if(!E.factory||E.salt===void 0||E.salt===null)throw new f("bad-input",{field:"order"});let q=null;try{q=gn(g.recovery&&g.recovery.salt?g.recovery.salt:E.salt)}catch{throw new f("bad-input",{field:"offer.recovery"})}let W=Er({mnemonic:D.mnemonic,chainId:U,factory:E.factory,salt:q}),G=sf(E,{spendHalf:W.spendHalf,viewHalf:W.viewHalf}),z=G.commitHalf,ee=j=>String(j||"").replace(/^0x/,"").toLowerCase();if(!z||ee(z)!==ee(C.commitHalfClaimer))throw new f("quote-refused",{step:"sell-record",why:"commitment"});if(String(G.spendPoint).toLowerCase()!==String(C.edPointClaimer||"").toLowerCase())throw new f("quote-refused",{step:"sell-record",why:"spend-point"});if(g.edViewPointClaimer&&String(G.viewPoint).toLowerCase()!==String(g.edViewPointClaimer).toLowerCase())throw new f("quote-refused",{step:"sell-record",why:"view-point"});let A=Rf({side:"sell",network:String(E.chainId),moneroNetwork:o||void 0,payToken:E.asset||C.asset||void 0,payAmount:C.amount,xmrAmount:Number(C.xmrAmount)/1e12,orderQuoteId:$||void 0,receiveAddress:E.claimer,makerId:C.provider||null},{order:E,side:G.side,store:c}).swap;A.side="sell",A.order=E,A.orderQuote=g.orderQuote||null,A.quote=C,A.claimTip=C.claimTip||null,A.expect={chainId:U,factory:E.factory,locker:E.locker,claimer:E.claimer,amount:String(E.amount),readyBy:E.readyBy,t1:E.t1,salt:E.salt,commitHalfLocker:g.nodeHalf&&g.nodeHalf.commitHalf||null,edPointLocker:g.nodeHalf&&g.nodeHalf.edPoint||null,edViewPointLocker:g.edViewPointLocker||null,commitHalfClaimer:C.commitHalfClaimer||null,edPointClaimer:C.edPointClaimer||null},A.escrow={...A.escrow||{},address:g.escrow,moneroAddress:g.jointAddress,half:xn(G.side.half),viewHalf:xn(G.side.viewHalf),edPointClaimer:G.spendPoint,edViewPointClaimer:ge(G.side.viewPub),commitHalfClaimer:C.commitHalfClaimer,edPointLocker:g.nodeHalf&&g.nodeHalf.edPoint||null,edViewPointLocker:g.edViewPointLocker||null,commitHalfLocker:g.nodeHalf&&g.nodeHalf.commitHalf||null,orderContext:g.context||null,xmrAmount:C.xmrAmount||null};try{await X(g.escrow,A.expect,m.wallet)}catch(j){try{me.forgetSwap(A.id,c)}catch{}throw j}try{me.saveSwap(A,c)}catch{throw new f("storage-unavailable",{step:"save-swap"})}return{id:A.id,side:"sell",escrow:g.escrow,address:g.jointAddress,xmrAmount:C.xmrAmount,claimTip:C.claimTip||null,orderQuote:g.orderQuote||null,resumed:!1,next:"send-xmr"}},async sellClaim(m,g){if(!m||typeof m!="object")throw new f("bad-input",{field:"request"});let E=String(m.id||"").trim();if(!E)throw new f("bad-input",{field:"id"});let C=null;try{C=me.getSwap(E,c)}catch{C=null}if(!C||C.side!=="sell")throw new f("bad-input",{field:"id",why:"sell-not-found"});let M=m.escrow||C.escrow&&C.escrow.address||null,$=m.halfClaimer||C.escrow&&C.escrow.half||null;if(!M||!$)throw new f("bad-input",{field:"escrow",missing:["escrow","halfClaimer"]});let L=m.expect||C.expect||null;if(!L)throw new f("bad-input",{field:"expect",why:"not-in-record"});return x.claim({escrow:M,halfClaimer:$,claimer:C.order&&C.order.claimer,expect:L,onStep:m.onStep},g)},async sellWatch(m){if(!m||typeof m!="object")throw new f("bad-input",{field:"request"});let g=String(m.escrow||"").trim();if(!g)throw new f("bad-input",{field:"escrow"});let E=Number.isFinite(Number(m.pollMs))&&Number(m.pollMs)>0?Number(m.pollMs):v("watchPollMs",6e3),C=Number.isFinite(Number(m.timeoutMs))&&Number(m.timeoutMs)>0?Number(m.timeoutMs):v("watchTimeoutMs",12e5);if(!(Number.isFinite(Number(m.timeoutMs))&&Number(m.timeoutMs)>0))try{let P=await Pr(g,{call:w});C=h3({configuredMs:C,readyBySec:P.readyBy})}catch{}let M=null;try{M=await Pr(g,{call:w})}catch{}let $=()=>{let P=typeof s=="function"?Number(s()):Date.now();return Number.isFinite(P)?Math.floor(P/1e3):null},L=Date.now(),F=null,B=null;for(;;){try{F=await Br(g,{call:w})}catch(P){B=P&&P.code||"status-unread",F=null}if(F&&(F.isClaimed||F.isRefunded))return{escrow:g,state:F.isClaimed?"claimed":"refunded",funded:F.isFunded,claimed:F.isClaimed,refunded:F.isRefunded,ready:null,claimOpen:!1,balanceWei:String(F.balance),waitedMs:Date.now()-L};if(F&&F.isFunded){let P=null;try{let D=await w({to:g,data:Re.encodeRead("ready")}),U=String(D||"").replace(/^0x/,"");P=U.length>0&&BigInt("0x"+U)!==0n}catch(D){B=D&&D.code||"ready-unread"}if(P===!0)return{escrow:g,state:"ready",funded:!0,claimed:!1,refunded:!1,ready:!0,claimOpen:!1,balanceWei:String(F.balance),waitedMs:Date.now()-L}}if(F&&F.isFunded&&M&&Number.isSafeInteger(Number(M.readyBy))){let P=$();if(P!==null&&P>=Number(M.readyBy))return{escrow:g,state:"claim-open",funded:!0,claimed:!1,refunded:!1,ready:!1,claimOpen:!0,balanceWei:String(F.balance),waitedMs:Date.now()-L}}if(Date.now()-L>=C)throw new f("sell-timeout",{escrow:g,waitedMs:Date.now()-L,timeoutMs:C,status:F,error:B});await new Promise(P=>setTimeout(P,E))}}}}xe();$e();xe();var m3=2,w3=10,Fo=(e,t)=>{try{return BigInt(e)}catch{throw new f("bad-input",{field:t})}},y3=e=>{if(!e||typeof e.driver!="function")throw new f("bad-input",{field:"wallet.driver"});let t=e.driver();if(!t||typeof t!="object")throw new f("bad-input",{field:"wallet.driver"});let n=["setRestoreHeight","getBalance"].filter(r=>typeof t[r]!="function");if(n.length)throw new f("bad-input",{field:"wallet.driver",missing:n});return t},zt=async(e,t)=>{try{return await t()}catch(n){throw n instanceof f?n:new f("wallet-rejected",{surface:e,why:String(n&&n.message||n)})}},tx=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}},nx=async(e,{syncError:t=null,rescanError:n=null,spentChecked:r=!0}={})=>{let o=await tx(e,"getHeight"),i=await tx(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 b3({nodeUrl:e,fromHeight:t,toHeight:n,fetchImpl:r=globalThis.fetch,sleep:o=g3,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 f("bad-input",{field:"window.nodeUrl"});if(!Number.isSafeInteger(a)||a<0)throw new f("bad-input",{field:"window.fromHeight"});if(!Number.isSafeInteger(c)||c<a)throw new f("bad-input",{field:"window.toHeight"});if(typeof r!="function")throw new f("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,h=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,h=new f("wallet-rejected",{surface:"window-blocks",height:d,why:"transport"}),x<l){await o(rx(x));continue}throw h}if(p&&p.ok===!0){h=null;break}let _=p?p.status:null;if(h=new f("wallet-rejected",{surface:"window-blocks",height:d,status:_}),(_===429||_!==null&&_>=500)&&x<l){await o(x3(p)??rx(x));continue}throw h}if(!p||p.ok!==!0)throw h||new f("wallet-rejected",{surface:"window-blocks",height:d});let w=null;try{w=await p.json()}catch{throw new f("wallet-rejected",{surface:"window-blocks",height:d,why:"not-json"})}if(!w||w.error||!w.result)throw new f("wallet-rejected",{surface:"window-blocks",height:d,why:"rpc"});let y=w.result,k=Array.isArray(y.tx_hashes)?y.tx_hashes:null;if(!k&&typeof y.json=="string")try{let x=JSON.parse(y.json);k=Array.isArray(x.tx_hashes)?x.tx_hashes:null}catch{k=null}if(!k)throw new f("wallet-rejected",{surface:"window-blocks",height:d,why:"no-tx-hashes"});u.push(...k.map(String))}return u}var g3=e=>new Promise(t=>setTimeout(t,e)),rx=e=>Math.min(4e3,250*2**Math.max(0,e-1));function x3(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 ox(e={}){let t=e.wallet;if(!t||typeof t!="object")throw new f("bad-input",{field:"wallet"});let n=["sync","unlockedBalance"].filter(v=>typeof t[v]!="function");if(n.length)throw new f("bad-input",{field:"wallet",missing:n});let r=Number(e.fromHeight);if(!Number.isFinite(r)||r<=0)throw new f("bad-input",{field:"restoreHeight"});let o=Number.isFinite(Number(e.scanBack))&&Number(e.scanBack)>=0?Math.floor(Number(e.scanBack)):w3,i=Math.max(0,Math.floor(r)-o),s=y3(t),a=e.window&&typeof e.window=="object"?e.window:null,c=null,l=0n,u=0n;if(a){let v=Number(a.tipHeight);if(!Number.isSafeInteger(v)||v<=0)throw new f("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 H=Array.isArray(a.txHashes)?a.txHashes.map(String):null;if(H===null)try{H=await b3({nodeUrl:a.nodeUrl,fromHeight:r,toHeight:a.toHeight,fetchImpl:e.fetchImpl})}catch(b){if(b&&b.code==="bad-input")throw b;c.fallback=!0,c.fallbackWhy="window-read",c.error={code:b&&b.code?b.code:"wallet-rejected",surface:b&&b.params&&b.params.surface?b.params.surface:"window-blocks",status:b&&b.params&&b.params.status!==void 0?b.params.status:null,height:b&&b.params&&b.params.height!==void 0?b.params.height:null,why:b&&b.params&&b.params.why?b.params.why:null},H=[]}if(c.txs=H.length,H.length&&typeof s.scanTxs=="function"){let b=null;try{await zt("setRestoreHeight",()=>s.setRestoreHeight(v)),await zt("scanTxs",()=>s.scanTxs(H));try{await t.sync()}catch(I){b=I}l=Fo(await zt("getBalance",()=>s.getBalance()),"balance"),u=Fo(await zt("unlockedBalance",()=>t.unlockedBalance()),"unlockedBalance"),c.used=!0}catch(I){if(I&&I.code==="bad-input")throw I;l=0n,u=0n,c.fallback=!0,c.fallbackWhy="window-scan",c.error={code:I&&I.code?I.code:"wallet-rejected",surface:I&&I.params&&I.params.surface?I.params.surface:"scanTxs",status:null,height:null,why:I&&I.params&&I.params.why?I.params.why:null}}if(c.used&&a.nodeUrl&&a.trustedNode===!0&&typeof s.getKeyImages=="function")try{let I=await s.getKeyImages(),S=(Array.isArray(I)?I:I&&typeof I.getKeyImages=="function"?I.getKeyImages():[]).map(T=>typeof T=="string"?T:T&&typeof T.getHex=="function"?T.getHex():T&&T.hex).filter(Boolean);if(S.length){let T=String(a.nodeUrl);for(;T.endsWith("/");)T=T.slice(0,-1);let N=await(e.fetchImpl||globalThis.fetch)(T+"/is_key_image_spent",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({key_images:S}),signal:typeof AbortSignal<"u"&&AbortSignal.timeout?AbortSignal.timeout(8e3):void 0}),V=N&&N.ok===!0?await N.json():null;V&&Array.isArray(V.spent_status)?(c.spent=V.spent_status.filter(X=>X===!0||X===1).length,c.keyImages=S.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 I=await nx(s,{syncError:b,spentChecked:c.spent!==null&&c.spent!==void 0});return{total:l.toString(),unlocked:u.toString(),scanHeight:i,...I,passes:1,lockedPass:!1,window:c}}}else H.length&&(c.skipped="no-scan-txs")}if(c&&(c.fallback=!0,c.fallbackWhy||(c.fallbackWhy="empty-window")),await zt("setRestoreHeight",()=>s.setRestoreHeight(i)),typeof s.rescanBlockchain!="function")throw new f("bad-input",{field:"wallet.driver.rescanBlockchain"});let d=null;try{await zt("rescanBlockchain",()=>s.rescanBlockchain())}catch(v){d=v}let p=null;try{await t.sync()}catch(v){p=v}let h=Fo(await zt("getBalance",()=>s.getBalance()),"balance"),w=Fo(await zt("unlockedBalance",()=>t.unlockedBalance()),"unlockedBalance"),y=1,k=!1;if(e.rescanWhenLocked!==!1&&h>0n&&w===0n&&typeof s.rescanSpent=="function"&&y<m3){k=!0,await zt("rescanSpent",()=>s.rescanSpent());try{await t.sync()}catch(v){p=v}h=Fo(await zt("getBalance",()=>s.getBalance()),"balance"),w=Fo(await zt("unlockedBalance",()=>t.unlockedBalance()),"unlockedBalance"),y+=1}let _=await nx(s,{syncError:p,rescanError:d});return{total:h.toString(),unlocked:w.toString(),scanHeight:i,..._,passes:y,lockedPass:k,window:c}}xe();function ix(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 Do="monero",k3="ninsei-wallet-session",v3=["mainnet","stagenet","testnet","fakechain"],S3=()=>{let e=ue.XMR_NETWORKS||{};return[...new Set([...Object.values(e).filter(t=>typeof t=="string"&&t),...v3])].sort()};function sx({createWallet:e=null,network:t=null,serverUri:n=null,password:r=k3,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 f("wallet-not-connected",{vm:Do,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 f("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 f("bad-input",{field:"keys",missing:["seed","privateSpendKey"]})},h=async()=>{if(a===null)return;let w=a;a=null,c=null;try{await w.close()}catch{}};return{vm:Do,id:Do,async connect(){if(typeof e!="function")throw new f("bad-input",{field:"createWallet"});let w=S3();if(typeof t!="string"||!t)throw new f("bad-input",{field:"network",known:w});if(w.length&&!w.includes(t))throw new f("bad-input",{field:"network",known:w,got:t});if(typeof n!="string"||!n)throw new f("bad-input",{field:"serverUri"});let y=p(),k=Number(i);if(!Number.isFinite(k)||k<=0)throw new f("bad-input",{field:"restoreHeight",got:i});await h(),a=await e({networkType:t,server:{uri:n},password:r,restoreHeight:k,...y}),c=String(await a.getAddress(0,0));let _=typeof En.networkFromShape=="function"?En.networkFromShape(c):null;if(_&&_!==t)throw await h(),new f("wrong-chain",{got:_,want:t});if(s&&c!==s)throw await h(),new f("recovery-failed",{step:"address"});await a.setRestoreHeight(k),u()},async disconnect(){return await h()},async close(){return await h()},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 f("wallet-not-connected",{vm:Do,surface:"open"});let y=w&&w.address?String(w.address):null;if(y&&c!==y)throw new f("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 ix(w)},subscribe(w){if(typeof w!="function")throw new f("bad-input",{field:"handler"});return l.add(w),()=>l.delete(w)},async send(){throw new f("not-implemented",{surface:"adapter.send",vm:Do})},async receipt(){throw new f("not-implemented",{surface:"adapter.receipt",vm:Do})},driver(){return a}}}sr();var E3=e=>typeof e=="string"?e.trim():"";function A3(e){let t=e&&e.receive;return(t&&typeof t.address=="string"?t.address.trim():"")||null}async function ax(e,t){let n=E3(t),r=A3(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 Yc(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 _3=/^[0-9a-f]{64}$/;function cx(e){let t=String(e??"").trim(),n=(t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t).toLowerCase();return!_3.test(n)||/^0+$/.test(n)?null:"0x"+n}var N3=e=>{if(e==null||e==="")return null;let t=String(e);if(/^\d+$/.test(t))return eb(BigInt(t));let n=Number(t);return Number.isFinite(n)&&n>0?t:null},Tc=12,I3=["unlock","sync","sweep","relay"],T3=10000000000n;function B3({feeAtomic:e=null,amountAtomic:t=null,maxFeeAtomic:n=T3}={}){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 P3="0x3f267bb6",Yf=e=>typeof e=="string"?e:e&&typeof e.contents=="string"?e.contents:null,Mo=e=>String(e??"").replace(/^0x/i,"").toLowerCase(),O3=async e=>{let t=e&&e.order;if(!t||typeof t!="object")throw new f("bad-input",{field:"order"});if(typeof e.mnemonic!="string"||!e.mnemonic.trim())throw new f("bad-input",{field:"mnemonic"});let n=Number(e.chainId);if(!Number.isSafeInteger(n)||n<=0)throw new f("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 f("bad-input",{field:"network"});if(!o)throw new f("bad-input",{field:"moneroNetwork"});let i=typeof e.passphrase=="string"?e.passphrase:"";if(i&&i.length<Tc)throw new f("bad-input",{field:"passphrase",min:Tc});let s=t.side==="locker"?"buy":t.side==="claimer"?"sell":null;if(!s)throw new f("bad-input",{field:"order.side"});if(typeof t.factory!="string"||!/^0x[0-9a-fA-F]{40}$/.test(t.factory))throw new f("bad-input",{field:"order.factory"});let a=Er({mnemonic:e.mnemonic,chainId:n,factory:t.factory,salt:t.salt}),c=s==="buy";if(Mo(c?t.edPointLocker:t.edPointClaimer)!==Mo(a.spendPoint))throw new f("bad-input",{field:"order",why:"spend-point"});if(Mo(t.edViewPointLocker)!==Mo(c?a.viewPoint:a.makerViewPoint))throw new f("bad-input",{field:"order",why:c?"own-view-point":"maker-view-point"});let l="0x"+Mo(c?t.edPointClaimer:t.edPointLocker),u="0x"+Mo(a.makerViewPoint),d=go({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}})(),h={address:t.escrow,readyBy:t.readyBy,t1:t.t1,...p?{expectedAtomic:p}:{}},w=yt.buildPayload({swap:{id:t.escrow,side:s,network:r,moneroNetwork:o,createdAt:t.blockTime?Number(t.blockTime)*1e3:null,payToken:null,payAmount:null,xmrAmount:N3(t.xmrAmount),rate:null,maker:null,quoteSignature:null,escrow:h,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:h,receiveAddress:null,restoreHeight:Number(t.startHeight)>0?Number(t.startHeight):null});return{payload:w,contents:await yt.createRecoveryFile(w,i),address:d.address}},lx=async(e,t)=>{try{return await t()}catch(n){throw n instanceof f?n:new f("wallet-rejected",{surface:e,why:String(n&&n.message||n)})}},C3=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 ux({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 O3(a)},wallet(a={}){let c=a.moneroTs;if(!c||typeof c!="object")throw new f("bad-input",{field:"moneroTs"});if(typeof c.createWalletFull!="function")throw new f("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 f("bad-input",{field:"network",known:Object.keys(i),got:a.network});if(typeof a.serverUri!="string"||!a.serverUri)throw new f("bad-input",{field:"serverUri"});return sx({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=Yf(a.file);if(!c)throw new f("bad-input",{field:"file"});if(typeof a.passphrase!="string")throw new f("bad-input",{field:"passphrase"});if(typeof a.dest!="string"||!a.dest.trim())throw new f("bad-input",{field:"dest"});let l=null;try{l=await yt.decryptFile(JSON.parse(c),a.passphrase)}catch{throw new f("recovery-failed",{step:"decrypt"})}try{yt.validatePayload(l)}catch{throw new f("recovery-failed",{step:"validate"})}return ax(l,a.dest)},async plan(a){if(!a||typeof a!="object")throw new f("bad-input",{field:"request"});let c=Yf(a.file);if(!c)throw new f("bad-input",{field:"file"});if(typeof a.passphrase!="string"||a.passphrase.length>0&&a.passphrase.length<Tc)throw new f("bad-input",{field:"passphrase",min:Tc});let l=null;try{l=JSON.parse(c)}catch{throw new f("recovery-failed",{step:"parse"})}let u=null;try{u=await yt.decryptFile(l,a.passphrase)}catch{throw new f("recovery-failed",{step:"decrypt"})}try{yt.validatePayload(u)}catch{throw new f("recovery-failed",{step:"validate"})}let d=u.moneroWallet||{},p=d.address||null;if(!p)throw new f("recovery-failed",{step:"address"});let h=[],w=!!d.spendHalf;w||h.push("spendable");let y=Number(d.restoreHeight)||0;y>0||h.push("restore-height");let k=!1,x=null,_=d.escrowAddress||u.escrow&&u.escrow.address||null;if(_&&typeof n=="function")try{let v=String(await n({to:_,data:P3})||""),H=cx(v);H!==null&&(k=!0,x=H)}catch{k=!1}return k||h.push("revealed-half"),{swapId:u.swapId||null,address:p,spendable:w,restoreHeight:y,steps:I3,revealedHalf:k,half:x,missing:h}},async keys(a){let c=await s.plan(a);if(!c.half)throw new f("bad-input",{field:"revealedHalf",why:"not-revealed"});let l=Yf(a.file),u=null;try{u=await yt.decryptFile(JSON.parse(l),a.passphrase)}catch{throw new f("recovery-failed",{step:"decrypt"})}let d=u.moneroWallet||{},h=["spendHalf","viewHalf","otherSpendPoint","otherViewHalf"].filter(w=>d[w]===void 0||d[w]===null||d[w]==="");if(h.length)throw new f("bad-input",{field:"payload",missing:h});try{let w=mn.createHalves(hn),y=Pa.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 f("bad-input",{field:"revealedHalf",step:"verify"})}},async restore(a){return await ox(a||{})},async sign(a){let c=await s.plan(a);if(!a||typeof a.to!="string"||!a.to)throw new f("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 f("bad-input",{field:"connectWallet"})})(),d=["open","sync","unlockedBalance","sweepUnlocked","relay","close"].filter(p=>!l||typeof l[p]!="function");if(d.length)throw new f("bad-input",{field:"wallet",missing:d});await l.open(c);try{try{await l.sync()}catch{}let p=BigInt(await lx("unlockedBalance",()=>l.unlockedBalance()));if(p<=0n)throw new f("insufficient-funds",{unlocked:p.toString()});let h=await lx("sweepUnlocked",()=>l.sweepUnlocked({address:a.to,relay:!1})),w=await C3(l,h),y=w===null?null:BigInt(w),k=B3({feeAtomic:w,amountAtomic:p,...a.maxFeeAtomic===void 0||a.maxFeeAtomic===null?{}:{maxFeeAtomic:a.maxFeeAtomic}});if(!k.ok)throw new f(k.code,{fee:k.fee,limit:k.limit,amount:k.amount,why:k.why});let x="sweep-"+ ++o;return r.set(x,{wallet:l,plan:c,signed:h}),{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 f("bad-input",{field:"token"});let c=r.get(a.token);if(!c)throw new f("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}xe();var R3=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)&&R("bad-input",{field:"settlement.chain"}),n.vm!==void 0&&(typeof n.vm!="string"||!n.vm)&&R("bad-input",{field:"settlement.vm"}),(typeof t.xmrNetwork!="string"||!t.xmrNetwork)&&R("bad-input",{field:"xmrNetwork"});let r=t.mode===void 0?"live":t.mode;if(r!=="live"&&r!=="sim"&&R("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"||R("bad-input",{field:"storage"})}if(t.fetch!==void 0&&typeof t.fetch!="function"&&R("bad-input",{field:"fetch"}),t.now!==void 0&&typeof t.now!="function"&&R("bad-input",{field:"now"}),t.routing!==void 0){let o=t.routing;(!o||typeof o!="object"||o.prefer!==void 0&&!Array.isArray(o.prefer))&&R("bad-input",{field:"routing"})}if(t.routes!==void 0&&(!t.routes||typeof t.routes!="object"||Array.isArray(t.routes))&&R("bad-input",{field:"routes"}),t.endpoints!==void 0&&(!t.endpoints||typeof t.endpoints!="object"||Array.isArray(t.endpoints))&&R("bad-input",{field:"endpoints"}),t.nodes!==void 0&&!Array.isArray(t.nodes)&&(!t.nodes||typeof t.nodes!="object")&&R("bad-input",{field:"nodes"}),t.addNodes!==void 0&&!Array.isArray(t.addNodes)&&R("bad-input",{field:"addNodes"}),t.evmCall!==void 0&&typeof t.evmCall!="function"&&R("bad-input",{field:"evmCall"}),t.evmCode!==void 0&&typeof t.evmCode!="function"&&R("bad-input",{field:"evmCode"}),t.evmLogs!==void 0&&typeof t.evmLogs!="function"&&R("bad-input",{field:"evmLogs"}),t.evmBlock!==void 0&&typeof t.evmBlock!="function"&&R("bad-input",{field:"evmBlock"}),t.allowedProviders!==void 0&&t.allowedProviders!==null){let o=t.allowedProviders;!Array.isArray(o)&&typeof o!="function"&&R("bad-input",{field:"allowedProviders"})}if(t.knownFactoryCodes!==void 0&&t.knownFactoryCodes!==null&&!Array.isArray(t.knownFactoryCodes)&&R("bad-input",{field:"knownFactoryCodes"}),t.knownImplementationCodes!==void 0&&t.knownImplementationCodes!==null&&!Array.isArray(t.knownImplementationCodes)&&R("bad-input",{field:"knownImplementationCodes"}),t.denylist!==void 0&&t.denylist!==null&&(!Array.isArray(t.denylist)||t.denylist.some(o=>typeof o!="string"))&&R("bad-input",{field:"denylist"}),t.serverAuth!==void 0&&typeof t.serverAuth!="function"&&R("bad-input",{field:"serverAuth"}),t.createRecord!==void 0&&typeof t.createRecord!="function"&&R("bad-input",{field:"createRecord"}),t.watch!==void 0){let o=t.watch;(!o||typeof o!="object"||Array.isArray(o))&&R("bad-input",{field:"watch"});for(let i of["pollMs","timeoutMs"])o[i]!==void 0&&!(Number.isFinite(Number(o[i]))&&Number(o[i])>0)&&R("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 H3(e){let t=R3(e),n=Q0({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=Z0({chain:n.settlement.chain,knownFactoryCodes:t.knownFactoryCodes}),o=J0({chain:n.settlement.chain,knownImplementationCodes:t.knownImplementationCodes}),i=yo(n.settlement.vm),s=Bg({settlement:n.settlement.chain,leg:i}),a=_g({config:{...n,evmNetwork:n.settlement.chain},wallet:s,limits:n.limits}),c=t.mode==="sim"?Ig():null,l=hr.createStore(t.storage||hr.storage()),u=ht({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 v=>x(v)===!0;let _=new Set(x.map(v=>String(v).toLowerCase()));return v=>_.has(String(v).toLowerCase())})(),p=Array.isArray(t.denylist)&&t.denylist.length?new Set(t.denylist.map(x=>String(x).toLowerCase())):null,h=Pf({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=ss({call:t.evmCall}),y=typeof t.evmCall=="function"?{call:t.evmCall}:{},k=typeof t.evmLogs=="function"?{logs:t.evmLogs}:{};return Object.freeze({config:n,wallet:s,preflight:a,recovery:Of({http:u,config:n}),actions:w,order:{context:x=>Ut(x),verifyCounterparty:x=>kb(x),jointAddress:x=>go(x),escrowNativeWei:x=>Re.escrowNativeWei(x),status:x=>Br(x,y),deadlines:x=>Pr(x,y),decline:(x,_={})=>Mg(x,{...k,..._||{}})},sim:c,quotes:{watch:(x,_)=>h.watch(x,_),snapshot:()=>h.snapshot(),firm:x=>h.firm(x),firmRelay:x=>h.firmRelay(x),sale:x=>h.sale(x)},swaps:Xf({preflight:a,http:u,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,auth:t.serverAuth,denylist:p,watch:t.watch,createRecord:t.createRecord}),sweep:ux({http:u,config:n,call:t.evmCall})})}xe();var Gf=e=>typeof e=="string"&&/^0x[0-9a-f]+$/i.test(e)?Number.parseInt(e,16):null,qf=/^0x[0-9a-fA-F]{40}$/,dx=e=>"0x"+Number(e).toString(16),L3=4902,F3=e=>(e&&(e.code||e.data&&e.data.originalError&&e.data.originalError.code))===L3||/unrecognized chain|not added/i.test(String(e&&e.message||"")),fx=e=>e&&e.code===4001||/rejected|denied/i.test(String(e&&e.message||""));function D3(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)&&Gf(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"&&qf.test(o)?o:null},async chainId(){return Gf(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=dx(o);try{await e.request({method:"wallet_switchEthereumChain",params:[{chainId:i}]})}catch(s){if(!F3(s))throw new f(fx(s)?"wallet-rejected":"wrong-chain",{vm:"evm"});let a=typeof ue.chainByChainId=="function"?ue.chainByChainId(o):null;if(!a)throw new f("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 f(fx(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 f("bad-input",{field:"send.to"});let l=y=>"0x"+BigInt(y).toString(16),u=Gf(await e.request({method:"eth_chainId"}).catch(()=>null));if(!Number.isSafeInteger(u)||u<=0)throw new f("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 f("wrong-chain",{vm:"evm",step:"send",want:d,got:u});let p=await e.request({method:"eth_accounts"}),h=Array.isArray(p)?p[0]:null;if(typeof h!="string"||!qf.test(h))throw new f("wallet-not-connected",{step:"send"});if(c!=null){let y=String(c).toLowerCase();if(!qf.test(y))throw new f("bad-input",{field:"send.from"});if(h.toLowerCase()!==y)throw new f("wrong-account",{vm:"evm",step:"send",want:y,got:h})}let w={from:h,to:r,data:o,value:l(i),chainId:dx(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 f("bad-input",{field:"receipt.txHash"});return await e.request({method:"eth_getTransactionReceipt",params:[r]})},async signTypedData(r){if(!r||typeof r!="object")throw new f("bad-input",{field:"signTypedData"});let o=await e.request({method:"eth_accounts"}),i=Array.isArray(o)?o[0]:null;if(!i)throw new f("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 f("wallet-rejected",{step:"signTypedData",why:"bad-signature-shape"});return s},driver(){return e}}}function M3(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 U3(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{Fa as CHECK_CODES,so as ERROR_CODES,La as STEP_CODES,f as SdkError,ss as createActions,H3 as createNinsei,Pf as createQuotes,Of as createRecovery,Xf as createSwaps,D3 as evmWallet,M3 as localStorageAdapter,U3 as memoryAdapter};
|
|
2054
|
+
`}async function c2(e,t,n){if(!globalThis.crypto||!globalThis.crypto.subtle)throw xy("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 l2=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 _d({mnemonic:e,createdAt:t,passphrase:n=""}={}){let r=ua(e,t);if(typeof n!="string")throw xt("passphrase");if(n==="")return a2(r);if(n.length<12)throw xt("passphrase");if(!globalThis.crypto||!globalThis.crypto.subtle)throw xy("crypto-unavailable");let o=crypto.getRandomValues(new Uint8Array(16)),i=crypto.getRandomValues(new Uint8Array(12)),s={kind:"ninsei-recovery-key",v:J1,alg:e2,iter:yy,salt:xd(o),iv:xd(i),meta:{fingerprint:r.fingerprint,createdAt:r.createdAt}},a=await c2(n,o,yy),c=await crypto.subtle.encrypt({name:"AES-GCM",iv:i,tagLength:128,additionalData:da.encode(l2(s))},a,da.encode(JSON.stringify({mnemonic:r.mnemonic})));return JSON.stringify({...s,ciphertext:xd(new Uint8Array(c))},null,2)}var si=e=>new u("storage-unavailable",{step:e}),d2=e=>{if(!e||typeof e.get!="function"||typeof e.set!="function"||typeof e.remove!="function")throw xt("storage");let t;try{t=e.get(by)}catch{throw si("read")}if(t==null||t==="")return null;let n;try{n=JSON.parse(t)}catch{throw si("parse")}if(!n||n.version!==gy||typeof n.mnemonic!="string")throw si("parse");return n},u2=(e,t)=>{let n;try{n=JSON.stringify(t)}catch{throw si("serialize")}try{e.set(by,n)}catch{throw si("write")}};function ai(e,t){let n=ua(t&&t.mnemonic,t&&t.createdAt);return u2(e,{...n,backupConfirmed:t.backupConfirmed===!0}),n}function Id(e){let t=d2(e);return t?{...t,fingerprint:t.fingerprint||Ad(t.mnemonic)}:null}var f2=18,p2=45,nT=p2+f2*32;var Sd=e=>"0x"+Array.from(te(new TextEncoder().encode(e)),t=>t.toString(16).padStart(2,"0")).join(""),vd=Object.freeze({halfRevealed:Sd("HalfRevealed(bytes32,bool)"),ready:Sd("Ready(address)"),declined:Sd("Declined(address)")}),rT=new Map([[vd.halfRevealed,"HalfRevealed"],[vd.ready,"Ready"],[vd.declined,"Declined"]]);me();_e();var et=()=>Ns.createOrderBuilder(Xt);function Tt(e){if(!e||typeof e!="object")throw new u("bad-input",{field:"order"});try{return xn.orderContextString(e)}catch{throw new u("bad-input",{field:"order"})}}function Ny({side:e,order:t,sealed:n=null,ownEncPriv:r=null}){if(!e||typeof e!="object")throw new u("bad-input",{field:"side"});let o=Tt(t),i=null;try{i=et().verifySide(e,o,n,r)}catch{throw new u("bad-input",{field:"side"})}if(!i||i.ok!==!0)throw new u("quote-refused",{step:"proof",why:i&&i.reason?"rejected":"unknown"});return e}function eo({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 u("bad-input",{field:"jointAddress",missing:s});try{return et().jointAddress({ownSpendHalf:e,ownViewHalf:t,otherSpendPoint:n,otherViewPoint:r,network:o})}catch{throw new u("bad-input",{field:"jointAddress"})}}var be=e=>"0x"+String(e).replace(/^0x/i,"").toLowerCase(),Jt=e=>"0x"+BigInt(e).toString(16).padStart(64,"0"),Td=e=>/^0x[0-9a-f]{64}$/.test(String(e)),Ay=e=>e&&typeof e=="object"&&e.XB?{...e,XB:be(e.XB)}:e,fa=e=>typeof e=="string"&&e?be(e):e;function Bd(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 u("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 u("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=fa(o[0]),!Td(i))throw new u("bad-input",{field:"counterparty",why:"view-point"});for(let s of o.slice(1))if(fa(s)!==i)throw new u("bad-input",{field:"counterparty",why:"conflicting-view-point"})}if(r!==null){let s=null;try{s=fa(et().pointOf(r))}catch{s=null}if(!s)throw new u("bad-input",{field:"counterparty",why:"view-half"});if(i!==null&&i!==s)throw new u("bad-input",{field:"counterparty",why:"view-half-point-mismatch"});i=s}return{half:r===null?null:n[0],point:i}}function Cd(e,t){let n=Tt(e),r=et().newSide(n,!1,t);return{context:n,side:r,spendPoint:be(r.pub.ed),viewPoint:be(r.viewPub),encPub:be(r.enc.pub)}}async function m2(e,t={}){let n=Tt(e),r=await et().newSideChunked(n,!1,t);return{context:n,side:r,spendPoint:be(r.pub.ed),viewPoint:be(r.viewPub),encPub:be(r.enc.pub)}}function Od(e,{spendHalf:t,viewHalf:n}={}){let r=(s,a)=>{let c=BigInt(s);if(c<=0n||c>=BigInt(e.halves.LIMIT))throw new u("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 Rd({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:be(n.ed),viewPoint:be(r),encPub:be(o.pub)}}function _y(e,{spendHalf:t,viewHalf:n}={}){let r=Tt(e),o=et(),i=Od(o,{spendHalf:t,viewHalf:n}),s=o.dleq.prove(i.half,r),{side:a,spendPoint:c,viewPoint:l,encPub:d}=Rd(i,s);return{context:r,side:a,spendPoint:c,viewPoint:l,encPub:d}}async function Iy(e,{spendHalf:t,viewHalf:n}={},r={}){let o=Tt(e),i=et(),s=Od(i,{spendHalf:t,viewHalf:n}),a=await i.dleq.proveChunked(s.half,o,r),{side:c,spendPoint:l,viewPoint:d,encPub:f}=Rd(s,a);return{context:o,side:c,spendPoint:l,viewPoint:d,encPub:f,commitHalf:be(i.halfCommitment(s.half))}}function Pd(e,{spendHalf:t,viewHalf:n}={}){let r=Tt(e),o=et(),i=Od(o,{spendHalf:t,viewHalf:n}),{side:s,spendPoint:a,viewPoint:c,encPub:l}=Rd(i,null);return{context:r,side:s,spendPoint:a,viewPoint:c,encPub:l,commitHalf:be(o.halfCommitment(i.half))}}function h2({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=Bd(n);i={proof:Ay(n.proof),edPub:fa(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||et().newSide(e,!0);i={proof:Ay(c.proof),edPub:be(c.pub.ed),viewPoint:be(c.viewPub),viewHalf:c.viewHalf,half:c.half,commitHalfClaimer:be(et().halfCommitment(c.half)),sealed:null,providerId:null,standIn:!0,mock:c}}else throw new u("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 u("bad-input",{field:"counterparty",missing:s});let a=i.sealed&&t&&t.enc?t.enc.priv:null;return{accepted:i,ownEncPriv:a}}async function Hd({context:e,side:t=null,counterparty:n=null,standIn:r=!1,options:o={}}){let i=n||r!==!0?null:await et().newSideChunked(e,!0,o),{accepted:s,ownEncPriv:a}=h2({context:e,side:t,counterparty:n,standIn:r,mock:i}),c=null;try{c=await et().verifySideChunked({proof:s.proof,pub:{ed:s.edPub},commitHalfClaimer:s.commitHalfClaimer},e,s.sealed,a,o)}catch{throw new u("bad-input",{field:"counterparty"})}if(!c||c.ok!==!0)throw new u("quote-refused",{step:"proof",why:c&&c.reason?"rejected":"unknown"});return s}function w2({order:e,side:t,context:n}){return t?{context:n,side:t,spendPoint:be(t.pub&&t.pub.ed),viewPoint:be(t.viewPub),encPub:be(t.enc&&t.enc.pub?t.enc.pub:null)}:Cd(e)}function y2(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"),Td(e.spendPoint)||t.push("spendPoint"),Td(e.viewPoint)||t.push("viewPoint"),t.length)throw new u("bad-input",{field:"side",missing:t})}function g2({own:e,other:t,network:n}){let r=t.viewPoint||(t.viewHalf?be(et().pointOf(t.viewHalf)):null);if(!r)throw new u("bad-input",{field:"counterparty",missing:["viewPoint"]});let o=null;try{o=et().jointAddress({ownSpendHalf:e.side.half,ownViewHalf:e.side.viewHalf,otherSpendPoint:t.edPub,otherViewPoint:r,network:n})}catch{throw new u("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:be(r),otherViewHalf:t.viewHalf?Jt(t.viewHalf):null,address:o.address,spendPub:be(o.spendPub),viewPub:be(o.viewPub),otherCommitHalf:t.commitHalfClaimer||null,commitHalfLocker:be(et().halfCommitment(e.side.half)),commitHalfClaimer:t.commitHalfClaimer||null,network:n||null}}}async function Ty({order:e,side:t=null,counterparty:n=null,standIn:r=!1,network:o=null,options:i={}}){let s=Tt(e),a=t?w2({order:e,side:t,context:s}):await m2(e,i);y2(a);let c=await Hd({context:a.context,side:a.side,counterparty:n,standIn:r,options:i});return g2({own:a,other:c,network:o})}me();me();_e();me();_e();var b2="Ninsei Relay",x2="1",k2="EIP712Domain(string name,string version)",Cy="FirmWindow(string market,string side,string xmrNetwork,uint32 readyMinSeconds,uint32 readyMaxSeconds,uint32 settlementMinSeconds,uint32 settlementMaxSeconds,uint32 quoteTtlSeconds)",S2="NodeFeatures(string relayId,address provider,address quoteKey,address registry,bytes32 hpkeKey,FirmWindow[] firmWindows,uint64 time,bytes32 nonce)"+Cy,v2=[["market","string"],["side","string"],["xmrNetwork","string"],["readyMinSeconds","uint32"],["readyMaxSeconds","uint32"],["settlementMinSeconds","uint32"],["settlementMaxSeconds","uint32"],["quoteTtlSeconds","uint32"]],E2=[["relayId","string"],["provider","address"],["quoteKey","address"],["registry","address"],["hpkeKey","bytes32"],["firmWindows","FirmWindow[]"],["time","uint64"],["nonce","bytes32"]],Cn=(e,t)=>{if(typeof e=="string")return e;if(typeof e=="number"&&Number.isFinite(e)||typeof e=="bigint")return String(e);throw new u("bad-input",{field:t})},A2=(e,t)=>{let n=null;try{n=Number(e)}catch{n=null}if(!Number.isFinite(n))throw new u("bad-input",{field:t});return n},to=(e,t="text")=>new TextEncoder().encode(Cn(e,t)),no=(...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},pa=(e,t,n)=>{let r=Cn(e??"",t).replace(/^0x/,"");if(!new RegExp("^[0-9a-fA-F]{"+n*2+"}$").test(r))throw new u("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},Oy=(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 u("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},N2=(e,t)=>{let n=Cn(e??"",t).trim();if(!/^(0x)?[0-9a-fA-F]{40}$/.test(n))throw new u("bad-input",{field:t});let r=new Uint8Array(32);return r.set(pa(n,t,20),12),r},Fd=(e,t)=>te(to(e??"",t)),By=(e,t,n)=>{if(!Array.isArray(e))throw new u("bad-input",{field:t});let r=e.map(o=>n(o));return te(no(...r))};function _2(e){if(!e||typeof e!="object")throw new u("bad-input",{field:"firmWindows"});let t=[te(to(Cy))];for(let[n,r]of v2)t.push(r==="string"?Fd(e[n],"firmWindows."+n):Oy(e[n],"firmWindows."+n,32));return te(no(...t))}function I2(e){if(!e||typeof e!="object")throw new u("bad-input",{field:"features"});let t=[te(to(S2))];for(let[n,r]of E2)if(r==="string")t.push(Fd(e[n],"features."+n));else if(r==="address")t.push(N2(e[n],"features."+n));else if(r==="bytes32")t.push(pa(e[n],"features."+n,32));else if(r==="uint64")t.push(Oy(e[n],"features."+n,64));else if(r==="string[]")t.push(By(e[n],"features."+n,o=>Fd(o,"features."+n)));else if(r==="FirmWindow[]")t.push(By(e[n],"features."+n,_2));else throw new u("bad-input",{field:"features."+n});return te(no(...t))}function T2(){return te(no(te(to(k2)),te(to(b2)),te(to(x2))))}function B2(e){return te(no(Uint8Array.from([25,1]),T2(),I2(e)))}var Ld=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t};function C2(e,t){let n=Cn(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=Pe.Signature.fromBytes(no(pa(n.slice(0,64),"signature",32),pa(n.slice(64,128),"signature",32))).addRecoveryBit(r).recoverPublicKey(e);return Ld(te(o.toBytes(!1).slice(1)).slice(12))}catch{return null}}function Ry({features:e,terms:t=null}={}){if(!e||typeof e!="object")throw new u("bad-input",{field:"features"});if(e.type!=="node_features"||A2(e.version,"features.version")!==1)throw new u("quote-refused",{step:"features",why:"version"});let n=B2(e),r=C2(n,e.signature),o=Cn(e.quoteKey===void 0||e.quoteKey===null?"":e.quoteKey,"features.quoteKey").toLowerCase();if(r===null||r!==o)throw new u("quote-refused",{step:"features",why:"signature"});let i=Cn(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 u("quote-refused",{step:"features",why:"hpke-key"});if(!Array.isArray(e.firmWindows)||e.firmWindows.length===0)throw new u("quote-refused",{step:"features",why:"windows"});if(t){if(Cn(e.provider===void 0||e.provider===null?"":e.provider,"features.provider").toLowerCase()!==String(t.maker||"").toLowerCase()||Cn(e.registry===void 0||e.registry===null?"":e.registry,"features.registry").toLowerCase()!==String(t.registry||"").toLowerCase())throw new u("quote-refused",{step:"features",why:"identity"});let s=String(t.market||""),a=String(t.side||""),c=String(t.xmrNetwork||""),l=e.firmWindows.find(d=>d&&d.market===s&&d.side===a&&d.xmrNetwork===c);if(!l)throw new u("quote-refused",{step:"features",why:"window"});return{featuresHash:Ld(n),hpkeKey:"0x"+i,window:l}}return{featuresHash:Ld(n),hpkeKey:"0x"+i,window:null}}var dt=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}},st=class extends dt{};var ro=class extends dt{},ar=class extends dt{},ma=class extends dt{},ha=class extends dt{},wa=class extends dt{},ya=class extends dt{},ga=class extends dt{},ba=class extends dt{},xa=class extends dt{},Bt=class extends dt{};var O2={},Py=R2(globalThis,O2);function R2(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 H2(){if(Py!==void 0&&globalThis.crypto!==void 0)return globalThis.crypto.subtle;try{let{webcrypto:e}=await Promise.resolve().then(()=>Og(Hy(),1));return e.subtle}catch(e){throw new Bt(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 H2())}};var xe=new Uint8Array(0);var Fy=new Uint8Array([75,69,77,0,0]);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 Ct(...e){let t=0;for(let o of e)t+=o.length;let n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n}function Dd(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 Md(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 Ly=new Uint8Array([72,80,75,69,45,118,49]);function oo(e){return new Uint8Array(he(e))}function he(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 Ud=class extends en{constructor(t){super(),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"hashSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_suiteId",{enumerable:!0,configurable:!0,writable:!0,value:xe}),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){return this._checkInit(),Ct(Ly,this._suiteId,t,n)}buildLabeledInfo(t,n,r){return this._checkInit(),Ct(new Uint8Array([r>>8,r]),Ly,this._suiteId,t,n)}async extract(t,n){await this._setup();let r=t.byteLength===0?new ArrayBuffer(this.hashSize):he(t),o=he(n);if(r.byteLength!==this.hashSize&&this._fallbackExtract!==void 0)return this._fallbackExtract(new Uint8Array(r),new Uint8Array(o)).buffer;let i=await this._api.importKey("raw",r,{name:this.algHash.name,hash:this.algHash.hash},!1,["sign"]);return await this._api.sign("HMAC",i,o)}async expand(t,n,r){if(await this._setup(),r>255*this.hashSize)throw new Error("Entropy limit reached");let o=he(t),i=await this._api.importKey("raw",o,this.algHash,!1,["sign"]),s=new Uint8Array(r),a=xe,c=oo(n);for(let l=1,d=0;d<s.length;l++){let f=new Uint8Array(a.length+c.length+1);f.set(a),f.set(c,a.length),f[f.length-1]=l,a=new Uint8Array(await this._api.sign("HMAC",i,f));let p=a.subarray(0,Math.min(a.length,s.length-d));s.set(p,d),d+=p.length}return s.buffer}async extractAndExpand(t,n,r,o){await this._setup();let i=he(n),s=await this._api.importKey("raw",i,"HKDF",!1,["deriveBits"]);return await this._api.deriveBits({name:"HKDF",hash:this.algHash.hash,salt:he(t),info:he(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===xe)throw new Error("Not initialized. Call init()")}},lr=class extends Ud{constructor(){super(...arguments),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:1}),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 F2=new Uint8Array([101,97,101,95,112,114,107]),L2=new Uint8Array([115,104,97,114,101,100,95,115,101,99,114,101,116]),ci=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(Fy);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(he(t))}async serializePrivateKey(t){return await this._prim.serializePrivateKey(t)}async deserializePrivateKey(t){return await this._prim.deserializePrivateKey(he(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=he(t);if(n.byteLength>8192)throw new st("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),i=xe,s=xe,a=xe;try{s=new Uint8Array(await this._prim.dh(n.privateKey,t.recipientPublicKey)),i=s;let c=xe;if(t.senderKey!==void 0){let f=cr(t.senderKey)?t.senderKey.privateKey:t.senderKey;a=new Uint8Array(await this._prim.dh(f,t.recipientPublicKey)),i=Ct(s,a),s.fill(0),a.fill(0);let p=cr(t.senderKey)?t.senderKey.publicKey:await this._prim.derivePublicKey(t.senderKey);c=new Uint8Array(await this._prim.serializePublicKey(p))}let l=Ct(new Uint8Array(r),new Uint8Array(o),c),d=await this._generateSharedSecret(i,l);return{enc:r,sharedSecret:d}}catch(c){throw new ma(c)}finally{i.fill(0),s.fill(0),a.fill(0)}}async decap(t){let n=he(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),a=xe,c=xe,l=xe;try{c=new Uint8Array(await this._prim.dh(o,r)),a=c;let d=xe;t.senderPublicKey!==void 0&&(l=new Uint8Array(await this._prim.dh(o,t.senderPublicKey)),a=Ct(c,l),c.fill(0),l.fill(0),d=new Uint8Array(await this._prim.serializePublicKey(t.senderPublicKey)));let f=Ct(new Uint8Array(n),new Uint8Array(s),d);return await this._generateSharedSecret(a,f)}catch(d){throw new ha(d)}finally{a.fill(0),c.fill(0),l.fill(0)}}async _generateSharedSecret(t,n){let r=this._kdf.buildLabeledIkm(F2,t);try{let o=this._kdf.buildLabeledInfo(L2,n,this.secretSize);return await this._kdf.extractAndExpand(xe,r,o,this.secretSize)}finally{r.fill(0)}}};var ka=["deriveBits"],Dy=new Uint8Array([100,107,112,95,112,114,107]),My=new Uint8Array([115,107]);var jd={name:"X25519",size:32,pkcs8AlgId:new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),basePoint:(()=>{let e=new Uint8Array(32);return e[0]=9,e})()};var li=class extends en{constructor(t,n){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.name,this._alg={name:t.name},this._hkdf=n,this._nPk=t.size,this._nSk=t.size,this._nDh=t.size,this._pkcs8AlgId=t.pkcs8AlgId,this._basePoint=t.basePoint}async serializePublicKey(t){await this._setup();try{return await this._api.exportKey("raw",t)}catch(n){throw new ro(n)}}async deserializePublicKey(t){await this._setup();try{return await this._importRawKey(he(t),!0)}catch(n){throw new ar(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 Dd(n.d).buffer}catch(n){throw new ro(n)}}async deserializePrivateKey(t){await this._setup();try{return await this._importRawKey(he(t),!1)}catch(n){throw new ar(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 ar(o)}}async generateKeyPair(){await this._setup();try{return await this._api.generateKey(this._algName,!0,ka)}catch(t){throw new Bt(t)}}async deriveKeyPair(t){await this._setup();try{let n=he(t),r=await this._hkdf.labeledExtract(xe,Dy,new Uint8Array(n)),o=await this._hkdf.labeledExpand(r,My,xe,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 xa(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 ar(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 ro(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,ka)}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,ka)}};function D2(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function $e(e,t,n=""){let r=D2(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 kt(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function ut(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}var M2=new Uint32Array([287454020]),U2=new Uint8Array(M2.buffer),Wd=U2[0]===68;function Sa(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ut(e){return Uint8Array.from(e)}var K2=new Uint8Array([115,101,99]),io=class{constructor(t,n){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._kdf=t,this.exporterSecret=n}seal(t,n){return Promise.reject(new Bt("Not supported"))}open(t,n){return Promise.reject(new Bt("Not supported"))}async export(t,n){let r=he(t);if(r.byteLength>8192)throw new st("Too long exporter context");try{return await this._kdf.labeledExpand(this.exporterSecret,K2,new Uint8Array(r),n)}catch(o){throw new wa(o)}}},va=class extends io{},Ea=class extends io{constructor(t,n,r){super(t,n),Object.defineProperty(this,"enc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.enc=r}};var so=class extends io{constructor(t,n){super(t,n.exporterSecret),Object.defineProperty(this,"_ctx",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._ctx={key:n.aead.createEncryptionContext(n.key),baseNonce:n.baseNonce,seq:n.seq}}computeNonce(t){let n=tn(t.seq,t.baseNonce.byteLength);return Md(t.baseNonce,n).buffer}incrementSeq(t){if(t.seq>Number.MAX_SAFE_INTEGER)throw new ba("Message limit reached");t.seq+=1}};var V2=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)},$2=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},Aa,ao=class{constructor(){Aa.set(this,Promise.resolve())}async lock(){let t,n=new Promise(o=>{t=o}),r=V2(this,Aa,"f");return $2(this,Aa,n,"f"),await r,t}};Aa=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)},z2=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},di,Na=class extends so{constructor(){super(...arguments),di.set(this,void 0)}async open(t,n=xe.buffer){z2(this,di,jy(this,di,"f")??new ao,"f");let r=await jy(this,di,"f").lock(),o;try{o=await this._ctx.key.open(this.computeNonce(this._ctx),he(t),he(n))}catch(i){throw new ga(i)}finally{r()}return this.incrementSeq(this._ctx),o}};di=new WeakMap;var Wy=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)},X2=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},ui,_a=class extends so{constructor(t,n,r){super(t,n),Object.defineProperty(this,"enc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),ui.set(this,void 0),this.enc=r}async seal(t,n=xe.buffer){X2(this,ui,Wy(this,ui,"f")??new ao,"f");let r=await Wy(this,ui,"f").lock(),o;try{o=await this._ctx.key.seal(this.computeNonce(this._ctx),he(t),he(n))}catch(i){throw new ya(i)}finally{r()}return this.incrementSeq(this._ctx),o}};ui=new WeakMap;function Vd(e){if("auth"in e&&e.auth===!1)throw new Bt("Auth and AuthPSK modes are not supported by this KEM")}var Y2=new Uint8Array([98,97,115,101,95,110,111,110,99,101]),G2=new Uint8Array([101,120,112]),Q2=new Uint8Array([105,110,102,111,95,104,97,115,104]),Z2=new Uint8Array([107,101,121]),q2=new Uint8Array([112,115,107,95,105,100,95,104,97,115,104]),J2=new Uint8Array([115,101,99,114,101,116]),eE=new Uint8Array([72,80,75,69,0,0,0,0,0,0]),Ia=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 st("KemId cannot be used");if(this._kem=t.kem,typeof t.kdf=="number")throw new st("KdfId cannot be used");if(this._kdf=t.kdf,typeof t.aead=="number")throw new st("AeadId cannot be used");this._aead=t.aead,this._suiteId=new Uint8Array(eE),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){t.senderKey!==void 0&&Vd(this._kem),this._validateInputLength(t),await this._setup();let n=await this._kem.encap(t),r=(t.psk!==void 0?1:0)|(t.senderKey!==void 0?2:0);return await this._keyScheduleS(r,n.sharedSecret,n.enc,t)}async createRecipientContext(t){t.senderPublicKey!==void 0&&Vd(this._kem),this._validateInputLength(t),await this._setup();let n=await this._kem.decap(t),r=(t.psk!==void 0?1:0)|(t.senderPublicKey!==void 0?2:0);return await this._keyScheduleR(r,n,t)}async seal(t,n,r=xe.buffer){let o=await this.createSenderContext(t);return{ct:await o.seal(n,r),enc:o.enc}}async open(t,n,r=xe.buffer){return await(await this.createRecipientContext(t)).open(n,r)}async _keySchedule(t,n,r){let o=r.psk===void 0?xe:oo(r.psk.id),i=await this._kdf.labeledExtract(xe,q2,o),s=r.info===void 0?xe:oo(r.info),a=await this._kdf.labeledExtract(xe,Q2,s),c=Ct(new Uint8Array([t]),new Uint8Array(i),new Uint8Array(a)),l=r.psk===void 0?xe:oo(r.psk.key),d=this._kdf.buildLabeledIkm(J2,l),f=this._kdf.buildLabeledInfo(G2,c,this._kdf.hashSize),p=await this._kdf.extractAndExpand(n,d,f,this._kdf.hashSize);if(this._aead.id===65535)return{aead:this._aead,exporterSecret:p};let h=this._kdf.buildLabeledInfo(Z2,c,this._aead.keySize),w=await this._kdf.extractAndExpand(n,d,h,this._aead.keySize),b=this._kdf.buildLabeledInfo(Y2,c,this._aead.nonceSize),y=await this._kdf.extractAndExpand(n,d,b,this._aead.nonceSize);return{aead:this._aead,exporterSecret:p,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 Ea(this._kdf,i.exporterSecret,r):new _a(this._kdf,i,r)}async _keyScheduleR(t,n,r){let o=await this._keySchedule(t,n,r);return o.key===void 0?new va(this._kdf,o.exporterSecret):new Na(this._kdf,o)}_validateInputLength(t){if(t.info!==void 0&&t.info.byteLength>268435456)throw new st("Too long info");if(t.psk!==void 0){if(t.psk.key.byteLength<32)throw new st(`PSK must have at least ${32} bytes`);if(t.psk.key.byteLength>8192)throw new st("Too long psk.key");if(t.psk.id.byteLength>8192)throw new st("Too long psk.id")}}};var fi=class extends Ia{};var pi=class extends lr{};var mi=class extends ci{constructor(){let t=new lr;super(32,new li(jd,t),t),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:32}),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})}};function Ky(e){function t(n,r,o){if($e(n,void 0,"key"),!Wd)throw new Error("Non little-endian hardware is not yet supported");$e(r,12,"nonce"),o!==void 0&&$e(o,void 0,"AAD");let i=e(n,r,o),s=!1;return{encrypt(a,c){if(s)throw new Error("cannot encrypt() twice with same key + nonce");return s=!0,$e(a),c!==void 0&&$e(c,void 0,"output"),i.encrypt(a,c)},decrypt(a,c){if($e(a),a.length<16)throw new Error('"ciphertext" expected length bigger than tagLength=16');return c!==void 0&&$e(c,void 0,"output"),i.decrypt(a,c)}}}return Object.assign(t,{blockSize:64,nonceLength:12,tagLength:16})}function Vy(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 $d(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&&!ur(t))throw new Error("invalid output, must be aligned");return t}function ur(e){return e.byteOffset%4===0}var zd=Uint32Array.of(1634760805,857760878,2036477234,1797285236);function we(e,t){return e<<t|e>>>32-t}var Ta=64,tE=16,zy=2**32-1,$y=Uint32Array.of();function nE(e,t,n,r,o,i,s){let a=o.length,c=new Uint8Array(Ta),l=kt(c),d=ur(o)&&ur(i),f=d?kt(o):$y,p=d?kt(i):$y;for(let h=0;h<a;s++){if(e(t,n,r,l,s,20),s>=zy)throw new Error("arx: counter overflow");let w=Math.min(Ta,a-h);if(d&&w===Ta){let b=h/4;if(h%4!==0)throw new Error("arx: invalid block position");for(let y=0,v;y<tE;y++)v=b+y,p[v]=f[v]^l[y];h+=Ta;continue}for(let b=0,y;b<w;b++)y=h+b,i[y]=o[y]^c[b];h+=w}}function Xy(e){if(typeof e!="function")throw new Error("core must be a function");return(t,n,r,o,i=0)=>{$e(t,32,"arx key"),$e(n,12,"nonce"),$e(r,void 0,"data");let s=r.length;if(o===void 0&&(o=new Uint8Array(s)),$e(o,void 0,"output"),!Number.isSafeInteger(i)||i<0||i>=zy)throw new Error("arx: counter overflow");if(o.length<s)throw new Error(`arx: output (${o.length}) is shorter than data (${s})`);let a=Ut(t),c=ur(n)?void 0:Ut(n),l=kt(a);return nE(e,zd,l,kt(c??n),r,o,i),ut(a),c&&ut(c),o}}function Ge(e,t){return e[t++]&255|(e[t++]&255)<<8}var Ba=class{constructor(t){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,"r5",{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=Ut($e(t,32,"key"));let n=Ge(t,0),r=Ge(t,2),o=Ge(t,4),i=Ge(t,6),s=Ge(t,8),a=Ge(t,10),c=Ge(t,12),l=Ge(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 d=0;d<10;d++)this.r5[d]=5*this.r[d];for(let d=0;d<8;d++)this.pad[d]=Ge(t,16+2*d)}process(t,n,r=!1){let o=r?0:2048,{h:i,r:s,r5:a}=this,c=s[0],l=s[1],d=s[2],f=s[3],p=s[4],h=s[5],w=s[6],b=s[7],y=s[8],v=s[9],I=a[1],g=a[2],T=a[3],A=a[4],B=a[5],P=a[6],O=a[7],j=a[8],D=a[9],X=Ge(t,n+0),H=Ge(t,n+2),m=Ge(t,n+4),k=Ge(t,n+6),x=Ge(t,n+8),C=Ge(t,n+10),U=Ge(t,n+12),W=Ge(t,n+14),Y=i[0]+(X&8191),N=i[1]+((X>>>13|H<<3)&8191),S=i[2]+((H>>>10|m<<6)&8191),_=i[3]+((m>>>7|k<<9)&8191),R=i[4]+((k>>>4|x<<12)&8191),M=i[5]+(x>>>1&8191),K=i[6]+((x>>>14|C<<2)&8191),G=i[7]+((C>>>11|U<<5)&8191),Z=i[8]+((U>>>8|W<<8)&8191),V=i[9]+(W>>>5|o),J=0,re=J+Y*c+N*D+S*j+_*O+R*P;J=re>>>13,re&=8191,re+=M*B+K*A+G*T+Z*g+V*I,J+=re>>>13,re&=8191;let E=J+Y*l+N*c+S*D+_*j+R*O;J=E>>>13,E&=8191,E+=M*P+K*B+G*A+Z*T+V*g,J+=E>>>13,E&=8191;let F=J+Y*d+N*l+S*c+_*D+R*j;J=F>>>13,F&=8191,F+=M*O+K*P+G*B+Z*A+V*T,J+=F>>>13,F&=8191;let L=J+Y*f+N*d+S*l+_*c+R*D;J=L>>>13,L&=8191,L+=M*j+K*O+G*P+Z*B+V*A,J+=L>>>13,L&=8191;let z=J+Y*p+N*f+S*d+_*l+R*c;J=z>>>13,z&=8191,z+=M*D+K*j+G*O+Z*P+V*B,J+=z>>>13,z&=8191;let $=J+Y*h+N*p+S*f+_*d+R*l;J=$>>>13,$&=8191,$+=M*c+K*D+G*j+Z*O+V*P,J+=$>>>13,$&=8191;let ee=J+Y*w+N*h+S*p+_*f+R*d;J=ee>>>13,ee&=8191,ee+=M*l+K*c+G*D+Z*j+V*O,J+=ee>>>13,ee&=8191;let ne=J+Y*b+N*w+S*h+_*p+R*f;J=ne>>>13,ne&=8191,ne+=M*d+K*l+G*c+Z*D+V*j,J+=ne>>>13,ne&=8191;let le=J+Y*y+N*b+S*w+_*h+R*p;J=le>>>13,le&=8191,le+=M*f+K*d+G*l+Z*c+V*D,J+=le>>>13,le&=8191;let de=J+Y*v+N*y+S*b+_*w+R*h;J=de>>>13,de&=8191,de+=M*p+K*f+G*d+Z*l+V*c,J+=de>>>13,de&=8191,J=(J<<2)+J|0,J=J+re|0,re=J&8191,J=J>>>13,E+=J,i[0]=re,i[1]=E,i[2]=F,i[3]=L,i[4]=z,i[5]=$,i[6]=ee,i[7]=ne,i[8]=le,i[9]=de}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;ut(r)}update(t){this.assertActive();let{buffer:n}=this,r=16,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(){ut(this.h,this.r,this.r5,this.buffer,this.pad)}assertActive(){if(this.finished)throw new Error("Hash#digest() has already been called")}digest(){this.assertActive(),this.finished=!0;let{buffer:t,h:n}=this,{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let o=0;for(let s=0;s<8;s++)t[o++]=n[s]>>>0,t[o++]=n[s]>>>8;let i=t.slice();return this.destroy(),i}};function Qy(e,t,n,r,o,i=20){let s=e[0],a=e[1],c=e[2],l=e[3],d=t[0],f=t[1],p=t[2],h=t[3],w=t[4],b=t[5],y=t[6],v=t[7],I=o,g=n[0],T=n[1],A=n[2],B=s,P=a,O=c,j=l,D=d,X=f,H=p,m=h,k=w,x=b,C=y,U=v,W=I,Y=g,N=T,S=A;for(let R=0;R<i;R+=2)B=B+D|0,W=we(W^B,16),k=k+W|0,D=we(D^k,12),B=B+D|0,W=we(W^B,8),k=k+W|0,D=we(D^k,7),P=P+X|0,Y=we(Y^P,16),x=x+Y|0,X=we(X^x,12),P=P+X|0,Y=we(Y^P,8),x=x+Y|0,X=we(X^x,7),O=O+H|0,N=we(N^O,16),C=C+N|0,H=we(H^C,12),O=O+H|0,N=we(N^O,8),C=C+N|0,H=we(H^C,7),j=j+m|0,S=we(S^j,16),U=U+S|0,m=we(m^U,12),j=j+m|0,S=we(S^j,8),U=U+S|0,m=we(m^U,7),B=B+X|0,S=we(S^B,16),C=C+S|0,X=we(X^C,12),B=B+X|0,S=we(S^B,8),C=C+S|0,X=we(X^C,7),P=P+H|0,W=we(W^P,16),U=U+W|0,H=we(H^U,12),P=P+H|0,W=we(W^P,8),U=U+W|0,H=we(H^U,7),O=O+m|0,Y=we(Y^O,16),k=k+Y|0,m=we(m^k,12),O=O+m|0,Y=we(Y^O,8),k=k+Y|0,m=we(m^k,7),j=j+D|0,N=we(N^j,16),x=x+N|0,D=we(D^x,12),j=j+D|0,N=we(N^j,8),x=x+N|0,D=we(D^x,7);let _=0;r[_++]=s+B|0,r[_++]=a+P|0,r[_++]=c+O|0,r[_++]=l+j|0,r[_++]=d+D|0,r[_++]=f+X|0,r[_++]=p+H|0,r[_++]=h+m|0,r[_++]=w+k|0,r[_++]=b+x|0,r[_++]=y+C|0,r[_++]=v+U|0,r[_++]=I+W|0,r[_++]=g+Y|0,r[_++]=T+N|0,r[_++]=A+S|0}var rE=Xy(Qy),Yy=new Uint8Array(16);function Gy(e,t,n,r,o){$e(t,32,"arx key");let i=new Uint8Array(64),s=kt(i),a=Ut(t),c=kt(a),l;ur(n)||(l=Ut(n));let d=kt(l??n);Qy(zd,c,d,s,0,20);let f=i.subarray(0,32),p=new Uint8Array(16),h=Sa(p);h.setBigUint64(0,BigInt(o?o.length:0),!0),h.setBigUint64(8,BigInt(r.length),!0);let w=new Ba(f);if(o){w.update(o);let v=o.length%16;v&&w.update(Yy.subarray(v))}w.update(r);let b=r.length%16;b&&w.update(Yy.subarray(b)),w.update(p);let y=w.digest();return ut(s,a,p),l&&ut(l),y}var oE=e=>(t,n,r)=>({encrypt(i,s){let a=i.length;s=$d(a+16,s,!1),s.set(i);let c=s.subarray(0,-16);e(t,n,c,c,1);let l=Gy(e,t,n,c,r);return s.set(l,a),ut(l),s},decrypt(i,s){s=$d(i.length-16,s,!1);let a=i.subarray(0,-16),c=i.subarray(-16),l=Gy(e,t,n,a,r);if(!Vy(c,l))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),e(t,n,s,s,1),ut(l),s}}),Xd=Ky(oE(rE));var Yd=class{constructor(t){Object.defineProperty(this,"_key",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._key=new Uint8Array(he(t))}async seal(t,n,r){return Xd(this._key,new Uint8Array(he(t)),new Uint8Array(he(r))).encrypt(new Uint8Array(he(n))).buffer}async open(t,n,r){return Xd(this._key,new Uint8Array(he(t)),new Uint8Array(he(r))).decrypt(new Uint8Array(he(n))).buffer}},hi=class{constructor(){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:3}),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 Yd(t)}};me();var iE=e=>new TextEncoder().encode(String(e)),Gd=e=>{if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);throw new u("bad-input",{field:"viewEnvelope"})},Zy=e=>{let t="0x";for(let n of Gd(e))t+=n.toString(16).padStart(2,"0");return t},qy=(e,t,n)=>{let r=String(e??"").replace(/^0x/,"");if(!new RegExp("^[0-9a-fA-F]{"+t*2+"}$").test(r))throw new u("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},sE=()=>new fi({kem:new mi,kdf:new pi,aead:new hi}),aE="ninsei-relay-view-v1";function Jy({termsDigest:e,commitHalf:t,edPoint:n,edViewPointClient:r,edViewPointNode:o}={}){let i=[["termsDigest",e],["commitHalf",t],["edPoint",n],["edViewPointClient",r],["edViewPointNode",o]].map(([l,d])=>qy(d,32,l)),s=iE(aE),a=new Uint8Array(s.length+i.reduce((l,d)=>l+d.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 e0({hpkeKey:e,info:t,plaintext:n}={}){let r=qy(e,32,"hpkeKey"),o=Gd(n);if(o.length!==32&&o.length!==64)throw new u("bad-input",{field:"plaintext"});if(!(t instanceof Uint8Array))throw new u("bad-input",{field:"info"});let i=sE(),s=null;try{s=await i.kem.deserializePublicKey(r);let a=await i.createSenderContext({recipientPublicKey:s,info:t}),c=Gd(await a.seal(o));return{enc:Zy(a.enc),ciphertext:Zy(c)}}catch(a){throw a instanceof u?a:new u("bad-input",{field:"hpkeKey"})}}me();var cE="Ninsei Relay",lE="1",dE=["EIP712Domain(","string name,","string version)"],uE=dE.join(""),Qd=[["chainId","uint256"],["factory","address"],["locker","address"],["claimer","address"],["amount","uint256"],["readyBy","uint64"],["t1","uint64"],["salt","bytes32"]],n0="FirmOrder("+Qd.map(([e,t])=>t+" "+e).join(",")+")",Zd=[["market","string"],["side","string"],["maker","address"],["registry","address"],["featuresHash","bytes32"],["xmrNetwork","string"],["order","FirmOrder"],["xmrAmount","uint256"],["claimTip","uint256"]],fE="FirmTerms("+Zd.map(([e,t])=>t+" "+e).join(",")+")"+n0,wi=e=>new TextEncoder().encode(String(e)),qd=(...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},r0=(e,t)=>{let n=String(e??"").replace(/^0x/,"");if(!/^[0-9a-fA-F]*$/.test(n)||n.length%2)throw new u("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},t0=(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 u("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},pE=(e,t)=>{let n=String(e??"").trim();if(!/^(0x)?[0-9a-fA-F]{40}$/.test(n))throw new u("bad-input",{field:t});let r=new Uint8Array(32);return r.set(r0(n.replace(/^0x/,""),t),12),r},mE=(e,t)=>{let n=r0(e,t);if(n.length!==32)throw new u("bad-input",{field:t});return n},hE=(e,t,n,r)=>{if(t==="string")return e.keccak256(wi(n??""));if(t==="address")return pE(n,r);if(t==="bytes32")return mE(n,r);if(t==="uint64")return t0(n,r,64);if(t==="uint256")return t0(n,r,256);throw new u("bad-input",{field:r})},o0=(e,t,n,r,o)=>{let i=[e.keccak256(wi(t))];for(let[s,a]of n)if(a==="FirmOrder"){let c=r&&r.order;if(!c||typeof c!="object")throw new u("bad-input",{field:o+".order"});i.push(wE(e,c))}else i.push(hE(e,a,r?r[s]:void 0,o+"."+s));return e.keccak256(qd(...i))};function wE(e,t){return o0(e,n0,Qd,t,"terms.order")}function yE(e){return e.keccak256(qd(e.keccak256(wi(uE)),e.keccak256(wi(cE)),e.keccak256(wi(lE))))}function gE({crypto:e,terms:t}={}){if(!e||typeof e.keccak256!="function")throw new u("bad-input",{field:"crypto"});return o0(e,fE,Zd,t,"terms")}function i0({crypto:e,terms:t}={}){if(!e||typeof e.keccak256!="function")throw new u("bad-input",{field:"crypto"});return e.keccak256(qd(Uint8Array.from([25,1]),yE(e),gE({crypto:e,terms:t})))}function s0(e){let t=[];if(!e||typeof e!="object")return["terms"];for(let[n]of Zd)if(n==="order")if(!e.order||typeof e.order!="object")t.push("order");else for(let[r]of Qd){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 d0=(e,t,n)=>{let r=String(e??"").replace(/^0x/i,"");if(!new RegExp("^[0-9a-fA-F]{"+n*2+"}$").test(r))throw new u("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},yi=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},ze=(e,t,n)=>yi(d0(e,n,t)),u0=(e,t)=>{let n=null;try{n=BigInt(e)}catch{n=null}if(n===null||n<=0n||n>=Te.Point.Fn.ORDER)throw new u("bad-input",{field:t});return n},a0=(e,t)=>{let n=u0(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},c0=(e,t)=>yi(Te.Point.BASE.multiply(u0(e,t)).toBytes()),l0=(e,t)=>{let n=d0(e,t,32);try{Te.Point.fromHex(yi(n).slice(2))}catch{throw new u("bad-input",{field:t})}return yi(n)},bE=["XA","XB","pokA","pokB","proofs"];function xE(e){if(!e||typeof e!="object")throw new u("bad-input",{field:"clientHalf.proof"});for(let a of bE)if(e[a]===void 0||e[a]===null||e[a]==="")throw new u("bad-input",{field:"clientHalf.proof."+a});if(!Array.isArray(e.proofs)||e.proofs.length!==253)throw new u("bad-input",{field:"clientHalf.proof.proofs"});let t=ze(e.XA,33,"clientHalf.proof.XA"),n=ze(e.XB,32,"clientHalf.proof.XB"),r=(a,c,l)=>{if(!a||typeof a!="object")throw new u("bad-input",{field:"clientHalf.proof."+c});return{R:ze(a.R,l,"clientHalf.proof."+c+".R"),s:ze(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 u("bad-input",{field:"clientHalf.proof.proofs."+c});let l={};for(let d of["eA","eB","a0","a1","b0","b1"])l[d]=ze(a.sig[d],32,"clientHalf.proof.proofs."+c+".sig."+d);return{cA:ze(a.cA,33,"clientHalf.proof.proofs."+c+".cA"),cB:ze(a.cB,32,"clientHalf.proof.proofs."+c+".cB"),sig:l}});return{XA:t,XB:n,pokA:o,pokB:i,proofs:s}}async function f0({features:e,terms:t,clientHalf:n,edViewPointClient:r,edViewPointNode:o,nodeViewScalar:i,clientViewScalar:s=null,side:a=null}={}){let c=Ry({features:e,terms:t}),l=String(a||t?.side||"");if(l!=="ask"&&l!=="bid")throw new u("bad-input",{field:"side"});if(t?.side!==void 0&&t.side!==l)throw new u("bad-input",{field:"terms.side"});if(!t||typeof t!="object"||!t.order||typeof t.order!="object")throw new u("bad-input",{field:"terms"});if(t.featuresHash!==void 0&&t.featuresHash!==null&&t.featuresHash!==""&&String(t.featuresHash).toLowerCase()!==c.featuresHash)throw new u("quote-refused",{step:"features",why:"hash"});let d=t.order,f=["chainId","factory","locker","claimer","amount","readyBy","t1","salt"];for(let k of f)if(d[k]===void 0||d[k]===null||d[k]==="")throw new u("bad-input",{field:"terms.order."+k});if(String(d.chainId)!==String(t.market||"").split(":")[0])throw new u("bad-input",{field:"terms.market"});let p=n||{},h=ze(p.commitHalf,32,"clientHalf.commitHalf"),w=ze(p.edPoint,32,"clientHalf.edPoint"),b=xE(p.proof);if(b.XB!==w)throw new u("bad-input",{field:"clientHalf.edPoint"});let y=ze(t.maker,20,"terms.maker"),v=ze(d.locker,20,"terms.order.locker"),I=ze(d.claimer,20,"terms.order.claimer");if(v===I)throw new u("bad-input",{field:"terms.order.roles"});if(l==="ask"){if(I!==y)throw new u("bad-input",{field:"terms.order.claimer"});if(String(t.claimTip)!=="0")throw new u("bad-input",{field:"terms.claimTip"})}else if(v!==y)throw new u("bad-input",{field:"terms.order.locker"});let g=l0(r,"edViewPointClient"),T=l0(o,"edViewPointNode"),A=a0(i,"nodeViewScalar");if(c0(i,"nodeViewScalar").toLowerCase()!==T.toLowerCase())throw new u("bad-input",{field:"edViewPointNode"});let B=a0(s,"clientViewScalar");if(c0(s,"clientViewScalar").toLowerCase()!==g.toLowerCase())throw new u("bad-input",{field:"edViewPointClient"});let P={market:String(t.market),side:l,maker:ze(t.maker,20,"terms.maker"),registry:ze(t.registry,20,"terms.registry"),featuresHash:c.featuresHash,xmrNetwork:String(t.xmrNetwork),order:{chainId:String(d.chainId),factory:ze(d.factory,20,"terms.order.factory"),locker:ze(d.locker,20,"terms.order.locker"),claimer:ze(d.claimer,20,"terms.order.claimer"),amount:String(d.amount),readyBy:Number(d.readyBy),t1:Number(d.t1),salt:ze(d.salt,32,"terms.order.salt")},xmrAmount:String(t.xmrAmount),claimTip:String(t.claimTip)},O=s0(P);if(O.length)throw new u("bad-input",{field:"terms",missing:O});let j=yi(i0({crypto:{keccak256:te},terms:P})),D=Jy({termsDigest:j,commitHalf:h,edPoint:w,edViewPointClient:g,edViewPointNode:T}),X=new Uint8Array(64);X.set(A,0),X.set(B,32);let H=await e0({hpkeKey:c.hpkeKey,info:D,plaintext:X});return{payload:JSON.stringify({terms:P,clientHalf:{commitHalf:h,edPoint:w,proof:b},edViewPointClient:g,edViewPointNode:T,viewEnvelope:H}),terms:P,viewEnvelope:H,edViewPointClient:g,edViewPointNode:T}}me();_e();_e();var kE={keccak256:te,secp256k1:Pe};var p0=e=>Kh({crypto:kE,quote:e});function m0({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 SE="Quote(string relayId,address provider,bytes32 session,bytes32 requestId,uint64 counter,bytes32 requestHash,string payload,uint64 time)",vE="EIP712Domain(string name,string version)",EE="Ninsei Relay",AE="1",xi=(e,t)=>{if(typeof e=="string")return e;if(typeof e=="number"&&Number.isFinite(e)||typeof e=="bigint")return String(e);throw new u("bad-input",{field:t})},co=(e,t)=>{let n=null;try{n=Number(e)}catch{n=null}if(!Number.isFinite(n))throw new u("bad-input",{field:t});return n},lo=(e,t="text")=>new TextEncoder().encode(xi(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},Ca=(e,t,n)=>{let r=xi(e??"",t).replace(/^0x/,"");if(!new RegExp("^[0-9a-fA-F]{"+n*2+"}$").test(r))throw new u("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},Jd=(e,t)=>{let n=new Uint8Array(32);return n.set(Ca(e,t,20),12),n},gi=(e,t)=>Ca(e,t,32),bi=(e,t)=>{let n=null;try{n=BigInt(e)}catch{n=null}if(n===null||n<0n)throw new u("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},Oa=(e,t)=>te(lo(e??"",t));function NE(e){if(!e||typeof e!="object")throw new u("bad-input",{field:"answer"});return te(uo(te(lo(SE)),Oa(e.relayId,"answer.relayId"),Jd(e.provider,"answer.provider"),gi(e.session,"answer.session"),gi(e.requestId,"answer.requestId"),bi(e.counter,"answer.counter"),gi(e.requestHash,"answer.requestHash"),Oa(e.payload,"answer.payload"),bi(e.time,"answer.time")))}function y0(){return te(uo(te(lo(vE)),te(lo(EE)),te(lo(AE))))}function _E(e){return te(uo(Uint8Array.from([25,1]),y0(),NE(e)))}var IE="QuoteRequest(string relayId,address provider,bytes32 session,bytes32 requestId,uint64 counter,uint64 expiry,string payload,uint256 feeBps,address feeRecipient)";function TE(e){if(!e||typeof e!="object")throw new u("bad-input",{field:"forwarded"});return te(uo(te(lo(IE)),Oa(e.relayId,"forwarded.relayId"),Jd(e.provider,"forwarded.provider"),gi(e.session,"forwarded.session"),gi(e.requestId,"forwarded.requestId"),bi(e.counter,"forwarded.counter"),bi(e.expiry,"forwarded.expiry"),Oa(e.payload,"forwarded.payload"),bi(e.feeBps,"forwarded.feeBps"),Jd(e.feeRecipient,"forwarded.feeRecipient")))}function h0(e){return te(uo(Uint8Array.from([25,1]),y0(),TE(e)))}function g0({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 u("quote-refused",{step:"answer",why:"forwarded"});if(!/^0x[0-9a-fA-F]{40}$/.test(String(t||"")))throw new u("quote-refused",{step:"relay-info",why:"key"});if(xi(e.payload===void 0||e.payload===null?"":e.payload,"forwarded.payload")!==n)throw new u("quote-refused",{step:"answer",why:"forwarded-payload"});if(!St(e.provider,r))throw new u("quote-refused",{step:"answer",why:"forwarded-provider"});let i=x0(h0(e),e.signature);if(i===null||i!==String(t).toLowerCase())throw new u("quote-refused",{step:"answer",why:"forwarded-signature"});if(o!=null){let s=b0(h0(e));if(!St(s,o))throw new u("quote-refused",{step:"answer",why:"forwarded-hash"})}return e}var b0=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t};function x0(e,t){let n=xi(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=Pe.Signature.fromBytes(uo(Ca(n.slice(0,64),"signature",32),Ca(n.slice(64,128),"signature",32))).addRecoveryBit(r).recoverPublicKey(e);return b0(te(o.toBytes(!1).slice(1)).slice(12))}catch{return null}}function BE(e,t){if(!e||typeof e!="object"||e.type!=="quote"||co(e.version,"answer.version")!==1)throw new u("quote-refused",{step:"answer",why:"frame"});let n=x0(_E(e),e.signature);if(n===null||n!==String(t||"").toLowerCase())throw new u("quote-refused",{step:"answer",why:"signature"});return e}var CE="0x"+"00".repeat(20),w0=e=>xi(e??"","field").toLowerCase(),St=(e,t)=>w0(e)===w0(t);function OE(e,t,n){let r=t.order;if(!e||typeof e!="object")throw new u("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[p,h]of o)if(!St(e[p],h))throw new u("quote-refused",{step:"answer",why:"field",field:p});if(!m0({side:t.side,requested:t.xmrAmount,signed:e.xmrAmount}).ok)throw new u("quote-refused",{step:"answer",why:"field",field:"xmrAmount"});if(St(e.feeRecipient,CE))throw new u("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 u("quote-refused",{step:"answer",why:"fee"})}if(!Number.isSafeInteger(s)||s<0||s>200)throw new u("quote-refused",{step:"answer",why:"fee"});if(a!==c*BigInt(s)/10000n)throw new u("quote-refused",{step:"answer",why:"fee"});let l=co(e.validUntil,"quote.validUntil");if(!Number.isSafeInteger(l)||l<=n)throw new u("quote-expired",{step:"answer",validUntil:e.validUntil});let d=co(r.readyBy,"order.readyBy"),f=co(r.t1,"order.t1");if(!Number.isSafeInteger(d)||!Number.isSafeInteger(f)||d>=f||l>=d)throw new u("quote-refused",{step:"answer",why:"validity",field:"validUntil"})}function k0({answer:e,features:t,request:n,now:r=null}={}){if(!n||!n.terms)throw new u("bad-input",{field:"request"});if(BE(e,t&&t.quoteKey),!e.relayId||!St(e.relayId,t&&t.relayId))throw new u("quote-refused",{step:"answer",why:"relay"});let o=null;try{o=JSON.parse(e.payload)}catch{throw new u("quote-refused",{step:"answer",why:"payload"})}if(!o||typeof o!="object"||!o.quote)throw new u("quote-refused",{step:"answer",why:"payload"});if(o.contextVersion!=="ninsei-order-v3"||co(o.quoteVersion,"payload.quoteVersion")!==10)throw new u("quote-refused",{step:"answer",why:"version"});if(!St(o.factory,n.terms.order.factory))throw new u("quote-refused",{step:"answer",why:"factory"});if(!St(e.provider,n.terms.maker))throw new u("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 u("quote-refused",{step:"context",why:"other-terms"});let a=p0({...i,signature:o.quoteSignature});if(a===null)throw new u("quote-refused",{step:"signature",why:"invalid"});if(!St(a,i.quoteKey))throw new u("quote-refused",{step:"signature",why:"key"});let c=Math.floor((r===null?Date.now():r)/1e3);OE(i,n.terms,c);let l=n.terms.side,d=l==="ask"?n.edViewPointClient:n.edViewPointNode,f=l==="ask"?n.edViewPointNode:n.edViewPointClient;if(!St(o.edViewPointLocker,d)||!St(o.edViewPointClaimer,f))throw new u("quote-refused",{step:"answer",why:"view-points"});let p=o.nodeHalf;if(!p||typeof p!="object"||!p.proof)throw new u("quote-refused",{step:"answer",why:"node-half"});if(l==="ask"&&(!St(p.commitHalf,i.commitHalfClaimer)||!St(p.edPoint,i.edPointClaimer)))throw new u("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 RE=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 u("bad-input",{field:t})},PE=(e,t)=>(e==null?"":On(e,"relay"))===(t==null?"":On(t,"relay"));async function S0({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 u("bad-input",{field:"relayUrl"});if(!/^https:\/\//i.test(s))throw new u("bad-input",{field:"relayUrl",why:"not-https"});let a=await f0(i),c=JSON.stringify({version:1,payload:a.payload,...t?{partner:String(t)}:{}}),l=it({apiBase:s,fetchImpl:n,timeoutMs:r}),d=null;try{let I=await l.tryJson("/v1/relay");if(!I||I.ok!==!0||!I.body||typeof I.body!="object")throw new u("quote-refused",{step:"relay-info",why:"unavailable"});d=I.body}catch(I){throw I instanceof u?I:new u("quote-refused",{step:"relay-info",why:"unavailable"})}let f=()=>l.tryJson("/v1/quote",{method:"POST",headers:{"content-type":"application/json"},body:c}),p;try{p=await f()}catch(I){if(o>0&&I&&I.code==="server-unavailable"&&I.params&&I.params.why==="timeout")p=await f();else throw I}if(!p.ok){let I=p.body&&p.body.code?String(p.body.code):null;throw I&&RE.has(I)?new u("quote-refused",{step:"relay",code:I,status:p.status}):new u("server-unavailable",{step:"relay",status:p.status})}let h=p.body&&p.body.answer,w=null;try{w=p.body?Number(p.body.version):null}catch{w=null}if(!p.body||w!==1||!h)throw new u("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 u("quote-refused",{step:"answer",why:"relay"});if(!PE(h.relayId,p.body.relay))throw new u("quote-refused",{step:"answer",why:"relay"});g0({forwarded:p.body.forwarded,relayKey:d.relayKey,payload:a.payload,provider:i.features.provider,requestHash:h.requestHash===void 0||h.requestHash===null?"":h.requestHash});let b=k0({answer:h,features:i.features,request:a}),y=On(d.feeRecipient===void 0||d.feeRecipient===null?"":d.feeRecipient,"relay.feeRecipient").toLowerCase(),v=On(b.quote.feeRecipient===void 0||b.quote.feeRecipient===null?"":b.quote.feeRecipient,"quote.feeRecipient").toLowerCase();if(!y||y!==v)throw new u("quote-refused",{step:"fee",why:"fee-recipient"});if(!t&&On(d.feeBps===void 0||d.feeBps===null?"":d.feeBps,"relay.feeBps")!==On(b.quote.feeBps===void 0||b.quote.feeBps===null?"":b.quote.feeBps,"quote.feeBps"))throw new u("quote-refused",{step:"fee",why:"fee-bps"});if(d.relayId===void 0||d.relayId===null||On(d.relayId,"relay.relayId")!==On(p.body.relay,"relay"))throw new u("quote-refused",{step:"relay-info",why:"relay"});return{...b,relayUrl:s,relay:p.body.relay??null,offered:p.body.offered??null,forwarded:p.body.forwarded??null,answer:h}}me();var ki=e=>{let t=Number(e);return Number.isSafeInteger(t)?t:null};function vt(e,{side:t=null,field:n="readyWindow"}={}){if(!e||typeof e!="object"||Array.isArray(e))throw new u("bad-input",{field:n,why:"missing"});let r=ki(e.readyMinSeconds),o=ki(e.readyMaxSeconds);if(r===null||o===null||r<=0||o<r)throw new u("bad-input",{field:n,why:"bounds"});if(t!==null&&e.side!==void 0&&String(e.side)!==String(t))throw new u("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:ki(e.settlementMinSeconds),settlementMaxSeconds:ki(e.settlementMaxSeconds),quoteTtlSeconds:ki(e.quoteTtlSeconds)})}function v0(e){let t=vt(e),n=t.readyMaxSeconds-t.readyMinSeconds;return Math.max(0,Math.min(n,t.readyMinSeconds))}function E0(e){let t=vt(e),n=t.readyMaxSeconds-t.readyMinSeconds,r=t.readyMinSeconds-n;return Math.max(0,r>0?r:t.readyMinSeconds)}function eu(e,t=300){let n=vt(e),r=Number.isFinite(Number(t))&&Number(t)>=0?Number(t):300;return(n.readyMaxSeconds+r)*1e3}function Ra({validUntil:e,nowSec:t,side:n="ask",marginSec:r=30,prepSec:o=15}={}){let i=Number(e),s=Number(t),a=Number(r),c=Number(o);if(!Number.isSafeInteger(i)||!Number.isSafeInteger(s))return{ok:!1,code:"quote-too-short",remainingSec:null,marginSec:null,prepSec:null,confirmBySec:null};let l=i-s;if(n==="bid"){let h=l>0;return{ok:h,code:h?null:"quote-too-short",remainingSec:l,marginSec:0,prepSec:0,confirmBySec:i}}if(!Number.isSafeInteger(a)||!Number.isSafeInteger(c)||a<0||c<0)return{ok:!1,code:"quote-too-short",remainingSec:l,marginSec:null,prepSec:null,confirmBySec:null};let f=a+c,p=l>f;return{ok:p,code:p?null:"quote-too-short",remainingSec:l,marginSec:a,prepSec:c,confirmBySec:i-f}}_e();var I0=e=>new TextEncoder().encode(String(e)),Si=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},HE=()=>Si(te(I0("providerOf(address)")).slice(0,4)),A0=e=>HE()+"0".repeat(24)+String(e).toLowerCase().replace(/^0x/,""),FE=()=>Si(te(I0("factoryOf(address)")).slice(0,4)),LE=e=>FE()+"0".repeat(24)+String(e).toLowerCase().replace(/^0x/,""),N0=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(),tu=e=>{let t=String(e??"").replace(/^0x/,"");return t.length>=40?"0x"+t.slice(-40).toLowerCase():null},DE=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},ME=(e,t,n)=>{let r=n&&n.settlement&&n.settlement.chain,o=DE(n);if(!o&&!r)return;let i=String(e&&e.cashier||"").toLowerCase();o||Q("quote-cashier-mismatch",{step:t,why:"no-pinned-cashier",got:i||null}),i!==o&&Q("quote-cashier-mismatch",{step:t,got:i||null,want:o})},UE=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 _0({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=rl({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 nu({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,fetchImpl:l=null}){let d=Array.isArray(s)&&s.length?s.map(p=>String(p).toLowerCase()).filter(Boolean):null,f=Array.isArray(a)&&a.length?a.map(p=>String(p).toLowerCase()).filter(Boolean):null;return{async firmRelay(p){(!p||typeof p!="object")&&Q("bad-input",{field:"request"});let h=p.features,w=p.order&&typeof p.order=="object"?{...p.order}:null;(!h||typeof h!="object")&&Q("bad-input",{field:"features"}),w||Q("bad-input",{field:"order"});let b=String(p.side||"");b!=="ask"&&b!=="bid"&&Q("bad-input",{field:"side"});let y=String(h.provider||"").toLowerCase(),v=String(h.registry||"").toLowerCase();(!/^0x[0-9a-f]{40}$/.test(y)||y===fo)&&Q("bad-input",{field:"features.provider"}),(!/^0x[0-9a-f]{40}$/.test(v)||v===fo)&&Q("bad-input",{field:"features.registry"});let I=e&&e.settlement&&e.settlement.chain&&e.settlement.chain.escrow&&e.settlement.chain.escrow.registry;I&&!po(v,I)&&Q("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)&&Q("bad-input",{field:"features.quoteKey"}),typeof n!="function"&&Q("quote-registry-unchecked",{step:"features",why:"no-chain-read",registry:v});let g=null;try{g=tu(await n({to:v,data:A0(h.quoteKey)}))}catch{Q("quote-registry-unchecked",{step:"features",why:"read-failed",registry:v})}(g===null||g===fo)&&Q("quote-key-unknown",{step:"registry",registry:v,quoteKey:h.quoteKey}),po(g,h.provider)||Q("quote-provider-mismatch",{step:"registry",got:g,want:h.provider});let T=b==="bid"?w.claimer:w.locker;c&&typeof T=="string"&&c.has(T.toLowerCase())&&Q("address-denied",{step:"order-quote"}),b==="ask"?(w.claimer&&!po(w.claimer,y)&&Q("bad-input",{field:"order.claimer"}),w.claimer=y):(w.locker&&!po(w.locker,y)&&Q("bad-input",{field:"order.locker"}),w.locker=y);let A=Number(w.chainId);(!Number.isSafeInteger(A)||A<=0)&&Q("bad-input",{field:"order.chainId"});let B=Array.isArray(h.firmWindows)?h.firmWindows.filter(ie=>ie&&ie.side===b):[],P=[...new Set(B.map(ie=>ie.market).filter(ie=>typeof ie=="string"&&ie))],O=p.market!==void 0?String(p.market):P.length===1?P[0]:null;O||Q("bad-input",{field:"market"});let j=B.find(ie=>ie.market===O)||null;j||Q("quote-refused",{step:"features",why:"window"});let D=vt(j,{side:b,field:"features.firmWindows"}),X=p.xmrNetwork!==void 0?String(p.xmrNetwork):j.xmrNetwork;X||Q("bad-input",{field:"xmrNetwork"}),(p.xmrAmount===void 0||p.xmrAmount===null||p.xmrAmount==="")&&Q("bad-input",{field:"xmrAmount"});let H=p.claimTip===void 0||p.claimTip===null?"0":String(p.claimTip),m=typeof p.recoveryKey=="string"?p.recoveryKey:p.recoveryKey&&typeof p.recoveryKey.mnemonic=="string"?p.recoveryKey.mnemonic:null;m||Q("bad-input",{field:"recoveryKey"});let k=p.recoverySalt!==void 0&&p.recoverySalt!==null;(!w.factory||!/^0x[0-9a-f]{40}$/i.test(String(w.factory)))&&Q("bad-input",{field:"order.factory"});let x=null;try{x=qt(k?p.recoverySalt:w.salt)}catch{Q("bad-input",{field:"recoverySalt"})}if(k){let ie=null;try{ie=qt(w.salt)}catch{Q("bad-input",{field:"recoverySalt",why:"order-salt"})}x!==ie&&Q("bad-input",{field:"recoverySalt",why:"order-salt"})}let C=sr({mnemonic:m,chainId:A,factory:w.factory,salt:x}),U={kind:"salt-v2",salt:x},W=await Iy(w,{spendHalf:C.spendHalf,viewHalf:C.viewHalf}),Y=Pe.Point.fromHex(W.side.proof.XA),N={commitHalf:Si(te(Y.toBytes(!1).slice(1))),edPoint:W.side.pub.ed,proof:W.side.proof},S=await S0({relayUrl:p.relayUrl,partner:p.partner,fetchImpl:p.fetchImpl||l,timeoutMs:p.timeoutMs,features:h,terms:{market:O,side:b,maker:y,registry:v,xmrNetwork:X,order:w,xmrAmount:String(p.xmrAmount),claimTip:H},clientHalf:N,edViewPointClient:W.side.viewPub,edViewPointNode:C.makerViewPoint,nodeViewScalar:C.makerViewHalf,clientViewScalar:C.viewHalf,side:b}),_=S.quote;ME(_,"relay",e);let R=S.nodeHalf;await Hd({context:W.context,side:W.side,counterparty:b==="ask"?{proof:R.proof,edPub:_.edPointClaimer,commitHalfClaimer:_.commitHalfClaimer,viewPoint:S.edViewPointClaimer,viewHalf:C.makerViewHalf}:{proof:R.proof,edPub:R.edPoint,commitHalfClaimer:R.commitHalf,viewPoint:S.edViewPointLocker,viewHalf:C.makerViewHalf}});let M=b==="ask"?_.edPointClaimer:R.edPoint,K=b==="ask"?S.edViewPointClaimer:S.edViewPointLocker,G=eo({ownSpendHalf:C.spendHalf,ownViewHalf:C.viewHalf,otherSpendPoint:M,otherViewPoint:K,network:X}),Z=b==="ask"?{commitHalfLocker:N.commitHalf,edPointLocker:W.side.pub.ed,edViewPointLocker:W.side.viewPub}:{commitHalfLocker:R.commitHalf,edPointLocker:R.edPoint,edViewPointLocker:S.edViewPointLocker},V=null;try{let ie=await n({to:_.factory,data:He.encodePredict({...S.orderQuote,...Z,signature:S.orderQuote.signature})});V=He.decodeAddress(ie)}catch{Q("quote-escrow-unchecked",{step:"factory",why:"predict-failed",factory:_.factory})}i&&i(y)!==!0&&Q("quote-provider-not-allowed",{step:"policy",provider:y}),typeof n!="function"&&Q("quote-registry-unchecked",{step:"registry",why:"no-chain-read"});let J=null;try{J=tu(await n({to:v,data:A0(_.quoteKey)}))}catch{Q("quote-registry-unchecked",{step:"registry",why:"read-failed",registry:v})}(J===null||J===fo)&&Q("quote-key-unknown",{step:"registry",registry:v,quoteKey:_.quoteKey}),po(J,_.provider)||Q("quote-provider-mismatch",{step:"registry",got:J,want:_.provider});let re=null;try{re=tu(await n({to:v,data:LE(_.provider)}))}catch{Q("quote-factory-unchecked",{step:"factory",why:"read-failed",registry:v})}if((re===null||re===fo)&&Q("quote-factory-unknown",{step:"factory",registry:v,provider:_.provider}),po(re,_.factory)||Q("quote-factory-mismatch",{step:"factory",got:_.factory,want:re}),d){typeof r!="function"&&Q("quote-factory-unchecked",{step:"factory",why:"no-code-read"});let ie=null;try{ie=await r(_.factory)}catch{Q("quote-factory-unchecked",{step:"factory",why:"code-read-failed",factory:_.factory})}let q=Si(te(N0(ie)||new Uint8Array(0)));d.includes(q)||Q("quote-factory-code-unknown",{step:"factory",factory:_.factory,codeHash:q})}if(f){typeof n!="function"&&Q("quote-factory-unchecked",{step:"factory",why:"no-chain-read"}),typeof r!="function"&&Q("quote-factory-unchecked",{step:"factory",why:"no-code-read"});let ie=await He.verifyFactoryImplementationOnChain({factory:_.factory,read:n,code:q=>r(q),policy:f,hashCode:q=>Si(te(N0(q)||new Uint8Array(0)))});if(!ie.ok){let q=ie.why==="implementation-code-unknown"||ie.why==="implementation-code-mismatch"||ie.why==="implementation-has-no-code";Q(q?"quote-factory-code-unknown":"quote-factory-unchecked",{step:"factory",why:ie.why,factory:_.factory,implementation:ie.implementation||null})}}let E=(()=>{try{return _0({claimTipWei:_.claimTip})}catch{return{ok:!0,tipWei:"0"}}})();if(!E.ok&&E.code==="quote-tip-unreadable"&&Q("quote-field-unbound",{step:"claimTip",field:"claimTip"}),E.tipWei!=="0"){typeof o!="function"&&Q("quote-tip-unchecked",{step:"claimTip",why:"no-block-read"});let ie=null;try{ie=await o("latest")}catch{Q("quote-tip-unchecked",{step:"claimTip",why:"block-read-failed"})}let q=ie&&(ie.baseFeePerGas!==void 0?ie.baseFeePerGas:ie.baseFeeWei),oe=UE(ie),se=_0({claimTipWei:_.claimTip,baseFeeWei:q,priorityFeeWei:oe});se.ok||Q(se.code,{step:"claimTip",...se})}let F=S.orderQuote&&S.orderQuote.xmrAmount!==void 0&&S.orderQuote.xmrAmount!==null?String(S.orderQuote.xmrAmount):null;F||Q("quote-field-unbound",{step:"xmrAmount",field:"orderQuote.xmrAmount"});let L=p.market&&String(p.market).includes(":")?String(p.market).split(":").slice(1).join(":"):null,z=String(w.asset||L||"").trim(),$=Math.floor(Number(t())/1e3),ee=Ra({validUntil:_.validUntil,nowSec:$,side:b});ee.ok||Q("quote-too-short",{step:"answer",side:b,validUntil:Number.isFinite(Number(_.validUntil))?Number(_.validUntil):null,now:$,remainingSec:ee.remainingSec,marginSec:ee.marginSec,prepSec:ee.prepSec,confirmBySec:ee.confirmBySec});let ne={..._,viewHalfClaimer:C.makerViewHalf,xmrAmount:F,readyWindow:D,escrow:V,remainingSec:ee.remainingSec,confirmBySec:ee.confirmBySec,...z?{asset:z,token:z.toLowerCase()}:{},..._.nonce!==void 0&&_.nonce!==null?{id:String(_.nonce)}:{}},le={proof:R.proof,edPointClaimer:b==="ask"?_.edPointClaimer:R.edPoint,commitHalfClaimer:b==="ask"?_.commitHalfClaimer:R.commitHalf,viewHalfClaimer:C.makerViewHalf,viewPoint:b==="ask"?S.edViewPointClaimer:S.edViewPointLocker},de={...w,xmrAmount:F};return{...S,quote:ne,order:de,readyWindow:D,startRequest:{quote:ne,order:de,orderQuote:S.orderQuote,counterparty:le,recoveryKey:p.recoveryKey,recoverySalt:w.salt,escrow:V},remainingSec:ee.remainingSec,confirmBySec:ee.confirmBySec,counterparty:le,viewHalfClaimer:C.makerViewHalf,viewHalfPoint:C.makerViewPoint,jointAddress:G.address,escrow:V,recovery:U}}}}var jE=e=>{let t=e&&typeof e=="object"?e:{},{reason:n,kind:r,ok:o,checked:i,blocks:s,...a}=t;return{code:Fh(r),ok:o===!0,checked:i!==!1,blocks:s===!0,kind:typeof r=="string"?r:"unknown",params:a}},T0=(...e)=>e.some(t=>t!=null&&t!==""),Ot=(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 B0({config:e,wallet:t,limits:n={}}){return async function(o={},i={}){let s=pe.SIGNING_GUARDS||{},a=Number.isFinite(i.nowMs)?i.nowMs:Date.now(),c=o&&typeof o=="object"?o:{},l=!!i.tokenIsNative,d=e.evmNetwork,p=[Ot(ke.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}),Ot(ke.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}),Ot(ke.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}),Ot(ke.payBalanceVerdict,{payBalanceWei:i.payBalanceWei??null,payAmountWei:i.payAmountWei??null,symbol:l?d.nativeSymbol:c.token||null,decimals:Number.isFinite(i.decimals)?i.decimals:18}),Ot(ke.gasReserveVerdict,{nativeBalanceWei:i.nativeBalanceWei??null,requiredNativeWei:i.requiredNativeWei??null,gasReserveWei:i.gasReserveWei??null,symbol:d.nativeSymbol,decimals:18}),Ot(ke.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}),Ot(ke.networkGateVerdict,{walletChainId:t.status().chainId,selectedChainId:d.chainId,settlementChainId:d.chainId,selectedChainName:d.name}),Ot(ke.counterpartyVerdict,{standIn:i.standIn===!0,liveChain:i.liveChain===!0,network:e.evmNetwork.id,chainId:d.chainId}),Ot(ke.escrowStateVerdict,{status:i.escrowStatus??null,error:null,address:i.escrowAddress??null}),...T0(i.point,i.commit)?[Ot(ke.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})]:[],...T0(i.slots)?[Ot(ke.liveOrderSlotsVerdict,{slots:i.slots??null,expect:i.slotsExpect??null,readError:i.slotsReadError??null})]:[]].map(jE),h=[...new Set(p.filter(w=>w.blocks).map(w=>w.code))];return{ok:h.length===0,blockedBy:h,checks:p}}}me();var C0=e=>typeof e=="string"?e:e&&typeof e.contents=="string"?e.contents:null;function ru(){return{async open(e,t){let n=C0(e);if(n===null)throw new u("bad-input",{field:"file"});let r;try{r=JSON.parse(n)}catch{throw new u("recovery-failed",{stage:"parse"})}let o;try{o=await ys.restoreFromFile(r,t)}catch{throw new u("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=C0(e.file);if(t===null)throw new u("bad-input",{field:"file"});if(typeof e.passphrase!="string")throw new u("bad-input",{field:"passphrase"});let n;try{n=JSON.parse(t)}catch{throw new u("recovery-failed",{stage:"parse"})}let r;try{r=await at.decryptFile(n,e.passphrase),at.validatePayload(r)}catch{throw new u("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}}}}me();var Pa=Object.keys(pe.SCENARIO_LABELS||{});function O0(){let e=Pa[0]||null,t=1,n=0;return{scenarios:()=>Pa.slice(),apply(r){Pa.includes(r)||Q("bad-input",{field:"scenario",known:Pa}),e=r},speed(r){let o=Number(r);(!Number.isFinite(o)||o<=0)&&Q("bad-input",{field:"speed"}),t=o},advance(r){let o=Number(r);Number.isFinite(o)||Q("bad-input",{field:"ms"}),n+=o},debug:()=>({scenario:e,speed:t,advancedMs:n})}}me();var WE=["connect","disconnect","address","chainId","subscribe","driver"],R0=e=>e&&Kr.includes(e.code)?e.code:"unknown",ou="monero",vi={token:"xmr",symbol:"XMR",decimals:12},KE=2;function P0({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,d]=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:d===void 0?null:d,chainMatches:f&&t.sameChain(d,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")&&Q("bad-input",{field:"adapter"});let l=WE.filter(f=>typeof c[f]!="function");l.length&&Q("bad-input",{field:"adapter",missing:l}),(typeof c.vm!="string"||!c.vm)&&Q("bad-input",{field:"adapter.vm"});let d=[e.vm,ou];d.includes(c.vm)||Q("bad-input",{field:"adapter.vm",expected:e.vm,accepted:d,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||Q("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 u(R0(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||Q("wallet-not-connected"),Number.isFinite(Number(c))||Q("bad-input",{field:"chainId"}),(n.vm!==e.vm||typeof n.switchChain!="function")&&Q("not-implemented",{surface:"wallet.switchChain",vm:n.vm,stage:KE});try{await n.switchChain(Number(c))}catch(d){throw new u(R0(d),{vm:n.vm})}let l=await s();return l.chainMatches||Q("wrong-chain",{got:l.chainId,want:t.walletChainId(e)}),l},async balances(c){n||Q("wallet-not-connected");let l=r.connected?r:await s(!1);if(l.connected||Q("wallet-not-connected"),n.vm===ou){let w=(Array.isArray(c)&&c.length?c.map(y=>String(y).toLowerCase()):[vi.token]).find(y=>y!==vi.token);w!==void 0&&Q("bad-input",{field:"tokens",unknown:w}),typeof n.unlockedBalance!="function"&&Q("not-implemented",{surface:"wallet.balances",vm:ou});let b=BigInt(await n.unlockedBalance()).toString();return[{token:vi.token,symbol:vi.symbol,decimals:vi.decimals,amount:b}]}l.chainMatches||Q("wrong-chain",{got:l.chainId,want:t.walletChainId(e)}),typeof t.balances!="function"&&Q("not-implemented",{surface:"wallet.balances",vm:e.vm});let d=e.tokens||[],f=Array.isArray(c)&&c.length?c.map(h=>String(h).toLowerCase()):d.map(h=>h.id),p=[];for(let h of f){let w=d.find(b=>b.id===h);w||Q("bad-input",{field:"tokens",unknown:h}),p.push(w)}return t.balances({driver:n.driver(),address:l.address,tokens:p})},subscribe(c){return typeof c!="function"&&Q("bad-input",{field:"handler"}),o.add(c),()=>o.delete(c)},driver:()=>n?n.driver():null}}me();me();_e();function VE(e=null,t=null){if(t&&t.spendHalf&&t.viewHalf)return _y(e,t).side;if(e!=null)return Cd(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 iu(e,{order:t=null,side:n=null,store:r=null}={}){if(!e||typeof e!="object")throw new u("bad-input",{field:"input"});let o=n||VE(t),i=null;try{i=fe.createSwap(e,r)}catch{throw new u("bad-input",{field:"input"})}let s={...i.escrow||{},half:Jt(o.half),viewHalf:Jt(o.viewHalf),edPointLocker:be(o.pub.ed),edViewPointLocker:be(o.viewPub)};if(e.expectedAtomic!==void 0&&e.expectedAtomic!==null){let l;try{l=BigInt(String(e.expectedAtomic))}catch{throw new u("bad-input",{field:"expectedAtomic"})}if(l<=0n)throw new u("bad-input",{field:"expectedAtomic"});s.expectedAtomic=l.toString()}e.chainId!==void 0&&e.chainId!==null&&(s.chainId=String(e.chainId)),e.factory!==void 0&&e.factory!==null&&(s.factory=String(e.factory)),o.enc&&o.enc.pub&&(s.encPub=be(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 u("storage-unavailable",{step:"save-swap"})}return{swap:a,side:o,missing:["counterparty-half"],nextStep:"order"}}me();me();_e();me();_e();var zE="Declined",XE=()=>`${zE}(${["address"].join(",")})`,YE=e=>{let t="0x";for(let n of e)t+=n.toString(16).padStart(2,"0");return t},mo=YE(te(XE())),GE="declined",Fa="compliance",nn="declined",QE=["declined","terminal","code","source","at","checked"],H0=e=>{let t={};for(let n of QE)t[n]=e[n]===void 0?null:e[n];return t},F0=({source:e=null,at:t=null}={})=>H0({declined:!0,terminal:nn,code:Fa,source:e,at:t,checked:!0}),Ha=({source:e=null,at:t=null,checked:n=!0}={})=>H0({declined:!1,terminal:null,code:null,source:e,at:t,checked:n});function su(e,{escrow:t=null,at:n=null}={}){if(!Array.isArray(e))throw new u("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()===mo)return F0({source:"event",at:n})}return Ha({source:"event",at:n})}function ZE(e,{at:t=null}={}){if(!e||typeof e!="object")return Ha({source:"status",at:t,checked:!1});for(let n of[e,e.userStatus])if(!(!n||typeof n!="object")&&String(n.status||"")===GE&&String(n.code||"")===Fa)return F0({source:"status",at:t});return Ha({source:"status",at:t})}function L0({logs:e=void 0,status:t=void 0,escrow:n=null,at:r=null}={}){let o=Array.isArray(e)?su(e,{escrow:n,at:r}):null;if(o&&o.declined)return o;let i=t&&typeof t=="object"?ZE(t,{at:r}):null;return i&&i.declined?i:o||i||Ha({checked:!1,at:r})}async function qE({address:e,topics:t=[mo],fromBlock:n="earliest",toBlock:r="latest"}={}){if(typeof e!="string"||!/^0x[0-9a-fA-F]{40}$/.test(e))throw new u("bad-input",{field:"logs.address"});let o=null;try{o=typeof He.currentProvider=="function"?He.currentProvider():null}catch{o=null}if(!o||typeof o.request!="function")throw new u("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 u("server-unavailable",{step:"logs",why:"bad-response"});return i}var La=e=>typeof e=="function"?e:qE,Da=(e,t="earliest")=>{let n=Number(e);return!Number.isFinite(n)||n<0?t:"0x"+Math.trunc(n).toString(16)};var{chainById:cC,DEFAULT_CHAIN:lC,MONERO:dC}=pe,{fundOrderLive:uC,newSecret:fC,sendTransaction:au,readContract:Ei}=He,{encodeClaim:JE,encodeRefund:eA,encodeMarkReady:D0,encodeStatus:tA,encodeT1:nA,encodeTermsHash:rA,encodeRead:Ma,decodeUint64:M0,decodeBytes32:cu,decodeStatus:oA}=Mr,{liveOrderSlotsVerdict:iA,counterpartyVerdict:pC}=ke,{orderContextString:mC}=xn,{requestOrderQuote:hC,checkOrderQuoteShape:wC}=Ms,{CLAIM_GAS_LIMIT:sA}=xs;async function Rn(e,t={}){if(!e)throw new u("bad-input",{field:"escrow"});let r=await(t.call||Ei)({to:e,data:tA(),block:t.blockTag||"latest"});return oA(r)}async function j0(e,t={}){if(typeof e!="string"||!e)throw new u("bad-input",{field:"escrow"});let n=La(t.logs),r=t.fromBlock===void 0?"earliest":Da(t.fromBlock),o=await n({address:e,topics:[mo],fromBlock:r,toBlock:"latest"});return su(o,{escrow:e,at:Number.isFinite(Number(t.at))?Number(t.at):null})}async function fr(e,t={}){if(!e)throw new u("bad-input",{field:"escrow"});let n=t.call||Ei,r=t.blockTag||"latest",[o,i,s]=await Promise.all([n({to:e,data:nA(),block:r}),n({to:e,data:rA(),block:r}),n({to:e,data:Ma("readyBy"),block:r})]);for(let[a,c]of[[o,"t1()"]])if(String(a||"").replace(/^0x/,"").length===0)throw new u("bad-input",{field:"escrow",why:"no-contract"});return{t1:M0(o,"t1()"),termsHash:cu(i,"termsHash()"),readyBy:M0(s,"readyBy()")}}async function aA(e,t={}){let n=t.call||Ei;if(!e)throw new u("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:Ma(a),block:o}))),s={};return r.forEach((a,c)=>{s[a]=cu(i[c],a+"()")}),{slots:s}}catch(o){return{error:String(o&&o.message||o)}}}async function Ai(e,t,n="signature",r={}){if(!t)throw new u("bad-input",{field:"expect"});let o=await aA(e,r),i=iA({slots:o.slots,readError:o.error,expect:t});if(i.blocks)throw new u("contract-reverted",{step:n,why:"slots-mismatch"});return i}async function lu(e,t,n){let r=await Rn(e,n);if(!r.isFunded||r.isClaimed||r.isRefunded)throw new u("contract-reverted",{step:t,why:"closed"})}async function du(e,t,n,r=null){if(typeof n.blockTime!="function")return;let o=n.call||Ei,i=n.blockTag||"latest",[s,a]=await Promise.all([o({to:e,data:Ma("ready"),block:i}),fr(e,n)]),c=BigInt(s)!==0n,l=Number(r===null?await n.blockTime():r);if(!Number.isSafeInteger(l)||l<=0)throw new u("contract-reverted",{step:t,why:"clock-unreadable"});let d=60;if(t==="claim"){if(l+d>=Number(a.t1))throw new u("contract-reverted",{step:t,why:"window-closed"});if(!c&&l<Number(a.readyBy))throw new u("contract-reverted",{step:t,why:"not-ready"})}else if(t==="refund"){if(l<Number(a.t1)&&(l+d>=Number(a.readyBy)||c))throw new u("contract-reverted",{step:t,why:"too-early"})}else if(t==="mark-ready"){if(c)throw new u("contract-reverted",{step:t,why:"already-ready"});if(l+d>=Number(a.readyBy))throw new u("contract-reverted",{step:t,why:"ready-window-closed"})}}async function cA(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 u("contract-reverted",{step:n,why:"simulation",detail:typeof s=="string"?s.slice(0,200):null}):i}}var U0=e=>String(e??"").replace(/^0x/i,"").toLowerCase().slice(-40);async function W0(e,t,n,r,o){let i=r==="claim"?"halfClaimer":"halfLocker",s;try{s=U0(Lr(BigInt(t),Pe,te))}catch{throw new u("bad-input",{field:i})}let a=o.call||Ei,c;try{c=cu(await a({to:e,data:Ma(n),block:o.blockTag||"latest"}),n+"()")}catch{throw new u("contract-reverted",{step:r,why:"slots-unreadable"})}if(s!==U0(c))throw new u("contract-reverted",{step:r,why:"half-mismatch"})}async function K0({escrow:e,halfClaimer:t,expect:n,onStep:r,deps:o={}}){if(!e)throw new u("bad-input",{field:"escrow"});if(!t)throw new u("bad-input",{field:"halfClaimer"});return await lu(e,"claim",o),await du(e,"claim",o),await Ai(e,n,"claim",o),await W0(e,t,"commitHalfClaimer","claim",o),r?.("confirm-claim"),{hash:await(o.send||au)({to:e,data:JE(t),gas:sA})}}async function V0({escrow:e,halfLocker:t,onStep:n,expect:r=null,deps:o={}}){if(!e)throw new u("bad-input",{field:"escrow"});if(!t)throw new u("bad-input",{field:"halfLocker"});return await lu(e,"refund",o),await du(e,"refund",o),r&&await Ai(e,r,"refund",o),await W0(e,t,"commitHalfLocker","refund",o),n?.("confirm-refund"),{hash:await(o.send||au)({to:e,data:eA(t),gas:250000n})}}async function $0({escrow:e,expect:t,onStep:n,deps:r={}}){if(!e)throw new u("bad-input",{field:"escrow"});return await lu(e,"mark-ready",r),await du(e,"mark-ready",r),await Ai(e,t,"mark-ready",r),await cA(e,D0(),"mark-ready",r),n?.("confirm-mark-ready"),{hash:await(r.send||au)({to:e,data:D0(),gas:120000n})}}me();async function ho(e,t,n="send"){let r=Number(t);if(!Number.isSafeInteger(r)||r<=0)throw new u("bad-input",{field:"chainId",step:n});if(!e||typeof e.chainId!="function")throw new u("bad-input",{field:"wallet.chainId",step:n});let o=null;try{o=Number(await e.chainId())}catch{throw new u("wrong-chain",{vm:"evm",step:n,want:r,got:null,why:"unreadable"})}if(!Number.isSafeInteger(o)||o<=0)throw new u("wrong-chain",{vm:"evm",step:n,want:r,got:null,why:"unreadable"});if(o!==r)throw new u("wrong-chain",{vm:"evm",step:n,want:r,got:o});return r}var lA=["commitHalfLocker","commitHalfClaimer","edPointLocker","edPointClaimer","edViewPointLocker"],dA=e=>typeof e=="string"&&e&&!/^0x/i.test(e)?"0x"+e:e;function z0(e){if(!e||typeof e!="object")throw new u("bad-input",{field:"request"});let t={...e};for(let n of lA)t[n]=dA(t[n]);return t}function uA(e){if(!e||typeof e!="object")throw new u("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 u("bad-input",{field:"terms",missing:n});try{return Mr.orderTerms(z0(e))}catch{let o=Math.floor(Date.now()/1e3);throw Number(e.readyBy)<=o?new u("bad-input",{field:"readyBy",why:"not-in-future"}):Number(e.t1)<=Number(e.readyBy)?new u("bad-input",{field:"t1",why:"not-after-readyBy"}):new u("bad-input",{field:"terms"})}}var fA=e=>String(e??"").replace(/0x[0-9a-fA-F]{64}/g,"0x<redacted>").slice(0,200),pA=/fetch failed|network|ECONN|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|socket|timeout|HTTP \d|status \d|non-ok/i,mA=e=>pA.test(e);async function X0(e,t,n={}){if(!e||typeof e!="object")throw new u("bad-input",{field:"request"});if(!t||typeof t.send!="function"||typeof t.receipt!="function")throw new u("bad-input",{field:"wallet",missing:["send","receipt"]});let r=z0(e);uA({...r,amount:r.amountWei});let o=He;await ho(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=fA(s&&s.message||s);throw new u(mA(a)?"server-unavailable":"bad-input",{step:"fund-order",why:a})}}_e();me();var wA=(e,t)=>t.filter(n=>e[n]===void 0||e[n]===null||e[n]===""),fu=e=>{let t=["send","receipt"],n=e?t.filter(r=>typeof e[r]!="function"):t;if(n.length)throw new u("bad-input",{field:"wallet",missing:n});return e};function yA({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 pu=(e,t)=>{if(!e||typeof e!="object")throw new u("bad-input",{field:"request"});let n=wA(e,["escrow","expect",...t]);if(n.length)throw new u("bad-input",{field:"request",missing:n});return e},mu=async(e,t)=>{try{return await t()}catch(n){throw n&&typeof n.code=="string"?n:new u("contract-reverted",{step:e})}};function Ni({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 u("wallet-not-connected",{surface:"actions.read"})}:async({to:l,data:d,from:f})=>{let p=f?{to:l,data:d,from:f}:{to:l,data:d},h=await c.request({method:"eth_call",params:[p,"latest"]});if(typeof h!="string"||!h.startsWith("0x"))throw new u("contract-reverted",{surface:"actions.read"});return h}},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]}),d=Number(l&&l.timestamp);return Number.isSafeInteger(d)&&d>0?d: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 u("bad-input",{field:"wallet.address",step:c});return l},s=(a,c,l)=>({call:r(a),from:l,send:d=>a.send({...d,chainId:c,from:l}),receipt:d=>a.receipt(d),blockTime:o(a)});return{async markReady(a,c){pu(a,[]),fu(c);let{escrow:l,expect:d,onStep:f}=a,p=await i(c,"mark-ready");return await ho(c,d.chainId,"mark-ready"),await mu("mark-ready",()=>$0({escrow:l,expect:d,onStep:f,deps:s(c,d.chainId,p)}))},async claim(a,c){pu(a,["halfClaimer"]),fu(c);let{escrow:l,halfClaimer:d,expect:f,onStep:p}=a,h=await i(c,"claim"),w=yA({sender:h,claimer:a.claimer||f&&f.claimer});if(!w.ok)throw new u(w.code,{field:w.field,why:w.why,surface:"actions.claim"});return await ho(c,f.chainId,"claim"),await mu("claim",()=>K0({escrow:l,halfClaimer:d,expect:f,onStep:p,deps:s(c,f.chainId,h)}))},async refund(a,c){pu(a,["halfLocker"]),fu(c);let{escrow:l,halfLocker:d,expect:f,onStep:p}=a,h=await i(c,"refund");return await ho(c,f.chainId,"refund"),await mu("refund",()=>V0({escrow:l,halfLocker:d,expect:f,onStep:p,deps:s(c,f.chainId,h)}))}}}me();me();var pr=20;function hu(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<0)throw new u("bad-input",{field:"height"});return Math.floor(t/pr)}function wu(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<0)throw new u("bad-input",{field:"slice"});return t*pr}function Y0(e){return wu(e)+pr-1}var Ua=e=>{let t=String(e||"").replace(/^0x/,"").toLowerCase();return/^[0-9a-f]{64}$/.test(t)?t:null};function G0(e,{network:t,index:n,tipHeight:r=null}){if(!e||typeof e!="object")throw new u("xmr-no-nodes",{why:"bad-witness-slice"});if(Number(e.version)!==1)throw new u("xmr-no-nodes",{why:"bad-witness-version"});if(String(e.network)!==String(t))throw new u("xmr-no-nodes",{why:"witness-network"});if(Number(e.grid)!==pr)throw new u("xmr-no-nodes",{why:"witness-grid"});if(Number(e.slice)!==n)throw new u("xmr-no-nodes",{why:"witness-slice"});let o=wu(n),i=Y0(n),s=Number(e.to);if(Number(e.from)!==o||!Number.isSafeInteger(s)||s<o||s>i)throw new u("xmr-no-nodes",{why:"witness-bounds"});if(typeof e.complete!="boolean"||e.complete!==(s===i))throw new u("xmr-no-nodes",{why:"witness-complete"});let a=s-o+1;if(!Array.isArray(e.blocks)||e.blocks.length!==a)throw new u("xmr-no-nodes",{why:"witness-block-count"});let c=e.blocks.map((d,f)=>{if(!d||Number(d.height)!==o+f)throw new u("xmr-no-nodes",{why:"witness-height"});let p=Ua(d.hash);if(!p)throw new u("xmr-no-nodes",{why:"witness-hash"});if(!Array.isArray(d.txids))throw new u("xmr-no-nodes",{why:"witness-txids"});let h=d.txids.map(w=>{let b=Ua(w);if(!b)throw new u("xmr-no-nodes",{why:"witness-txid"});return b});return{height:Number(d.height),hash:p,txids:h}}),l=null;if(e.complete){if(e.tip!==null&&e.tip!==void 0)throw new u("xmr-no-nodes",{why:"witness-tip"})}else{let d=e.tip;if(!d||typeof d!="object"||Number(d.height)!==s||!Ua(d.hash)||String(d.hash).toLowerCase()!==c[a-1].hash)throw new u("xmr-no-nodes",{why:"witness-tip"});if(r!==null&&Number(d.height)<Number(r))throw new u("xmr-no-nodes",{why:"witness-tip-height"});l={height:Number(d.height),hash:Ua(d.hash)}}return{version:1,network:String(t),grid:pr,slice:n,from:o,to:s,complete:e.complete,blocks:c,tip:l}}var rn=e=>typeof e=="string"&&e.length>0,mr=e=>{let t=Number(e);return Number.isFinite(t)?Math.trunc(t):null},gA=e=>rn(e)?e.trim().replace(/^0x/,"").toLowerCase():null,Q0=e=>{try{return new URL(e).host}catch{throw new u("bad-input",{field:"nodes.url",unknown:e})}},Pn=(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 Z0(e){if(!Array.isArray(e))throw new u("bad-input",{field:"nodes"});let t=[];for(let n of e)if(rn(n)){let r=n.replace(/\/+$/,"");t.push({url:r,operator:Q0(r)})}else if(n&&typeof n=="object"&&rn(n.url)){let r=n.url.replace(/\/+$/,""),o={url:r,operator:rn(n.operator)?n.operator:Q0(r)};if(n.protocol!==void 0&&n.protocol!==null){if(!rn(n.protocol))throw new u("bad-input",{field:"nodes.protocol"});o.protocol=n.protocol}t.push(o)}else throw new u("bad-input",{field:"nodes",why:"each-node-is-url-or-url+operator"});if(!t.length)throw new u("bad-input",{field:"nodes",why:"empty-list"});return t}async function ja(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 u("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 u("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 u("xmr-no-nodes",{node:e.url,name:a,why:c?"timeout":"bad-json"})}}async function yu(e,t,n){let r=await ja(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 u("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 u("xmr-no-nodes",{node:e.url,why:"busy"});return{height:Number(o.height),synced:o.synchronized===!0,nettype:o.nettype||null}}async function q0(e,t,n,r){let o=await ja(e,"/json_rpc",{jsonrpc:"2.0",id:"block",method:"get_block",params:{height:t}},n,r),i=o&&o.result;if(!i)throw new u("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 gu(e,t,n,r){if(!t.length)return[];let o=await ja(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 u("xmr-no-nodes",{node:e.url,why:"partial-transactions",want:t.length,got:s.length});let a=s.map((c,l)=>{let d;try{d=typeof c=="string"?JSON.parse(c):c}catch{throw new u("xmr-no-nodes",{node:e.url,why:"bad-json"})}let f=i[l]||{};return d.tx_hash=String(f.tx_hash||d.tx_hash||"").replace(/^0x/,"").toLowerCase(),d.block_height=f.block_height??null,d.confirmations=f.confirmations??null,d}).filter(c=>t.includes(String(c.tx_hash||"").toLowerCase()));if(a.length!==t.length)throw new u("xmr-no-nodes",{node:e.url,why:"partial-transactions",want:t.length,got:a.length});return a}var bu=e=>e.outputs.reduce((t,n)=>t+(n.amountVerified&&n.amountAtomic||0n),0n);async function bA(e,{expectedAtomic:t,address:n,viewSecret:r,spendPub:o,fromHeight:i,toHeight:s,nowSec:a,fetchImpl:c,timeoutMs:l}){let d=Math.max(0,mr(i)??0),f=mr(s);if(!Number.isFinite(f)||f<d)throw new u("bad-input",{field:"fromHeight",got:i});let p=null;for(let h=d;h<=f;h++){let{txHashes:w}=await q0(e,h,c,l);if(!w.length)continue;let b=await gu(e,w,c,l);for(let y of b){let v=An.matchTransaction(y,[{address:n,viewSecret:r,spendPub:o}],{height:h,tipHeight:Math.max(0,f),nowSec:a});if(!v.length)continue;let I=bu(v[0]),g=v[0].outputs.every(P=>P.amountVerified===!0),T=v[0].unlock&&v[0].unlock.locked===!0,A=(I>=t?4:0)+(g?2:0)+(T?0:1),B={txid:y.tx_hash,height:h};if(A===7)return B;(!p||A>p.score||A===p.score&&I>p.amountAtomic)&&(p={...B,score:A,amountAtomic:I})}}return p}async function _i(e){if(!e||typeof e!="object")throw new u("bad-input",{field:"request"});let t=Z0(e.nodes);if(!rn(e.address))throw new u("bad-input",{field:"address"});if(e.viewSecret===void 0||e.viewSecret===null)throw new u("bad-input",{field:"viewSecret"});if(!rn(e.spendPub))throw new u("bad-input",{field:"spendPub"});let n;try{n=BigInt(e.expectedAtomic)}catch{throw new u("bad-input",{field:"expectedAtomic"})}if(n<=0n)throw new u("bad-input",{field:"expectedAtomic"});let r=Math.max(1,mr(e.minConfirmations)??1),o=typeof e.fetch=="function"?e.fetch:globalThis.fetch;if(typeof o!="function")throw new u("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=gA(e.txid),c=An.watchedAddressVerdict({address:e.address,viewSecret:e.viewSecret,spendPub:e.spendPub});if(!c.ok)throw c.code==="bad-input"?new u("bad-input",{field:c.field||"address",why:c.why}):new u(c.code,{field:c.field||"address",address:e.address});let l=c.viewSecret,d=c.spendPub,f={address:e.address,viewSecret:l,spendPub:d},p=[],h=[];for(let H of t)try{let m=await yu(H,o,s);p.push({node:H,info:m})}catch(m){h.push(Pn(m,H))}if(!p.length)throw new u("xmr-no-nodes",{tried:t.map(H=>H.url),nodes:h});let w=Math.max(...p.map(H=>H.info.height)),b=Math.max(0,w-1),y=null,v=new Set,I=[];for(let{node:H,info:m}of p){if(!m.synced){I.push({url:H.url,operator:H.operator,code:"stale",why:"not-synchronized"});continue}try{y=await bA(H,{expectedAtomic:n,address:e.address,viewSecret:l,spendPub:d,fromHeight:e.fromHeight,toHeight:b,nowSec:i,fetchImpl:o,timeoutMs:s}),y||v.add(H.operator)}catch(k){h.push(Pn(k,H)),y=null}if(y)break}if(!y){if(h.push(...I),!v.size){if(p.some(H=>!H.info.synced))return{seen:!1,state:"pending",absent:!1,txid:a,tip:w,completedOperators:[],checked:p.map(H=>({url:H.node.url,operator:H.node.operator,height:H.info.height,synchronized:H.info.synced})),failed:h};throw new u("xmr-no-nodes",{tried:t.map(H=>H.url),nodes:h})}return{seen:!1,state:"pending",absent:v.size>=2,txid:a,tip:w,completedOperators:[...v],checked:p.map(H=>({url:H.node.url,operator:H.node.operator,height:H.info.height,synchronized:H.info.synced})),failed:h}}let g=[];for(let H of t){let m={url:H.url,operator:H.operator},k;try{k=await yu(H,o,s)}catch(W){m.state="down",m.failure=Pn(W,H),h.push(m.failure),g.push(m);continue}if(!k.synced||k.height<y.height){m.state="stale",m.height=k.height,g.push(m);continue}m.height=k.height;let x;try{x=await q0(H,y.height,o,s)}catch(W){m.state="down",m.failure=Pn(W,H),h.push(m.failure),g.push(m);continue}if(m.blockHash=x.hash,!x.hash||!x.txHashes.includes(y.txid)){m.state="no-tx",g.push(m);continue}let C=null;try{C=(await gu(H,x.txHashes,o,s)).find(W=>W.tx_hash===y.txid)||null}catch(W){m.state="down",m.failure=Pn(W,H),h.push(m.failure),g.push(m);continue}if(!C){m.state="no-tx",g.push(m);continue}let U=An.matchTransaction(C,[f],{height:y.height,tipHeight:Math.max(0,k.height-1),nowSec:i});if(!U.length){m.state="no-output",g.push(m);continue}if(m.state="ok",m.amountAtomic=bu(U[0]),m.amountVerified=U[0].outputs.every(W=>W.amountVerified===!0),m.outputs=U[0].outputs.map(W=>({index:W.index,key:String(W.key||"").replace(/^0x/,"").toLowerCase(),amountAtomic:W.amountVerified?String(W.amountAtomic??null):null,amountVerified:W.amountVerified===!0})),m.unlock=U[0].unlock,m.confirmations=Number.isFinite(Number(C.confirmations))?Number(C.confirmations):k.height-y.height,!m.amountVerified){m.state="amount-unverified",g.push(m);continue}m.observation={txid:y.txid,blockHash:String(x.hash||"").replace(/^0x/,"").toLowerCase(),outputs:m.outputs,unlock:m.unlock?{locked:m.unlock.locked===!0,untilHeight:m.unlock.untilHeight??null,untilTime:m.unlock.untilTime??null}:null},g.push(m)}let T=g.filter(H=>H.state==="no-tx"||H.state==="no-output"||H.state==="amount-unverified");if(T.length)throw new u("xmr-nodes-disagree",{txid:y.txid,height:y.height,nodes:T.map(H=>({url:H.url,operator:H.operator,blockHash:H.blockHash||null,why:H.state,outputs:H.outputs||null})),agreed:g.filter(H=>H.state==="ok").map(H=>({url:H.url,operator:H.operator,blockHash:H.blockHash})),failed:h});let A=g.filter(H=>H.state==="ok");if(!A.length)return{seen:!1,state:"pending",txid:y.txid,height:y.height,checked:g,failed:h};let B=new Map;for(let H of A){let m=JSON.stringify(H.observation);B.has(m)||B.set(m,{observation:H.observation,operators:new Set,nodes:[]});let k=B.get(m);k.operators.add(H.operator),k.nodes.push(H)}if(B.size>1)throw new u("xmr-nodes-disagree",{txid:y.txid,height:y.height,nodes:A.map(H=>({url:H.url,operator:H.operator,blockHash:H.blockHash||null,outputs:H.outputs,why:"observation"})),agreed:[],failed:h});let P=[...B.values()][0],O=Math.min(...P.nodes.map(H=>H.confirmations)),j=P.nodes[0].amountAtomic,D=P.nodes.map(H=>({url:H.url,operator:H.operator,blockHash:H.blockHash,confirmations:H.confirmations})),X=P.nodes.find(H=>H.unlock&&H.unlock.locked);if(X){let H=X.unlock;throw new u("xmr-locked",{txid:y.txid,height:y.height,address:e.address,untilHeight:H.untilHeight??null,untilTime:H.untilTime??null,failed:h})}if(j<n)throw new u("xmr-underpaid",{txid:y.txid,height:y.height,got:j.toString(),want:n.toString(),failed:h});return P.operators.size<2?{seen:!1,state:"one-node",txid:y.txid,height:y.height,blockHash:P.observation.blockHash,amountAtomic:j.toString(),confirmations:O,operators:[...P.operators],agreedBy:D,checked:g,failed:h}:O<r?{seen:!1,state:"pending",why:"confirmations",txid:y.txid,height:y.height,blockHash:P.observation.blockHash,amountAtomic:j.toString(),confirmations:O,needConfirmations:r,agreedBy:D,checked:g,failed:h}:{seen:!0,state:"arrived",txid:y.txid,height:y.height,blockHash:P.observation.blockHash,amountAtomic:j.toString(),confirmations:O,needConfirmations:r,operators:[...P.operators],agreedBy:D,checked:g,failed:h}}async function xA(e,t,{network:n,fetchImpl:r,timeoutMs:o,tipHeight:i=null}){if(e.protocol!=="witness-v1")throw new u("xmr-no-nodes",{node:e.url,why:"no-slice-witness"});let s=await ja(e,"/v1/witness/slice",{version:1,network:n,grid:pr,slice:t},r,o);return G0(s,{network:n,index:t,tipHeight:i})}async function kA(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 u("xmr-no-nodes",{node:e.url,why:"slice-too-large",count:o.length});let i=await gu(e,o,n,r);return new Map(i.map(s=>[String(s.tx_hash||"").toLowerCase(),s]))}function SA(e){if(!e||typeof e!="object")return null;let t=Array.isArray(e.checked)?e.checked.filter(r=>r&&r.synchronized!==!1&&r.state!=="stale"&&r.state!=="down").map(r=>mr(r.height)).filter(r=>r!==null&&r>0):[];if(Array.isArray(e.checked)&&e.checked.length)return t.length?Math.max(0,Math.max(...t)-1):null;let n=mr(e.tip);return n!==null&&n>0?Math.max(0,n-1):null}async function vA(e,{expectedAtomic:t,address:n,viewSecret:r,spendPub:o,fromHeight:i,toHeight:s,targetTop:a=s,nowSec:c,network:l,fetchImpl:d,timeoutMs:f}){let p=mr(a);if(p===null)throw new u("bad-input",{field:"targetTop"});if(p<i||s<i)return{located:null,completed:!1};let h=hu(i),w=hu(Math.min(s,p)),b=null,y=!1,v=null;for(let I=h;I<=w;I++){let g,T;try{g=await xA(e,I,{network:l,fetchImpl:d,timeoutMs:f,tipHeight:s}),T=await kA(e,g,{fetchImpl:d,timeoutMs:f})}catch(A){v=A;break}for(let A of g.blocks)if(!(A.height<i))for(let B of A.txids){let P=T.get(B);if(!P)continue;let O=An.matchTransaction(P,[{address:n,viewSecret:r,spendPub:o}],{height:A.height,tipHeight:Math.max(0,s),nowSec:c});if(!O.length)continue;let j=bu(O[0]),D=O[0].outputs.every(k=>k.amountVerified===!0),X=O[0].unlock&&O[0].unlock.locked===!0,H=(j>=t?4:0)+(D?2:0)+(X?0:1),m={txid:B,height:A.height,blockHash:A.hash,amountAtomic:j,locked:X,score:H};(!b||H>b.score||H===b.score&&j>b.amountAtomic)&&(b=m)}if(b&&b.score===7){y=g.to>=p;break}I===w&&(y=g.to>=p)}return{located:b,completed:y,failure:v}}async function J0(e){if(!e||typeof e!="object")throw new u("bad-input",{field:"request"});if(e.witnessNodes===void 0||e.witnessNodes===null)throw new u("bad-input",{field:"witnessNodes",why:"required"});let t=Z0(e.witnessNodes);if(!t.some(N=>N.protocol==="witness-v1"))throw new u("bad-input",{field:"witnessNodes",why:"no-witness-v1"});if(!rn(e.address))throw new u("bad-input",{field:"address"});if(!rn(e.spendPub))throw new u("bad-input",{field:"spendPub"});if(e.viewSecret===void 0||e.viewSecret===null)throw new u("bad-input",{field:"viewSecret"});let n=An.watchedAddressVerdict({address:e.address,viewSecret:e.viewSecret,spendPub:e.spendPub});if(!n.ok)throw n.code==="bad-input"?new u("bad-input",{field:n.field||"address",why:n.why}):new u(n.code,{field:n.field||"address",address:e.address});let r=e.network||n.keys.network,o=n.viewSecret,i=n.spendPub,s=typeof e.fetch=="function"?e.fetch:globalThis.fetch;if(typeof s!="function")throw new u("bad-input",{field:"fetch"});let a=Number.isFinite(Number(e.timeoutMs))&&Number(e.timeoutMs)>0?Number(e.timeoutMs):2e4,c=Number.isFinite(Number(e.nowSec))?Number(e.nowSec):Math.floor(Date.now()/1e3),l=Number(e.fromHeight);if(!Number.isSafeInteger(l)||l<=0)throw new u("bad-input",{field:"fromHeight"});let d;try{d=BigInt(e.expectedAtomic)}catch{throw new u("bad-input",{field:"expectedAtomic"})}if(d<=0n)throw new u("bad-input",{field:"expectedAtomic"});let f=null,p=null;try{f=await _i(e)}catch(N){p={code:N&&N.code?N.code:"unknown",params:N&&N.params||{}}}let h=[],w=[],b=[],y=[],v=[],g=SA(f);for(let N of t){if(N.protocol!=="witness-v1"){w.push({url:N.url,operator:N.operator,code:"no-slice-witness"});continue}let S;try{S=await yu(N,s,a)}catch(M){w.push(Pn(M,N)),h.push({url:N.url,operator:N.operator,state:"down"});continue}if(!S.synced){b.push({url:N.url,operator:N.operator,code:"stale",why:"not-synchronized"}),h.push({url:N.url,operator:N.operator,state:"stale",height:S.height});continue}let _=Math.max(0,S.height-1),R={url:N.url,operator:N.operator,state:"ok",height:S.height};h.push(R),g=g===null?_:Math.max(g,_),y.push({node:N,top:_,entry:R})}let T=null,A=!1,B=new Set;for(let{node:N,top:S,entry:_}of y){let R=g===null?S:Math.max(S,g);try{let M=await vA(N,{expectedAtomic:d,address:e.address,viewSecret:o,spendPub:i,fromHeight:l,toHeight:S,targetTop:R,nowSec:c,network:r,fetchImpl:s,timeoutMs:a});A=A||M.completed,M.completed&&B.add(N.operator||N.url),M.failure?(w.push(Pn(M.failure,N)),_.state="error"):M.completed||(_.state=M.located?"partial":"behind"),M.located?(v.push({operator:N.operator||N.url,url:N.url,seen:!0,completed:M.completed,txid:M.located.txid,height:M.located.height,blockHash:M.located.blockHash,amountAtomic:M.located.amountAtomic.toString(),locked:M.located.locked===!0}),(!T||M.located.score>T.score)&&(T=M.located,T.operator=N.operator,T.url=N.url)):M.completed&&v.push({operator:N.operator||N.url,url:N.url,seen:!1,completed:!0,txid:null,height:null,blockHash:null,amountAtomic:null,locked:null})}catch(M){_.state="error",w.push(Pn(M,N))}}T||w.push(...b);let P=[...B],O=P.filter(N=>String(N).toLowerCase()!=="ninsei"),j=2,D={required:j,completed:P,independent:O,ok:(r==="mainnet"?O.length:P.length)>=j},X=N=>({operator:String(N.operator||N.url||""),seen:N.seen===!0,txid:N.txid===null||N.txid===void 0?null:String(N.txid).toLowerCase(),height:N.height===null||N.height===void 0?null:Number(N.height),blockHash:N.blockHash===null||N.blockHash===void 0?null:String(N.blockHash).toLowerCase(),amountAtomic:N.amountAtomic===null||N.amountAtomic===void 0?null:String(N.amountAtomic),locked:N.locked===null||N.locked===void 0?null:N.locked===!0}),H=(N,S)=>{for(let _ of["seen","txid","height","blockHash","amountAtomic","locked"])if(N[_]!==S[_])return _;return null},m=new Map;for(let N of v){let S=X(N),_=S.operator.toLowerCase();m.has(_)||m.set(_,[]),m.get(_).push(S)}let k=[];for(let[N,S]of m)for(let _=1;_<S.length;_+=1){let R=H(S[0],S[_]);R&&k.push({operators:[N],field:R,against:"same-operator"})}let x=[...m.values()].map(N=>N[0]);for(let N=1;N<x.length;N+=1){let S=H(x[0],x[N]);S&&k.push({operators:[x[0].operator,x[N].operator],field:S})}let C={observations:x,disagreements:k},U=T?{state:"seen",txid:T.txid,height:T.height,blockHash:T.blockHash,amountAtomic:T.amountAtomic.toString(),operator:T.operator,url:T.url,completed:A,checked:h,failed:w,...C,quorum:D}:{state:"pending",txid:null,height:null,blockHash:null,amountAtomic:null,completed:A,checked:h,failed:w,...C,quorum:D},W=[],Y=null;if(p&&W.push("exact:"+p.code),T&&f&&f.txid){let N=S=>{W.includes(S)||W.push(S)};for(let S of x){if(!S.seen){N("witness:txid"),k.push({operators:[S.operator],field:"seen",against:"exact"});continue}String(f.txid).toLowerCase()!==S.txid&&(N("txid"),k.push({operators:[S.operator],field:"txid",against:"exact"})),Number(f.height)!==S.height&&(N("height"),k.push({operators:[S.operator],field:"height",against:"exact"})),String(f.blockHash||"").toLowerCase()!==S.blockHash&&(N("blockHash"),k.push({operators:[S.operator],field:"blockHash",against:"exact"})),String(f.amountAtomic??"")!==S.amountAtomic&&(N("amount"),k.push({operators:[S.operator],field:"amountAtomic",against:"exact"}))}k.length&&N("witness:disagreement"),Y=W.length===0}else T?(W.push("exact:no-transaction"),Y=!1):f&&f.absent===!0&&(U.completed&&U.failed.length===0&&U.quorum.ok&&!k.length?Y=!0:(Y=!1,W.push(U.completed&&U.failed.length===0?"witness:no-quorum":"witness:not-completed"),k.length&&W.push("witness:disagreement")));return{exact:f,exactError:p,witness:U,agrees:Y,problems:W}}function xu({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,mr(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,d=Math.max(a*c,l),f=Math.floor(i-s);if(f<d)throw new u("xmr-too-late",{needSec:d,leftSec:f,minConfirmations:a,readyBy:Math.floor(i)});return f}me();var eg=/^0x[0-9a-f]{40}$/,AA=/^[0-9a-f]{64}$/,NA=/^0x[0-9a-f]{64}$/,_A=/^(0|[1-9][0-9]*)$/;function wo(e){let t=String(e??"").trim().replace(/\/+$/,"");if(!t)throw new u("bad-input",{field:"relayUrl"});if(!/^https:\/\//i.test(t))throw new u("bad-input",{field:"relayUrl",why:"not-https"});return t}function Et(e,t){let n=String(e??"").trim().toLowerCase();if(!eg.test(n))throw new u("bad-input",{field:t});return n}function ku(e){let t=String(e??"").trim().toLowerCase().replace(/^0x/,"");if(!AA.test(t))throw new u("bad-input",{field:"halfClaimer",why:"not-in-record"});return"0x"+t}async function tg({relayUrl:e,provider:t,escrow:n,halfClaimer:r,expectedTipWei:o,fetchImpl:i=null,timeoutMs:s=2e4}={}){let a=wo(e),c=Et(t,"provider"),l=Et(n,"escrow"),d=ku(r),f=it({apiBase:a,fetchImpl:i,timeoutMs:s}),p=JSON.stringify({version:1,halfClaimer:d}),h;try{h=await f.tryJson(`/v1/claims/${c}/${l}`,{method:"POST",headers:{"content-type":"application/json"},body:p})}catch(B){throw B instanceof u&&B.code==="bad-input"?B:new u("claim-unknown",{step:"relay-claim",why:B&&B.params&&B.params.why||"answer-lost",outcome:"unknown"})}let w=h.body&&typeof h.body=="object"?h.body:null,b=w?Number(w.version):null,y=w&&typeof w.code=="string"&&w.code?w.code:null;if(!h.ok)throw y==="claim-unknown"||y==="claim_unknown"?new u("claim-unknown",{step:"relay-claim",why:"relay-timeout",code:y,status:h.status,outcome:"unknown"}):y&&b===1?new u("quote-refused",{step:"relay-claim",code:y,status:h.status}):new u("claim-unknown",{step:"relay-claim",why:"answer-status",status:h.status,outcome:"unknown"});if(!w||b!==1)throw new u("claim-unknown",{step:"relay-claim",why:"answer",outcome:"unknown"});if(y)throw new u("quote-refused",{step:"relay-claim",code:y,status:h.status});let v=String(w.txid===void 0||w.txid===null?"":w.txid).trim().toLowerCase();if(!NA.test(v))throw new u("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(!eg.test(I))throw new u("claim-unknown",{step:"relay-claim",why:"answer-from",outcome:"unknown"});let g=String(w.tipWei===void 0||w.tipWei===null?"":w.tipWei).trim();if(!_A.test(g))throw new u("claim-unknown",{step:"relay-claim",why:"answer-tip",outcome:"unknown"});let T=String(w.provider===void 0||w.provider===null?"":w.provider).trim().toLowerCase(),A=String(w.escrow===void 0||w.escrow===null?"":w.escrow).trim().toLowerCase();if(!T||!A)throw new u("claim-unknown",{step:"relay-claim",why:"answer-binding",outcome:"unknown"});if(T!==c)throw new u("quote-refused",{step:"relay-claim",why:"answer-provider"});if(A!==l)throw new u("quote-refused",{step:"relay-claim",why:"answer-escrow"});if(BigInt(g)!==BigInt(o))throw new u("quote-refused",{step:"relay-claim",why:"tip",tipWei:g,expectedTipWei:String(o)});return{txid:v,from:I,tipWei:g}}var IA={success:"success",refund_eth:"refunded_eth",[nn]:nn},Hn=e=>{if(e==null||e==="")return null;let t=Number(e);return Number.isFinite(t)?t:null};function TA(e){let t=e&&e.escrow||{};if(typeof t.viewHalf!="string"||!t.viewHalf)throw new u("bad-input",{field:"viewHalf"});if(typeof t.counterViewHalf!="string"||!t.counterViewHalf)throw new u("bad-input",{field:"counterViewHalf"});try{return Yt.createHalves(Xt).combineHalves(BigInt(t.viewHalf),BigInt(t.counterViewHalf)).toString(16).padStart(64,"0")}catch{throw new u("bad-input",{field:"viewKey"})}}function ng(e){if(!e||typeof e!="object"||!e.id)throw new u("bad-input",{field:"swap"});let t=fe.derive(e),n=[],r=Array.isArray(t.steps)?t.steps:[],o=r.find(d=>d.key==="funded")||null;n.push({code:"awaiting_funding",done:!!(o&&o.done),active:!(o&&o.done),at:null});for(let d of r)n.push({code:d.key,done:!!d.done,active:!!d.active,failed:!!d.failed,at:t.simulated&&t.simulated.evm?d.atSim??null:null});let i=n.find(d=>d.active)||[...n].reverse().find(d=>d.done)||n[0],s=t.terminal?IA[t.terminal.kind]??"closed":null,a=s===nn,c=e.network||e.chain||null,l=c&&wd(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)?Hn(t.xmrAmount&&t.xmrAmount.seen):null,escrowLocked:!!(e.escrow&&(e.escrow.fundTx||e.escrow.secret))},pay:{token:e.payToken||"eth",amount:Hn(e.payAmount)},get:{xmr:Hn(e.xmrAmount)},step:i.code,steps:n,deadlines:{readyBy:t.deadlines&&t.deadlines.readyBy!==void 0?Hn(t.deadlines.readyBy):null,t1:t.deadlines&&t.deadlines.t1!==void 0?Hn(t.deadlines.t1):null},xmr:{confirmations:Hn(t.xmr&&(t.xmr.confirmations!==void 0?t.xmr.confirmations:t.conf))??0,target:Hn(t.xmr&&t.xmr.confTarget)??Hn(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 rg=12,og=(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 u("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),chainId:r((e.order&&e.order.chainId)??(e.orderQuote&&e.orderQuote.chainId)),factory:r((e.order&&e.order.factory)??(e.orderQuote&&e.orderQuote.factory)),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 BA({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 wy({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(d=>Number(d.height)).filter(d=>Number.isSafeInteger(d)&&d>=0);if(!a.length)throw new u("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 u("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 u("xmr-no-nodes",{step:"restore-height",network:t||null,why:s})}var CA=300;function OA({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+CA)*1e3)}var Ii=e=>String(e??"").replace(/^0x/i,"").toLowerCase(),hr=e=>String(e??"").replace(/^0x/i,"").toLowerCase();function ig(e){let t=e&&e.escrow&&typeof e.escrow=="object"?e.escrow:{},n=e&&e.order&&typeof e.order=="object"?e.order:{},r=e&&e.quote&&typeof e.quote=="object"?e.quote:{};return{salt:Ii(t.salt??(e&&e.recoverySalt)),chainId:Number(n.chainId??r.chainId??(e&&e.chainId)??t.chainId),factory:hr(n.factory??r.factory??(e&&e.factory)??t.factory),escrow:hr(t.address??(e&&e.predictedEscrow))}}function RA(e,t={}){if(!e||!(e.fundingPending===!0||e.escrow&&e.escrow.fundingPending===!0))return!1;let n=ig(e),r={salt:Ii(t.salt),chainId:Number(t.chainId),factory:hr(t.factory)};return!(!r.salt||!r.factory||!Number.isSafeInteger(r.chainId)||r.chainId<=0||n.salt!==r.salt||n.factory&&n.factory!==r.factory||Number.isSafeInteger(n.chainId)&&n.chainId>0&&n.chainId!==r.chainId)}function PA(e,t={}){if(!e||!(e.fundingPending===!0||e.escrow&&e.escrow.fundingPending===!0))return!1;let n=ig(e),r={salt:Ii(t.salt),chainId:Number(t.chainId),factory:hr(t.factory),escrow:hr(t.escrow)};return!(!r.salt||!r.factory||!r.escrow||!Number.isSafeInteger(r.chainId)||r.chainId<=0||n.salt!==r.salt||n.escrow!==r.escrow||Number.isSafeInteger(n.chainId)&&n.chainId>0&&n.chainId!==r.chainId||n.factory&&n.factory!==r.factory)}function HA(e,t={}){if(!!!(e&&(e.fundingPending===!0||e.escrow&&e.escrow.fundingPending===!0)))return"not-pending";let r=Ii(t.salt),o=String(t.quoteId===void 0||t.quoteId===null?"":t.quoteId);return r?PA(e,t)?"resume":"different":!o||String(e.orderQuoteId||"")===o?"salt-required":"different"}function FA(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 Su({preflight:e,createRecord:t,mode:n=null,xmrNetwork:r=null,call:o=null,fetchImpl:i=null,now:s=null,sleep:a=null,evmBlock:c=null,store:l=Yn,config:d=null,denylist:f=null,watch:p=null,logs:h=null}={}){let w=typeof o=="function"?o:He.readContract,b=async m=>{let k=m&&m.orderQuote,x=m&&m.order;if(!k||typeof k!="object"||!k.signature)return null;let C=x&&x.factory||k.factory;if(!C)return null;let U={commitHalfLocker:(x&&x.commitHalfLocker)??k.commitHalfLocker,edPointLocker:(x&&x.edPointLocker)??k.edPointLocker,edViewPointLocker:(x&&x.edViewPointLocker)??k.edViewPointLocker};if(!U.commitHalfLocker||!U.edPointLocker||!U.edViewPointLocker)return null;try{let W=await w({to:C,data:He.encodePredict({...k,...U,factory:C})});return He.decodeAddress(W)}catch{return null}},y=m=>i&&m&&typeof m=="object"&&typeof m.fetch!="function"?{...m,fetch:i}:m,v=()=>{let m=typeof s=="function"?Number(s()):Date.now();return Number.isFinite(m)?m:Date.now()},I=typeof a=="function"?a:m=>new Promise(k=>setTimeout(k,m)),g=async(m=null)=>{let k=null;if(typeof c=="function")k=await c("latest");else if(m&&typeof m.driver=="function"){let U=m.driver();if(U&&typeof U.request=="function"){let W=await U.request({method:"eth_blockNumber"});typeof W=="string"&&/^0x[0-9a-f]+$/i.test(W)&&(k=await U.request({method:"eth_getBlockByNumber",params:[W,!1]}))}}let x=k&&Number(k.number),C=k&&Number(k.timestamp);return!Number.isSafeInteger(x)||x<0||!Number.isFinite(C)||C<=0?null:{blockTag:"0x"+x.toString(16),timestamp:C}},T=La(h),A=Ni({call:typeof o=="function"?o:null}),B=(m,k)=>{let x=d&&d.limits?d.limits[m]:null;return Number.isFinite(Number(x))&&Number(x)>0?Number(x):k};async function P(m,k){let x=Number(m.restoreHeight);if(Number.isSafeInteger(x)&&x>0)return x;let C=Array.isArray(m.xmrNodes)?m.xmrNodes:d&&typeof d.nodesFor=="function"?d.nodesFor(k):[];return BA({nodes:C,network:k,fetchImpl:m.fetchImpl||i||(typeof fetch=="function"?fetch:null)})}let O=()=>{let m=l.loadState();return Object.values(m&&m.swaps||{}).filter(x=>x&&x.id).sort((x,C)=>Number(C.createdAt||0)-Number(x.createdAt||0))},j=m=>{let k=Ii(m&&m.salt),x=String(m&&m.quoteId!==void 0&&m.quoteId!==null?m.quoteId:"");if(!k&&!x)return null;for(let C of O()){let U=HA(C,m);if(U==="salt-required")throw new u("bad-input",{field:"recoverySalt",why:"required-for-pending-funding"});if(U==="resume")return C}return null};async function D(m,k){let x=m.swap||m,C=x.escrow&&typeof x.escrow=="object"?x.escrow:{},U=C.fundTx||x.fundTx||null,W=null;if(C.address)try{W=await Rn(C.address,{call:w})}catch(R){/short .*status\(\)/.test(String(R&&R.message||R))?W={isFunded:!1,absent:!0}:W=null}if(!U&&W&&!W.isFunded&&C.fundingReason==="not-sent"){delete x.fundingPending,x.escrow={...C,fundingPending:!1,fundingReason:"send-not-started"};try{fe.saveSwap(x,l)}catch{throw new u("storage-unavailable",{step:"save-pending"})}return null}if(!U&&!(W&&W.isFunded))return{id:x.id||null,escrow:C.address||null,address:m.swapWallet&&m.swapWallet.address||null,step:"funding-pending",txHash:null,reason:"no-transaction-hash",next:"receipt"};let Y=k.wallet,N=null;if(U&&Y&&typeof Y.receipt=="function")try{N=await Y.receipt(U)}catch{N=null}let S=k.order&&typeof k.order=="object"?k.order:{},_=Os(N,{factory:S.factory||k.orderQuote&&k.orderQuote.factory||null,expectedEscrow:C.address||null});if(_.status==="reverted")throw new u("contract-reverted",{step:"funding"});if(_.status==="funded"||W&&W.isFunded){let R=_.status==="funded"?_.escrow:C.address;if(!R)throw new u("funding-pending",{reason:"no-escrow-address"});x.escrow={...C,address:R,fundingPending:!1,evmBirthBlock:Number(_.birthBlock)>0?Number(_.birthBlock):C.evmBirthBlock??null},delete x.fundingPending;try{fe.saveSwap(x,l)}catch{throw new u("storage-unavailable",{step:"save-escrow"})}return{id:x.id||null,escrow:R,address:m.swapWallet&&m.swapWallet.address||null,step:"xmr-incoming",next:"watch"}}return{id:x.id||null,escrow:C.address||null,address:m.swapWallet&&m.swapWallet.address||null,step:"funding-pending",txHash:U,reason:_.reason||"no-receipt",next:"receipt"}}async function X(m){let k=m.order&&typeof m.order=="object"?m.order:{},x=k.amount,C=x==null||x===""?null:String(x),U=Number(k.chainId),W=Number.isFinite(U)?pe.chainByChainId(U):null,Y=W?pe.tokensOf(W.id):[],N=String(m.quote&&(m.quote.token||m.quote.asset)||"").toLowerCase(),S=Y.find(K=>String(K.symbol).toLowerCase()===N)||null,_=Y.find(K=>!K.address)||null,R=!!(S&&!S.address),M={tokenIsNative:R,standIn:!m.counterparty&&n!=="live",liveChain:!!(W&&W.escrow&&W.escrow.mode==="live"&&!W.testnet)};C!==null&&(M.payAmountWei=C,M.requiredNativeWei=C);try{let K=m.wallet,G=K&&typeof K.driver=="function"?K.driver():null,Z=K&&typeof K.address=="function"?await K.address():null,V=Jr("evm"),J=E=>String(E.symbol).toLowerCase(),re=[];if(_&&re.push({id:J(_),symbol:_.symbol,decimals:_.decimals,address:null}),S&&S.address&&re.push({id:J(S),symbol:S.symbol,decimals:S.decimals,address:S.address}),G&&Z&&V&&typeof V.balances=="function"&&re.length){let E=await V.balances({driver:G,address:Z,tokens:re}),F=$=>{let ee=$?E.find(ne=>ne.token===J($)):null;return ee&&ee.amount!==null?ee.amount:null},L=_?F(_):null;L!==null&&(M.nativeBalanceWei=L);let z=R?L:F(S);z!==null&&(M.payBalanceWei=z)}}catch{}return M}async function H(m,k,x=null){if(!m||!k)throw new u("bad-input",{field:"escrow"});let C=null;try{C=await g(x)}catch{throw new u("quote-refused",{step:"send-xmr",why:"block-unreadable"})}let U={call:w,blockTag:C?C.blockTag:"latest"},W=C?C.timestamp:Math.floor((typeof s=="function"?s():Date.now())/1e3),Y=null;try{Y=await Rn(m,U)}catch{throw new u("quote-refused",{step:"send-xmr",why:"escrow-unreadable"})}if(!Y||Y.isFunded!==!0||Y.isClaimed===!0||Y.isRefunded===!0)throw new u("quote-refused",{step:"send-xmr",why:"escrow-not-open"});let N=null;try{N=await fr(m,U)}catch{throw new u("quote-refused",{step:"send-xmr",why:"deadline-unreadable"})}if(Number(N.readyBy)!==Number(k.readyBy)||Number(N.t1)!==Number(k.t1))throw new u("quote-refused",{step:"send-xmr",why:"terms-mismatch"});let S=Math.max(1,Number(B("xmrConfirmations",10))),_=Math.max(1,Number(B("xmrBlockTimeSec",120))),R=Number(B("sellReadyLeadSec",0)),M=Number.isFinite(R)&&R>0?R:S*_;if(W+M>=Number(N.readyBy))throw new u("quote-refused",{step:"send-xmr",why:"deadline-too-close"});try{await Ai(m,k,"send-xmr",U)}catch(K){throw K&&K.code==="contract-reverted"?K:new u("quote-refused",{step:"send-xmr",why:"slots-unreadable"})}}return{async list(){return O().map(ng)},async get(m){if(typeof m!="string"||!m)throw new u("bad-input",{field:"id"});let k=O().find(x=>x.id===m);return k?ng(k):null},async progress(m){if(typeof m!="string"||!m)throw new u("bad-input",{field:"id"});let k=fe.getSwap(m,l);return k?{id:String(k.id||m),swap:k,swapWallet:fe.halvesWalletOf(k),view:fe.derive(k)}:null},async confirmReady(m){if(typeof m!="string"||!m)throw new u("bad-input",{field:"id"});return fe.confirmReady(m,l)},async refundEth(m,k="you"){if(typeof m!="string"||!m)throw new u("bad-input",{field:"id"});return fe.refundEth(m,k,l)},async sweepNow(m){if(typeof m!="string"||!m)throw new u("bad-input",{field:"id"});return fe.sweepNow(m,l)},async setDestination(m,k){if(typeof m!="string"||!m)throw new u("bad-input",{field:"id"});if(typeof k!="string"||!k)throw new u("bad-input",{field:"address"});let x=fe.getSwap(m,l);return x?(x.receiveAddress=k,fe.saveSwap(x,l)):null},async addressNetwork(m){if(typeof m!="string"||!m)return null;try{return hn.networkFromShape(m)}catch{return null}},async forget(m){if(typeof m!="string"||!m)throw new u("bad-input",{field:"id"});let k=null;try{k=l.loadState()}catch{throw new u("storage-unavailable",{step:"forget"})}let x=k&&k.swaps;if(!x||!x[m])return!1;delete x[m];try{l.saveState(k)}catch{throw new u("storage-unavailable",{step:"forget"})}return!0},verifyArrival:m=>_i(y(m)),verifyArrivalShadow:m=>J0(y(m)),assertTimeForConfirmations:m=>xu(m),async refundIfXmrMissing(m={},k={}){let x=typeof k.verify=="function"?k.verify:z=>_i(y(z)),C=typeof k.refund=="function"?k.refund:A.refund,U=typeof k.now=="function"?k.now:()=>Math.floor(Date.now()/1e3);if(!m||typeof m!="object")throw new u("bad-input",{field:"request"});let W=m.swap&&typeof m.swap=="object"?m.swap:null,Y=W&&W.escrow||{},N=m.escrow||Y.address||null;if(!N)throw new u("bad-input",{field:"escrow"});let S=m.halfLocker||Y.half||null;if(!S)throw new u("bad-input",{field:"halfLocker"});if(!m.expect||typeof m.expect!="object")throw new u("bad-input",{field:"expect"});let _=m.address||Y.moneroAddress||null;if(!_)throw new u("bad-input",{field:"address"});let R=m.viewSecret!==void 0&&m.viewSecret!==null?m.viewSecret:W?TA(W):null;if(R==null)throw new u("bad-input",{field:"viewSecret"});let M=m.spendPub||Y.moneroSpendPub||null;if(!M)throw new u("bad-input",{field:"spendPub"});let K=m.expectedAtomic!==void 0&&m.expectedAtomic!==null?m.expectedAtomic:Y.expectedAtomic!==void 0&&Y.expectedAtomic!==null?Y.expectedAtomic:null;if(K===null)throw new u("bad-input",{field:"expectedAtomic",why:"unsigned-amount"});let G=Number(m.readyBySec!==void 0&&m.readyBySec!==null?m.readyBySec:Y.readyBy);if(!Number.isFinite(G)||G<=0)throw new u("bad-input",{field:"readyBySec"});let Z=Number.isFinite(Number(m.minConfirmations))&&Number(m.minConfirmations)>0?Math.trunc(Number(m.minConfirmations)):B("xmrConfirmations",10),V=Number.isFinite(Number(m.leadSec))&&Number(m.leadSec)>=0?Number(m.leadSec):(()=>{let z=m.readyWindow||W&&(W.readyWindow||W.sellWindow);if(!z)throw new u("bad-input",{field:"readyWindow",why:"not-in-record"});return v0(vt(z,{field:"readyWindow"}))})(),J=m.fromHeight!==void 0&&m.fromHeight!==null?Number(m.fromHeight):Number(W&&(W.restoreHeight??Y.moneroRestoreHeight??Y.restoreHeight));if(!Number.isSafeInteger(J)||J<=0)throw new u("bad-input",{field:"fromHeight",why:"missing"});let re=Number.isFinite(Number(m.nowSec))?Number(m.nowSec):U(),E=Math.floor(G-re);if(E<=0)return{refunded:!1,state:"claim-window",leftSec:E,readyBy:G,nowSec:re};if(E>V)return{refunded:!1,state:"waiting",leftSec:E,needSec:V,readyBy:G,nowSec:re};let F=null;try{F=await x({nodes:m.nodes,address:_,viewSecret:R,spendPub:M,expectedAtomic:K,minConfirmations:Z,txid:m.txid||null,fromHeight:J,timeoutMs:m.timeoutMs,nowSec:re})}catch(z){if(z&&z.code==="xmr-underpaid")return{refunded:!1,state:"arrival-underpaid",leftSec:E,verdict:null,error:z.params||null};if(z&&z.code==="xmr-locked")return{refunded:!1,state:"arrival-locked",leftSec:E,verdict:null,error:z.params||null};throw z}if(F.seen)return{refunded:!1,state:"arrived",leftSec:E,verdict:F};if(!F||F.absent!==!0)return{refunded:!1,state:"arrival-pending",leftSec:E,verdict:F};let L=await C({escrow:N,halfLocker:S,expect:m.expect,onStep:m.onStep},m.wallet);return{refunded:!0,state:"refunded",hash:L&&L.hash||null,leftSec:E,verified:F}},async start(m){if(!m||typeof m!="object")throw new u("bad-input",{field:"request"});if(m.side==="sell")throw new u("bad-input",{field:"side",why:"sell-not-supported",surface:"swaps.start"});if(!m.quote||typeof m.quote!="object")throw new u("bad-input",{field:"quote"});if(m.recoveryKey===void 0||m.recoveryKey===null)throw new u("bad-input",{field:"recoveryKey",why:"required"});if(!m.receiveTo||typeof m.receiveTo!="string")throw new u("bad-input",{field:"receiveTo"});if(!og(m,r).expectedAtomic)throw new u("bad-input",{field:"expectedAtomic",why:"signed-amount-missing"});let x={salt:m.recoverySalt||m.order&&m.order.salt||m.orderQuote&&m.orderQuote.salt||null,quoteId:m.orderQuote&&m.orderQuote.id||m.quote&&m.quote.id||null,chainId:(m.order&&m.order.chainId)??(m.orderQuote&&m.orderQuote.chainId)??(m.quote&&m.quote.chainId),factory:(m.order&&m.order.factory)??(m.orderQuote&&m.orderQuote.factory)??(m.quote&&m.quote.factory),escrow:m.escrow||m.predictedEscrow||m.quote&&m.quote.escrow||m.orderQuote&&m.orderQuote.escrow||null},C=null;if(O().some(q=>RA(q,x))){let q=await b(m);if(!q)throw new u("bad-input",{field:"escrow",why:"required-for-pending-funding"});let oe=hr(x.escrow);if(x.escrow&&!oe)throw new u("bad-input",{field:"escrow",why:"unreadable"});if(oe&&oe!==hr(q))throw new u("bad-input",{field:"escrow",why:"escrow-mismatch"});if(x.escrow=q,C=j(x),!C)throw new u("bad-input",{field:"escrow",why:"pending-funding-unresolved"})}else C=j(x);if(C){let q=await D(C,m);if(q)return q}if(m.recoverySalt===void 0||m.recoverySalt===null){if(!m.order||typeof m.order!="object")throw new u("bad-input",{field:"order"});(m.order.salt===void 0||m.order.salt===null||m.order.salt==="")&&(m.order={...m.order,salt:vy()}),m.recoverySalt=m.order.salt}let U=await X(m),W=e?await e(m.quote,U):null,N=(W&&(W.checks||W.results)||[]).filter(q=>q&&q.blocks===!0);if(N.length){let q=N[0];throw new u(q.code||"bad-input",{...q.params||{},kind:q.kind,surface:"swaps.start"})}let S=null,_=null,R=typeof t=="function"?t:async q=>iu(og(q,r),{order:q.order,side:S,store:l}),M=typeof m.passphrase=="string"?m.passphrase:"";if(typeof M!="string")throw new u("bad-input",{field:"passphrase"});if(M.length>0&&M.length<rg)throw new u("bad-input",{field:"passphrase",min:rg});let K=Tt(m.order),G=null;{let q=l.storage(),oe=typeof m.recoveryKey=="string"?m.recoveryKey:m.recoveryKey&&typeof m.recoveryKey.mnemonic=="string"?m.recoveryKey.mnemonic:null,se=Id(q);if(se&&oe&&se.mnemonic!==oe)throw new u("bad-input",{field:"recoveryKey",why:"different-key"});if(!se&&!oe)throw new u("bad-input",{field:"recoveryKey"});let ce=se||Ed(oe);se||ai(q,{...ce,backupConfirmed:!1});let Me=m.order.chainId;if(typeof m.order.factory!="string"||!m.order.factory)throw new u("bad-input",{field:"order.factory"});let Ue;try{Ue=qt(m.recoverySalt)}catch{throw new u("bad-input",{field:"recoverySalt"})}let qe;try{qe=qt(m.order.salt)}catch{throw new u("bad-input",{field:"recoverySalt",why:"order-salt"})}if(Ue!==qe)throw new u("bad-input",{field:"recoverySalt",why:"order-salt"});let Xe=sr({mnemonic:ce.mnemonic,chainId:Me,factory:m.order.factory,salt:Ue});G={storage:q,key:ce,salt:Ue,derivation:"salt-v2",newKey:!se||se.backupConfirmed!==!0},S=Pd(m.order,{spendHalf:Xe.spendHalf,viewHalf:Xe.viewHalf}).side,_={half:Xe.makerViewHalf,point:Xe.makerViewPoint}}if(_){let q=m.counterparty&&typeof m.counterparty=="object"?m.counterparty:null,oe=Bd(q);if(oe.half===null)throw new u("quote-field-unbound",{step:"viewHalfClaimer",field:"viewHalfClaimer"});let se=!1;try{se=BigInt(oe.half)===BigInt(_.half)}catch{se=!1}if(!se)throw new u("quote-refused",{step:"viewHalfClaimer",why:"not-the-derived-half"});if(oe.point!==null&&String(oe.point).replace(/^0x/,"").toLowerCase()!==String(_.point).replace(/^0x/,"").toLowerCase())throw new u("quote-refused",{step:"viewHalfClaimer",why:"point-mismatch"})}let Z=null;try{Z=await R(m)}catch(q){throw q&&typeof q.code=="string"?q:new u("storage-unavailable",{step:"create-record"})}if(!Z||!Z.swap)throw new u("bad-input",{field:"record"});let V=Z,J=m.readyWindow||m.quote&&m.quote.readyWindow||null,re=null;J&&(re=vt(J,{side:"ask",field:"readyWindow"}),V.swap.readyWindow=re);let E=null;if(!V.swapWallet){let q=await Ty({order:m.order,side:Z.side||null,counterparty:m.counterparty||null,standIn:n!=="live",network:V.swap.moneroNetwork||r||null}),oe=V.swap.escrow&&typeof V.swap.escrow=="object"?V.swap.escrow:{};V.swap.escrow={...oe,half:q.wallet.spendHalf,viewHalf:q.wallet.viewHalf,edPointLocker:q.own.spendPoint,edViewPointLocker:q.own.viewPoint,edPointClaimer:q.wallet.otherSpendPoint,counterViewPoint:q.wallet.otherViewPoint,counterViewHalf:q.wallet.otherViewHalf,moneroAddress:q.wallet.address,moneroSpendPub:q.wallet.spendPub,moneroViewPub:q.wallet.viewPub,moneroNetwork:q.wallet.network,standIn:q.counterparty.standIn,providerId:q.counterparty.providerId,orderContext:q.context};try{fe.saveSwap(V.swap,l)}catch{throw new u("storage-unavailable",{step:"save-swap"})}if(V={...V,swapWallet:fe.halvesWalletOf(V.swap)},!V.swapWallet)throw new u("bad-input",{field:"swapWallet"});E=q}let F=await P(m,V.swap.moneroNetwork||r||null);V.swap.restoreHeight=F,V.restoreHeight=F,V.swap.escrow={...V.swap.escrow||{},moneroRestoreHeight:F};try{fe.saveSwap(V.swap,l)}catch{throw new u("storage-unavailable",{step:"save-restore-height"})}let L=null;if(G.newKey){if(typeof m.onRecoveryKey!="function")throw new u("bad-input",{field:"onRecoveryKey"});try{L={name:Nd(G.key),contents:await _d({mnemonic:G.key.mnemonic,createdAt:G.key.createdAt,passphrase:M})}}catch{throw new u("recovery-failed",{step:"encrypt-key"})}if(await m.onRecoveryKey(L)!==!0)throw new u("recovery-declined",{key:G.key.fingerprint});try{ai(G.storage,{...G.key,backupConfirmed:!0}),G.key={...G.key,backupConfirmed:!0}}catch{throw new u("storage-unavailable",{step:"save-recovery-key"})}}let z=m.wallet;if(!z||typeof z.send!="function"||typeof z.receipt!="function")throw new u("bad-input",{field:"wallet",missing:["send","receipt"],surface:"swaps.start",step:"lock"});if(f){let q=typeof z.address=="function"?await z.address():null;if(typeof q!="string"||!q)throw new u("bad-input",{field:"wallet",missing:["address"],surface:"swaps.start",step:"lock"});if(f.has(q.toLowerCase()))throw new u("address-denied",{step:"lock"})}let $=E?{commitHalfLocker:E.wallet.commitHalfLocker,commitHalfClaimer:E.wallet.commitHalfClaimer,edPointLocker:E.own.spendPoint,edPointClaimer:E.wallet.otherSpendPoint,edViewPointLocker:E.own.viewPoint}:{},ee={...m.order,...$,amountWei:m.order.amount};if(m.orderQuote&&(E||m.counterparty)){let q=ce=>String(ce??"").replace(/^0x/i,"").toLowerCase(),oe=E?E.wallet.commitHalfClaimer:m.counterparty.commitHalfClaimer||null,se=E?E.wallet.otherSpendPoint:m.counterparty.edPointClaimer||m.counterparty.edPub||null;if(!oe||!se||q(m.orderQuote.commitHalfClaimer)!==q(oe)||q(m.orderQuote.edPointClaimer)!==q(se))throw new u("quote-refused",{step:"quote-binding",why:"counterparty-half"})}let ne=m.orderQuote&&m.orderQuote.validUntil!==void 0?m.orderQuote.validUntil:void 0;if(ne!=null){let q=Number(ne),oe=typeof s=="function"?Number(s()):Date.now(),se=Math.floor(oe/1e3),ce=Ra({validUntil:q,nowSec:se,side:"ask",prepSec:0});if(!ce.ok)throw new u("quote-expired",{validUntil:Number.isFinite(q)?q:null,now:Number.isFinite(se)?se:null,remainingSec:ce.remainingSec,marginSec:ce.marginSec,prepSec:ce.prepSec,confirmBySec:ce.confirmBySec,step:"lock"})}ee.quote=m.orderQuote||null;let le=async({escrow:q,salt:oe})=>{if(!q||!/^0x[0-9a-fA-F]{40}$/.test(String(q)))return;let se=V.swap.escrow&&typeof V.swap.escrow=="object"?V.swap.escrow:{};V.swap.fundingPending=!0,V.swap.escrow={...se,address:q,salt:oe||se.salt||null,fundingPending:!0,fundingReason:"not-sent"};try{fe.saveSwap(V.swap,l)}catch{throw new u("storage-unavailable",{step:"save-pending"})}},de=null;try{de=await X0(ee,z,{call:w,onPredicted:le})}catch(q){if(V.swap.escrow&&V.swap.escrow.fundingReason==="not-sent"){delete V.swap.fundingPending,V.swap.escrow={...V.swap.escrow,fundingPending:!1,fundingReason:"send-rejected"};try{fe.saveSwap(V.swap,l)}catch{}}throw q&&typeof q.code=="string"?q:new u("server-unavailable",{step:"lock"})}if(de&&de.pending){let q=de.createHash||null,oe=de.predictedEscrow||null,se=V.swap.escrow&&typeof V.swap.escrow=="object"?V.swap.escrow:{};V.swap.fundingPending=!0,V.swap.escrow={...se,address:oe||se.address||null,fundTx:q||se.fundTx||null,fundingPending:!0,fundingReason:de.pendingReason||"no-receipt"};try{fe.saveSwap(V.swap,l)}catch{throw new u("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:q,reason:de.pendingReason||"no-receipt",predictedEscrow:oe,next:"receipt",readyWindow:re}}let ie=de&&de.escrow||null;if(ie){let q=V.swap.escrow&&typeof V.swap.escrow=="object"?V.swap.escrow:{};V.swap.escrow={...q,address:ie,evmBirthBlock:Number(de.birthBlock)>0?Number(de.birthBlock):q.evmBirthBlock??q.birthHeight??null};try{fe.saveSwap(V.swap,l)}catch{throw new u("storage-unavailable",{step:"save-escrow"})}}return{id:V.swap.id||null,escrow:ie,address:V.swapWallet&&V.swapWallet.address||null,step:"xmr-incoming",next:"watch",readyWindow:re}},async watch(m){if(!m||typeof m!="object")throw new u("bad-input",{field:"request"});let k=typeof m.id=="string"&&m.id?m.id:null;if(!k)throw new u("bad-input",{field:"id"});let x=m.expect!==void 0&&m.expect!==null,C=m.wallet!==void 0&&m.wallet!==null;if(x!==C)throw new u("bad-input",{field:x?"wallet":"expect"});if(x&&!(m.escrow||m.address))throw new u("bad-input",{field:"escrow"});let U=(()=>{try{return fe.getSwap(k,l)}catch{return null}})(),W=m.readyWindow||U&&(U.readyWindow||U.sellWindow)||null,Y=Number.isFinite(Number(m.pollMs))&&Number(m.pollMs)>0?Number(m.pollMs):B("watchPollMs",5e3),N=Number.isFinite(Number(m.timeoutMs))&&Number(m.timeoutMs)>0?Number(m.timeoutMs):B("watchTimeoutMs",12e5),S=Number.isFinite(Number(m.minConfirmations))&&Number(m.minConfirmations)>0?Math.trunc(Number(m.minConfirmations)):B("xmrConfirmations",10),_=m.verify&&typeof m.verify=="object"?{...m.verify,nodes:Array.isArray(m.verify.nodes)?m.verify.nodes:d&&typeof d.nodesFor=="function"?d.nodesFor(m.verify.network||m.network||r):[],minConfirmations:S}:null;if(_){if(!W)throw new u("bad-input",{field:"readyWindow",why:"not-in-record"});let F=vt(W,{side:"ask",field:"readyWindow"}),L=m.readyBySec!==void 0&&m.readyBySec!==null?Number(m.readyBySec):m.deadline&&m.deadline.readyBy!==void 0?Number(m.deadline.readyBy):null;L&&xu({readyBySec:L,nowSec:Math.floor(Date.now()/1e3),minConfirmations:S,blockTimeSec:B("xmrBlockTimeSec",120),minLeadSec:E0(F)})}if(!_)throw new u("bad-input",{field:"verify",why:"required"});let R=Date.now(),M=null;try{M=fe.getSwap(k,l)}catch{M=null}let K=m.escrow||M&&M.escrow&&M.escrow.address||null,G=Da(M&&M.escrow?M.escrow.evmBirthBlock??M.escrow.birthHeight:null),Z={checked:!1,error:null,logs:void 0},V=async()=>{if(Z.checked=!1,Z.error=null,Z.logs=void 0,!K){Z.error="no-escrow";return}try{Z.logs=await T({address:K,topics:[mo],fromBlock:G,toBlock:"latest"}),Z.checked=!0}catch(F){Z.error=F&&F.code||"logs-unread"}},J=(F,L)=>{if(!(!F||F.settlement)){F.settlement={kind:nn,phase:nn,at:L};try{fe.saveSwap(F,l)}catch{throw new u("storage-unavailable",{step:"decline"})}}},re=({source:F,at:L,waitedMs:z,address:$,chainChecked:ee,chainError:ne})=>({id:k,escrow:K,address:$||null,seen:!1,declined:!0,terminal:nn,code:Fa,source:F,at:L,waitedMs:z,chain:{checked:!!ee,error:ne||null}});if(M&&M.settlement&&M.settlement.kind===nn){let F=Number(M.settlement.at);return re({source:"record",at:Number.isFinite(F)?F:Date.now(),waitedMs:0,address:null,chainChecked:!1,chainError:null})}let E=null;for(;;){await V(),E={address:m.address||K,expectedXmr:m.expectedXmr??null,status:null};let F=L0({logs:Z.logs,escrow:K,at:Date.now()});if(F.declined)return J(M,F.at),re({source:F.source,at:F.at,waitedMs:Date.now()-R,address:E&&E.address,chainChecked:Z.checked,chainError:Z.error});if(_){let L=await _i(y({..._,nowSec:Math.floor(Date.now()/1e3)}));if(E.verify=L,!L.seen){if(Date.now()-R>=N)throw new u("xmr-timeout",{id:k,address:E.address,expectedXmr:E.expectedXmr,state:L.state,confirmations:L.confirmations??0,waitedMs:Date.now()-R,timeoutMs:N,pollMs:Y});await new Promise($=>setTimeout($,Y));continue}let z={seen:!0,id:k,address:E.address,status:E.status,expectedXmr:E.expectedXmr,receivedXmr:Number(L.amountAtomic)/1e12,confirmations:L.confirmations,txids:[L.txid],at:Date.now(),verified:{height:L.height,blockHash:L.blockHash,operators:L.operators,agreedBy:L.agreedBy},source:"client"};return x&&C?z.marked=await A.markReady({escrow:m.escrow||E.address,expect:m.expect,onStep:m.onStep},m.wallet):z.next="mark-ready",z}}},async startSell(m){if(!m||typeof m!="object")throw new u("bad-input",{field:"request"});let k=m.offer&&typeof m.offer=="object"?m.offer:null;if(!k)throw new u("bad-input",{field:"offer"});let x=k.order&&typeof k.order=="object"?k.order:null,C=k.quote&&typeof k.quote=="object"?k.quote:null;if(!x||!C)throw new u("bad-input",{field:"offer",missing:["order","quote"]});if(typeof k.jointAddress!="string"||!k.jointAddress)throw new u("bad-input",{field:"offer.jointAddress"});if(typeof k.escrow!="string"||!k.escrow)throw new u("bad-input",{field:"offer.escrow"});let U=k.relayUrl===void 0||k.relayUrl===null||k.relayUrl===""?null:wo(k.relayUrl),W=k.readyWindow||C&&C.readyWindow||null,Y=W?vt(W,{side:"bid",field:"offer.readyWindow"}):null,N=(le,de)=>String(le||"").replace(/^0x/,"").toLowerCase()===String(de||"").replace(/^0x/,"").toLowerCase();if(!N(C.locker,x.locker)||!N(C.claimer,x.claimer)||!N(C.provider,x.locker)||!N(C.factory,x.factory)||Number(C.chainId)!==Number(x.chainId))throw new u("quote-refused",{step:"sell-record",why:"terms"});let S=Et(C.provider,"provider"),_=C.quoteKey===void 0||C.quoteKey===null||String(C.quoteKey).trim()===""?null:Et(C.quoteKey,"quoteKey"),R=m.claimSender===void 0||m.claimSender===null||String(m.claimSender).trim()===""?null:Et(m.claimSender,"claimSender");if(R&&R===S)throw new u("bad-input",{field:"claimSender",why:"is-deal-maker"});if(R&&_&&R===_)throw new u("bad-input",{field:"claimSender",why:"is-quote-key"});let M=C.id||C.nonce||null,K=O().find(le=>le.side==="sell"&&(le.escrow&&String(le.escrow.address||"").toLowerCase()===String(k.escrow).toLowerCase()||M!==null&&String(le.orderQuoteId||"")===String(M)));if(K){let le=K.quote&&typeof K.quote=="object"?K.quote:{},de=(se,ce)=>String(se||"").replace(/^0x/,"").toLowerCase()===String(ce||"").replace(/^0x/,"").toLowerCase();if(!de(le.commitHalfClaimer,C.commitHalfClaimer)||!de(le.edPointClaimer,C.edPointClaimer)||!de(K.escrow&&K.escrow.moneroAddress,k.jointAddress))throw new u("quote-refused",{step:"sell-record",why:"offer-changed"});let ie=K.claimSender?Et(K.claimSender,"claimSender"):null;if(R&&R!==ie){K.claimSender=R,delete K.claimSenders;try{fe.saveSwap(K,l)}catch{throw new u("storage-unavailable",{step:"save-claim-sender"})}}let q=K.relayUrl?wo(K.relayUrl):null;if(U&&q&&U!==q)throw new u("quote-refused",{step:"sell-record",why:"relay-changed"});if(await H(K.escrow&&K.escrow.address||k.escrow,K.expect||null,m.wallet),U&&!q){K.relayUrl=U;try{fe.saveSwap(K,l)}catch{throw new u("storage-unavailable",{step:"save-relay"})}}let oe=K.readyWindow||K.sellWindow||null;if(Y&&oe){let se=vt(oe,{side:"bid",field:"readyWindow"});if(se.readyMinSeconds!==Y.readyMinSeconds||se.readyMaxSeconds!==Y.readyMaxSeconds)throw new u("quote-refused",{step:"sell-record",why:"window-changed"})}if(Y&&!oe){K.readyWindow=Y;try{fe.saveSwap(K,l)}catch{throw new u("storage-unavailable",{step:"save-window"})}}return{id:K.id,side:"sell",escrow:K.escrow&&K.escrow.address||k.escrow,address:K.escrow&&K.escrow.moneroAddress||k.jointAddress,xmrAmount:K.escrow&&K.escrow.xmrAmount||C.xmrAmount,claimTip:K.claimTip||C.claimTip,orderQuote:K.orderQuote||k.orderQuote,claimSender:K.claimSender||null,readyWindow:K.readyWindow||K.sellWindow||null,resumed:!0,next:"send-xmr"}}let G=l.storage(),Z=typeof m.recoveryKey=="string"?m.recoveryKey:m.recoveryKey&&typeof m.recoveryKey.mnemonic=="string"?m.recoveryKey.mnemonic:null,V=Id(G);if(V&&Z&&V.mnemonic!==Z)throw new u("bad-input",{field:"recoveryKey",why:"different-key"});if(!V&&!Z)throw new u("bad-input",{field:"recoveryKey"});let J=V||Ed(Z);if(V||ai(G,{...J,backupConfirmed:!1}),!V||V.backupConfirmed!==!0){if(typeof m.onRecoveryKey!="function")throw new u("bad-input",{field:"onRecoveryKey"});let le=null;try{le={name:Nd(J),contents:await _d({mnemonic:J.mnemonic,createdAt:J.createdAt,passphrase:m.passphrase})}}catch{throw new u("recovery-failed",{step:"encrypt-key"})}if(await m.onRecoveryKey(le)!==!0)throw new u("recovery-declined",{key:J.fingerprint});try{ai(G,{...J,backupConfirmed:!0})}catch{throw new u("storage-unavailable",{step:"save-recovery-key"})}}let re=Number(x.chainId);if(!Number.isSafeInteger(re)||re<=0)throw new u("bad-input",{field:"order.chainId"});if(!x.factory||x.salt===void 0||x.salt===null)throw new u("bad-input",{field:"order"});let E=null;try{E=qt(k.recovery&&k.recovery.salt?k.recovery.salt:x.salt)}catch{throw new u("bad-input",{field:"offer.recovery"})}let F=sr({mnemonic:J.mnemonic,chainId:re,factory:x.factory,salt:E}),L=Pd(x,{spendHalf:F.spendHalf,viewHalf:F.viewHalf}),z=L.commitHalf,$=le=>String(le||"").replace(/^0x/,"").toLowerCase();if(!z||$(z)!==$(C.commitHalfClaimer))throw new u("quote-refused",{step:"sell-record",why:"commitment"});if(String(L.spendPoint).toLowerCase()!==String(C.edPointClaimer||"").toLowerCase())throw new u("quote-refused",{step:"sell-record",why:"spend-point"});if(k.edViewPointClaimer&&String(L.viewPoint).toLowerCase()!==String(k.edViewPointClaimer).toLowerCase())throw new u("quote-refused",{step:"sell-record",why:"view-point"});let ne=iu({side:"sell",network:String(x.chainId),moneroNetwork:r||void 0,payToken:x.asset||C.asset||void 0,payAmount:C.amount,xmrAmount:Number(C.xmrAmount)/1e12,orderQuoteId:M||void 0,receiveAddress:x.claimer,makerId:C.provider||null},{order:x,side:L.side,store:l}).swap;ne.side="sell",ne.order=x,ne.orderQuote=k.orderQuote||null,ne.quote=C,ne.claimTip=C.claimTip||null,R&&(ne.claimSender=R),ne.expect={chainId:re,factory:x.factory,locker:x.locker,claimer:x.claimer,amount:String(x.amount),readyBy:x.readyBy,t1:x.t1,salt:x.salt,commitHalfLocker:k.nodeHalf&&k.nodeHalf.commitHalf||null,edPointLocker:k.nodeHalf&&k.nodeHalf.edPoint||null,edViewPointLocker:k.edViewPointLocker||null,commitHalfClaimer:C.commitHalfClaimer||null,edPointClaimer:C.edPointClaimer||null},ne.escrow={...ne.escrow||{},address:k.escrow,moneroAddress:k.jointAddress,half:Jt(L.side.half),viewHalf:Jt(L.side.viewHalf),edPointClaimer:L.spendPoint,edViewPointClaimer:be(L.side.viewPub),commitHalfClaimer:C.commitHalfClaimer,edPointLocker:k.nodeHalf&&k.nodeHalf.edPoint||null,edViewPointLocker:k.edViewPointLocker||null,commitHalfLocker:k.nodeHalf&&k.nodeHalf.commitHalf||null,orderContext:k.context||null,xmrAmount:C.xmrAmount||null},U&&(ne.relayUrl=U),Y&&(ne.readyWindow=Y);try{await H(k.escrow,ne.expect,m.wallet)}catch(le){try{fe.forgetSwap(ne.id,l)}catch{}throw le}try{fe.saveSwap(ne,l)}catch{throw new u("storage-unavailable",{step:"save-swap"})}return{id:ne.id,side:"sell",escrow:k.escrow,address:k.jointAddress,xmrAmount:C.xmrAmount,claimTip:C.claimTip||null,orderQuote:k.orderQuote||null,claimSender:ne.claimSender||null,readyWindow:ne.readyWindow||null,resumed:!1,next:"send-xmr"}},async sellClaim(m,k){if(!m||typeof m!="object")throw new u("bad-input",{field:"request"});let x=String(m.id||"").trim();if(!x)throw new u("bad-input",{field:"id"});let C=null;try{C=fe.getSwap(x,l)}catch{C=null}if(!C||C.side!=="sell")throw new u("bad-input",{field:"id",why:"sell-not-found"});let U=m.escrow||C.escrow&&C.escrow.address||null,W=m.halfClaimer||C.escrow&&C.escrow.half||null;if(!U||!W)throw new u("bad-input",{field:"escrow",missing:["escrow","halfClaimer"]});let Y=m.expect||C.expect||null;if(!Y)throw new u("bad-input",{field:"expect",why:"not-in-record"});return A.claim({escrow:U,halfClaimer:W,claimer:C.order&&C.order.claimer,expect:Y,onStep:m.onStep},k)},async claimViaRelay(m={}){if(!m||typeof m!="object")throw new u("bad-input",{field:"request"});let k=String(m.id===void 0||m.id===null?"":m.id).trim();if(!k)throw new u("bad-input",{field:"id"});let x=null;try{x=fe.getSwap(k,l)}catch{x=null}if(!x||x.side!=="sell")throw new u("bad-input",{field:"id",why:"sell-not-found"});let C=0n;try{C=BigInt(x.claimTip===void 0||x.claimTip===null||x.claimTip===""?0:x.claimTip)}catch{throw new u("bad-input",{field:"claimTip",why:"unreadable"})}if(C<=0n)throw new u("bad-input",{field:"claimTip",why:"not-positive"});let U=x.quote&&typeof x.quote=="object"?x.quote:{},W=x.order&&typeof x.order=="object"?x.order:{},Y=x.escrow&&typeof x.escrow=="object"?x.escrow:{},N=U.provider!==void 0&&U.provider!==null?U.provider:Y.providerId!==void 0&&Y.providerId!==null?Y.providerId:W.locker;if(N==null||N==="")throw new u("bad-input",{field:"provider",why:"not-in-record"});let S=Et(N,"provider");for(let[se,ce]of[["order.locker",W.locker],["quote.locker",U.locker]])if(ce!=null&&String(ce)!==""&&Et(ce,se)!==S)throw new u("quote-refused",{step:"relay-claim",why:"provider"});let _=U.quoteKey===void 0||U.quoteKey===null||String(U.quoteKey).trim()===""?null:Et(U.quoteKey,"quoteKey"),R=x.claimSender===void 0||x.claimSender===null||String(x.claimSender).trim()===""?null:x.claimSender,M=m.claimSender===void 0||m.claimSender===null||String(m.claimSender).trim()===""?null:m.claimSender;if(m.claimSenders!==void 0&&!Array.isArray(m.claimSenders))throw new u("bad-input",{field:"claimSenders",why:"not-an-array"});let K=Array.isArray(m.claimSenders)?m.claimSenders:null;if(K&&K.length===0)throw new u("bad-input",{field:"claimSenders",why:"empty"});if(K&&M)throw new u("bad-input",{field:"claimSenders",why:"with-claim-sender"});let G=K||(M?[M]:null)||(Array.isArray(x.claimSenders)?x.claimSenders:null)||(R?[R]:[]);if(!G.length)throw new u("bad-input",{field:"claimSenders",why:"not-in-record"});let Z=[];for(let se of G){if(se==null||String(se).trim()==="")throw new u("bad-input",{field:"claimSenders",why:"empty"});let ce=Et(se,"claimSenders");if(ce===S)throw new u("bad-input",{field:"claimSenders",why:"is-deal-maker"});if(_&&ce===_)throw new u("bad-input",{field:"claimSenders",why:"is-quote-key"});Z.includes(ce)||Z.push(ce)}if(!Z.length)throw new u("bad-input",{field:"claimSenders",why:"not-in-record"});if(Y.address===void 0||Y.address===null||Y.address==="")throw new u("bad-input",{field:"escrow",why:"not-in-record"});let V=Et(Y.address,"escrow"),J=ku(Y.half);if(x.relayUrl===void 0||x.relayUrl===null||x.relayUrl==="")throw new u("bad-input",{field:"relayUrl",why:"not-in-record"});let re=wo(x.relayUrl);if(m.relayUrl!==void 0&&m.relayUrl!==null&&String(m.relayUrl).trim()!==""&&wo(m.relayUrl)!==re)throw new u("bad-input",{field:"relayUrl",why:"foreign-relay"});if(!Array.isArray(x.claimSenders)||x.claimSenders.length!==Z.length||x.claimSenders.some((se,ce)=>String(se).toLowerCase()!==Z[ce])){x.claimSenders=Z,x.claimSender=Z[0];try{fe.saveSwap(x,l)}catch{throw new u("storage-unavailable",{step:"save-claim-senders"})}}let E=Number.isFinite(Number(m.timeoutMs))&&Number(m.timeoutMs)>0?Number(m.timeoutMs):2e4,F=Number.isFinite(Number(m.slotMs))&&Number(m.slotMs)>0?Math.min(3e4,Math.max(15e3,Number(m.slotMs))):2e4,L=Number.isFinite(Number(m.pollMs))&&Number(m.pollMs)>0?Math.min(F,Number(m.pollMs)):2e3,z=async()=>{try{return await Rn(V,{call:w})}catch{return null}},$=W.t1??(x.expect&&x.expect.t1),ee=Number.isSafeInteger(Number($))&&Number($)>0?Number($):null,ne=()=>ee===null?null:Math.max(0,ee-Math.floor(v()/1e3)),le=(se=null,ce=null,Me=[])=>({id:k,state:"claimed",provider:se,claimSender:se,escrow:V,relayUrl:re,txid:ce?ce.txid:null,from:ce&&ce.from||null,tipWei:ce&&ce.tipWei||C.toString(),tried:Me}),de=await z();if(de&&de.isClaimed)return le();let ie=!!(de&&de.isRefunded),q=[];if(!ie)for(let se of Z){let ce=null,Me=null;try{ce=await tg({relayUrl:re,provider:se,escrow:V,halfClaimer:J,expectedTipWei:C,fetchImpl:m.fetchImpl||i||null,timeoutMs:E})}catch(qe){Me=qe}if(Me&&Me.code!=="claim-unknown"){q.push({sender:se,outcome:"refused",code:Me.code||"unknown",params:Me.params||null});continue}let Ue=v()+F;for(;;){let qe=await z();if(qe&&qe.isClaimed){x.claimSender=se;try{fe.saveSwap(x,l)}catch{}return le(se,ce,q)}if(qe&&qe.isRefunded){ie=!0;break}let Xe=Ue-v();if(Xe<=0)break;await I(Math.min(L,Xe))}if(q.push({sender:se,outcome:Me?"unknown":"unconfirmed",txid:ce?ce.txid:null,code:Me?Me.code:null}),ie)break}let oe=await z();if(oe&&oe.isClaimed){try{fe.saveSwap(x,l)}catch{}return le(null,null,q)}return oe&&oe.isRefunded&&(ie=!0),{id:k,state:"claim-yourself",reason:ie?"escrow-refunded":"senders-exhausted",provider:null,claimSender:null,escrow:V,relayUrl:re,txid:null,from:null,tipWei:C.toString(),t1:ee,secondsLeft:ne(),tried:q}},async sellWatch(m){if(!m||typeof m!="object")throw new u("bad-input",{field:"request"});let k=String(m.escrow||"").trim();if(!k)throw new u("bad-input",{field:"escrow"});let x=FA(l,k),C=m.readyWindow||x&&(x.readyWindow||x.sellWindow)||null,U=Number.isFinite(Number(m.pollMs))&&Number(m.pollMs)>0?Number(m.pollMs):B("watchPollMs",6e3),W=Number.isFinite(Number(m.timeoutMs))&&Number(m.timeoutMs)>0,Y=!W&&C?vt(C,{side:"bid",field:"readyWindow"}):null;if(!Y&&!W)throw new u("bad-input",{field:"readyWindow",why:"not-in-record"});let N=W?Number(m.timeoutMs):null;if(!W)try{let G=await fr(k,{call:w});N=OA({configuredMs:eu(Y),readyBySec:G.readyBy})}catch{N=eu(Y)}let S=null;try{S=await fr(k,{call:w})}catch{}let _=()=>{let G=typeof s=="function"?Number(s()):Date.now();return Number.isFinite(G)?Math.floor(G/1e3):null},R=Date.now(),M=null,K=null;for(;;){try{M=await Rn(k,{call:w})}catch(G){K=G&&G.code||"status-unread",M=null}if(M&&(M.isClaimed||M.isRefunded))return{escrow:k,state:M.isClaimed?"claimed":"refunded",funded:M.isFunded,claimed:M.isClaimed,refunded:M.isRefunded,ready:null,claimOpen:!1,balanceWei:String(M.balance),waitedMs:Date.now()-R};if(M&&M.isFunded){let G=null;try{let Z=await w({to:k,data:He.encodeRead("ready")}),V=String(Z||"").replace(/^0x/,"");G=V.length>0&&BigInt("0x"+V)!==0n}catch(Z){K=Z&&Z.code||"ready-unread"}if(G===!0)return{escrow:k,state:"ready",funded:!0,claimed:!1,refunded:!1,ready:!0,claimOpen:!1,balanceWei:String(M.balance),waitedMs:Date.now()-R}}if(M&&M.isFunded&&S&&Number.isSafeInteger(Number(S.readyBy))){let G=_();if(G!==null&&G>=Number(S.readyBy))return{escrow:k,state:"claim-open",funded:!0,claimed:!1,refunded:!1,ready:!1,claimOpen:!0,balanceWei:String(M.balance),waitedMs:Date.now()-R}}if(Date.now()-R>=N)throw new u("sell-timeout",{escrow:k,waitedMs:Date.now()-R,timeoutMs:N,status:M,error:K});await new Promise(G=>setTimeout(G,U))}}}}me();me();var LA=/^0x[0-9a-fA-F]{40}$/,DA=/^0x[0-9a-fA-F]{64}$/,MA=/^\d+$/,Wa=e=>typeof e=="string"&&LA.test(e)?e.toLowerCase():null,wr=e=>typeof e=="string"&&DA.test(e)?e.toLowerCase():null;function sg({order:e=null,chainId:t=null,half:n=null}={}){if(!e||typeof e!="object")throw new u("bad-input",{field:"order"});let r=Number(t);if(!Number.isSafeInteger(r)||r<=0)throw new u("bad-input",{field:"chainId"});let o=e.side;if(o!=="locker"&&o!=="claimer")throw new u("bad-input",{field:"order.side"});let i=Wa(e.escrow),s=Wa(e.locker),a=Wa(e.claimer),c=Wa(e.factory),l=wr(e.salt),d=wr(e.commitHalfLocker),f=wr(e.commitHalfClaimer),p=wr(e.edPointLocker),h=wr(e.edPointClaimer),w=wr(e.edViewPointLocker),b=wr(n),y=typeof e.amount=="string"?e.amount:typeof e.amount=="bigint"?e.amount.toString():null,v=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"),d||g.push("commitHalfLocker"),f||g.push("commitHalfClaimer"),p||g.push("edPointLocker"),h||g.push("edPointClaimer"),w||g.push("edViewPointLocker"),b||g.push("half"),(!y||!MA.test(y)||BigInt(y)<=0n)&&g.push("amount"),(!Number.isSafeInteger(v)||v<=0)&&g.push("readyBy"),(!Number.isSafeInteger(I)||I<=0)&&g.push("t1"),g.length)throw new u("bad-input",{field:"order",missing:g});return Object.freeze({side:o,kind:o==="locker"?"refund":"claim",escrow:i,half:b,claimer:a,expect:Object.freeze({chainId:r,factory:c,locker:s,claimer:a,amount:y,readyBy:v,t1:I,salt:l,commitHalfLocker:d,commitHalfClaimer:f,edPointLocker:p,edPointClaimer:h,edViewPointLocker:w})})}_e();me();var UA=2,jA=10,yo=(e,t)=>{try{return BigInt(e)}catch{throw new u("bad-input",{field:t})}},WA=e=>{if(!e||typeof e.driver!="function")throw new u("bad-input",{field:"wallet.driver"});let t=e.driver();if(!t||typeof t!="object")throw new u("bad-input",{field:"wallet.driver"});let n=["setRestoreHeight","getBalance"].filter(r=>typeof t[r]!="function");if(n.length)throw new u("bad-input",{field:"wallet.driver",missing:n});return t},Rt=async(e,t)=>{try{return await t()}catch(n){throw n instanceof u?n:new u("wallet-rejected",{surface:e,why:String(n&&n.message||n)})}},ag=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}},cg=async(e,{syncError:t=null,rescanError:n=null,spentChecked:r=!0}={})=>{let o=await ag(e,"getHeight"),i=await ag(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 KA({nodeUrl:e,fromHeight:t,toHeight:n,fetchImpl:r=globalThis.fetch,sleep:o=VA,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 u("bad-input",{field:"window.nodeUrl"});if(!Number.isSafeInteger(a)||a<0)throw new u("bad-input",{field:"window.fromHeight"});if(!Number.isSafeInteger(c)||c<a)throw new u("bad-input",{field:"window.toHeight"});if(typeof r!="function")throw new u("bad-input",{field:"fetchImpl"});let l=Math.max(1,Math.min(5,Number(i)||3)),d=[];for(let f=a;f<=c;f+=1){let p=null,h=null;for(let v=1;v<=l;v+=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:f}}),signal:typeof AbortSignal<"u"&&AbortSignal.timeout?AbortSignal.timeout(8e3):void 0})}catch{if(p=null,h=new u("wallet-rejected",{surface:"window-blocks",height:f,why:"transport"}),v<l){await o(lg(v));continue}throw h}if(p&&p.ok===!0){h=null;break}let I=p?p.status:null;if(h=new u("wallet-rejected",{surface:"window-blocks",height:f,status:I}),(I===429||I!==null&&I>=500)&&v<l){await o($A(p)??lg(v));continue}throw h}if(!p||p.ok!==!0)throw h||new u("wallet-rejected",{surface:"window-blocks",height:f});let w=null;try{w=await p.json()}catch{throw new u("wallet-rejected",{surface:"window-blocks",height:f,why:"not-json"})}if(!w||w.error||!w.result)throw new u("wallet-rejected",{surface:"window-blocks",height:f,why:"rpc"});let b=w.result,y=Array.isArray(b.tx_hashes)?b.tx_hashes:null;if(!y&&typeof b.json=="string")try{let v=JSON.parse(b.json);y=Array.isArray(v.tx_hashes)?v.tx_hashes:null}catch{y=null}if(!y)throw new u("wallet-rejected",{surface:"window-blocks",height:f,why:"no-tx-hashes"});d.push(...y.map(String))}return d}var VA=e=>new Promise(t=>setTimeout(t,e)),lg=e=>Math.min(4e3,250*2**Math.max(0,e-1));function $A(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 dg(e={}){let t=e.wallet;if(!t||typeof t!="object")throw new u("bad-input",{field:"wallet"});let n=["sync","unlockedBalance"].filter(g=>typeof t[g]!="function");if(n.length)throw new u("bad-input",{field:"wallet",missing:n});let r=Number(e.fromHeight);if(!Number.isFinite(r)||r<=0)throw new u("bad-input",{field:"restoreHeight"});let o=Number.isFinite(Number(e.scanBack))&&Number(e.scanBack)>=0?Math.floor(Number(e.scanBack)):jA,i=Math.max(0,Math.floor(r)-o),s=WA(t),a=e.window&&typeof e.window=="object"?e.window:null,c=null,l=0n,d=0n;if(a){let g=Number(a.tipHeight);if(!Number.isSafeInteger(g)||g<=0)throw new u("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 T=Array.isArray(a.txHashes)?a.txHashes.map(String):null;if(T===null)try{T=await KA({nodeUrl:a.nodeUrl,fromHeight:r,toHeight:a.toHeight,fetchImpl:e.fetchImpl})}catch(A){if(A&&A.code==="bad-input")throw A;c.fallback=!0,c.fallbackWhy="window-read",c.error={code:A&&A.code?A.code:"wallet-rejected",surface:A&&A.params&&A.params.surface?A.params.surface:"window-blocks",status:A&&A.params&&A.params.status!==void 0?A.params.status:null,height:A&&A.params&&A.params.height!==void 0?A.params.height:null,why:A&&A.params&&A.params.why?A.params.why:null},T=[]}if(c.txs=T.length,T.length&&typeof s.scanTxs=="function"){let A=null;try{await Rt("setRestoreHeight",()=>s.setRestoreHeight(g)),await Rt("scanTxs",()=>s.scanTxs(T));try{await t.sync()}catch(B){A=B}l=yo(await Rt("getBalance",()=>s.getBalance()),"balance"),d=yo(await Rt("unlockedBalance",()=>t.unlockedBalance()),"unlockedBalance"),c.used=!0}catch(B){if(B&&B.code==="bad-input")throw B;l=0n,d=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(),O=(Array.isArray(B)?B:B&&typeof B.getKeyImages=="function"?B.getKeyImages():[]).map(j=>typeof j=="string"?j:j&&typeof j.getHex=="function"?j.getHex():j&&j.hex).filter(Boolean);if(O.length){let j=String(a.nodeUrl);for(;j.endsWith("/");)j=j.slice(0,-1);let D=await(e.fetchImpl||globalThis.fetch)(j+"/is_key_image_spent",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({key_images:O}),signal:typeof AbortSignal<"u"&&AbortSignal.timeout?AbortSignal.timeout(8e3):void 0}),X=D&&D.ok===!0?await D.json():null;X&&Array.isArray(X.spent_status)?(c.spent=X.spent_status.filter(H=>H===!0||H===1).length,c.keyImages=O.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||d>0n||a.fallback===!1)){let B=await cg(s,{syncError:A,spentChecked:c.spent!==null&&c.spent!==void 0});return{total:l.toString(),unlocked:d.toString(),scanHeight:i,...B,passes:1,lockedPass:!1,window:c}}}else T.length&&(c.skipped="no-scan-txs")}if(c&&(c.fallback=!0,c.fallbackWhy||(c.fallbackWhy="empty-window")),await Rt("setRestoreHeight",()=>s.setRestoreHeight(i)),typeof s.rescanBlockchain!="function")throw new u("bad-input",{field:"wallet.driver.rescanBlockchain"});let f=null;try{await Rt("rescanBlockchain",()=>s.rescanBlockchain())}catch(g){f=g}let p=null;try{await t.sync()}catch(g){p=g}let h=yo(await Rt("getBalance",()=>s.getBalance()),"balance"),w=yo(await Rt("unlockedBalance",()=>t.unlockedBalance()),"unlockedBalance"),b=1,y=!1;if(e.rescanWhenLocked!==!1&&h>0n&&w===0n&&typeof s.rescanSpent=="function"&&b<UA){y=!0,await Rt("rescanSpent",()=>s.rescanSpent());try{await t.sync()}catch(g){p=g}h=yo(await Rt("getBalance",()=>s.getBalance()),"balance"),w=yo(await Rt("unlockedBalance",()=>t.unlockedBalance()),"unlockedBalance"),b+=1}let I=await cg(s,{syncError:p,rescanError:f});return{total:h.toString(),unlocked:w.toString(),scanHeight:i,...I,passes:b,lockedPass:y,window:c}}me();function ug(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 go="monero",zA="ninsei-wallet-session",XA=["mainnet","stagenet","testnet","fakechain"],YA=()=>{let e=pe.XMR_NETWORKS||{};return[...new Set([...Object.values(e).filter(t=>typeof t=="string"&&t),...XA])].sort()};function fg({createWallet:e=null,network:t=null,serverUri:n=null,password:r=zA,keys:o={},restoreHeight:i=0,expectedAddress:s=null}={}){let a=null,c=null,l=new Set,d=()=>{for(let w of l)try{w()}catch{}},f=w=>{if(a===null)throw new u("wallet-not-connected",{vm:go,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 u("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 u("bad-input",{field:"keys",missing:["seed","privateSpendKey"]})},h=async()=>{if(a===null)return;let w=a;a=null,c=null;try{await w.close()}catch{}};return{vm:go,id:go,async connect(){if(typeof e!="function")throw new u("bad-input",{field:"createWallet"});let w=YA();if(typeof t!="string"||!t)throw new u("bad-input",{field:"network",known:w});if(w.length&&!w.includes(t))throw new u("bad-input",{field:"network",known:w,got:t});if(typeof n!="string"||!n)throw new u("bad-input",{field:"serverUri"});let b=p(),y=Number(i);if(!Number.isFinite(y)||y<=0)throw new u("bad-input",{field:"restoreHeight",got:i});await h(),a=await e({networkType:t,server:{uri:n},password:r,restoreHeight:y,...b}),c=String(await a.getAddress(0,0));let I=typeof hn.networkFromShape=="function"?hn.networkFromShape(c):null;if(I&&I!==t)throw await h(),new u("wrong-chain",{got:I,want:t});if(s&&c!==s)throw await h(),new u("recovery-failed",{step:"address"});await a.setRestoreHeight(y),d()},async disconnect(){return await h()},async close(){return await h()},address(){return f("address"),c},chainId(){return t},async unlockedBalance(){return await f("unlockedBalance").getUnlockedBalance()},async sync(){await f("sync").sync(),d()},async open(w){if(a===null)throw new u("wallet-not-connected",{vm:go,surface:"open"});let b=w&&w.address?String(w.address):null;if(b&&c!==b)throw new u("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 ug(w)},subscribe(w){if(typeof w!="function")throw new u("bad-input",{field:"handler"});return l.add(w),()=>l.delete(w)},async send(){throw new u("not-implemented",{surface:"adapter.send",vm:go})},async receipt(){throw new u("not-implemented",{surface:"adapter.receipt",vm:go})},driver(){return a}}}$n();var GA=e=>typeof e=="string"?e.trim():"";function QA(e){let t=e&&e.receive;return(t&&typeof t.address=="string"?t.address.trim():"")||null}async function pg(e,t){let n=GA(t),r=QA(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 Wc(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 ZA=/^[0-9a-f]{64}$/;function mg(e){let t=String(e??"").trim(),n=(t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t).toLowerCase();return!ZA.test(n)||/^0+$/.test(n)?null:"0x"+n}var hg=10n**BigInt(12);function wg(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/hg,s=(o%hg).toString().padStart(12,"0"),a=t?s.replace(/0+$/,""):s,c=a?`${i}.${a}`:`${i}`;return r?`-${c}`:c}var qA=e=>{if(e==null||e==="")return null;let t=String(e);if(/^\d+$/.test(t))return wg(BigInt(t));let n=Number(t);return Number.isFinite(n)&&n>0?t:null},Ka=12,JA=["unlock","sync","sweep","relay"],e6=10000000000n;function t6({feeAtomic:e=null,amountAtomic:t=null,maxFeeAtomic:n=e6}={}){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 n6="0x3f267bb6",vu=e=>typeof e=="string"?e:e&&typeof e.contents=="string"?e.contents:null,bo=e=>String(e??"").replace(/^0x/i,"").toLowerCase(),r6=async e=>{let t=e&&e.order;if(!t||typeof t!="object")throw new u("bad-input",{field:"order"});if(typeof e.mnemonic!="string"||!e.mnemonic.trim())throw new u("bad-input",{field:"mnemonic"});let n=Number(e.chainId);if(!Number.isSafeInteger(n)||n<=0)throw new u("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 u("bad-input",{field:"network"});if(!o)throw new u("bad-input",{field:"moneroNetwork"});let i=typeof e.passphrase=="string"?e.passphrase:"";if(i&&i.length<Ka)throw new u("bad-input",{field:"passphrase",min:Ka});let s=t.side==="locker"?"buy":t.side==="claimer"?"sell":null;if(!s)throw new u("bad-input",{field:"order.side"});if(typeof t.factory!="string"||!/^0x[0-9a-fA-F]{40}$/.test(t.factory))throw new u("bad-input",{field:"order.factory"});let a=sr({mnemonic:e.mnemonic,chainId:n,factory:t.factory,salt:t.salt}),c=s==="buy";if(bo(c?t.edPointLocker:t.edPointClaimer)!==bo(a.spendPoint))throw new u("bad-input",{field:"order",why:"spend-point"});if(bo(t.edViewPointLocker)!==bo(c?a.viewPoint:a.makerViewPoint))throw new u("bad-input",{field:"order",why:c?"own-view-point":"maker-view-point"});let l="0x"+bo(c?t.edPointClaimer:t.edPointLocker),d="0x"+bo(a.makerViewPoint),f=eo({ownSpendHalf:a.spendHalf,ownViewHalf:a.viewHalf,otherSpendPoint:l,otherViewPoint:d,network:o}),p=(()=>{try{let y=BigInt(String(t.xmrAmount));return y>0n?y.toString():null}catch{return null}})(),h={address:t.escrow,readyBy:t.readyBy,t1:t.t1,...p?{expectedAtomic:p}:{}},w=at.buildPayload({swap:{id:t.escrow,side:s,network:r,moneroNetwork:o,createdAt:t.blockTime?Number(t.blockTime)*1e3:null,payToken:null,payAmount:null,xmrAmount:qA(t.xmrAmount),rate:null,maker:null,quoteSignature:null,escrow:h,timeline:null},swapWallet:{source:"halves",network:o,address:f.address,spendHalf:a.spendHalf,viewHalf:a.viewHalf,otherSpendPoint:l,otherViewPoint:d,otherViewHalf:a.makerViewHalf,escrowAddress:t.escrow},escrow:h,receiveAddress:null,restoreHeight:Number(t.startHeight)>0?Number(t.startHeight):null}),b=sg({order:t,chainId:n,half:a.spendHalf});return{payload:w,contents:await at.createRecoveryFile(w,i),address:f.address,...b}},yg=async(e,t)=>{try{return await t()}catch(n){throw n instanceof u?n:new u("wallet-rejected",{surface:e,why:String(n&&n.message||n)})}},o6=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 gg({call:e=null}){let t=new Map,n=0,r={mainnet:"MAINNET",stagenet:"STAGENET",testnet:"TESTNET"},o={async fromOrder(i={}){return await r6(i)},wallet(i={}){let s=i.moneroTs;if(!s||typeof s!="object")throw new u("bad-input",{field:"moneroTs"});if(typeof s.createWalletFull!="function")throw new u("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 u("bad-input",{field:"network",known:Object.keys(r),got:i.network});if(typeof i.serverUri!="string"||!i.serverUri)throw new u("bad-input",{field:"serverUri"});return fg({createWallet:d=>s.createWalletFull({...d,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=vu(i.file);if(!s)throw new u("bad-input",{field:"file"});if(typeof i.passphrase!="string")throw new u("bad-input",{field:"passphrase"});if(typeof i.dest!="string"||!i.dest.trim())throw new u("bad-input",{field:"dest"});let a=null;try{a=await at.decryptFile(JSON.parse(s),i.passphrase)}catch{throw new u("recovery-failed",{step:"decrypt"})}try{at.validatePayload(a)}catch{throw new u("recovery-failed",{step:"validate"})}return pg(a,i.dest)},async plan(i){if(!i||typeof i!="object")throw new u("bad-input",{field:"request"});let s=vu(i.file);if(!s)throw new u("bad-input",{field:"file"});if(typeof i.passphrase!="string"||i.passphrase.length>0&&i.passphrase.length<Ka)throw new u("bad-input",{field:"passphrase",min:Ka});let a=null;try{a=JSON.parse(s)}catch{throw new u("recovery-failed",{step:"parse"})}let c=null;try{c=await at.decryptFile(a,i.passphrase)}catch{throw new u("recovery-failed",{step:"decrypt"})}try{at.validatePayload(c)}catch{throw new u("recovery-failed",{step:"validate"})}let l=c.moneroWallet||{},d=l.address||null;if(!d)throw new u("recovery-failed",{step:"address"});let f=[],p=!!l.spendHalf;p||f.push("spendable");let h=Number(l.restoreHeight)||0;h>0||f.push("restore-height");let w=!1,b=null,y=l.escrowAddress||c.escrow&&c.escrow.address||null;if(y&&typeof e=="function")try{let v=String(await e({to:y,data:n6})||""),I=mg(v);I!==null&&(w=!0,b=I)}catch{w=!1}return w||f.push("revealed-half"),{swapId:c.swapId||null,address:d,spendable:p,restoreHeight:h,steps:JA,revealedHalf:w,half:b,missing:f}},async keys(i){let s=await o.plan(i);if(!s.half)throw new u("bad-input",{field:"revealedHalf",why:"not-revealed"});let a=vu(i.file),c=null;try{c=await at.decryptFile(JSON.parse(a),i.passphrase)}catch{throw new u("recovery-failed",{step:"decrypt"})}let l=c.moneroWallet||{},f=["spendHalf","viewHalf","otherSpendPoint","otherViewHalf"].filter(p=>l[p]===void 0||l[p]===null||l[p]==="");if(f.length)throw new u("bad-input",{field:"payload",missing:f});try{let p=Yt.createHalves(Xt),h=Us.spendKeysFromRevealedHalf({halves:p,ownSpendHalf:l.spendHalf,ownViewHalf:l.viewHalf,otherSpendPoint:l.otherSpendPoint,otherViewHalf:l.otherViewHalf,revealedHalf:s.half});return{privateSpendKey:h.privateSpendKey,privateViewKey:h.privateViewKey,address:s.address}}catch{throw new u("bad-input",{field:"revealedHalf",step:"verify"})}},async restore(i){return await dg(i||{})},async sign(i){let s=await o.plan(i);if(!i||typeof i.to!="string"||!i.to)throw new u("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 u("bad-input",{field:"connectWallet"})})(),l=["open","sync","unlockedBalance","sweepUnlocked","relay","close"].filter(d=>!a||typeof a[d]!="function");if(l.length)throw new u("bad-input",{field:"wallet",missing:l});await a.open(s);try{try{await a.sync()}catch{}let d=BigInt(await yg("unlockedBalance",()=>a.unlockedBalance()));if(d<=0n)throw new u("insufficient-funds",{unlocked:d.toString()});let f=await yg("sweepUnlocked",()=>a.sweepUnlocked({address:i.to,relay:!1})),p=await o6(a,f),h=p===null?null:BigInt(p),w=t6({feeAtomic:p,amountAtomic:d,...i.maxFeeAtomic===void 0||i.maxFeeAtomic===null?{}:{maxFeeAtomic:i.maxFeeAtomic}});if(!w.ok)throw new u(w.code,{fee:w.fee,limit:w.limit,amount:w.amount,why:w.why});let b="sweep-"+ ++n;return t.set(b,{wallet:a,plan:s,signed:f}),{token:b,amount:d.toString(),fee:p,receive:h===null||h>=d?null:(d-h).toString(),to:i.to,swept:s.address}}catch(d){try{await a.close()}catch{}throw d}},async relay(i){if(!i||typeof i.token!="string"||!i.token)throw new u("bad-input",{field:"token"});let s=t.get(i.token);if(!s)throw new u("bad-input",{field:"token",why:"no-open-session"});t.delete(i.token);let{wallet:a,plan:c,signed:l}=s;try{let d=await a.relay(l);return{txids:Array.isArray(d)?d:[],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}me();var i6=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)&&Q("bad-input",{field:"settlement.chain"}),n.vm!==void 0&&(typeof n.vm!="string"||!n.vm)&&Q("bad-input",{field:"settlement.vm"}),(typeof t.xmrNetwork!="string"||!t.xmrNetwork)&&Q("bad-input",{field:"xmrNetwork"});let r=t.mode===void 0?"live":t.mode;if(r!=="live"&&r!=="sim"&&Q("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"||Q("bad-input",{field:"storage"})}t.fetch!==void 0&&typeof t.fetch!="function"&&Q("bad-input",{field:"fetch"}),t.now!==void 0&&typeof t.now!="function"&&Q("bad-input",{field:"now"});for(let o of["apiBase","routes","serverAuth"])t[o]!==void 0&&Q("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))&&Q("bad-input",{field:"routing"})}if(t.endpoints!==void 0&&(!t.endpoints||typeof t.endpoints!="object"||Array.isArray(t.endpoints))&&Q("bad-input",{field:"endpoints"}),t.nodes!==void 0&&!Array.isArray(t.nodes)&&(!t.nodes||typeof t.nodes!="object")&&Q("bad-input",{field:"nodes"}),t.addNodes!==void 0&&!Array.isArray(t.addNodes)&&Q("bad-input",{field:"addNodes"}),t.evmCall!==void 0&&typeof t.evmCall!="function"&&Q("bad-input",{field:"evmCall"}),t.evmCode!==void 0&&typeof t.evmCode!="function"&&Q("bad-input",{field:"evmCode"}),t.evmLogs!==void 0&&typeof t.evmLogs!="function"&&Q("bad-input",{field:"evmLogs"}),t.evmBlock!==void 0&&typeof t.evmBlock!="function"&&Q("bad-input",{field:"evmBlock"}),t.allowedProviders!==void 0&&t.allowedProviders!==null){let o=t.allowedProviders;!Array.isArray(o)&&typeof o!="function"&&Q("bad-input",{field:"allowedProviders"})}if(t.knownFactoryCodes!==void 0&&t.knownFactoryCodes!==null&&!Array.isArray(t.knownFactoryCodes)&&Q("bad-input",{field:"knownFactoryCodes"}),t.knownImplementationCodes!==void 0&&t.knownImplementationCodes!==null&&!Array.isArray(t.knownImplementationCodes)&&Q("bad-input",{field:"knownImplementationCodes"}),t.denylist!==void 0&&t.denylist!==null&&(!Array.isArray(t.denylist)||t.denylist.some(o=>typeof o!="string"))&&Q("bad-input",{field:"denylist"}),t.createRecord!==void 0&&typeof t.createRecord!="function"&&Q("bad-input",{field:"createRecord"}),t.watch!==void 0){let o=t.watch;(!o||typeof o!="object"||Array.isArray(o))&&Q("bad-input",{field:"watch"});for(let i of["pollMs","timeoutMs"])o[i]!==void 0&&!(Number.isFinite(Number(o[i]))&&Number(o[i])>0)&&Q("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 s6(e){let t=i6(e),n=oy({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=iy({chain:n.settlement.chain,knownFactoryCodes:t.knownFactoryCodes}),o=sy({chain:n.settlement.chain,knownImplementationCodes:t.knownImplementationCodes}),i=Jr(n.settlement.vm),s=P0({settlement:n.settlement.chain,leg:i}),a=B0({config:{...n,evmNetwork:n.settlement.chain},wallet:s,limits:n.limits}),c=t.mode==="sim"?O0():null,l=Yn.createStore(t.storage||Yn.storage()),d=(()=>{let y=t.allowedProviders;if(y==null)return null;if(typeof y=="function")return I=>y(I)===!0;let v=new Set(y.map(I=>String(I).toLowerCase()));return I=>v.has(String(I).toLowerCase())})(),f=Array.isArray(t.denylist)&&t.denylist.length?new Set(t.denylist.map(y=>String(y).toLowerCase())):null,p=nu({config:n,now:t.now||(()=>Date.now()),evmCall:t.evmCall||null,evmCode:t.evmCode||null,evmBlock:t.evmBlock||null,providerAllowed:d,knownFactoryCodes:r,knownImplementationCodes:o,denylist:f,fetchImpl:t.fetch||null}),h=Ni({call:t.evmCall}),w=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:ru(),actions:h,order:{context:y=>Tt(y),verifyCounterparty:y=>Ny(y),jointAddress:y=>eo(y),escrowNativeWei:y=>He.escrowNativeWei(y),status:y=>Rn(y,w),deadlines:y=>fr(y,w),decline:(y,v={})=>j0(y,{...b,...v||{}})},sim:c,quotes:{firmRelay:y=>p.firmRelay(y)},swaps:Su({preflight:a,mode:t.mode,xmrNetwork:t.xmrNetwork,call:t.evmCall,fetchImpl:t.fetch||null,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:gg({call:t.evmCall})})}me();var Eu=e=>typeof e=="string"&&/^0x[0-9a-f]+$/i.test(e)?Number.parseInt(e,16):null,Au=/^0x[0-9a-fA-F]{40}$/,bg=e=>"0x"+Number(e).toString(16),a6=4902,c6=e=>(e&&(e.code||e.data&&e.data.originalError&&e.data.originalError.code))===a6||/unrecognized chain|not added/i.test(String(e&&e.message||"")),xg=e=>e&&e.code===4001||/rejected|denied/i.test(String(e&&e.message||""));function l6(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)&&Eu(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"&&Au.test(o)?o:null},async chainId(){return Eu(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=bg(o);try{await e.request({method:"wallet_switchEthereumChain",params:[{chainId:i}]})}catch(s){if(!c6(s))throw new u(xg(s)?"wallet-rejected":"wrong-chain",{vm:"evm"});let a=typeof pe.chainByChainId=="function"?pe.chainByChainId(o):null;if(!a)throw new u("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 u(xg(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 u("bad-input",{field:"send.to"});let l=b=>"0x"+BigInt(b).toString(16),d=Eu(await e.request({method:"eth_chainId"}).catch(()=>null));if(!Number.isSafeInteger(d)||d<=0)throw new u("wrong-chain",{vm:"evm",step:"send",want:a==null?null:Number(a),got:null,why:"unreadable"});let f=a==null?d:Number(a);if(!Number.isSafeInteger(f)||f<=0||d!==f)throw new u("wrong-chain",{vm:"evm",step:"send",want:f,got:d});let p=await e.request({method:"eth_accounts"}),h=Array.isArray(p)?p[0]:null;if(typeof h!="string"||!Au.test(h))throw new u("wallet-not-connected",{step:"send"});if(c!=null){let b=String(c).toLowerCase();if(!Au.test(b))throw new u("bad-input",{field:"send.from"});if(h.toLowerCase()!==b)throw new u("wrong-account",{vm:"evm",step:"send",want:b,got:h})}let w={from:h,to:r,data:o,value:l(i),chainId:bg(d)};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 u("bad-input",{field:"receipt.txHash"});return await e.request({method:"eth_getTransactionReceipt",params:[r]})},async signTypedData(r){if(!r||typeof r!="object")throw new u("bad-input",{field:"signTypedData"});let o=await e.request({method:"eth_accounts"}),i=Array.isArray(o)?o[0]:null;if(!i)throw new u("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 u("wallet-rejected",{step:"signTypedData",why:"bad-signature-shape"});return s},driver(){return e}}}function d6(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 u6(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{Xs as CHECK_CODES,Kr as ERROR_CODES,zs as STEP_CODES,u as SdkError,Ni as createActions,s6 as createNinsei,nu as createQuotes,ru as createRecovery,Su as createSwaps,l6 as evmWallet,d6 as localStorageAdapter,u6 as memoryAdapter};
|
|
2055
2055
|
/*! Bundled license information:
|
|
2056
2056
|
|
|
2057
2057
|
@noble/curves/utils.js:
|
|
@@ -2062,8 +2062,6 @@ ${n.mnemonic}
|
|
|
2062
2062
|
@noble/curves/abstract/der.js:
|
|
2063
2063
|
@noble/curves/abstract/weierstrass.js:
|
|
2064
2064
|
@noble/curves/secp256k1.js:
|
|
2065
|
-
@hpke/common/esm/src/curve/modular.js:
|
|
2066
|
-
@hpke/common/esm/src/curve/montgomery.js:
|
|
2067
2065
|
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
2068
2066
|
|
|
2069
2067
|
@scure/bip39/index.js:
|