@gardenfi/core 3.1.3-beta.14 → 3.1.3-beta.15

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.
@@ -1,12 +1,12 @@
1
- "use strict";var I0=t=>{throw TypeError(t)};var P0=(t,e,r)=>e.has(t)||I0("Cannot "+r);var Se=(t,e,r)=>(P0(t,e,"read from private field"),r?r.call(t):e.get(t)),ks=(t,e,r)=>e.has(t)?I0("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Ts=(t,e,r,n)=>(P0(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r);const D=require("@gardenfi/orderbook"),m=require("@gardenfi/utils"),me=require("bitcoinjs-lib"),k6=require("tiny-secp256k1"),Cm=require("varuint-bitcoin"),Go=require("bitcore-lib-ltc"),cs=require("bech32"),Lf=require("bignumber.js"),T6=require("@buildonspark/spark-sdk"),Qe=require("starknet"),Ar=require("@coral-xyz/anchor"),_6=require("@solana/spl-token"),O0=require("@mysten/wallet-standard"),B0=require("tronweb"),C0=require("xrpl"),pc=require("ecpair"),I6=require("node-cache"),R0=require("yup"),N0=require("bip39"),P6=require("bip32");function Gc(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const r in t)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:()=>t[r]})}}return e.default=t,Object.freeze(e)}const ke=Gc(me),mr=Gc(k6),U0=Gc(Cm),O6=Gc(_6),yc={mainnet:{baseurl:"https://api.garden.finance",auth:"https://api.garden.finance/auth",relayer:"https://relayer.garden.finance"},testnet:{baseurl:"https://testnet.api.garden.finance",auth:"https://testnet.api.garden.finance/auth",relayer:"https://testnet.api.garden.finance/relayer"},localnet:{baseurl:"http://api.localhost",auth:"http://api.localhost/auth",relayer:"http://api.localhost/relayer"}},Fa={[m.Network.MAINNET]:{chainId:"0x534e5f4d41494e",nodeUrl:"https://rpc.starknet.lava.build"},[m.Network.TESTNET]:{chainId:"0x534e5f5345504f4c4941",nodeUrl:"https://starknet-sepolia-rpc.publicnode.com"},[m.Network.LOCALNET]:{chainId:"",nodeUrl:""}},Rm={[m.Network.MAINNET]:"9cBuPNiHXiMNg3Fin8xLCGJQBTXjYQTFtyaFQv2uiM1H",[m.Network.TESTNET]:"ANUVKxeqaec3bf4DVPqLTnG1PT3Fng56wPcE7LXAb46Q",[m.Network.LOCALNET]:"AKnL4NNf3DGWZJS6cPknBuEGnVsV4A4m5tgebLHaRSZ9"},Df={mainnet:{native:"2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",spl:"gdnvdMCHJgnidtU7SL8RkRshHPvDJU1pdfZEpoLvqdU"},staging:{native:"6eksgdCnSjUaGQWZ6iYvauv1qzvYPF33RTGTM1ZuyENx",spl:"2WXpY8havGjfRxme9LUxtjFHTh1EfU3ur4v6wiK4KdNC"}},zf={[m.Network.TESTNET]:{packageId:"0x99865b03dd1bc03d0a6a805c454ea257c464f7abcccae9cd4b621b91e7ca04de",moduleName:"AtomicSwap"},[m.Network.MAINNET]:{packageId:"0xbfb5728aab0dd117747ef4574af6d3540ea6093109c22856e3ae201dfd58c0fc",moduleName:"AtomicSwap"},[m.Network.LOCALNET]:{packageId:"",moduleName:""}},Nm={[m.Network.MAINNET]:"https://api.trongrid.io",[m.Network.TESTNET]:"https://api.shasta.trongrid.io",[m.Network.LOCALNET]:""},Um={[m.Network.MAINNET]:"wss://s.altnet.rippletest.net:51233",[m.Network.TESTNET]:"wss://s.altnet.rippletest.net:51233",[m.Network.LOCALNET]:""},B6={asset:D.ChainAsset.from(D.Assets.base.cBBTC)};var Ta=(t=>(t.orderCreated="orderCreated",t.orderInitiating="orderInitiating",t.orderInitiated="orderInitiated",t))(Ta||{}),Ii=(t=>(t.SLOW="SLOW",t.MEDIUM="MEDIUM",t.FAST="FAST",t))(Ii||{}),Cr=(t=>(t.Mainnet="Mainnet",t.Testnet="Testnet",t.Regtest="Regtest",t))(Cr||{}),mc=(t=>(t.ALL="ALL",t.IN="IN",t.OUT="OUT",t))(mc||{});const C6={SLOW:"economyFee",MEDIUM:"hourFee",FAST:"fastestFee"};function Vf(t){const e=typeof t=="string"?t:t.network,r=e===m.Network.MAINNET?yc.mainnet:e===m.Network.TESTNET?yc.testnet:yc.localnet;return{api:typeof t=="string"?r:{...r,...t},network:e}}function R6(t){return typeof t=="string"&&(t=Buffer.from(t,"hex")),t.length===32?t:t.subarray(1,33)}function F0(t,e){if(!t)throw new Error(e)}function N6(t){return Buffer.concat([Uint8Array.from([192]),U6(t)])}function U6(t){const e=U0.encodingLength(t.length),r=Buffer.allocUnsafe(e);return U0.encode(t.length,r),Buffer.concat([r,t])}function F6(t,e){if(t.compare(e)>0){const r=t;t=e,e=r}return[t,e]}const De=t=>t.length===64?t:t.slice(2),M6=t=>{if(!t)return!1;try{const e=Buffer.from(t,"hex");return mr.isPoint(e)}catch{return!1}};function $6(t,e){if(!t)return!1;const r=e===m.Environment.MAINNET?ke.networks.bitcoin:e===m.Environment.TESTNET?ke.networks.testnet:ke.networks.regtest;if(!r)return!1;ke.initEccLib(mr);try{return ke.address.toOutputScript(t,r),!0}catch{return!1}}function j6(t,e){if(!t)return!1;const r=e===m.Environment.MAINNET?"MAINNET":"REGTEST";try{return T6.decodeSparkAddress(t,r),!0}catch{return!1}}function H6(t,e){if(!t)return!1;let r;if(e===m.Environment.MAINNET?r=Go.Networks.livenet:(m.Environment.TESTNET,r=Go.Networks.testnet),!r)return!1;try{return Go.Address.fromString(t,r),!0}catch{const n=t.toLowerCase(),i=e===m.Environment.MAINNET?"ltc":"tltc";if(!n.startsWith(i+"1"))return!1;const a=[cs.bech32.decode,cs.bech32m.decode];for(const o of a)try{const c=o(n);if(c.prefix!==i)continue;const u=c.words;if(u.length===0)continue;const l=u[0],f=u.slice(1);if(l<0||l>16)continue;const p=cs.bech32.fromWords(f);if(p.length!==20&&p.length!==32)continue;return!0}catch{continue}return!1}}function L6(t,e){if(!t)return!1;const r=t.trim();if(r.includes("@")){const i=r.split("@");if(i.length!==2)return!1;const[a,o]=i;return!(!a||a.length===0||!o||!o.includes(".")||!/^[a-zA-Z0-9._-]+$/.test(a)||!/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(o))}const n=r.toLowerCase();if(n.startsWith("lnurl1"))try{return cs.bech32.decode(n,2e3),!0}catch{return!1}const s=e===m.Environment.MAINNET;return s&&n.startsWith("lnbc")||!s&&(n.startsWith("lntb")||n.startsWith("lnbcrt"))?r.length>50:!1}function oa(t,e){const r=[];for(let n=0;n<e;n++)r.push(t);return r}const D6=t=>{switch(t){case m.Network.MAINNET:return Cr.Mainnet;case m.Network.TESTNET:return Cr.Testnet;case m.Network.LOCALNET:return Cr.Regtest;default:throw new Error(`Invalid bitcoin network ${t}`)}},z6=t=>{switch(t){case m.Network.MAINNET:return ke.networks.bitcoin;case m.Network.TESTNET:return ke.networks.testnet;case m.Network.LOCALNET:return ke.networks.regtest;default:throw new Error(`Invalid bitcoin network ${t}`)}},V6=t=>{const e=t.toLowerCase().replace("0x","");return/^[0-9a-f]+$/.test(e)},M0=t=>{if(typeof t=="object"&&"r"in t&&"s"in t)return m.Ok([t.r.toString(),t.s.toString()]);if(Array.isArray(t)){const e=t.map(r=>typeof r=="string"&&r.startsWith("0x")&&V6(r)?BigInt(r).toString():r);return m.Ok(e.join(","))}return m.Err("Invalid signature format")};function Gf(t){return Buffer.from(t,"hex").reverse()}function qf(t){return typeof t=="object"&&t!==null&&"message"in t&&typeof t.message=="string"}const qo=async(t,e)=>{const r=Date.now(),n=3e4,s=2e3;for(;Date.now()-r<n;){const i=await t.getLatestBlockhash(),a=await t.confirmTransaction({signature:e,blockhash:i.blockhash,lastValidBlockHeight:i.lastValidBlockHeight},"confirmed");if(a.value&&a.value.err==null)return console.log("Tx Confirmed ✅",e),!0;console.log("Tx not confirmed yet. Retrying in 2 seconds..."),await new Promise(o=>setTimeout(o,s))}return!1},$i=async(t,e,r)=>{var u,l;const n=await r.getAuthHeaders();if(!n.ok)return m.Err(n.error);const s=await m.Fetcher.get(e+"/v2/assets",{headers:{...n.val}});if(s.error)return m.Err("Failed to fetch asset info: "+s.error);const a=(s.result||[]).find(f=>f.id===t);if(!a)return m.Err(`Asset info not found for asset id: ${t}`);const o=((u=a.htlc)==null?void 0:u.address)||"",c=((l=a.token)==null?void 0:l.address)||"";return m.Ok({htlcAddress:o,tokenAddress:c})},$0=t=>{if(t==null||t.includes("."))return m.Err("Invalid amount ",t);const e=new Lf.BigNumber(t);return!e.isInteger()||e.isNaN()||e.lt(0)||e.isLessThanOrEqualTo(0)?m.Err("Invalid amount ",t):m.Ok(e)},G6=async(t,e)=>{const r={[D.BlockchainType.evm]:{htlc:e.evm,name:"EVM"},[D.BlockchainType.solana]:{htlc:e.solana,name:"Solana"},[D.BlockchainType.starknet]:{htlc:e.starknet,name:"Starknet"},[D.BlockchainType.sui]:{htlc:e.sui,name:"Sui"},[D.BlockchainType.bitcoin]:{htlc:e.bitcoin,name:"Bitcoin"},[D.BlockchainType.tron]:{htlc:e.tron,name:"Tron"},[D.BlockchainType.litecoin]:{htlc:e.litecoin,name:"Litecoin"},[D.BlockchainType.alpen_signet]:{htlc:e.alpen_signet,name:"Alpen Signet"},[D.BlockchainType.xrpl]:{htlc:e.xrpl,name:"XRPL"},[D.BlockchainType.spark]:{htlc:e.spark,name:"Spark"},[D.BlockchainType.lightning]:{htlc:e.lightning,name:"Lightning"}};if(t===D.BlockchainType.bitcoin||t===D.BlockchainType.litecoin||t===D.BlockchainType.alpen_signet||t===D.BlockchainType.spark||t===D.BlockchainType.lightning)return m.Ok(void 0);const n=r[t];return n?n.htlc?m.Ok(void 0):m.Err(`${n.name} HTLC is required for swap initiation. Please provide ${n.name.toLowerCase()}HTLC when initializing garden.`):m.Err(`Unsupported blockchain type for swap initiation: ${t}`)},q6=["0x90c06174","0xee1b963b"],W6=t=>{if(!t)return"";if(typeof t=="string")return t;if(t instanceof Error)return[t.message,t.shortMessage,t.reason,t.signature,t.stack].filter(Boolean).join(" | ");if(typeof t=="object"){const e=t.message;if(typeof e=="string")return e;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)},Qd=t=>{const e=W6(t).toLowerCase();return q6.some(r=>e.includes(r.toLowerCase()))},K6=t=>t.toLowerCase().includes("not supported for initiations"),Fm=async({attempt:t,wallet:e,maxAttempts:r=1,baseDelayMs:n=1e3})=>{var s;for(let i=0;i<r;i++){const a=await t();if(a.error&&K6(a.error))break;if(a.ok){const o=await m.waitForTransactionReceipt(e,a.val);if(!o.ok){if(i<r-1){await m.sleep(n*2**i);continue}break}if(((s=o.val)==null?void 0:s.status)==="success")return a.val}i<r-1&&await m.sleep(n*2**i)}return null},X6=Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),Y6=Buffer.from("483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8","hex"),J6=Buffer.concat([X6,Y6]),Z6=Buffer.from("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0","hex"),j0={failedToCreateInternalPubkey:"failed to create internal pubkey"};function H0(){const t=me.crypto.sha256(Buffer.from("GardenHTLC","utf-8")),e=mr.pointMultiply(Buffer.concat([Buffer.from("04","hex"),J6]),t);if(!e)throw new Error(j0.failedToCreateInternalPubkey);const r=mr.pointAdd(Z6,e);if(!r)throw new Error(j0.failedToCreateInternalPubkey);return R6(Buffer.from(r))}var sn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},ze={},kt={},si={},qc={};qc.byteLength=tv;qc.toByteArray=nv;qc.fromByteArray=av;var Qr=[],dr=[],Q6=typeof Uint8Array<"u"?Uint8Array:Array,Lu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var di=0,ev=Lu.length;di<ev;++di)Qr[di]=Lu[di],dr[Lu.charCodeAt(di)]=di;dr[45]=62;dr[95]=63;function Mm(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function tv(t){var e=Mm(t),r=e[0],n=e[1];return(r+n)*3/4-n}function rv(t,e,r){return(e+r)*3/4-r}function nv(t){var e,r=Mm(t),n=r[0],s=r[1],i=new Q6(rv(t,n,s)),a=0,o=s>0?n-4:n,c;for(c=0;c<o;c+=4)e=dr[t.charCodeAt(c)]<<18|dr[t.charCodeAt(c+1)]<<12|dr[t.charCodeAt(c+2)]<<6|dr[t.charCodeAt(c+3)],i[a++]=e>>16&255,i[a++]=e>>8&255,i[a++]=e&255;return s===2&&(e=dr[t.charCodeAt(c)]<<2|dr[t.charCodeAt(c+1)]>>4,i[a++]=e&255),s===1&&(e=dr[t.charCodeAt(c)]<<10|dr[t.charCodeAt(c+1)]<<4|dr[t.charCodeAt(c+2)]>>2,i[a++]=e>>8&255,i[a++]=e&255),i}function sv(t){return Qr[t>>18&63]+Qr[t>>12&63]+Qr[t>>6&63]+Qr[t&63]}function iv(t,e,r){for(var n,s=[],i=e;i<r;i+=3)n=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(t[i+2]&255),s.push(sv(n));return s.join("")}function av(t){for(var e,r=t.length,n=r%3,s=[],i=16383,a=0,o=r-n;a<o;a+=i)s.push(iv(t,a,a+i>o?o:a+i));return n===1?(e=t[r-1],s.push(Qr[e>>2]+Qr[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],s.push(Qr[e>>10]+Qr[e>>4&63]+Qr[e<<2&63]+"=")),s.join("")}var eh={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */eh.read=function(t,e,r,n,s){var i,a,o=s*8-n-1,c=(1<<o)-1,u=c>>1,l=-7,f=r?s-1:0,p=r?-1:1,d=t[e+f];for(f+=p,i=d&(1<<-l)-1,d>>=-l,l+=o;l>0;i=i*256+t[e+f],f+=p,l-=8);for(a=i&(1<<-l)-1,i>>=-l,l+=n;l>0;a=a*256+t[e+f],f+=p,l-=8);if(i===0)i=1-u;else{if(i===c)return a?NaN:(d?-1:1)*(1/0);a=a+Math.pow(2,n),i=i-u}return(d?-1:1)*a*Math.pow(2,i-n)};eh.write=function(t,e,r,n,s,i){var a,o,c,u=i*8-s-1,l=(1<<u)-1,f=l>>1,p=s===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:i-1,b=n?1:-1,g=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(o=isNaN(e)?1:0,a=l):(a=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-a))<1&&(a--,c*=2),a+f>=1?e+=p/c:e+=p*Math.pow(2,1-f),e*c>=2&&(a++,c/=2),a+f>=l?(o=0,a=l):a+f>=1?(o=(e*c-1)*Math.pow(2,s),a=a+f):(o=e*Math.pow(2,f-1)*Math.pow(2,s),a=0));s>=8;t[r+d]=o&255,d+=b,o/=256,s-=8);for(a=a<<s|o,u+=s;u>0;t[r+d]=a&255,d+=b,a/=256,u-=8);t[r+d-b]|=g*128};/*!
1
+ "use strict";var O0=t=>{throw TypeError(t)};var B0=(t,e,r)=>e.has(t)||O0("Cannot "+r);var Se=(t,e,r)=>(B0(t,e,"read from private field"),r?r.call(t):e.get(t)),Ts=(t,e,r)=>e.has(t)?O0("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),_s=(t,e,r,n)=>(B0(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r);const D=require("@gardenfi/orderbook"),m=require("@gardenfi/utils"),me=require("bitcoinjs-lib"),_6=require("tiny-secp256k1"),Nm=require("varuint-bitcoin"),Go=require("bitcore-lib-ltc"),us=require("bech32"),zf=require("bignumber.js"),I6=require("@buildonspark/spark-sdk"),Qe=require("starknet"),Ar=require("@coral-xyz/anchor"),P6=require("@solana/spl-token"),C0=require("@mysten/wallet-standard"),R0=require("tronweb"),N0=require("xrpl"),mc=require("ecpair"),O6=require("node-cache"),U0=require("yup"),F0=require("bip39"),B6=require("bip32");function Wc(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const r in t)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:()=>t[r]})}}return e.default=t,Object.freeze(e)}const ke=Wc(me),mr=Wc(_6),M0=Wc(Nm),C6=Wc(P6),bc={mainnet:{baseurl:"https://api.garden.finance",auth:"https://api.garden.finance/auth",relayer:"https://relayer.garden.finance"},testnet:{baseurl:"https://testnet.api.garden.finance",auth:"https://testnet.api.garden.finance/auth",relayer:"https://testnet.api.garden.finance/relayer"},localnet:{baseurl:"http://api.localhost",auth:"http://api.localhost/auth",relayer:"http://api.localhost/relayer"}},Fa={[m.Network.MAINNET]:{chainId:"0x534e5f4d41494e",nodeUrl:"https://rpc.starknet.lava.build"},[m.Network.TESTNET]:{chainId:"0x534e5f5345504f4c4941",nodeUrl:"https://starknet-sepolia-rpc.publicnode.com"},[m.Network.LOCALNET]:{chainId:"",nodeUrl:""}},Um={[m.Network.MAINNET]:"9cBuPNiHXiMNg3Fin8xLCGJQBTXjYQTFtyaFQv2uiM1H",[m.Network.TESTNET]:"ANUVKxeqaec3bf4DVPqLTnG1PT3Fng56wPcE7LXAb46Q",[m.Network.LOCALNET]:"AKnL4NNf3DGWZJS6cPknBuEGnVsV4A4m5tgebLHaRSZ9"},Vf={mainnet:{native:"2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",spl:"gdnvdMCHJgnidtU7SL8RkRshHPvDJU1pdfZEpoLvqdU"},staging:{native:"6eksgdCnSjUaGQWZ6iYvauv1qzvYPF33RTGTM1ZuyENx",spl:"2WXpY8havGjfRxme9LUxtjFHTh1EfU3ur4v6wiK4KdNC"}},Gf={[m.Network.TESTNET]:{packageId:"0x99865b03dd1bc03d0a6a805c454ea257c464f7abcccae9cd4b621b91e7ca04de",moduleName:"AtomicSwap"},[m.Network.MAINNET]:{packageId:"0xbfb5728aab0dd117747ef4574af6d3540ea6093109c22856e3ae201dfd58c0fc",moduleName:"AtomicSwap"},[m.Network.LOCALNET]:{packageId:"",moduleName:""}},Fm={[m.Network.MAINNET]:"https://api.trongrid.io",[m.Network.TESTNET]:"https://api.shasta.trongrid.io",[m.Network.LOCALNET]:""},Mm={[m.Network.MAINNET]:"wss://s.altnet.rippletest.net:51233",[m.Network.TESTNET]:"wss://s.altnet.rippletest.net:51233",[m.Network.LOCALNET]:""},R6={asset:D.ChainAsset.from(D.Assets.base.cBBTC)};var Ta=(t=>(t.orderCreated="orderCreated",t.orderInitiating="orderInitiating",t.orderInitiated="orderInitiated",t))(Ta||{}),Pi=(t=>(t.SLOW="SLOW",t.MEDIUM="MEDIUM",t.FAST="FAST",t))(Pi||{}),Cr=(t=>(t.Mainnet="Mainnet",t.Testnet="Testnet",t.Regtest="Regtest",t))(Cr||{}),gc=(t=>(t.ALL="ALL",t.IN="IN",t.OUT="OUT",t))(gc||{});const N6={SLOW:"economyFee",MEDIUM:"hourFee",FAST:"fastestFee"};function qf(t){const e=typeof t=="string"?t:t.network,r=e===m.Network.MAINNET?bc.mainnet:e===m.Network.TESTNET?bc.testnet:bc.localnet;return{api:typeof t=="string"?r:{...r,...t},network:e}}function U6(t){return typeof t=="string"&&(t=Buffer.from(t,"hex")),t.length===32?t:t.subarray(1,33)}function $0(t,e){if(!t)throw new Error(e)}function F6(t){return Buffer.concat([Uint8Array.from([192]),M6(t)])}function M6(t){const e=M0.encodingLength(t.length),r=Buffer.allocUnsafe(e);return M0.encode(t.length,r),Buffer.concat([r,t])}function $6(t,e){if(t.compare(e)>0){const r=t;t=e,e=r}return[t,e]}const De=t=>t.length===64?t:t.slice(2),j6=t=>{if(!t)return!1;try{const e=Buffer.from(t,"hex");return mr.isPoint(e)}catch{return!1}};function H6(t,e){if(!t)return!1;const r=e===m.Environment.MAINNET?ke.networks.bitcoin:e===m.Environment.TESTNET?ke.networks.testnet:ke.networks.regtest;if(!r)return!1;ke.initEccLib(mr);try{return ke.address.toOutputScript(t,r),!0}catch{return!1}}function L6(t,e){if(!t)return!1;const r=e===m.Environment.MAINNET?"MAINNET":"REGTEST";try{return I6.decodeSparkAddress(t,r),!0}catch{return!1}}function D6(t,e){if(!t)return!1;let r;if(e===m.Environment.MAINNET?r=Go.Networks.livenet:(m.Environment.TESTNET,r=Go.Networks.testnet),!r)return!1;try{return Go.Address.fromString(t,r),!0}catch{const n=t.toLowerCase(),i=e===m.Environment.MAINNET?"ltc":"tltc";if(!n.startsWith(i+"1"))return!1;const a=[us.bech32.decode,us.bech32m.decode];for(const o of a)try{const c=o(n);if(c.prefix!==i)continue;const u=c.words;if(u.length===0)continue;const l=u[0],f=u.slice(1);if(l<0||l>16)continue;const p=us.bech32.fromWords(f);if(p.length!==20&&p.length!==32)continue;return!0}catch{continue}return!1}}function z6(t,e){if(!t)return!1;const r=t.trim();if(r.includes("@")){const i=r.split("@");if(i.length!==2)return!1;const[a,o]=i;return!(!a||a.length===0||!o||!o.includes(".")||!/^[a-zA-Z0-9._-]+$/.test(a)||!/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(o))}const n=r.toLowerCase();if(n.startsWith("lnurl1"))try{return us.bech32.decode(n,2e3),!0}catch{return!1}const s=e===m.Environment.MAINNET;return s&&n.startsWith("lnbc")||!s&&(n.startsWith("lntb")||n.startsWith("lnbcrt"))?r.length>50:!1}function oa(t,e){const r=[];for(let n=0;n<e;n++)r.push(t);return r}const V6=t=>{switch(t){case m.Network.MAINNET:return Cr.Mainnet;case m.Network.TESTNET:return Cr.Testnet;case m.Network.LOCALNET:return Cr.Regtest;default:throw new Error(`Invalid bitcoin network ${t}`)}},G6=t=>{switch(t){case m.Network.MAINNET:return ke.networks.bitcoin;case m.Network.TESTNET:return ke.networks.testnet;case m.Network.LOCALNET:return ke.networks.regtest;default:throw new Error(`Invalid bitcoin network ${t}`)}},q6=t=>{const e=t.toLowerCase().replace("0x","");return/^[0-9a-f]+$/.test(e)},j0=t=>{if(typeof t=="object"&&"r"in t&&"s"in t)return m.Ok([t.r.toString(),t.s.toString()]);if(Array.isArray(t)){const e=t.map(r=>typeof r=="string"&&r.startsWith("0x")&&q6(r)?BigInt(r).toString():r);return m.Ok(e.join(","))}return m.Err("Invalid signature format")};function Wf(t){return Buffer.from(t,"hex").reverse()}function Kf(t){return typeof t=="object"&&t!==null&&"message"in t&&typeof t.message=="string"}const qo=async(t,e)=>{const r=Date.now(),n=3e4,s=2e3;for(;Date.now()-r<n;){const i=await t.getLatestBlockhash(),a=await t.confirmTransaction({signature:e,blockhash:i.blockhash,lastValidBlockHeight:i.lastValidBlockHeight},"confirmed");if(a.value&&a.value.err==null)return console.log("Tx Confirmed ✅",e),!0;console.log("Tx not confirmed yet. Retrying in 2 seconds..."),await new Promise(o=>setTimeout(o,s))}return!1},ji=async(t,e,r)=>{var u,l;const n=await r.getAuthHeaders();if(!n.ok)return m.Err(n.error);const s=await m.Fetcher.get(e+"/v2/assets",{headers:{...n.val}});if(s.error)return m.Err("Failed to fetch asset info: "+s.error);const a=(s.result||[]).find(f=>f.id===t);if(!a)return m.Err(`Asset info not found for asset id: ${t}`);const o=((u=a.htlc)==null?void 0:u.address)||"",c=((l=a.token)==null?void 0:l.address)||"";return m.Ok({htlcAddress:o,tokenAddress:c})},H0=t=>{if(t==null||t.includes("."))return m.Err("Invalid amount ",t);const e=new zf.BigNumber(t);return!e.isInteger()||e.isNaN()||e.lt(0)||e.isLessThanOrEqualTo(0)?m.Err("Invalid amount ",t):m.Ok(e)},W6=async(t,e)=>{const r={[D.BlockchainType.evm]:{htlc:e.evm,name:"EVM"},[D.BlockchainType.solana]:{htlc:e.solana,name:"Solana"},[D.BlockchainType.starknet]:{htlc:e.starknet,name:"Starknet"},[D.BlockchainType.sui]:{htlc:e.sui,name:"Sui"},[D.BlockchainType.bitcoin]:{htlc:e.bitcoin,name:"Bitcoin"},[D.BlockchainType.tron]:{htlc:e.tron,name:"Tron"},[D.BlockchainType.litecoin]:{htlc:e.litecoin,name:"Litecoin"},[D.BlockchainType.alpen_signet]:{htlc:e.alpen_signet,name:"Alpen Signet"},[D.BlockchainType.xrpl]:{htlc:e.xrpl,name:"XRPL"},[D.BlockchainType.spark]:{htlc:e.spark,name:"Spark"},[D.BlockchainType.lightning]:{htlc:e.lightning,name:"Lightning"}};if(t===D.BlockchainType.bitcoin||t===D.BlockchainType.litecoin||t===D.BlockchainType.alpen_signet||t===D.BlockchainType.spark||t===D.BlockchainType.lightning)return m.Ok(void 0);const n=r[t];return n?n.htlc?m.Ok(void 0):m.Err(`${n.name} HTLC is required for swap initiation. Please provide ${n.name.toLowerCase()}HTLC when initializing garden.`):m.Err(`Unsupported blockchain type for swap initiation: ${t}`)},K6=["0x90c06174","0xee1b963b"],X6=t=>{if(!t)return"";if(typeof t=="string")return t;if(t instanceof Error)return[t.message,t.shortMessage,t.reason,t.signature,t.stack].filter(Boolean).join(" | ");if(typeof t=="object"){const e=t.message;if(typeof e=="string")return e;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)},th=t=>{const e=X6(t).toLowerCase();return K6.some(r=>e.includes(r.toLowerCase()))},Y6=t=>t.toLowerCase().includes("not supported for initiations"),$m=async({attempt:t,wallet:e,maxAttempts:r=1,baseDelayMs:n=1e3})=>{var s;for(let i=0;i<r;i++){const a=await t();if(a.error&&Y6(a.error))break;if(a.ok){const o=await m.waitForTransactionReceipt(e,a.val);if(!o.ok){if(i<r-1){await m.sleep(n*2**i);continue}break}if(((s=o.val)==null?void 0:s.status)==="success")return a.val}i<r-1&&await m.sleep(n*2**i)}return null},J6=Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),Z6=Buffer.from("483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8","hex"),Q6=Buffer.concat([J6,Z6]),ev=Buffer.from("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0","hex"),L0={failedToCreateInternalPubkey:"failed to create internal pubkey"};function D0(){const t=me.crypto.sha256(Buffer.from("GardenHTLC","utf-8")),e=mr.pointMultiply(Buffer.concat([Buffer.from("04","hex"),Q6]),t);if(!e)throw new Error(L0.failedToCreateInternalPubkey);const r=mr.pointAdd(ev,e);if(!r)throw new Error(L0.failedToCreateInternalPubkey);return U6(Buffer.from(r))}var sn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},ze={},kt={},ii={},Kc={};Kc.byteLength=nv;Kc.toByteArray=iv;Kc.fromByteArray=cv;var Qr=[],dr=[],tv=typeof Uint8Array<"u"?Uint8Array:Array,zu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var hi=0,rv=zu.length;hi<rv;++hi)Qr[hi]=zu[hi],dr[zu.charCodeAt(hi)]=hi;dr[45]=62;dr[95]=63;function jm(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function nv(t){var e=jm(t),r=e[0],n=e[1];return(r+n)*3/4-n}function sv(t,e,r){return(e+r)*3/4-r}function iv(t){var e,r=jm(t),n=r[0],s=r[1],i=new tv(sv(t,n,s)),a=0,o=s>0?n-4:n,c;for(c=0;c<o;c+=4)e=dr[t.charCodeAt(c)]<<18|dr[t.charCodeAt(c+1)]<<12|dr[t.charCodeAt(c+2)]<<6|dr[t.charCodeAt(c+3)],i[a++]=e>>16&255,i[a++]=e>>8&255,i[a++]=e&255;return s===2&&(e=dr[t.charCodeAt(c)]<<2|dr[t.charCodeAt(c+1)]>>4,i[a++]=e&255),s===1&&(e=dr[t.charCodeAt(c)]<<10|dr[t.charCodeAt(c+1)]<<4|dr[t.charCodeAt(c+2)]>>2,i[a++]=e>>8&255,i[a++]=e&255),i}function av(t){return Qr[t>>18&63]+Qr[t>>12&63]+Qr[t>>6&63]+Qr[t&63]}function ov(t,e,r){for(var n,s=[],i=e;i<r;i+=3)n=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(t[i+2]&255),s.push(av(n));return s.join("")}function cv(t){for(var e,r=t.length,n=r%3,s=[],i=16383,a=0,o=r-n;a<o;a+=i)s.push(ov(t,a,a+i>o?o:a+i));return n===1?(e=t[r-1],s.push(Qr[e>>2]+Qr[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],s.push(Qr[e>>10]+Qr[e>>4&63]+Qr[e<<2&63]+"=")),s.join("")}var rh={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */rh.read=function(t,e,r,n,s){var i,a,o=s*8-n-1,c=(1<<o)-1,u=c>>1,l=-7,f=r?s-1:0,p=r?-1:1,d=t[e+f];for(f+=p,i=d&(1<<-l)-1,d>>=-l,l+=o;l>0;i=i*256+t[e+f],f+=p,l-=8);for(a=i&(1<<-l)-1,i>>=-l,l+=n;l>0;a=a*256+t[e+f],f+=p,l-=8);if(i===0)i=1-u;else{if(i===c)return a?NaN:(d?-1:1)*(1/0);a=a+Math.pow(2,n),i=i-u}return(d?-1:1)*a*Math.pow(2,i-n)};rh.write=function(t,e,r,n,s,i){var a,o,c,u=i*8-s-1,l=(1<<u)-1,f=l>>1,p=s===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:i-1,b=n?1:-1,g=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(o=isNaN(e)?1:0,a=l):(a=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-a))<1&&(a--,c*=2),a+f>=1?e+=p/c:e+=p*Math.pow(2,1-f),e*c>=2&&(a++,c/=2),a+f>=l?(o=0,a=l):a+f>=1?(o=(e*c-1)*Math.pow(2,s),a=a+f):(o=e*Math.pow(2,f-1)*Math.pow(2,s),a=0));s>=8;t[r+d]=o&255,d+=b,o/=256,s-=8);for(a=a<<s|o,u+=s;u>0;t[r+d]=a&255,d+=b,a/=256,u-=8);t[r+d-b]|=g*128};/*!
2
2
  * The buffer module from node.js, for the browser.
3
3
  *
4
4
  * @author Feross Aboukhadijeh <https://feross.org>
5
5
  * @license MIT
6
- */(function(t){const e=qc,r=eh,n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=o,t.SlowBuffer=T,t.INSPECT_MAX_BYTES=50;const s=2147483647;t.kMaxLength=s,o.TYPED_ARRAY_SUPPORT=i(),!o.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function i(){try{const E=new Uint8Array(1),h={foo:function(){return 42}};return Object.setPrototypeOf(h,Uint8Array.prototype),Object.setPrototypeOf(E,h),E.foo()===42}catch{return!1}}Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}});function a(E){if(E>s)throw new RangeError('The value "'+E+'" is invalid for option "size"');const h=new Uint8Array(E);return Object.setPrototypeOf(h,o.prototype),h}function o(E,h,y){if(typeof E=="number"){if(typeof h=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return f(E)}return c(E,h,y)}o.poolSize=8192;function c(E,h,y){if(typeof E=="string")return p(E,h);if(ArrayBuffer.isView(E))return b(E);if(E==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof E);if(It(E,ArrayBuffer)||E&&It(E.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(It(E,SharedArrayBuffer)||E&&It(E.buffer,SharedArrayBuffer)))return g(E,h,y);if(typeof E=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const k=E.valueOf&&E.valueOf();if(k!=null&&k!==E)return o.from(k,h,y);const R=A(E);if(R)return R;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof E[Symbol.toPrimitive]=="function")return o.from(E[Symbol.toPrimitive]("string"),h,y);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof E)}o.from=function(E,h,y){return c(E,h,y)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array);function u(E){if(typeof E!="number")throw new TypeError('"size" argument must be of type number');if(E<0)throw new RangeError('The value "'+E+'" is invalid for option "size"')}function l(E,h,y){return u(E),E<=0?a(E):h!==void 0?typeof y=="string"?a(E).fill(h,y):a(E).fill(h):a(E)}o.alloc=function(E,h,y){return l(E,h,y)};function f(E){return u(E),a(E<0?0:S(E)|0)}o.allocUnsafe=function(E){return f(E)},o.allocUnsafeSlow=function(E){return f(E)};function p(E,h){if((typeof h!="string"||h==="")&&(h="utf8"),!o.isEncoding(h))throw new TypeError("Unknown encoding: "+h);const y=v(E,h)|0;let k=a(y);const R=k.write(E,h);return R!==y&&(k=k.slice(0,R)),k}function d(E){const h=E.length<0?0:S(E.length)|0,y=a(h);for(let k=0;k<h;k+=1)y[k]=E[k]&255;return y}function b(E){if(It(E,Uint8Array)){const h=new Uint8Array(E);return g(h.buffer,h.byteOffset,h.byteLength)}return d(E)}function g(E,h,y){if(h<0||E.byteLength<h)throw new RangeError('"offset" is outside of buffer bounds');if(E.byteLength<h+(y||0))throw new RangeError('"length" is outside of buffer bounds');let k;return h===void 0&&y===void 0?k=new Uint8Array(E):y===void 0?k=new Uint8Array(E,h):k=new Uint8Array(E,h,y),Object.setPrototypeOf(k,o.prototype),k}function A(E){if(o.isBuffer(E)){const h=S(E.length)|0,y=a(h);return y.length===0||E.copy(y,0,0,h),y}if(E.length!==void 0)return typeof E.length!="number"||jn(E.length)?a(0):d(E);if(E.type==="Buffer"&&Array.isArray(E.data))return d(E.data)}function S(E){if(E>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return E|0}function T(E){return+E!=E&&(E=0),o.alloc(+E)}o.isBuffer=function(h){return h!=null&&h._isBuffer===!0&&h!==o.prototype},o.compare=function(h,y){if(It(h,Uint8Array)&&(h=o.from(h,h.offset,h.byteLength)),It(y,Uint8Array)&&(y=o.from(y,y.offset,y.byteLength)),!o.isBuffer(h)||!o.isBuffer(y))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(h===y)return 0;let k=h.length,R=y.length;for(let $=0,W=Math.min(k,R);$<W;++$)if(h[$]!==y[$]){k=h[$],R=y[$];break}return k<R?-1:R<k?1:0},o.isEncoding=function(h){switch(String(h).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(h,y){if(!Array.isArray(h))throw new TypeError('"list" argument must be an Array of Buffers');if(h.length===0)return o.alloc(0);let k;if(y===void 0)for(y=0,k=0;k<h.length;++k)y+=h[k].length;const R=o.allocUnsafe(y);let $=0;for(k=0;k<h.length;++k){let W=h[k];if(It(W,Uint8Array))$+W.length>R.length?(o.isBuffer(W)||(W=o.from(W)),W.copy(R,$)):Uint8Array.prototype.set.call(R,W,$);else if(o.isBuffer(W))W.copy(R,$);else throw new TypeError('"list" argument must be an Array of Buffers');$+=W.length}return R};function v(E,h){if(o.isBuffer(E))return E.length;if(ArrayBuffer.isView(E)||It(E,ArrayBuffer))return E.byteLength;if(typeof E!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof E);const y=E.length,k=arguments.length>2&&arguments[2]===!0;if(!k&&y===0)return 0;let R=!1;for(;;)switch(h){case"ascii":case"latin1":case"binary":return y;case"utf8":case"utf-8":return Hr(E).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return y*2;case"hex":return y>>>1;case"base64":return Lr(E).length;default:if(R)return k?-1:Hr(E).length;h=(""+h).toLowerCase(),R=!0}}o.byteLength=v;function w(E,h,y){let k=!1;if((h===void 0||h<0)&&(h=0),h>this.length||((y===void 0||y>this.length)&&(y=this.length),y<=0)||(y>>>=0,h>>>=0,y<=h))return"";for(E||(E="utf8");;)switch(E){case"hex":return O(this,h,y);case"utf8":case"utf-8":return Q(this,h,y);case"ascii":return ee(this,h,y);case"latin1":case"binary":return q(this,h,y);case"base64":return V(this,h,y);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,h,y);default:if(k)throw new TypeError("Unknown encoding: "+E);E=(E+"").toLowerCase(),k=!0}}o.prototype._isBuffer=!0;function x(E,h,y){const k=E[h];E[h]=E[y],E[y]=k}o.prototype.swap16=function(){const h=this.length;if(h%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let y=0;y<h;y+=2)x(this,y,y+1);return this},o.prototype.swap32=function(){const h=this.length;if(h%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let y=0;y<h;y+=4)x(this,y,y+3),x(this,y+1,y+2);return this},o.prototype.swap64=function(){const h=this.length;if(h%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let y=0;y<h;y+=8)x(this,y,y+7),x(this,y+1,y+6),x(this,y+2,y+5),x(this,y+3,y+4);return this},o.prototype.toString=function(){const h=this.length;return h===0?"":arguments.length===0?Q(this,0,h):w.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(h){if(!o.isBuffer(h))throw new TypeError("Argument must be a Buffer");return this===h?!0:o.compare(this,h)===0},o.prototype.inspect=function(){let h="";const y=t.INSPECT_MAX_BYTES;return h=this.toString("hex",0,y).replace(/(.{2})/g,"$1 ").trim(),this.length>y&&(h+=" ... "),"<Buffer "+h+">"},n&&(o.prototype[n]=o.prototype.inspect),o.prototype.compare=function(h,y,k,R,$){if(It(h,Uint8Array)&&(h=o.from(h,h.offset,h.byteLength)),!o.isBuffer(h))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof h);if(y===void 0&&(y=0),k===void 0&&(k=h?h.length:0),R===void 0&&(R=0),$===void 0&&($=this.length),y<0||k>h.length||R<0||$>this.length)throw new RangeError("out of range index");if(R>=$&&y>=k)return 0;if(R>=$)return-1;if(y>=k)return 1;if(y>>>=0,k>>>=0,R>>>=0,$>>>=0,this===h)return 0;let W=$-R,we=k-y;const qe=Math.min(W,we),je=this.slice(R,$),We=h.slice(y,k);for(let Ie=0;Ie<qe;++Ie)if(je[Ie]!==We[Ie]){W=je[Ie],we=We[Ie];break}return W<we?-1:we<W?1:0};function _(E,h,y,k,R){if(E.length===0)return-1;if(typeof y=="string"?(k=y,y=0):y>2147483647?y=2147483647:y<-2147483648&&(y=-2147483648),y=+y,jn(y)&&(y=R?0:E.length-1),y<0&&(y=E.length+y),y>=E.length){if(R)return-1;y=E.length-1}else if(y<0)if(R)y=0;else return-1;if(typeof h=="string"&&(h=o.from(h,k)),o.isBuffer(h))return h.length===0?-1:I(E,h,y,k,R);if(typeof h=="number")return h=h&255,typeof Uint8Array.prototype.indexOf=="function"?R?Uint8Array.prototype.indexOf.call(E,h,y):Uint8Array.prototype.lastIndexOf.call(E,h,y):I(E,[h],y,k,R);throw new TypeError("val must be string, number or Buffer")}function I(E,h,y,k,R){let $=1,W=E.length,we=h.length;if(k!==void 0&&(k=String(k).toLowerCase(),k==="ucs2"||k==="ucs-2"||k==="utf16le"||k==="utf-16le")){if(E.length<2||h.length<2)return-1;$=2,W/=2,we/=2,y/=2}function qe(We,Ie){return $===1?We[Ie]:We.readUInt16BE(Ie*$)}let je;if(R){let We=-1;for(je=y;je<W;je++)if(qe(E,je)===qe(h,We===-1?0:je-We)){if(We===-1&&(We=je),je-We+1===we)return We*$}else We!==-1&&(je-=je-We),We=-1}else for(y+we>W&&(y=W-we),je=y;je>=0;je--){let We=!0;for(let Ie=0;Ie<we;Ie++)if(qe(E,je+Ie)!==qe(h,Ie)){We=!1;break}if(We)return je}return-1}o.prototype.includes=function(h,y,k){return this.indexOf(h,y,k)!==-1},o.prototype.indexOf=function(h,y,k){return _(this,h,y,k,!0)},o.prototype.lastIndexOf=function(h,y,k){return _(this,h,y,k,!1)};function N(E,h,y,k){y=Number(y)||0;const R=E.length-y;k?(k=Number(k),k>R&&(k=R)):k=R;const $=h.length;k>$/2&&(k=$/2);let W;for(W=0;W<k;++W){const we=parseInt(h.substr(W*2,2),16);if(jn(we))return W;E[y+W]=we}return W}function C(E,h,y,k){return _t(Hr(h,E.length-y),E,y,k)}function j(E,h,y,k){return _t(xs(h),E,y,k)}function M(E,h,y,k){return _t(Lr(h),E,y,k)}function H(E,h,y,k){return _t(X(h,E.length-y),E,y,k)}o.prototype.write=function(h,y,k,R){if(y===void 0)R="utf8",k=this.length,y=0;else if(k===void 0&&typeof y=="string")R=y,k=this.length,y=0;else if(isFinite(y))y=y>>>0,isFinite(k)?(k=k>>>0,R===void 0&&(R="utf8")):(R=k,k=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const $=this.length-y;if((k===void 0||k>$)&&(k=$),h.length>0&&(k<0||y<0)||y>this.length)throw new RangeError("Attempt to write outside buffer bounds");R||(R="utf8");let W=!1;for(;;)switch(R){case"hex":return N(this,h,y,k);case"utf8":case"utf-8":return C(this,h,y,k);case"ascii":case"latin1":case"binary":return j(this,h,y,k);case"base64":return M(this,h,y,k);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return H(this,h,y,k);default:if(W)throw new TypeError("Unknown encoding: "+R);R=(""+R).toLowerCase(),W=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function V(E,h,y){return h===0&&y===E.length?e.fromByteArray(E):e.fromByteArray(E.slice(h,y))}function Q(E,h,y){y=Math.min(E.length,y);const k=[];let R=h;for(;R<y;){const $=E[R];let W=null,we=$>239?4:$>223?3:$>191?2:1;if(R+we<=y){let qe,je,We,Ie;switch(we){case 1:$<128&&(W=$);break;case 2:qe=E[R+1],(qe&192)===128&&(Ie=($&31)<<6|qe&63,Ie>127&&(W=Ie));break;case 3:qe=E[R+1],je=E[R+2],(qe&192)===128&&(je&192)===128&&(Ie=($&15)<<12|(qe&63)<<6|je&63,Ie>2047&&(Ie<55296||Ie>57343)&&(W=Ie));break;case 4:qe=E[R+1],je=E[R+2],We=E[R+3],(qe&192)===128&&(je&192)===128&&(We&192)===128&&(Ie=($&15)<<18|(qe&63)<<12|(je&63)<<6|We&63,Ie>65535&&Ie<1114112&&(W=Ie))}}W===null?(W=65533,we=1):W>65535&&(W-=65536,k.push(W>>>10&1023|55296),W=56320|W&1023),k.push(W),R+=we}return K(k)}const U=4096;function K(E){const h=E.length;if(h<=U)return String.fromCharCode.apply(String,E);let y="",k=0;for(;k<h;)y+=String.fromCharCode.apply(String,E.slice(k,k+=U));return y}function ee(E,h,y){let k="";y=Math.min(E.length,y);for(let R=h;R<y;++R)k+=String.fromCharCode(E[R]&127);return k}function q(E,h,y){let k="";y=Math.min(E.length,y);for(let R=h;R<y;++R)k+=String.fromCharCode(E[R]);return k}function O(E,h,y){const k=E.length;(!h||h<0)&&(h=0),(!y||y<0||y>k)&&(y=k);let R="";for(let $=h;$<y;++$)R+=fi[E[$]];return R}function L(E,h,y){const k=E.slice(h,y);let R="";for(let $=0;$<k.length-1;$+=2)R+=String.fromCharCode(k[$]+k[$+1]*256);return R}o.prototype.slice=function(h,y){const k=this.length;h=~~h,y=y===void 0?k:~~y,h<0?(h+=k,h<0&&(h=0)):h>k&&(h=k),y<0?(y+=k,y<0&&(y=0)):y>k&&(y=k),y<h&&(y=h);const R=this.subarray(h,y);return Object.setPrototypeOf(R,o.prototype),R};function J(E,h,y){if(E%1!==0||E<0)throw new RangeError("offset is not uint");if(E+h>y)throw new RangeError("Trying to access beyond buffer length")}o.prototype.readUintLE=o.prototype.readUIntLE=function(h,y,k){h=h>>>0,y=y>>>0,k||J(h,y,this.length);let R=this[h],$=1,W=0;for(;++W<y&&($*=256);)R+=this[h+W]*$;return R},o.prototype.readUintBE=o.prototype.readUIntBE=function(h,y,k){h=h>>>0,y=y>>>0,k||J(h,y,this.length);let R=this[h+--y],$=1;for(;y>0&&($*=256);)R+=this[h+--y]*$;return R},o.prototype.readUint8=o.prototype.readUInt8=function(h,y){return h=h>>>0,y||J(h,1,this.length),this[h]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(h,y){return h=h>>>0,y||J(h,2,this.length),this[h]|this[h+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(h,y){return h=h>>>0,y||J(h,2,this.length),this[h]<<8|this[h+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(h,y){return h=h>>>0,y||J(h,4,this.length),(this[h]|this[h+1]<<8|this[h+2]<<16)+this[h+3]*16777216},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(h,y){return h=h>>>0,y||J(h,4,this.length),this[h]*16777216+(this[h+1]<<16|this[h+2]<<8|this[h+3])},o.prototype.readBigUInt64LE=Hn(function(h){h=h>>>0,Ee(h,"offset");const y=this[h],k=this[h+7];(y===void 0||k===void 0)&&Te(h,this.length-8);const R=y+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24,$=this[++h]+this[++h]*2**8+this[++h]*2**16+k*2**24;return BigInt(R)+(BigInt($)<<BigInt(32))}),o.prototype.readBigUInt64BE=Hn(function(h){h=h>>>0,Ee(h,"offset");const y=this[h],k=this[h+7];(y===void 0||k===void 0)&&Te(h,this.length-8);const R=y*2**24+this[++h]*2**16+this[++h]*2**8+this[++h],$=this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+k;return(BigInt(R)<<BigInt(32))+BigInt($)}),o.prototype.readIntLE=function(h,y,k){h=h>>>0,y=y>>>0,k||J(h,y,this.length);let R=this[h],$=1,W=0;for(;++W<y&&($*=256);)R+=this[h+W]*$;return $*=128,R>=$&&(R-=Math.pow(2,8*y)),R},o.prototype.readIntBE=function(h,y,k){h=h>>>0,y=y>>>0,k||J(h,y,this.length);let R=y,$=1,W=this[h+--R];for(;R>0&&($*=256);)W+=this[h+--R]*$;return $*=128,W>=$&&(W-=Math.pow(2,8*y)),W},o.prototype.readInt8=function(h,y){return h=h>>>0,y||J(h,1,this.length),this[h]&128?(255-this[h]+1)*-1:this[h]},o.prototype.readInt16LE=function(h,y){h=h>>>0,y||J(h,2,this.length);const k=this[h]|this[h+1]<<8;return k&32768?k|4294901760:k},o.prototype.readInt16BE=function(h,y){h=h>>>0,y||J(h,2,this.length);const k=this[h+1]|this[h]<<8;return k&32768?k|4294901760:k},o.prototype.readInt32LE=function(h,y){return h=h>>>0,y||J(h,4,this.length),this[h]|this[h+1]<<8|this[h+2]<<16|this[h+3]<<24},o.prototype.readInt32BE=function(h,y){return h=h>>>0,y||J(h,4,this.length),this[h]<<24|this[h+1]<<16|this[h+2]<<8|this[h+3]},o.prototype.readBigInt64LE=Hn(function(h){h=h>>>0,Ee(h,"offset");const y=this[h],k=this[h+7];(y===void 0||k===void 0)&&Te(h,this.length-8);const R=this[h+4]+this[h+5]*2**8+this[h+6]*2**16+(k<<24);return(BigInt(R)<<BigInt(32))+BigInt(y+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24)}),o.prototype.readBigInt64BE=Hn(function(h){h=h>>>0,Ee(h,"offset");const y=this[h],k=this[h+7];(y===void 0||k===void 0)&&Te(h,this.length-8);const R=(y<<24)+this[++h]*2**16+this[++h]*2**8+this[++h];return(BigInt(R)<<BigInt(32))+BigInt(this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+k)}),o.prototype.readFloatLE=function(h,y){return h=h>>>0,y||J(h,4,this.length),r.read(this,h,!0,23,4)},o.prototype.readFloatBE=function(h,y){return h=h>>>0,y||J(h,4,this.length),r.read(this,h,!1,23,4)},o.prototype.readDoubleLE=function(h,y){return h=h>>>0,y||J(h,8,this.length),r.read(this,h,!0,52,8)},o.prototype.readDoubleBE=function(h,y){return h=h>>>0,y||J(h,8,this.length),r.read(this,h,!1,52,8)};function B(E,h,y,k,R,$){if(!o.isBuffer(E))throw new TypeError('"buffer" argument must be a Buffer instance');if(h>R||h<$)throw new RangeError('"value" argument is out of bounds');if(y+k>E.length)throw new RangeError("Index out of range")}o.prototype.writeUintLE=o.prototype.writeUIntLE=function(h,y,k,R){if(h=+h,y=y>>>0,k=k>>>0,!R){const we=Math.pow(2,8*k)-1;B(this,h,y,k,we,0)}let $=1,W=0;for(this[y]=h&255;++W<k&&($*=256);)this[y+W]=h/$&255;return y+k},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(h,y,k,R){if(h=+h,y=y>>>0,k=k>>>0,!R){const we=Math.pow(2,8*k)-1;B(this,h,y,k,we,0)}let $=k-1,W=1;for(this[y+$]=h&255;--$>=0&&(W*=256);)this[y+$]=h/W&255;return y+k},o.prototype.writeUint8=o.prototype.writeUInt8=function(h,y,k){return h=+h,y=y>>>0,k||B(this,h,y,1,255,0),this[y]=h&255,y+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(h,y,k){return h=+h,y=y>>>0,k||B(this,h,y,2,65535,0),this[y]=h&255,this[y+1]=h>>>8,y+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(h,y,k){return h=+h,y=y>>>0,k||B(this,h,y,2,65535,0),this[y]=h>>>8,this[y+1]=h&255,y+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(h,y,k){return h=+h,y=y>>>0,k||B(this,h,y,4,4294967295,0),this[y+3]=h>>>24,this[y+2]=h>>>16,this[y+1]=h>>>8,this[y]=h&255,y+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(h,y,k){return h=+h,y=y>>>0,k||B(this,h,y,4,4294967295,0),this[y]=h>>>24,this[y+1]=h>>>16,this[y+2]=h>>>8,this[y+3]=h&255,y+4};function F(E,h,y,k,R){ge(h,k,R,E,y,7);let $=Number(h&BigInt(4294967295));E[y++]=$,$=$>>8,E[y++]=$,$=$>>8,E[y++]=$,$=$>>8,E[y++]=$;let W=Number(h>>BigInt(32)&BigInt(4294967295));return E[y++]=W,W=W>>8,E[y++]=W,W=W>>8,E[y++]=W,W=W>>8,E[y++]=W,y}function z(E,h,y,k,R){ge(h,k,R,E,y,7);let $=Number(h&BigInt(4294967295));E[y+7]=$,$=$>>8,E[y+6]=$,$=$>>8,E[y+5]=$,$=$>>8,E[y+4]=$;let W=Number(h>>BigInt(32)&BigInt(4294967295));return E[y+3]=W,W=W>>8,E[y+2]=W,W=W>>8,E[y+1]=W,W=W>>8,E[y]=W,y+8}o.prototype.writeBigUInt64LE=Hn(function(h,y=0){return F(this,h,y,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=Hn(function(h,y=0){return z(this,h,y,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(h,y,k,R){if(h=+h,y=y>>>0,!R){const qe=Math.pow(2,8*k-1);B(this,h,y,k,qe-1,-qe)}let $=0,W=1,we=0;for(this[y]=h&255;++$<k&&(W*=256);)h<0&&we===0&&this[y+$-1]!==0&&(we=1),this[y+$]=(h/W>>0)-we&255;return y+k},o.prototype.writeIntBE=function(h,y,k,R){if(h=+h,y=y>>>0,!R){const qe=Math.pow(2,8*k-1);B(this,h,y,k,qe-1,-qe)}let $=k-1,W=1,we=0;for(this[y+$]=h&255;--$>=0&&(W*=256);)h<0&&we===0&&this[y+$+1]!==0&&(we=1),this[y+$]=(h/W>>0)-we&255;return y+k},o.prototype.writeInt8=function(h,y,k){return h=+h,y=y>>>0,k||B(this,h,y,1,127,-128),h<0&&(h=255+h+1),this[y]=h&255,y+1},o.prototype.writeInt16LE=function(h,y,k){return h=+h,y=y>>>0,k||B(this,h,y,2,32767,-32768),this[y]=h&255,this[y+1]=h>>>8,y+2},o.prototype.writeInt16BE=function(h,y,k){return h=+h,y=y>>>0,k||B(this,h,y,2,32767,-32768),this[y]=h>>>8,this[y+1]=h&255,y+2},o.prototype.writeInt32LE=function(h,y,k){return h=+h,y=y>>>0,k||B(this,h,y,4,2147483647,-2147483648),this[y]=h&255,this[y+1]=h>>>8,this[y+2]=h>>>16,this[y+3]=h>>>24,y+4},o.prototype.writeInt32BE=function(h,y,k){return h=+h,y=y>>>0,k||B(this,h,y,4,2147483647,-2147483648),h<0&&(h=4294967295+h+1),this[y]=h>>>24,this[y+1]=h>>>16,this[y+2]=h>>>8,this[y+3]=h&255,y+4},o.prototype.writeBigInt64LE=Hn(function(h,y=0){return F(this,h,y,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=Hn(function(h,y=0){return z(this,h,y,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ne(E,h,y,k,R,$){if(y+k>E.length)throw new RangeError("Index out of range");if(y<0)throw new RangeError("Index out of range")}function ae(E,h,y,k,R){return h=+h,y=y>>>0,R||ne(E,h,y,4),r.write(E,h,y,k,23,4),y+4}o.prototype.writeFloatLE=function(h,y,k){return ae(this,h,y,!0,k)},o.prototype.writeFloatBE=function(h,y,k){return ae(this,h,y,!1,k)};function fe(E,h,y,k,R){return h=+h,y=y>>>0,R||ne(E,h,y,8),r.write(E,h,y,k,52,8),y+8}o.prototype.writeDoubleLE=function(h,y,k){return fe(this,h,y,!0,k)},o.prototype.writeDoubleBE=function(h,y,k){return fe(this,h,y,!1,k)},o.prototype.copy=function(h,y,k,R){if(!o.isBuffer(h))throw new TypeError("argument should be a Buffer");if(k||(k=0),!R&&R!==0&&(R=this.length),y>=h.length&&(y=h.length),y||(y=0),R>0&&R<k&&(R=k),R===k||h.length===0||this.length===0)return 0;if(y<0)throw new RangeError("targetStart out of bounds");if(k<0||k>=this.length)throw new RangeError("Index out of range");if(R<0)throw new RangeError("sourceEnd out of bounds");R>this.length&&(R=this.length),h.length-y<R-k&&(R=h.length-y+k);const $=R-k;return this===h&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(y,k,R):Uint8Array.prototype.set.call(h,this.subarray(k,R),y),$},o.prototype.fill=function(h,y,k,R){if(typeof h=="string"){if(typeof y=="string"?(R=y,y=0,k=this.length):typeof k=="string"&&(R=k,k=this.length),R!==void 0&&typeof R!="string")throw new TypeError("encoding must be a string");if(typeof R=="string"&&!o.isEncoding(R))throw new TypeError("Unknown encoding: "+R);if(h.length===1){const W=h.charCodeAt(0);(R==="utf8"&&W<128||R==="latin1")&&(h=W)}}else typeof h=="number"?h=h&255:typeof h=="boolean"&&(h=Number(h));if(y<0||this.length<y||this.length<k)throw new RangeError("Out of range index");if(k<=y)return this;y=y>>>0,k=k===void 0?this.length:k>>>0,h||(h=0);let $;if(typeof h=="number")for($=y;$<k;++$)this[$]=h;else{const W=o.isBuffer(h)?h:o.from(h,R),we=W.length;if(we===0)throw new TypeError('The value "'+h+'" is invalid for argument "value"');for($=0;$<k-y;++$)this[$+y]=W[$%we]}return this};const ue={};function ie(E,h,y){ue[E]=class extends y{constructor(){super(),Object.defineProperty(this,"message",{value:h.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${E}]`,this.stack,delete this.name}get code(){return E}set code(R){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:R,writable:!0})}toString(){return`${this.name} [${E}]: ${this.message}`}}}ie("ERR_BUFFER_OUT_OF_BOUNDS",function(E){return E?`${E} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),ie("ERR_INVALID_ARG_TYPE",function(E,h){return`The "${E}" argument must be of type number. Received type ${typeof h}`},TypeError),ie("ERR_OUT_OF_RANGE",function(E,h,y){let k=`The value of "${E}" is out of range.`,R=y;return Number.isInteger(y)&&Math.abs(y)>2**32?R=se(String(y)):typeof y=="bigint"&&(R=String(y),(y>BigInt(2)**BigInt(32)||y<-(BigInt(2)**BigInt(32)))&&(R=se(R)),R+="n"),k+=` It must be ${h}. Received ${R}`,k},RangeError);function se(E){let h="",y=E.length;const k=E[0]==="-"?1:0;for(;y>=k+4;y-=3)h=`_${E.slice(y-3,y)}${h}`;return`${E.slice(0,y)}${h}`}function be(E,h,y){Ee(h,"offset"),(E[h]===void 0||E[h+y]===void 0)&&Te(h,E.length-(y+1))}function ge(E,h,y,k,R,$){if(E>y||E<h){const W=typeof h=="bigint"?"n":"";let we;throw h===0||h===BigInt(0)?we=`>= 0${W} and < 2${W} ** ${($+1)*8}${W}`:we=`>= -(2${W} ** ${($+1)*8-1}${W}) and < 2 ** ${($+1)*8-1}${W}`,new ue.ERR_OUT_OF_RANGE("value",we,E)}be(k,R,$)}function Ee(E,h){if(typeof E!="number")throw new ue.ERR_INVALID_ARG_TYPE(h,"number",E)}function Te(E,h,y){throw Math.floor(E)!==E?(Ee(E,y),new ue.ERR_OUT_OF_RANGE("offset","an integer",E)):h<0?new ue.ERR_BUFFER_OUT_OF_BOUNDS:new ue.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${h}`,E)}const rt=/[^+/0-9A-Za-z-_]/g;function Ce(E){if(E=E.split("=")[0],E=E.trim().replace(rt,""),E.length<2)return"";for(;E.length%4!==0;)E=E+"=";return E}function Hr(E,h){h=h||1/0;let y;const k=E.length;let R=null;const $=[];for(let W=0;W<k;++W){if(y=E.charCodeAt(W),y>55295&&y<57344){if(!R){if(y>56319){(h-=3)>-1&&$.push(239,191,189);continue}else if(W+1===k){(h-=3)>-1&&$.push(239,191,189);continue}R=y;continue}if(y<56320){(h-=3)>-1&&$.push(239,191,189),R=y;continue}y=(R-55296<<10|y-56320)+65536}else R&&(h-=3)>-1&&$.push(239,191,189);if(R=null,y<128){if((h-=1)<0)break;$.push(y)}else if(y<2048){if((h-=2)<0)break;$.push(y>>6|192,y&63|128)}else if(y<65536){if((h-=3)<0)break;$.push(y>>12|224,y>>6&63|128,y&63|128)}else if(y<1114112){if((h-=4)<0)break;$.push(y>>18|240,y>>12&63|128,y>>6&63|128,y&63|128)}else throw new Error("Invalid code point")}return $}function xs(E){const h=[];for(let y=0;y<E.length;++y)h.push(E.charCodeAt(y)&255);return h}function X(E,h){let y,k,R;const $=[];for(let W=0;W<E.length&&!((h-=2)<0);++W)y=E.charCodeAt(W),k=y>>8,R=y%256,$.push(R),$.push(k);return $}function Lr(E){return e.toByteArray(Ce(E))}function _t(E,h,y,k){let R;for(R=0;R<k&&!(R+y>=h.length||R>=E.length);++R)h[R+y]=E[R];return R}function It(E,h){return E instanceof h||E!=null&&E.constructor!=null&&E.constructor.name!=null&&E.constructor.name===h.name}function jn(E){return E!==E}const fi=function(){const E="0123456789abcdef",h=new Array(256);for(let y=0;y<16;++y){const k=y*16;for(let R=0;R<16;++R)h[k+R]=E[y]+E[R]}return h}();function Hn(E){return typeof BigInt>"u"?x6:E}function x6(){throw new Error("BigInt not supported")}})(si);var Ma={Array:function(t){return t!=null&&t.constructor===Array},Boolean:function(t){return typeof t=="boolean"},Function:function(t){return typeof t=="function"},Nil:function(t){return t==null},Number:function(t){return typeof t=="number"},Object:function(t){return typeof t=="object"},String:function(t){return typeof t=="string"},"":function(){return!0}};Ma.Null=Ma.Nil;for(var L0 in Ma)Ma[L0].toJSON=(function(t){return t}).bind(null,L0);var th=Ma,$s=th;function $m(t){return t.name||t.toString().match(/function (.*?)\s*\(/)[1]}function rh(t){return $s.Nil(t)?"":$m(t.constructor)}function ov(t){return $s.Function(t)?"":$s.String(t)?JSON.stringify(t):t&&$s.Object(t)?"":t}function nh(t,e){Error.captureStackTrace&&Error.captureStackTrace(t,e)}function Ic(t){return $s.Function(t)?t.toJSON?t.toJSON():$m(t):$s.Array(t)?"Array":t&&$s.Object(t)?"Object":t!==void 0?t:""}function jm(t,e,r){var n=ov(e);return"Expected "+Ic(t)+", got"+(r!==""?" "+r:"")+(n!==""?" "+n:"")}function Bn(t,e,r){r=r||rh(e),this.message=jm(t,e,r),nh(this,Bn),this.__type=t,this.__value=e,this.__valueTypeName=r}Bn.prototype=Object.create(Error.prototype);Bn.prototype.constructor=Bn;function cv(t,e,r,n,s){var i='" of type ';return e==="key"&&(i='" with key type '),jm('property "'+Ic(r)+i+Ic(t),n,s)}function Pi(t,e,r,n,s){t?(s=s||rh(n),this.message=cv(t,r,e,n,s)):this.message='Unexpected property "'+e+'"',nh(this,Bn),this.__label=r,this.__property=e,this.__type=t,this.__value=n,this.__valueTypeName=s}Pi.prototype=Object.create(Error.prototype);Pi.prototype.constructor=Bn;function uv(t,e){return new Bn(t,{},e)}function lv(t,e,r){return t instanceof Pi?(e=e+"."+t.__property,t=new Pi(t.__type,e,t.__label,t.__value,t.__valueTypeName)):t instanceof Bn&&(t=new Pi(t.__type,e,r,t.__value,t.__valueTypeName)),nh(t),t}var Hm={TfTypeError:Bn,TfPropertyTypeError:Pi,tfCustomError:uv,tfSubError:lv,tfJSON:Ic,getValueTypeName:rh},Du,D0;function fv(){if(D0)return Du;D0=1;var t=th,e=Hm;function r(_){return Buffer.isBuffer(_)}function n(_){return typeof _=="string"&&/^([0-9a-f]{2})+$/i.test(_)}function s(_,I){var N=_.toJSON();function C(j){if(!_(j))return!1;if(j.length===I)return!0;throw e.tfCustomError(N+"(Length: "+I+")",N+"(Length: "+j.length+")")}return C.toJSON=function(){return N},C}var i=s.bind(null,t.Array),a=s.bind(null,r),o=s.bind(null,n),c=s.bind(null,t.String);function u(_,I,N){N=N||t.Number;function C(j,M){return N(j,M)&&j>_&&j<I}return C.toJSON=function(){return`${N.toJSON()} between [${_}, ${I}]`},C}var l=Math.pow(2,53)-1;function f(_){return typeof _=="number"&&isFinite(_)}function p(_){return _<<24>>24===_}function d(_){return _<<16>>16===_}function b(_){return(_|0)===_}function g(_){return typeof _=="number"&&_>=-l&&_<=l&&Math.floor(_)===_}function A(_){return(_&255)===_}function S(_){return(_&65535)===_}function T(_){return _>>>0===_}function v(_){return typeof _=="number"&&_>=0&&_<=l&&Math.floor(_)===_}var w={ArrayN:i,Buffer:r,BufferN:a,Finite:f,Hex:n,HexN:o,Int8:p,Int16:d,Int32:b,Int53:g,Range:u,StringN:c,UInt8:A,UInt16:S,UInt32:T,UInt53:v};for(var x in w)w[x].toJSON=(function(_){return _}).bind(null,x);return Du=w,Du}var vo=Hm,ht=th,un=vo.tfJSON,Lm=vo.TfTypeError,Dm=vo.TfPropertyTypeError,ca=vo.tfSubError,dv=vo.getValueTypeName,xn={arrayOf:function(e,r){e=Jr(e),r=r||{};function n(s,i){return!ht.Array(s)||ht.Nil(s)||r.minLength!==void 0&&s.length<r.minLength||r.maxLength!==void 0&&s.length>r.maxLength||r.length!==void 0&&s.length!==r.length?!1:s.every(function(a,o){try{return Rt(e,a,i)}catch(c){throw ca(c,o)}})}return n.toJSON=function(){var s="["+un(e)+"]";return r.length!==void 0?s+="{"+r.length+"}":(r.minLength!==void 0||r.maxLength!==void 0)&&(s+="{"+(r.minLength===void 0?0:r.minLength)+","+(r.maxLength===void 0?1/0:r.maxLength)+"}"),s},n},maybe:function t(e){e=Jr(e);function r(n,s){return ht.Nil(n)||e(n,s,t)}return r.toJSON=function(){return"?"+un(e)},r},map:function(e,r){e=Jr(e),r&&(r=Jr(r));function n(s,i){if(!ht.Object(s)||ht.Nil(s))return!1;for(var a in s){try{r&&Rt(r,a,i)}catch(c){throw ca(c,a,"key")}try{var o=s[a];Rt(e,o,i)}catch(c){throw ca(c,a)}}return!0}return r?n.toJSON=function(){return"{"+un(r)+": "+un(e)+"}"}:n.toJSON=function(){return"{"+un(e)+"}"},n},object:function(e){var r={};for(var n in e)r[n]=Jr(e[n]);function s(i,a){if(!ht.Object(i)||ht.Nil(i))return!1;var o;try{for(o in r){var c=r[o],u=i[o];Rt(c,u,a)}}catch(l){throw ca(l,o)}if(a){for(o in i)if(!r[o])throw new Dm(void 0,o)}return!0}return s.toJSON=function(){return un(r)},s},anyOf:function(){var e=[].slice.call(arguments).map(Jr);function r(n,s){return e.some(function(i){try{return Rt(i,n,s)}catch{return!1}})}return r.toJSON=function(){return e.map(un).join("|")},r},allOf:function(){var e=[].slice.call(arguments).map(Jr);function r(n,s){return e.every(function(i){try{return Rt(i,n,s)}catch{return!1}})}return r.toJSON=function(){return e.map(un).join(" & ")},r},quacksLike:function(e){function r(n){return e===dv(n)}return r.toJSON=function(){return e},r},tuple:function(){var e=[].slice.call(arguments).map(Jr);function r(n,s){return ht.Nil(n)||ht.Nil(n.length)||s&&n.length!==e.length?!1:e.every(function(i,a){try{return Rt(i,n[a],s)}catch(o){throw ca(o,a)}})}return r.toJSON=function(){return"("+e.map(un).join(", ")+")"},r},value:function(e){function r(n){return n===e}return r.toJSON=function(){return e},r}};xn.oneOf=xn.anyOf;function Jr(t){if(ht.String(t))return t[0]==="?"?xn.maybe(t.slice(1)):ht[t]||xn.quacksLike(t);if(t&&ht.Object(t)){if(ht.Array(t)){if(t.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return xn.arrayOf(t[0])}return xn.object(t)}else if(ht.Function(t))return t;return xn.value(t)}function Rt(t,e,r,n){if(ht.Function(t)){if(t(e,r))return!0;throw new Lm(n||t,e)}return Rt(Jr(t),e,r)}for(var us in ht)Rt[us]=ht[us];for(us in xn)Rt[us]=xn[us];var z0=fv();for(us in z0)Rt[us]=z0[us];Rt.compile=Jr;Rt.TfTypeError=Lm;Rt.TfPropertyTypeError=Dm;var hv=Rt;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.oneOf=t.Null=t.BufferN=t.Function=t.UInt32=t.UInt8=t.tuple=t.maybe=t.Hex=t.Buffer=t.String=t.Boolean=t.Array=t.Number=t.Hash256bit=t.Hash160bit=t.Buffer256bit=t.isTaptree=t.isTapleaf=t.TAPLEAF_VERSION_MASK=t.Satoshi=t.isPoint=t.stacksEqual=t.typeforce=void 0;const e=si;t.typeforce=hv;const r=e.Buffer.alloc(32,0),n=e.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function s(l,f){return l.length!==f.length?!1:l.every((p,d)=>p.equals(f[d]))}t.stacksEqual=s;function i(l){if(!e.Buffer.isBuffer(l)||l.length<33)return!1;const f=l[0],p=l.slice(1,33);if(p.compare(r)===0||p.compare(n)>=0)return!1;if((f===2||f===3)&&l.length===33)return!0;const d=l.slice(33);return d.compare(r)===0||d.compare(n)>=0?!1:f===4&&l.length===65}t.isPoint=i;const a=21*1e14;function o(l){return t.typeforce.UInt53(l)&&l<=a}t.Satoshi=o,t.TAPLEAF_VERSION_MASK=254;function c(l){return!l||!("output"in l)||!e.Buffer.isBuffer(l.output)?!1:l.version!==void 0?(l.version&t.TAPLEAF_VERSION_MASK)===l.version:!0}t.isTapleaf=c;function u(l){return(0,t.Array)(l)?l.length!==2?!1:l.every(f=>u(f)):c(l)}t.isTaptree=u,t.Buffer256bit=t.typeforce.BufferN(32),t.Hash160bit=t.typeforce.BufferN(20),t.Hash256bit=t.typeforce.BufferN(32),t.Number=t.typeforce.Number,t.Array=t.typeforce.Array,t.Boolean=t.typeforce.Boolean,t.String=t.typeforce.String,t.Buffer=t.typeforce.Buffer,t.Hex=t.typeforce.Hex,t.maybe=t.typeforce.maybe,t.tuple=t.typeforce.tuple,t.UInt8=t.typeforce.UInt8,t.UInt32=t.typeforce.UInt32,t.Function=t.typeforce.Function,t.BufferN=t.typeforce.BufferN,t.Null=t.typeforce.Null,t.oneOf=t.typeforce.oneOf})(kt);var Eo={},pt={};Object.defineProperty(pt,"__esModule",{value:!0});pt.BufferReader=pt.BufferWriter=pt.cloneBuffer=pt.reverseBuffer=pt.writeUInt64LE=pt.readUInt64LE=pt.varuint=void 0;const js=kt,{typeforce:zm}=js,$a=Cm;pt.varuint=$a;function Vm(t,e){if(typeof t!="number")throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}function Gm(t,e){const r=t.readUInt32LE(e);let n=t.readUInt32LE(e+4);return n*=4294967296,Vm(n+r,9007199254740991),n+r}pt.readUInt64LE=Gm;function qm(t,e,r){return Vm(e,9007199254740991),t.writeInt32LE(e&-1,r),t.writeUInt32LE(Math.floor(e/4294967296),r+4),r+8}pt.writeUInt64LE=qm;function pv(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;n<t.length/2;n++)r=t[n],t[n]=t[e],t[e]=r,e--;return t}pt.reverseBuffer=pv;function yv(t){const e=Buffer.allocUnsafe(t.length);return t.copy(e),e}pt.cloneBuffer=yv;class sh{static withCapacity(e){return new sh(Buffer.alloc(e))}constructor(e,r=0){this.buffer=e,this.offset=r,zm(js.tuple(js.Buffer,js.UInt32),[e,r])}writeUInt8(e){this.offset=this.buffer.writeUInt8(e,this.offset)}writeInt32(e){this.offset=this.buffer.writeInt32LE(e,this.offset)}writeUInt32(e){this.offset=this.buffer.writeUInt32LE(e,this.offset)}writeUInt64(e){this.offset=qm(this.buffer,e,this.offset)}writeVarInt(e){$a.encode(e,this.buffer,this.offset),this.offset+=$a.encode.bytes}writeSlice(e){if(this.buffer.length<this.offset+e.length)throw new Error("Cannot write slice out of bounds");this.offset+=e.copy(this.buffer,this.offset)}writeVarSlice(e){this.writeVarInt(e.length),this.writeSlice(e)}writeVector(e){this.writeVarInt(e.length),e.forEach(r=>this.writeVarSlice(r))}end(){if(this.buffer.length===this.offset)return this.buffer;throw new Error(`buffer size ${this.buffer.length}, offset ${this.offset}`)}}pt.BufferWriter=sh;class mv{constructor(e,r=0){this.buffer=e,this.offset=r,zm(js.tuple(js.Buffer,js.UInt32),[e,r])}readUInt8(){const e=this.buffer.readUInt8(this.offset);return this.offset++,e}readInt32(){const e=this.buffer.readInt32LE(this.offset);return this.offset+=4,e}readUInt32(){const e=this.buffer.readUInt32LE(this.offset);return this.offset+=4,e}readUInt64(){const e=Gm(this.buffer,this.offset);return this.offset+=8,e}readVarInt(){const e=$a.decode(this.buffer,this.offset);return this.offset+=$a.decode.bytes,e}readSlice(e){if(this.buffer.length<this.offset+e)throw new Error("Cannot read slice out of bounds");const r=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,r}readVarSlice(){return this.readSlice(this.readVarInt())}readVector(){const e=this.readVarInt(),r=[];for(let n=0;n<e;n++)r.push(this.readVarSlice());return r}}pt.BufferReader=mv;var ws={},ji={},Nt={},At={},Wc={},Kc={};Object.defineProperty(Kc,"__esModule",{value:!0});Kc.crypto=void 0;Kc.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;(function(t){/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */Object.defineProperty(t,"__esModule",{value:!0}),t.wrapXOFConstructorWithOpts=t.wrapConstructorWithOpts=t.wrapConstructor=t.Hash=t.nextTick=t.swap32IfBE=t.byteSwapIfBE=t.swap8IfBE=t.isLE=void 0,t.isBytes=r,t.anumber=n,t.abytes=s,t.ahash=i,t.aexists=a,t.aoutput=o,t.u8=c,t.u32=u,t.clean=l,t.createView=f,t.rotr=p,t.rotl=d,t.byteSwap=b,t.byteSwap32=g,t.bytesToHex=T,t.hexToBytes=x,t.asyncLoop=I,t.utf8ToBytes=N,t.bytesToUtf8=C,t.toBytes=j,t.kdfInputToBytes=M,t.concatBytes=H,t.checkOpts=V,t.createHasher=U,t.createOptHasher=K,t.createXOFer=ee,t.randomBytes=q;const e=Kc;function r(O){return O instanceof Uint8Array||ArrayBuffer.isView(O)&&O.constructor.name==="Uint8Array"}function n(O){if(!Number.isSafeInteger(O)||O<0)throw new Error("positive integer expected, got "+O)}function s(O,...L){if(!r(O))throw new Error("Uint8Array expected");if(L.length>0&&!L.includes(O.length))throw new Error("Uint8Array expected of length "+L+", got length="+O.length)}function i(O){if(typeof O!="function"||typeof O.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");n(O.outputLen),n(O.blockLen)}function a(O,L=!0){if(O.destroyed)throw new Error("Hash instance has been destroyed");if(L&&O.finished)throw new Error("Hash#digest() has already been called")}function o(O,L){s(O);const J=L.outputLen;if(O.length<J)throw new Error("digestInto() expects output buffer of length at least "+J)}function c(O){return new Uint8Array(O.buffer,O.byteOffset,O.byteLength)}function u(O){return new Uint32Array(O.buffer,O.byteOffset,Math.floor(O.byteLength/4))}function l(...O){for(let L=0;L<O.length;L++)O[L].fill(0)}function f(O){return new DataView(O.buffer,O.byteOffset,O.byteLength)}function p(O,L){return O<<32-L|O>>>L}function d(O,L){return O<<L|O>>>32-L>>>0}t.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function b(O){return O<<24&4278190080|O<<8&16711680|O>>>8&65280|O>>>24&255}t.swap8IfBE=t.isLE?O=>O:O=>b(O),t.byteSwapIfBE=t.swap8IfBE;function g(O){for(let L=0;L<O.length;L++)O[L]=b(O[L]);return O}t.swap32IfBE=t.isLE?O=>O:g;const A=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",S=Array.from({length:256},(O,L)=>L.toString(16).padStart(2,"0"));function T(O){if(s(O),A)return O.toHex();let L="";for(let J=0;J<O.length;J++)L+=S[O[J]];return L}const v={_0:48,_9:57,A:65,F:70,a:97,f:102};function w(O){if(O>=v._0&&O<=v._9)return O-v._0;if(O>=v.A&&O<=v.F)return O-(v.A-10);if(O>=v.a&&O<=v.f)return O-(v.a-10)}function x(O){if(typeof O!="string")throw new Error("hex string expected, got "+typeof O);if(A)return Uint8Array.fromHex(O);const L=O.length,J=L/2;if(L%2)throw new Error("hex string expected, got unpadded hex of length "+L);const B=new Uint8Array(J);for(let F=0,z=0;F<J;F++,z+=2){const ne=w(O.charCodeAt(z)),ae=w(O.charCodeAt(z+1));if(ne===void 0||ae===void 0){const fe=O[z]+O[z+1];throw new Error('hex string expected, got non-hex character "'+fe+'" at index '+z)}B[F]=ne*16+ae}return B}const _=async()=>{};t.nextTick=_;async function I(O,L,J){let B=Date.now();for(let F=0;F<O;F++){J(F);const z=Date.now()-B;z>=0&&z<L||(await(0,t.nextTick)(),B+=z)}}function N(O){if(typeof O!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(O))}function C(O){return new TextDecoder().decode(O)}function j(O){return typeof O=="string"&&(O=N(O)),s(O),O}function M(O){return typeof O=="string"&&(O=N(O)),s(O),O}function H(...O){let L=0;for(let B=0;B<O.length;B++){const F=O[B];s(F),L+=F.length}const J=new Uint8Array(L);for(let B=0,F=0;B<O.length;B++){const z=O[B];J.set(z,F),F+=z.length}return J}function V(O,L){if(L!==void 0&&{}.toString.call(L)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(O,L)}class Q{}t.Hash=Q;function U(O){const L=B=>O().update(j(B)).digest(),J=O();return L.outputLen=J.outputLen,L.blockLen=J.blockLen,L.create=()=>O(),L}function K(O){const L=(B,F)=>O(F).update(j(B)).digest(),J=O({});return L.outputLen=J.outputLen,L.blockLen=J.blockLen,L.create=B=>O(B),L}function ee(O){const L=(B,F)=>O(F).update(j(B)).digest(),J=O({});return L.outputLen=J.outputLen,L.blockLen=J.blockLen,L.create=B=>O(B),L}t.wrapConstructor=U,t.wrapConstructorWithOpts=K,t.wrapXOFConstructorWithOpts=ee;function q(O=32){if(e.crypto&&typeof e.crypto.getRandomValues=="function")return e.crypto.getRandomValues(new Uint8Array(O));if(e.crypto&&typeof e.crypto.randomBytes=="function")return Uint8Array.from(e.crypto.randomBytes(O));throw new Error("crypto.getRandomValues must be defined")}})(Wc);Object.defineProperty(At,"__esModule",{value:!0});At.SHA512_IV=At.SHA384_IV=At.SHA224_IV=At.SHA256_IV=At.HashMD=void 0;At.setBigUint64=Wm;At.Chi=bv;At.Maj=gv;const Dr=Wc;function Wm(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const s=BigInt(32),i=BigInt(4294967295),a=Number(r>>s&i),o=Number(r&i),c=n?4:0,u=n?0:4;t.setUint32(e+c,a,n),t.setUint32(e+u,o,n)}function bv(t,e,r){return t&e^~t&r}function gv(t,e,r){return t&e^t&r^e&r}let wv=class extends Dr.Hash{constructor(e,r,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=(0,Dr.createView)(this.buffer)}update(e){(0,Dr.aexists)(this),e=(0,Dr.toBytes)(e),(0,Dr.abytes)(e);const{view:r,buffer:n,blockLen:s}=this,i=e.length;for(let a=0;a<i;){const o=Math.min(s-this.pos,i-a);if(o===s){const c=(0,Dr.createView)(e);for(;s<=i-a;a+=s)this.process(c,a);continue}n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){(0,Dr.aexists)(this),(0,Dr.aoutput)(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:s,isLE:i}=this;let{pos:a}=this;r[a++]=128,(0,Dr.clean)(this.buffer.subarray(a)),this.padOffset>s-a&&(this.process(n,0),a=0);for(let f=a;f<s;f++)r[f]=0;Wm(n,s-8,BigInt(this.length*8),i),this.process(n,0);const o=(0,Dr.createView)(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)o.setUint32(4*f,l[f],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:s,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=s,e.pos=o,s%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}};At.HashMD=wv;At.SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);At.SHA224_IV=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);At.SHA384_IV=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]);At.SHA512_IV=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);Object.defineProperty(Nt,"__esModule",{value:!0});Nt.ripemd160=Nt.RIPEMD160=Nt.md5=Nt.MD5=Nt.sha1=Nt.SHA1=void 0;const Hs=At,yt=Wc,mi=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Ln=new Uint32Array(80);class Km extends Hs.HashMD{constructor(){super(64,20,8,!1),this.A=mi[0]|0,this.B=mi[1]|0,this.C=mi[2]|0,this.D=mi[3]|0,this.E=mi[4]|0}get(){const{A:e,B:r,C:n,D:s,E:i}=this;return[e,r,n,s,i]}set(e,r,n,s,i){this.A=e|0,this.B=r|0,this.C=n|0,this.D=s|0,this.E=i|0}process(e,r){for(let c=0;c<16;c++,r+=4)Ln[c]=e.getUint32(r,!1);for(let c=16;c<80;c++)Ln[c]=(0,yt.rotl)(Ln[c-3]^Ln[c-8]^Ln[c-14]^Ln[c-16],1);let{A:n,B:s,C:i,D:a,E:o}=this;for(let c=0;c<80;c++){let u,l;c<20?(u=(0,Hs.Chi)(s,i,a),l=1518500249):c<40?(u=s^i^a,l=1859775393):c<60?(u=(0,Hs.Maj)(s,i,a),l=2400959708):(u=s^i^a,l=3395469782);const f=(0,yt.rotl)(n,5)+u+o+l+Ln[c]|0;o=a,a=i,i=(0,yt.rotl)(s,30),s=n,n=f}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,this.set(n,s,i,a,o)}roundClean(){(0,yt.clean)(Ln)}destroy(){this.set(0,0,0,0,0),(0,yt.clean)(this.buffer)}}Nt.SHA1=Km;Nt.sha1=(0,yt.createHasher)(()=>new Km);const vv=Math.pow(2,32),Ev=Array.from({length:64},(t,e)=>Math.floor(vv*Math.abs(Math.sin(e+1)))),Wo=mi.slice(0,4),zu=new Uint32Array(16);class Xm extends Hs.HashMD{constructor(){super(64,16,8,!0),this.A=Wo[0]|0,this.B=Wo[1]|0,this.C=Wo[2]|0,this.D=Wo[3]|0}get(){const{A:e,B:r,C:n,D:s}=this;return[e,r,n,s]}set(e,r,n,s){this.A=e|0,this.B=r|0,this.C=n|0,this.D=s|0}process(e,r){for(let o=0;o<16;o++,r+=4)zu[o]=e.getUint32(r,!0);let{A:n,B:s,C:i,D:a}=this;for(let o=0;o<64;o++){let c,u,l;o<16?(c=(0,Hs.Chi)(s,i,a),u=o,l=[7,12,17,22]):o<32?(c=(0,Hs.Chi)(a,s,i),u=(5*o+1)%16,l=[5,9,14,20]):o<48?(c=s^i^a,u=(3*o+5)%16,l=[4,11,16,23]):(c=i^(s|~a),u=7*o%16,l=[6,10,15,21]),c=c+n+Ev[o]+zu[u],n=a,a=i,i=s,s=s+(0,yt.rotl)(c,l[o%4])}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,a=a+this.D|0,this.set(n,s,i,a)}roundClean(){(0,yt.clean)(zu)}destroy(){this.set(0,0,0,0),(0,yt.clean)(this.buffer)}}Nt.MD5=Xm;Nt.md5=(0,yt.createHasher)(()=>new Xm);const Av=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Ym=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),Sv=Ym.map(t=>(9*t+5)%16),Jm=(()=>{const r=[[Ym],[Sv]];for(let n=0;n<4;n++)for(let s of r)s.push(s[n].map(i=>Av[i]));return r})(),Zm=Jm[0],Qm=Jm[1],eb=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(t=>Uint8Array.from(t)),xv=Zm.map((t,e)=>t.map(r=>eb[e][r])),kv=Qm.map((t,e)=>t.map(r=>eb[e][r])),Tv=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),_v=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function V0(t,e,r,n){return t===0?e^r^n:t===1?e&r|~e&n:t===2?(e|~r)^n:t===3?e&n|r&~n:e^(r|~n)}const Ko=new Uint32Array(16);class tb extends Hs.HashMD{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:r,h2:n,h3:s,h4:i}=this;return[e,r,n,s,i]}set(e,r,n,s,i){this.h0=e|0,this.h1=r|0,this.h2=n|0,this.h3=s|0,this.h4=i|0}process(e,r){for(let d=0;d<16;d++,r+=4)Ko[d]=e.getUint32(r,!0);let n=this.h0|0,s=n,i=this.h1|0,a=i,o=this.h2|0,c=o,u=this.h3|0,l=u,f=this.h4|0,p=f;for(let d=0;d<5;d++){const b=4-d,g=Tv[d],A=_v[d],S=Zm[d],T=Qm[d],v=xv[d],w=kv[d];for(let x=0;x<16;x++){const _=(0,yt.rotl)(n+V0(d,i,o,u)+Ko[S[x]]+g,v[x])+f|0;n=f,f=u,u=(0,yt.rotl)(o,10)|0,o=i,i=_}for(let x=0;x<16;x++){const _=(0,yt.rotl)(s+V0(b,a,c,l)+Ko[T[x]]+A,w[x])+p|0;s=p,p=l,l=(0,yt.rotl)(c,10)|0,c=a,a=_}}this.set(this.h1+o+l|0,this.h2+u+p|0,this.h3+f+s|0,this.h4+n+a|0,this.h0+i+c|0)}roundClean(){(0,yt.clean)(Ko)}destroy(){this.destroyed=!0,(0,yt.clean)(this.buffer),this.set(0,0,0,0,0)}}Nt.RIPEMD160=tb;Nt.ripemd160=(0,yt.createHasher)(()=>new tb);Object.defineProperty(ji,"__esModule",{value:!0});ji.ripemd160=ji.RIPEMD160=void 0;const rb=Nt;ji.RIPEMD160=rb.RIPEMD160;ji.ripemd160=rb.ripemd160;var Hi={};Object.defineProperty(Hi,"__esModule",{value:!0});Hi.sha1=Hi.SHA1=void 0;const nb=Nt;Hi.SHA1=nb.SHA1;Hi.sha1=nb.sha1;var Ir={},Ue={},he={};Object.defineProperty(he,"__esModule",{value:!0});he.toBig=he.shrSL=he.shrSH=he.rotrSL=he.rotrSH=he.rotrBL=he.rotrBH=he.rotr32L=he.rotr32H=he.rotlSL=he.rotlSH=he.rotlBL=he.rotlBH=he.add5L=he.add5H=he.add4L=he.add4H=he.add3L=he.add3H=void 0;he.add=gb;he.fromBig=ih;he.split=sb;const Xo=BigInt(2**32-1),Wf=BigInt(32);function ih(t,e=!1){return e?{h:Number(t&Xo),l:Number(t>>Wf&Xo)}:{h:Number(t>>Wf&Xo)|0,l:Number(t&Xo)|0}}function sb(t,e=!1){const r=t.length;let n=new Uint32Array(r),s=new Uint32Array(r);for(let i=0;i<r;i++){const{h:a,l:o}=ih(t[i],e);[n[i],s[i]]=[a,o]}return[n,s]}const ib=(t,e)=>BigInt(t>>>0)<<Wf|BigInt(e>>>0);he.toBig=ib;const ab=(t,e,r)=>t>>>r;he.shrSH=ab;const ob=(t,e,r)=>t<<32-r|e>>>r;he.shrSL=ob;const cb=(t,e,r)=>t>>>r|e<<32-r;he.rotrSH=cb;const ub=(t,e,r)=>t<<32-r|e>>>r;he.rotrSL=ub;const lb=(t,e,r)=>t<<64-r|e>>>r-32;he.rotrBH=lb;const fb=(t,e,r)=>t>>>r-32|e<<64-r;he.rotrBL=fb;const db=(t,e)=>e;he.rotr32H=db;const hb=(t,e)=>t;he.rotr32L=hb;const pb=(t,e,r)=>t<<r|e>>>32-r;he.rotlSH=pb;const yb=(t,e,r)=>e<<r|t>>>32-r;he.rotlSL=yb;const mb=(t,e,r)=>e<<r-32|t>>>64-r;he.rotlBH=mb;const bb=(t,e,r)=>t<<r-32|e>>>64-r;he.rotlBL=bb;function gb(t,e,r,n){const s=(e>>>0)+(n>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}const wb=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0);he.add3L=wb;const vb=(t,e,r,n)=>e+r+n+(t/2**32|0)|0;he.add3H=vb;const Eb=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0);he.add4L=Eb;const Ab=(t,e,r,n,s)=>e+r+n+s+(t/2**32|0)|0;he.add4H=Ab;const Sb=(t,e,r,n,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(s>>>0);he.add5L=Sb;const xb=(t,e,r,n,s,i)=>e+r+n+s+i+(t/2**32|0)|0;he.add5H=xb;const Iv={fromBig:ih,split:sb,toBig:ib,shrSH:ab,shrSL:ob,rotrSH:cb,rotrSL:ub,rotrBH:lb,rotrBL:fb,rotr32H:db,rotr32L:hb,rotlSH:pb,rotlSL:yb,rotlBH:mb,rotlBL:bb,add:gb,add3L:wb,add3H:vb,add4L:Eb,add4H:Ab,add5H:xb,add5L:Sb};he.default=Iv;Object.defineProperty(Ue,"__esModule",{value:!0});Ue.sha512_224=Ue.sha512_256=Ue.sha384=Ue.sha512=Ue.sha224=Ue.sha256=Ue.SHA512_256=Ue.SHA512_224=Ue.SHA384=Ue.SHA512=Ue.SHA224=Ue.SHA256=void 0;const ce=At,ye=he,Ze=Wc,Pv=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]),Dn=new Uint32Array(64);let ah=class extends ce.HashMD{constructor(e=32){super(64,e,8,!1),this.A=ce.SHA256_IV[0]|0,this.B=ce.SHA256_IV[1]|0,this.C=ce.SHA256_IV[2]|0,this.D=ce.SHA256_IV[3]|0,this.E=ce.SHA256_IV[4]|0,this.F=ce.SHA256_IV[5]|0,this.G=ce.SHA256_IV[6]|0,this.H=ce.SHA256_IV[7]|0}get(){const{A:e,B:r,C:n,D:s,E:i,F:a,G:o,H:c}=this;return[e,r,n,s,i,a,o,c]}set(e,r,n,s,i,a,o,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=s|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=c|0}process(e,r){for(let f=0;f<16;f++,r+=4)Dn[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){const p=Dn[f-15],d=Dn[f-2],b=(0,Ze.rotr)(p,7)^(0,Ze.rotr)(p,18)^p>>>3,g=(0,Ze.rotr)(d,17)^(0,Ze.rotr)(d,19)^d>>>10;Dn[f]=g+Dn[f-7]+b+Dn[f-16]|0}let{A:n,B:s,C:i,D:a,E:o,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){const p=(0,Ze.rotr)(o,6)^(0,Ze.rotr)(o,11)^(0,Ze.rotr)(o,25),d=l+p+(0,ce.Chi)(o,c,u)+Pv[f]+Dn[f]|0,g=((0,Ze.rotr)(n,2)^(0,Ze.rotr)(n,13)^(0,Ze.rotr)(n,22))+(0,ce.Maj)(n,s,i)|0;l=u,u=c,c=o,o=a+d|0,a=i,i=s,s=n,n=d+g|0}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,s,i,a,o,c,u,l)}roundClean(){(0,Ze.clean)(Dn)}destroy(){this.set(0,0,0,0,0,0,0,0),(0,Ze.clean)(this.buffer)}};Ue.SHA256=ah;class kb extends ah{constructor(){super(28),this.A=ce.SHA224_IV[0]|0,this.B=ce.SHA224_IV[1]|0,this.C=ce.SHA224_IV[2]|0,this.D=ce.SHA224_IV[3]|0,this.E=ce.SHA224_IV[4]|0,this.F=ce.SHA224_IV[5]|0,this.G=ce.SHA224_IV[6]|0,this.H=ce.SHA224_IV[7]|0}}Ue.SHA224=kb;const Tb=ye.split(["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(t=>BigInt(t))),Ov=Tb[0],Bv=Tb[1],zn=new Uint32Array(80),Vn=new Uint32Array(80);class Ao extends ce.HashMD{constructor(e=64){super(128,e,16,!1),this.Ah=ce.SHA512_IV[0]|0,this.Al=ce.SHA512_IV[1]|0,this.Bh=ce.SHA512_IV[2]|0,this.Bl=ce.SHA512_IV[3]|0,this.Ch=ce.SHA512_IV[4]|0,this.Cl=ce.SHA512_IV[5]|0,this.Dh=ce.SHA512_IV[6]|0,this.Dl=ce.SHA512_IV[7]|0,this.Eh=ce.SHA512_IV[8]|0,this.El=ce.SHA512_IV[9]|0,this.Fh=ce.SHA512_IV[10]|0,this.Fl=ce.SHA512_IV[11]|0,this.Gh=ce.SHA512_IV[12]|0,this.Gl=ce.SHA512_IV[13]|0,this.Hh=ce.SHA512_IV[14]|0,this.Hl=ce.SHA512_IV[15]|0}get(){const{Ah:e,Al:r,Bh:n,Bl:s,Ch:i,Cl:a,Dh:o,Dl:c,Eh:u,El:l,Fh:f,Fl:p,Gh:d,Gl:b,Hh:g,Hl:A}=this;return[e,r,n,s,i,a,o,c,u,l,f,p,d,b,g,A]}set(e,r,n,s,i,a,o,c,u,l,f,p,d,b,g,A){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=s|0,this.Ch=i|0,this.Cl=a|0,this.Dh=o|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=p|0,this.Gh=d|0,this.Gl=b|0,this.Hh=g|0,this.Hl=A|0}process(e,r){for(let v=0;v<16;v++,r+=4)zn[v]=e.getUint32(r),Vn[v]=e.getUint32(r+=4);for(let v=16;v<80;v++){const w=zn[v-15]|0,x=Vn[v-15]|0,_=ye.rotrSH(w,x,1)^ye.rotrSH(w,x,8)^ye.shrSH(w,x,7),I=ye.rotrSL(w,x,1)^ye.rotrSL(w,x,8)^ye.shrSL(w,x,7),N=zn[v-2]|0,C=Vn[v-2]|0,j=ye.rotrSH(N,C,19)^ye.rotrBH(N,C,61)^ye.shrSH(N,C,6),M=ye.rotrSL(N,C,19)^ye.rotrBL(N,C,61)^ye.shrSL(N,C,6),H=ye.add4L(I,M,Vn[v-7],Vn[v-16]),V=ye.add4H(H,_,j,zn[v-7],zn[v-16]);zn[v]=V|0,Vn[v]=H|0}let{Ah:n,Al:s,Bh:i,Bl:a,Ch:o,Cl:c,Dh:u,Dl:l,Eh:f,El:p,Fh:d,Fl:b,Gh:g,Gl:A,Hh:S,Hl:T}=this;for(let v=0;v<80;v++){const w=ye.rotrSH(f,p,14)^ye.rotrSH(f,p,18)^ye.rotrBH(f,p,41),x=ye.rotrSL(f,p,14)^ye.rotrSL(f,p,18)^ye.rotrBL(f,p,41),_=f&d^~f&g,I=p&b^~p&A,N=ye.add5L(T,x,I,Bv[v],Vn[v]),C=ye.add5H(N,S,w,_,Ov[v],zn[v]),j=N|0,M=ye.rotrSH(n,s,28)^ye.rotrBH(n,s,34)^ye.rotrBH(n,s,39),H=ye.rotrSL(n,s,28)^ye.rotrBL(n,s,34)^ye.rotrBL(n,s,39),V=n&i^n&o^i&o,Q=s&a^s&c^a&c;S=g|0,T=A|0,g=d|0,A=b|0,d=f|0,b=p|0,{h:f,l:p}=ye.add(u|0,l|0,C|0,j|0),u=o|0,l=c|0,o=i|0,c=a|0,i=n|0,a=s|0;const U=ye.add3L(j,H,Q);n=ye.add3H(U,C,M,V),s=U|0}({h:n,l:s}=ye.add(this.Ah|0,this.Al|0,n|0,s|0)),{h:i,l:a}=ye.add(this.Bh|0,this.Bl|0,i|0,a|0),{h:o,l:c}=ye.add(this.Ch|0,this.Cl|0,o|0,c|0),{h:u,l}=ye.add(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:p}=ye.add(this.Eh|0,this.El|0,f|0,p|0),{h:d,l:b}=ye.add(this.Fh|0,this.Fl|0,d|0,b|0),{h:g,l:A}=ye.add(this.Gh|0,this.Gl|0,g|0,A|0),{h:S,l:T}=ye.add(this.Hh|0,this.Hl|0,S|0,T|0),this.set(n,s,i,a,o,c,u,l,f,p,d,b,g,A,S,T)}roundClean(){(0,Ze.clean)(zn,Vn)}destroy(){(0,Ze.clean)(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}Ue.SHA512=Ao;class _b extends Ao{constructor(){super(48),this.Ah=ce.SHA384_IV[0]|0,this.Al=ce.SHA384_IV[1]|0,this.Bh=ce.SHA384_IV[2]|0,this.Bl=ce.SHA384_IV[3]|0,this.Ch=ce.SHA384_IV[4]|0,this.Cl=ce.SHA384_IV[5]|0,this.Dh=ce.SHA384_IV[6]|0,this.Dl=ce.SHA384_IV[7]|0,this.Eh=ce.SHA384_IV[8]|0,this.El=ce.SHA384_IV[9]|0,this.Fh=ce.SHA384_IV[10]|0,this.Fl=ce.SHA384_IV[11]|0,this.Gh=ce.SHA384_IV[12]|0,this.Gl=ce.SHA384_IV[13]|0,this.Hh=ce.SHA384_IV[14]|0,this.Hl=ce.SHA384_IV[15]|0}}Ue.SHA384=_b;const gt=Uint32Array.from([2352822216,424955298,1944164710,2312950998,502970286,855612546,1738396948,1479516111,258812777,2077511080,2011393907,79989058,1067287976,1780299464,286451373,2446758561]),wt=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class Ib extends Ao{constructor(){super(28),this.Ah=gt[0]|0,this.Al=gt[1]|0,this.Bh=gt[2]|0,this.Bl=gt[3]|0,this.Ch=gt[4]|0,this.Cl=gt[5]|0,this.Dh=gt[6]|0,this.Dl=gt[7]|0,this.Eh=gt[8]|0,this.El=gt[9]|0,this.Fh=gt[10]|0,this.Fl=gt[11]|0,this.Gh=gt[12]|0,this.Gl=gt[13]|0,this.Hh=gt[14]|0,this.Hl=gt[15]|0}}Ue.SHA512_224=Ib;class Pb extends Ao{constructor(){super(32),this.Ah=wt[0]|0,this.Al=wt[1]|0,this.Bh=wt[2]|0,this.Bl=wt[3]|0,this.Ch=wt[4]|0,this.Cl=wt[5]|0,this.Dh=wt[6]|0,this.Dl=wt[7]|0,this.Eh=wt[8]|0,this.El=wt[9]|0,this.Fh=wt[10]|0,this.Fl=wt[11]|0,this.Gh=wt[12]|0,this.Gl=wt[13]|0,this.Hh=wt[14]|0,this.Hl=wt[15]|0}}Ue.SHA512_256=Pb;Ue.sha256=(0,Ze.createHasher)(()=>new ah);Ue.sha224=(0,Ze.createHasher)(()=>new kb);Ue.sha512=(0,Ze.createHasher)(()=>new Ao);Ue.sha384=(0,Ze.createHasher)(()=>new _b);Ue.sha512_256=(0,Ze.createHasher)(()=>new Pb);Ue.sha512_224=(0,Ze.createHasher)(()=>new Ib);Object.defineProperty(Ir,"__esModule",{value:!0});Ir.sha224=Ir.SHA224=Ir.sha256=Ir.SHA256=void 0;const Xc=Ue;Ir.SHA256=Xc.SHA256;Ir.sha256=Xc.sha256;Ir.SHA224=Xc.SHA224;Ir.sha224=Xc.sha224;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.taggedHash=t.TAGGED_HASH_PREFIXES=t.TAGS=t.hash256=t.hash160=t.sha256=t.sha1=t.ripemd160=void 0;const e=ji,r=Hi,n=Ir;function s(l){return Buffer.from((0,e.ripemd160)(Uint8Array.from(l)))}t.ripemd160=s;function i(l){return Buffer.from((0,r.sha1)(Uint8Array.from(l)))}t.sha1=i;function a(l){return Buffer.from((0,n.sha256)(Uint8Array.from(l)))}t.sha256=a;function o(l){return Buffer.from((0,e.ripemd160)((0,n.sha256)(Uint8Array.from(l))))}t.hash160=o;function c(l){return Buffer.from((0,n.sha256)((0,n.sha256)(Uint8Array.from(l))))}t.hash256=c,t.TAGS=["BIP0340/challenge","BIP0340/aux","BIP0340/nonce","TapLeaf","TapBranch","TapSighash","TapTweak","KeyAgg list","KeyAgg coefficient"],t.TAGGED_HASH_PREFIXES={"BIP0340/challenge":Buffer.from([123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124,123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124]),"BIP0340/aux":Buffer.from([241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144,241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144]),"BIP0340/nonce":Buffer.from([7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47,7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47]),TapLeaf:Buffer.from([174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238,174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238]),TapBranch:Buffer.from([25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21,25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21]),TapSighash:Buffer.from([244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49,244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49]),TapTweak:Buffer.from([232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233,232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233]),"KeyAgg list":Buffer.from([72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240,72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240]),"KeyAgg coefficient":Buffer.from([191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129,191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129])};function u(l,f){return a(Buffer.concat([t.TAGGED_HASH_PREFIXES[l],f]))}t.taggedHash=u})(ws);var Vu={},_n={};Object.defineProperty(_n,"__esModule",{value:!0});_n.encode=_n.decode=_n.check=void 0;function Cv(t){if(t.length<8||t.length>72||t[0]!==48||t[1]!==t.length-2||t[2]!==2)return!1;const e=t[3];if(e===0||5+e>=t.length||t[4+e]!==2)return!1;const r=t[5+e];return!(r===0||6+e+r!==t.length||t[4]&128||e>1&&t[4]===0&&!(t[5]&128)||t[e+6]&128||r>1&&t[e+6]===0&&!(t[e+7]&128))}_n.check=Cv;function Rv(t){if(t.length<8)throw new Error("DER sequence length is too short");if(t.length>72)throw new Error("DER sequence length is too long");if(t[0]!==48)throw new Error("Expected DER sequence");if(t[1]!==t.length-2)throw new Error("DER sequence length is invalid");if(t[2]!==2)throw new Error("Expected DER integer");const e=t[3];if(e===0)throw new Error("R length is zero");if(5+e>=t.length)throw new Error("R length is too long");if(t[4+e]!==2)throw new Error("Expected DER integer (2)");const r=t[5+e];if(r===0)throw new Error("S length is zero");if(6+e+r!==t.length)throw new Error("S length is invalid");if(t[4]&128)throw new Error("R value is negative");if(e>1&&t[4]===0&&!(t[5]&128))throw new Error("R value excessively padded");if(t[e+6]&128)throw new Error("S value is negative");if(r>1&&t[e+6]===0&&!(t[e+7]&128))throw new Error("S value excessively padded");return{r:t.slice(4,4+e),s:t.slice(6+e)}}_n.decode=Rv;function Nv(t,e){const r=t.length,n=e.length;if(r===0)throw new Error("R length is zero");if(n===0)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(t[0]&128)throw new Error("R value is negative");if(e[0]&128)throw new Error("S value is negative");if(r>1&&t[0]===0&&!(t[1]&128))throw new Error("R value excessively padded");if(n>1&&e[0]===0&&!(e[1]&128))throw new Error("S value excessively padded");const s=Buffer.allocUnsafe(6+r+n);return s[0]=48,s[1]=s.length-2,s[2]=2,s[3]=t.length,t.copy(s,4),s[4+r]=2,s[5+r]=e.length,e.copy(s,6+r),s}_n.encode=Nv;var qs={};Object.defineProperty(qs,"__esModule",{value:!0});qs.REVERSE_OPS=qs.OPS=void 0;const Kf={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP3:178,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_CHECKSIGADD:186,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255};qs.OPS=Kf;const Ob={};qs.REVERSE_OPS=Ob;for(const t of Object.keys(Kf)){const e=Kf[t];Ob[e]=t}var ls={};Object.defineProperty(ls,"__esModule",{value:!0});ls.decode=ls.encode=ls.encodingLength=void 0;const as=qs;function Bb(t){return t<as.OPS.OP_PUSHDATA1?1:t<=255?2:t<=65535?3:5}ls.encodingLength=Bb;function Uv(t,e,r){const n=Bb(e);return n===1?t.writeUInt8(e,r):n===2?(t.writeUInt8(as.OPS.OP_PUSHDATA1,r),t.writeUInt8(e,r+1)):n===3?(t.writeUInt8(as.OPS.OP_PUSHDATA2,r),t.writeUInt16LE(e,r+1)):(t.writeUInt8(as.OPS.OP_PUSHDATA4,r),t.writeUInt32LE(e,r+1)),n}ls.encode=Uv;function Fv(t,e){const r=t.readUInt8(e);let n,s;if(r<as.OPS.OP_PUSHDATA1)n=r,s=1;else if(r===as.OPS.OP_PUSHDATA1){if(e+2>t.length)return null;n=t.readUInt8(e+1),s=2}else if(r===as.OPS.OP_PUSHDATA2){if(e+3>t.length)return null;n=t.readUInt16LE(e+1),s=3}else{if(e+5>t.length)return null;if(r!==as.OPS.OP_PUSHDATA4)throw new Error("Unexpected opcode");n=t.readUInt32LE(e+1),s=5}return{opcode:r,number:n,size:s}}ls.decode=Fv;var Li={};Object.defineProperty(Li,"__esModule",{value:!0});Li.encode=Li.decode=void 0;function Mv(t,e,r){e=e||4,r=r===void 0?!0:r;const n=t.length;if(n===0)return 0;if(n>e)throw new TypeError("Script number overflow");if(r&&!(t[n-1]&127)&&(n<=1||!(t[n-2]&128)))throw new Error("Non-minimally encoded script number");if(n===5){const i=t.readUInt32LE(0),a=t.readUInt8(4);return a&128?-((a&-129)*4294967296+i):a*4294967296+i}let s=0;for(let i=0;i<n;++i)s|=t[i]<<8*i;return t[n-1]&128?-(s&~(128<<8*(n-1))):s}Li.decode=Mv;function $v(t){return t>2147483647?5:t>8388607?4:t>32767?3:t>127?2:t>0?1:0}function jv(t){let e=Math.abs(t);const r=$v(e),n=Buffer.allocUnsafe(r),s=t<0;for(let i=0;i<r;++i)n.writeUInt8(e&255,i),e>>=8;return n[r-1]&128?n.writeUInt8(s?128:0,r-1):s&&(n[r-1]|=128),n}Li.encode=jv;var _s={},G0;function Hv(){if(G0)return _s;G0=1,Object.defineProperty(_s,"__esModule",{value:!0}),_s.encode=_s.decode=void 0;const t=_n,e=ar(),r=kt,{typeforce:n}=r,s=Buffer.alloc(1,0);function i(u){let l=0;for(;u[l]===0;)++l;return l===u.length?s:(u=u.slice(l),u[0]&128?Buffer.concat([s,u],1+u.length):u)}function a(u){u[0]===0&&(u=u.slice(1));const l=Buffer.alloc(32,0),f=Math.max(0,32-u.length);return u.copy(l,f),l}function o(u){const l=u.readUInt8(u.length-1);if(!(0,e.isDefinedHashType)(l))throw new Error("Invalid hashType "+l);const f=t.decode(u.slice(0,-1)),p=a(f.r),d=a(f.s);return{signature:Buffer.concat([p,d],64),hashType:l}}_s.decode=o;function c(u,l){if(n({signature:r.BufferN(64),hashType:r.UInt8},{signature:u,hashType:l}),!(0,e.isDefinedHashType)(l))throw new Error("Invalid hashType "+l);const f=Buffer.allocUnsafe(1);f.writeUInt8(l,0);const p=i(u.slice(0,32)),d=i(u.slice(32,64));return Buffer.concat([t.encode(p,d),f])}return _s.encode=c,_s}var q0;function ar(){return q0||(q0=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.signature=t.number=t.isCanonicalScriptSignature=t.isDefinedHashType=t.isCanonicalPubKey=t.toStack=t.fromASM=t.toASM=t.decompile=t.compile=t.countNonPushOnlyOPs=t.isPushOnly=t.OPS=void 0;const e=_n,r=qs;Object.defineProperty(t,"OPS",{enumerable:!0,get:function(){return r.OPS}});const n=ls,s=Li,i=Hv(),a=kt,{typeforce:o}=a,c=r.OPS.OP_RESERVED;function u(C){return a.Number(C)&&(C===r.OPS.OP_0||C>=r.OPS.OP_1&&C<=r.OPS.OP_16||C===r.OPS.OP_1NEGATE)}function l(C){return a.Buffer(C)||u(C)}function f(C){return a.Array(C)&&C.every(l)}t.isPushOnly=f;function p(C){return C.length-C.filter(l).length}t.countNonPushOnlyOPs=p;function d(C){if(C.length===0)return r.OPS.OP_0;if(C.length===1){if(C[0]>=1&&C[0]<=16)return c+C[0];if(C[0]===129)return r.OPS.OP_1NEGATE}}function b(C){return Buffer.isBuffer(C)}function g(C){return a.Array(C)}function A(C){return Buffer.isBuffer(C)}function S(C){if(b(C))return C;o(a.Array,C);const j=C.reduce((V,Q)=>A(Q)?Q.length===1&&d(Q)!==void 0?V+1:V+n.encodingLength(Q.length)+Q.length:V+1,0),M=Buffer.allocUnsafe(j);let H=0;if(C.forEach(V=>{if(A(V)){const Q=d(V);if(Q!==void 0){M.writeUInt8(Q,H),H+=1;return}H+=n.encode(M,V.length,H),V.copy(M,H),H+=V.length}else M.writeUInt8(V,H),H+=1}),H!==M.length)throw new Error("Could not decode chunks");return M}t.compile=S;function T(C){if(g(C))return C;o(a.Buffer,C);const j=[];let M=0;for(;M<C.length;){const H=C[M];if(H>r.OPS.OP_0&&H<=r.OPS.OP_PUSHDATA4){const V=n.decode(C,M);if(V===null||(M+=V.size,M+V.number>C.length))return null;const Q=C.slice(M,M+V.number);M+=V.number;const U=d(Q);U!==void 0?j.push(U):j.push(Q)}else j.push(H),M+=1}return j}t.decompile=T;function v(C){if(b(C)&&(C=T(C)),!C)throw new Error("Could not convert invalid chunks to ASM");return C.map(j=>{if(A(j)){const M=d(j);if(M===void 0)return j.toString("hex");j=M}return r.REVERSE_OPS[j]}).join(" ")}t.toASM=v;function w(C){return o(a.String,C),S(C.split(" ").map(j=>r.OPS[j]!==void 0?r.OPS[j]:(o(a.Hex,j),Buffer.from(j,"hex"))))}t.fromASM=w;function x(C){return C=T(C),o(f,C),C.map(j=>A(j)?j:j===r.OPS.OP_0?Buffer.allocUnsafe(0):s.encode(j-c))}t.toStack=x;function _(C){return a.isPoint(C)}t.isCanonicalPubKey=_;function I(C){const j=C&-129;return j>0&&j<4}t.isDefinedHashType=I;function N(C){return!Buffer.isBuffer(C)||!I(C[C.length-1])?!1:e.check(C.slice(0,-1))}t.isCanonicalScriptSignature=N,t.number=s,t.signature=i}(Vu)),Vu}Object.defineProperty(Eo,"__esModule",{value:!0});Eo.Transaction=void 0;const Je=pt,Pt=ws,W0=ar(),Lv=ar(),Ae=kt,{typeforce:zr}=Ae;function Xr(t){const e=t.length;return Je.varuint.encodingLength(e)+e}function Dv(t){const e=t.length;return Je.varuint.encodingLength(e)+t.reduce((r,n)=>r+Xr(n),0)}const Zn=Buffer.allocUnsafe(0),Gu=[],qu=Buffer.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),K0=Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),zv=Buffer.from("ffffffffffffffff","hex"),Vv={script:Zn,valueBuffer:zv};function Gv(t){return t.value!==void 0}let Mr=class Pe{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(e,r){const n=new Je.BufferReader(e),s=new Pe;s.version=n.readInt32();const i=n.readUInt8(),a=n.readUInt8();let o=!1;i===Pe.ADVANCED_TRANSACTION_MARKER&&a===Pe.ADVANCED_TRANSACTION_FLAG?o=!0:n.offset-=2;const c=n.readVarInt();for(let l=0;l<c;++l)s.ins.push({hash:n.readSlice(32),index:n.readUInt32(),script:n.readVarSlice(),sequence:n.readUInt32(),witness:Gu});const u=n.readVarInt();for(let l=0;l<u;++l)s.outs.push({value:n.readUInt64(),script:n.readVarSlice()});if(o){for(let l=0;l<c;++l)s.ins[l].witness=n.readVector();if(!s.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(s.locktime=n.readUInt32(),r)return s;if(n.offset!==e.length)throw new Error("Transaction has unexpected data");return s}static fromHex(e){return Pe.fromBuffer(Buffer.from(e,"hex"),!1)}static isCoinbaseHash(e){zr(Ae.Hash256bit,e);for(let r=0;r<32;++r)if(e[r]!==0)return!1;return!0}isCoinbase(){return this.ins.length===1&&Pe.isCoinbaseHash(this.ins[0].hash)}addInput(e,r,n,s){return zr(Ae.tuple(Ae.Hash256bit,Ae.UInt32,Ae.maybe(Ae.UInt32),Ae.maybe(Ae.Buffer)),arguments),Ae.Null(n)&&(n=Pe.DEFAULT_SEQUENCE),this.ins.push({hash:e,index:r,script:s||Zn,sequence:n,witness:Gu})-1}addOutput(e,r){return zr(Ae.tuple(Ae.Buffer,Ae.Satoshi),arguments),this.outs.push({script:e,value:r})-1}hasWitnesses(){return this.ins.some(e=>e.witness.length!==0)}stripWitnesses(){this.ins.forEach(e=>{e.witness=Gu})}weight(){const e=this.byteLength(!1),r=this.byteLength(!0);return e*3+r}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(e=!0){const r=e&&this.hasWitnesses();return(r?10:8)+Je.varuint.encodingLength(this.ins.length)+Je.varuint.encodingLength(this.outs.length)+this.ins.reduce((n,s)=>n+40+Xr(s.script),0)+this.outs.reduce((n,s)=>n+8+Xr(s.script),0)+(r?this.ins.reduce((n,s)=>n+Dv(s.witness),0):0)}clone(){const e=new Pe;return e.version=this.version,e.locktime=this.locktime,e.ins=this.ins.map(r=>({hash:r.hash,index:r.index,script:r.script,sequence:r.sequence,witness:r.witness})),e.outs=this.outs.map(r=>({script:r.script,value:r.value})),e}hashForSignature(e,r,n){if(zr(Ae.tuple(Ae.UInt32,Ae.Buffer,Ae.Number),arguments),e>=this.ins.length)return K0;const s=W0.compile(W0.decompile(r).filter(o=>o!==Lv.OPS.OP_CODESEPARATOR)),i=this.clone();if((n&31)===Pe.SIGHASH_NONE)i.outs=[],i.ins.forEach((o,c)=>{c!==e&&(o.sequence=0)});else if((n&31)===Pe.SIGHASH_SINGLE){if(e>=this.outs.length)return K0;i.outs.length=e+1;for(let o=0;o<e;o++)i.outs[o]=Vv;i.ins.forEach((o,c)=>{c!==e&&(o.sequence=0)})}n&Pe.SIGHASH_ANYONECANPAY?(i.ins=[i.ins[e]],i.ins[0].script=s):(i.ins.forEach(o=>{o.script=Zn}),i.ins[e].script=s);const a=Buffer.allocUnsafe(i.byteLength(!1)+4);return a.writeInt32LE(n,a.length-4),i.__toBuffer(a,0,!1),Pt.hash256(a)}hashForWitnessV1(e,r,n,s,i,a){if(zr(Ae.tuple(Ae.UInt32,zr.arrayOf(Ae.Buffer),zr.arrayOf(Ae.Satoshi),Ae.UInt32),arguments),n.length!==this.ins.length||r.length!==this.ins.length)throw new Error("Must supply prevout script and value for all inputs");const o=s===Pe.SIGHASH_DEFAULT?Pe.SIGHASH_ALL:s&Pe.SIGHASH_OUTPUT_MASK,u=(s&Pe.SIGHASH_INPUT_MASK)===Pe.SIGHASH_ANYONECANPAY,l=o===Pe.SIGHASH_NONE,f=o===Pe.SIGHASH_SINGLE;let p=Zn,d=Zn,b=Zn,g=Zn,A=Zn;if(!u){let w=Je.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(x=>{w.writeSlice(x.hash),w.writeUInt32(x.index)}),p=Pt.sha256(w.end()),w=Je.BufferWriter.withCapacity(8*this.ins.length),n.forEach(x=>w.writeUInt64(x)),d=Pt.sha256(w.end()),w=Je.BufferWriter.withCapacity(r.map(Xr).reduce((x,_)=>x+_)),r.forEach(x=>w.writeVarSlice(x)),b=Pt.sha256(w.end()),w=Je.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(x=>w.writeUInt32(x.sequence)),g=Pt.sha256(w.end())}if(l||f){if(f&&e<this.outs.length){const w=this.outs[e],x=Je.BufferWriter.withCapacity(8+Xr(w.script));x.writeUInt64(w.value),x.writeVarSlice(w.script),A=Pt.sha256(x.end())}}else{const w=this.outs.map(_=>8+Xr(_.script)).reduce((_,I)=>_+I),x=Je.BufferWriter.withCapacity(w);this.outs.forEach(_=>{x.writeUInt64(_.value),x.writeVarSlice(_.script)}),A=Pt.sha256(x.end())}const S=(i?2:0)+(a?1:0),T=174-(u?49:0)-(l?32:0)+(a?32:0)+(i?37:0),v=Je.BufferWriter.withCapacity(T);if(v.writeUInt8(s),v.writeInt32(this.version),v.writeUInt32(this.locktime),v.writeSlice(p),v.writeSlice(d),v.writeSlice(b),v.writeSlice(g),l||f||v.writeSlice(A),v.writeUInt8(S),u){const w=this.ins[e];v.writeSlice(w.hash),v.writeUInt32(w.index),v.writeUInt64(n[e]),v.writeVarSlice(r[e]),v.writeUInt32(w.sequence)}else v.writeUInt32(e);if(a){const w=Je.BufferWriter.withCapacity(Xr(a));w.writeVarSlice(a),v.writeSlice(Pt.sha256(w.end()))}return f&&v.writeSlice(A),i&&(v.writeSlice(i),v.writeUInt8(0),v.writeUInt32(4294967295)),Pt.taggedHash("TapSighash",Buffer.concat([Buffer.from([0]),v.end()]))}hashForWitnessV0(e,r,n,s){zr(Ae.tuple(Ae.UInt32,Ae.Buffer,Ae.Satoshi,Ae.UInt32),arguments);let i=Buffer.from([]),a,o=qu,c=qu,u=qu;if(s&Pe.SIGHASH_ANYONECANPAY||(i=Buffer.allocUnsafe(36*this.ins.length),a=new Je.BufferWriter(i,0),this.ins.forEach(f=>{a.writeSlice(f.hash),a.writeUInt32(f.index)}),c=Pt.hash256(i)),!(s&Pe.SIGHASH_ANYONECANPAY)&&(s&31)!==Pe.SIGHASH_SINGLE&&(s&31)!==Pe.SIGHASH_NONE&&(i=Buffer.allocUnsafe(4*this.ins.length),a=new Je.BufferWriter(i,0),this.ins.forEach(f=>{a.writeUInt32(f.sequence)}),u=Pt.hash256(i)),(s&31)!==Pe.SIGHASH_SINGLE&&(s&31)!==Pe.SIGHASH_NONE){const f=this.outs.reduce((p,d)=>p+8+Xr(d.script),0);i=Buffer.allocUnsafe(f),a=new Je.BufferWriter(i,0),this.outs.forEach(p=>{a.writeUInt64(p.value),a.writeVarSlice(p.script)}),o=Pt.hash256(i)}else if((s&31)===Pe.SIGHASH_SINGLE&&e<this.outs.length){const f=this.outs[e];i=Buffer.allocUnsafe(8+Xr(f.script)),a=new Je.BufferWriter(i,0),a.writeUInt64(f.value),a.writeVarSlice(f.script),o=Pt.hash256(i)}i=Buffer.allocUnsafe(156+Xr(r)),a=new Je.BufferWriter(i,0);const l=this.ins[e];return a.writeInt32(this.version),a.writeSlice(c),a.writeSlice(u),a.writeSlice(l.hash),a.writeUInt32(l.index),a.writeVarSlice(r),a.writeUInt64(n),a.writeUInt32(l.sequence),a.writeSlice(o),a.writeUInt32(this.locktime),a.writeUInt32(s),Pt.hash256(i)}getHash(e){return e&&this.isCoinbase()?Buffer.alloc(32,0):Pt.hash256(this.__toBuffer(void 0,void 0,e))}getId(){return(0,Je.reverseBuffer)(this.getHash(!1)).toString("hex")}toBuffer(e,r){return this.__toBuffer(e,r,!0)}toHex(){return this.toBuffer(void 0,void 0).toString("hex")}setInputScript(e,r){zr(Ae.tuple(Ae.Number,Ae.Buffer),arguments),this.ins[e].script=r}setWitness(e,r){zr(Ae.tuple(Ae.Number,[Ae.Buffer]),arguments),this.ins[e].witness=r}__toBuffer(e,r,n=!1){e||(e=Buffer.allocUnsafe(this.byteLength(n)));const s=new Je.BufferWriter(e,r||0);s.writeInt32(this.version);const i=n&&this.hasWitnesses();return i&&(s.writeUInt8(Pe.ADVANCED_TRANSACTION_MARKER),s.writeUInt8(Pe.ADVANCED_TRANSACTION_FLAG)),s.writeVarInt(this.ins.length),this.ins.forEach(a=>{s.writeSlice(a.hash),s.writeUInt32(a.index),s.writeVarSlice(a.script),s.writeUInt32(a.sequence)}),s.writeVarInt(this.outs.length),this.outs.forEach(a=>{Gv(a)?s.writeUInt64(a.value):s.writeSlice(a.valueBuffer),s.writeVarSlice(a.script)}),i&&this.ins.forEach(a=>{s.writeVector(a.witness)}),s.writeUInt32(this.locktime),r!==void 0?e.slice(r,s.offset):e}};Eo.Transaction=Mr;Mr.DEFAULT_SEQUENCE=4294967295;Mr.SIGHASH_DEFAULT=0;Mr.SIGHASH_ALL=1;Mr.SIGHASH_NONE=2;Mr.SIGHASH_SINGLE=3;Mr.SIGHASH_ANYONECANPAY=128;Mr.SIGHASH_OUTPUT_MASK=3;Mr.SIGHASH_INPUT_MASK=128;Mr.ADVANCED_TRANSACTION_MARKER=0;Mr.ADVANCED_TRANSACTION_FLAG=1;var Be={},So={};Object.defineProperty(So,"__esModule",{value:!0});const qv=9007199254740991;function oh(t){if(t<0||t>qv||t%1!==0)throw new RangeError("value out of range")}function wa(t,e,r){if(oh(t),e||(e=Buffer.allocUnsafe(Cb(t))),!Buffer.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");return r||(r=0),t<253?(e.writeUInt8(t,r),Object.assign(wa,{bytes:1})):t<=65535?(e.writeUInt8(253,r),e.writeUInt16LE(t,r+1),Object.assign(wa,{bytes:3})):t<=4294967295?(e.writeUInt8(254,r),e.writeUInt32LE(t,r+1),Object.assign(wa,{bytes:5})):(e.writeUInt8(255,r),e.writeUInt32LE(t>>>0,r+1),e.writeUInt32LE(t/4294967296|0,r+5),Object.assign(wa,{bytes:9})),e}So.encode=wa;function va(t,e){if(!Buffer.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");e||(e=0);const r=t.readUInt8(e);if(r<253)return Object.assign(va,{bytes:1}),r;if(r===253)return Object.assign(va,{bytes:3}),t.readUInt16LE(e+1);if(r===254)return Object.assign(va,{bytes:5}),t.readUInt32LE(e+1);{Object.assign(va,{bytes:9});const n=t.readUInt32LE(e+1),i=t.readUInt32LE(e+5)*4294967296+n;return oh(i),i}}So.decode=va;function Cb(t){return oh(t),t<253?1:t<=65535?3:t<=4294967295?5:9}So.encodingLength=Cb;var Wu={},Yc={},xt={};Object.defineProperty(xt,"__esModule",{value:!0});xt.testnet=xt.regtest=xt.bitcoin=void 0;xt.bitcoin={messagePrefix:`Bitcoin Signed Message:
6
+ */(function(t){const e=Kc,r=rh,n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=o,t.SlowBuffer=T,t.INSPECT_MAX_BYTES=50;const s=2147483647;t.kMaxLength=s,o.TYPED_ARRAY_SUPPORT=i(),!o.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function i(){try{const E=new Uint8Array(1),h={foo:function(){return 42}};return Object.setPrototypeOf(h,Uint8Array.prototype),Object.setPrototypeOf(E,h),E.foo()===42}catch{return!1}}Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}});function a(E){if(E>s)throw new RangeError('The value "'+E+'" is invalid for option "size"');const h=new Uint8Array(E);return Object.setPrototypeOf(h,o.prototype),h}function o(E,h,y){if(typeof E=="number"){if(typeof h=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return f(E)}return c(E,h,y)}o.poolSize=8192;function c(E,h,y){if(typeof E=="string")return p(E,h);if(ArrayBuffer.isView(E))return b(E);if(E==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof E);if(It(E,ArrayBuffer)||E&&It(E.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(It(E,SharedArrayBuffer)||E&&It(E.buffer,SharedArrayBuffer)))return g(E,h,y);if(typeof E=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const k=E.valueOf&&E.valueOf();if(k!=null&&k!==E)return o.from(k,h,y);const R=A(E);if(R)return R;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof E[Symbol.toPrimitive]=="function")return o.from(E[Symbol.toPrimitive]("string"),h,y);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof E)}o.from=function(E,h,y){return c(E,h,y)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array);function u(E){if(typeof E!="number")throw new TypeError('"size" argument must be of type number');if(E<0)throw new RangeError('The value "'+E+'" is invalid for option "size"')}function l(E,h,y){return u(E),E<=0?a(E):h!==void 0?typeof y=="string"?a(E).fill(h,y):a(E).fill(h):a(E)}o.alloc=function(E,h,y){return l(E,h,y)};function f(E){return u(E),a(E<0?0:S(E)|0)}o.allocUnsafe=function(E){return f(E)},o.allocUnsafeSlow=function(E){return f(E)};function p(E,h){if((typeof h!="string"||h==="")&&(h="utf8"),!o.isEncoding(h))throw new TypeError("Unknown encoding: "+h);const y=v(E,h)|0;let k=a(y);const R=k.write(E,h);return R!==y&&(k=k.slice(0,R)),k}function d(E){const h=E.length<0?0:S(E.length)|0,y=a(h);for(let k=0;k<h;k+=1)y[k]=E[k]&255;return y}function b(E){if(It(E,Uint8Array)){const h=new Uint8Array(E);return g(h.buffer,h.byteOffset,h.byteLength)}return d(E)}function g(E,h,y){if(h<0||E.byteLength<h)throw new RangeError('"offset" is outside of buffer bounds');if(E.byteLength<h+(y||0))throw new RangeError('"length" is outside of buffer bounds');let k;return h===void 0&&y===void 0?k=new Uint8Array(E):y===void 0?k=new Uint8Array(E,h):k=new Uint8Array(E,h,y),Object.setPrototypeOf(k,o.prototype),k}function A(E){if(o.isBuffer(E)){const h=S(E.length)|0,y=a(h);return y.length===0||E.copy(y,0,0,h),y}if(E.length!==void 0)return typeof E.length!="number"||Hn(E.length)?a(0):d(E);if(E.type==="Buffer"&&Array.isArray(E.data))return d(E.data)}function S(E){if(E>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return E|0}function T(E){return+E!=E&&(E=0),o.alloc(+E)}o.isBuffer=function(h){return h!=null&&h._isBuffer===!0&&h!==o.prototype},o.compare=function(h,y){if(It(h,Uint8Array)&&(h=o.from(h,h.offset,h.byteLength)),It(y,Uint8Array)&&(y=o.from(y,y.offset,y.byteLength)),!o.isBuffer(h)||!o.isBuffer(y))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(h===y)return 0;let k=h.length,R=y.length;for(let $=0,W=Math.min(k,R);$<W;++$)if(h[$]!==y[$]){k=h[$],R=y[$];break}return k<R?-1:R<k?1:0},o.isEncoding=function(h){switch(String(h).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(h,y){if(!Array.isArray(h))throw new TypeError('"list" argument must be an Array of Buffers');if(h.length===0)return o.alloc(0);let k;if(y===void 0)for(y=0,k=0;k<h.length;++k)y+=h[k].length;const R=o.allocUnsafe(y);let $=0;for(k=0;k<h.length;++k){let W=h[k];if(It(W,Uint8Array))$+W.length>R.length?(o.isBuffer(W)||(W=o.from(W)),W.copy(R,$)):Uint8Array.prototype.set.call(R,W,$);else if(o.isBuffer(W))W.copy(R,$);else throw new TypeError('"list" argument must be an Array of Buffers');$+=W.length}return R};function v(E,h){if(o.isBuffer(E))return E.length;if(ArrayBuffer.isView(E)||It(E,ArrayBuffer))return E.byteLength;if(typeof E!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof E);const y=E.length,k=arguments.length>2&&arguments[2]===!0;if(!k&&y===0)return 0;let R=!1;for(;;)switch(h){case"ascii":case"latin1":case"binary":return y;case"utf8":case"utf-8":return Hr(E).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return y*2;case"hex":return y>>>1;case"base64":return Lr(E).length;default:if(R)return k?-1:Hr(E).length;h=(""+h).toLowerCase(),R=!0}}o.byteLength=v;function w(E,h,y){let k=!1;if((h===void 0||h<0)&&(h=0),h>this.length||((y===void 0||y>this.length)&&(y=this.length),y<=0)||(y>>>=0,h>>>=0,y<=h))return"";for(E||(E="utf8");;)switch(E){case"hex":return O(this,h,y);case"utf8":case"utf-8":return Q(this,h,y);case"ascii":return ee(this,h,y);case"latin1":case"binary":return q(this,h,y);case"base64":return V(this,h,y);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,h,y);default:if(k)throw new TypeError("Unknown encoding: "+E);E=(E+"").toLowerCase(),k=!0}}o.prototype._isBuffer=!0;function x(E,h,y){const k=E[h];E[h]=E[y],E[y]=k}o.prototype.swap16=function(){const h=this.length;if(h%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let y=0;y<h;y+=2)x(this,y,y+1);return this},o.prototype.swap32=function(){const h=this.length;if(h%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let y=0;y<h;y+=4)x(this,y,y+3),x(this,y+1,y+2);return this},o.prototype.swap64=function(){const h=this.length;if(h%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let y=0;y<h;y+=8)x(this,y,y+7),x(this,y+1,y+6),x(this,y+2,y+5),x(this,y+3,y+4);return this},o.prototype.toString=function(){const h=this.length;return h===0?"":arguments.length===0?Q(this,0,h):w.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(h){if(!o.isBuffer(h))throw new TypeError("Argument must be a Buffer");return this===h?!0:o.compare(this,h)===0},o.prototype.inspect=function(){let h="";const y=t.INSPECT_MAX_BYTES;return h=this.toString("hex",0,y).replace(/(.{2})/g,"$1 ").trim(),this.length>y&&(h+=" ... "),"<Buffer "+h+">"},n&&(o.prototype[n]=o.prototype.inspect),o.prototype.compare=function(h,y,k,R,$){if(It(h,Uint8Array)&&(h=o.from(h,h.offset,h.byteLength)),!o.isBuffer(h))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof h);if(y===void 0&&(y=0),k===void 0&&(k=h?h.length:0),R===void 0&&(R=0),$===void 0&&($=this.length),y<0||k>h.length||R<0||$>this.length)throw new RangeError("out of range index");if(R>=$&&y>=k)return 0;if(R>=$)return-1;if(y>=k)return 1;if(y>>>=0,k>>>=0,R>>>=0,$>>>=0,this===h)return 0;let W=$-R,we=k-y;const qe=Math.min(W,we),je=this.slice(R,$),We=h.slice(y,k);for(let Ie=0;Ie<qe;++Ie)if(je[Ie]!==We[Ie]){W=je[Ie],we=We[Ie];break}return W<we?-1:we<W?1:0};function _(E,h,y,k,R){if(E.length===0)return-1;if(typeof y=="string"?(k=y,y=0):y>2147483647?y=2147483647:y<-2147483648&&(y=-2147483648),y=+y,Hn(y)&&(y=R?0:E.length-1),y<0&&(y=E.length+y),y>=E.length){if(R)return-1;y=E.length-1}else if(y<0)if(R)y=0;else return-1;if(typeof h=="string"&&(h=o.from(h,k)),o.isBuffer(h))return h.length===0?-1:I(E,h,y,k,R);if(typeof h=="number")return h=h&255,typeof Uint8Array.prototype.indexOf=="function"?R?Uint8Array.prototype.indexOf.call(E,h,y):Uint8Array.prototype.lastIndexOf.call(E,h,y):I(E,[h],y,k,R);throw new TypeError("val must be string, number or Buffer")}function I(E,h,y,k,R){let $=1,W=E.length,we=h.length;if(k!==void 0&&(k=String(k).toLowerCase(),k==="ucs2"||k==="ucs-2"||k==="utf16le"||k==="utf-16le")){if(E.length<2||h.length<2)return-1;$=2,W/=2,we/=2,y/=2}function qe(We,Ie){return $===1?We[Ie]:We.readUInt16BE(Ie*$)}let je;if(R){let We=-1;for(je=y;je<W;je++)if(qe(E,je)===qe(h,We===-1?0:je-We)){if(We===-1&&(We=je),je-We+1===we)return We*$}else We!==-1&&(je-=je-We),We=-1}else for(y+we>W&&(y=W-we),je=y;je>=0;je--){let We=!0;for(let Ie=0;Ie<we;Ie++)if(qe(E,je+Ie)!==qe(h,Ie)){We=!1;break}if(We)return je}return-1}o.prototype.includes=function(h,y,k){return this.indexOf(h,y,k)!==-1},o.prototype.indexOf=function(h,y,k){return _(this,h,y,k,!0)},o.prototype.lastIndexOf=function(h,y,k){return _(this,h,y,k,!1)};function N(E,h,y,k){y=Number(y)||0;const R=E.length-y;k?(k=Number(k),k>R&&(k=R)):k=R;const $=h.length;k>$/2&&(k=$/2);let W;for(W=0;W<k;++W){const we=parseInt(h.substr(W*2,2),16);if(Hn(we))return W;E[y+W]=we}return W}function C(E,h,y,k){return _t(Hr(h,E.length-y),E,y,k)}function j(E,h,y,k){return _t(ks(h),E,y,k)}function M(E,h,y,k){return _t(Lr(h),E,y,k)}function H(E,h,y,k){return _t(X(h,E.length-y),E,y,k)}o.prototype.write=function(h,y,k,R){if(y===void 0)R="utf8",k=this.length,y=0;else if(k===void 0&&typeof y=="string")R=y,k=this.length,y=0;else if(isFinite(y))y=y>>>0,isFinite(k)?(k=k>>>0,R===void 0&&(R="utf8")):(R=k,k=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const $=this.length-y;if((k===void 0||k>$)&&(k=$),h.length>0&&(k<0||y<0)||y>this.length)throw new RangeError("Attempt to write outside buffer bounds");R||(R="utf8");let W=!1;for(;;)switch(R){case"hex":return N(this,h,y,k);case"utf8":case"utf-8":return C(this,h,y,k);case"ascii":case"latin1":case"binary":return j(this,h,y,k);case"base64":return M(this,h,y,k);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return H(this,h,y,k);default:if(W)throw new TypeError("Unknown encoding: "+R);R=(""+R).toLowerCase(),W=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function V(E,h,y){return h===0&&y===E.length?e.fromByteArray(E):e.fromByteArray(E.slice(h,y))}function Q(E,h,y){y=Math.min(E.length,y);const k=[];let R=h;for(;R<y;){const $=E[R];let W=null,we=$>239?4:$>223?3:$>191?2:1;if(R+we<=y){let qe,je,We,Ie;switch(we){case 1:$<128&&(W=$);break;case 2:qe=E[R+1],(qe&192)===128&&(Ie=($&31)<<6|qe&63,Ie>127&&(W=Ie));break;case 3:qe=E[R+1],je=E[R+2],(qe&192)===128&&(je&192)===128&&(Ie=($&15)<<12|(qe&63)<<6|je&63,Ie>2047&&(Ie<55296||Ie>57343)&&(W=Ie));break;case 4:qe=E[R+1],je=E[R+2],We=E[R+3],(qe&192)===128&&(je&192)===128&&(We&192)===128&&(Ie=($&15)<<18|(qe&63)<<12|(je&63)<<6|We&63,Ie>65535&&Ie<1114112&&(W=Ie))}}W===null?(W=65533,we=1):W>65535&&(W-=65536,k.push(W>>>10&1023|55296),W=56320|W&1023),k.push(W),R+=we}return K(k)}const U=4096;function K(E){const h=E.length;if(h<=U)return String.fromCharCode.apply(String,E);let y="",k=0;for(;k<h;)y+=String.fromCharCode.apply(String,E.slice(k,k+=U));return y}function ee(E,h,y){let k="";y=Math.min(E.length,y);for(let R=h;R<y;++R)k+=String.fromCharCode(E[R]&127);return k}function q(E,h,y){let k="";y=Math.min(E.length,y);for(let R=h;R<y;++R)k+=String.fromCharCode(E[R]);return k}function O(E,h,y){const k=E.length;(!h||h<0)&&(h=0),(!y||y<0||y>k)&&(y=k);let R="";for(let $=h;$<y;++$)R+=di[E[$]];return R}function L(E,h,y){const k=E.slice(h,y);let R="";for(let $=0;$<k.length-1;$+=2)R+=String.fromCharCode(k[$]+k[$+1]*256);return R}o.prototype.slice=function(h,y){const k=this.length;h=~~h,y=y===void 0?k:~~y,h<0?(h+=k,h<0&&(h=0)):h>k&&(h=k),y<0?(y+=k,y<0&&(y=0)):y>k&&(y=k),y<h&&(y=h);const R=this.subarray(h,y);return Object.setPrototypeOf(R,o.prototype),R};function J(E,h,y){if(E%1!==0||E<0)throw new RangeError("offset is not uint");if(E+h>y)throw new RangeError("Trying to access beyond buffer length")}o.prototype.readUintLE=o.prototype.readUIntLE=function(h,y,k){h=h>>>0,y=y>>>0,k||J(h,y,this.length);let R=this[h],$=1,W=0;for(;++W<y&&($*=256);)R+=this[h+W]*$;return R},o.prototype.readUintBE=o.prototype.readUIntBE=function(h,y,k){h=h>>>0,y=y>>>0,k||J(h,y,this.length);let R=this[h+--y],$=1;for(;y>0&&($*=256);)R+=this[h+--y]*$;return R},o.prototype.readUint8=o.prototype.readUInt8=function(h,y){return h=h>>>0,y||J(h,1,this.length),this[h]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(h,y){return h=h>>>0,y||J(h,2,this.length),this[h]|this[h+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(h,y){return h=h>>>0,y||J(h,2,this.length),this[h]<<8|this[h+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(h,y){return h=h>>>0,y||J(h,4,this.length),(this[h]|this[h+1]<<8|this[h+2]<<16)+this[h+3]*16777216},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(h,y){return h=h>>>0,y||J(h,4,this.length),this[h]*16777216+(this[h+1]<<16|this[h+2]<<8|this[h+3])},o.prototype.readBigUInt64LE=Ln(function(h){h=h>>>0,Ee(h,"offset");const y=this[h],k=this[h+7];(y===void 0||k===void 0)&&Te(h,this.length-8);const R=y+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24,$=this[++h]+this[++h]*2**8+this[++h]*2**16+k*2**24;return BigInt(R)+(BigInt($)<<BigInt(32))}),o.prototype.readBigUInt64BE=Ln(function(h){h=h>>>0,Ee(h,"offset");const y=this[h],k=this[h+7];(y===void 0||k===void 0)&&Te(h,this.length-8);const R=y*2**24+this[++h]*2**16+this[++h]*2**8+this[++h],$=this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+k;return(BigInt(R)<<BigInt(32))+BigInt($)}),o.prototype.readIntLE=function(h,y,k){h=h>>>0,y=y>>>0,k||J(h,y,this.length);let R=this[h],$=1,W=0;for(;++W<y&&($*=256);)R+=this[h+W]*$;return $*=128,R>=$&&(R-=Math.pow(2,8*y)),R},o.prototype.readIntBE=function(h,y,k){h=h>>>0,y=y>>>0,k||J(h,y,this.length);let R=y,$=1,W=this[h+--R];for(;R>0&&($*=256);)W+=this[h+--R]*$;return $*=128,W>=$&&(W-=Math.pow(2,8*y)),W},o.prototype.readInt8=function(h,y){return h=h>>>0,y||J(h,1,this.length),this[h]&128?(255-this[h]+1)*-1:this[h]},o.prototype.readInt16LE=function(h,y){h=h>>>0,y||J(h,2,this.length);const k=this[h]|this[h+1]<<8;return k&32768?k|4294901760:k},o.prototype.readInt16BE=function(h,y){h=h>>>0,y||J(h,2,this.length);const k=this[h+1]|this[h]<<8;return k&32768?k|4294901760:k},o.prototype.readInt32LE=function(h,y){return h=h>>>0,y||J(h,4,this.length),this[h]|this[h+1]<<8|this[h+2]<<16|this[h+3]<<24},o.prototype.readInt32BE=function(h,y){return h=h>>>0,y||J(h,4,this.length),this[h]<<24|this[h+1]<<16|this[h+2]<<8|this[h+3]},o.prototype.readBigInt64LE=Ln(function(h){h=h>>>0,Ee(h,"offset");const y=this[h],k=this[h+7];(y===void 0||k===void 0)&&Te(h,this.length-8);const R=this[h+4]+this[h+5]*2**8+this[h+6]*2**16+(k<<24);return(BigInt(R)<<BigInt(32))+BigInt(y+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24)}),o.prototype.readBigInt64BE=Ln(function(h){h=h>>>0,Ee(h,"offset");const y=this[h],k=this[h+7];(y===void 0||k===void 0)&&Te(h,this.length-8);const R=(y<<24)+this[++h]*2**16+this[++h]*2**8+this[++h];return(BigInt(R)<<BigInt(32))+BigInt(this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+k)}),o.prototype.readFloatLE=function(h,y){return h=h>>>0,y||J(h,4,this.length),r.read(this,h,!0,23,4)},o.prototype.readFloatBE=function(h,y){return h=h>>>0,y||J(h,4,this.length),r.read(this,h,!1,23,4)},o.prototype.readDoubleLE=function(h,y){return h=h>>>0,y||J(h,8,this.length),r.read(this,h,!0,52,8)},o.prototype.readDoubleBE=function(h,y){return h=h>>>0,y||J(h,8,this.length),r.read(this,h,!1,52,8)};function B(E,h,y,k,R,$){if(!o.isBuffer(E))throw new TypeError('"buffer" argument must be a Buffer instance');if(h>R||h<$)throw new RangeError('"value" argument is out of bounds');if(y+k>E.length)throw new RangeError("Index out of range")}o.prototype.writeUintLE=o.prototype.writeUIntLE=function(h,y,k,R){if(h=+h,y=y>>>0,k=k>>>0,!R){const we=Math.pow(2,8*k)-1;B(this,h,y,k,we,0)}let $=1,W=0;for(this[y]=h&255;++W<k&&($*=256);)this[y+W]=h/$&255;return y+k},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(h,y,k,R){if(h=+h,y=y>>>0,k=k>>>0,!R){const we=Math.pow(2,8*k)-1;B(this,h,y,k,we,0)}let $=k-1,W=1;for(this[y+$]=h&255;--$>=0&&(W*=256);)this[y+$]=h/W&255;return y+k},o.prototype.writeUint8=o.prototype.writeUInt8=function(h,y,k){return h=+h,y=y>>>0,k||B(this,h,y,1,255,0),this[y]=h&255,y+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(h,y,k){return h=+h,y=y>>>0,k||B(this,h,y,2,65535,0),this[y]=h&255,this[y+1]=h>>>8,y+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(h,y,k){return h=+h,y=y>>>0,k||B(this,h,y,2,65535,0),this[y]=h>>>8,this[y+1]=h&255,y+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(h,y,k){return h=+h,y=y>>>0,k||B(this,h,y,4,4294967295,0),this[y+3]=h>>>24,this[y+2]=h>>>16,this[y+1]=h>>>8,this[y]=h&255,y+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(h,y,k){return h=+h,y=y>>>0,k||B(this,h,y,4,4294967295,0),this[y]=h>>>24,this[y+1]=h>>>16,this[y+2]=h>>>8,this[y+3]=h&255,y+4};function F(E,h,y,k,R){ge(h,k,R,E,y,7);let $=Number(h&BigInt(4294967295));E[y++]=$,$=$>>8,E[y++]=$,$=$>>8,E[y++]=$,$=$>>8,E[y++]=$;let W=Number(h>>BigInt(32)&BigInt(4294967295));return E[y++]=W,W=W>>8,E[y++]=W,W=W>>8,E[y++]=W,W=W>>8,E[y++]=W,y}function z(E,h,y,k,R){ge(h,k,R,E,y,7);let $=Number(h&BigInt(4294967295));E[y+7]=$,$=$>>8,E[y+6]=$,$=$>>8,E[y+5]=$,$=$>>8,E[y+4]=$;let W=Number(h>>BigInt(32)&BigInt(4294967295));return E[y+3]=W,W=W>>8,E[y+2]=W,W=W>>8,E[y+1]=W,W=W>>8,E[y]=W,y+8}o.prototype.writeBigUInt64LE=Ln(function(h,y=0){return F(this,h,y,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=Ln(function(h,y=0){return z(this,h,y,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(h,y,k,R){if(h=+h,y=y>>>0,!R){const qe=Math.pow(2,8*k-1);B(this,h,y,k,qe-1,-qe)}let $=0,W=1,we=0;for(this[y]=h&255;++$<k&&(W*=256);)h<0&&we===0&&this[y+$-1]!==0&&(we=1),this[y+$]=(h/W>>0)-we&255;return y+k},o.prototype.writeIntBE=function(h,y,k,R){if(h=+h,y=y>>>0,!R){const qe=Math.pow(2,8*k-1);B(this,h,y,k,qe-1,-qe)}let $=k-1,W=1,we=0;for(this[y+$]=h&255;--$>=0&&(W*=256);)h<0&&we===0&&this[y+$+1]!==0&&(we=1),this[y+$]=(h/W>>0)-we&255;return y+k},o.prototype.writeInt8=function(h,y,k){return h=+h,y=y>>>0,k||B(this,h,y,1,127,-128),h<0&&(h=255+h+1),this[y]=h&255,y+1},o.prototype.writeInt16LE=function(h,y,k){return h=+h,y=y>>>0,k||B(this,h,y,2,32767,-32768),this[y]=h&255,this[y+1]=h>>>8,y+2},o.prototype.writeInt16BE=function(h,y,k){return h=+h,y=y>>>0,k||B(this,h,y,2,32767,-32768),this[y]=h>>>8,this[y+1]=h&255,y+2},o.prototype.writeInt32LE=function(h,y,k){return h=+h,y=y>>>0,k||B(this,h,y,4,2147483647,-2147483648),this[y]=h&255,this[y+1]=h>>>8,this[y+2]=h>>>16,this[y+3]=h>>>24,y+4},o.prototype.writeInt32BE=function(h,y,k){return h=+h,y=y>>>0,k||B(this,h,y,4,2147483647,-2147483648),h<0&&(h=4294967295+h+1),this[y]=h>>>24,this[y+1]=h>>>16,this[y+2]=h>>>8,this[y+3]=h&255,y+4},o.prototype.writeBigInt64LE=Ln(function(h,y=0){return F(this,h,y,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=Ln(function(h,y=0){return z(this,h,y,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ne(E,h,y,k,R,$){if(y+k>E.length)throw new RangeError("Index out of range");if(y<0)throw new RangeError("Index out of range")}function ae(E,h,y,k,R){return h=+h,y=y>>>0,R||ne(E,h,y,4),r.write(E,h,y,k,23,4),y+4}o.prototype.writeFloatLE=function(h,y,k){return ae(this,h,y,!0,k)},o.prototype.writeFloatBE=function(h,y,k){return ae(this,h,y,!1,k)};function fe(E,h,y,k,R){return h=+h,y=y>>>0,R||ne(E,h,y,8),r.write(E,h,y,k,52,8),y+8}o.prototype.writeDoubleLE=function(h,y,k){return fe(this,h,y,!0,k)},o.prototype.writeDoubleBE=function(h,y,k){return fe(this,h,y,!1,k)},o.prototype.copy=function(h,y,k,R){if(!o.isBuffer(h))throw new TypeError("argument should be a Buffer");if(k||(k=0),!R&&R!==0&&(R=this.length),y>=h.length&&(y=h.length),y||(y=0),R>0&&R<k&&(R=k),R===k||h.length===0||this.length===0)return 0;if(y<0)throw new RangeError("targetStart out of bounds");if(k<0||k>=this.length)throw new RangeError("Index out of range");if(R<0)throw new RangeError("sourceEnd out of bounds");R>this.length&&(R=this.length),h.length-y<R-k&&(R=h.length-y+k);const $=R-k;return this===h&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(y,k,R):Uint8Array.prototype.set.call(h,this.subarray(k,R),y),$},o.prototype.fill=function(h,y,k,R){if(typeof h=="string"){if(typeof y=="string"?(R=y,y=0,k=this.length):typeof k=="string"&&(R=k,k=this.length),R!==void 0&&typeof R!="string")throw new TypeError("encoding must be a string");if(typeof R=="string"&&!o.isEncoding(R))throw new TypeError("Unknown encoding: "+R);if(h.length===1){const W=h.charCodeAt(0);(R==="utf8"&&W<128||R==="latin1")&&(h=W)}}else typeof h=="number"?h=h&255:typeof h=="boolean"&&(h=Number(h));if(y<0||this.length<y||this.length<k)throw new RangeError("Out of range index");if(k<=y)return this;y=y>>>0,k=k===void 0?this.length:k>>>0,h||(h=0);let $;if(typeof h=="number")for($=y;$<k;++$)this[$]=h;else{const W=o.isBuffer(h)?h:o.from(h,R),we=W.length;if(we===0)throw new TypeError('The value "'+h+'" is invalid for argument "value"');for($=0;$<k-y;++$)this[$+y]=W[$%we]}return this};const ue={};function ie(E,h,y){ue[E]=class extends y{constructor(){super(),Object.defineProperty(this,"message",{value:h.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${E}]`,this.stack,delete this.name}get code(){return E}set code(R){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:R,writable:!0})}toString(){return`${this.name} [${E}]: ${this.message}`}}}ie("ERR_BUFFER_OUT_OF_BOUNDS",function(E){return E?`${E} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),ie("ERR_INVALID_ARG_TYPE",function(E,h){return`The "${E}" argument must be of type number. Received type ${typeof h}`},TypeError),ie("ERR_OUT_OF_RANGE",function(E,h,y){let k=`The value of "${E}" is out of range.`,R=y;return Number.isInteger(y)&&Math.abs(y)>2**32?R=se(String(y)):typeof y=="bigint"&&(R=String(y),(y>BigInt(2)**BigInt(32)||y<-(BigInt(2)**BigInt(32)))&&(R=se(R)),R+="n"),k+=` It must be ${h}. Received ${R}`,k},RangeError);function se(E){let h="",y=E.length;const k=E[0]==="-"?1:0;for(;y>=k+4;y-=3)h=`_${E.slice(y-3,y)}${h}`;return`${E.slice(0,y)}${h}`}function be(E,h,y){Ee(h,"offset"),(E[h]===void 0||E[h+y]===void 0)&&Te(h,E.length-(y+1))}function ge(E,h,y,k,R,$){if(E>y||E<h){const W=typeof h=="bigint"?"n":"";let we;throw h===0||h===BigInt(0)?we=`>= 0${W} and < 2${W} ** ${($+1)*8}${W}`:we=`>= -(2${W} ** ${($+1)*8-1}${W}) and < 2 ** ${($+1)*8-1}${W}`,new ue.ERR_OUT_OF_RANGE("value",we,E)}be(k,R,$)}function Ee(E,h){if(typeof E!="number")throw new ue.ERR_INVALID_ARG_TYPE(h,"number",E)}function Te(E,h,y){throw Math.floor(E)!==E?(Ee(E,y),new ue.ERR_OUT_OF_RANGE("offset","an integer",E)):h<0?new ue.ERR_BUFFER_OUT_OF_BOUNDS:new ue.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${h}`,E)}const nt=/[^+/0-9A-Za-z-_]/g;function Ce(E){if(E=E.split("=")[0],E=E.trim().replace(nt,""),E.length<2)return"";for(;E.length%4!==0;)E=E+"=";return E}function Hr(E,h){h=h||1/0;let y;const k=E.length;let R=null;const $=[];for(let W=0;W<k;++W){if(y=E.charCodeAt(W),y>55295&&y<57344){if(!R){if(y>56319){(h-=3)>-1&&$.push(239,191,189);continue}else if(W+1===k){(h-=3)>-1&&$.push(239,191,189);continue}R=y;continue}if(y<56320){(h-=3)>-1&&$.push(239,191,189),R=y;continue}y=(R-55296<<10|y-56320)+65536}else R&&(h-=3)>-1&&$.push(239,191,189);if(R=null,y<128){if((h-=1)<0)break;$.push(y)}else if(y<2048){if((h-=2)<0)break;$.push(y>>6|192,y&63|128)}else if(y<65536){if((h-=3)<0)break;$.push(y>>12|224,y>>6&63|128,y&63|128)}else if(y<1114112){if((h-=4)<0)break;$.push(y>>18|240,y>>12&63|128,y>>6&63|128,y&63|128)}else throw new Error("Invalid code point")}return $}function ks(E){const h=[];for(let y=0;y<E.length;++y)h.push(E.charCodeAt(y)&255);return h}function X(E,h){let y,k,R;const $=[];for(let W=0;W<E.length&&!((h-=2)<0);++W)y=E.charCodeAt(W),k=y>>8,R=y%256,$.push(R),$.push(k);return $}function Lr(E){return e.toByteArray(Ce(E))}function _t(E,h,y,k){let R;for(R=0;R<k&&!(R+y>=h.length||R>=E.length);++R)h[R+y]=E[R];return R}function It(E,h){return E instanceof h||E!=null&&E.constructor!=null&&E.constructor.name!=null&&E.constructor.name===h.name}function Hn(E){return E!==E}const di=function(){const E="0123456789abcdef",h=new Array(256);for(let y=0;y<16;++y){const k=y*16;for(let R=0;R<16;++R)h[k+R]=E[y]+E[R]}return h}();function Ln(E){return typeof BigInt>"u"?T6:E}function T6(){throw new Error("BigInt not supported")}})(ii);var Ma={Array:function(t){return t!=null&&t.constructor===Array},Boolean:function(t){return typeof t=="boolean"},Function:function(t){return typeof t=="function"},Nil:function(t){return t==null},Number:function(t){return typeof t=="number"},Object:function(t){return typeof t=="object"},String:function(t){return typeof t=="string"},"":function(){return!0}};Ma.Null=Ma.Nil;for(var z0 in Ma)Ma[z0].toJSON=(function(t){return t}).bind(null,z0);var nh=Ma,js=nh;function Hm(t){return t.name||t.toString().match(/function (.*?)\s*\(/)[1]}function sh(t){return js.Nil(t)?"":Hm(t.constructor)}function uv(t){return js.Function(t)?"":js.String(t)?JSON.stringify(t):t&&js.Object(t)?"":t}function ih(t,e){Error.captureStackTrace&&Error.captureStackTrace(t,e)}function Oc(t){return js.Function(t)?t.toJSON?t.toJSON():Hm(t):js.Array(t)?"Array":t&&js.Object(t)?"Object":t!==void 0?t:""}function Lm(t,e,r){var n=uv(e);return"Expected "+Oc(t)+", got"+(r!==""?" "+r:"")+(n!==""?" "+n:"")}function Cn(t,e,r){r=r||sh(e),this.message=Lm(t,e,r),ih(this,Cn),this.__type=t,this.__value=e,this.__valueTypeName=r}Cn.prototype=Object.create(Error.prototype);Cn.prototype.constructor=Cn;function lv(t,e,r,n,s){var i='" of type ';return e==="key"&&(i='" with key type '),Lm('property "'+Oc(r)+i+Oc(t),n,s)}function Oi(t,e,r,n,s){t?(s=s||sh(n),this.message=lv(t,r,e,n,s)):this.message='Unexpected property "'+e+'"',ih(this,Cn),this.__label=r,this.__property=e,this.__type=t,this.__value=n,this.__valueTypeName=s}Oi.prototype=Object.create(Error.prototype);Oi.prototype.constructor=Cn;function fv(t,e){return new Cn(t,{},e)}function dv(t,e,r){return t instanceof Oi?(e=e+"."+t.__property,t=new Oi(t.__type,e,t.__label,t.__value,t.__valueTypeName)):t instanceof Cn&&(t=new Oi(t.__type,e,r,t.__value,t.__valueTypeName)),ih(t),t}var Dm={TfTypeError:Cn,TfPropertyTypeError:Oi,tfCustomError:fv,tfSubError:dv,tfJSON:Oc,getValueTypeName:sh},Vu,V0;function hv(){if(V0)return Vu;V0=1;var t=nh,e=Dm;function r(_){return Buffer.isBuffer(_)}function n(_){return typeof _=="string"&&/^([0-9a-f]{2})+$/i.test(_)}function s(_,I){var N=_.toJSON();function C(j){if(!_(j))return!1;if(j.length===I)return!0;throw e.tfCustomError(N+"(Length: "+I+")",N+"(Length: "+j.length+")")}return C.toJSON=function(){return N},C}var i=s.bind(null,t.Array),a=s.bind(null,r),o=s.bind(null,n),c=s.bind(null,t.String);function u(_,I,N){N=N||t.Number;function C(j,M){return N(j,M)&&j>_&&j<I}return C.toJSON=function(){return`${N.toJSON()} between [${_}, ${I}]`},C}var l=Math.pow(2,53)-1;function f(_){return typeof _=="number"&&isFinite(_)}function p(_){return _<<24>>24===_}function d(_){return _<<16>>16===_}function b(_){return(_|0)===_}function g(_){return typeof _=="number"&&_>=-l&&_<=l&&Math.floor(_)===_}function A(_){return(_&255)===_}function S(_){return(_&65535)===_}function T(_){return _>>>0===_}function v(_){return typeof _=="number"&&_>=0&&_<=l&&Math.floor(_)===_}var w={ArrayN:i,Buffer:r,BufferN:a,Finite:f,Hex:n,HexN:o,Int8:p,Int16:d,Int32:b,Int53:g,Range:u,StringN:c,UInt8:A,UInt16:S,UInt32:T,UInt53:v};for(var x in w)w[x].toJSON=(function(_){return _}).bind(null,x);return Vu=w,Vu}var vo=Dm,ht=nh,ln=vo.tfJSON,zm=vo.TfTypeError,Vm=vo.TfPropertyTypeError,ca=vo.tfSubError,pv=vo.getValueTypeName,kn={arrayOf:function(e,r){e=Jr(e),r=r||{};function n(s,i){return!ht.Array(s)||ht.Nil(s)||r.minLength!==void 0&&s.length<r.minLength||r.maxLength!==void 0&&s.length>r.maxLength||r.length!==void 0&&s.length!==r.length?!1:s.every(function(a,o){try{return Rt(e,a,i)}catch(c){throw ca(c,o)}})}return n.toJSON=function(){var s="["+ln(e)+"]";return r.length!==void 0?s+="{"+r.length+"}":(r.minLength!==void 0||r.maxLength!==void 0)&&(s+="{"+(r.minLength===void 0?0:r.minLength)+","+(r.maxLength===void 0?1/0:r.maxLength)+"}"),s},n},maybe:function t(e){e=Jr(e);function r(n,s){return ht.Nil(n)||e(n,s,t)}return r.toJSON=function(){return"?"+ln(e)},r},map:function(e,r){e=Jr(e),r&&(r=Jr(r));function n(s,i){if(!ht.Object(s)||ht.Nil(s))return!1;for(var a in s){try{r&&Rt(r,a,i)}catch(c){throw ca(c,a,"key")}try{var o=s[a];Rt(e,o,i)}catch(c){throw ca(c,a)}}return!0}return r?n.toJSON=function(){return"{"+ln(r)+": "+ln(e)+"}"}:n.toJSON=function(){return"{"+ln(e)+"}"},n},object:function(e){var r={};for(var n in e)r[n]=Jr(e[n]);function s(i,a){if(!ht.Object(i)||ht.Nil(i))return!1;var o;try{for(o in r){var c=r[o],u=i[o];Rt(c,u,a)}}catch(l){throw ca(l,o)}if(a){for(o in i)if(!r[o])throw new Vm(void 0,o)}return!0}return s.toJSON=function(){return ln(r)},s},anyOf:function(){var e=[].slice.call(arguments).map(Jr);function r(n,s){return e.some(function(i){try{return Rt(i,n,s)}catch{return!1}})}return r.toJSON=function(){return e.map(ln).join("|")},r},allOf:function(){var e=[].slice.call(arguments).map(Jr);function r(n,s){return e.every(function(i){try{return Rt(i,n,s)}catch{return!1}})}return r.toJSON=function(){return e.map(ln).join(" & ")},r},quacksLike:function(e){function r(n){return e===pv(n)}return r.toJSON=function(){return e},r},tuple:function(){var e=[].slice.call(arguments).map(Jr);function r(n,s){return ht.Nil(n)||ht.Nil(n.length)||s&&n.length!==e.length?!1:e.every(function(i,a){try{return Rt(i,n[a],s)}catch(o){throw ca(o,a)}})}return r.toJSON=function(){return"("+e.map(ln).join(", ")+")"},r},value:function(e){function r(n){return n===e}return r.toJSON=function(){return e},r}};kn.oneOf=kn.anyOf;function Jr(t){if(ht.String(t))return t[0]==="?"?kn.maybe(t.slice(1)):ht[t]||kn.quacksLike(t);if(t&&ht.Object(t)){if(ht.Array(t)){if(t.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return kn.arrayOf(t[0])}return kn.object(t)}else if(ht.Function(t))return t;return kn.value(t)}function Rt(t,e,r,n){if(ht.Function(t)){if(t(e,r))return!0;throw new zm(n||t,e)}return Rt(Jr(t),e,r)}for(var ls in ht)Rt[ls]=ht[ls];for(ls in kn)Rt[ls]=kn[ls];var G0=hv();for(ls in G0)Rt[ls]=G0[ls];Rt.compile=Jr;Rt.TfTypeError=zm;Rt.TfPropertyTypeError=Vm;var yv=Rt;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.oneOf=t.Null=t.BufferN=t.Function=t.UInt32=t.UInt8=t.tuple=t.maybe=t.Hex=t.Buffer=t.String=t.Boolean=t.Array=t.Number=t.Hash256bit=t.Hash160bit=t.Buffer256bit=t.isTaptree=t.isTapleaf=t.TAPLEAF_VERSION_MASK=t.Satoshi=t.isPoint=t.stacksEqual=t.typeforce=void 0;const e=ii;t.typeforce=yv;const r=e.Buffer.alloc(32,0),n=e.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function s(l,f){return l.length!==f.length?!1:l.every((p,d)=>p.equals(f[d]))}t.stacksEqual=s;function i(l){if(!e.Buffer.isBuffer(l)||l.length<33)return!1;const f=l[0],p=l.slice(1,33);if(p.compare(r)===0||p.compare(n)>=0)return!1;if((f===2||f===3)&&l.length===33)return!0;const d=l.slice(33);return d.compare(r)===0||d.compare(n)>=0?!1:f===4&&l.length===65}t.isPoint=i;const a=21*1e14;function o(l){return t.typeforce.UInt53(l)&&l<=a}t.Satoshi=o,t.TAPLEAF_VERSION_MASK=254;function c(l){return!l||!("output"in l)||!e.Buffer.isBuffer(l.output)?!1:l.version!==void 0?(l.version&t.TAPLEAF_VERSION_MASK)===l.version:!0}t.isTapleaf=c;function u(l){return(0,t.Array)(l)?l.length!==2?!1:l.every(f=>u(f)):c(l)}t.isTaptree=u,t.Buffer256bit=t.typeforce.BufferN(32),t.Hash160bit=t.typeforce.BufferN(20),t.Hash256bit=t.typeforce.BufferN(32),t.Number=t.typeforce.Number,t.Array=t.typeforce.Array,t.Boolean=t.typeforce.Boolean,t.String=t.typeforce.String,t.Buffer=t.typeforce.Buffer,t.Hex=t.typeforce.Hex,t.maybe=t.typeforce.maybe,t.tuple=t.typeforce.tuple,t.UInt8=t.typeforce.UInt8,t.UInt32=t.typeforce.UInt32,t.Function=t.typeforce.Function,t.BufferN=t.typeforce.BufferN,t.Null=t.typeforce.Null,t.oneOf=t.typeforce.oneOf})(kt);var Eo={},pt={};Object.defineProperty(pt,"__esModule",{value:!0});pt.BufferReader=pt.BufferWriter=pt.cloneBuffer=pt.reverseBuffer=pt.writeUInt64LE=pt.readUInt64LE=pt.varuint=void 0;const Hs=kt,{typeforce:Gm}=Hs,$a=Nm;pt.varuint=$a;function qm(t,e){if(typeof t!="number")throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}function Wm(t,e){const r=t.readUInt32LE(e);let n=t.readUInt32LE(e+4);return n*=4294967296,qm(n+r,9007199254740991),n+r}pt.readUInt64LE=Wm;function Km(t,e,r){return qm(e,9007199254740991),t.writeInt32LE(e&-1,r),t.writeUInt32LE(Math.floor(e/4294967296),r+4),r+8}pt.writeUInt64LE=Km;function mv(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;n<t.length/2;n++)r=t[n],t[n]=t[e],t[e]=r,e--;return t}pt.reverseBuffer=mv;function bv(t){const e=Buffer.allocUnsafe(t.length);return t.copy(e),e}pt.cloneBuffer=bv;class ah{static withCapacity(e){return new ah(Buffer.alloc(e))}constructor(e,r=0){this.buffer=e,this.offset=r,Gm(Hs.tuple(Hs.Buffer,Hs.UInt32),[e,r])}writeUInt8(e){this.offset=this.buffer.writeUInt8(e,this.offset)}writeInt32(e){this.offset=this.buffer.writeInt32LE(e,this.offset)}writeUInt32(e){this.offset=this.buffer.writeUInt32LE(e,this.offset)}writeUInt64(e){this.offset=Km(this.buffer,e,this.offset)}writeVarInt(e){$a.encode(e,this.buffer,this.offset),this.offset+=$a.encode.bytes}writeSlice(e){if(this.buffer.length<this.offset+e.length)throw new Error("Cannot write slice out of bounds");this.offset+=e.copy(this.buffer,this.offset)}writeVarSlice(e){this.writeVarInt(e.length),this.writeSlice(e)}writeVector(e){this.writeVarInt(e.length),e.forEach(r=>this.writeVarSlice(r))}end(){if(this.buffer.length===this.offset)return this.buffer;throw new Error(`buffer size ${this.buffer.length}, offset ${this.offset}`)}}pt.BufferWriter=ah;class gv{constructor(e,r=0){this.buffer=e,this.offset=r,Gm(Hs.tuple(Hs.Buffer,Hs.UInt32),[e,r])}readUInt8(){const e=this.buffer.readUInt8(this.offset);return this.offset++,e}readInt32(){const e=this.buffer.readInt32LE(this.offset);return this.offset+=4,e}readUInt32(){const e=this.buffer.readUInt32LE(this.offset);return this.offset+=4,e}readUInt64(){const e=Wm(this.buffer,this.offset);return this.offset+=8,e}readVarInt(){const e=$a.decode(this.buffer,this.offset);return this.offset+=$a.decode.bytes,e}readSlice(e){if(this.buffer.length<this.offset+e)throw new Error("Cannot read slice out of bounds");const r=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,r}readVarSlice(){return this.readSlice(this.readVarInt())}readVector(){const e=this.readVarInt(),r=[];for(let n=0;n<e;n++)r.push(this.readVarSlice());return r}}pt.BufferReader=gv;var vs={},Hi={},Nt={},At={},Xc={},Yc={};Object.defineProperty(Yc,"__esModule",{value:!0});Yc.crypto=void 0;Yc.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;(function(t){/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */Object.defineProperty(t,"__esModule",{value:!0}),t.wrapXOFConstructorWithOpts=t.wrapConstructorWithOpts=t.wrapConstructor=t.Hash=t.nextTick=t.swap32IfBE=t.byteSwapIfBE=t.swap8IfBE=t.isLE=void 0,t.isBytes=r,t.anumber=n,t.abytes=s,t.ahash=i,t.aexists=a,t.aoutput=o,t.u8=c,t.u32=u,t.clean=l,t.createView=f,t.rotr=p,t.rotl=d,t.byteSwap=b,t.byteSwap32=g,t.bytesToHex=T,t.hexToBytes=x,t.asyncLoop=I,t.utf8ToBytes=N,t.bytesToUtf8=C,t.toBytes=j,t.kdfInputToBytes=M,t.concatBytes=H,t.checkOpts=V,t.createHasher=U,t.createOptHasher=K,t.createXOFer=ee,t.randomBytes=q;const e=Yc;function r(O){return O instanceof Uint8Array||ArrayBuffer.isView(O)&&O.constructor.name==="Uint8Array"}function n(O){if(!Number.isSafeInteger(O)||O<0)throw new Error("positive integer expected, got "+O)}function s(O,...L){if(!r(O))throw new Error("Uint8Array expected");if(L.length>0&&!L.includes(O.length))throw new Error("Uint8Array expected of length "+L+", got length="+O.length)}function i(O){if(typeof O!="function"||typeof O.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");n(O.outputLen),n(O.blockLen)}function a(O,L=!0){if(O.destroyed)throw new Error("Hash instance has been destroyed");if(L&&O.finished)throw new Error("Hash#digest() has already been called")}function o(O,L){s(O);const J=L.outputLen;if(O.length<J)throw new Error("digestInto() expects output buffer of length at least "+J)}function c(O){return new Uint8Array(O.buffer,O.byteOffset,O.byteLength)}function u(O){return new Uint32Array(O.buffer,O.byteOffset,Math.floor(O.byteLength/4))}function l(...O){for(let L=0;L<O.length;L++)O[L].fill(0)}function f(O){return new DataView(O.buffer,O.byteOffset,O.byteLength)}function p(O,L){return O<<32-L|O>>>L}function d(O,L){return O<<L|O>>>32-L>>>0}t.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function b(O){return O<<24&4278190080|O<<8&16711680|O>>>8&65280|O>>>24&255}t.swap8IfBE=t.isLE?O=>O:O=>b(O),t.byteSwapIfBE=t.swap8IfBE;function g(O){for(let L=0;L<O.length;L++)O[L]=b(O[L]);return O}t.swap32IfBE=t.isLE?O=>O:g;const A=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",S=Array.from({length:256},(O,L)=>L.toString(16).padStart(2,"0"));function T(O){if(s(O),A)return O.toHex();let L="";for(let J=0;J<O.length;J++)L+=S[O[J]];return L}const v={_0:48,_9:57,A:65,F:70,a:97,f:102};function w(O){if(O>=v._0&&O<=v._9)return O-v._0;if(O>=v.A&&O<=v.F)return O-(v.A-10);if(O>=v.a&&O<=v.f)return O-(v.a-10)}function x(O){if(typeof O!="string")throw new Error("hex string expected, got "+typeof O);if(A)return Uint8Array.fromHex(O);const L=O.length,J=L/2;if(L%2)throw new Error("hex string expected, got unpadded hex of length "+L);const B=new Uint8Array(J);for(let F=0,z=0;F<J;F++,z+=2){const ne=w(O.charCodeAt(z)),ae=w(O.charCodeAt(z+1));if(ne===void 0||ae===void 0){const fe=O[z]+O[z+1];throw new Error('hex string expected, got non-hex character "'+fe+'" at index '+z)}B[F]=ne*16+ae}return B}const _=async()=>{};t.nextTick=_;async function I(O,L,J){let B=Date.now();for(let F=0;F<O;F++){J(F);const z=Date.now()-B;z>=0&&z<L||(await(0,t.nextTick)(),B+=z)}}function N(O){if(typeof O!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(O))}function C(O){return new TextDecoder().decode(O)}function j(O){return typeof O=="string"&&(O=N(O)),s(O),O}function M(O){return typeof O=="string"&&(O=N(O)),s(O),O}function H(...O){let L=0;for(let B=0;B<O.length;B++){const F=O[B];s(F),L+=F.length}const J=new Uint8Array(L);for(let B=0,F=0;B<O.length;B++){const z=O[B];J.set(z,F),F+=z.length}return J}function V(O,L){if(L!==void 0&&{}.toString.call(L)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(O,L)}class Q{}t.Hash=Q;function U(O){const L=B=>O().update(j(B)).digest(),J=O();return L.outputLen=J.outputLen,L.blockLen=J.blockLen,L.create=()=>O(),L}function K(O){const L=(B,F)=>O(F).update(j(B)).digest(),J=O({});return L.outputLen=J.outputLen,L.blockLen=J.blockLen,L.create=B=>O(B),L}function ee(O){const L=(B,F)=>O(F).update(j(B)).digest(),J=O({});return L.outputLen=J.outputLen,L.blockLen=J.blockLen,L.create=B=>O(B),L}t.wrapConstructor=U,t.wrapConstructorWithOpts=K,t.wrapXOFConstructorWithOpts=ee;function q(O=32){if(e.crypto&&typeof e.crypto.getRandomValues=="function")return e.crypto.getRandomValues(new Uint8Array(O));if(e.crypto&&typeof e.crypto.randomBytes=="function")return Uint8Array.from(e.crypto.randomBytes(O));throw new Error("crypto.getRandomValues must be defined")}})(Xc);Object.defineProperty(At,"__esModule",{value:!0});At.SHA512_IV=At.SHA384_IV=At.SHA224_IV=At.SHA256_IV=At.HashMD=void 0;At.setBigUint64=Xm;At.Chi=wv;At.Maj=vv;const Dr=Xc;function Xm(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const s=BigInt(32),i=BigInt(4294967295),a=Number(r>>s&i),o=Number(r&i),c=n?4:0,u=n?0:4;t.setUint32(e+c,a,n),t.setUint32(e+u,o,n)}function wv(t,e,r){return t&e^~t&r}function vv(t,e,r){return t&e^t&r^e&r}let Ev=class extends Dr.Hash{constructor(e,r,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=(0,Dr.createView)(this.buffer)}update(e){(0,Dr.aexists)(this),e=(0,Dr.toBytes)(e),(0,Dr.abytes)(e);const{view:r,buffer:n,blockLen:s}=this,i=e.length;for(let a=0;a<i;){const o=Math.min(s-this.pos,i-a);if(o===s){const c=(0,Dr.createView)(e);for(;s<=i-a;a+=s)this.process(c,a);continue}n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){(0,Dr.aexists)(this),(0,Dr.aoutput)(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:s,isLE:i}=this;let{pos:a}=this;r[a++]=128,(0,Dr.clean)(this.buffer.subarray(a)),this.padOffset>s-a&&(this.process(n,0),a=0);for(let f=a;f<s;f++)r[f]=0;Xm(n,s-8,BigInt(this.length*8),i),this.process(n,0);const o=(0,Dr.createView)(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)o.setUint32(4*f,l[f],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:s,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=s,e.pos=o,s%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}};At.HashMD=Ev;At.SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);At.SHA224_IV=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);At.SHA384_IV=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]);At.SHA512_IV=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);Object.defineProperty(Nt,"__esModule",{value:!0});Nt.ripemd160=Nt.RIPEMD160=Nt.md5=Nt.MD5=Nt.sha1=Nt.SHA1=void 0;const Ls=At,yt=Xc,bi=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Dn=new Uint32Array(80);class Ym extends Ls.HashMD{constructor(){super(64,20,8,!1),this.A=bi[0]|0,this.B=bi[1]|0,this.C=bi[2]|0,this.D=bi[3]|0,this.E=bi[4]|0}get(){const{A:e,B:r,C:n,D:s,E:i}=this;return[e,r,n,s,i]}set(e,r,n,s,i){this.A=e|0,this.B=r|0,this.C=n|0,this.D=s|0,this.E=i|0}process(e,r){for(let c=0;c<16;c++,r+=4)Dn[c]=e.getUint32(r,!1);for(let c=16;c<80;c++)Dn[c]=(0,yt.rotl)(Dn[c-3]^Dn[c-8]^Dn[c-14]^Dn[c-16],1);let{A:n,B:s,C:i,D:a,E:o}=this;for(let c=0;c<80;c++){let u,l;c<20?(u=(0,Ls.Chi)(s,i,a),l=1518500249):c<40?(u=s^i^a,l=1859775393):c<60?(u=(0,Ls.Maj)(s,i,a),l=2400959708):(u=s^i^a,l=3395469782);const f=(0,yt.rotl)(n,5)+u+o+l+Dn[c]|0;o=a,a=i,i=(0,yt.rotl)(s,30),s=n,n=f}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,this.set(n,s,i,a,o)}roundClean(){(0,yt.clean)(Dn)}destroy(){this.set(0,0,0,0,0),(0,yt.clean)(this.buffer)}}Nt.SHA1=Ym;Nt.sha1=(0,yt.createHasher)(()=>new Ym);const Av=Math.pow(2,32),Sv=Array.from({length:64},(t,e)=>Math.floor(Av*Math.abs(Math.sin(e+1)))),Wo=bi.slice(0,4),Gu=new Uint32Array(16);class Jm extends Ls.HashMD{constructor(){super(64,16,8,!0),this.A=Wo[0]|0,this.B=Wo[1]|0,this.C=Wo[2]|0,this.D=Wo[3]|0}get(){const{A:e,B:r,C:n,D:s}=this;return[e,r,n,s]}set(e,r,n,s){this.A=e|0,this.B=r|0,this.C=n|0,this.D=s|0}process(e,r){for(let o=0;o<16;o++,r+=4)Gu[o]=e.getUint32(r,!0);let{A:n,B:s,C:i,D:a}=this;for(let o=0;o<64;o++){let c,u,l;o<16?(c=(0,Ls.Chi)(s,i,a),u=o,l=[7,12,17,22]):o<32?(c=(0,Ls.Chi)(a,s,i),u=(5*o+1)%16,l=[5,9,14,20]):o<48?(c=s^i^a,u=(3*o+5)%16,l=[4,11,16,23]):(c=i^(s|~a),u=7*o%16,l=[6,10,15,21]),c=c+n+Sv[o]+Gu[u],n=a,a=i,i=s,s=s+(0,yt.rotl)(c,l[o%4])}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,a=a+this.D|0,this.set(n,s,i,a)}roundClean(){(0,yt.clean)(Gu)}destroy(){this.set(0,0,0,0),(0,yt.clean)(this.buffer)}}Nt.MD5=Jm;Nt.md5=(0,yt.createHasher)(()=>new Jm);const xv=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Zm=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),kv=Zm.map(t=>(9*t+5)%16),Qm=(()=>{const r=[[Zm],[kv]];for(let n=0;n<4;n++)for(let s of r)s.push(s[n].map(i=>xv[i]));return r})(),eb=Qm[0],tb=Qm[1],rb=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(t=>Uint8Array.from(t)),Tv=eb.map((t,e)=>t.map(r=>rb[e][r])),_v=tb.map((t,e)=>t.map(r=>rb[e][r])),Iv=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Pv=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function q0(t,e,r,n){return t===0?e^r^n:t===1?e&r|~e&n:t===2?(e|~r)^n:t===3?e&n|r&~n:e^(r|~n)}const Ko=new Uint32Array(16);class nb extends Ls.HashMD{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:r,h2:n,h3:s,h4:i}=this;return[e,r,n,s,i]}set(e,r,n,s,i){this.h0=e|0,this.h1=r|0,this.h2=n|0,this.h3=s|0,this.h4=i|0}process(e,r){for(let d=0;d<16;d++,r+=4)Ko[d]=e.getUint32(r,!0);let n=this.h0|0,s=n,i=this.h1|0,a=i,o=this.h2|0,c=o,u=this.h3|0,l=u,f=this.h4|0,p=f;for(let d=0;d<5;d++){const b=4-d,g=Iv[d],A=Pv[d],S=eb[d],T=tb[d],v=Tv[d],w=_v[d];for(let x=0;x<16;x++){const _=(0,yt.rotl)(n+q0(d,i,o,u)+Ko[S[x]]+g,v[x])+f|0;n=f,f=u,u=(0,yt.rotl)(o,10)|0,o=i,i=_}for(let x=0;x<16;x++){const _=(0,yt.rotl)(s+q0(b,a,c,l)+Ko[T[x]]+A,w[x])+p|0;s=p,p=l,l=(0,yt.rotl)(c,10)|0,c=a,a=_}}this.set(this.h1+o+l|0,this.h2+u+p|0,this.h3+f+s|0,this.h4+n+a|0,this.h0+i+c|0)}roundClean(){(0,yt.clean)(Ko)}destroy(){this.destroyed=!0,(0,yt.clean)(this.buffer),this.set(0,0,0,0,0)}}Nt.RIPEMD160=nb;Nt.ripemd160=(0,yt.createHasher)(()=>new nb);Object.defineProperty(Hi,"__esModule",{value:!0});Hi.ripemd160=Hi.RIPEMD160=void 0;const sb=Nt;Hi.RIPEMD160=sb.RIPEMD160;Hi.ripemd160=sb.ripemd160;var Li={};Object.defineProperty(Li,"__esModule",{value:!0});Li.sha1=Li.SHA1=void 0;const ib=Nt;Li.SHA1=ib.SHA1;Li.sha1=ib.sha1;var Ir={},Ue={},he={};Object.defineProperty(he,"__esModule",{value:!0});he.toBig=he.shrSL=he.shrSH=he.rotrSL=he.rotrSH=he.rotrBL=he.rotrBH=he.rotr32L=he.rotr32H=he.rotlSL=he.rotlSH=he.rotlBL=he.rotlBH=he.add5L=he.add5H=he.add4L=he.add4H=he.add3L=he.add3H=void 0;he.add=vb;he.fromBig=oh;he.split=ab;const Xo=BigInt(2**32-1),Xf=BigInt(32);function oh(t,e=!1){return e?{h:Number(t&Xo),l:Number(t>>Xf&Xo)}:{h:Number(t>>Xf&Xo)|0,l:Number(t&Xo)|0}}function ab(t,e=!1){const r=t.length;let n=new Uint32Array(r),s=new Uint32Array(r);for(let i=0;i<r;i++){const{h:a,l:o}=oh(t[i],e);[n[i],s[i]]=[a,o]}return[n,s]}const ob=(t,e)=>BigInt(t>>>0)<<Xf|BigInt(e>>>0);he.toBig=ob;const cb=(t,e,r)=>t>>>r;he.shrSH=cb;const ub=(t,e,r)=>t<<32-r|e>>>r;he.shrSL=ub;const lb=(t,e,r)=>t>>>r|e<<32-r;he.rotrSH=lb;const fb=(t,e,r)=>t<<32-r|e>>>r;he.rotrSL=fb;const db=(t,e,r)=>t<<64-r|e>>>r-32;he.rotrBH=db;const hb=(t,e,r)=>t>>>r-32|e<<64-r;he.rotrBL=hb;const pb=(t,e)=>e;he.rotr32H=pb;const yb=(t,e)=>t;he.rotr32L=yb;const mb=(t,e,r)=>t<<r|e>>>32-r;he.rotlSH=mb;const bb=(t,e,r)=>e<<r|t>>>32-r;he.rotlSL=bb;const gb=(t,e,r)=>e<<r-32|t>>>64-r;he.rotlBH=gb;const wb=(t,e,r)=>t<<r-32|e>>>64-r;he.rotlBL=wb;function vb(t,e,r,n){const s=(e>>>0)+(n>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}const Eb=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0);he.add3L=Eb;const Ab=(t,e,r,n)=>e+r+n+(t/2**32|0)|0;he.add3H=Ab;const Sb=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0);he.add4L=Sb;const xb=(t,e,r,n,s)=>e+r+n+s+(t/2**32|0)|0;he.add4H=xb;const kb=(t,e,r,n,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(s>>>0);he.add5L=kb;const Tb=(t,e,r,n,s,i)=>e+r+n+s+i+(t/2**32|0)|0;he.add5H=Tb;const Ov={fromBig:oh,split:ab,toBig:ob,shrSH:cb,shrSL:ub,rotrSH:lb,rotrSL:fb,rotrBH:db,rotrBL:hb,rotr32H:pb,rotr32L:yb,rotlSH:mb,rotlSL:bb,rotlBH:gb,rotlBL:wb,add:vb,add3L:Eb,add3H:Ab,add4L:Sb,add4H:xb,add5H:Tb,add5L:kb};he.default=Ov;Object.defineProperty(Ue,"__esModule",{value:!0});Ue.sha512_224=Ue.sha512_256=Ue.sha384=Ue.sha512=Ue.sha224=Ue.sha256=Ue.SHA512_256=Ue.SHA512_224=Ue.SHA384=Ue.SHA512=Ue.SHA224=Ue.SHA256=void 0;const ce=At,ye=he,Ze=Xc,Bv=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]),zn=new Uint32Array(64);let ch=class extends ce.HashMD{constructor(e=32){super(64,e,8,!1),this.A=ce.SHA256_IV[0]|0,this.B=ce.SHA256_IV[1]|0,this.C=ce.SHA256_IV[2]|0,this.D=ce.SHA256_IV[3]|0,this.E=ce.SHA256_IV[4]|0,this.F=ce.SHA256_IV[5]|0,this.G=ce.SHA256_IV[6]|0,this.H=ce.SHA256_IV[7]|0}get(){const{A:e,B:r,C:n,D:s,E:i,F:a,G:o,H:c}=this;return[e,r,n,s,i,a,o,c]}set(e,r,n,s,i,a,o,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=s|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=c|0}process(e,r){for(let f=0;f<16;f++,r+=4)zn[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){const p=zn[f-15],d=zn[f-2],b=(0,Ze.rotr)(p,7)^(0,Ze.rotr)(p,18)^p>>>3,g=(0,Ze.rotr)(d,17)^(0,Ze.rotr)(d,19)^d>>>10;zn[f]=g+zn[f-7]+b+zn[f-16]|0}let{A:n,B:s,C:i,D:a,E:o,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){const p=(0,Ze.rotr)(o,6)^(0,Ze.rotr)(o,11)^(0,Ze.rotr)(o,25),d=l+p+(0,ce.Chi)(o,c,u)+Bv[f]+zn[f]|0,g=((0,Ze.rotr)(n,2)^(0,Ze.rotr)(n,13)^(0,Ze.rotr)(n,22))+(0,ce.Maj)(n,s,i)|0;l=u,u=c,c=o,o=a+d|0,a=i,i=s,s=n,n=d+g|0}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,s,i,a,o,c,u,l)}roundClean(){(0,Ze.clean)(zn)}destroy(){this.set(0,0,0,0,0,0,0,0),(0,Ze.clean)(this.buffer)}};Ue.SHA256=ch;class _b extends ch{constructor(){super(28),this.A=ce.SHA224_IV[0]|0,this.B=ce.SHA224_IV[1]|0,this.C=ce.SHA224_IV[2]|0,this.D=ce.SHA224_IV[3]|0,this.E=ce.SHA224_IV[4]|0,this.F=ce.SHA224_IV[5]|0,this.G=ce.SHA224_IV[6]|0,this.H=ce.SHA224_IV[7]|0}}Ue.SHA224=_b;const Ib=ye.split(["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(t=>BigInt(t))),Cv=Ib[0],Rv=Ib[1],Vn=new Uint32Array(80),Gn=new Uint32Array(80);class Ao extends ce.HashMD{constructor(e=64){super(128,e,16,!1),this.Ah=ce.SHA512_IV[0]|0,this.Al=ce.SHA512_IV[1]|0,this.Bh=ce.SHA512_IV[2]|0,this.Bl=ce.SHA512_IV[3]|0,this.Ch=ce.SHA512_IV[4]|0,this.Cl=ce.SHA512_IV[5]|0,this.Dh=ce.SHA512_IV[6]|0,this.Dl=ce.SHA512_IV[7]|0,this.Eh=ce.SHA512_IV[8]|0,this.El=ce.SHA512_IV[9]|0,this.Fh=ce.SHA512_IV[10]|0,this.Fl=ce.SHA512_IV[11]|0,this.Gh=ce.SHA512_IV[12]|0,this.Gl=ce.SHA512_IV[13]|0,this.Hh=ce.SHA512_IV[14]|0,this.Hl=ce.SHA512_IV[15]|0}get(){const{Ah:e,Al:r,Bh:n,Bl:s,Ch:i,Cl:a,Dh:o,Dl:c,Eh:u,El:l,Fh:f,Fl:p,Gh:d,Gl:b,Hh:g,Hl:A}=this;return[e,r,n,s,i,a,o,c,u,l,f,p,d,b,g,A]}set(e,r,n,s,i,a,o,c,u,l,f,p,d,b,g,A){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=s|0,this.Ch=i|0,this.Cl=a|0,this.Dh=o|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=p|0,this.Gh=d|0,this.Gl=b|0,this.Hh=g|0,this.Hl=A|0}process(e,r){for(let v=0;v<16;v++,r+=4)Vn[v]=e.getUint32(r),Gn[v]=e.getUint32(r+=4);for(let v=16;v<80;v++){const w=Vn[v-15]|0,x=Gn[v-15]|0,_=ye.rotrSH(w,x,1)^ye.rotrSH(w,x,8)^ye.shrSH(w,x,7),I=ye.rotrSL(w,x,1)^ye.rotrSL(w,x,8)^ye.shrSL(w,x,7),N=Vn[v-2]|0,C=Gn[v-2]|0,j=ye.rotrSH(N,C,19)^ye.rotrBH(N,C,61)^ye.shrSH(N,C,6),M=ye.rotrSL(N,C,19)^ye.rotrBL(N,C,61)^ye.shrSL(N,C,6),H=ye.add4L(I,M,Gn[v-7],Gn[v-16]),V=ye.add4H(H,_,j,Vn[v-7],Vn[v-16]);Vn[v]=V|0,Gn[v]=H|0}let{Ah:n,Al:s,Bh:i,Bl:a,Ch:o,Cl:c,Dh:u,Dl:l,Eh:f,El:p,Fh:d,Fl:b,Gh:g,Gl:A,Hh:S,Hl:T}=this;for(let v=0;v<80;v++){const w=ye.rotrSH(f,p,14)^ye.rotrSH(f,p,18)^ye.rotrBH(f,p,41),x=ye.rotrSL(f,p,14)^ye.rotrSL(f,p,18)^ye.rotrBL(f,p,41),_=f&d^~f&g,I=p&b^~p&A,N=ye.add5L(T,x,I,Rv[v],Gn[v]),C=ye.add5H(N,S,w,_,Cv[v],Vn[v]),j=N|0,M=ye.rotrSH(n,s,28)^ye.rotrBH(n,s,34)^ye.rotrBH(n,s,39),H=ye.rotrSL(n,s,28)^ye.rotrBL(n,s,34)^ye.rotrBL(n,s,39),V=n&i^n&o^i&o,Q=s&a^s&c^a&c;S=g|0,T=A|0,g=d|0,A=b|0,d=f|0,b=p|0,{h:f,l:p}=ye.add(u|0,l|0,C|0,j|0),u=o|0,l=c|0,o=i|0,c=a|0,i=n|0,a=s|0;const U=ye.add3L(j,H,Q);n=ye.add3H(U,C,M,V),s=U|0}({h:n,l:s}=ye.add(this.Ah|0,this.Al|0,n|0,s|0)),{h:i,l:a}=ye.add(this.Bh|0,this.Bl|0,i|0,a|0),{h:o,l:c}=ye.add(this.Ch|0,this.Cl|0,o|0,c|0),{h:u,l}=ye.add(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:p}=ye.add(this.Eh|0,this.El|0,f|0,p|0),{h:d,l:b}=ye.add(this.Fh|0,this.Fl|0,d|0,b|0),{h:g,l:A}=ye.add(this.Gh|0,this.Gl|0,g|0,A|0),{h:S,l:T}=ye.add(this.Hh|0,this.Hl|0,S|0,T|0),this.set(n,s,i,a,o,c,u,l,f,p,d,b,g,A,S,T)}roundClean(){(0,Ze.clean)(Vn,Gn)}destroy(){(0,Ze.clean)(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}Ue.SHA512=Ao;class Pb extends Ao{constructor(){super(48),this.Ah=ce.SHA384_IV[0]|0,this.Al=ce.SHA384_IV[1]|0,this.Bh=ce.SHA384_IV[2]|0,this.Bl=ce.SHA384_IV[3]|0,this.Ch=ce.SHA384_IV[4]|0,this.Cl=ce.SHA384_IV[5]|0,this.Dh=ce.SHA384_IV[6]|0,this.Dl=ce.SHA384_IV[7]|0,this.Eh=ce.SHA384_IV[8]|0,this.El=ce.SHA384_IV[9]|0,this.Fh=ce.SHA384_IV[10]|0,this.Fl=ce.SHA384_IV[11]|0,this.Gh=ce.SHA384_IV[12]|0,this.Gl=ce.SHA384_IV[13]|0,this.Hh=ce.SHA384_IV[14]|0,this.Hl=ce.SHA384_IV[15]|0}}Ue.SHA384=Pb;const gt=Uint32Array.from([2352822216,424955298,1944164710,2312950998,502970286,855612546,1738396948,1479516111,258812777,2077511080,2011393907,79989058,1067287976,1780299464,286451373,2446758561]),wt=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class Ob extends Ao{constructor(){super(28),this.Ah=gt[0]|0,this.Al=gt[1]|0,this.Bh=gt[2]|0,this.Bl=gt[3]|0,this.Ch=gt[4]|0,this.Cl=gt[5]|0,this.Dh=gt[6]|0,this.Dl=gt[7]|0,this.Eh=gt[8]|0,this.El=gt[9]|0,this.Fh=gt[10]|0,this.Fl=gt[11]|0,this.Gh=gt[12]|0,this.Gl=gt[13]|0,this.Hh=gt[14]|0,this.Hl=gt[15]|0}}Ue.SHA512_224=Ob;class Bb extends Ao{constructor(){super(32),this.Ah=wt[0]|0,this.Al=wt[1]|0,this.Bh=wt[2]|0,this.Bl=wt[3]|0,this.Ch=wt[4]|0,this.Cl=wt[5]|0,this.Dh=wt[6]|0,this.Dl=wt[7]|0,this.Eh=wt[8]|0,this.El=wt[9]|0,this.Fh=wt[10]|0,this.Fl=wt[11]|0,this.Gh=wt[12]|0,this.Gl=wt[13]|0,this.Hh=wt[14]|0,this.Hl=wt[15]|0}}Ue.SHA512_256=Bb;Ue.sha256=(0,Ze.createHasher)(()=>new ch);Ue.sha224=(0,Ze.createHasher)(()=>new _b);Ue.sha512=(0,Ze.createHasher)(()=>new Ao);Ue.sha384=(0,Ze.createHasher)(()=>new Pb);Ue.sha512_256=(0,Ze.createHasher)(()=>new Bb);Ue.sha512_224=(0,Ze.createHasher)(()=>new Ob);Object.defineProperty(Ir,"__esModule",{value:!0});Ir.sha224=Ir.SHA224=Ir.sha256=Ir.SHA256=void 0;const Jc=Ue;Ir.SHA256=Jc.SHA256;Ir.sha256=Jc.sha256;Ir.SHA224=Jc.SHA224;Ir.sha224=Jc.sha224;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.taggedHash=t.TAGGED_HASH_PREFIXES=t.TAGS=t.hash256=t.hash160=t.sha256=t.sha1=t.ripemd160=void 0;const e=Hi,r=Li,n=Ir;function s(l){return Buffer.from((0,e.ripemd160)(Uint8Array.from(l)))}t.ripemd160=s;function i(l){return Buffer.from((0,r.sha1)(Uint8Array.from(l)))}t.sha1=i;function a(l){return Buffer.from((0,n.sha256)(Uint8Array.from(l)))}t.sha256=a;function o(l){return Buffer.from((0,e.ripemd160)((0,n.sha256)(Uint8Array.from(l))))}t.hash160=o;function c(l){return Buffer.from((0,n.sha256)((0,n.sha256)(Uint8Array.from(l))))}t.hash256=c,t.TAGS=["BIP0340/challenge","BIP0340/aux","BIP0340/nonce","TapLeaf","TapBranch","TapSighash","TapTweak","KeyAgg list","KeyAgg coefficient"],t.TAGGED_HASH_PREFIXES={"BIP0340/challenge":Buffer.from([123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124,123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124]),"BIP0340/aux":Buffer.from([241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144,241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144]),"BIP0340/nonce":Buffer.from([7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47,7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47]),TapLeaf:Buffer.from([174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238,174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238]),TapBranch:Buffer.from([25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21,25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21]),TapSighash:Buffer.from([244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49,244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49]),TapTweak:Buffer.from([232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233,232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233]),"KeyAgg list":Buffer.from([72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240,72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240]),"KeyAgg coefficient":Buffer.from([191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129,191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129])};function u(l,f){return a(Buffer.concat([t.TAGGED_HASH_PREFIXES[l],f]))}t.taggedHash=u})(vs);var qu={},In={};Object.defineProperty(In,"__esModule",{value:!0});In.encode=In.decode=In.check=void 0;function Nv(t){if(t.length<8||t.length>72||t[0]!==48||t[1]!==t.length-2||t[2]!==2)return!1;const e=t[3];if(e===0||5+e>=t.length||t[4+e]!==2)return!1;const r=t[5+e];return!(r===0||6+e+r!==t.length||t[4]&128||e>1&&t[4]===0&&!(t[5]&128)||t[e+6]&128||r>1&&t[e+6]===0&&!(t[e+7]&128))}In.check=Nv;function Uv(t){if(t.length<8)throw new Error("DER sequence length is too short");if(t.length>72)throw new Error("DER sequence length is too long");if(t[0]!==48)throw new Error("Expected DER sequence");if(t[1]!==t.length-2)throw new Error("DER sequence length is invalid");if(t[2]!==2)throw new Error("Expected DER integer");const e=t[3];if(e===0)throw new Error("R length is zero");if(5+e>=t.length)throw new Error("R length is too long");if(t[4+e]!==2)throw new Error("Expected DER integer (2)");const r=t[5+e];if(r===0)throw new Error("S length is zero");if(6+e+r!==t.length)throw new Error("S length is invalid");if(t[4]&128)throw new Error("R value is negative");if(e>1&&t[4]===0&&!(t[5]&128))throw new Error("R value excessively padded");if(t[e+6]&128)throw new Error("S value is negative");if(r>1&&t[e+6]===0&&!(t[e+7]&128))throw new Error("S value excessively padded");return{r:t.slice(4,4+e),s:t.slice(6+e)}}In.decode=Uv;function Fv(t,e){const r=t.length,n=e.length;if(r===0)throw new Error("R length is zero");if(n===0)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(t[0]&128)throw new Error("R value is negative");if(e[0]&128)throw new Error("S value is negative");if(r>1&&t[0]===0&&!(t[1]&128))throw new Error("R value excessively padded");if(n>1&&e[0]===0&&!(e[1]&128))throw new Error("S value excessively padded");const s=Buffer.allocUnsafe(6+r+n);return s[0]=48,s[1]=s.length-2,s[2]=2,s[3]=t.length,t.copy(s,4),s[4+r]=2,s[5+r]=e.length,e.copy(s,6+r),s}In.encode=Fv;var Ws={};Object.defineProperty(Ws,"__esModule",{value:!0});Ws.REVERSE_OPS=Ws.OPS=void 0;const Yf={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP3:178,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_CHECKSIGADD:186,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255};Ws.OPS=Yf;const Cb={};Ws.REVERSE_OPS=Cb;for(const t of Object.keys(Yf)){const e=Yf[t];Cb[e]=t}var fs={};Object.defineProperty(fs,"__esModule",{value:!0});fs.decode=fs.encode=fs.encodingLength=void 0;const os=Ws;function Rb(t){return t<os.OPS.OP_PUSHDATA1?1:t<=255?2:t<=65535?3:5}fs.encodingLength=Rb;function Mv(t,e,r){const n=Rb(e);return n===1?t.writeUInt8(e,r):n===2?(t.writeUInt8(os.OPS.OP_PUSHDATA1,r),t.writeUInt8(e,r+1)):n===3?(t.writeUInt8(os.OPS.OP_PUSHDATA2,r),t.writeUInt16LE(e,r+1)):(t.writeUInt8(os.OPS.OP_PUSHDATA4,r),t.writeUInt32LE(e,r+1)),n}fs.encode=Mv;function $v(t,e){const r=t.readUInt8(e);let n,s;if(r<os.OPS.OP_PUSHDATA1)n=r,s=1;else if(r===os.OPS.OP_PUSHDATA1){if(e+2>t.length)return null;n=t.readUInt8(e+1),s=2}else if(r===os.OPS.OP_PUSHDATA2){if(e+3>t.length)return null;n=t.readUInt16LE(e+1),s=3}else{if(e+5>t.length)return null;if(r!==os.OPS.OP_PUSHDATA4)throw new Error("Unexpected opcode");n=t.readUInt32LE(e+1),s=5}return{opcode:r,number:n,size:s}}fs.decode=$v;var Di={};Object.defineProperty(Di,"__esModule",{value:!0});Di.encode=Di.decode=void 0;function jv(t,e,r){e=e||4,r=r===void 0?!0:r;const n=t.length;if(n===0)return 0;if(n>e)throw new TypeError("Script number overflow");if(r&&!(t[n-1]&127)&&(n<=1||!(t[n-2]&128)))throw new Error("Non-minimally encoded script number");if(n===5){const i=t.readUInt32LE(0),a=t.readUInt8(4);return a&128?-((a&-129)*4294967296+i):a*4294967296+i}let s=0;for(let i=0;i<n;++i)s|=t[i]<<8*i;return t[n-1]&128?-(s&~(128<<8*(n-1))):s}Di.decode=jv;function Hv(t){return t>2147483647?5:t>8388607?4:t>32767?3:t>127?2:t>0?1:0}function Lv(t){let e=Math.abs(t);const r=Hv(e),n=Buffer.allocUnsafe(r),s=t<0;for(let i=0;i<r;++i)n.writeUInt8(e&255,i),e>>=8;return n[r-1]&128?n.writeUInt8(s?128:0,r-1):s&&(n[r-1]|=128),n}Di.encode=Lv;var Is={},W0;function Dv(){if(W0)return Is;W0=1,Object.defineProperty(Is,"__esModule",{value:!0}),Is.encode=Is.decode=void 0;const t=In,e=ar(),r=kt,{typeforce:n}=r,s=Buffer.alloc(1,0);function i(u){let l=0;for(;u[l]===0;)++l;return l===u.length?s:(u=u.slice(l),u[0]&128?Buffer.concat([s,u],1+u.length):u)}function a(u){u[0]===0&&(u=u.slice(1));const l=Buffer.alloc(32,0),f=Math.max(0,32-u.length);return u.copy(l,f),l}function o(u){const l=u.readUInt8(u.length-1);if(!(0,e.isDefinedHashType)(l))throw new Error("Invalid hashType "+l);const f=t.decode(u.slice(0,-1)),p=a(f.r),d=a(f.s);return{signature:Buffer.concat([p,d],64),hashType:l}}Is.decode=o;function c(u,l){if(n({signature:r.BufferN(64),hashType:r.UInt8},{signature:u,hashType:l}),!(0,e.isDefinedHashType)(l))throw new Error("Invalid hashType "+l);const f=Buffer.allocUnsafe(1);f.writeUInt8(l,0);const p=i(u.slice(0,32)),d=i(u.slice(32,64));return Buffer.concat([t.encode(p,d),f])}return Is.encode=c,Is}var K0;function ar(){return K0||(K0=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.signature=t.number=t.isCanonicalScriptSignature=t.isDefinedHashType=t.isCanonicalPubKey=t.toStack=t.fromASM=t.toASM=t.decompile=t.compile=t.countNonPushOnlyOPs=t.isPushOnly=t.OPS=void 0;const e=In,r=Ws;Object.defineProperty(t,"OPS",{enumerable:!0,get:function(){return r.OPS}});const n=fs,s=Di,i=Dv(),a=kt,{typeforce:o}=a,c=r.OPS.OP_RESERVED;function u(C){return a.Number(C)&&(C===r.OPS.OP_0||C>=r.OPS.OP_1&&C<=r.OPS.OP_16||C===r.OPS.OP_1NEGATE)}function l(C){return a.Buffer(C)||u(C)}function f(C){return a.Array(C)&&C.every(l)}t.isPushOnly=f;function p(C){return C.length-C.filter(l).length}t.countNonPushOnlyOPs=p;function d(C){if(C.length===0)return r.OPS.OP_0;if(C.length===1){if(C[0]>=1&&C[0]<=16)return c+C[0];if(C[0]===129)return r.OPS.OP_1NEGATE}}function b(C){return Buffer.isBuffer(C)}function g(C){return a.Array(C)}function A(C){return Buffer.isBuffer(C)}function S(C){if(b(C))return C;o(a.Array,C);const j=C.reduce((V,Q)=>A(Q)?Q.length===1&&d(Q)!==void 0?V+1:V+n.encodingLength(Q.length)+Q.length:V+1,0),M=Buffer.allocUnsafe(j);let H=0;if(C.forEach(V=>{if(A(V)){const Q=d(V);if(Q!==void 0){M.writeUInt8(Q,H),H+=1;return}H+=n.encode(M,V.length,H),V.copy(M,H),H+=V.length}else M.writeUInt8(V,H),H+=1}),H!==M.length)throw new Error("Could not decode chunks");return M}t.compile=S;function T(C){if(g(C))return C;o(a.Buffer,C);const j=[];let M=0;for(;M<C.length;){const H=C[M];if(H>r.OPS.OP_0&&H<=r.OPS.OP_PUSHDATA4){const V=n.decode(C,M);if(V===null||(M+=V.size,M+V.number>C.length))return null;const Q=C.slice(M,M+V.number);M+=V.number;const U=d(Q);U!==void 0?j.push(U):j.push(Q)}else j.push(H),M+=1}return j}t.decompile=T;function v(C){if(b(C)&&(C=T(C)),!C)throw new Error("Could not convert invalid chunks to ASM");return C.map(j=>{if(A(j)){const M=d(j);if(M===void 0)return j.toString("hex");j=M}return r.REVERSE_OPS[j]}).join(" ")}t.toASM=v;function w(C){return o(a.String,C),S(C.split(" ").map(j=>r.OPS[j]!==void 0?r.OPS[j]:(o(a.Hex,j),Buffer.from(j,"hex"))))}t.fromASM=w;function x(C){return C=T(C),o(f,C),C.map(j=>A(j)?j:j===r.OPS.OP_0?Buffer.allocUnsafe(0):s.encode(j-c))}t.toStack=x;function _(C){return a.isPoint(C)}t.isCanonicalPubKey=_;function I(C){const j=C&-129;return j>0&&j<4}t.isDefinedHashType=I;function N(C){return!Buffer.isBuffer(C)||!I(C[C.length-1])?!1:e.check(C.slice(0,-1))}t.isCanonicalScriptSignature=N,t.number=s,t.signature=i}(qu)),qu}Object.defineProperty(Eo,"__esModule",{value:!0});Eo.Transaction=void 0;const Je=pt,Pt=vs,X0=ar(),zv=ar(),Ae=kt,{typeforce:zr}=Ae;function Xr(t){const e=t.length;return Je.varuint.encodingLength(e)+e}function Vv(t){const e=t.length;return Je.varuint.encodingLength(e)+t.reduce((r,n)=>r+Xr(n),0)}const Qn=Buffer.allocUnsafe(0),Wu=[],Ku=Buffer.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),Y0=Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),Gv=Buffer.from("ffffffffffffffff","hex"),qv={script:Qn,valueBuffer:Gv};function Wv(t){return t.value!==void 0}let Mr=class Pe{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(e,r){const n=new Je.BufferReader(e),s=new Pe;s.version=n.readInt32();const i=n.readUInt8(),a=n.readUInt8();let o=!1;i===Pe.ADVANCED_TRANSACTION_MARKER&&a===Pe.ADVANCED_TRANSACTION_FLAG?o=!0:n.offset-=2;const c=n.readVarInt();for(let l=0;l<c;++l)s.ins.push({hash:n.readSlice(32),index:n.readUInt32(),script:n.readVarSlice(),sequence:n.readUInt32(),witness:Wu});const u=n.readVarInt();for(let l=0;l<u;++l)s.outs.push({value:n.readUInt64(),script:n.readVarSlice()});if(o){for(let l=0;l<c;++l)s.ins[l].witness=n.readVector();if(!s.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(s.locktime=n.readUInt32(),r)return s;if(n.offset!==e.length)throw new Error("Transaction has unexpected data");return s}static fromHex(e){return Pe.fromBuffer(Buffer.from(e,"hex"),!1)}static isCoinbaseHash(e){zr(Ae.Hash256bit,e);for(let r=0;r<32;++r)if(e[r]!==0)return!1;return!0}isCoinbase(){return this.ins.length===1&&Pe.isCoinbaseHash(this.ins[0].hash)}addInput(e,r,n,s){return zr(Ae.tuple(Ae.Hash256bit,Ae.UInt32,Ae.maybe(Ae.UInt32),Ae.maybe(Ae.Buffer)),arguments),Ae.Null(n)&&(n=Pe.DEFAULT_SEQUENCE),this.ins.push({hash:e,index:r,script:s||Qn,sequence:n,witness:Wu})-1}addOutput(e,r){return zr(Ae.tuple(Ae.Buffer,Ae.Satoshi),arguments),this.outs.push({script:e,value:r})-1}hasWitnesses(){return this.ins.some(e=>e.witness.length!==0)}stripWitnesses(){this.ins.forEach(e=>{e.witness=Wu})}weight(){const e=this.byteLength(!1),r=this.byteLength(!0);return e*3+r}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(e=!0){const r=e&&this.hasWitnesses();return(r?10:8)+Je.varuint.encodingLength(this.ins.length)+Je.varuint.encodingLength(this.outs.length)+this.ins.reduce((n,s)=>n+40+Xr(s.script),0)+this.outs.reduce((n,s)=>n+8+Xr(s.script),0)+(r?this.ins.reduce((n,s)=>n+Vv(s.witness),0):0)}clone(){const e=new Pe;return e.version=this.version,e.locktime=this.locktime,e.ins=this.ins.map(r=>({hash:r.hash,index:r.index,script:r.script,sequence:r.sequence,witness:r.witness})),e.outs=this.outs.map(r=>({script:r.script,value:r.value})),e}hashForSignature(e,r,n){if(zr(Ae.tuple(Ae.UInt32,Ae.Buffer,Ae.Number),arguments),e>=this.ins.length)return Y0;const s=X0.compile(X0.decompile(r).filter(o=>o!==zv.OPS.OP_CODESEPARATOR)),i=this.clone();if((n&31)===Pe.SIGHASH_NONE)i.outs=[],i.ins.forEach((o,c)=>{c!==e&&(o.sequence=0)});else if((n&31)===Pe.SIGHASH_SINGLE){if(e>=this.outs.length)return Y0;i.outs.length=e+1;for(let o=0;o<e;o++)i.outs[o]=qv;i.ins.forEach((o,c)=>{c!==e&&(o.sequence=0)})}n&Pe.SIGHASH_ANYONECANPAY?(i.ins=[i.ins[e]],i.ins[0].script=s):(i.ins.forEach(o=>{o.script=Qn}),i.ins[e].script=s);const a=Buffer.allocUnsafe(i.byteLength(!1)+4);return a.writeInt32LE(n,a.length-4),i.__toBuffer(a,0,!1),Pt.hash256(a)}hashForWitnessV1(e,r,n,s,i,a){if(zr(Ae.tuple(Ae.UInt32,zr.arrayOf(Ae.Buffer),zr.arrayOf(Ae.Satoshi),Ae.UInt32),arguments),n.length!==this.ins.length||r.length!==this.ins.length)throw new Error("Must supply prevout script and value for all inputs");const o=s===Pe.SIGHASH_DEFAULT?Pe.SIGHASH_ALL:s&Pe.SIGHASH_OUTPUT_MASK,u=(s&Pe.SIGHASH_INPUT_MASK)===Pe.SIGHASH_ANYONECANPAY,l=o===Pe.SIGHASH_NONE,f=o===Pe.SIGHASH_SINGLE;let p=Qn,d=Qn,b=Qn,g=Qn,A=Qn;if(!u){let w=Je.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(x=>{w.writeSlice(x.hash),w.writeUInt32(x.index)}),p=Pt.sha256(w.end()),w=Je.BufferWriter.withCapacity(8*this.ins.length),n.forEach(x=>w.writeUInt64(x)),d=Pt.sha256(w.end()),w=Je.BufferWriter.withCapacity(r.map(Xr).reduce((x,_)=>x+_)),r.forEach(x=>w.writeVarSlice(x)),b=Pt.sha256(w.end()),w=Je.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(x=>w.writeUInt32(x.sequence)),g=Pt.sha256(w.end())}if(l||f){if(f&&e<this.outs.length){const w=this.outs[e],x=Je.BufferWriter.withCapacity(8+Xr(w.script));x.writeUInt64(w.value),x.writeVarSlice(w.script),A=Pt.sha256(x.end())}}else{const w=this.outs.map(_=>8+Xr(_.script)).reduce((_,I)=>_+I),x=Je.BufferWriter.withCapacity(w);this.outs.forEach(_=>{x.writeUInt64(_.value),x.writeVarSlice(_.script)}),A=Pt.sha256(x.end())}const S=(i?2:0)+(a?1:0),T=174-(u?49:0)-(l?32:0)+(a?32:0)+(i?37:0),v=Je.BufferWriter.withCapacity(T);if(v.writeUInt8(s),v.writeInt32(this.version),v.writeUInt32(this.locktime),v.writeSlice(p),v.writeSlice(d),v.writeSlice(b),v.writeSlice(g),l||f||v.writeSlice(A),v.writeUInt8(S),u){const w=this.ins[e];v.writeSlice(w.hash),v.writeUInt32(w.index),v.writeUInt64(n[e]),v.writeVarSlice(r[e]),v.writeUInt32(w.sequence)}else v.writeUInt32(e);if(a){const w=Je.BufferWriter.withCapacity(Xr(a));w.writeVarSlice(a),v.writeSlice(Pt.sha256(w.end()))}return f&&v.writeSlice(A),i&&(v.writeSlice(i),v.writeUInt8(0),v.writeUInt32(4294967295)),Pt.taggedHash("TapSighash",Buffer.concat([Buffer.from([0]),v.end()]))}hashForWitnessV0(e,r,n,s){zr(Ae.tuple(Ae.UInt32,Ae.Buffer,Ae.Satoshi,Ae.UInt32),arguments);let i=Buffer.from([]),a,o=Ku,c=Ku,u=Ku;if(s&Pe.SIGHASH_ANYONECANPAY||(i=Buffer.allocUnsafe(36*this.ins.length),a=new Je.BufferWriter(i,0),this.ins.forEach(f=>{a.writeSlice(f.hash),a.writeUInt32(f.index)}),c=Pt.hash256(i)),!(s&Pe.SIGHASH_ANYONECANPAY)&&(s&31)!==Pe.SIGHASH_SINGLE&&(s&31)!==Pe.SIGHASH_NONE&&(i=Buffer.allocUnsafe(4*this.ins.length),a=new Je.BufferWriter(i,0),this.ins.forEach(f=>{a.writeUInt32(f.sequence)}),u=Pt.hash256(i)),(s&31)!==Pe.SIGHASH_SINGLE&&(s&31)!==Pe.SIGHASH_NONE){const f=this.outs.reduce((p,d)=>p+8+Xr(d.script),0);i=Buffer.allocUnsafe(f),a=new Je.BufferWriter(i,0),this.outs.forEach(p=>{a.writeUInt64(p.value),a.writeVarSlice(p.script)}),o=Pt.hash256(i)}else if((s&31)===Pe.SIGHASH_SINGLE&&e<this.outs.length){const f=this.outs[e];i=Buffer.allocUnsafe(8+Xr(f.script)),a=new Je.BufferWriter(i,0),a.writeUInt64(f.value),a.writeVarSlice(f.script),o=Pt.hash256(i)}i=Buffer.allocUnsafe(156+Xr(r)),a=new Je.BufferWriter(i,0);const l=this.ins[e];return a.writeInt32(this.version),a.writeSlice(c),a.writeSlice(u),a.writeSlice(l.hash),a.writeUInt32(l.index),a.writeVarSlice(r),a.writeUInt64(n),a.writeUInt32(l.sequence),a.writeSlice(o),a.writeUInt32(this.locktime),a.writeUInt32(s),Pt.hash256(i)}getHash(e){return e&&this.isCoinbase()?Buffer.alloc(32,0):Pt.hash256(this.__toBuffer(void 0,void 0,e))}getId(){return(0,Je.reverseBuffer)(this.getHash(!1)).toString("hex")}toBuffer(e,r){return this.__toBuffer(e,r,!0)}toHex(){return this.toBuffer(void 0,void 0).toString("hex")}setInputScript(e,r){zr(Ae.tuple(Ae.Number,Ae.Buffer),arguments),this.ins[e].script=r}setWitness(e,r){zr(Ae.tuple(Ae.Number,[Ae.Buffer]),arguments),this.ins[e].witness=r}__toBuffer(e,r,n=!1){e||(e=Buffer.allocUnsafe(this.byteLength(n)));const s=new Je.BufferWriter(e,r||0);s.writeInt32(this.version);const i=n&&this.hasWitnesses();return i&&(s.writeUInt8(Pe.ADVANCED_TRANSACTION_MARKER),s.writeUInt8(Pe.ADVANCED_TRANSACTION_FLAG)),s.writeVarInt(this.ins.length),this.ins.forEach(a=>{s.writeSlice(a.hash),s.writeUInt32(a.index),s.writeVarSlice(a.script),s.writeUInt32(a.sequence)}),s.writeVarInt(this.outs.length),this.outs.forEach(a=>{Wv(a)?s.writeUInt64(a.value):s.writeSlice(a.valueBuffer),s.writeVarSlice(a.script)}),i&&this.ins.forEach(a=>{s.writeVector(a.witness)}),s.writeUInt32(this.locktime),r!==void 0?e.slice(r,s.offset):e}};Eo.Transaction=Mr;Mr.DEFAULT_SEQUENCE=4294967295;Mr.SIGHASH_DEFAULT=0;Mr.SIGHASH_ALL=1;Mr.SIGHASH_NONE=2;Mr.SIGHASH_SINGLE=3;Mr.SIGHASH_ANYONECANPAY=128;Mr.SIGHASH_OUTPUT_MASK=3;Mr.SIGHASH_INPUT_MASK=128;Mr.ADVANCED_TRANSACTION_MARKER=0;Mr.ADVANCED_TRANSACTION_FLAG=1;var Be={},So={};Object.defineProperty(So,"__esModule",{value:!0});const Kv=9007199254740991;function uh(t){if(t<0||t>Kv||t%1!==0)throw new RangeError("value out of range")}function wa(t,e,r){if(uh(t),e||(e=Buffer.allocUnsafe(Nb(t))),!Buffer.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");return r||(r=0),t<253?(e.writeUInt8(t,r),Object.assign(wa,{bytes:1})):t<=65535?(e.writeUInt8(253,r),e.writeUInt16LE(t,r+1),Object.assign(wa,{bytes:3})):t<=4294967295?(e.writeUInt8(254,r),e.writeUInt32LE(t,r+1),Object.assign(wa,{bytes:5})):(e.writeUInt8(255,r),e.writeUInt32LE(t>>>0,r+1),e.writeUInt32LE(t/4294967296|0,r+5),Object.assign(wa,{bytes:9})),e}So.encode=wa;function va(t,e){if(!Buffer.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");e||(e=0);const r=t.readUInt8(e);if(r<253)return Object.assign(va,{bytes:1}),r;if(r===253)return Object.assign(va,{bytes:3}),t.readUInt16LE(e+1);if(r===254)return Object.assign(va,{bytes:5}),t.readUInt32LE(e+1);{Object.assign(va,{bytes:9});const n=t.readUInt32LE(e+1),i=t.readUInt32LE(e+5)*4294967296+n;return uh(i),i}}So.decode=va;function Nb(t){return uh(t),t<253?1:t<=65535?3:t<=4294967295?5:9}So.encodingLength=Nb;var Xu={},Zc={},xt={};Object.defineProperty(xt,"__esModule",{value:!0});xt.testnet=xt.regtest=xt.bitcoin=void 0;xt.bitcoin={messagePrefix:`Bitcoin Signed Message:
7
7
  `,bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128};xt.regtest={messagePrefix:`Bitcoin Signed Message:
8
8
  `,bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};xt.testnet={messagePrefix:`Bitcoin Signed Message:
9
- `,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var nr={};Object.defineProperty(nr,"__esModule",{value:!0});nr.value=nr.prop=void 0;function Wv(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get(){const n=r.call(this);return this[e]=n,n},set(n){Object.defineProperty(this,e,{configurable:!0,enumerable:!0,value:n,writable:!0})}})}nr.prop=Wv;function Kv(t){let e;return()=>(e!==void 0||(e=t()),e)}nr.value=Kv;Object.defineProperty(Yc,"__esModule",{value:!0});Yc.p2data=void 0;const Xv=xt,bc=ar(),Vr=kt,X0=nr,Y0=bc.OPS;function Yv(t,e){if(!t.data&&!t.output)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Vr.typeforce)({network:Vr.typeforce.maybe(Vr.typeforce.Object),output:Vr.typeforce.maybe(Vr.typeforce.Buffer),data:Vr.typeforce.maybe(Vr.typeforce.arrayOf(Vr.typeforce.Buffer))},t);const n={name:"embed",network:t.network||Xv.bitcoin};if(X0.prop(n,"output",()=>{if(t.data)return bc.compile([Y0.OP_RETURN].concat(t.data))}),X0.prop(n,"data",()=>{if(t.output)return bc.decompile(t.output).slice(1)}),e.validate&&t.output){const s=bc.decompile(t.output);if(s[0]!==Y0.OP_RETURN)throw new TypeError("Output is invalid");if(!s.slice(1).every(Vr.typeforce.Buffer))throw new TypeError("Output is invalid");if(t.data&&!(0,Vr.stacksEqual)(t.data,n.data))throw new TypeError("Data mismatch")}return Object.assign(n,t)}Yc.p2data=Yv;var Jc={};Object.defineProperty(Jc,"__esModule",{value:!0});Jc.p2ms=void 0;const Jv=xt,bi=ar(),Xe=kt,Gn=nr,gi=bi.OPS,Yo=gi.OP_RESERVED;function Zv(t,e){if(!t.input&&!t.output&&!(t.pubkeys&&t.m!==void 0)&&!t.signatures)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{});function r(c){return bi.isCanonicalScriptSignature(c)||(e.allowIncomplete&&c===gi.OP_0)!==void 0}(0,Xe.typeforce)({network:Xe.typeforce.maybe(Xe.typeforce.Object),m:Xe.typeforce.maybe(Xe.typeforce.Number),n:Xe.typeforce.maybe(Xe.typeforce.Number),output:Xe.typeforce.maybe(Xe.typeforce.Buffer),pubkeys:Xe.typeforce.maybe(Xe.typeforce.arrayOf(Xe.isPoint)),signatures:Xe.typeforce.maybe(Xe.typeforce.arrayOf(r)),input:Xe.typeforce.maybe(Xe.typeforce.Buffer)},t);const s={network:t.network||Jv.bitcoin};let i=[],a=!1;function o(c){a||(a=!0,i=bi.decompile(c),s.m=i[0]-Yo,s.n=i[i.length-2]-Yo,s.pubkeys=i.slice(1,-2))}if(Gn.prop(s,"output",()=>{if(t.m&&s.n&&t.pubkeys)return bi.compile([].concat(Yo+t.m,t.pubkeys,Yo+s.n,gi.OP_CHECKMULTISIG))}),Gn.prop(s,"m",()=>{if(s.output)return o(s.output),s.m}),Gn.prop(s,"n",()=>{if(s.pubkeys)return s.pubkeys.length}),Gn.prop(s,"pubkeys",()=>{if(t.output)return o(t.output),s.pubkeys}),Gn.prop(s,"signatures",()=>{if(t.input)return bi.decompile(t.input).slice(1)}),Gn.prop(s,"input",()=>{if(t.signatures)return bi.compile([gi.OP_0].concat(t.signatures))}),Gn.prop(s,"witness",()=>{if(s.input)return[]}),Gn.prop(s,"name",()=>{if(!(!s.m||!s.n))return`p2ms(${s.m} of ${s.n})`}),e.validate){if(t.output){if(o(t.output),!Xe.typeforce.Number(i[0]))throw new TypeError("Output is invalid");if(!Xe.typeforce.Number(i[i.length-2]))throw new TypeError("Output is invalid");if(i[i.length-1]!==gi.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(s.m<=0||s.n>16||s.m>s.n||s.n!==i.length-3)throw new TypeError("Output is invalid");if(!s.pubkeys.every(c=>(0,Xe.isPoint)(c)))throw new TypeError("Output is invalid");if(t.m!==void 0&&t.m!==s.m)throw new TypeError("m mismatch");if(t.n!==void 0&&t.n!==s.n)throw new TypeError("n mismatch");if(t.pubkeys&&!(0,Xe.stacksEqual)(t.pubkeys,s.pubkeys))throw new TypeError("Pubkeys mismatch")}if(t.pubkeys){if(t.n!==void 0&&t.n!==t.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(s.n=t.pubkeys.length,s.n<s.m)throw new TypeError("Pubkey count cannot be less than m")}if(t.signatures){if(t.signatures.length<s.m)throw new TypeError("Not enough signatures provided");if(t.signatures.length>s.m)throw new TypeError("Too many signatures provided")}if(t.input){if(t.input[0]!==gi.OP_0)throw new TypeError("Input is invalid");if(s.signatures.length===0||!s.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(t.signatures&&!(0,Xe.stacksEqual)(t.signatures,s.signatures))throw new TypeError("Signature mismatch");if(t.m!==void 0&&t.m!==t.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(s,t)}Jc.p2ms=Zv;var Zc={};Object.defineProperty(Zc,"__esModule",{value:!0});Zc.p2pk=void 0;const Qv=xt,wi=ar(),vr=kt,hi=nr,J0=wi.OPS;function e5(t,e){if(!t.input&&!t.output&&!t.pubkey&&!t.input&&!t.signature)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,vr.typeforce)({network:vr.typeforce.maybe(vr.typeforce.Object),output:vr.typeforce.maybe(vr.typeforce.Buffer),pubkey:vr.typeforce.maybe(vr.isPoint),signature:vr.typeforce.maybe(wi.isCanonicalScriptSignature),input:vr.typeforce.maybe(vr.typeforce.Buffer)},t);const r=hi.value(()=>wi.decompile(t.input)),s={name:"p2pk",network:t.network||Qv.bitcoin};if(hi.prop(s,"output",()=>{if(t.pubkey)return wi.compile([t.pubkey,J0.OP_CHECKSIG])}),hi.prop(s,"pubkey",()=>{if(t.output)return t.output.slice(1,-1)}),hi.prop(s,"signature",()=>{if(t.input)return r()[0]}),hi.prop(s,"input",()=>{if(t.signature)return wi.compile([t.signature])}),hi.prop(s,"witness",()=>{if(s.input)return[]}),e.validate){if(t.output){if(t.output[t.output.length-1]!==J0.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!(0,vr.isPoint)(s.pubkey))throw new TypeError("Output pubkey is invalid");if(t.pubkey&&!t.pubkey.equals(s.pubkey))throw new TypeError("Pubkey mismatch")}if(t.signature&&t.input&&!t.input.equals(s.input))throw new TypeError("Signature mismatch");if(t.input){if(r().length!==1)throw new TypeError("Input is invalid");if(!wi.isCanonicalScriptSignature(s.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(s,t)}Zc.p2pk=e5;var Qc={};function t5(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r<e.length;r++)e[r]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=n}var a=t.length,o=t.charAt(0),c=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function l(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var b=0,g=0,A=0,S=d.length;A!==S&&d[A]===0;)A++,b++;for(var T=(S-A)*u+1>>>0,v=new Uint8Array(T);A!==S;){for(var w=d[A],x=0,_=T-1;(w!==0||x<g)&&_!==-1;_--,x++)w+=256*v[_]>>>0,v[_]=w%a>>>0,w=w/a>>>0;if(w!==0)throw new Error("Non-zero carry");g=x,A++}for(var I=T-g;I!==T&&v[I]===0;)I++;for(var N=o.repeat(b);I<T;++I)N+=t.charAt(v[I]);return N}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;for(var b=0,g=0,A=0;d[b]===o;)g++,b++;for(var S=(d.length-b)*c+1>>>0,T=new Uint8Array(S);d[b];){var v=d.charCodeAt(b);if(v>255)return;var w=e[v];if(w===255)return;for(var x=0,_=S-1;(w!==0||x<A)&&_!==-1;_--,x++)w+=a*T[_]>>>0,T[_]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");A=x,b++}for(var I=S-A;I!==S&&T[I]===0;)I++;for(var N=new Uint8Array(g+(S-I)),C=g;I!==S;)N[C++]=T[I++];return N}function p(d){var b=f(d);if(b)return b;throw new Error("Non-base"+a+" character")}return{encode:l,decodeUnsafe:f,decode:p}}var r5=t5;const n5=r5,s5="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";var i5=n5(s5),Ku=i5,a5=function(t){function e(i){var a=Uint8Array.from(i),o=t(a),c=a.length+4,u=new Uint8Array(c);return u.set(a,0),u.set(o.subarray(0,4),a.length),Ku.encode(u,c)}function r(i){var a=i.slice(0,-4),o=i.slice(-4),c=t(a);if(!(o[0]^c[0]|o[1]^c[1]|o[2]^c[2]|o[3]^c[3]))return a}function n(i){var a=Ku.decodeUnsafe(i);if(a)return r(a)}function s(i){var a=Ku.decode(i),o=r(a);if(!o)throw new Error("Invalid checksum");return o}return{encode:e,decode:s,decodeUnsafe:n}},{sha256:Z0}=Ir,o5=a5;function c5(t){return Z0(Z0(t))}var ch=o5(c5);Object.defineProperty(Qc,"__esModule",{value:!0});Qc.p2pkh=void 0;const Xu=ws,u5=xt,vi=ar(),Ot=kt,ln=nr,Q0=ch,qn=vi.OPS;function l5(t,e){if(!t.address&&!t.hash&&!t.output&&!t.pubkey&&!t.input)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Ot.typeforce)({network:Ot.typeforce.maybe(Ot.typeforce.Object),address:Ot.typeforce.maybe(Ot.typeforce.String),hash:Ot.typeforce.maybe(Ot.typeforce.BufferN(20)),output:Ot.typeforce.maybe(Ot.typeforce.BufferN(25)),pubkey:Ot.typeforce.maybe(Ot.isPoint),signature:Ot.typeforce.maybe(vi.isCanonicalScriptSignature),input:Ot.typeforce.maybe(Ot.typeforce.Buffer)},t);const r=ln.value(()=>{const a=Buffer.from(Q0.decode(t.address)),o=a.readUInt8(0),c=a.slice(1);return{version:o,hash:c}}),n=ln.value(()=>vi.decompile(t.input)),s=t.network||u5.bitcoin,i={name:"p2pkh",network:s};if(ln.prop(i,"address",()=>{if(!i.hash)return;const a=Buffer.allocUnsafe(21);return a.writeUInt8(s.pubKeyHash,0),i.hash.copy(a,1),Q0.encode(a)}),ln.prop(i,"hash",()=>{if(t.output)return t.output.slice(3,23);if(t.address)return r().hash;if(t.pubkey||i.pubkey)return Xu.hash160(t.pubkey||i.pubkey)}),ln.prop(i,"output",()=>{if(i.hash)return vi.compile([qn.OP_DUP,qn.OP_HASH160,i.hash,qn.OP_EQUALVERIFY,qn.OP_CHECKSIG])}),ln.prop(i,"pubkey",()=>{if(t.input)return n()[1]}),ln.prop(i,"signature",()=>{if(t.input)return n()[0]}),ln.prop(i,"input",()=>{if(t.pubkey&&t.signature)return vi.compile([t.signature,t.pubkey])}),ln.prop(i,"witness",()=>{if(i.input)return[]}),e.validate){let a=Buffer.from([]);if(t.address){if(r().version!==s.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(r().hash.length!==20)throw new TypeError("Invalid address");a=r().hash}if(t.hash){if(a.length>0&&!a.equals(t.hash))throw new TypeError("Hash mismatch");a=t.hash}if(t.output){if(t.output.length!==25||t.output[0]!==qn.OP_DUP||t.output[1]!==qn.OP_HASH160||t.output[2]!==20||t.output[23]!==qn.OP_EQUALVERIFY||t.output[24]!==qn.OP_CHECKSIG)throw new TypeError("Output is invalid");const o=t.output.slice(3,23);if(a.length>0&&!a.equals(o))throw new TypeError("Hash mismatch");a=o}if(t.pubkey){const o=Xu.hash160(t.pubkey);if(a.length>0&&!a.equals(o))throw new TypeError("Hash mismatch");a=o}if(t.input){const o=n();if(o.length!==2)throw new TypeError("Input is invalid");if(!vi.isCanonicalScriptSignature(o[0]))throw new TypeError("Input has invalid signature");if(!(0,Ot.isPoint)(o[1]))throw new TypeError("Input has invalid pubkey");if(t.signature&&!t.signature.equals(o[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(o[1]))throw new TypeError("Pubkey mismatch");const c=Xu.hash160(o[1]);if(a.length>0&&!a.equals(c))throw new TypeError("Hash mismatch")}}return Object.assign(i,t)}Qc.p2pkh=l5;var eu={};Object.defineProperty(eu,"__esModule",{value:!0});eu.p2sh=void 0;const ep=ws,f5=xt,Yr=ar(),Fe=kt,Gr=nr,tp=ch,ua=Yr.OPS;function d5(t,e){if(!t.address&&!t.hash&&!t.output&&!t.redeem&&!t.input)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Fe.typeforce)({network:Fe.typeforce.maybe(Fe.typeforce.Object),address:Fe.typeforce.maybe(Fe.typeforce.String),hash:Fe.typeforce.maybe(Fe.typeforce.BufferN(20)),output:Fe.typeforce.maybe(Fe.typeforce.BufferN(23)),redeem:Fe.typeforce.maybe({network:Fe.typeforce.maybe(Fe.typeforce.Object),output:Fe.typeforce.maybe(Fe.typeforce.Buffer),input:Fe.typeforce.maybe(Fe.typeforce.Buffer),witness:Fe.typeforce.maybe(Fe.typeforce.arrayOf(Fe.typeforce.Buffer))}),input:Fe.typeforce.maybe(Fe.typeforce.Buffer),witness:Fe.typeforce.maybe(Fe.typeforce.arrayOf(Fe.typeforce.Buffer))},t);let r=t.network;r||(r=t.redeem&&t.redeem.network||f5.bitcoin);const n={network:r},s=Gr.value(()=>{const o=Buffer.from(tp.decode(t.address)),c=o.readUInt8(0),u=o.slice(1);return{version:c,hash:u}}),i=Gr.value(()=>Yr.decompile(t.input)),a=Gr.value(()=>{const o=i(),c=o[o.length-1];return{network:r,output:c===ua.OP_FALSE?Buffer.from([]):c,input:Yr.compile(o.slice(0,-1)),witness:t.witness||[]}});if(Gr.prop(n,"address",()=>{if(!n.hash)return;const o=Buffer.allocUnsafe(21);return o.writeUInt8(n.network.scriptHash,0),n.hash.copy(o,1),tp.encode(o)}),Gr.prop(n,"hash",()=>{if(t.output)return t.output.slice(2,22);if(t.address)return s().hash;if(n.redeem&&n.redeem.output)return ep.hash160(n.redeem.output)}),Gr.prop(n,"output",()=>{if(n.hash)return Yr.compile([ua.OP_HASH160,n.hash,ua.OP_EQUAL])}),Gr.prop(n,"redeem",()=>{if(t.input)return a()}),Gr.prop(n,"input",()=>{if(!(!t.redeem||!t.redeem.input||!t.redeem.output))return Yr.compile([].concat(Yr.decompile(t.redeem.input),t.redeem.output))}),Gr.prop(n,"witness",()=>{if(n.redeem&&n.redeem.witness)return n.redeem.witness;if(n.input)return[]}),Gr.prop(n,"name",()=>{const o=["p2sh"];return n.redeem!==void 0&&n.redeem.name!==void 0&&o.push(n.redeem.name),o.join("-")}),e.validate){let o=Buffer.from([]);if(t.address){if(s().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(s().hash.length!==20)throw new TypeError("Invalid address");o=s().hash}if(t.hash){if(o.length>0&&!o.equals(t.hash))throw new TypeError("Hash mismatch");o=t.hash}if(t.output){if(t.output.length!==23||t.output[0]!==ua.OP_HASH160||t.output[1]!==20||t.output[22]!==ua.OP_EQUAL)throw new TypeError("Output is invalid");const u=t.output.slice(2,22);if(o.length>0&&!o.equals(u))throw new TypeError("Hash mismatch");o=u}const c=u=>{if(u.output){const l=Yr.decompile(u.output);if(!l||l.length<1)throw new TypeError("Redeem.output too short");if(u.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(Yr.countNonPushOnlyOPs(l)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const f=ep.hash160(u.output);if(o.length>0&&!o.equals(f))throw new TypeError("Hash mismatch");o=f}if(u.input){const l=u.input.length>0,f=u.witness&&u.witness.length>0;if(!l&&!f)throw new TypeError("Empty input");if(l&&f)throw new TypeError("Input and witness provided");if(l){const p=Yr.decompile(u.input);if(!Yr.isPushOnly(p))throw new TypeError("Non push-only scriptSig")}}};if(t.input){const u=i();if(!u||u.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(a().output))throw new TypeError("Input is invalid");c(a())}if(t.redeem){if(t.redeem.network&&t.redeem.network!==r)throw new TypeError("Network mismatch");if(t.input){const u=a();if(t.redeem.output&&!t.redeem.output.equals(u.output))throw new TypeError("Redeem.output mismatch");if(t.redeem.input&&!t.redeem.input.equals(u.input))throw new TypeError("Redeem.input mismatch")}c(t.redeem)}if(t.witness&&t.redeem&&t.redeem.witness&&!(0,Fe.stacksEqual)(t.redeem.witness,t.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,t)}eu.p2sh=d5;var tu={};Object.defineProperty(tu,"__esModule",{value:!0});tu.p2wpkh=void 0;const Yu=ws,h5=xt,gc=ar(),nt=kt,Wn=nr,Jo=cs,rp=gc.OPS,p5=Buffer.alloc(0);function y5(t,e){if(!t.address&&!t.hash&&!t.output&&!t.pubkey&&!t.witness)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,nt.typeforce)({address:nt.typeforce.maybe(nt.typeforce.String),hash:nt.typeforce.maybe(nt.typeforce.BufferN(20)),input:nt.typeforce.maybe(nt.typeforce.BufferN(0)),network:nt.typeforce.maybe(nt.typeforce.Object),output:nt.typeforce.maybe(nt.typeforce.BufferN(22)),pubkey:nt.typeforce.maybe(nt.isPoint),signature:nt.typeforce.maybe(gc.isCanonicalScriptSignature),witness:nt.typeforce.maybe(nt.typeforce.arrayOf(nt.typeforce.Buffer))},t);const r=Wn.value(()=>{const i=Jo.bech32.decode(t.address),a=i.words.shift(),o=Jo.bech32.fromWords(i.words);return{version:a,prefix:i.prefix,data:Buffer.from(o)}}),n=t.network||h5.bitcoin,s={name:"p2wpkh",network:n};if(Wn.prop(s,"address",()=>{if(!s.hash)return;const i=Jo.bech32.toWords(s.hash);return i.unshift(0),Jo.bech32.encode(n.bech32,i)}),Wn.prop(s,"hash",()=>{if(t.output)return t.output.slice(2,22);if(t.address)return r().data;if(t.pubkey||s.pubkey)return Yu.hash160(t.pubkey||s.pubkey)}),Wn.prop(s,"output",()=>{if(s.hash)return gc.compile([rp.OP_0,s.hash])}),Wn.prop(s,"pubkey",()=>{if(t.pubkey)return t.pubkey;if(t.witness)return t.witness[1]}),Wn.prop(s,"signature",()=>{if(t.witness)return t.witness[0]}),Wn.prop(s,"input",()=>{if(s.witness)return p5}),Wn.prop(s,"witness",()=>{if(t.pubkey&&t.signature)return[t.signature,t.pubkey]}),e.validate){let i=Buffer.from([]);if(t.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==20)throw new TypeError("Invalid address data");i=r().data}if(t.hash){if(i.length>0&&!i.equals(t.hash))throw new TypeError("Hash mismatch");i=t.hash}if(t.output){if(t.output.length!==22||t.output[0]!==rp.OP_0||t.output[1]!==20)throw new TypeError("Output is invalid");if(i.length>0&&!i.equals(t.output.slice(2)))throw new TypeError("Hash mismatch");i=t.output.slice(2)}if(t.pubkey){const a=Yu.hash160(t.pubkey);if(i.length>0&&!i.equals(a))throw new TypeError("Hash mismatch");if(i=a,!(0,nt.isPoint)(t.pubkey)||t.pubkey.length!==33)throw new TypeError("Invalid pubkey for p2wpkh")}if(t.witness){if(t.witness.length!==2)throw new TypeError("Witness is invalid");if(!gc.isCanonicalScriptSignature(t.witness[0]))throw new TypeError("Witness has invalid signature");if(!(0,nt.isPoint)(t.witness[1])||t.witness[1].length!==33)throw new TypeError("Witness has invalid pubkey");if(t.signature&&!t.signature.equals(t.witness[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(t.witness[1]))throw new TypeError("Pubkey mismatch");const a=Yu.hash160(t.witness[1]);if(i.length>0&&!i.equals(a))throw new TypeError("Hash mismatch")}}return Object.assign(s,t)}tu.p2wpkh=y5;var ru={};Object.defineProperty(ru,"__esModule",{value:!0});ru.p2wsh=void 0;const np=ws,m5=xt,wn=ar(),Re=kt,fn=nr,Zo=cs,sp=wn.OPS,Ju=Buffer.alloc(0);function Qo(t){return!!(Buffer.isBuffer(t)&&t.length===65&&t[0]===4&&(0,Re.isPoint)(t))}function b5(t,e){if(!t.address&&!t.hash&&!t.output&&!t.redeem&&!t.witness)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Re.typeforce)({network:Re.typeforce.maybe(Re.typeforce.Object),address:Re.typeforce.maybe(Re.typeforce.String),hash:Re.typeforce.maybe(Re.typeforce.BufferN(32)),output:Re.typeforce.maybe(Re.typeforce.BufferN(34)),redeem:Re.typeforce.maybe({input:Re.typeforce.maybe(Re.typeforce.Buffer),network:Re.typeforce.maybe(Re.typeforce.Object),output:Re.typeforce.maybe(Re.typeforce.Buffer),witness:Re.typeforce.maybe(Re.typeforce.arrayOf(Re.typeforce.Buffer))}),input:Re.typeforce.maybe(Re.typeforce.BufferN(0)),witness:Re.typeforce.maybe(Re.typeforce.arrayOf(Re.typeforce.Buffer))},t);const r=fn.value(()=>{const a=Zo.bech32.decode(t.address),o=a.words.shift(),c=Zo.bech32.fromWords(a.words);return{version:o,prefix:a.prefix,data:Buffer.from(c)}}),n=fn.value(()=>wn.decompile(t.redeem.input));let s=t.network;s||(s=t.redeem&&t.redeem.network||m5.bitcoin);const i={network:s};if(fn.prop(i,"address",()=>{if(!i.hash)return;const a=Zo.bech32.toWords(i.hash);return a.unshift(0),Zo.bech32.encode(s.bech32,a)}),fn.prop(i,"hash",()=>{if(t.output)return t.output.slice(2);if(t.address)return r().data;if(i.redeem&&i.redeem.output)return np.sha256(i.redeem.output)}),fn.prop(i,"output",()=>{if(i.hash)return wn.compile([sp.OP_0,i.hash])}),fn.prop(i,"redeem",()=>{if(t.witness)return{output:t.witness[t.witness.length-1],input:Ju,witness:t.witness.slice(0,-1)}}),fn.prop(i,"input",()=>{if(i.witness)return Ju}),fn.prop(i,"witness",()=>{if(t.redeem&&t.redeem.input&&t.redeem.input.length>0&&t.redeem.output&&t.redeem.output.length>0){const a=wn.toStack(n());return i.redeem=Object.assign({witness:a},t.redeem),i.redeem.input=Ju,[].concat(a,t.redeem.output)}if(t.redeem&&t.redeem.output&&t.redeem.witness)return[].concat(t.redeem.witness,t.redeem.output)}),fn.prop(i,"name",()=>{const a=["p2wsh"];return i.redeem!==void 0&&i.redeem.name!==void 0&&a.push(i.redeem.name),a.join("-")}),e.validate){let a=Buffer.from([]);if(t.address){if(r().prefix!==s.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==32)throw new TypeError("Invalid address data");a=r().data}if(t.hash){if(a.length>0&&!a.equals(t.hash))throw new TypeError("Hash mismatch");a=t.hash}if(t.output){if(t.output.length!==34||t.output[0]!==sp.OP_0||t.output[1]!==32)throw new TypeError("Output is invalid");const o=t.output.slice(2);if(a.length>0&&!a.equals(o))throw new TypeError("Hash mismatch");a=o}if(t.redeem){if(t.redeem.network&&t.redeem.network!==s)throw new TypeError("Network mismatch");if(t.redeem.input&&t.redeem.input.length>0&&t.redeem.witness&&t.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(t.redeem.output){const o=wn.decompile(t.redeem.output);if(!o||o.length<1)throw new TypeError("Redeem.output is invalid");if(t.redeem.output.byteLength>3600)throw new TypeError("Redeem.output unspendable if larger than 3600 bytes");if(wn.countNonPushOnlyOPs(o)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const c=np.sha256(t.redeem.output);if(a.length>0&&!a.equals(c))throw new TypeError("Hash mismatch");a=c}if(t.redeem.input&&!wn.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(t.witness&&t.redeem.witness&&!(0,Re.stacksEqual)(t.witness,t.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(t.redeem.input&&n().some(Qo)||t.redeem.output&&(wn.decompile(t.redeem.output)||[]).some(Qo))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(t.witness&&t.witness.length>0){const o=t.witness[t.witness.length-1];if(t.redeem&&t.redeem.output&&!t.redeem.output.equals(o))throw new TypeError("Witness and redeem.output mismatch");if(t.witness.some(Qo)||(wn.decompile(o)||[]).some(Qo))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(i,t)}ru.p2wsh=b5;var la={},Ws={};Object.defineProperty(Ws,"__esModule",{value:!0});Ws.getEccLib=Ws.initEccLib=void 0;const _a={};function g5(t,e){t?t!==_a.eccLib&&(e!=null&&e.DANGER_DO_NOT_VERIFY_ECCLIB||v5(t),_a.eccLib=t):_a.eccLib=t}Ws.initEccLib=g5;function w5(){if(!_a.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return _a.eccLib}Ws.getEccLib=w5;const dn=t=>Buffer.from(t,"hex");function v5(t){ur(typeof t.isXOnlyPoint=="function"),ur(t.isXOnlyPoint(dn("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),ur(t.isXOnlyPoint(dn("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),ur(t.isXOnlyPoint(dn("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),ur(t.isXOnlyPoint(dn("0000000000000000000000000000000000000000000000000000000000000001"))),ur(!t.isXOnlyPoint(dn("0000000000000000000000000000000000000000000000000000000000000000"))),ur(!t.isXOnlyPoint(dn("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),ur(typeof t.xOnlyPointAddTweak=="function"),E5.forEach(e=>{const r=t.xOnlyPointAddTweak(dn(e.pubkey),dn(e.tweak));e.result===null?ur(r===null):(ur(r!==null),ur(r.parity===e.parity),ur(Buffer.from(r.xOnlyPubkey).equals(dn(e.result))))})}function ur(t){if(!t)throw new Error("ecc library invalid")}const E5=[{pubkey:"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",tweak:"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140",parity:-1,result:null},{pubkey:"1617d38ed8d8657da4d4761e8057bc396ea9e4b9d29776d4be096016dbd2509b",tweak:"a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac",parity:1,result:"e478f99dab91052ab39a33ea35fd5e6e4933f4d28023cd597c9a1f6760346adf"},{pubkey:"2c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991",tweak:"823c3cd2142744b075a87eade7e1b8678ba308d566226a0056ca2b7a76f86b47",parity:0,result:"9534f8dc8c6deda2dc007655981c78b49c5d96c778fbf363462a11ec9dfd948c"}];var uh={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.tweakKey=t.tapTweakHash=t.tapleafHash=t.findScriptPath=t.toHashTree=t.rootHashFromPath=t.MAX_TAPTREE_DEPTH=t.LEAF_VERSION_TAPSCRIPT=void 0;const e=si,r=Ws,n=ws,s=pt,i=kt;t.LEAF_VERSION_TAPSCRIPT=192,t.MAX_TAPTREE_DEPTH=128;const a=g=>"left"in g&&"right"in g;function o(g,A){if(g.length<33)throw new TypeError(`The control-block length is too small. Got ${g.length}, expected min 33.`);const S=(g.length-33)/32;let T=A;for(let v=0;v<S;v++){const w=g.slice(33+32*v,65+32*v);T.compare(w)<0?T=d(T,w):T=d(w,T)}return T}t.rootHashFromPath=o;function c(g){if((0,i.isTapleaf)(g))return{hash:l(g)};const A=[c(g[0]),c(g[1])];A.sort((v,w)=>v.hash.compare(w.hash));const[S,T]=A;return{hash:d(S.hash,T.hash),left:S,right:T}}t.toHashTree=c;function u(g,A){if(a(g)){const S=u(g.left,A);if(S!==void 0)return[...S,g.right.hash];const T=u(g.right,A);if(T!==void 0)return[...T,g.left.hash]}else if(g.hash.equals(A))return[]}t.findScriptPath=u;function l(g){const A=g.version||t.LEAF_VERSION_TAPSCRIPT;return n.taggedHash("TapLeaf",e.Buffer.concat([e.Buffer.from([A]),b(g.output)]))}t.tapleafHash=l;function f(g,A){return n.taggedHash("TapTweak",e.Buffer.concat(A?[g,A]:[g]))}t.tapTweakHash=f;function p(g,A){if(!e.Buffer.isBuffer(g)||g.length!==32||A&&A.length!==32)return null;const S=f(g,A),T=(0,r.getEccLib)().xOnlyPointAddTweak(g,S);return!T||T.xOnlyPubkey===null?null:{parity:T.parity,x:e.Buffer.from(T.xOnlyPubkey)}}t.tweakKey=p;function d(g,A){return n.taggedHash("TapBranch",e.Buffer.concat([g,A]))}function b(g){const A=s.varuint.encodingLength(g.length),S=e.Buffer.allocUnsafe(A);return s.varuint.encode(g.length,S),e.Buffer.concat([S,g])}})(uh);var Bt={},ip;function A5(){if(ip)return Bt;ip=1,Object.defineProperty(Bt,"__esModule",{value:!0}),Bt.toOutputScript=Bt.fromOutputScript=Bt.toBech32=Bt.toBase58Check=Bt.fromBech32=Bt.fromBase58Check=void 0;const t=xt,e=lh(),r=ar(),n=kt,s=cs,i=ch,a=40,o=2,c=16,u=2,l=80,f="WARNING: Sending to a future segwit version address can lead to loss of funds. End users MUST be warned carefully in the GUI and asked if they wish to proceed with caution. Wallets should verify the segwit version from the output of fromBech32, then decide when it is safe to use which version of segwit.";function p(v,w){const x=v.slice(2);if(x.length<o||x.length>a)throw new TypeError("Invalid program length for segwit address");const _=v[0]-l;if(_<u||_>c)throw new TypeError("Invalid version for segwit address");if(v[1]!==x.length)throw new TypeError("Invalid script for segwit address");return console.warn(f),A(x,_,w.bech32)}function d(v){const w=Buffer.from(i.decode(v));if(w.length<21)throw new TypeError(v+" is too short");if(w.length>21)throw new TypeError(v+" is too long");const x=w.readUInt8(0),_=w.slice(1);return{version:x,hash:_}}Bt.fromBase58Check=d;function b(v){let w,x;try{w=s.bech32.decode(v)}catch{}if(w){if(x=w.words[0],x!==0)throw new TypeError(v+" uses wrong encoding")}else if(w=s.bech32m.decode(v),x=w.words[0],x===0)throw new TypeError(v+" uses wrong encoding");const _=s.bech32.fromWords(w.words.slice(1));return{version:x,prefix:w.prefix,data:Buffer.from(_)}}Bt.fromBech32=b;function g(v,w){(0,n.typeforce)((0,n.tuple)(n.Hash160bit,n.UInt8),arguments);const x=Buffer.allocUnsafe(21);return x.writeUInt8(w,0),v.copy(x,1),i.encode(x)}Bt.toBase58Check=g;function A(v,w,x){const _=s.bech32.toWords(v);return _.unshift(w),w===0?s.bech32.encode(x,_):s.bech32m.encode(x,_)}Bt.toBech32=A;function S(v,w){w=w||t.bitcoin;try{return e.p2pkh({output:v,network:w}).address}catch{}try{return e.p2sh({output:v,network:w}).address}catch{}try{return e.p2wpkh({output:v,network:w}).address}catch{}try{return e.p2wsh({output:v,network:w}).address}catch{}try{return e.p2tr({output:v,network:w}).address}catch{}try{return p(v,w)}catch{}throw new Error(r.toASM(v)+" has no matching Address")}Bt.fromOutputScript=S;function T(v,w){w=w||t.bitcoin;let x,_;try{x=d(v)}catch{}if(x){if(x.version===w.pubKeyHash)return e.p2pkh({hash:x.hash}).output;if(x.version===w.scriptHash)return e.p2sh({hash:x.hash}).output}else{try{_=b(v)}catch{}if(_){if(_.prefix!==w.bech32)throw new Error(v+" has an invalid prefix");if(_.version===0){if(_.data.length===20)return e.p2wpkh({hash:_.data}).output;if(_.data.length===32)return e.p2wsh({hash:_.data}).output}else if(_.version===1){if(_.data.length===32)return e.p2tr({pubkey:_.data}).output}else if(_.version>=u&&_.version<=c&&_.data.length>=o&&_.data.length<=a)return console.warn(f),r.compile([_.version+l,_.data])}}throw new Error(v+" has no matching Script")}return Bt.toOutputScript=T,Bt}var ap;function S5(){if(ap)return la;ap=1,Object.defineProperty(la,"__esModule",{value:!0}),la.p2tr=void 0;const t=si,e=xt,r=ar(),n=kt,s=Ws,i=uh,a=nr,o=cs,c=A5(),u=r.OPS,l=1,f=80;function p(d,b){if(!d.address&&!d.output&&!d.pubkey&&!d.internalPubkey&&!(d.witness&&d.witness.length>1))throw new TypeError("Not enough data");b=Object.assign({validate:!0},b||{}),(0,n.typeforce)({address:n.typeforce.maybe(n.typeforce.String),input:n.typeforce.maybe(n.typeforce.BufferN(0)),network:n.typeforce.maybe(n.typeforce.Object),output:n.typeforce.maybe(n.typeforce.BufferN(34)),internalPubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),hash:n.typeforce.maybe(n.typeforce.BufferN(32)),pubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),signature:n.typeforce.maybe(n.typeforce.anyOf(n.typeforce.BufferN(64),n.typeforce.BufferN(65))),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer)),scriptTree:n.typeforce.maybe(n.isTaptree),redeem:n.typeforce.maybe({output:n.typeforce.maybe(n.typeforce.Buffer),redeemVersion:n.typeforce.maybe(n.typeforce.Number),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer))}),redeemVersion:n.typeforce.maybe(n.typeforce.Number)},d);const g=a.value(()=>(0,c.fromBech32)(d.address)),A=a.value(()=>{if(!(!d.witness||!d.witness.length))return d.witness.length>=2&&d.witness[d.witness.length-1][0]===f?d.witness.slice(0,-1):d.witness.slice()}),S=a.value(()=>{if(d.scriptTree)return(0,i.toHashTree)(d.scriptTree);if(d.hash)return{hash:d.hash}}),T=d.network||e.bitcoin,v={name:"p2tr",network:T};if(a.prop(v,"address",()=>{if(!v.pubkey)return;const w=o.bech32m.toWords(v.pubkey);return w.unshift(l),o.bech32m.encode(T.bech32,w)}),a.prop(v,"hash",()=>{const w=S();if(w)return w.hash;const x=A();if(x&&x.length>1){const _=x[x.length-1],I=_[0]&n.TAPLEAF_VERSION_MASK,N=x[x.length-2],C=(0,i.tapleafHash)({output:N,version:I});return(0,i.rootHashFromPath)(_,C)}return null}),a.prop(v,"output",()=>{if(v.pubkey)return r.compile([u.OP_1,v.pubkey])}),a.prop(v,"redeemVersion",()=>d.redeemVersion?d.redeemVersion:d.redeem&&d.redeem.redeemVersion!==void 0&&d.redeem.redeemVersion!==null?d.redeem.redeemVersion:i.LEAF_VERSION_TAPSCRIPT),a.prop(v,"redeem",()=>{const w=A();if(!(!w||w.length<2))return{output:w[w.length-2],witness:w.slice(0,-2),redeemVersion:w[w.length-1][0]&n.TAPLEAF_VERSION_MASK}}),a.prop(v,"pubkey",()=>{if(d.pubkey)return d.pubkey;if(d.output)return d.output.slice(2);if(d.address)return g().data;if(v.internalPubkey){const w=(0,i.tweakKey)(v.internalPubkey,v.hash);if(w)return w.x}}),a.prop(v,"internalPubkey",()=>{if(d.internalPubkey)return d.internalPubkey;const w=A();if(w&&w.length>1)return w[w.length-1].slice(1,33)}),a.prop(v,"signature",()=>{if(d.signature)return d.signature;const w=A();if(!(!w||w.length!==1))return w[0]}),a.prop(v,"witness",()=>{if(d.witness)return d.witness;const w=S();if(w&&d.redeem&&d.redeem.output&&d.internalPubkey){const x=(0,i.tapleafHash)({output:d.redeem.output,version:v.redeemVersion}),_=(0,i.findScriptPath)(w,x);if(!_)return;const I=(0,i.tweakKey)(d.internalPubkey,w.hash);if(!I)return;const N=t.Buffer.concat([t.Buffer.from([v.redeemVersion|I.parity]),d.internalPubkey].concat(_));return[d.redeem.output,N]}if(d.signature)return[d.signature]}),b.validate){let w=t.Buffer.from([]);if(d.address){if(T&&T.bech32!==g().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(g().version!==l)throw new TypeError("Invalid address version");if(g().data.length!==32)throw new TypeError("Invalid address data");w=g().data}if(d.pubkey){if(w.length>0&&!w.equals(d.pubkey))throw new TypeError("Pubkey mismatch");w=d.pubkey}if(d.output){if(d.output.length!==34||d.output[0]!==u.OP_1||d.output[1]!==32)throw new TypeError("Output is invalid");if(w.length>0&&!w.equals(d.output.slice(2)))throw new TypeError("Pubkey mismatch");w=d.output.slice(2)}if(d.internalPubkey){const I=(0,i.tweakKey)(d.internalPubkey,v.hash);if(w.length>0&&!w.equals(I.x))throw new TypeError("Pubkey mismatch");w=I.x}if(w&&w.length&&!(0,s.getEccLib)().isXOnlyPoint(w))throw new TypeError("Invalid pubkey for p2tr");const x=S();if(d.hash&&x&&!d.hash.equals(x.hash))throw new TypeError("Hash mismatch");if(d.redeem&&d.redeem.output&&x){const I=(0,i.tapleafHash)({output:d.redeem.output,version:v.redeemVersion});if(!(0,i.findScriptPath)(x,I))throw new TypeError("Redeem script not in tree")}const _=A();if(d.redeem&&v.redeem){if(d.redeem.redeemVersion&&d.redeem.redeemVersion!==v.redeem.redeemVersion)throw new TypeError("Redeem.redeemVersion and witness mismatch");if(d.redeem.output){if(r.decompile(d.redeem.output).length===0)throw new TypeError("Redeem.output is invalid");if(v.redeem.output&&!d.redeem.output.equals(v.redeem.output))throw new TypeError("Redeem.output and witness mismatch")}if(d.redeem.witness&&v.redeem.witness&&!(0,n.stacksEqual)(d.redeem.witness,v.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(_&&_.length)if(_.length===1){if(d.signature&&!d.signature.equals(_[0]))throw new TypeError("Signature mismatch")}else{const I=_[_.length-1];if(I.length<33)throw new TypeError(`The control-block length is too small. Got ${I.length}, expected min 33.`);if((I.length-33)%32!==0)throw new TypeError(`The control-block length of ${I.length} is incorrect!`);const N=(I.length-33)/32;if(N>128)throw new TypeError(`The script path is too long. Got ${N}, expected max 128.`);const C=I.slice(1,33);if(d.internalPubkey&&!d.internalPubkey.equals(C))throw new TypeError("Internal pubkey mismatch");if(!(0,s.getEccLib)().isXOnlyPoint(C))throw new TypeError("Invalid internalPubkey for p2tr witness");const j=I[0]&n.TAPLEAF_VERSION_MASK,M=_[_.length-2],H=(0,i.tapleafHash)({output:M,version:j}),V=(0,i.rootHashFromPath)(I,H),Q=(0,i.tweakKey)(C,V);if(!Q)throw new TypeError("Invalid outputKey for p2tr witness");if(w.length&&!w.equals(Q.x))throw new TypeError("Pubkey mismatch for p2tr witness");if(Q.parity!==(I[0]&1))throw new Error("Incorrect parity")}}return Object.assign(v,d)}return la.p2tr=p,la}var op;function lh(){return op||(op=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.p2tr=t.p2wsh=t.p2wpkh=t.p2sh=t.p2pkh=t.p2pk=t.p2ms=t.embed=void 0;const e=Yc;Object.defineProperty(t,"embed",{enumerable:!0,get:function(){return e.p2data}});const r=Jc;Object.defineProperty(t,"p2ms",{enumerable:!0,get:function(){return r.p2ms}});const n=Zc;Object.defineProperty(t,"p2pk",{enumerable:!0,get:function(){return n.p2pk}});const s=Qc;Object.defineProperty(t,"p2pkh",{enumerable:!0,get:function(){return s.p2pkh}});const i=eu;Object.defineProperty(t,"p2sh",{enumerable:!0,get:function(){return i.p2sh}});const a=tu;Object.defineProperty(t,"p2wpkh",{enumerable:!0,get:function(){return a.p2wpkh}});const o=ru;Object.defineProperty(t,"p2wsh",{enumerable:!0,get:function(){return o.p2wsh}});const c=S5();Object.defineProperty(t,"p2tr",{enumerable:!0,get:function(){return c.p2tr}})}(Wu)),Wu}Object.defineProperty(Be,"__esModule",{value:!0});Be.signatureBlocksAction=Be.checkInputForSig=Be.pubkeyInScript=Be.pubkeyPositionInScript=Be.witnessStackToScriptWitness=Be.isP2TR=Be.isP2SHScript=Be.isP2WSHScript=Be.isP2WPKH=Be.isP2PKH=Be.isP2PK=Be.isP2MS=void 0;const cp=So,Ia=ar(),ec=Eo,x5=ws,ii=lh();function ai(t){return e=>{try{return t({output:e}),!0}catch{return!1}}}Be.isP2MS=ai(ii.p2ms);Be.isP2PK=ai(ii.p2pk);Be.isP2PKH=ai(ii.p2pkh);Be.isP2WPKH=ai(ii.p2wpkh);Be.isP2WSHScript=ai(ii.p2wsh);Be.isP2SHScript=ai(ii.p2sh);Be.isP2TR=ai(ii.p2tr);function k5(t){let e=Buffer.allocUnsafe(0);function r(a){e=Buffer.concat([e,Buffer.from(a)])}function n(a){const o=e.length,c=cp.encodingLength(a);e=Buffer.concat([e,Buffer.allocUnsafe(c)]),cp.encode(a,e,o)}function s(a){n(a.length),r(a)}function i(a){n(a.length),a.forEach(s)}return i(t),e}Be.witnessStackToScriptWitness=k5;function Rb(t,e){const r=(0,x5.hash160)(t),n=t.slice(1,33),s=Ia.decompile(e);if(s===null)throw new Error("Unknown script error");return s.findIndex(i=>typeof i=="number"?!1:i.equals(t)||i.equals(r)||i.equals(n))}Be.pubkeyPositionInScript=Rb;function T5(t,e){return Rb(t,e)!==-1}Be.pubkeyInScript=T5;function _5(t,e){return I5(t).some(n=>Nb(n,Ia.signature.decode,e))}Be.checkInputForSig=_5;function Nb(t,e,r){const{hashType:n}=e(t),s=[];switch(n&ec.Transaction.SIGHASH_ANYONECANPAY&&s.push("addInput"),n&31){case ec.Transaction.SIGHASH_ALL:break;case ec.Transaction.SIGHASH_SINGLE:case ec.Transaction.SIGHASH_NONE:s.push("addOutput"),s.push("setInputSequence");break}return s.indexOf(r)===-1}Be.signatureBlocksAction=Nb;function I5(t){let e=[];if((t.partialSig||[]).length===0){if(!t.finalScriptSig&&!t.finalScriptWitness)return[];e=P5(t)}else e=t.partialSig;return e.map(r=>r.signature)}function P5(t){const e=t.finalScriptSig?Ia.decompile(t.finalScriptSig)||[]:[],r=t.finalScriptWitness?Ia.decompile(t.finalScriptWitness)||[]:[];return e.concat(r).filter(n=>Buffer.isBuffer(n)&&Ia.isCanonicalScriptSignature(n)).map(n=>({signature:n}))}Object.defineProperty(ze,"__esModule",{value:!0});ze.checkTaprootInputForSigs=ze.tapTreeFromList=ze.tapTreeToList=ze.tweakInternalPubKey=ze.checkTaprootOutputFields=ze.checkTaprootInputFields=ze.isTaprootOutput=ze.isTaprootInput=Ea=ze.serializeTaprootSignature=ze.tapScriptFinalizer=ze.toXOnly=void 0;const fh=kt,O5=Eo,nu=Be,ds=uh,B5=lh(),C5=Be,R5=t=>t.length===32?t:t.slice(1,33);ze.toXOnly=R5;function N5(t,e,r){const n=Z5(e,t,r);try{const i=Y5(e,n).concat(n.script).concat(n.controlBlock);return{finalScriptWitness:(0,nu.witnessStackToScriptWitness)(i)}}catch(s){throw new Error(`Can not finalize taproot input #${t}: ${s}`)}}ze.tapScriptFinalizer=N5;function U5(t,e){const r=e?Buffer.from([e]):Buffer.from([]);return Buffer.concat([t,r])}var Ea=ze.serializeTaprootSignature=U5;function wc(t){return t&&!!(t.tapInternalKey||t.tapMerkleRoot||t.tapLeafScript&&t.tapLeafScript.length||t.tapBip32Derivation&&t.tapBip32Derivation.length||t.witnessUtxo&&(0,nu.isP2TR)(t.witnessUtxo.script))}ze.isTaprootInput=wc;function vc(t,e){return t&&!!(t.tapInternalKey||t.tapTree||t.tapBip32Derivation&&t.tapBip32Derivation.length||e&&(0,nu.isP2TR)(e))}ze.isTaprootOutput=vc;function F5(t,e,r){W5(t,e,r),X5(t,e,r)}ze.checkTaprootInputFields=F5;function M5(t,e,r){K5(t,e,r),$5(t,e)}ze.checkTaprootOutputFields=M5;function $5(t,e){if(!e.tapTree&&!e.tapInternalKey)return;const r=e.tapInternalKey||t.tapInternalKey,n=e.tapTree||t.tapTree;if(r){const{script:s}=t,i=j5(r,n);if(s&&!s.equals(i))throw new Error("Error adding output. Script or address missmatch.")}}function j5(t,e){const r=e&&Ub(e.leaves),{output:n}=(0,B5.p2tr)({internalPubkey:t,scriptTree:r});return n}function H5(t,e){const r=e.tapInternalKey,n=r&&(0,ds.tweakKey)(r,e.tapMerkleRoot);if(!n)throw new Error(`Cannot tweak tap internal key for input #${t}. Public key: ${r&&r.toString("hex")}`);return n.x}ze.tweakInternalPubKey=H5;function L5(t){if(!(0,fh.isTaptree)(t))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return Xf(t)}ze.tapTreeToList=L5;function Ub(t=[]){return t.length===1&&t[0].depth===0?{output:t[0].script,version:t[0].leafVersion}:q5(t)}ze.tapTreeFromList=Ub;function D5(t,e){return V5(t).some(n=>(0,C5.signatureBlocksAction)(n,z5,e))}ze.checkTaprootInputForSigs=D5;function z5(t){return{signature:t.slice(0,64),hashType:t.slice(64)[0]||O5.Transaction.SIGHASH_DEFAULT}}function V5(t){const e=[];if(t.tapKeySig&&e.push(t.tapKeySig),t.tapScriptSig&&e.push(...t.tapScriptSig.map(r=>r.signature)),!e.length){const r=G5(t.finalScriptWitness);r&&e.push(r)}return e}function G5(t){if(!t)return;const e=t.slice(2);if(e.length===64||e.length===65)return e}function Xf(t,e=[],r=0){if(r>ds.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return t?(0,fh.isTapleaf)(t)?(e.push({depth:r,leafVersion:t.version||ds.LEAF_VERSION_TAPSCRIPT,script:t.output}),e):(t[0]&&Xf(t[0],e,r+1),t[1]&&Xf(t[1],e,r+1),e):[]}function q5(t){let e;for(const r of t)if(e=Yf(r,e),!e)throw new Error("No room left to insert tapleaf in tree");return e}function Yf(t,e,r=0){if(r>ds.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");if(t.depth===r)return e?void 0:{output:t.script,version:t.leafVersion};if((0,fh.isTapleaf)(e))return;const n=Yf(t,e&&e[0],r+1);if(n)return[n,e&&e[1]];const s=Yf(t,e&&e[1],r+1);if(s)return[e&&e[0],s]}function W5(t,e,r){const n=wc(t)&&Oi(e),s=Oi(t)&&wc(e),i=t===e&&wc(e)&&Oi(e);if(n||s||i)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function K5(t,e,r){const n=vc(t)&&Oi(e),s=Oi(t)&&vc(e),i=t===e&&vc(e)&&Oi(e);if(n||s||i)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function X5(t,e,r){if(e.tapMerkleRoot){const n=(e.tapLeafScript||[]).every(i=>Zu(i,e.tapMerkleRoot)),s=(t.tapLeafScript||[]).every(i=>Zu(i,e.tapMerkleRoot));if(!n||!s)throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}else if(t.tapMerkleRoot&&!(e.tapLeafScript||[]).every(s=>Zu(s,t.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}function Zu(t,e){if(!e)return!0;const r=(0,ds.tapleafHash)({output:t.script,version:t.leafVersion});return(0,ds.rootHashFromPath)(t.controlBlock,r).equals(e)}function Y5(t,e){const r=(0,ds.tapleafHash)({output:e.script,version:e.leafVersion});return(t.tapScriptSig||[]).filter(n=>n.leafHash.equals(r)).map(n=>J5(e.script,n)).sort((n,s)=>s.positionInScript-n.positionInScript).map(n=>n.signature)}function J5(t,e){return Object.assign({positionInScript:(0,nu.pubkeyPositionInScript)(e.pubkey,t)},e)}function Z5(t,e,r){if(!t.tapScriptSig||!t.tapScriptSig.length)throw new Error(`Can not finalize taproot input #${e}. No tapleaf script signature provided.`);const n=(t.tapLeafScript||[]).sort((s,i)=>s.controlBlock.length-i.controlBlock.length).find(s=>Q5(s,t.tapScriptSig,r));if(!n)throw new Error(`Can not finalize taproot input #${e}. Signature for tapleaf script not found.`);return n}function Q5(t,e,r){const n=(0,ds.tapleafHash)({output:t.script,version:t.leafVersion});return(!r||r.equals(n))&&e.find(i=>i.leafHash.equals(n))!==void 0}function Oi(t){return t&&!!(t.redeemScript||t.witnessScript||t.bip32Derivation&&t.bip32Derivation.length)}const lr={secretMismatch:"invalid secret",secretHashLenMismatch:"secret hash should be 32 bytes",pubkeyLenMismatch:"pubkey should be 32 bytes",zeroOrNegativeExpiry:"expiry should be greater than 0",htlcAddressGenerationFailed:"failed to generate htlc address",notFunded:"address not funded",noCounterpartySigs:"counterparty signatures are required",counterPartySigNotFound:t=>"counterparty signature not found for utxo "+t,invalidCounterpartySigForUTXO:t=>"invalid counterparty signature for utxo "+t,htlcNotExpired:t=>`HTLC not expired, need more ${t} blocks`,controlBlockGenerationFailed:"failed to generate control block",invalidLeaf:"invalid leaf"},tc=192;ke.initEccLib(mr);let eE=class{constructor(e,r){this.signer=e,this.internalPubkey=H0(),this.network=z6(r)}address(e,r){const n=this.generateLeaves(e,r),{address:s}=ke.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:n});if(!s)throw new Error(lr.htlcAddressGenerationFailed);return s}async _buildRawTx(e,r,n,s,i){const a=new ke.Transaction;a.version=2;const o=this.address(e,n||"redeem"),c=await this.getProvider();let u=[];if(i&&i.length>0)for(const p of i){const d=await c.getTransaction(p);for(let b=0;b<d.vout.length;b++){const g=d.vout[b];g.scriptpubkey_address===o&&u.push({txid:d.txid,vout:b,value:g.value,status:{confirmed:!1}})}}else u=await c.getUTXOs(o);const l=u.reduce((p,d)=>p+d.value,0);if(l===0)throw new Error(`${o} ${lr.notFunded}`);for(let p=0;p<u.length;p++)a.addInput(Buffer.from(u[p].txid,"hex").reverse(),u[p].vout);if(s!=null&&s.vSize){const p=await c.getFeeRates(),d=Math.ceil(p.hourFee*s.vSize),b=l-d;return a.addOutput(ke.address.toOutputScript(r,this.network),b),{tx:a,usedUtxos:u}}const f=(s==null?void 0:s.fee)??await c.suggestFee(o,l,Ii.MEDIUM);return a.addOutput(ke.address.toOutputScript(r,this.network),l-f),{tx:a,usedUtxos:u,fee:f,balance:l}}getOutputScript(e,r){return ke.address.toOutputScript(this.address(e,r||"redeem"),this.network)}async initiate(e,r){const n=await this.getProvider(),s=await this.signer.getAddress();let i,a;D.isOrder(e)?(i=e.source_swap.swap_id,a=Number(e.source_swap.amount)):(i=e.to,a=Number(e.amount)),r===void 0&&(r=await n.suggestFee(s,a,Ii.MEDIUM));const o=await this.signer.send(i,a,r);return m.Ok(o)}async generateRedeemSACP(e,r,n){const{tx:s,usedUtxos:i}=await this._buildRawTx(e,e.destination_swap.delegate,"redeem",{fee:n}),a=this.getOutputScript(e,"redeem"),o=ke.Transaction.SIGHASH_SINGLE|ke.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(1,e),u=i.map(f=>f.value),l=oa(a,i.length);for(let f=0;f<s.ins.length;f++){const p=s.hashForWitnessV1(f,l,u,o,c),d=await this.signer.signSchnorr(p);s.setWitness(f,[Ea(d,o),Buffer.from(r,"hex"),this.redeemLeaf(m.trim0x(e.destination_swap.secret_hash),De(e.destination_swap.delegate)),await this.generateControlBlockFor(1,e)])}return s.toHex()}async generateInstantRefundSACP(e){const r=this.getOutputScript(e,"instantRefund"),{tx:n,usedUtxos:s,fee:i}=await this._buildRawTx(e,e.destination_swap.delegate,"instantRefund",{fee:0});n.outs=[];const a=Math.max(...s.map(f=>f.value));s.forEach(({value:f})=>{n.addOutput(r,f-(f===a?i??0:0))});const o=ke.Transaction.SIGHASH_SINGLE|ke.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(2,e),u=s.map(f=>f.value),l=oa(r,s.length);for(let f=0;f<n.ins.length;f++){const p=n.hashForWitnessV1(f,l,u,o,c),d=await this.signer.signSchnorr(p);n.setWitness(f,[Ea(d,o),Ea(d,o),this.instantRefundLeaf(De(e.source_swap.initiator),De(e.destination_swap.delegate)),await this.generateControlBlockFor(2,e)])}return n.toHex()}async generateInstantRefundSACPWithHash(e){const r=[],n=ke.Transaction.SIGHASH_SINGLE|ke.Transaction.SIGHASH_ANYONECANPAY;for(let s=0;s<e.length;s++){const i=Buffer.from(e[s],"hex"),a=await this.signer.signSchnorr(i);r.push(Ea(a,n).toString("hex"))}return m.Ok(r)}async instantRefund(e,r,n){F0(r.length>0,lr.noCounterpartySigs);const{tx:s,usedUtxos:i}=await this._buildRawTx(e,await this.signer.getAddress(),"instantRefund",{fee:n});for(const p of i)if(!r.find(d=>d.utxo===p.txid))throw new Error(lr.counterPartySigNotFound(p.txid));const a=this.getOutputScript(e,"instantRefund"),o=ke.Transaction.SIGHASH_DEFAULT,c=this.leafHash(2,e),u=i.map(p=>p.value),l=oa(a,i.length);for(let p=0;p<s.ins.length;p++){const d=s.hashForWitnessV1(p,l,u,o,c);if(!mr.verifySchnorr(d,Buffer.from(De(e.destination_swap.delegate),"hex"),Buffer.from(r[p].sig,"hex")))throw new Error(lr.invalidCounterpartySigForUTXO(r[p].utxo));const b=await this.signer.signSchnorr(d),g=Buffer.from(s.ins[p].hash).reverse().toString("hex"),A=r.find(S=>S.utxo===g);if(!A)throw new Error(lr.counterPartySigNotFound(g));s.setWitness(p,[Buffer.from(A.sig,"hex"),b,this.instantRefundLeaf(De(e.source_swap.initiator),De(e.destination_swap.delegate)),await this.generateControlBlockFor(2,e)])}return await(await this.getProvider()).broadcast(s.toHex())}async redeem(e,r,n){const s=await this.getRedeemHex(e,r,n);if(!s.ok)return m.Err(s.error);const a=await(await this.getProvider()).broadcast(s.val);return m.Ok(a)}async getRedeemHex(e,r,n){F0(ke.crypto.sha256(Buffer.from(r,"hex")).toString("hex")===m.trim0x(e.destination_swap.secret_hash),lr.secretMismatch);const a=(D.isBitcoin(e.source_swap.chain)?e.source_swap.redeemer:e.destination_swap.redeemer)??await this.signer.getAddress(),{tx:o,usedUtxos:c}=await this._buildRawTx(e,a,"redeem",{fee:0},n),u=this.leafHash(1,e),l=c.map(b=>b.value),f=oa(this.getOutputScript(e,"redeem"),c.length),p=ke.Transaction.SIGHASH_DEFAULT;for(let b=0;b<o.ins.length;b++){const g=o.hashForWitnessV1(b,f,l,p,u),A=await this.signer.signSchnorr(g);o.setWitness(b,[A,Buffer.from(r,"hex"),this.redeemLeaf(m.trim0x(e.destination_swap.secret_hash),De(e.destination_swap.delegate)),await this.generateControlBlockFor(1,e)])}const{tx:d}=await this._buildRawTx(e,a,"redeem",{vSize:o.virtualSize()},n);for(let b=0;b<d.ins.length;b++){const g=d.hashForWitnessV1(b,f,l,p,u),A=await this.signer.signSchnorr(g);d.setWitness(b,[A,Buffer.from(r,"hex"),this.redeemLeaf(m.trim0x(e.destination_swap.secret_hash),De(e.destination_swap.delegate)),await this.generateControlBlockFor(1,e)])}return m.Ok(d.toHex())}async refund(e,r){const{tx:n,usedUtxos:s}=await this._buildRawTx(e,e.source_swap.delegate??await this.signer.getAddress(),"refund",{fee:r}),[i,a]=await this.canRefund(e,s);if(!i)throw new Error(lr.htlcNotExpired(a));const o=this.leafHash(0,e),c=s.map(d=>d.value),u=oa(this.getOutputScript(e,"refund"),s.length),l=ke.Transaction.SIGHASH_DEFAULT;for(let d=0;d<n.ins.length;d++){n.ins[d].sequence=e.source_swap.timelock;const b=n.hashForWitnessV1(d,u,c,l,o),g=await this.signer.signSchnorr(b);n.setWitness(d,[g,this.refundLeaf(e.source_swap.timelock,De(e.source_swap.initiator)),await this.generateControlBlockFor(0,e)])}const p=await(await this.getProvider()).broadcast(n.toHex());return m.Ok(p)}async canRefund(e,r){const s=await(await this.getProvider()).getLatestTip();for(const i of r){let a=0;if(i.status.confirmed&&i.status.block_height+e.source_swap.timelock>s?a=i.status.block_height+e.source_swap.timelock-s+1:i.status.confirmed||(a=e.source_swap.timelock+1),a>0)return[!1,a]}return[!0,0]}async generateControlBlockFor(e,r){let n,s;switch(e){case 1:n=this.redeemLeaf(m.trim0x(r.destination_swap.secret_hash),De(r.destination_swap.delegate)),s=this.generateLeaves(r,"redeem");break;case 0:n=this.refundLeaf(r.source_swap.timelock,De(r.source_swap.initiator)),s=this.generateLeaves(r,"refund");break;case 2:n=this.instantRefundLeaf(De(r.source_swap.initiator),De(r.destination_swap.delegate)),s=this.generateLeaves(r,"instantRefund");break;default:throw new Error(lr.controlBlockGenerationFailed)}const i=await this.signer.getNetwork(),a=ke.payments.p2tr({internalPubkey:H0(),network:i,scriptTree:s,redeem:{output:n,redeemVersion:tc}});if(!a.witness)throw new Error(lr.controlBlockGenerationFailed);return a.witness[a.witness.length-1]}leafHash(e,r){let n;switch(e){case 1:n=this.redeemLeaf(m.trim0x(r.destination_swap.secret_hash),De(r.destination_swap.delegate));break;case 0:n=this.refundLeaf(r.source_swap.timelock,De(r.source_swap.initiator));break;case 2:n=this.instantRefundLeaf(De(r.source_swap.initiator),De(r.destination_swap.redeemer));break;default:throw new Error(lr.invalidLeaf)}return ke.crypto.taggedHash("TapLeaf",N6(n))}refundLeaf(e,r){return ke.script.fromASM(`
9
+ `,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var nr={};Object.defineProperty(nr,"__esModule",{value:!0});nr.value=nr.prop=void 0;function Xv(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get(){const n=r.call(this);return this[e]=n,n},set(n){Object.defineProperty(this,e,{configurable:!0,enumerable:!0,value:n,writable:!0})}})}nr.prop=Xv;function Yv(t){let e;return()=>(e!==void 0||(e=t()),e)}nr.value=Yv;Object.defineProperty(Zc,"__esModule",{value:!0});Zc.p2data=void 0;const Jv=xt,wc=ar(),Vr=kt,J0=nr,Z0=wc.OPS;function Zv(t,e){if(!t.data&&!t.output)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Vr.typeforce)({network:Vr.typeforce.maybe(Vr.typeforce.Object),output:Vr.typeforce.maybe(Vr.typeforce.Buffer),data:Vr.typeforce.maybe(Vr.typeforce.arrayOf(Vr.typeforce.Buffer))},t);const n={name:"embed",network:t.network||Jv.bitcoin};if(J0.prop(n,"output",()=>{if(t.data)return wc.compile([Z0.OP_RETURN].concat(t.data))}),J0.prop(n,"data",()=>{if(t.output)return wc.decompile(t.output).slice(1)}),e.validate&&t.output){const s=wc.decompile(t.output);if(s[0]!==Z0.OP_RETURN)throw new TypeError("Output is invalid");if(!s.slice(1).every(Vr.typeforce.Buffer))throw new TypeError("Output is invalid");if(t.data&&!(0,Vr.stacksEqual)(t.data,n.data))throw new TypeError("Data mismatch")}return Object.assign(n,t)}Zc.p2data=Zv;var Qc={};Object.defineProperty(Qc,"__esModule",{value:!0});Qc.p2ms=void 0;const Qv=xt,gi=ar(),Xe=kt,qn=nr,wi=gi.OPS,Yo=wi.OP_RESERVED;function e5(t,e){if(!t.input&&!t.output&&!(t.pubkeys&&t.m!==void 0)&&!t.signatures)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{});function r(c){return gi.isCanonicalScriptSignature(c)||(e.allowIncomplete&&c===wi.OP_0)!==void 0}(0,Xe.typeforce)({network:Xe.typeforce.maybe(Xe.typeforce.Object),m:Xe.typeforce.maybe(Xe.typeforce.Number),n:Xe.typeforce.maybe(Xe.typeforce.Number),output:Xe.typeforce.maybe(Xe.typeforce.Buffer),pubkeys:Xe.typeforce.maybe(Xe.typeforce.arrayOf(Xe.isPoint)),signatures:Xe.typeforce.maybe(Xe.typeforce.arrayOf(r)),input:Xe.typeforce.maybe(Xe.typeforce.Buffer)},t);const s={network:t.network||Qv.bitcoin};let i=[],a=!1;function o(c){a||(a=!0,i=gi.decompile(c),s.m=i[0]-Yo,s.n=i[i.length-2]-Yo,s.pubkeys=i.slice(1,-2))}if(qn.prop(s,"output",()=>{if(t.m&&s.n&&t.pubkeys)return gi.compile([].concat(Yo+t.m,t.pubkeys,Yo+s.n,wi.OP_CHECKMULTISIG))}),qn.prop(s,"m",()=>{if(s.output)return o(s.output),s.m}),qn.prop(s,"n",()=>{if(s.pubkeys)return s.pubkeys.length}),qn.prop(s,"pubkeys",()=>{if(t.output)return o(t.output),s.pubkeys}),qn.prop(s,"signatures",()=>{if(t.input)return gi.decompile(t.input).slice(1)}),qn.prop(s,"input",()=>{if(t.signatures)return gi.compile([wi.OP_0].concat(t.signatures))}),qn.prop(s,"witness",()=>{if(s.input)return[]}),qn.prop(s,"name",()=>{if(!(!s.m||!s.n))return`p2ms(${s.m} of ${s.n})`}),e.validate){if(t.output){if(o(t.output),!Xe.typeforce.Number(i[0]))throw new TypeError("Output is invalid");if(!Xe.typeforce.Number(i[i.length-2]))throw new TypeError("Output is invalid");if(i[i.length-1]!==wi.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(s.m<=0||s.n>16||s.m>s.n||s.n!==i.length-3)throw new TypeError("Output is invalid");if(!s.pubkeys.every(c=>(0,Xe.isPoint)(c)))throw new TypeError("Output is invalid");if(t.m!==void 0&&t.m!==s.m)throw new TypeError("m mismatch");if(t.n!==void 0&&t.n!==s.n)throw new TypeError("n mismatch");if(t.pubkeys&&!(0,Xe.stacksEqual)(t.pubkeys,s.pubkeys))throw new TypeError("Pubkeys mismatch")}if(t.pubkeys){if(t.n!==void 0&&t.n!==t.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(s.n=t.pubkeys.length,s.n<s.m)throw new TypeError("Pubkey count cannot be less than m")}if(t.signatures){if(t.signatures.length<s.m)throw new TypeError("Not enough signatures provided");if(t.signatures.length>s.m)throw new TypeError("Too many signatures provided")}if(t.input){if(t.input[0]!==wi.OP_0)throw new TypeError("Input is invalid");if(s.signatures.length===0||!s.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(t.signatures&&!(0,Xe.stacksEqual)(t.signatures,s.signatures))throw new TypeError("Signature mismatch");if(t.m!==void 0&&t.m!==t.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(s,t)}Qc.p2ms=e5;var eu={};Object.defineProperty(eu,"__esModule",{value:!0});eu.p2pk=void 0;const t5=xt,vi=ar(),vr=kt,pi=nr,Q0=vi.OPS;function r5(t,e){if(!t.input&&!t.output&&!t.pubkey&&!t.input&&!t.signature)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,vr.typeforce)({network:vr.typeforce.maybe(vr.typeforce.Object),output:vr.typeforce.maybe(vr.typeforce.Buffer),pubkey:vr.typeforce.maybe(vr.isPoint),signature:vr.typeforce.maybe(vi.isCanonicalScriptSignature),input:vr.typeforce.maybe(vr.typeforce.Buffer)},t);const r=pi.value(()=>vi.decompile(t.input)),s={name:"p2pk",network:t.network||t5.bitcoin};if(pi.prop(s,"output",()=>{if(t.pubkey)return vi.compile([t.pubkey,Q0.OP_CHECKSIG])}),pi.prop(s,"pubkey",()=>{if(t.output)return t.output.slice(1,-1)}),pi.prop(s,"signature",()=>{if(t.input)return r()[0]}),pi.prop(s,"input",()=>{if(t.signature)return vi.compile([t.signature])}),pi.prop(s,"witness",()=>{if(s.input)return[]}),e.validate){if(t.output){if(t.output[t.output.length-1]!==Q0.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!(0,vr.isPoint)(s.pubkey))throw new TypeError("Output pubkey is invalid");if(t.pubkey&&!t.pubkey.equals(s.pubkey))throw new TypeError("Pubkey mismatch")}if(t.signature&&t.input&&!t.input.equals(s.input))throw new TypeError("Signature mismatch");if(t.input){if(r().length!==1)throw new TypeError("Input is invalid");if(!vi.isCanonicalScriptSignature(s.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(s,t)}eu.p2pk=r5;var tu={};function n5(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r<e.length;r++)e[r]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=n}var a=t.length,o=t.charAt(0),c=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function l(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var b=0,g=0,A=0,S=d.length;A!==S&&d[A]===0;)A++,b++;for(var T=(S-A)*u+1>>>0,v=new Uint8Array(T);A!==S;){for(var w=d[A],x=0,_=T-1;(w!==0||x<g)&&_!==-1;_--,x++)w+=256*v[_]>>>0,v[_]=w%a>>>0,w=w/a>>>0;if(w!==0)throw new Error("Non-zero carry");g=x,A++}for(var I=T-g;I!==T&&v[I]===0;)I++;for(var N=o.repeat(b);I<T;++I)N+=t.charAt(v[I]);return N}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;for(var b=0,g=0,A=0;d[b]===o;)g++,b++;for(var S=(d.length-b)*c+1>>>0,T=new Uint8Array(S);d[b];){var v=d.charCodeAt(b);if(v>255)return;var w=e[v];if(w===255)return;for(var x=0,_=S-1;(w!==0||x<A)&&_!==-1;_--,x++)w+=a*T[_]>>>0,T[_]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");A=x,b++}for(var I=S-A;I!==S&&T[I]===0;)I++;for(var N=new Uint8Array(g+(S-I)),C=g;I!==S;)N[C++]=T[I++];return N}function p(d){var b=f(d);if(b)return b;throw new Error("Non-base"+a+" character")}return{encode:l,decodeUnsafe:f,decode:p}}var s5=n5;const i5=s5,a5="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";var o5=i5(a5),Yu=o5,c5=function(t){function e(i){var a=Uint8Array.from(i),o=t(a),c=a.length+4,u=new Uint8Array(c);return u.set(a,0),u.set(o.subarray(0,4),a.length),Yu.encode(u,c)}function r(i){var a=i.slice(0,-4),o=i.slice(-4),c=t(a);if(!(o[0]^c[0]|o[1]^c[1]|o[2]^c[2]|o[3]^c[3]))return a}function n(i){var a=Yu.decodeUnsafe(i);if(a)return r(a)}function s(i){var a=Yu.decode(i),o=r(a);if(!o)throw new Error("Invalid checksum");return o}return{encode:e,decode:s,decodeUnsafe:n}},{sha256:ep}=Ir,u5=c5;function l5(t){return ep(ep(t))}var lh=u5(l5);Object.defineProperty(tu,"__esModule",{value:!0});tu.p2pkh=void 0;const Ju=vs,f5=xt,Ei=ar(),Ot=kt,fn=nr,tp=lh,Wn=Ei.OPS;function d5(t,e){if(!t.address&&!t.hash&&!t.output&&!t.pubkey&&!t.input)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Ot.typeforce)({network:Ot.typeforce.maybe(Ot.typeforce.Object),address:Ot.typeforce.maybe(Ot.typeforce.String),hash:Ot.typeforce.maybe(Ot.typeforce.BufferN(20)),output:Ot.typeforce.maybe(Ot.typeforce.BufferN(25)),pubkey:Ot.typeforce.maybe(Ot.isPoint),signature:Ot.typeforce.maybe(Ei.isCanonicalScriptSignature),input:Ot.typeforce.maybe(Ot.typeforce.Buffer)},t);const r=fn.value(()=>{const a=Buffer.from(tp.decode(t.address)),o=a.readUInt8(0),c=a.slice(1);return{version:o,hash:c}}),n=fn.value(()=>Ei.decompile(t.input)),s=t.network||f5.bitcoin,i={name:"p2pkh",network:s};if(fn.prop(i,"address",()=>{if(!i.hash)return;const a=Buffer.allocUnsafe(21);return a.writeUInt8(s.pubKeyHash,0),i.hash.copy(a,1),tp.encode(a)}),fn.prop(i,"hash",()=>{if(t.output)return t.output.slice(3,23);if(t.address)return r().hash;if(t.pubkey||i.pubkey)return Ju.hash160(t.pubkey||i.pubkey)}),fn.prop(i,"output",()=>{if(i.hash)return Ei.compile([Wn.OP_DUP,Wn.OP_HASH160,i.hash,Wn.OP_EQUALVERIFY,Wn.OP_CHECKSIG])}),fn.prop(i,"pubkey",()=>{if(t.input)return n()[1]}),fn.prop(i,"signature",()=>{if(t.input)return n()[0]}),fn.prop(i,"input",()=>{if(t.pubkey&&t.signature)return Ei.compile([t.signature,t.pubkey])}),fn.prop(i,"witness",()=>{if(i.input)return[]}),e.validate){let a=Buffer.from([]);if(t.address){if(r().version!==s.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(r().hash.length!==20)throw new TypeError("Invalid address");a=r().hash}if(t.hash){if(a.length>0&&!a.equals(t.hash))throw new TypeError("Hash mismatch");a=t.hash}if(t.output){if(t.output.length!==25||t.output[0]!==Wn.OP_DUP||t.output[1]!==Wn.OP_HASH160||t.output[2]!==20||t.output[23]!==Wn.OP_EQUALVERIFY||t.output[24]!==Wn.OP_CHECKSIG)throw new TypeError("Output is invalid");const o=t.output.slice(3,23);if(a.length>0&&!a.equals(o))throw new TypeError("Hash mismatch");a=o}if(t.pubkey){const o=Ju.hash160(t.pubkey);if(a.length>0&&!a.equals(o))throw new TypeError("Hash mismatch");a=o}if(t.input){const o=n();if(o.length!==2)throw new TypeError("Input is invalid");if(!Ei.isCanonicalScriptSignature(o[0]))throw new TypeError("Input has invalid signature");if(!(0,Ot.isPoint)(o[1]))throw new TypeError("Input has invalid pubkey");if(t.signature&&!t.signature.equals(o[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(o[1]))throw new TypeError("Pubkey mismatch");const c=Ju.hash160(o[1]);if(a.length>0&&!a.equals(c))throw new TypeError("Hash mismatch")}}return Object.assign(i,t)}tu.p2pkh=d5;var ru={};Object.defineProperty(ru,"__esModule",{value:!0});ru.p2sh=void 0;const rp=vs,h5=xt,Yr=ar(),Fe=kt,Gr=nr,np=lh,ua=Yr.OPS;function p5(t,e){if(!t.address&&!t.hash&&!t.output&&!t.redeem&&!t.input)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Fe.typeforce)({network:Fe.typeforce.maybe(Fe.typeforce.Object),address:Fe.typeforce.maybe(Fe.typeforce.String),hash:Fe.typeforce.maybe(Fe.typeforce.BufferN(20)),output:Fe.typeforce.maybe(Fe.typeforce.BufferN(23)),redeem:Fe.typeforce.maybe({network:Fe.typeforce.maybe(Fe.typeforce.Object),output:Fe.typeforce.maybe(Fe.typeforce.Buffer),input:Fe.typeforce.maybe(Fe.typeforce.Buffer),witness:Fe.typeforce.maybe(Fe.typeforce.arrayOf(Fe.typeforce.Buffer))}),input:Fe.typeforce.maybe(Fe.typeforce.Buffer),witness:Fe.typeforce.maybe(Fe.typeforce.arrayOf(Fe.typeforce.Buffer))},t);let r=t.network;r||(r=t.redeem&&t.redeem.network||h5.bitcoin);const n={network:r},s=Gr.value(()=>{const o=Buffer.from(np.decode(t.address)),c=o.readUInt8(0),u=o.slice(1);return{version:c,hash:u}}),i=Gr.value(()=>Yr.decompile(t.input)),a=Gr.value(()=>{const o=i(),c=o[o.length-1];return{network:r,output:c===ua.OP_FALSE?Buffer.from([]):c,input:Yr.compile(o.slice(0,-1)),witness:t.witness||[]}});if(Gr.prop(n,"address",()=>{if(!n.hash)return;const o=Buffer.allocUnsafe(21);return o.writeUInt8(n.network.scriptHash,0),n.hash.copy(o,1),np.encode(o)}),Gr.prop(n,"hash",()=>{if(t.output)return t.output.slice(2,22);if(t.address)return s().hash;if(n.redeem&&n.redeem.output)return rp.hash160(n.redeem.output)}),Gr.prop(n,"output",()=>{if(n.hash)return Yr.compile([ua.OP_HASH160,n.hash,ua.OP_EQUAL])}),Gr.prop(n,"redeem",()=>{if(t.input)return a()}),Gr.prop(n,"input",()=>{if(!(!t.redeem||!t.redeem.input||!t.redeem.output))return Yr.compile([].concat(Yr.decompile(t.redeem.input),t.redeem.output))}),Gr.prop(n,"witness",()=>{if(n.redeem&&n.redeem.witness)return n.redeem.witness;if(n.input)return[]}),Gr.prop(n,"name",()=>{const o=["p2sh"];return n.redeem!==void 0&&n.redeem.name!==void 0&&o.push(n.redeem.name),o.join("-")}),e.validate){let o=Buffer.from([]);if(t.address){if(s().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(s().hash.length!==20)throw new TypeError("Invalid address");o=s().hash}if(t.hash){if(o.length>0&&!o.equals(t.hash))throw new TypeError("Hash mismatch");o=t.hash}if(t.output){if(t.output.length!==23||t.output[0]!==ua.OP_HASH160||t.output[1]!==20||t.output[22]!==ua.OP_EQUAL)throw new TypeError("Output is invalid");const u=t.output.slice(2,22);if(o.length>0&&!o.equals(u))throw new TypeError("Hash mismatch");o=u}const c=u=>{if(u.output){const l=Yr.decompile(u.output);if(!l||l.length<1)throw new TypeError("Redeem.output too short");if(u.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(Yr.countNonPushOnlyOPs(l)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const f=rp.hash160(u.output);if(o.length>0&&!o.equals(f))throw new TypeError("Hash mismatch");o=f}if(u.input){const l=u.input.length>0,f=u.witness&&u.witness.length>0;if(!l&&!f)throw new TypeError("Empty input");if(l&&f)throw new TypeError("Input and witness provided");if(l){const p=Yr.decompile(u.input);if(!Yr.isPushOnly(p))throw new TypeError("Non push-only scriptSig")}}};if(t.input){const u=i();if(!u||u.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(a().output))throw new TypeError("Input is invalid");c(a())}if(t.redeem){if(t.redeem.network&&t.redeem.network!==r)throw new TypeError("Network mismatch");if(t.input){const u=a();if(t.redeem.output&&!t.redeem.output.equals(u.output))throw new TypeError("Redeem.output mismatch");if(t.redeem.input&&!t.redeem.input.equals(u.input))throw new TypeError("Redeem.input mismatch")}c(t.redeem)}if(t.witness&&t.redeem&&t.redeem.witness&&!(0,Fe.stacksEqual)(t.redeem.witness,t.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,t)}ru.p2sh=p5;var nu={};Object.defineProperty(nu,"__esModule",{value:!0});nu.p2wpkh=void 0;const Zu=vs,y5=xt,vc=ar(),st=kt,Kn=nr,Jo=us,sp=vc.OPS,m5=Buffer.alloc(0);function b5(t,e){if(!t.address&&!t.hash&&!t.output&&!t.pubkey&&!t.witness)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,st.typeforce)({address:st.typeforce.maybe(st.typeforce.String),hash:st.typeforce.maybe(st.typeforce.BufferN(20)),input:st.typeforce.maybe(st.typeforce.BufferN(0)),network:st.typeforce.maybe(st.typeforce.Object),output:st.typeforce.maybe(st.typeforce.BufferN(22)),pubkey:st.typeforce.maybe(st.isPoint),signature:st.typeforce.maybe(vc.isCanonicalScriptSignature),witness:st.typeforce.maybe(st.typeforce.arrayOf(st.typeforce.Buffer))},t);const r=Kn.value(()=>{const i=Jo.bech32.decode(t.address),a=i.words.shift(),o=Jo.bech32.fromWords(i.words);return{version:a,prefix:i.prefix,data:Buffer.from(o)}}),n=t.network||y5.bitcoin,s={name:"p2wpkh",network:n};if(Kn.prop(s,"address",()=>{if(!s.hash)return;const i=Jo.bech32.toWords(s.hash);return i.unshift(0),Jo.bech32.encode(n.bech32,i)}),Kn.prop(s,"hash",()=>{if(t.output)return t.output.slice(2,22);if(t.address)return r().data;if(t.pubkey||s.pubkey)return Zu.hash160(t.pubkey||s.pubkey)}),Kn.prop(s,"output",()=>{if(s.hash)return vc.compile([sp.OP_0,s.hash])}),Kn.prop(s,"pubkey",()=>{if(t.pubkey)return t.pubkey;if(t.witness)return t.witness[1]}),Kn.prop(s,"signature",()=>{if(t.witness)return t.witness[0]}),Kn.prop(s,"input",()=>{if(s.witness)return m5}),Kn.prop(s,"witness",()=>{if(t.pubkey&&t.signature)return[t.signature,t.pubkey]}),e.validate){let i=Buffer.from([]);if(t.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==20)throw new TypeError("Invalid address data");i=r().data}if(t.hash){if(i.length>0&&!i.equals(t.hash))throw new TypeError("Hash mismatch");i=t.hash}if(t.output){if(t.output.length!==22||t.output[0]!==sp.OP_0||t.output[1]!==20)throw new TypeError("Output is invalid");if(i.length>0&&!i.equals(t.output.slice(2)))throw new TypeError("Hash mismatch");i=t.output.slice(2)}if(t.pubkey){const a=Zu.hash160(t.pubkey);if(i.length>0&&!i.equals(a))throw new TypeError("Hash mismatch");if(i=a,!(0,st.isPoint)(t.pubkey)||t.pubkey.length!==33)throw new TypeError("Invalid pubkey for p2wpkh")}if(t.witness){if(t.witness.length!==2)throw new TypeError("Witness is invalid");if(!vc.isCanonicalScriptSignature(t.witness[0]))throw new TypeError("Witness has invalid signature");if(!(0,st.isPoint)(t.witness[1])||t.witness[1].length!==33)throw new TypeError("Witness has invalid pubkey");if(t.signature&&!t.signature.equals(t.witness[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(t.witness[1]))throw new TypeError("Pubkey mismatch");const a=Zu.hash160(t.witness[1]);if(i.length>0&&!i.equals(a))throw new TypeError("Hash mismatch")}}return Object.assign(s,t)}nu.p2wpkh=b5;var su={};Object.defineProperty(su,"__esModule",{value:!0});su.p2wsh=void 0;const ip=vs,g5=xt,vn=ar(),Re=kt,dn=nr,Zo=us,ap=vn.OPS,Qu=Buffer.alloc(0);function Qo(t){return!!(Buffer.isBuffer(t)&&t.length===65&&t[0]===4&&(0,Re.isPoint)(t))}function w5(t,e){if(!t.address&&!t.hash&&!t.output&&!t.redeem&&!t.witness)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),(0,Re.typeforce)({network:Re.typeforce.maybe(Re.typeforce.Object),address:Re.typeforce.maybe(Re.typeforce.String),hash:Re.typeforce.maybe(Re.typeforce.BufferN(32)),output:Re.typeforce.maybe(Re.typeforce.BufferN(34)),redeem:Re.typeforce.maybe({input:Re.typeforce.maybe(Re.typeforce.Buffer),network:Re.typeforce.maybe(Re.typeforce.Object),output:Re.typeforce.maybe(Re.typeforce.Buffer),witness:Re.typeforce.maybe(Re.typeforce.arrayOf(Re.typeforce.Buffer))}),input:Re.typeforce.maybe(Re.typeforce.BufferN(0)),witness:Re.typeforce.maybe(Re.typeforce.arrayOf(Re.typeforce.Buffer))},t);const r=dn.value(()=>{const a=Zo.bech32.decode(t.address),o=a.words.shift(),c=Zo.bech32.fromWords(a.words);return{version:o,prefix:a.prefix,data:Buffer.from(c)}}),n=dn.value(()=>vn.decompile(t.redeem.input));let s=t.network;s||(s=t.redeem&&t.redeem.network||g5.bitcoin);const i={network:s};if(dn.prop(i,"address",()=>{if(!i.hash)return;const a=Zo.bech32.toWords(i.hash);return a.unshift(0),Zo.bech32.encode(s.bech32,a)}),dn.prop(i,"hash",()=>{if(t.output)return t.output.slice(2);if(t.address)return r().data;if(i.redeem&&i.redeem.output)return ip.sha256(i.redeem.output)}),dn.prop(i,"output",()=>{if(i.hash)return vn.compile([ap.OP_0,i.hash])}),dn.prop(i,"redeem",()=>{if(t.witness)return{output:t.witness[t.witness.length-1],input:Qu,witness:t.witness.slice(0,-1)}}),dn.prop(i,"input",()=>{if(i.witness)return Qu}),dn.prop(i,"witness",()=>{if(t.redeem&&t.redeem.input&&t.redeem.input.length>0&&t.redeem.output&&t.redeem.output.length>0){const a=vn.toStack(n());return i.redeem=Object.assign({witness:a},t.redeem),i.redeem.input=Qu,[].concat(a,t.redeem.output)}if(t.redeem&&t.redeem.output&&t.redeem.witness)return[].concat(t.redeem.witness,t.redeem.output)}),dn.prop(i,"name",()=>{const a=["p2wsh"];return i.redeem!==void 0&&i.redeem.name!==void 0&&a.push(i.redeem.name),a.join("-")}),e.validate){let a=Buffer.from([]);if(t.address){if(r().prefix!==s.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==32)throw new TypeError("Invalid address data");a=r().data}if(t.hash){if(a.length>0&&!a.equals(t.hash))throw new TypeError("Hash mismatch");a=t.hash}if(t.output){if(t.output.length!==34||t.output[0]!==ap.OP_0||t.output[1]!==32)throw new TypeError("Output is invalid");const o=t.output.slice(2);if(a.length>0&&!a.equals(o))throw new TypeError("Hash mismatch");a=o}if(t.redeem){if(t.redeem.network&&t.redeem.network!==s)throw new TypeError("Network mismatch");if(t.redeem.input&&t.redeem.input.length>0&&t.redeem.witness&&t.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(t.redeem.output){const o=vn.decompile(t.redeem.output);if(!o||o.length<1)throw new TypeError("Redeem.output is invalid");if(t.redeem.output.byteLength>3600)throw new TypeError("Redeem.output unspendable if larger than 3600 bytes");if(vn.countNonPushOnlyOPs(o)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const c=ip.sha256(t.redeem.output);if(a.length>0&&!a.equals(c))throw new TypeError("Hash mismatch");a=c}if(t.redeem.input&&!vn.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(t.witness&&t.redeem.witness&&!(0,Re.stacksEqual)(t.witness,t.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(t.redeem.input&&n().some(Qo)||t.redeem.output&&(vn.decompile(t.redeem.output)||[]).some(Qo))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(t.witness&&t.witness.length>0){const o=t.witness[t.witness.length-1];if(t.redeem&&t.redeem.output&&!t.redeem.output.equals(o))throw new TypeError("Witness and redeem.output mismatch");if(t.witness.some(Qo)||(vn.decompile(o)||[]).some(Qo))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(i,t)}su.p2wsh=w5;var la={},Ks={};Object.defineProperty(Ks,"__esModule",{value:!0});Ks.getEccLib=Ks.initEccLib=void 0;const _a={};function v5(t,e){t?t!==_a.eccLib&&(e!=null&&e.DANGER_DO_NOT_VERIFY_ECCLIB||A5(t),_a.eccLib=t):_a.eccLib=t}Ks.initEccLib=v5;function E5(){if(!_a.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return _a.eccLib}Ks.getEccLib=E5;const hn=t=>Buffer.from(t,"hex");function A5(t){ur(typeof t.isXOnlyPoint=="function"),ur(t.isXOnlyPoint(hn("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),ur(t.isXOnlyPoint(hn("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),ur(t.isXOnlyPoint(hn("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),ur(t.isXOnlyPoint(hn("0000000000000000000000000000000000000000000000000000000000000001"))),ur(!t.isXOnlyPoint(hn("0000000000000000000000000000000000000000000000000000000000000000"))),ur(!t.isXOnlyPoint(hn("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),ur(typeof t.xOnlyPointAddTweak=="function"),S5.forEach(e=>{const r=t.xOnlyPointAddTweak(hn(e.pubkey),hn(e.tweak));e.result===null?ur(r===null):(ur(r!==null),ur(r.parity===e.parity),ur(Buffer.from(r.xOnlyPubkey).equals(hn(e.result))))})}function ur(t){if(!t)throw new Error("ecc library invalid")}const S5=[{pubkey:"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",tweak:"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140",parity:-1,result:null},{pubkey:"1617d38ed8d8657da4d4761e8057bc396ea9e4b9d29776d4be096016dbd2509b",tweak:"a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac",parity:1,result:"e478f99dab91052ab39a33ea35fd5e6e4933f4d28023cd597c9a1f6760346adf"},{pubkey:"2c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991",tweak:"823c3cd2142744b075a87eade7e1b8678ba308d566226a0056ca2b7a76f86b47",parity:0,result:"9534f8dc8c6deda2dc007655981c78b49c5d96c778fbf363462a11ec9dfd948c"}];var fh={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.tweakKey=t.tapTweakHash=t.tapleafHash=t.findScriptPath=t.toHashTree=t.rootHashFromPath=t.MAX_TAPTREE_DEPTH=t.LEAF_VERSION_TAPSCRIPT=void 0;const e=ii,r=Ks,n=vs,s=pt,i=kt;t.LEAF_VERSION_TAPSCRIPT=192,t.MAX_TAPTREE_DEPTH=128;const a=g=>"left"in g&&"right"in g;function o(g,A){if(g.length<33)throw new TypeError(`The control-block length is too small. Got ${g.length}, expected min 33.`);const S=(g.length-33)/32;let T=A;for(let v=0;v<S;v++){const w=g.slice(33+32*v,65+32*v);T.compare(w)<0?T=d(T,w):T=d(w,T)}return T}t.rootHashFromPath=o;function c(g){if((0,i.isTapleaf)(g))return{hash:l(g)};const A=[c(g[0]),c(g[1])];A.sort((v,w)=>v.hash.compare(w.hash));const[S,T]=A;return{hash:d(S.hash,T.hash),left:S,right:T}}t.toHashTree=c;function u(g,A){if(a(g)){const S=u(g.left,A);if(S!==void 0)return[...S,g.right.hash];const T=u(g.right,A);if(T!==void 0)return[...T,g.left.hash]}else if(g.hash.equals(A))return[]}t.findScriptPath=u;function l(g){const A=g.version||t.LEAF_VERSION_TAPSCRIPT;return n.taggedHash("TapLeaf",e.Buffer.concat([e.Buffer.from([A]),b(g.output)]))}t.tapleafHash=l;function f(g,A){return n.taggedHash("TapTweak",e.Buffer.concat(A?[g,A]:[g]))}t.tapTweakHash=f;function p(g,A){if(!e.Buffer.isBuffer(g)||g.length!==32||A&&A.length!==32)return null;const S=f(g,A),T=(0,r.getEccLib)().xOnlyPointAddTweak(g,S);return!T||T.xOnlyPubkey===null?null:{parity:T.parity,x:e.Buffer.from(T.xOnlyPubkey)}}t.tweakKey=p;function d(g,A){return n.taggedHash("TapBranch",e.Buffer.concat([g,A]))}function b(g){const A=s.varuint.encodingLength(g.length),S=e.Buffer.allocUnsafe(A);return s.varuint.encode(g.length,S),e.Buffer.concat([S,g])}})(fh);var Bt={},op;function x5(){if(op)return Bt;op=1,Object.defineProperty(Bt,"__esModule",{value:!0}),Bt.toOutputScript=Bt.fromOutputScript=Bt.toBech32=Bt.toBase58Check=Bt.fromBech32=Bt.fromBase58Check=void 0;const t=xt,e=dh(),r=ar(),n=kt,s=us,i=lh,a=40,o=2,c=16,u=2,l=80,f="WARNING: Sending to a future segwit version address can lead to loss of funds. End users MUST be warned carefully in the GUI and asked if they wish to proceed with caution. Wallets should verify the segwit version from the output of fromBech32, then decide when it is safe to use which version of segwit.";function p(v,w){const x=v.slice(2);if(x.length<o||x.length>a)throw new TypeError("Invalid program length for segwit address");const _=v[0]-l;if(_<u||_>c)throw new TypeError("Invalid version for segwit address");if(v[1]!==x.length)throw new TypeError("Invalid script for segwit address");return console.warn(f),A(x,_,w.bech32)}function d(v){const w=Buffer.from(i.decode(v));if(w.length<21)throw new TypeError(v+" is too short");if(w.length>21)throw new TypeError(v+" is too long");const x=w.readUInt8(0),_=w.slice(1);return{version:x,hash:_}}Bt.fromBase58Check=d;function b(v){let w,x;try{w=s.bech32.decode(v)}catch{}if(w){if(x=w.words[0],x!==0)throw new TypeError(v+" uses wrong encoding")}else if(w=s.bech32m.decode(v),x=w.words[0],x===0)throw new TypeError(v+" uses wrong encoding");const _=s.bech32.fromWords(w.words.slice(1));return{version:x,prefix:w.prefix,data:Buffer.from(_)}}Bt.fromBech32=b;function g(v,w){(0,n.typeforce)((0,n.tuple)(n.Hash160bit,n.UInt8),arguments);const x=Buffer.allocUnsafe(21);return x.writeUInt8(w,0),v.copy(x,1),i.encode(x)}Bt.toBase58Check=g;function A(v,w,x){const _=s.bech32.toWords(v);return _.unshift(w),w===0?s.bech32.encode(x,_):s.bech32m.encode(x,_)}Bt.toBech32=A;function S(v,w){w=w||t.bitcoin;try{return e.p2pkh({output:v,network:w}).address}catch{}try{return e.p2sh({output:v,network:w}).address}catch{}try{return e.p2wpkh({output:v,network:w}).address}catch{}try{return e.p2wsh({output:v,network:w}).address}catch{}try{return e.p2tr({output:v,network:w}).address}catch{}try{return p(v,w)}catch{}throw new Error(r.toASM(v)+" has no matching Address")}Bt.fromOutputScript=S;function T(v,w){w=w||t.bitcoin;let x,_;try{x=d(v)}catch{}if(x){if(x.version===w.pubKeyHash)return e.p2pkh({hash:x.hash}).output;if(x.version===w.scriptHash)return e.p2sh({hash:x.hash}).output}else{try{_=b(v)}catch{}if(_){if(_.prefix!==w.bech32)throw new Error(v+" has an invalid prefix");if(_.version===0){if(_.data.length===20)return e.p2wpkh({hash:_.data}).output;if(_.data.length===32)return e.p2wsh({hash:_.data}).output}else if(_.version===1){if(_.data.length===32)return e.p2tr({pubkey:_.data}).output}else if(_.version>=u&&_.version<=c&&_.data.length>=o&&_.data.length<=a)return console.warn(f),r.compile([_.version+l,_.data])}}throw new Error(v+" has no matching Script")}return Bt.toOutputScript=T,Bt}var cp;function k5(){if(cp)return la;cp=1,Object.defineProperty(la,"__esModule",{value:!0}),la.p2tr=void 0;const t=ii,e=xt,r=ar(),n=kt,s=Ks,i=fh,a=nr,o=us,c=x5(),u=r.OPS,l=1,f=80;function p(d,b){if(!d.address&&!d.output&&!d.pubkey&&!d.internalPubkey&&!(d.witness&&d.witness.length>1))throw new TypeError("Not enough data");b=Object.assign({validate:!0},b||{}),(0,n.typeforce)({address:n.typeforce.maybe(n.typeforce.String),input:n.typeforce.maybe(n.typeforce.BufferN(0)),network:n.typeforce.maybe(n.typeforce.Object),output:n.typeforce.maybe(n.typeforce.BufferN(34)),internalPubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),hash:n.typeforce.maybe(n.typeforce.BufferN(32)),pubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),signature:n.typeforce.maybe(n.typeforce.anyOf(n.typeforce.BufferN(64),n.typeforce.BufferN(65))),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer)),scriptTree:n.typeforce.maybe(n.isTaptree),redeem:n.typeforce.maybe({output:n.typeforce.maybe(n.typeforce.Buffer),redeemVersion:n.typeforce.maybe(n.typeforce.Number),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer))}),redeemVersion:n.typeforce.maybe(n.typeforce.Number)},d);const g=a.value(()=>(0,c.fromBech32)(d.address)),A=a.value(()=>{if(!(!d.witness||!d.witness.length))return d.witness.length>=2&&d.witness[d.witness.length-1][0]===f?d.witness.slice(0,-1):d.witness.slice()}),S=a.value(()=>{if(d.scriptTree)return(0,i.toHashTree)(d.scriptTree);if(d.hash)return{hash:d.hash}}),T=d.network||e.bitcoin,v={name:"p2tr",network:T};if(a.prop(v,"address",()=>{if(!v.pubkey)return;const w=o.bech32m.toWords(v.pubkey);return w.unshift(l),o.bech32m.encode(T.bech32,w)}),a.prop(v,"hash",()=>{const w=S();if(w)return w.hash;const x=A();if(x&&x.length>1){const _=x[x.length-1],I=_[0]&n.TAPLEAF_VERSION_MASK,N=x[x.length-2],C=(0,i.tapleafHash)({output:N,version:I});return(0,i.rootHashFromPath)(_,C)}return null}),a.prop(v,"output",()=>{if(v.pubkey)return r.compile([u.OP_1,v.pubkey])}),a.prop(v,"redeemVersion",()=>d.redeemVersion?d.redeemVersion:d.redeem&&d.redeem.redeemVersion!==void 0&&d.redeem.redeemVersion!==null?d.redeem.redeemVersion:i.LEAF_VERSION_TAPSCRIPT),a.prop(v,"redeem",()=>{const w=A();if(!(!w||w.length<2))return{output:w[w.length-2],witness:w.slice(0,-2),redeemVersion:w[w.length-1][0]&n.TAPLEAF_VERSION_MASK}}),a.prop(v,"pubkey",()=>{if(d.pubkey)return d.pubkey;if(d.output)return d.output.slice(2);if(d.address)return g().data;if(v.internalPubkey){const w=(0,i.tweakKey)(v.internalPubkey,v.hash);if(w)return w.x}}),a.prop(v,"internalPubkey",()=>{if(d.internalPubkey)return d.internalPubkey;const w=A();if(w&&w.length>1)return w[w.length-1].slice(1,33)}),a.prop(v,"signature",()=>{if(d.signature)return d.signature;const w=A();if(!(!w||w.length!==1))return w[0]}),a.prop(v,"witness",()=>{if(d.witness)return d.witness;const w=S();if(w&&d.redeem&&d.redeem.output&&d.internalPubkey){const x=(0,i.tapleafHash)({output:d.redeem.output,version:v.redeemVersion}),_=(0,i.findScriptPath)(w,x);if(!_)return;const I=(0,i.tweakKey)(d.internalPubkey,w.hash);if(!I)return;const N=t.Buffer.concat([t.Buffer.from([v.redeemVersion|I.parity]),d.internalPubkey].concat(_));return[d.redeem.output,N]}if(d.signature)return[d.signature]}),b.validate){let w=t.Buffer.from([]);if(d.address){if(T&&T.bech32!==g().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(g().version!==l)throw new TypeError("Invalid address version");if(g().data.length!==32)throw new TypeError("Invalid address data");w=g().data}if(d.pubkey){if(w.length>0&&!w.equals(d.pubkey))throw new TypeError("Pubkey mismatch");w=d.pubkey}if(d.output){if(d.output.length!==34||d.output[0]!==u.OP_1||d.output[1]!==32)throw new TypeError("Output is invalid");if(w.length>0&&!w.equals(d.output.slice(2)))throw new TypeError("Pubkey mismatch");w=d.output.slice(2)}if(d.internalPubkey){const I=(0,i.tweakKey)(d.internalPubkey,v.hash);if(w.length>0&&!w.equals(I.x))throw new TypeError("Pubkey mismatch");w=I.x}if(w&&w.length&&!(0,s.getEccLib)().isXOnlyPoint(w))throw new TypeError("Invalid pubkey for p2tr");const x=S();if(d.hash&&x&&!d.hash.equals(x.hash))throw new TypeError("Hash mismatch");if(d.redeem&&d.redeem.output&&x){const I=(0,i.tapleafHash)({output:d.redeem.output,version:v.redeemVersion});if(!(0,i.findScriptPath)(x,I))throw new TypeError("Redeem script not in tree")}const _=A();if(d.redeem&&v.redeem){if(d.redeem.redeemVersion&&d.redeem.redeemVersion!==v.redeem.redeemVersion)throw new TypeError("Redeem.redeemVersion and witness mismatch");if(d.redeem.output){if(r.decompile(d.redeem.output).length===0)throw new TypeError("Redeem.output is invalid");if(v.redeem.output&&!d.redeem.output.equals(v.redeem.output))throw new TypeError("Redeem.output and witness mismatch")}if(d.redeem.witness&&v.redeem.witness&&!(0,n.stacksEqual)(d.redeem.witness,v.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(_&&_.length)if(_.length===1){if(d.signature&&!d.signature.equals(_[0]))throw new TypeError("Signature mismatch")}else{const I=_[_.length-1];if(I.length<33)throw new TypeError(`The control-block length is too small. Got ${I.length}, expected min 33.`);if((I.length-33)%32!==0)throw new TypeError(`The control-block length of ${I.length} is incorrect!`);const N=(I.length-33)/32;if(N>128)throw new TypeError(`The script path is too long. Got ${N}, expected max 128.`);const C=I.slice(1,33);if(d.internalPubkey&&!d.internalPubkey.equals(C))throw new TypeError("Internal pubkey mismatch");if(!(0,s.getEccLib)().isXOnlyPoint(C))throw new TypeError("Invalid internalPubkey for p2tr witness");const j=I[0]&n.TAPLEAF_VERSION_MASK,M=_[_.length-2],H=(0,i.tapleafHash)({output:M,version:j}),V=(0,i.rootHashFromPath)(I,H),Q=(0,i.tweakKey)(C,V);if(!Q)throw new TypeError("Invalid outputKey for p2tr witness");if(w.length&&!w.equals(Q.x))throw new TypeError("Pubkey mismatch for p2tr witness");if(Q.parity!==(I[0]&1))throw new Error("Incorrect parity")}}return Object.assign(v,d)}return la.p2tr=p,la}var up;function dh(){return up||(up=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.p2tr=t.p2wsh=t.p2wpkh=t.p2sh=t.p2pkh=t.p2pk=t.p2ms=t.embed=void 0;const e=Zc;Object.defineProperty(t,"embed",{enumerable:!0,get:function(){return e.p2data}});const r=Qc;Object.defineProperty(t,"p2ms",{enumerable:!0,get:function(){return r.p2ms}});const n=eu;Object.defineProperty(t,"p2pk",{enumerable:!0,get:function(){return n.p2pk}});const s=tu;Object.defineProperty(t,"p2pkh",{enumerable:!0,get:function(){return s.p2pkh}});const i=ru;Object.defineProperty(t,"p2sh",{enumerable:!0,get:function(){return i.p2sh}});const a=nu;Object.defineProperty(t,"p2wpkh",{enumerable:!0,get:function(){return a.p2wpkh}});const o=su;Object.defineProperty(t,"p2wsh",{enumerable:!0,get:function(){return o.p2wsh}});const c=k5();Object.defineProperty(t,"p2tr",{enumerable:!0,get:function(){return c.p2tr}})}(Xu)),Xu}Object.defineProperty(Be,"__esModule",{value:!0});Be.signatureBlocksAction=Be.checkInputForSig=Be.pubkeyInScript=Be.pubkeyPositionInScript=Be.witnessStackToScriptWitness=Be.isP2TR=Be.isP2SHScript=Be.isP2WSHScript=Be.isP2WPKH=Be.isP2PKH=Be.isP2PK=Be.isP2MS=void 0;const lp=So,Ia=ar(),ec=Eo,T5=vs,ai=dh();function oi(t){return e=>{try{return t({output:e}),!0}catch{return!1}}}Be.isP2MS=oi(ai.p2ms);Be.isP2PK=oi(ai.p2pk);Be.isP2PKH=oi(ai.p2pkh);Be.isP2WPKH=oi(ai.p2wpkh);Be.isP2WSHScript=oi(ai.p2wsh);Be.isP2SHScript=oi(ai.p2sh);Be.isP2TR=oi(ai.p2tr);function _5(t){let e=Buffer.allocUnsafe(0);function r(a){e=Buffer.concat([e,Buffer.from(a)])}function n(a){const o=e.length,c=lp.encodingLength(a);e=Buffer.concat([e,Buffer.allocUnsafe(c)]),lp.encode(a,e,o)}function s(a){n(a.length),r(a)}function i(a){n(a.length),a.forEach(s)}return i(t),e}Be.witnessStackToScriptWitness=_5;function Ub(t,e){const r=(0,T5.hash160)(t),n=t.slice(1,33),s=Ia.decompile(e);if(s===null)throw new Error("Unknown script error");return s.findIndex(i=>typeof i=="number"?!1:i.equals(t)||i.equals(r)||i.equals(n))}Be.pubkeyPositionInScript=Ub;function I5(t,e){return Ub(t,e)!==-1}Be.pubkeyInScript=I5;function P5(t,e){return O5(t).some(n=>Fb(n,Ia.signature.decode,e))}Be.checkInputForSig=P5;function Fb(t,e,r){const{hashType:n}=e(t),s=[];switch(n&ec.Transaction.SIGHASH_ANYONECANPAY&&s.push("addInput"),n&31){case ec.Transaction.SIGHASH_ALL:break;case ec.Transaction.SIGHASH_SINGLE:case ec.Transaction.SIGHASH_NONE:s.push("addOutput"),s.push("setInputSequence");break}return s.indexOf(r)===-1}Be.signatureBlocksAction=Fb;function O5(t){let e=[];if((t.partialSig||[]).length===0){if(!t.finalScriptSig&&!t.finalScriptWitness)return[];e=B5(t)}else e=t.partialSig;return e.map(r=>r.signature)}function B5(t){const e=t.finalScriptSig?Ia.decompile(t.finalScriptSig)||[]:[],r=t.finalScriptWitness?Ia.decompile(t.finalScriptWitness)||[]:[];return e.concat(r).filter(n=>Buffer.isBuffer(n)&&Ia.isCanonicalScriptSignature(n)).map(n=>({signature:n}))}Object.defineProperty(ze,"__esModule",{value:!0});ze.checkTaprootInputForSigs=ze.tapTreeFromList=ze.tapTreeToList=ze.tweakInternalPubKey=ze.checkTaprootOutputFields=ze.checkTaprootInputFields=ze.isTaprootOutput=ze.isTaprootInput=Ea=ze.serializeTaprootSignature=ze.tapScriptFinalizer=ze.toXOnly=void 0;const hh=kt,C5=Eo,iu=Be,hs=fh,R5=dh(),N5=Be,U5=t=>t.length===32?t:t.slice(1,33);ze.toXOnly=U5;function F5(t,e,r){const n=eE(e,t,r);try{const i=Z5(e,n).concat(n.script).concat(n.controlBlock);return{finalScriptWitness:(0,iu.witnessStackToScriptWitness)(i)}}catch(s){throw new Error(`Can not finalize taproot input #${t}: ${s}`)}}ze.tapScriptFinalizer=F5;function M5(t,e){const r=e?Buffer.from([e]):Buffer.from([]);return Buffer.concat([t,r])}var Ea=ze.serializeTaprootSignature=M5;function Ec(t){return t&&!!(t.tapInternalKey||t.tapMerkleRoot||t.tapLeafScript&&t.tapLeafScript.length||t.tapBip32Derivation&&t.tapBip32Derivation.length||t.witnessUtxo&&(0,iu.isP2TR)(t.witnessUtxo.script))}ze.isTaprootInput=Ec;function Ac(t,e){return t&&!!(t.tapInternalKey||t.tapTree||t.tapBip32Derivation&&t.tapBip32Derivation.length||e&&(0,iu.isP2TR)(e))}ze.isTaprootOutput=Ac;function $5(t,e,r){X5(t,e,r),J5(t,e,r)}ze.checkTaprootInputFields=$5;function j5(t,e,r){Y5(t,e,r),H5(t,e)}ze.checkTaprootOutputFields=j5;function H5(t,e){if(!e.tapTree&&!e.tapInternalKey)return;const r=e.tapInternalKey||t.tapInternalKey,n=e.tapTree||t.tapTree;if(r){const{script:s}=t,i=L5(r,n);if(s&&!s.equals(i))throw new Error("Error adding output. Script or address missmatch.")}}function L5(t,e){const r=e&&Mb(e.leaves),{output:n}=(0,R5.p2tr)({internalPubkey:t,scriptTree:r});return n}function D5(t,e){const r=e.tapInternalKey,n=r&&(0,hs.tweakKey)(r,e.tapMerkleRoot);if(!n)throw new Error(`Cannot tweak tap internal key for input #${t}. Public key: ${r&&r.toString("hex")}`);return n.x}ze.tweakInternalPubKey=D5;function z5(t){if(!(0,hh.isTaptree)(t))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return Jf(t)}ze.tapTreeToList=z5;function Mb(t=[]){return t.length===1&&t[0].depth===0?{output:t[0].script,version:t[0].leafVersion}:K5(t)}ze.tapTreeFromList=Mb;function V5(t,e){return q5(t).some(n=>(0,N5.signatureBlocksAction)(n,G5,e))}ze.checkTaprootInputForSigs=V5;function G5(t){return{signature:t.slice(0,64),hashType:t.slice(64)[0]||C5.Transaction.SIGHASH_DEFAULT}}function q5(t){const e=[];if(t.tapKeySig&&e.push(t.tapKeySig),t.tapScriptSig&&e.push(...t.tapScriptSig.map(r=>r.signature)),!e.length){const r=W5(t.finalScriptWitness);r&&e.push(r)}return e}function W5(t){if(!t)return;const e=t.slice(2);if(e.length===64||e.length===65)return e}function Jf(t,e=[],r=0){if(r>hs.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return t?(0,hh.isTapleaf)(t)?(e.push({depth:r,leafVersion:t.version||hs.LEAF_VERSION_TAPSCRIPT,script:t.output}),e):(t[0]&&Jf(t[0],e,r+1),t[1]&&Jf(t[1],e,r+1),e):[]}function K5(t){let e;for(const r of t)if(e=Zf(r,e),!e)throw new Error("No room left to insert tapleaf in tree");return e}function Zf(t,e,r=0){if(r>hs.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");if(t.depth===r)return e?void 0:{output:t.script,version:t.leafVersion};if((0,hh.isTapleaf)(e))return;const n=Zf(t,e&&e[0],r+1);if(n)return[n,e&&e[1]];const s=Zf(t,e&&e[1],r+1);if(s)return[e&&e[0],s]}function X5(t,e,r){const n=Ec(t)&&Bi(e),s=Bi(t)&&Ec(e),i=t===e&&Ec(e)&&Bi(e);if(n||s||i)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function Y5(t,e,r){const n=Ac(t)&&Bi(e),s=Bi(t)&&Ac(e),i=t===e&&Ac(e)&&Bi(e);if(n||s||i)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function J5(t,e,r){if(e.tapMerkleRoot){const n=(e.tapLeafScript||[]).every(i=>el(i,e.tapMerkleRoot)),s=(t.tapLeafScript||[]).every(i=>el(i,e.tapMerkleRoot));if(!n||!s)throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}else if(t.tapMerkleRoot&&!(e.tapLeafScript||[]).every(s=>el(s,t.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}function el(t,e){if(!e)return!0;const r=(0,hs.tapleafHash)({output:t.script,version:t.leafVersion});return(0,hs.rootHashFromPath)(t.controlBlock,r).equals(e)}function Z5(t,e){const r=(0,hs.tapleafHash)({output:e.script,version:e.leafVersion});return(t.tapScriptSig||[]).filter(n=>n.leafHash.equals(r)).map(n=>Q5(e.script,n)).sort((n,s)=>s.positionInScript-n.positionInScript).map(n=>n.signature)}function Q5(t,e){return Object.assign({positionInScript:(0,iu.pubkeyPositionInScript)(e.pubkey,t)},e)}function eE(t,e,r){if(!t.tapScriptSig||!t.tapScriptSig.length)throw new Error(`Can not finalize taproot input #${e}. No tapleaf script signature provided.`);const n=(t.tapLeafScript||[]).sort((s,i)=>s.controlBlock.length-i.controlBlock.length).find(s=>tE(s,t.tapScriptSig,r));if(!n)throw new Error(`Can not finalize taproot input #${e}. Signature for tapleaf script not found.`);return n}function tE(t,e,r){const n=(0,hs.tapleafHash)({output:t.script,version:t.leafVersion});return(!r||r.equals(n))&&e.find(i=>i.leafHash.equals(n))!==void 0}function Bi(t){return t&&!!(t.redeemScript||t.witnessScript||t.bip32Derivation&&t.bip32Derivation.length)}const lr={secretMismatch:"invalid secret",secretHashLenMismatch:"secret hash should be 32 bytes",pubkeyLenMismatch:"pubkey should be 32 bytes",zeroOrNegativeExpiry:"expiry should be greater than 0",htlcAddressGenerationFailed:"failed to generate htlc address",notFunded:"address not funded",noCounterpartySigs:"counterparty signatures are required",counterPartySigNotFound:t=>"counterparty signature not found for utxo "+t,invalidCounterpartySigForUTXO:t=>"invalid counterparty signature for utxo "+t,htlcNotExpired:t=>`HTLC not expired, need more ${t} blocks`,controlBlockGenerationFailed:"failed to generate control block",invalidLeaf:"invalid leaf"},tc=192;ke.initEccLib(mr);let rE=class{constructor(e,r){this.signer=e,this.internalPubkey=D0(),this.network=G6(r)}address(e,r){const n=this.generateLeaves(e,r),{address:s}=ke.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:n});if(!s)throw new Error(lr.htlcAddressGenerationFailed);return s}async _buildRawTx(e,r,n,s,i){const a=new ke.Transaction;a.version=2;const o=this.address(e,n||"redeem"),c=await this.getProvider();let u=[];if(i&&i.length>0)for(const p of i){const d=await c.getTransaction(p);for(let b=0;b<d.vout.length;b++){const g=d.vout[b];g.scriptpubkey_address===o&&u.push({txid:d.txid,vout:b,value:g.value,status:{confirmed:!1}})}}else u=await c.getUTXOs(o);const l=u.reduce((p,d)=>p+d.value,0);if(l===0)throw new Error(`${o} ${lr.notFunded}`);for(let p=0;p<u.length;p++)a.addInput(Buffer.from(u[p].txid,"hex").reverse(),u[p].vout);if(s!=null&&s.vSize){const p=await c.getFeeRates(),d=Math.ceil(p.hourFee*s.vSize),b=l-d;return a.addOutput(ke.address.toOutputScript(r,this.network),b),{tx:a,usedUtxos:u}}const f=(s==null?void 0:s.fee)??await c.suggestFee(o,l,Pi.MEDIUM);return a.addOutput(ke.address.toOutputScript(r,this.network),l-f),{tx:a,usedUtxos:u,fee:f,balance:l}}getOutputScript(e,r){return ke.address.toOutputScript(this.address(e,r||"redeem"),this.network)}async initiate(e,r){const n=await this.getProvider(),s=await this.signer.getAddress();let i,a;D.isOrder(e)?(i=e.source_swap.swap_id,a=Number(e.source_swap.amount)):(i=e.to,a=Number(e.amount)),r===void 0&&(r=await n.suggestFee(s,a,Pi.MEDIUM));const o=await this.signer.send(i,a,r);return m.Ok(o)}async generateRedeemSACP(e,r,n){const{tx:s,usedUtxos:i}=await this._buildRawTx(e,e.destination_swap.delegate,"redeem",{fee:n}),a=this.getOutputScript(e,"redeem"),o=ke.Transaction.SIGHASH_SINGLE|ke.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(1,e),u=i.map(f=>f.value),l=oa(a,i.length);for(let f=0;f<s.ins.length;f++){const p=s.hashForWitnessV1(f,l,u,o,c),d=await this.signer.signSchnorr(p);s.setWitness(f,[Ea(d,o),Buffer.from(r,"hex"),this.redeemLeaf(m.trim0x(e.destination_swap.secret_hash),De(e.destination_swap.delegate)),await this.generateControlBlockFor(1,e)])}return s.toHex()}async generateInstantRefundSACP(e){const r=this.getOutputScript(e,"instantRefund"),{tx:n,usedUtxos:s,fee:i}=await this._buildRawTx(e,e.destination_swap.delegate,"instantRefund",{fee:0});n.outs=[];const a=Math.max(...s.map(f=>f.value));s.forEach(({value:f})=>{n.addOutput(r,f-(f===a?i??0:0))});const o=ke.Transaction.SIGHASH_SINGLE|ke.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(2,e),u=s.map(f=>f.value),l=oa(r,s.length);for(let f=0;f<n.ins.length;f++){const p=n.hashForWitnessV1(f,l,u,o,c),d=await this.signer.signSchnorr(p);n.setWitness(f,[Ea(d,o),Ea(d,o),this.instantRefundLeaf(De(e.source_swap.initiator),De(e.destination_swap.delegate)),await this.generateControlBlockFor(2,e)])}return n.toHex()}async generateInstantRefundSACPWithHash(e){const r=[],n=ke.Transaction.SIGHASH_SINGLE|ke.Transaction.SIGHASH_ANYONECANPAY;for(let s=0;s<e.length;s++){const i=Buffer.from(e[s],"hex"),a=await this.signer.signSchnorr(i);r.push(Ea(a,n).toString("hex"))}return m.Ok(r)}async instantRefund(e,r,n){$0(r.length>0,lr.noCounterpartySigs);const{tx:s,usedUtxos:i}=await this._buildRawTx(e,await this.signer.getAddress(),"instantRefund",{fee:n});for(const p of i)if(!r.find(d=>d.utxo===p.txid))throw new Error(lr.counterPartySigNotFound(p.txid));const a=this.getOutputScript(e,"instantRefund"),o=ke.Transaction.SIGHASH_DEFAULT,c=this.leafHash(2,e),u=i.map(p=>p.value),l=oa(a,i.length);for(let p=0;p<s.ins.length;p++){const d=s.hashForWitnessV1(p,l,u,o,c);if(!mr.verifySchnorr(d,Buffer.from(De(e.destination_swap.delegate),"hex"),Buffer.from(r[p].sig,"hex")))throw new Error(lr.invalidCounterpartySigForUTXO(r[p].utxo));const b=await this.signer.signSchnorr(d),g=Buffer.from(s.ins[p].hash).reverse().toString("hex"),A=r.find(S=>S.utxo===g);if(!A)throw new Error(lr.counterPartySigNotFound(g));s.setWitness(p,[Buffer.from(A.sig,"hex"),b,this.instantRefundLeaf(De(e.source_swap.initiator),De(e.destination_swap.delegate)),await this.generateControlBlockFor(2,e)])}return await(await this.getProvider()).broadcast(s.toHex())}async redeem(e,r,n){const s=await this.getRedeemHex(e,r,n);if(!s.ok)return m.Err(s.error);const a=await(await this.getProvider()).broadcast(s.val);return m.Ok(a)}async getRedeemHex(e,r,n){$0(ke.crypto.sha256(Buffer.from(r,"hex")).toString("hex")===m.trim0x(e.destination_swap.secret_hash),lr.secretMismatch);const a=(D.isBitcoin(e.source_swap.chain)?e.source_swap.redeemer:e.destination_swap.redeemer)??await this.signer.getAddress(),{tx:o,usedUtxos:c}=await this._buildRawTx(e,a,"redeem",{fee:0},n),u=this.leafHash(1,e),l=c.map(b=>b.value),f=oa(this.getOutputScript(e,"redeem"),c.length),p=ke.Transaction.SIGHASH_DEFAULT;for(let b=0;b<o.ins.length;b++){const g=o.hashForWitnessV1(b,f,l,p,u),A=await this.signer.signSchnorr(g);o.setWitness(b,[A,Buffer.from(r,"hex"),this.redeemLeaf(m.trim0x(e.destination_swap.secret_hash),De(e.destination_swap.delegate)),await this.generateControlBlockFor(1,e)])}const{tx:d}=await this._buildRawTx(e,a,"redeem",{vSize:o.virtualSize()},n);for(let b=0;b<d.ins.length;b++){const g=d.hashForWitnessV1(b,f,l,p,u),A=await this.signer.signSchnorr(g);d.setWitness(b,[A,Buffer.from(r,"hex"),this.redeemLeaf(m.trim0x(e.destination_swap.secret_hash),De(e.destination_swap.delegate)),await this.generateControlBlockFor(1,e)])}return m.Ok(d.toHex())}async refund(e,r){const{tx:n,usedUtxos:s}=await this._buildRawTx(e,e.source_swap.delegate??await this.signer.getAddress(),"refund",{fee:r}),[i,a]=await this.canRefund(e,s);if(!i)throw new Error(lr.htlcNotExpired(a));const o=this.leafHash(0,e),c=s.map(d=>d.value),u=oa(this.getOutputScript(e,"refund"),s.length),l=ke.Transaction.SIGHASH_DEFAULT;for(let d=0;d<n.ins.length;d++){n.ins[d].sequence=e.source_swap.timelock;const b=n.hashForWitnessV1(d,u,c,l,o),g=await this.signer.signSchnorr(b);n.setWitness(d,[g,this.refundLeaf(e.source_swap.timelock,De(e.source_swap.initiator)),await this.generateControlBlockFor(0,e)])}const p=await(await this.getProvider()).broadcast(n.toHex());return m.Ok(p)}async canRefund(e,r){const s=await(await this.getProvider()).getLatestTip();for(const i of r){let a=0;if(i.status.confirmed&&i.status.block_height+e.source_swap.timelock>s?a=i.status.block_height+e.source_swap.timelock-s+1:i.status.confirmed||(a=e.source_swap.timelock+1),a>0)return[!1,a]}return[!0,0]}async generateControlBlockFor(e,r){let n,s;switch(e){case 1:n=this.redeemLeaf(m.trim0x(r.destination_swap.secret_hash),De(r.destination_swap.delegate)),s=this.generateLeaves(r,"redeem");break;case 0:n=this.refundLeaf(r.source_swap.timelock,De(r.source_swap.initiator)),s=this.generateLeaves(r,"refund");break;case 2:n=this.instantRefundLeaf(De(r.source_swap.initiator),De(r.destination_swap.delegate)),s=this.generateLeaves(r,"instantRefund");break;default:throw new Error(lr.controlBlockGenerationFailed)}const i=await this.signer.getNetwork(),a=ke.payments.p2tr({internalPubkey:D0(),network:i,scriptTree:s,redeem:{output:n,redeemVersion:tc}});if(!a.witness)throw new Error(lr.controlBlockGenerationFailed);return a.witness[a.witness.length-1]}leafHash(e,r){let n;switch(e){case 1:n=this.redeemLeaf(m.trim0x(r.destination_swap.secret_hash),De(r.destination_swap.delegate));break;case 0:n=this.refundLeaf(r.source_swap.timelock,De(r.source_swap.initiator));break;case 2:n=this.instantRefundLeaf(De(r.source_swap.initiator),De(r.destination_swap.redeemer));break;default:throw new Error(lr.invalidLeaf)}return ke.crypto.taggedHash("TapLeaf",F6(n))}refundLeaf(e,r){return ke.script.fromASM(`
10
10
  ${ke.script.number.encode(e).toString("hex")}
11
11
  OP_CHECKSEQUENCEVERIFY
12
12
  OP_DROP
@@ -25,50 +25,50 @@
25
25
  OP_CHECKSIGADD
26
26
  OP_2
27
27
  OP_NUMEQUAL
28
- `.trim().replace(/\s+/g," "))}generateLeaves(e,r){let n,s,i;switch(r){case"redeem":n=e.destination_swap,s=n.delegate,i=n.delegate;break;case"refund":n=e.source_swap,s=n.delegate,i=n.delegate;break;case"instantRefund":n=e.source_swap,s=n.redeemer,i=n.redeemer;break;default:throw new Error("Invalid leaf generation type")}return[{version:tc,output:this.redeemLeaf(n.secret_hash,De(s))},[{version:tc,output:this.refundLeaf(n.timelock,De(n.initiator))},{version:tc,output:this.instantRefundLeaf(De(n.initiator),De(i))}]]}generateMerkleProofFor(e,r){const n=this.leafHash(1,r),s=this.leafHash(2,r),i=this.leafHash(0,r);switch(e){case 1:{const a=F6(i,s);return[ke.crypto.taggedHash("TapBranch",Buffer.concat(a))]}case 0:return[s,n];case 2:return[i,n];default:throw new Error(lr.invalidLeaf)}}getProvider(){return this.signer.getProvider()}get getPublicKey(){return this.signer.getPublicKey()}get htlcActorAddress(){return this.signer.getPublicKey()}};class Fb{constructor(e,r){this.quoteUrl=new m.Url(e),this.auth=r}async getQuoteFromAssets({fromAsset:e,toAsset:r,amount:n,isExactOut:s=!1,options:i}){const a=D.ChainAsset.from(e),o=D.ChainAsset.from(r);return this.getQuote(a,o,n,s,i)}async getQuote(e,r,n,s=!1,i){try{const a=await this.auth.getAuthHeaders();if(a.error)return m.Err(a.error);const o={from:D.ChainAsset.from(e).toString(),to:D.ChainAsset.from(r).toString(),...s?{to_amount:n.toString()}:{from_amount:n.toString()},...(i==null?void 0:i.affiliateFee)!==void 0&&{affiliate_fee:i.affiliateFee.toString()},...(i==null?void 0:i.indicative)!==void 0&&{indicative:i.indicative.toString()}},c=this.quoteUrl.endpoint("/v2/quote").addSearchParams(o),u=await m.Fetcher.get(c,{retryCount:0,...i==null?void 0:i.request,headers:{...a.val,"Content-Type":"application/json"}});return u.error?m.Err(u.error):u.result?m.Ok(u.result):m.Err("GetQuote: Unexpected error, result is undefined")}catch(a){return m.Err("GetQuote:",String(a))}}}const tE="1.2.3";let Kt=class Jf extends Error{constructor(e,r={}){var a;const n=r.cause instanceof Jf?r.cause.details:(a=r.cause)!=null&&a.message?r.cause.message:r.details,s=r.cause instanceof Jf&&r.cause.docsPath||r.docsPath,i=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: https://abitype.dev${s}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${tE}`].join(`
29
- `);super(i),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=s,this.metaMessages=r.metaMessages,this.shortMessage=e}};function Mn(t,e){const r=t.exec(e);return r==null?void 0:r.groups}const Mb=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,$b=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,jb=/^\(.+?\).*?$/,up=/^tuple(?<array>(\[(\d*)\])*)$/;function Zf(t){let e=t.type;if(up.test(t.type)&&"components"in t){e="(";const r=t.components.length;for(let s=0;s<r;s++){const i=t.components[s];e+=Zf(i),s<r-1&&(e+=", ")}const n=Mn(up,t.type);return e+=`)${(n==null?void 0:n.array)||""}`,Zf({...t,type:e})}return"indexed"in t&&t.indexed&&(e=`${e} indexed`),t.name?`${e} ${t.name}`:e}function Ei(t){let e="";const r=t.length;for(let n=0;n<r;n++){const s=t[n];e+=Zf(s),n!==r-1&&(e+=", ")}return e}function Pc(t){var e;return t.type==="function"?`function ${t.name}(${Ei(t.inputs)})${t.stateMutability&&t.stateMutability!=="nonpayable"?` ${t.stateMutability}`:""}${(e=t.outputs)!=null&&e.length?` returns (${Ei(t.outputs)})`:""}`:t.type==="event"?`event ${t.name}(${Ei(t.inputs)})`:t.type==="error"?`error ${t.name}(${Ei(t.inputs)})`:t.type==="constructor"?`constructor(${Ei(t.inputs)})${t.stateMutability==="payable"?" payable":""}`:t.type==="fallback"?`fallback() external${t.stateMutability==="payable"?" payable":""}`:"receive() external payable"}const Hb=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function rE(t){return Hb.test(t)}function nE(t){return Mn(Hb,t)}const Lb=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function sE(t){return Lb.test(t)}function iE(t){return Mn(Lb,t)}const Db=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function aE(t){return Db.test(t)}function oE(t){return Mn(Db,t)}const zb=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function su(t){return zb.test(t)}function cE(t){return Mn(zb,t)}const Vb=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function uE(t){return Vb.test(t)}function lE(t){return Mn(Vb,t)}const Gb=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function fE(t){return Gb.test(t)}function dE(t){return Mn(Gb,t)}const hE=/^receive\(\) external payable$/;function pE(t){return hE.test(t)}const lp=new Set(["memory","indexed","storage","calldata"]),yE=new Set(["indexed"]),Qf=new Set(["calldata","memory","storage"]);class mE extends Kt{constructor({signature:e}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(e,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}}class bE extends Kt{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}}class gE extends Kt{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}}class wE extends Kt{constructor({params:e}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(e,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"})}}class vE extends Kt{constructor({param:e}){super("Invalid ABI parameter.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}}class EE extends Kt{constructor({param:e,name:r}){super("Invalid ABI parameter.",{details:e,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}}class AE extends Kt{constructor({param:e,type:r,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}}class SE extends Kt{constructor({param:e,type:r,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}}class xE extends Kt{constructor({abiParameter:e}){super("Invalid ABI parameter.",{details:JSON.stringify(e,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}}class Yi extends Kt{constructor({signature:e,type:r}){super(`Invalid ${r} signature.`,{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}}class kE extends Kt{constructor({signature:e}){super("Unknown signature.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}}class TE extends Kt{constructor({signature:e}){super("Invalid struct signature.",{details:e,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}}class _E extends Kt{constructor({type:e}){super("Circular reference detected.",{metaMessages:[`Struct "${e}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}}class IE extends Kt{constructor({current:e,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${e.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}}function PE(t,e,r){let n="";if(r)for(const s of Object.entries(r)){if(!s)continue;let i="";for(const a of s[1])i+=`[${a.type}${a.name?`:${a.name}`:""}]`;n+=`(${s[0]}{${i}})`}return e?`${e}:${t}${n}`:`${t}${n}`}const Qu=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]]);function ed(t,e={}){if(aE(t))return OE(t,e);if(sE(t))return BE(t,e);if(rE(t))return CE(t,e);if(uE(t))return RE(t,e);if(fE(t))return NE(t);if(pE(t))return{type:"receive",stateMutability:"payable"};throw new kE({signature:t})}function OE(t,e={}){const r=oE(t);if(!r)throw new Yi({signature:t,type:"function"});const n=Jt(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(Cn(n[o],{modifiers:Qf,structs:e,type:"function"}));const a=[];if(r.returns){const o=Jt(r.returns),c=o.length;for(let u=0;u<c;u++)a.push(Cn(o[u],{modifiers:Qf,structs:e,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:s,outputs:a}}function BE(t,e={}){const r=iE(t);if(!r)throw new Yi({signature:t,type:"event"});const n=Jt(r.parameters),s=[],i=n.length;for(let a=0;a<i;a++)s.push(Cn(n[a],{modifiers:yE,structs:e,type:"event"}));return{name:r.name,type:"event",inputs:s}}function CE(t,e={}){const r=nE(t);if(!r)throw new Yi({signature:t,type:"error"});const n=Jt(r.parameters),s=[],i=n.length;for(let a=0;a<i;a++)s.push(Cn(n[a],{structs:e,type:"error"}));return{name:r.name,type:"error",inputs:s}}function RE(t,e={}){const r=lE(t);if(!r)throw new Yi({signature:t,type:"constructor"});const n=Jt(r.parameters),s=[],i=n.length;for(let a=0;a<i;a++)s.push(Cn(n[a],{structs:e,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:s}}function NE(t){const e=dE(t);if(!e)throw new Yi({signature:t,type:"fallback"});return{type:"fallback",stateMutability:e.stateMutability??"nonpayable"}}const UE=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,FE=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,ME=/^u?int$/;function Cn(t,e){var f,p;const r=PE(t,e==null?void 0:e.type,e==null?void 0:e.structs);if(Qu.has(r))return Qu.get(r);const n=jb.test(t),s=Mn(n?FE:UE,t);if(!s)throw new vE({param:t});if(s.name&&jE(s.name))throw new EE({param:t,name:s.name});const i=s.name?{name:s.name}:{},a=s.modifier==="indexed"?{indexed:!0}:{},o=(e==null?void 0:e.structs)??{};let c,u={};if(n){c="tuple";const d=Jt(s.type),b=[],g=d.length;for(let A=0;A<g;A++)b.push(Cn(d[A],{structs:o}));u={components:b}}else if(s.type in o)c="tuple",u={components:o[s.type]};else if(ME.test(s.type))c=`${s.type}256`;else if(s.type==="address payable")c="address";else if(c=s.type,(e==null?void 0:e.type)!=="struct"&&!qb(c))throw new gE({type:c});if(s.modifier){if(!((p=(f=e==null?void 0:e.modifiers)==null?void 0:f.has)!=null&&p.call(f,s.modifier)))throw new AE({param:t,type:e==null?void 0:e.type,modifier:s.modifier});if(Qf.has(s.modifier)&&!HE(c,!!s.array))throw new SE({param:t,type:e==null?void 0:e.type,modifier:s.modifier})}const l={type:`${c}${s.array??""}`,...i,...a,...u};return Qu.set(r,l),l}function Jt(t,e=[],r="",n=0){const s=t.trim().length;for(let i=0;i<s;i++){const a=t[i],o=t.slice(i+1);switch(a){case",":return n===0?Jt(o,[...e,r.trim()]):Jt(o,e,`${r}${a}`,n);case"(":return Jt(o,e,`${r}${a}`,n+1);case")":return Jt(o,e,`${r}${a}`,n-1);default:return Jt(o,e,`${r}${a}`,n)}}if(r==="")return e;if(n!==0)throw new IE({current:r,depth:n});return e.push(r.trim()),e}function qb(t){return t==="address"||t==="bool"||t==="function"||t==="string"||Mb.test(t)||$b.test(t)}const $E=/^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/;function jE(t){return t==="address"||t==="bool"||t==="function"||t==="string"||t==="tuple"||Mb.test(t)||$b.test(t)||$E.test(t)}function HE(t,e){return e||t==="bytes"||t==="string"||t==="tuple"}function dh(t){const e={},r=t.length;for(let a=0;a<r;a++){const o=t[a];if(!su(o))continue;const c=cE(o);if(!c)throw new Yi({signature:o,type:"struct"});const u=c.properties.split(";"),l=[],f=u.length;for(let p=0;p<f;p++){const b=u[p].trim();if(!b)continue;const g=Cn(b,{type:"struct"});l.push(g)}if(!l.length)throw new TE({signature:o});e[c.name]=l}const n={},s=Object.entries(e),i=s.length;for(let a=0;a<i;a++){const[o,c]=s[a];n[o]=Wb(c,e)}return n}const LE=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function Wb(t=[],e={},r=new Set){const n=[],s=t.length;for(let i=0;i<s;i++){const a=t[i];if(jb.test(a.type))n.push(a);else{const c=Mn(LE,a.type);if(!(c!=null&&c.type))throw new xE({abiParameter:a});const{array:u,type:l}=c;if(l in e){if(r.has(l))throw new _E({type:l});n.push({...a,type:`tuple${u??""}`,components:Wb(e[l],e,new Set([...r,l]))})}else if(qb(l))n.push(a);else throw new bE({type:l})}}return n}function Kb(t){const e=dh(t),r=[],n=t.length;for(let s=0;s<n;s++){const i=t[s];su(i)||r.push(ed(i,e))}return r}function fp(t){let e;if(typeof t=="string")e=ed(t);else{const r=dh(t),n=t.length;for(let s=0;s<n;s++){const i=t[s];if(!su(i)){e=ed(i,r);break}}}if(!e)throw new mE({signature:t});return e}function dp(t){const e=[];if(typeof t=="string"){const r=Jt(t),n=r.length;for(let s=0;s<n;s++)e.push(Cn(r[s],{modifiers:lp}))}else{const r=dh(t),n=t.length;for(let s=0;s<n;s++){const i=t[s];if(su(i))continue;const a=Jt(i),o=a.length;for(let c=0;c<o;c++)e.push(Cn(a[c],{modifiers:lp,structs:r}))}}if(e.length===0)throw new wE({params:t});return e}function re(t,e,r){const n=t[e.name];if(typeof n=="function")return n;const s=t[r];return typeof s=="function"?s:i=>e(t,i)}function Rr(t,{includeName:e=!1}={}){if(t.type!=="function"&&t.type!=="event"&&t.type!=="error")throw new tA(t.type);return`${t.name}(${iu(t.inputs,{includeName:e})})`}function iu(t,{includeName:e=!1}={}){return t?t.map(r=>DE(r,{includeName:e})).join(e?", ":","):""}function DE(t,{includeName:e}){return t.type.startsWith("tuple")?`(${iu(t.components,{includeName:e})})${t.type.slice(5)}`:t.type+(e&&t.name?` ${t.name}`:"")}function Nr(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function Ge(t){return Nr(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const Xb="2.44.4";let fa={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:r})=>e?`${t??"https://viem.sh"}${e}${r?`#${r}`:""}`:void 0,version:`viem@${Xb}`},G=class td extends Error{constructor(e,r={}){var o;const n=(()=>{var c;return r.cause instanceof td?r.cause.details:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),s=r.cause instanceof td&&r.cause.docsPath||r.docsPath,i=(o=fa.getDocsUrl)==null?void 0:o.call(fa,{...r,docsPath:s}),a=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...n?[`Details: ${n}`]:[],...fa.version?[`Version: ${fa.version}`]:[]].join(`
30
- `);super(a,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=s,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=e,this.version=Xb}walk(e){return Yb(this,e)}};function Yb(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?Yb(t.cause,e):e?null:t}class zE extends G{constructor({docsPath:e}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(`
31
- `),{docsPath:e,name:"AbiConstructorNotFoundError"})}}class hp extends G{constructor({docsPath:e}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join(`
32
- `),{docsPath:e,name:"AbiConstructorParamsNotFoundError"})}}class Jb extends G{constructor({data:e,params:r,size:n}){super([`Data size of ${n} bytes is too small for given parameters.`].join(`
33
- `),{metaMessages:[`Params: (${iu(r,{includeName:!0})})`,`Data: ${e} (${n} bytes)`],name:"AbiDecodingDataSizeTooSmallError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=e,this.params=r,this.size=n}}class xo extends G{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError"})}}class VE extends G{constructor({expectedLength:e,givenLength:r,type:n}){super([`ABI encoding array length mismatch for type ${n}.`,`Expected length: ${e}`,`Given length: ${r}`].join(`
34
- `),{name:"AbiEncodingArrayLengthMismatchError"})}}class GE extends G{constructor({expectedSize:e,value:r}){super(`Size of bytes "${r}" (bytes${Ge(r)}) does not match expected size (bytes${e}).`,{name:"AbiEncodingBytesSizeMismatchError"})}}class qE extends G{constructor({expectedLength:e,givenLength:r}){super(["ABI encoding params/values length mismatch.",`Expected length (params): ${e}`,`Given length (values): ${r}`].join(`
35
- `),{name:"AbiEncodingLengthMismatchError"})}}class WE extends G{constructor(e,{docsPath:r}){super([`Arguments (\`args\`) were provided to "${e}", but "${e}" on the ABI does not contain any parameters (\`inputs\`).`,"Cannot encode error result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the inputs exist on it."].join(`
36
- `),{docsPath:r,name:"AbiErrorInputsNotFoundError"})}}class pp extends G{constructor(e,{docsPath:r}={}){super([`Error ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it."].join(`
37
- `),{docsPath:r,name:"AbiErrorNotFoundError"})}}class Zb extends G{constructor(e,{docsPath:r}){super([`Encoded error signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://openchain.xyz/signatures?query=${e}.`].join(`
38
- `),{docsPath:r,name:"AbiErrorSignatureNotFoundError"}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.signature=e}}class KE extends G{constructor({docsPath:e}){super("Cannot extract event signature from empty topics.",{docsPath:e,name:"AbiEventSignatureEmptyTopicsError"})}}class XE extends G{constructor(e,{docsPath:r}){super([`Encoded event signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it.",`You can look up the signature here: https://openchain.xyz/signatures?query=${e}.`].join(`
39
- `),{docsPath:r,name:"AbiEventSignatureNotFoundError"})}}class yp extends G{constructor(e,{docsPath:r}={}){super([`Event ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it."].join(`
40
- `),{docsPath:r,name:"AbiEventNotFoundError"})}}class Di extends G{constructor(e,{docsPath:r}={}){super([`Function ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it."].join(`
41
- `),{docsPath:r,name:"AbiFunctionNotFoundError"})}}class Qb extends G{constructor(e,{docsPath:r}){super([`Function "${e}" does not contain any \`outputs\` on ABI.`,"Cannot decode function result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the function exists on it."].join(`
42
- `),{docsPath:r,name:"AbiFunctionOutputsNotFoundError"})}}class YE extends G{constructor(e,{docsPath:r}){super([`Encoded function signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it.",`You can look up the signature here: https://openchain.xyz/signatures?query=${e}.`].join(`
43
- `),{docsPath:r,name:"AbiFunctionSignatureNotFoundError"})}}class JE extends G{constructor(e,r){super("Found ambiguous types in overloaded ABI items.",{metaMessages:[`\`${e.type}\` in \`${Rr(e.abiItem)}\`, and`,`\`${r.type}\` in \`${Rr(r.abiItem)}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."],name:"AbiItemAmbiguityError"})}}let ZE=class extends G{constructor({expectedSize:e,givenSize:r}){super(`Expected bytes${e}, got bytes${r}.`,{name:"BytesSizeMismatchError"})}};class Oc extends G{constructor({abiItem:e,data:r,params:n,size:s}){super([`Data size of ${s} bytes is too small for non-indexed event parameters.`].join(`
44
- `),{metaMessages:[`Params: (${iu(n,{includeName:!0})})`,`Data: ${r} (${s} bytes)`],name:"DecodeLogDataMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=e,this.data=r,this.params=n,this.size=s}}class hh extends G{constructor({abiItem:e,param:r}){super([`Expected a topic for indexed event parameter${r.name?` "${r.name}"`:""} on event "${Rr(e,{includeName:!0})}".`].join(`
45
- `),{name:"DecodeLogTopicsMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=e}}class QE extends G{constructor(e,{docsPath:r}){super([`Type "${e}" is not a valid encoding type.`,"Please provide a valid ABI type."].join(`
46
- `),{docsPath:r,name:"InvalidAbiEncodingType"})}}class eA extends G{constructor(e,{docsPath:r}){super([`Type "${e}" is not a valid decoding type.`,"Please provide a valid ABI type."].join(`
47
- `),{docsPath:r,name:"InvalidAbiDecodingType"})}}let eg=class extends G{constructor(e){super([`Value "${e}" is not a valid array.`].join(`
48
- `),{name:"InvalidArrayError"})}};class tA extends G{constructor(e){super([`"${e}" is not a valid definition type.`,'Valid types: "function", "event", "error"'].join(`
49
- `),{name:"InvalidDefinitionTypeError"})}}class rA extends G{constructor(e){super(`Filter type "${e}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}let tg=class extends G{constructor({offset:e,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${e}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}},rg=class extends G{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}};class mp extends G{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} is expected to be ${r} ${n} long, but is ${e} ${n} long.`,{name:"InvalidBytesLengthError"})}}function Ji(t,{dir:e,size:r=32}={}){return typeof t=="string"?fs(t,{dir:e,size:r}):nA(t,{dir:e,size:r})}function fs(t,{dir:e,size:r=32}={}){if(r===null)return t;const n=t.replace("0x","");if(n.length>r*2)throw new rg({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[e==="right"?"padEnd":"padStart"](r*2,"0")}`}function nA(t,{dir:e,size:r=32}={}){if(r===null)return t;if(t.length>r)throw new rg({size:t.length,targetSize:r,type:"bytes"});const n=new Uint8Array(r);for(let s=0;s<r;s++){const i=e==="right";n[i?s:r-s-1]=t[i?s:t.length-s-1]}return n}let ph=class extends G{constructor({max:e,min:r,signed:n,size:s,value:i}){super(`Number "${i}" is not in safe ${s?`${s*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${r} to ${e})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}},sA=class extends G{constructor(e){super(`Bytes value "${e}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}};class iA extends G{constructor(e){super(`Hex value "${e}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`,{name:"InvalidHexBooleanError"})}}let aA=class extends G{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};function br(t,{dir:e="left"}={}){let r=typeof t=="string"?t.replace("0x",""):t,n=0;for(let s=0;s<r.length-1&&r[e==="left"?s:r.length-s-1].toString()==="0";s++)n++;return r=e==="left"?r.slice(n):r.slice(0,r.length-n),typeof t=="string"?(r.length===1&&e==="right"&&(r=`${r}0`),`0x${r.length%2===1?`0${r}`:r}`):r}function $r(t,{size:e}){if(Ge(t)>e)throw new aA({givenSize:Ge(t),maxSize:e})}function lt(t,e={}){const{signed:r}=e;e.size&&$r(t,{size:e.size});const n=BigInt(t);if(!r)return n;const s=(t.length-2)/2,i=(1n<<BigInt(s)*8n-1n)-1n;return n<=i?n:n-BigInt(`0x${"f".padStart(s*2,"f")}`)-1n}function oA(t,e={}){let r=t;if(e.size&&($r(r,{size:e.size}),r=br(r)),br(r)==="0x00")return!1;if(br(r)==="0x01")return!0;throw new iA(r)}function gr(t,e={}){const r=lt(t,e),n=Number(r);if(!Number.isSafeInteger(n))throw new ph({max:`${Number.MAX_SAFE_INTEGER}`,min:`${Number.MIN_SAFE_INTEGER}`,signed:e.signed,size:e.size,value:`${r}n`});return n}const cA=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ft(t,e={}){return typeof t=="number"||typeof t=="bigint"?Y(t,e):typeof t=="string"?zi(t,e):typeof t=="boolean"?ng(t,e):tt(t,e)}function ng(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?($r(r,{size:e.size}),Ji(r,{size:e.size})):r}function tt(t,e={}){let r="";for(let s=0;s<t.length;s++)r+=cA[t[s]];const n=`0x${r}`;return typeof e.size=="number"?($r(n,{size:e.size}),Ji(n,{dir:"right",size:e.size})):n}function Y(t,e={}){const{signed:r,size:n}=e,s=BigInt(t);let i;n?r?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const a=typeof i=="bigint"&&r?-i-1n:0;if(i&&s>i||s<a){const c=typeof t=="bigint"?"n":"";throw new ph({max:i?`${i}${c}`:void 0,min:`${a}${c}`,signed:r,size:n,value:`${t}${c}`})}const o=`0x${(r&&s<0?(1n<<BigInt(n*8))+BigInt(s):s).toString(16)}`;return n?Ji(o,{size:n}):o}const uA=new TextEncoder;function zi(t,e={}){const r=uA.encode(t);return tt(r,e)}const lA=new TextEncoder;function Zi(t,e={}){return typeof t=="number"||typeof t=="bigint"?dA(t,e):typeof t=="boolean"?fA(t,e):Nr(t)?an(t,e):Ls(t,e)}function fA(t,e={}){const r=new Uint8Array(1);return r[0]=Number(t),typeof e.size=="number"?($r(r,{size:e.size}),Ji(r,{size:e.size})):r}const hn={zero:48,nine:57,A:65,F:70,a:97,f:102};function bp(t){if(t>=hn.zero&&t<=hn.nine)return t-hn.zero;if(t>=hn.A&&t<=hn.F)return t-(hn.A-10);if(t>=hn.a&&t<=hn.f)return t-(hn.a-10)}function an(t,e={}){let r=t;e.size&&($r(r,{size:e.size}),r=Ji(r,{dir:"right",size:e.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);const s=n.length/2,i=new Uint8Array(s);for(let a=0,o=0;a<s;a++){const c=bp(n.charCodeAt(o++)),u=bp(n.charCodeAt(o++));if(c===void 0||u===void 0)throw new G(`Invalid byte sequence ("${n[o-2]}${n[o-1]}" in "${n}").`);i[a]=c*16+u}return i}function dA(t,e){const r=Y(t,e);return an(r)}function Ls(t,e={}){const r=lA.encode(t);return typeof e.size=="number"?($r(r,{size:e.size}),Ji(r,{dir:"right",size:e.size})):r}const rc=BigInt(2**32-1),gp=BigInt(32);function sg(t,e=!1){return e?{h:Number(t&rc),l:Number(t>>gp&rc)}:{h:Number(t>>gp&rc)|0,l:Number(t&rc)|0}}function hA(t,e=!1){const r=t.length;let n=new Uint32Array(r),s=new Uint32Array(r);for(let i=0;i<r;i++){const{h:a,l:o}=sg(t[i],e);[n[i],s[i]]=[a,o]}return[n,s]}const ig=(t,e,r)=>t>>>r|e<<32-r,ag=(t,e,r)=>t<<32-r|e>>>r,pA=(t,e,r)=>t<<64-r|e>>>r-32,yA=(t,e,r)=>t>>>r-32|e<<64-r,mA=(t,e)=>e,bA=(t,e)=>t,gA=(t,e,r)=>t<<r|e>>>32-r,wA=(t,e,r)=>e<<r|t>>>32-r,vA=(t,e,r)=>e<<r-32|t>>>64-r,EA=(t,e,r)=>t<<r-32|e>>>64-r;function og(t,e,r,n){const s=(e>>>0)+(n>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}const cg=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),ug=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,pi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function AA(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function hs(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function ps(t,...e){if(!AA(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function SA(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");hs(t.outputLen),hs(t.blockLen)}function ys(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function yh(t,e){ps(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function ja(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Rn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function el(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function qr(t,e){return t<<32-e|t>>>e}const lg=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function fg(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const vn=lg?t=>t:t=>fg(t);function xA(t){for(let e=0;e<t.length;e++)t[e]=fg(t[e]);return t}const ts=lg?t=>t:xA;function kA(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function In(t){return typeof t=="string"&&(t=kA(t)),ps(t),t}function TA(...t){let e=0;for(let n=0;n<t.length;n++){const s=t[n];ps(s),e+=s.length}const r=new Uint8Array(e);for(let n=0,s=0;n<t.length;n++){const i=t[n];r.set(i,s),s+=i.length}return r}class au{}function dg(t){const e=n=>t().update(In(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function _A(t){const e=(n,s)=>t(s).update(In(n)).digest(),r=t({});return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}function IA(t=32){if(pi&&typeof pi.getRandomValues=="function")return pi.getRandomValues(new Uint8Array(t));if(pi&&typeof pi.randomBytes=="function")return Uint8Array.from(pi.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const PA=BigInt(0),da=BigInt(1),OA=BigInt(2),BA=BigInt(7),CA=BigInt(256),RA=BigInt(113),hg=[],pg=[],yg=[];for(let t=0,e=da,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],hg.push(2*(5*n+r)),pg.push((t+1)*(t+2)/2%64);let s=PA;for(let i=0;i<7;i++)e=(e<<da^(e>>BA)*RA)%CA,e&OA&&(s^=da<<(da<<BigInt(i))-da);yg.push(s)}const mg=hA(yg,!0),NA=mg[0],UA=mg[1],wp=(t,e,r)=>r>32?vA(t,e,r):gA(t,e,r),vp=(t,e,r)=>r>32?EA(t,e,r):wA(t,e,r);function FA(t,e=24){const r=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let a=0;a<10;a++)r[a]=t[a]^t[a+10]^t[a+20]^t[a+30]^t[a+40];for(let a=0;a<10;a+=2){const o=(a+8)%10,c=(a+2)%10,u=r[c],l=r[c+1],f=wp(u,l,1)^r[o],p=vp(u,l,1)^r[o+1];for(let d=0;d<50;d+=10)t[a+d]^=f,t[a+d+1]^=p}let s=t[2],i=t[3];for(let a=0;a<24;a++){const o=pg[a],c=wp(s,i,o),u=vp(s,i,o),l=hg[a];s=t[l],i=t[l+1],t[l]=c,t[l+1]=u}for(let a=0;a<50;a+=10){for(let o=0;o<10;o++)r[o]=t[a+o];for(let o=0;o<10;o++)t[a+o]^=~r[(o+2)%10]&r[(o+4)%10]}t[0]^=NA[n],t[1]^=UA[n]}Rn(r)}class mh extends au{constructor(e,r,n,s=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=s,this.rounds=i,hs(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=ja(this.state)}clone(){return this._cloneInto()}keccak(){ts(this.state32),FA(this.state32,this.rounds),ts(this.state32),this.posOut=0,this.pos=0}update(e){ys(this),e=In(e),ps(e);const{blockLen:r,state:n}=this,s=e.length;for(let i=0;i<s;){const a=Math.min(r-this.pos,s-i);for(let o=0;o<a;o++)n[this.pos++]^=e[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:n,blockLen:s}=this;e[n]^=r,r&128&&n===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){ys(this,!1),ps(e),this.finish();const r=this.state,{blockLen:n}=this;for(let s=0,i=e.length;s<i;){this.posOut>=n&&this.keccak();const a=Math.min(n-this.posOut,i-s);e.set(r.subarray(this.posOut,this.posOut+a),s),this.posOut+=a,s+=a}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return hs(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(yh(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Rn(this.state)}_cloneInto(e){const{blockLen:r,suffix:n,outputLen:s,rounds:i,enableXOF:a}=this;return e||(e=new mh(r,n,s,a,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=s,e.enableXOF=a,e.destroyed=this.destroyed,e}}const MA=(t,e,r)=>dg(()=>new mh(e,t,r)),bg=MA(1,136,256/8);function bt(t,e){const r=e||"hex",n=bg(Nr(t,{strict:!1})?Zi(t):t);return r==="bytes"?n:Ft(n)}const $A=t=>bt(Zi(t));function jA(t){return $A(t)}function HA(t){let e=!0,r="",n=0,s="",i=!1;for(let a=0;a<t.length;a++){const o=t[a];if(["(",")",","].includes(o)&&(e=!0),o==="("&&n++,o===")"&&n--,!!e){if(n===0){if(o===" "&&["event","function",""].includes(s))s="";else if(s+=o,o===")"){i=!0;break}continue}if(o===" "){t[a-1]!==","&&r!==","&&r!==",("&&(r="",e=!1);continue}s+=o,r+=o}}if(!i)throw new G("Unable to normalize signature.");return s}const LA=t=>{const e=typeof t=="string"?t:Pc(t);return HA(e)};function gg(t){return jA(LA(t))}const ou=gg;let $t=class extends G{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}},Qi=class extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}};const tl=new Qi(8192);function ko(t,e){if(tl.has(`${t}.${e}`))return tl.get(`${t}.${e}`);const r=t.substring(2).toLowerCase(),n=bt(Ls(r),"bytes"),s=r.split("");for(let a=0;a<40;a+=2)n[a>>1]>>4>=8&&s[a]&&(s[a]=s[a].toUpperCase()),(n[a>>1]&15)>=8&&s[a+1]&&(s[a+1]=s[a+1].toUpperCase());const i=`0x${s.join("")}`;return tl.set(`${t}.${e}`,i),i}function bh(t,e){if(!ct(t,{strict:!1}))throw new $t({address:t});return ko(t,e)}const DA=/^0x[a-fA-F0-9]{40}$/,rl=new Qi(8192);function ct(t,e){const{strict:r=!0}=e??{},n=`${t}.${r}`;if(rl.has(n))return rl.get(n);const s=DA.test(t)?t.toLowerCase()===t?!0:r?ko(t)===t:!0:!1;return rl.set(n,s),s}function sr(t){return typeof t[0]=="string"?jr(t):zA(t)}function zA(t){let e=0;for(const s of t)e+=s.length;const r=new Uint8Array(e);let n=0;for(const s of t)r.set(s,n),n+=s.length;return r}function jr(t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function Ks(t,e,r,{strict:n}={}){return Nr(t,{strict:!1})?rd(t,e,r,{strict:n}):Eg(t,e,r,{strict:n})}function wg(t,e){if(typeof e=="number"&&e>0&&e>Ge(t)-1)throw new tg({offset:e,position:"start",size:Ge(t)})}function vg(t,e,r){if(typeof e=="number"&&typeof r=="number"&&Ge(t)!==r-e)throw new tg({offset:r,position:"end",size:Ge(t)})}function Eg(t,e,r,{strict:n}={}){wg(t,e);const s=t.slice(e,r);return n&&vg(s,e,r),s}function rd(t,e,r,{strict:n}={}){wg(t,e);const s=`0x${t.replace("0x","").slice((e??0)*2,(r??t.length)*2)}`;return n&&vg(s,e,r),s}const VA=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Ag=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;function vs(t,e){if(t.length!==e.length)throw new qE({expectedLength:t.length,givenLength:e.length});const r=GA({params:t,values:e}),n=wh(r);return n.length===0?"0x":n}function GA({params:t,values:e}){const r=[];for(let n=0;n<t.length;n++)r.push(gh({param:t[n],value:e[n]}));return r}function gh({param:t,value:e}){const r=vh(t.type);if(r){const[n,s]=r;return WA(e,{length:n,param:{...t,type:s}})}if(t.type==="tuple")return ZA(e,{param:t});if(t.type==="address")return qA(e);if(t.type==="bool")return XA(e);if(t.type.startsWith("uint")||t.type.startsWith("int")){const n=t.type.startsWith("int"),[,,s="256"]=Ag.exec(t.type)??[];return YA(e,{signed:n,size:Number(s)})}if(t.type.startsWith("bytes"))return KA(e,{param:t});if(t.type==="string")return JA(e);throw new QE(t.type,{docsPath:"/docs/contract/encodeAbiParameters"})}function wh(t){let e=0;for(let i=0;i<t.length;i++){const{dynamic:a,encoded:o}=t[i];a?e+=32:e+=Ge(o)}const r=[],n=[];let s=0;for(let i=0;i<t.length;i++){const{dynamic:a,encoded:o}=t[i];a?(r.push(Y(e+s,{size:32})),n.push(o),s+=Ge(o)):r.push(o)}return sr([...r,...n])}function qA(t){if(!ct(t))throw new $t({address:t});return{dynamic:!1,encoded:fs(t.toLowerCase())}}function WA(t,{length:e,param:r}){const n=e===null;if(!Array.isArray(t))throw new eg(t);if(!n&&t.length!==e)throw new VE({expectedLength:e,givenLength:t.length,type:`${r.type}[${e}]`});let s=!1;const i=[];for(let a=0;a<t.length;a++){const o=gh({param:r,value:t[a]});o.dynamic&&(s=!0),i.push(o)}if(n||s){const a=wh(i);if(n){const o=Y(i.length,{size:32});return{dynamic:!0,encoded:i.length>0?sr([o,a]):o}}if(s)return{dynamic:!0,encoded:a}}return{dynamic:!1,encoded:sr(i.map(({encoded:a})=>a))}}function KA(t,{param:e}){const[,r]=e.type.split("bytes"),n=Ge(t);if(!r){let s=t;return n%32!==0&&(s=fs(s,{dir:"right",size:Math.ceil((t.length-2)/2/32)*32})),{dynamic:!0,encoded:sr([fs(Y(n,{size:32})),s])}}if(n!==Number.parseInt(r,10))throw new GE({expectedSize:Number.parseInt(r,10),value:t});return{dynamic:!1,encoded:fs(t,{dir:"right"})}}function XA(t){if(typeof t!="boolean")throw new G(`Invalid boolean value: "${t}" (type: ${typeof t}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:fs(ng(t))}}function YA(t,{signed:e,size:r=256}){if(typeof r=="number"){const n=2n**(BigInt(r)-(e?1n:0n))-1n,s=e?-n-1n:0n;if(t>n||t<s)throw new ph({max:n.toString(),min:s.toString(),signed:e,size:r/8,value:t.toString()})}return{dynamic:!1,encoded:Y(t,{size:32,signed:e})}}function JA(t){const e=zi(t),r=Math.ceil(Ge(e)/32),n=[];for(let s=0;s<r;s++)n.push(fs(Ks(e,s*32,(s+1)*32),{dir:"right"}));return{dynamic:!0,encoded:sr([fs(Y(Ge(e),{size:32})),...n])}}function ZA(t,{param:e}){let r=!1;const n=[];for(let s=0;s<e.components.length;s++){const i=e.components[s],a=Array.isArray(t)?s:i.name,o=gh({param:i,value:t[a]});n.push(o),o.dynamic&&(r=!0)}return{dynamic:r,encoded:r?wh(n):sr(n.map(({encoded:s})=>s))}}function vh(t){const e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}const To=t=>Ks(gg(t),0,4);function oi(t){const{abi:e,args:r=[],name:n}=t,s=Nr(n,{strict:!1}),i=e.filter(o=>s?o.type==="function"?To(o)===n:o.type==="event"?ou(o)===n:!1:"name"in o&&o.name===n);if(i.length===0)return;if(i.length===1)return i[0];let a;for(const o of i){if(!("inputs"in o))continue;if(!r||r.length===0){if(!o.inputs||o.inputs.length===0)return o;continue}if(!o.inputs||o.inputs.length===0||o.inputs.length!==r.length)continue;if(r.every((u,l)=>{const f="inputs"in o&&o.inputs[l];return f?nd(u,f):!1})){if(a&&"inputs"in a&&a.inputs){const u=Sg(o.inputs,a.inputs,r);if(u)throw new JE({abiItem:o,type:u[0]},{abiItem:a,type:u[1]})}a=o}}return a||i[0]}function nd(t,e){const r=typeof t,n=e.type;switch(n){case"address":return ct(t,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in e?Object.values(e.components).every((s,i)=>r==="object"&&nd(Object.values(t)[i],s)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?r==="number"||r==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?r==="string"||t instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(t)&&t.every(s=>nd(s,{...e,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function Sg(t,e,r){for(const n in t){const s=t[n],i=e[n];if(s.type==="tuple"&&i.type==="tuple"&&"components"in s&&"components"in i)return Sg(s.components,i.components,r[n]);const a=[s.type,i.type];if(a.includes("address")&&a.includes("bytes20")?!0:a.includes("address")&&a.includes("string")?ct(r[n],{strict:!1}):a.includes("address")&&a.includes("bytes")?ct(r[n],{strict:!1}):!1)return a}}const Ep="/docs/contract/encodeEventTopics";function _o(t){var c;const{abi:e,eventName:r,args:n}=t;let s=e[0];if(r){const u=oi({abi:e,name:r});if(!u)throw new yp(r,{docsPath:Ep});s=u}if(s.type!=="event")throw new yp(void 0,{docsPath:Ep});const i=Rr(s),a=ou(i);let o=[];if(n&&"inputs"in s){const u=(c=s.inputs)==null?void 0:c.filter(f=>"indexed"in f&&f.indexed),l=Array.isArray(n)?n:Object.values(n).length>0?(u==null?void 0:u.map(f=>n[f.name]))??[]:[];l.length>0&&(o=(u==null?void 0:u.map((f,p)=>Array.isArray(l[p])?l[p].map((d,b)=>Ap({param:f,value:l[p][b]})):typeof l[p]<"u"&&l[p]!==null?Ap({param:f,value:l[p]}):null))??[])}return[a,...o]}function Ap({param:t,value:e}){if(t.type==="string"||t.type==="bytes")return bt(Zi(e));if(t.type==="tuple"||t.type.match(/^(.*)\[(\d+)?\]$/))throw new rA(t.type);return vs([t],[e])}function cu(t,{method:e}){var n,s;const r={};return t.transport.type==="fallback"&&((s=(n=t.transport).onResponse)==null||s.call(n,({method:i,response:a,status:o,transport:c})=>{o==="success"&&e===i&&(r[a]=c.request)})),i=>r[i]||t.request}async function Eh(t,e){const{address:r,abi:n,args:s,eventName:i,fromBlock:a,strict:o,toBlock:c}=e,u=cu(t,{method:"eth_newFilter"}),l=i?_o({abi:n,args:s,eventName:i}):void 0,f=await t.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof a=="bigint"?Y(a):a,toBlock:typeof c=="bigint"?Y(c):c,topics:l}]});return{abi:n,args:s,eventName:i,id:f,request:u(f),strict:!!o,type:"event"}}function Le(t){return typeof t=="string"?{address:t,type:"json-rpc"}:t}const Sp="/docs/contract/encodeFunctionData";function QA(t){const{abi:e,args:r,functionName:n}=t;let s=e[0];if(n){const i=oi({abi:e,args:r,name:n});if(!i)throw new Di(n,{docsPath:Sp});s=i}if(s.type!=="function")throw new Di(void 0,{docsPath:Sp});return{abi:[s],functionName:To(Rr(s))}}function or(t){const{args:e}=t,{abi:r,functionName:n}=(()=>{var o;return t.abi.length===1&&((o=t.functionName)!=null&&o.startsWith("0x"))?t:QA(t)})(),s=r[0],i=n,a="inputs"in s&&s.inputs?vs(s.inputs,e??[]):void 0;return jr([i,a??"0x"])}const eS={1:"An `assert` condition failed.",17:"Arithmetic operation resulted in underflow or overflow.",18:"Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).",33:"Attempted to convert to an invalid type.",34:"Attempted to access a storage byte array that is incorrectly encoded.",49:"Performed `.pop()` on an empty array",50:"Array index is out of bounds.",65:"Allocated too much memory or created an array which is too large.",81:"Attempted to call a zero-initialized variable of internal function type."},xg={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},tS={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"};let xp=class extends G{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`,{name:"NegativeOffsetError"})}},kg=class extends G{constructor({length:e,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${e}\`).`,{name:"PositionOutOfBoundsError"})}},rS=class extends G{constructor({count:e,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${e}\`).`,{name:"RecursiveReadLimitExceededError"})}};const nS={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new rS({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(t){if(t<0||t>this.bytes.length-1)throw new kg({length:this.bytes.length,position:t})},decrementPosition(t){if(t<0)throw new xp({offset:t});const e=this.position-t;this.assertPosition(e),this.position=e},getReadCount(t){return this.positionReadCount.get(t||this.position)||0},incrementPosition(t){if(t<0)throw new xp({offset:t});const e=this.position+t;this.assertPosition(e),this.position=e},inspectByte(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectBytes(t,e){const r=e??this.position;return this.assertPosition(r+t-1),this.bytes.subarray(r,r+t)},inspectUint8(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectUint16(t){const e=t??this.position;return this.assertPosition(e+1),this.dataView.getUint16(e)},inspectUint24(t){const e=t??this.position;return this.assertPosition(e+2),(this.dataView.getUint16(e)<<8)+this.dataView.getUint8(e+2)},inspectUint32(t){const e=t??this.position;return this.assertPosition(e+3),this.dataView.getUint32(e)},pushByte(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushBytes(t){this.assertPosition(this.position+t.length-1),this.bytes.set(t,this.position),this.position+=t.length},pushUint8(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushUint16(t){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,t),this.position+=2},pushUint24(t){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,t>>8),this.dataView.setUint8(this.position+2,t&255),this.position+=3},pushUint32(t){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,t),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const t=this.inspectByte();return this.position++,t},readBytes(t,e){this.assertReadLimit(),this._touch();const r=this.inspectBytes(t);return this.position+=e??t,r},readUint8(){this.assertReadLimit(),this._touch();const t=this.inspectUint8();return this.position+=1,t},readUint16(){this.assertReadLimit(),this._touch();const t=this.inspectUint16();return this.position+=2,t},readUint24(){this.assertReadLimit(),this._touch();const t=this.inspectUint24();return this.position+=3,t},readUint32(){this.assertReadLimit(),this._touch();const t=this.inspectUint32();return this.position+=4,t},get remaining(){return this.bytes.length-this.position},setPosition(t){const e=this.position;return this.assertPosition(t),this.position=t,()=>this.position=e},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const t=this.getReadCount();this.positionReadCount.set(this.position,t+1),t>0&&this.recursiveReadCount++}};function Ah(t,{recursiveReadLimit:e=8192}={}){const r=Object.create(nS);return r.bytes=t,r.dataView=new DataView(t.buffer??t,t.byteOffset,t.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=e,r}function sS(t,e={}){typeof e.size<"u"&&$r(t,{size:e.size});const r=tt(t,e);return lt(r,e)}function iS(t,e={}){let r=t;if(typeof e.size<"u"&&($r(r,{size:e.size}),r=br(r)),r.length>1||r[0]>1)throw new sA(r);return!!r[0]}function Pn(t,e={}){typeof e.size<"u"&&$r(t,{size:e.size});const r=tt(t,e);return gr(r,e)}function aS(t,e={}){let r=t;return typeof e.size<"u"&&($r(r,{size:e.size}),r=br(r,{dir:"right"})),new TextDecoder().decode(r)}function Io(t,e){const r=typeof e=="string"?an(e):e,n=Ah(r);if(Ge(r)===0&&t.length>0)throw new xo;if(Ge(e)&&Ge(e)<32)throw new Jb({data:typeof e=="string"?e:tt(e),params:t,size:Ge(e)});let s=0;const i=[];for(let a=0;a<t.length;++a){const o=t[a];n.setPosition(s);const[c,u]=Bi(n,o,{staticPosition:0});s+=u,i.push(c)}return i}function Bi(t,e,{staticPosition:r}){const n=vh(e.type);if(n){const[s,i]=n;return cS(t,{...e,type:i},{length:s,staticPosition:r})}if(e.type==="tuple")return dS(t,e,{staticPosition:r});if(e.type==="address")return oS(t);if(e.type==="bool")return uS(t);if(e.type.startsWith("bytes"))return lS(t,e,{staticPosition:r});if(e.type.startsWith("uint")||e.type.startsWith("int"))return fS(t,e);if(e.type==="string")return hS(t,{staticPosition:r});throw new eA(e.type,{docsPath:"/docs/contract/decodeAbiParameters"})}const kp=32,sd=32;function oS(t){const e=t.readBytes(32);return[ko(tt(Eg(e,-20))),32]}function cS(t,e,{length:r,staticPosition:n}){if(!r){const a=Pn(t.readBytes(sd)),o=n+a,c=o+kp;t.setPosition(o);const u=Pn(t.readBytes(kp)),l=Ha(e);let f=0;const p=[];for(let d=0;d<u;++d){t.setPosition(c+(l?d*32:f));const[b,g]=Bi(t,e,{staticPosition:c});f+=g,p.push(b)}return t.setPosition(n+32),[p,32]}if(Ha(e)){const a=Pn(t.readBytes(sd)),o=n+a,c=[];for(let u=0;u<r;++u){t.setPosition(o+u*32);const[l]=Bi(t,e,{staticPosition:o});c.push(l)}return t.setPosition(n+32),[c,32]}let s=0;const i=[];for(let a=0;a<r;++a){const[o,c]=Bi(t,e,{staticPosition:n+s});s+=c,i.push(o)}return[i,s]}function uS(t){return[iS(t.readBytes(32),{size:32}),32]}function lS(t,e,{staticPosition:r}){const[n,s]=e.type.split("bytes");if(!s){const a=Pn(t.readBytes(32));t.setPosition(r+a);const o=Pn(t.readBytes(32));if(o===0)return t.setPosition(r+32),["0x",32];const c=t.readBytes(o);return t.setPosition(r+32),[tt(c),32]}return[tt(t.readBytes(Number.parseInt(s,10),32)),32]}function fS(t,e){const r=e.type.startsWith("int"),n=Number.parseInt(e.type.split("int")[1]||"256",10),s=t.readBytes(32);return[n>48?sS(s,{signed:r}):Pn(s,{signed:r}),32]}function dS(t,e,{staticPosition:r}){const n=e.components.length===0||e.components.some(({name:a})=>!a),s=n?[]:{};let i=0;if(Ha(e)){const a=Pn(t.readBytes(sd)),o=r+a;for(let c=0;c<e.components.length;++c){const u=e.components[c];t.setPosition(o+i);const[l,f]=Bi(t,u,{staticPosition:o});i+=f,s[n?c:u==null?void 0:u.name]=l}return t.setPosition(r+32),[s,32]}for(let a=0;a<e.components.length;++a){const o=e.components[a],[c,u]=Bi(t,o,{staticPosition:r});s[n?a:o==null?void 0:o.name]=c,i+=u}return[s,i]}function hS(t,{staticPosition:e}){const r=Pn(t.readBytes(32)),n=e+r;t.setPosition(n);const s=Pn(t.readBytes(32));if(s===0)return t.setPosition(e+32),["",32];const i=t.readBytes(s,32),a=aS(br(i));return t.setPosition(e+32),[a,32]}function Ha(t){var n;const{type:e}=t;if(e==="string"||e==="bytes"||e.endsWith("[]"))return!0;if(e==="tuple")return(n=t.components)==null?void 0:n.some(Ha);const r=vh(t.type);return!!(r&&Ha({...t,type:r[1]}))}function Tg(t){const{abi:e,data:r}=t,n=Ks(r,0,4);if(n==="0x")throw new xo;const i=[...e||[],xg,tS].find(a=>a.type==="error"&&n===To(Rr(a)));if(!i)throw new Zb(n,{docsPath:"/docs/contract/decodeErrorResult"});return{abiItem:i,args:"inputs"in i&&i.inputs&&i.inputs.length>0?Io(i.inputs,Ks(r,4)):void 0,errorName:i.name}}const et=(t,e,r)=>JSON.stringify(t,(n,s)=>typeof s=="bigint"?s.toString():s,r);function _g({abiItem:t,args:e,includeFunctionName:r=!0,includeName:n=!1}){if("name"in t&&"inputs"in t&&t.inputs)return`${r?t.name:""}(${t.inputs.map((s,i)=>`${n&&s.name?`${s.name}: `:""}${typeof e[i]=="object"?et(e[i]):e[i]}`).join(", ")})`}const pS={gwei:9,wei:18},yS={ether:-9,wei:9};function Ig(t,e){let r=t.toString();const n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(e,"0");let[s,i]=[r.slice(0,r.length-e),r.slice(r.length-e)];return i=i.replace(/(0+)$/,""),`${n?"-":""}${s||"0"}${i?`.${i}`:""}`}function Sh(t,e="wei"){return Ig(t,pS[e])}function Gt(t,e="wei"){return Ig(t,yS[e])}class mS extends G{constructor({address:e}){super(`State for account "${e}" is set multiple times.`,{name:"AccountStateConflictError"})}}class bS extends G{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}function Tp(t){return t.reduce((e,{slot:r,value:n})=>`${e} ${r}: ${n}
50
- `,"")}function gS(t){return t.reduce((e,{address:r,...n})=>{let s=`${e} ${r}:
28
+ `.trim().replace(/\s+/g," "))}generateLeaves(e,r){let n,s,i;switch(r){case"redeem":n=e.destination_swap,s=n.delegate,i=n.delegate;break;case"refund":n=e.source_swap,s=n.delegate,i=n.delegate;break;case"instantRefund":n=e.source_swap,s=n.redeemer,i=n.redeemer;break;default:throw new Error("Invalid leaf generation type")}return[{version:tc,output:this.redeemLeaf(n.secret_hash,De(s))},[{version:tc,output:this.refundLeaf(n.timelock,De(n.initiator))},{version:tc,output:this.instantRefundLeaf(De(n.initiator),De(i))}]]}generateMerkleProofFor(e,r){const n=this.leafHash(1,r),s=this.leafHash(2,r),i=this.leafHash(0,r);switch(e){case 1:{const a=$6(i,s);return[ke.crypto.taggedHash("TapBranch",Buffer.concat(a))]}case 0:return[s,n];case 2:return[i,n];default:throw new Error(lr.invalidLeaf)}}getProvider(){return this.signer.getProvider()}get getPublicKey(){return this.signer.getPublicKey()}get htlcActorAddress(){return this.signer.getPublicKey()}};class $b{constructor(e,r){this.quoteUrl=new m.Url(e),this.auth=r}async getQuoteFromAssets({fromAsset:e,toAsset:r,amount:n,isExactOut:s=!1,options:i}){const a=D.ChainAsset.from(e),o=D.ChainAsset.from(r);return this.getQuote(a,o,n,s,i)}async getQuote(e,r,n,s=!1,i){try{const a=await this.auth.getAuthHeaders();if(a.error)return m.Err(a.error);const o={from:D.ChainAsset.from(e).toString(),to:D.ChainAsset.from(r).toString(),...s?{to_amount:n.toString()}:{from_amount:n.toString()},...(i==null?void 0:i.affiliateFee)!==void 0&&{affiliate_fee:i.affiliateFee.toString()},...(i==null?void 0:i.indicative)!==void 0&&{indicative:i.indicative.toString()}},c=this.quoteUrl.endpoint("/v2/quote").addSearchParams(o),u=await m.Fetcher.get(c,{retryCount:0,...i==null?void 0:i.request,headers:{...a.val,"Content-Type":"application/json"}});return u.error?m.Err(u.error):u.result?m.Ok(u.result):m.Err("GetQuote: Unexpected error, result is undefined")}catch(a){return m.Err("GetQuote:",String(a))}}}const nE="1.2.3";let Kt=class Qf extends Error{constructor(e,r={}){var a;const n=r.cause instanceof Qf?r.cause.details:(a=r.cause)!=null&&a.message?r.cause.message:r.details,s=r.cause instanceof Qf&&r.cause.docsPath||r.docsPath,i=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: https://abitype.dev${s}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${nE}`].join(`
29
+ `);super(i),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=s,this.metaMessages=r.metaMessages,this.shortMessage=e}};function $n(t,e){const r=t.exec(e);return r==null?void 0:r.groups}const jb=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Hb=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,Lb=/^\(.+?\).*?$/,fp=/^tuple(?<array>(\[(\d*)\])*)$/;function ed(t){let e=t.type;if(fp.test(t.type)&&"components"in t){e="(";const r=t.components.length;for(let s=0;s<r;s++){const i=t.components[s];e+=ed(i),s<r-1&&(e+=", ")}const n=$n(fp,t.type);return e+=`)${(n==null?void 0:n.array)||""}`,ed({...t,type:e})}return"indexed"in t&&t.indexed&&(e=`${e} indexed`),t.name?`${e} ${t.name}`:e}function Ai(t){let e="";const r=t.length;for(let n=0;n<r;n++){const s=t[n];e+=ed(s),n!==r-1&&(e+=", ")}return e}function Bc(t){var e;return t.type==="function"?`function ${t.name}(${Ai(t.inputs)})${t.stateMutability&&t.stateMutability!=="nonpayable"?` ${t.stateMutability}`:""}${(e=t.outputs)!=null&&e.length?` returns (${Ai(t.outputs)})`:""}`:t.type==="event"?`event ${t.name}(${Ai(t.inputs)})`:t.type==="error"?`error ${t.name}(${Ai(t.inputs)})`:t.type==="constructor"?`constructor(${Ai(t.inputs)})${t.stateMutability==="payable"?" payable":""}`:t.type==="fallback"?`fallback() external${t.stateMutability==="payable"?" payable":""}`:"receive() external payable"}const Db=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function sE(t){return Db.test(t)}function iE(t){return $n(Db,t)}const zb=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function aE(t){return zb.test(t)}function oE(t){return $n(zb,t)}const Vb=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function cE(t){return Vb.test(t)}function uE(t){return $n(Vb,t)}const Gb=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function au(t){return Gb.test(t)}function lE(t){return $n(Gb,t)}const qb=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function fE(t){return qb.test(t)}function dE(t){return $n(qb,t)}const Wb=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function hE(t){return Wb.test(t)}function pE(t){return $n(Wb,t)}const yE=/^receive\(\) external payable$/;function mE(t){return yE.test(t)}const dp=new Set(["memory","indexed","storage","calldata"]),bE=new Set(["indexed"]),td=new Set(["calldata","memory","storage"]);class gE extends Kt{constructor({signature:e}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(e,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}}class wE extends Kt{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}}class vE extends Kt{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}}class EE extends Kt{constructor({params:e}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(e,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"})}}class AE extends Kt{constructor({param:e}){super("Invalid ABI parameter.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}}class SE extends Kt{constructor({param:e,name:r}){super("Invalid ABI parameter.",{details:e,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}}class xE extends Kt{constructor({param:e,type:r,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}}class kE extends Kt{constructor({param:e,type:r,modifier:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}}class TE extends Kt{constructor({abiParameter:e}){super("Invalid ABI parameter.",{details:JSON.stringify(e,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}}class Yi extends Kt{constructor({signature:e,type:r}){super(`Invalid ${r} signature.`,{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}}class _E extends Kt{constructor({signature:e}){super("Unknown signature.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}}class IE extends Kt{constructor({signature:e}){super("Invalid struct signature.",{details:e,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}}class PE extends Kt{constructor({type:e}){super("Circular reference detected.",{metaMessages:[`Struct "${e}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}}class OE extends Kt{constructor({current:e,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${e.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}}function BE(t,e,r){let n="";if(r)for(const s of Object.entries(r)){if(!s)continue;let i="";for(const a of s[1])i+=`[${a.type}${a.name?`:${a.name}`:""}]`;n+=`(${s[0]}{${i}})`}return e?`${e}:${t}${n}`:`${t}${n}`}const tl=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]]);function rd(t,e={}){if(cE(t))return CE(t,e);if(aE(t))return RE(t,e);if(sE(t))return NE(t,e);if(fE(t))return UE(t,e);if(hE(t))return FE(t);if(mE(t))return{type:"receive",stateMutability:"payable"};throw new _E({signature:t})}function CE(t,e={}){const r=uE(t);if(!r)throw new Yi({signature:t,type:"function"});const n=Jt(r.parameters),s=[],i=n.length;for(let o=0;o<i;o++)s.push(Rn(n[o],{modifiers:td,structs:e,type:"function"}));const a=[];if(r.returns){const o=Jt(r.returns),c=o.length;for(let u=0;u<c;u++)a.push(Rn(o[u],{modifiers:td,structs:e,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:s,outputs:a}}function RE(t,e={}){const r=oE(t);if(!r)throw new Yi({signature:t,type:"event"});const n=Jt(r.parameters),s=[],i=n.length;for(let a=0;a<i;a++)s.push(Rn(n[a],{modifiers:bE,structs:e,type:"event"}));return{name:r.name,type:"event",inputs:s}}function NE(t,e={}){const r=iE(t);if(!r)throw new Yi({signature:t,type:"error"});const n=Jt(r.parameters),s=[],i=n.length;for(let a=0;a<i;a++)s.push(Rn(n[a],{structs:e,type:"error"}));return{name:r.name,type:"error",inputs:s}}function UE(t,e={}){const r=dE(t);if(!r)throw new Yi({signature:t,type:"constructor"});const n=Jt(r.parameters),s=[],i=n.length;for(let a=0;a<i;a++)s.push(Rn(n[a],{structs:e,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:s}}function FE(t){const e=pE(t);if(!e)throw new Yi({signature:t,type:"fallback"});return{type:"fallback",stateMutability:e.stateMutability??"nonpayable"}}const ME=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,$E=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,jE=/^u?int$/;function Rn(t,e){var f,p;const r=BE(t,e==null?void 0:e.type,e==null?void 0:e.structs);if(tl.has(r))return tl.get(r);const n=Lb.test(t),s=$n(n?$E:ME,t);if(!s)throw new AE({param:t});if(s.name&&LE(s.name))throw new SE({param:t,name:s.name});const i=s.name?{name:s.name}:{},a=s.modifier==="indexed"?{indexed:!0}:{},o=(e==null?void 0:e.structs)??{};let c,u={};if(n){c="tuple";const d=Jt(s.type),b=[],g=d.length;for(let A=0;A<g;A++)b.push(Rn(d[A],{structs:o}));u={components:b}}else if(s.type in o)c="tuple",u={components:o[s.type]};else if(jE.test(s.type))c=`${s.type}256`;else if(s.type==="address payable")c="address";else if(c=s.type,(e==null?void 0:e.type)!=="struct"&&!Kb(c))throw new vE({type:c});if(s.modifier){if(!((p=(f=e==null?void 0:e.modifiers)==null?void 0:f.has)!=null&&p.call(f,s.modifier)))throw new xE({param:t,type:e==null?void 0:e.type,modifier:s.modifier});if(td.has(s.modifier)&&!DE(c,!!s.array))throw new kE({param:t,type:e==null?void 0:e.type,modifier:s.modifier})}const l={type:`${c}${s.array??""}`,...i,...a,...u};return tl.set(r,l),l}function Jt(t,e=[],r="",n=0){const s=t.trim().length;for(let i=0;i<s;i++){const a=t[i],o=t.slice(i+1);switch(a){case",":return n===0?Jt(o,[...e,r.trim()]):Jt(o,e,`${r}${a}`,n);case"(":return Jt(o,e,`${r}${a}`,n+1);case")":return Jt(o,e,`${r}${a}`,n-1);default:return Jt(o,e,`${r}${a}`,n)}}if(r==="")return e;if(n!==0)throw new OE({current:r,depth:n});return e.push(r.trim()),e}function Kb(t){return t==="address"||t==="bool"||t==="function"||t==="string"||jb.test(t)||Hb.test(t)}const HE=/^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/;function LE(t){return t==="address"||t==="bool"||t==="function"||t==="string"||t==="tuple"||jb.test(t)||Hb.test(t)||HE.test(t)}function DE(t,e){return e||t==="bytes"||t==="string"||t==="tuple"}function ph(t){const e={},r=t.length;for(let a=0;a<r;a++){const o=t[a];if(!au(o))continue;const c=lE(o);if(!c)throw new Yi({signature:o,type:"struct"});const u=c.properties.split(";"),l=[],f=u.length;for(let p=0;p<f;p++){const b=u[p].trim();if(!b)continue;const g=Rn(b,{type:"struct"});l.push(g)}if(!l.length)throw new IE({signature:o});e[c.name]=l}const n={},s=Object.entries(e),i=s.length;for(let a=0;a<i;a++){const[o,c]=s[a];n[o]=Xb(c,e)}return n}const zE=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function Xb(t=[],e={},r=new Set){const n=[],s=t.length;for(let i=0;i<s;i++){const a=t[i];if(Lb.test(a.type))n.push(a);else{const c=$n(zE,a.type);if(!(c!=null&&c.type))throw new TE({abiParameter:a});const{array:u,type:l}=c;if(l in e){if(r.has(l))throw new PE({type:l});n.push({...a,type:`tuple${u??""}`,components:Xb(e[l],e,new Set([...r,l]))})}else if(Kb(l))n.push(a);else throw new wE({type:l})}}return n}function Yb(t){const e=ph(t),r=[],n=t.length;for(let s=0;s<n;s++){const i=t[s];au(i)||r.push(rd(i,e))}return r}function hp(t){let e;if(typeof t=="string")e=rd(t);else{const r=ph(t),n=t.length;for(let s=0;s<n;s++){const i=t[s];if(!au(i)){e=rd(i,r);break}}}if(!e)throw new gE({signature:t});return e}function pp(t){const e=[];if(typeof t=="string"){const r=Jt(t),n=r.length;for(let s=0;s<n;s++)e.push(Rn(r[s],{modifiers:dp}))}else{const r=ph(t),n=t.length;for(let s=0;s<n;s++){const i=t[s];if(au(i))continue;const a=Jt(i),o=a.length;for(let c=0;c<o;c++)e.push(Rn(a[c],{modifiers:dp,structs:r}))}}if(e.length===0)throw new EE({params:t});return e}function re(t,e,r){const n=t[e.name];if(typeof n=="function")return n;const s=t[r];return typeof s=="function"?s:i=>e(t,i)}function Rr(t,{includeName:e=!1}={}){if(t.type!=="function"&&t.type!=="event"&&t.type!=="error")throw new nA(t.type);return`${t.name}(${ou(t.inputs,{includeName:e})})`}function ou(t,{includeName:e=!1}={}){return t?t.map(r=>VE(r,{includeName:e})).join(e?", ":","):""}function VE(t,{includeName:e}){return t.type.startsWith("tuple")?`(${ou(t.components,{includeName:e})})${t.type.slice(5)}`:t.type+(e&&t.name?` ${t.name}`:"")}function Nr(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function Ge(t){return Nr(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const Jb="2.44.4";let fa={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:r})=>e?`${t??"https://viem.sh"}${e}${r?`#${r}`:""}`:void 0,version:`viem@${Jb}`},G=class nd extends Error{constructor(e,r={}){var o;const n=(()=>{var c;return r.cause instanceof nd?r.cause.details:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),s=r.cause instanceof nd&&r.cause.docsPath||r.docsPath,i=(o=fa.getDocsUrl)==null?void 0:o.call(fa,{...r,docsPath:s}),a=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...n?[`Details: ${n}`]:[],...fa.version?[`Version: ${fa.version}`]:[]].join(`
30
+ `);super(a,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=s,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=e,this.version=Jb}walk(e){return Zb(this,e)}};function Zb(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?Zb(t.cause,e):e?null:t}class GE extends G{constructor({docsPath:e}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(`
31
+ `),{docsPath:e,name:"AbiConstructorNotFoundError"})}}class yp extends G{constructor({docsPath:e}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join(`
32
+ `),{docsPath:e,name:"AbiConstructorParamsNotFoundError"})}}class Qb extends G{constructor({data:e,params:r,size:n}){super([`Data size of ${n} bytes is too small for given parameters.`].join(`
33
+ `),{metaMessages:[`Params: (${ou(r,{includeName:!0})})`,`Data: ${e} (${n} bytes)`],name:"AbiDecodingDataSizeTooSmallError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=e,this.params=r,this.size=n}}class xo extends G{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError"})}}class qE extends G{constructor({expectedLength:e,givenLength:r,type:n}){super([`ABI encoding array length mismatch for type ${n}.`,`Expected length: ${e}`,`Given length: ${r}`].join(`
34
+ `),{name:"AbiEncodingArrayLengthMismatchError"})}}class WE extends G{constructor({expectedSize:e,value:r}){super(`Size of bytes "${r}" (bytes${Ge(r)}) does not match expected size (bytes${e}).`,{name:"AbiEncodingBytesSizeMismatchError"})}}class KE extends G{constructor({expectedLength:e,givenLength:r}){super(["ABI encoding params/values length mismatch.",`Expected length (params): ${e}`,`Given length (values): ${r}`].join(`
35
+ `),{name:"AbiEncodingLengthMismatchError"})}}class XE extends G{constructor(e,{docsPath:r}){super([`Arguments (\`args\`) were provided to "${e}", but "${e}" on the ABI does not contain any parameters (\`inputs\`).`,"Cannot encode error result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the inputs exist on it."].join(`
36
+ `),{docsPath:r,name:"AbiErrorInputsNotFoundError"})}}class mp extends G{constructor(e,{docsPath:r}={}){super([`Error ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it."].join(`
37
+ `),{docsPath:r,name:"AbiErrorNotFoundError"})}}class eg extends G{constructor(e,{docsPath:r}){super([`Encoded error signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://openchain.xyz/signatures?query=${e}.`].join(`
38
+ `),{docsPath:r,name:"AbiErrorSignatureNotFoundError"}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.signature=e}}class YE extends G{constructor({docsPath:e}){super("Cannot extract event signature from empty topics.",{docsPath:e,name:"AbiEventSignatureEmptyTopicsError"})}}class JE extends G{constructor(e,{docsPath:r}){super([`Encoded event signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it.",`You can look up the signature here: https://openchain.xyz/signatures?query=${e}.`].join(`
39
+ `),{docsPath:r,name:"AbiEventSignatureNotFoundError"})}}class bp extends G{constructor(e,{docsPath:r}={}){super([`Event ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it."].join(`
40
+ `),{docsPath:r,name:"AbiEventNotFoundError"})}}class zi extends G{constructor(e,{docsPath:r}={}){super([`Function ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it."].join(`
41
+ `),{docsPath:r,name:"AbiFunctionNotFoundError"})}}class tg extends G{constructor(e,{docsPath:r}){super([`Function "${e}" does not contain any \`outputs\` on ABI.`,"Cannot decode function result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the function exists on it."].join(`
42
+ `),{docsPath:r,name:"AbiFunctionOutputsNotFoundError"})}}class ZE extends G{constructor(e,{docsPath:r}){super([`Encoded function signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it.",`You can look up the signature here: https://openchain.xyz/signatures?query=${e}.`].join(`
43
+ `),{docsPath:r,name:"AbiFunctionSignatureNotFoundError"})}}class QE extends G{constructor(e,r){super("Found ambiguous types in overloaded ABI items.",{metaMessages:[`\`${e.type}\` in \`${Rr(e.abiItem)}\`, and`,`\`${r.type}\` in \`${Rr(r.abiItem)}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."],name:"AbiItemAmbiguityError"})}}let eA=class extends G{constructor({expectedSize:e,givenSize:r}){super(`Expected bytes${e}, got bytes${r}.`,{name:"BytesSizeMismatchError"})}};class Cc extends G{constructor({abiItem:e,data:r,params:n,size:s}){super([`Data size of ${s} bytes is too small for non-indexed event parameters.`].join(`
44
+ `),{metaMessages:[`Params: (${ou(n,{includeName:!0})})`,`Data: ${r} (${s} bytes)`],name:"DecodeLogDataMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=e,this.data=r,this.params=n,this.size=s}}class yh extends G{constructor({abiItem:e,param:r}){super([`Expected a topic for indexed event parameter${r.name?` "${r.name}"`:""} on event "${Rr(e,{includeName:!0})}".`].join(`
45
+ `),{name:"DecodeLogTopicsMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=e}}class tA extends G{constructor(e,{docsPath:r}){super([`Type "${e}" is not a valid encoding type.`,"Please provide a valid ABI type."].join(`
46
+ `),{docsPath:r,name:"InvalidAbiEncodingType"})}}class rA extends G{constructor(e,{docsPath:r}){super([`Type "${e}" is not a valid decoding type.`,"Please provide a valid ABI type."].join(`
47
+ `),{docsPath:r,name:"InvalidAbiDecodingType"})}}let rg=class extends G{constructor(e){super([`Value "${e}" is not a valid array.`].join(`
48
+ `),{name:"InvalidArrayError"})}};class nA extends G{constructor(e){super([`"${e}" is not a valid definition type.`,'Valid types: "function", "event", "error"'].join(`
49
+ `),{name:"InvalidDefinitionTypeError"})}}class sA extends G{constructor(e){super(`Filter type "${e}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}let ng=class extends G{constructor({offset:e,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${e}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}},sg=class extends G{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}};class gp extends G{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} is expected to be ${r} ${n} long, but is ${e} ${n} long.`,{name:"InvalidBytesLengthError"})}}function Ji(t,{dir:e,size:r=32}={}){return typeof t=="string"?ds(t,{dir:e,size:r}):iA(t,{dir:e,size:r})}function ds(t,{dir:e,size:r=32}={}){if(r===null)return t;const n=t.replace("0x","");if(n.length>r*2)throw new sg({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[e==="right"?"padEnd":"padStart"](r*2,"0")}`}function iA(t,{dir:e,size:r=32}={}){if(r===null)return t;if(t.length>r)throw new sg({size:t.length,targetSize:r,type:"bytes"});const n=new Uint8Array(r);for(let s=0;s<r;s++){const i=e==="right";n[i?s:r-s-1]=t[i?s:t.length-s-1]}return n}let mh=class extends G{constructor({max:e,min:r,signed:n,size:s,value:i}){super(`Number "${i}" is not in safe ${s?`${s*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${r} to ${e})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}},aA=class extends G{constructor(e){super(`Bytes value "${e}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}};class oA extends G{constructor(e){super(`Hex value "${e}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`,{name:"InvalidHexBooleanError"})}}let cA=class extends G{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};function br(t,{dir:e="left"}={}){let r=typeof t=="string"?t.replace("0x",""):t,n=0;for(let s=0;s<r.length-1&&r[e==="left"?s:r.length-s-1].toString()==="0";s++)n++;return r=e==="left"?r.slice(n):r.slice(0,r.length-n),typeof t=="string"?(r.length===1&&e==="right"&&(r=`${r}0`),`0x${r.length%2===1?`0${r}`:r}`):r}function $r(t,{size:e}){if(Ge(t)>e)throw new cA({givenSize:Ge(t),maxSize:e})}function ft(t,e={}){const{signed:r}=e;e.size&&$r(t,{size:e.size});const n=BigInt(t);if(!r)return n;const s=(t.length-2)/2,i=(1n<<BigInt(s)*8n-1n)-1n;return n<=i?n:n-BigInt(`0x${"f".padStart(s*2,"f")}`)-1n}function uA(t,e={}){let r=t;if(e.size&&($r(r,{size:e.size}),r=br(r)),br(r)==="0x00")return!1;if(br(r)==="0x01")return!0;throw new oA(r)}function gr(t,e={}){const r=ft(t,e),n=Number(r);if(!Number.isSafeInteger(n))throw new mh({max:`${Number.MAX_SAFE_INTEGER}`,min:`${Number.MIN_SAFE_INTEGER}`,signed:e.signed,size:e.size,value:`${r}n`});return n}const lA=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ft(t,e={}){return typeof t=="number"||typeof t=="bigint"?Y(t,e):typeof t=="string"?Vi(t,e):typeof t=="boolean"?ig(t,e):tt(t,e)}function ig(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?($r(r,{size:e.size}),Ji(r,{size:e.size})):r}function tt(t,e={}){let r="";for(let s=0;s<t.length;s++)r+=lA[t[s]];const n=`0x${r}`;return typeof e.size=="number"?($r(n,{size:e.size}),Ji(n,{dir:"right",size:e.size})):n}function Y(t,e={}){const{signed:r,size:n}=e,s=BigInt(t);let i;n?r?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const a=typeof i=="bigint"&&r?-i-1n:0;if(i&&s>i||s<a){const c=typeof t=="bigint"?"n":"";throw new mh({max:i?`${i}${c}`:void 0,min:`${a}${c}`,signed:r,size:n,value:`${t}${c}`})}const o=`0x${(r&&s<0?(1n<<BigInt(n*8))+BigInt(s):s).toString(16)}`;return n?Ji(o,{size:n}):o}const fA=new TextEncoder;function Vi(t,e={}){const r=fA.encode(t);return tt(r,e)}const dA=new TextEncoder;function Zi(t,e={}){return typeof t=="number"||typeof t=="bigint"?pA(t,e):typeof t=="boolean"?hA(t,e):Nr(t)?an(t,e):Ds(t,e)}function hA(t,e={}){const r=new Uint8Array(1);return r[0]=Number(t),typeof e.size=="number"?($r(r,{size:e.size}),Ji(r,{size:e.size})):r}const pn={zero:48,nine:57,A:65,F:70,a:97,f:102};function wp(t){if(t>=pn.zero&&t<=pn.nine)return t-pn.zero;if(t>=pn.A&&t<=pn.F)return t-(pn.A-10);if(t>=pn.a&&t<=pn.f)return t-(pn.a-10)}function an(t,e={}){let r=t;e.size&&($r(r,{size:e.size}),r=Ji(r,{dir:"right",size:e.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);const s=n.length/2,i=new Uint8Array(s);for(let a=0,o=0;a<s;a++){const c=wp(n.charCodeAt(o++)),u=wp(n.charCodeAt(o++));if(c===void 0||u===void 0)throw new G(`Invalid byte sequence ("${n[o-2]}${n[o-1]}" in "${n}").`);i[a]=c*16+u}return i}function pA(t,e){const r=Y(t,e);return an(r)}function Ds(t,e={}){const r=dA.encode(t);return typeof e.size=="number"?($r(r,{size:e.size}),Ji(r,{dir:"right",size:e.size})):r}const rc=BigInt(2**32-1),vp=BigInt(32);function ag(t,e=!1){return e?{h:Number(t&rc),l:Number(t>>vp&rc)}:{h:Number(t>>vp&rc)|0,l:Number(t&rc)|0}}function yA(t,e=!1){const r=t.length;let n=new Uint32Array(r),s=new Uint32Array(r);for(let i=0;i<r;i++){const{h:a,l:o}=ag(t[i],e);[n[i],s[i]]=[a,o]}return[n,s]}const og=(t,e,r)=>t>>>r|e<<32-r,cg=(t,e,r)=>t<<32-r|e>>>r,mA=(t,e,r)=>t<<64-r|e>>>r-32,bA=(t,e,r)=>t>>>r-32|e<<64-r,gA=(t,e)=>e,wA=(t,e)=>t,vA=(t,e,r)=>t<<r|e>>>32-r,EA=(t,e,r)=>e<<r|t>>>32-r,AA=(t,e,r)=>e<<r-32|t>>>64-r,SA=(t,e,r)=>t<<r-32|e>>>64-r;function ug(t,e,r,n){const s=(e>>>0)+(n>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}const lg=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),fg=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,yi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function xA(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ps(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function ys(t,...e){if(!xA(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function kA(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ps(t.outputLen),ps(t.blockLen)}function ms(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function bh(t,e){ys(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function ja(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Nn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function rl(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function qr(t,e){return t<<32-e|t>>>e}const dg=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function hg(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const En=dg?t=>t:t=>hg(t);function TA(t){for(let e=0;e<t.length;e++)t[e]=hg(t[e]);return t}const rs=dg?t=>t:TA;function _A(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Pn(t){return typeof t=="string"&&(t=_A(t)),ys(t),t}function IA(...t){let e=0;for(let n=0;n<t.length;n++){const s=t[n];ys(s),e+=s.length}const r=new Uint8Array(e);for(let n=0,s=0;n<t.length;n++){const i=t[n];r.set(i,s),s+=i.length}return r}class cu{}function pg(t){const e=n=>t().update(Pn(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function PA(t){const e=(n,s)=>t(s).update(Pn(n)).digest(),r=t({});return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}function OA(t=32){if(yi&&typeof yi.getRandomValues=="function")return yi.getRandomValues(new Uint8Array(t));if(yi&&typeof yi.randomBytes=="function")return Uint8Array.from(yi.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const BA=BigInt(0),da=BigInt(1),CA=BigInt(2),RA=BigInt(7),NA=BigInt(256),UA=BigInt(113),yg=[],mg=[],bg=[];for(let t=0,e=da,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],yg.push(2*(5*n+r)),mg.push((t+1)*(t+2)/2%64);let s=BA;for(let i=0;i<7;i++)e=(e<<da^(e>>RA)*UA)%NA,e&CA&&(s^=da<<(da<<BigInt(i))-da);bg.push(s)}const gg=yA(bg,!0),FA=gg[0],MA=gg[1],Ep=(t,e,r)=>r>32?AA(t,e,r):vA(t,e,r),Ap=(t,e,r)=>r>32?SA(t,e,r):EA(t,e,r);function $A(t,e=24){const r=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let a=0;a<10;a++)r[a]=t[a]^t[a+10]^t[a+20]^t[a+30]^t[a+40];for(let a=0;a<10;a+=2){const o=(a+8)%10,c=(a+2)%10,u=r[c],l=r[c+1],f=Ep(u,l,1)^r[o],p=Ap(u,l,1)^r[o+1];for(let d=0;d<50;d+=10)t[a+d]^=f,t[a+d+1]^=p}let s=t[2],i=t[3];for(let a=0;a<24;a++){const o=mg[a],c=Ep(s,i,o),u=Ap(s,i,o),l=yg[a];s=t[l],i=t[l+1],t[l]=c,t[l+1]=u}for(let a=0;a<50;a+=10){for(let o=0;o<10;o++)r[o]=t[a+o];for(let o=0;o<10;o++)t[a+o]^=~r[(o+2)%10]&r[(o+4)%10]}t[0]^=FA[n],t[1]^=MA[n]}Nn(r)}class gh extends cu{constructor(e,r,n,s=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=s,this.rounds=i,ps(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=ja(this.state)}clone(){return this._cloneInto()}keccak(){rs(this.state32),$A(this.state32,this.rounds),rs(this.state32),this.posOut=0,this.pos=0}update(e){ms(this),e=Pn(e),ys(e);const{blockLen:r,state:n}=this,s=e.length;for(let i=0;i<s;){const a=Math.min(r-this.pos,s-i);for(let o=0;o<a;o++)n[this.pos++]^=e[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:n,blockLen:s}=this;e[n]^=r,r&128&&n===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){ms(this,!1),ys(e),this.finish();const r=this.state,{blockLen:n}=this;for(let s=0,i=e.length;s<i;){this.posOut>=n&&this.keccak();const a=Math.min(n-this.posOut,i-s);e.set(r.subarray(this.posOut,this.posOut+a),s),this.posOut+=a,s+=a}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ps(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(bh(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Nn(this.state)}_cloneInto(e){const{blockLen:r,suffix:n,outputLen:s,rounds:i,enableXOF:a}=this;return e||(e=new gh(r,n,s,a,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=s,e.enableXOF=a,e.destroyed=this.destroyed,e}}const jA=(t,e,r)=>pg(()=>new gh(e,t,r)),wg=jA(1,136,256/8);function bt(t,e){const r=e||"hex",n=wg(Nr(t,{strict:!1})?Zi(t):t);return r==="bytes"?n:Ft(n)}const HA=t=>bt(Zi(t));function LA(t){return HA(t)}function DA(t){let e=!0,r="",n=0,s="",i=!1;for(let a=0;a<t.length;a++){const o=t[a];if(["(",")",","].includes(o)&&(e=!0),o==="("&&n++,o===")"&&n--,!!e){if(n===0){if(o===" "&&["event","function",""].includes(s))s="";else if(s+=o,o===")"){i=!0;break}continue}if(o===" "){t[a-1]!==","&&r!==","&&r!==",("&&(r="",e=!1);continue}s+=o,r+=o}}if(!i)throw new G("Unable to normalize signature.");return s}const zA=t=>{const e=typeof t=="string"?t:Bc(t);return DA(e)};function vg(t){return LA(zA(t))}const uu=vg;let $t=class extends G{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}},Qi=class extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}};const nl=new Qi(8192);function ko(t,e){if(nl.has(`${t}.${e}`))return nl.get(`${t}.${e}`);const r=t.substring(2).toLowerCase(),n=bt(Ds(r),"bytes"),s=r.split("");for(let a=0;a<40;a+=2)n[a>>1]>>4>=8&&s[a]&&(s[a]=s[a].toUpperCase()),(n[a>>1]&15)>=8&&s[a+1]&&(s[a+1]=s[a+1].toUpperCase());const i=`0x${s.join("")}`;return nl.set(`${t}.${e}`,i),i}function wh(t,e){if(!ut(t,{strict:!1}))throw new $t({address:t});return ko(t,e)}const VA=/^0x[a-fA-F0-9]{40}$/,sl=new Qi(8192);function ut(t,e){const{strict:r=!0}=e??{},n=`${t}.${r}`;if(sl.has(n))return sl.get(n);const s=VA.test(t)?t.toLowerCase()===t?!0:r?ko(t)===t:!0:!1;return sl.set(n,s),s}function sr(t){return typeof t[0]=="string"?jr(t):GA(t)}function GA(t){let e=0;for(const s of t)e+=s.length;const r=new Uint8Array(e);let n=0;for(const s of t)r.set(s,n),n+=s.length;return r}function jr(t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function Xs(t,e,r,{strict:n}={}){return Nr(t,{strict:!1})?sd(t,e,r,{strict:n}):Sg(t,e,r,{strict:n})}function Eg(t,e){if(typeof e=="number"&&e>0&&e>Ge(t)-1)throw new ng({offset:e,position:"start",size:Ge(t)})}function Ag(t,e,r){if(typeof e=="number"&&typeof r=="number"&&Ge(t)!==r-e)throw new ng({offset:r,position:"end",size:Ge(t)})}function Sg(t,e,r,{strict:n}={}){Eg(t,e);const s=t.slice(e,r);return n&&Ag(s,e,r),s}function sd(t,e,r,{strict:n}={}){Eg(t,e);const s=`0x${t.replace("0x","").slice((e??0)*2,(r??t.length)*2)}`;return n&&Ag(s,e,r),s}const qA=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,xg=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;function Es(t,e){if(t.length!==e.length)throw new KE({expectedLength:t.length,givenLength:e.length});const r=WA({params:t,values:e}),n=Eh(r);return n.length===0?"0x":n}function WA({params:t,values:e}){const r=[];for(let n=0;n<t.length;n++)r.push(vh({param:t[n],value:e[n]}));return r}function vh({param:t,value:e}){const r=Ah(t.type);if(r){const[n,s]=r;return XA(e,{length:n,param:{...t,type:s}})}if(t.type==="tuple")return eS(e,{param:t});if(t.type==="address")return KA(e);if(t.type==="bool")return JA(e);if(t.type.startsWith("uint")||t.type.startsWith("int")){const n=t.type.startsWith("int"),[,,s="256"]=xg.exec(t.type)??[];return ZA(e,{signed:n,size:Number(s)})}if(t.type.startsWith("bytes"))return YA(e,{param:t});if(t.type==="string")return QA(e);throw new tA(t.type,{docsPath:"/docs/contract/encodeAbiParameters"})}function Eh(t){let e=0;for(let i=0;i<t.length;i++){const{dynamic:a,encoded:o}=t[i];a?e+=32:e+=Ge(o)}const r=[],n=[];let s=0;for(let i=0;i<t.length;i++){const{dynamic:a,encoded:o}=t[i];a?(r.push(Y(e+s,{size:32})),n.push(o),s+=Ge(o)):r.push(o)}return sr([...r,...n])}function KA(t){if(!ut(t))throw new $t({address:t});return{dynamic:!1,encoded:ds(t.toLowerCase())}}function XA(t,{length:e,param:r}){const n=e===null;if(!Array.isArray(t))throw new rg(t);if(!n&&t.length!==e)throw new qE({expectedLength:e,givenLength:t.length,type:`${r.type}[${e}]`});let s=!1;const i=[];for(let a=0;a<t.length;a++){const o=vh({param:r,value:t[a]});o.dynamic&&(s=!0),i.push(o)}if(n||s){const a=Eh(i);if(n){const o=Y(i.length,{size:32});return{dynamic:!0,encoded:i.length>0?sr([o,a]):o}}if(s)return{dynamic:!0,encoded:a}}return{dynamic:!1,encoded:sr(i.map(({encoded:a})=>a))}}function YA(t,{param:e}){const[,r]=e.type.split("bytes"),n=Ge(t);if(!r){let s=t;return n%32!==0&&(s=ds(s,{dir:"right",size:Math.ceil((t.length-2)/2/32)*32})),{dynamic:!0,encoded:sr([ds(Y(n,{size:32})),s])}}if(n!==Number.parseInt(r,10))throw new WE({expectedSize:Number.parseInt(r,10),value:t});return{dynamic:!1,encoded:ds(t,{dir:"right"})}}function JA(t){if(typeof t!="boolean")throw new G(`Invalid boolean value: "${t}" (type: ${typeof t}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:ds(ig(t))}}function ZA(t,{signed:e,size:r=256}){if(typeof r=="number"){const n=2n**(BigInt(r)-(e?1n:0n))-1n,s=e?-n-1n:0n;if(t>n||t<s)throw new mh({max:n.toString(),min:s.toString(),signed:e,size:r/8,value:t.toString()})}return{dynamic:!1,encoded:Y(t,{size:32,signed:e})}}function QA(t){const e=Vi(t),r=Math.ceil(Ge(e)/32),n=[];for(let s=0;s<r;s++)n.push(ds(Xs(e,s*32,(s+1)*32),{dir:"right"}));return{dynamic:!0,encoded:sr([ds(Y(Ge(e),{size:32})),...n])}}function eS(t,{param:e}){let r=!1;const n=[];for(let s=0;s<e.components.length;s++){const i=e.components[s],a=Array.isArray(t)?s:i.name,o=vh({param:i,value:t[a]});n.push(o),o.dynamic&&(r=!0)}return{dynamic:r,encoded:r?Eh(n):sr(n.map(({encoded:s})=>s))}}function Ah(t){const e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}const To=t=>Xs(vg(t),0,4);function ci(t){const{abi:e,args:r=[],name:n}=t,s=Nr(n,{strict:!1}),i=e.filter(o=>s?o.type==="function"?To(o)===n:o.type==="event"?uu(o)===n:!1:"name"in o&&o.name===n);if(i.length===0)return;if(i.length===1)return i[0];let a;for(const o of i){if(!("inputs"in o))continue;if(!r||r.length===0){if(!o.inputs||o.inputs.length===0)return o;continue}if(!o.inputs||o.inputs.length===0||o.inputs.length!==r.length)continue;if(r.every((u,l)=>{const f="inputs"in o&&o.inputs[l];return f?id(u,f):!1})){if(a&&"inputs"in a&&a.inputs){const u=kg(o.inputs,a.inputs,r);if(u)throw new QE({abiItem:o,type:u[0]},{abiItem:a,type:u[1]})}a=o}}return a||i[0]}function id(t,e){const r=typeof t,n=e.type;switch(n){case"address":return ut(t,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in e?Object.values(e.components).every((s,i)=>r==="object"&&id(Object.values(t)[i],s)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?r==="number"||r==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?r==="string"||t instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(t)&&t.every(s=>id(s,{...e,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function kg(t,e,r){for(const n in t){const s=t[n],i=e[n];if(s.type==="tuple"&&i.type==="tuple"&&"components"in s&&"components"in i)return kg(s.components,i.components,r[n]);const a=[s.type,i.type];if(a.includes("address")&&a.includes("bytes20")?!0:a.includes("address")&&a.includes("string")?ut(r[n],{strict:!1}):a.includes("address")&&a.includes("bytes")?ut(r[n],{strict:!1}):!1)return a}}const Sp="/docs/contract/encodeEventTopics";function _o(t){var c;const{abi:e,eventName:r,args:n}=t;let s=e[0];if(r){const u=ci({abi:e,name:r});if(!u)throw new bp(r,{docsPath:Sp});s=u}if(s.type!=="event")throw new bp(void 0,{docsPath:Sp});const i=Rr(s),a=uu(i);let o=[];if(n&&"inputs"in s){const u=(c=s.inputs)==null?void 0:c.filter(f=>"indexed"in f&&f.indexed),l=Array.isArray(n)?n:Object.values(n).length>0?(u==null?void 0:u.map(f=>n[f.name]))??[]:[];l.length>0&&(o=(u==null?void 0:u.map((f,p)=>Array.isArray(l[p])?l[p].map((d,b)=>xp({param:f,value:l[p][b]})):typeof l[p]<"u"&&l[p]!==null?xp({param:f,value:l[p]}):null))??[])}return[a,...o]}function xp({param:t,value:e}){if(t.type==="string"||t.type==="bytes")return bt(Zi(e));if(t.type==="tuple"||t.type.match(/^(.*)\[(\d+)?\]$/))throw new sA(t.type);return Es([t],[e])}function lu(t,{method:e}){var n,s;const r={};return t.transport.type==="fallback"&&((s=(n=t.transport).onResponse)==null||s.call(n,({method:i,response:a,status:o,transport:c})=>{o==="success"&&e===i&&(r[a]=c.request)})),i=>r[i]||t.request}async function Sh(t,e){const{address:r,abi:n,args:s,eventName:i,fromBlock:a,strict:o,toBlock:c}=e,u=lu(t,{method:"eth_newFilter"}),l=i?_o({abi:n,args:s,eventName:i}):void 0,f=await t.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof a=="bigint"?Y(a):a,toBlock:typeof c=="bigint"?Y(c):c,topics:l}]});return{abi:n,args:s,eventName:i,id:f,request:u(f),strict:!!o,type:"event"}}function Le(t){return typeof t=="string"?{address:t,type:"json-rpc"}:t}const kp="/docs/contract/encodeFunctionData";function tS(t){const{abi:e,args:r,functionName:n}=t;let s=e[0];if(n){const i=ci({abi:e,args:r,name:n});if(!i)throw new zi(n,{docsPath:kp});s=i}if(s.type!=="function")throw new zi(void 0,{docsPath:kp});return{abi:[s],functionName:To(Rr(s))}}function or(t){const{args:e}=t,{abi:r,functionName:n}=(()=>{var o;return t.abi.length===1&&((o=t.functionName)!=null&&o.startsWith("0x"))?t:tS(t)})(),s=r[0],i=n,a="inputs"in s&&s.inputs?Es(s.inputs,e??[]):void 0;return jr([i,a??"0x"])}const rS={1:"An `assert` condition failed.",17:"Arithmetic operation resulted in underflow or overflow.",18:"Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).",33:"Attempted to convert to an invalid type.",34:"Attempted to access a storage byte array that is incorrectly encoded.",49:"Performed `.pop()` on an empty array",50:"Array index is out of bounds.",65:"Allocated too much memory or created an array which is too large.",81:"Attempted to call a zero-initialized variable of internal function type."},Tg={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},nS={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"};let Tp=class extends G{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`,{name:"NegativeOffsetError"})}},_g=class extends G{constructor({length:e,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${e}\`).`,{name:"PositionOutOfBoundsError"})}},sS=class extends G{constructor({count:e,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${e}\`).`,{name:"RecursiveReadLimitExceededError"})}};const iS={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new sS({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(t){if(t<0||t>this.bytes.length-1)throw new _g({length:this.bytes.length,position:t})},decrementPosition(t){if(t<0)throw new Tp({offset:t});const e=this.position-t;this.assertPosition(e),this.position=e},getReadCount(t){return this.positionReadCount.get(t||this.position)||0},incrementPosition(t){if(t<0)throw new Tp({offset:t});const e=this.position+t;this.assertPosition(e),this.position=e},inspectByte(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectBytes(t,e){const r=e??this.position;return this.assertPosition(r+t-1),this.bytes.subarray(r,r+t)},inspectUint8(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectUint16(t){const e=t??this.position;return this.assertPosition(e+1),this.dataView.getUint16(e)},inspectUint24(t){const e=t??this.position;return this.assertPosition(e+2),(this.dataView.getUint16(e)<<8)+this.dataView.getUint8(e+2)},inspectUint32(t){const e=t??this.position;return this.assertPosition(e+3),this.dataView.getUint32(e)},pushByte(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushBytes(t){this.assertPosition(this.position+t.length-1),this.bytes.set(t,this.position),this.position+=t.length},pushUint8(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushUint16(t){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,t),this.position+=2},pushUint24(t){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,t>>8),this.dataView.setUint8(this.position+2,t&255),this.position+=3},pushUint32(t){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,t),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const t=this.inspectByte();return this.position++,t},readBytes(t,e){this.assertReadLimit(),this._touch();const r=this.inspectBytes(t);return this.position+=e??t,r},readUint8(){this.assertReadLimit(),this._touch();const t=this.inspectUint8();return this.position+=1,t},readUint16(){this.assertReadLimit(),this._touch();const t=this.inspectUint16();return this.position+=2,t},readUint24(){this.assertReadLimit(),this._touch();const t=this.inspectUint24();return this.position+=3,t},readUint32(){this.assertReadLimit(),this._touch();const t=this.inspectUint32();return this.position+=4,t},get remaining(){return this.bytes.length-this.position},setPosition(t){const e=this.position;return this.assertPosition(t),this.position=t,()=>this.position=e},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const t=this.getReadCount();this.positionReadCount.set(this.position,t+1),t>0&&this.recursiveReadCount++}};function xh(t,{recursiveReadLimit:e=8192}={}){const r=Object.create(iS);return r.bytes=t,r.dataView=new DataView(t.buffer??t,t.byteOffset,t.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=e,r}function aS(t,e={}){typeof e.size<"u"&&$r(t,{size:e.size});const r=tt(t,e);return ft(r,e)}function oS(t,e={}){let r=t;if(typeof e.size<"u"&&($r(r,{size:e.size}),r=br(r)),r.length>1||r[0]>1)throw new aA(r);return!!r[0]}function On(t,e={}){typeof e.size<"u"&&$r(t,{size:e.size});const r=tt(t,e);return gr(r,e)}function cS(t,e={}){let r=t;return typeof e.size<"u"&&($r(r,{size:e.size}),r=br(r,{dir:"right"})),new TextDecoder().decode(r)}function Io(t,e){const r=typeof e=="string"?an(e):e,n=xh(r);if(Ge(r)===0&&t.length>0)throw new xo;if(Ge(e)&&Ge(e)<32)throw new Qb({data:typeof e=="string"?e:tt(e),params:t,size:Ge(e)});let s=0;const i=[];for(let a=0;a<t.length;++a){const o=t[a];n.setPosition(s);const[c,u]=Ci(n,o,{staticPosition:0});s+=u,i.push(c)}return i}function Ci(t,e,{staticPosition:r}){const n=Ah(e.type);if(n){const[s,i]=n;return lS(t,{...e,type:i},{length:s,staticPosition:r})}if(e.type==="tuple")return pS(t,e,{staticPosition:r});if(e.type==="address")return uS(t);if(e.type==="bool")return fS(t);if(e.type.startsWith("bytes"))return dS(t,e,{staticPosition:r});if(e.type.startsWith("uint")||e.type.startsWith("int"))return hS(t,e);if(e.type==="string")return yS(t,{staticPosition:r});throw new rA(e.type,{docsPath:"/docs/contract/decodeAbiParameters"})}const _p=32,ad=32;function uS(t){const e=t.readBytes(32);return[ko(tt(Sg(e,-20))),32]}function lS(t,e,{length:r,staticPosition:n}){if(!r){const a=On(t.readBytes(ad)),o=n+a,c=o+_p;t.setPosition(o);const u=On(t.readBytes(_p)),l=Ha(e);let f=0;const p=[];for(let d=0;d<u;++d){t.setPosition(c+(l?d*32:f));const[b,g]=Ci(t,e,{staticPosition:c});f+=g,p.push(b)}return t.setPosition(n+32),[p,32]}if(Ha(e)){const a=On(t.readBytes(ad)),o=n+a,c=[];for(let u=0;u<r;++u){t.setPosition(o+u*32);const[l]=Ci(t,e,{staticPosition:o});c.push(l)}return t.setPosition(n+32),[c,32]}let s=0;const i=[];for(let a=0;a<r;++a){const[o,c]=Ci(t,e,{staticPosition:n+s});s+=c,i.push(o)}return[i,s]}function fS(t){return[oS(t.readBytes(32),{size:32}),32]}function dS(t,e,{staticPosition:r}){const[n,s]=e.type.split("bytes");if(!s){const a=On(t.readBytes(32));t.setPosition(r+a);const o=On(t.readBytes(32));if(o===0)return t.setPosition(r+32),["0x",32];const c=t.readBytes(o);return t.setPosition(r+32),[tt(c),32]}return[tt(t.readBytes(Number.parseInt(s,10),32)),32]}function hS(t,e){const r=e.type.startsWith("int"),n=Number.parseInt(e.type.split("int")[1]||"256",10),s=t.readBytes(32);return[n>48?aS(s,{signed:r}):On(s,{signed:r}),32]}function pS(t,e,{staticPosition:r}){const n=e.components.length===0||e.components.some(({name:a})=>!a),s=n?[]:{};let i=0;if(Ha(e)){const a=On(t.readBytes(ad)),o=r+a;for(let c=0;c<e.components.length;++c){const u=e.components[c];t.setPosition(o+i);const[l,f]=Ci(t,u,{staticPosition:o});i+=f,s[n?c:u==null?void 0:u.name]=l}return t.setPosition(r+32),[s,32]}for(let a=0;a<e.components.length;++a){const o=e.components[a],[c,u]=Ci(t,o,{staticPosition:r});s[n?a:o==null?void 0:o.name]=c,i+=u}return[s,i]}function yS(t,{staticPosition:e}){const r=On(t.readBytes(32)),n=e+r;t.setPosition(n);const s=On(t.readBytes(32));if(s===0)return t.setPosition(e+32),["",32];const i=t.readBytes(s,32),a=cS(br(i));return t.setPosition(e+32),[a,32]}function Ha(t){var n;const{type:e}=t;if(e==="string"||e==="bytes"||e.endsWith("[]"))return!0;if(e==="tuple")return(n=t.components)==null?void 0:n.some(Ha);const r=Ah(t.type);return!!(r&&Ha({...t,type:r[1]}))}function Ig(t){const{abi:e,data:r}=t,n=Xs(r,0,4);if(n==="0x")throw new xo;const i=[...e||[],Tg,nS].find(a=>a.type==="error"&&n===To(Rr(a)));if(!i)throw new eg(n,{docsPath:"/docs/contract/decodeErrorResult"});return{abiItem:i,args:"inputs"in i&&i.inputs&&i.inputs.length>0?Io(i.inputs,Xs(r,4)):void 0,errorName:i.name}}const et=(t,e,r)=>JSON.stringify(t,(n,s)=>typeof s=="bigint"?s.toString():s,r);function Pg({abiItem:t,args:e,includeFunctionName:r=!0,includeName:n=!1}){if("name"in t&&"inputs"in t&&t.inputs)return`${r?t.name:""}(${t.inputs.map((s,i)=>`${n&&s.name?`${s.name}: `:""}${typeof e[i]=="object"?et(e[i]):e[i]}`).join(", ")})`}const mS={gwei:9,wei:18},bS={ether:-9,wei:9};function Og(t,e){let r=t.toString();const n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(e,"0");let[s,i]=[r.slice(0,r.length-e),r.slice(r.length-e)];return i=i.replace(/(0+)$/,""),`${n?"-":""}${s||"0"}${i?`.${i}`:""}`}function kh(t,e="wei"){return Og(t,mS[e])}function Gt(t,e="wei"){return Og(t,bS[e])}class gS extends G{constructor({address:e}){super(`State for account "${e}" is set multiple times.`,{name:"AccountStateConflictError"})}}class wS extends G{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}function Ip(t){return t.reduce((e,{slot:r,value:n})=>`${e} ${r}: ${n}
50
+ `,"")}function vS(t){return t.reduce((e,{address:r,...n})=>{let s=`${e} ${r}:
51
51
  `;return n.nonce&&(s+=` nonce: ${n.nonce}
52
52
  `),n.balance&&(s+=` balance: ${n.balance}
53
53
  `),n.code&&(s+=` code: ${n.code}
54
54
  `),n.state&&(s+=` state:
55
- `,s+=Tp(n.state)),n.stateDiff&&(s+=` stateDiff:
56
- `,s+=Tp(n.stateDiff)),s},` State Override:
55
+ `,s+=Ip(n.state)),n.stateDiff&&(s+=` stateDiff:
56
+ `,s+=Ip(n.stateDiff)),s},` State Override:
57
57
  `).slice(0,-1)}function Po(t){const e=Object.entries(t).map(([n,s])=>s===void 0||s===!1?null:[n,s]).filter(Boolean),r=e.reduce((n,[s])=>Math.max(n,s.length),0);return e.map(([n,s])=>` ${`${n}:`.padEnd(r+1)} ${s}`).join(`
58
- `)}class wS extends G{constructor({v:e}){super(`Invalid \`v\` value "${e}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}}class vS extends G{constructor({transaction:e}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",Po(e),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}class ES extends G{constructor({storageKey:e}){super(`Size for storage key "${e}" is invalid. Expected 32 bytes. Got ${Math.floor((e.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}}class AS extends G{constructor(e,{account:r,docsPath:n,chain:s,data:i,gas:a,gasPrice:o,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:l,to:f,value:p}){var b;const d=Po({chain:s&&`${s==null?void 0:s.name} (id: ${s==null?void 0:s.id})`,from:r==null?void 0:r.address,to:f,value:typeof p<"u"&&`${Sh(p)} ${((b=s==null?void 0:s.nativeCurrency)==null?void 0:b.symbol)||"ETH"}`,data:i,gas:a,gasPrice:typeof o<"u"&&`${Gt(o)} gwei`,maxFeePerGas:typeof c<"u"&&`${Gt(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${Gt(u)} gwei`,nonce:l});super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Request Arguments:",d].filter(Boolean),name:"TransactionExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class Pg extends G{constructor({blockHash:e,blockNumber:r,blockTag:n,hash:s,index:i}){let a="Transaction";n&&i!==void 0&&(a=`Transaction at block time "${n}" at index "${i}"`),e&&i!==void 0&&(a=`Transaction at block hash "${e}" at index "${i}"`),r&&i!==void 0&&(a=`Transaction at block number "${r}" at index "${i}"`),s&&(a=`Transaction with hash "${s}"`),super(`${a} could not be found.`,{name:"TransactionNotFoundError"})}}class Og extends G{constructor({hash:e}){super(`Transaction receipt with hash "${e}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}}class Bg extends G{constructor({receipt:e}){super(`Transaction with hash "${e.transactionHash}" reverted.`,{metaMessages:['The receipt marked the transaction as "reverted". This could mean that the function on the contract you are trying to call threw an error.'," ","You can attempt to extract the revert reason by:","- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract","- using the `call` Action with raw `data`"],name:"TransactionReceiptRevertedError"}),Object.defineProperty(this,"receipt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.receipt=e}}class SS extends G{constructor({hash:e}){super(`Timed out while waiting for transaction with hash "${e}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}const xS=t=>t,uu=t=>t;class Cg extends G{constructor(e,{account:r,docsPath:n,chain:s,data:i,gas:a,gasPrice:o,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:l,to:f,value:p,stateOverride:d}){var A;const b=r?Le(r):void 0;let g=Po({from:b==null?void 0:b.address,to:f,value:typeof p<"u"&&`${Sh(p)} ${((A=s==null?void 0:s.nativeCurrency)==null?void 0:A.symbol)||"ETH"}`,data:i,gas:a,gasPrice:typeof o<"u"&&`${Gt(o)} gwei`,maxFeePerGas:typeof c<"u"&&`${Gt(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${Gt(u)} gwei`,nonce:l});d&&(g+=`
59
- ${gS(d)}`),super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Raw Call Arguments:",g].filter(Boolean),name:"CallExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class Rg extends G{constructor(e,{abi:r,args:n,contractAddress:s,docsPath:i,functionName:a,sender:o}){const c=oi({abi:r,args:n,name:a}),u=c?_g({abiItem:c,args:n,includeFunctionName:!1,includeName:!1}):void 0,l=c?Rr(c,{includeName:!0}):void 0,f=Po({address:s&&xS(s),function:l,args:u&&u!=="()"&&`${[...Array((a==null?void 0:a.length)??0).keys()].map(()=>" ").join("")}${u}`,sender:o});super(e.shortMessage||`An unknown error occurred while executing the contract function "${a}".`,{cause:e,docsPath:i,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],f&&"Contract Call:",f].filter(Boolean),name:"ContractFunctionExecutionError"}),Object.defineProperty(this,"abi",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"contractAddress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"formattedArgs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abi=r,this.args=n,this.cause=e,this.contractAddress=s,this.functionName=a,this.sender=o}}class id extends G{constructor({abi:e,data:r,functionName:n,message:s}){let i,a,o,c;if(r&&r!=="0x")try{a=Tg({abi:e,data:r});const{abiItem:l,errorName:f,args:p}=a;if(f==="Error")c=p[0];else if(f==="Panic"){const[d]=p;c=eS[d]}else{const d=l?Rr(l,{includeName:!0}):void 0,b=l&&p?_g({abiItem:l,args:p,includeFunctionName:!1,includeName:!1}):void 0;o=[d?`Error: ${d}`:"",b&&b!=="()"?` ${[...Array((f==null?void 0:f.length)??0).keys()].map(()=>" ").join("")}${b}`:""]}}catch(l){i=l}else s&&(c=s);let u;i instanceof Zb&&(u=i.signature,o=[`Unable to decode signature "${u}" as it was not found on the provided ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://openchain.xyz/signatures?query=${u}.`]),super(c&&c!=="execution reverted"||u?[`The contract function "${n}" reverted with the following ${u?"signature":"reason"}:`,c||u].join(`
60
- `):`The contract function "${n}" reverted.`,{cause:i,metaMessages:o,name:"ContractFunctionRevertedError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"raw",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=a,this.raw=r,this.reason=c,this.signature=u}}class kS extends G{constructor({functionName:e}){super(`The contract function "${e}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${e}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError"})}}class TS extends G{constructor({factory:e}){super(`Deployment for counterfactual contract call failed${e?` for factory "${e}".`:""}`,{metaMessages:["Please ensure:","- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).","- The `factoryData` is a valid encoded function call for contract deployment function on the factory."],name:"CounterfactualDeploymentFailedError"})}}class lu extends G{constructor({data:e,message:r}){super(r||"",{name:"RawContractError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=e}}class Ci extends G{constructor({body:e,cause:r,details:n,headers:s,status:i,url:a}){super("HTTP request failed.",{cause:r,details:n,metaMessages:[i&&`Status: ${i}`,`URL: ${uu(a)}`,e&&`Request body: ${et(e)}`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=e,this.headers=s,this.status=i,this.url=a}}class xh extends G{constructor({body:e,error:r,url:n}){super("RPC Request failed.",{cause:r,details:r.message,metaMessages:[`URL: ${uu(n)}`,`Request body: ${et(e)}`],name:"RpcRequestError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=r.code,this.data=r.data,this.url=n}}class _p extends G{constructor({body:e,url:r}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${uu(r)}`,`Request body: ${et(e)}`],name:"TimeoutError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=r}}const _S=-1;class Xt extends G{constructor(e,{code:r,docsPath:n,metaMessages:s,name:i,shortMessage:a}){super(a,{cause:e,docsPath:n,metaMessages:s||(e==null?void 0:e.metaMessages),name:i||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=i||e.name,this.code=e instanceof xh?e.code:r??_S}}class cr extends Xt{constructor(e,r){super(e,r),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=r.data}}class La extends Xt{constructor(e){super(e,{code:La.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(La,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class Da extends Xt{constructor(e){super(e,{code:Da.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(Da,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class za extends Xt{constructor(e,{method:r}={}){super(e,{code:za.code,name:"MethodNotFoundRpcError",shortMessage:`The method${r?` "${r}"`:""} does not exist / is not available.`})}}Object.defineProperty(za,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class Va extends Xt{constructor(e){super(e,{code:Va.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
61
- `)})}}Object.defineProperty(Va,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class Xs extends Xt{constructor(e){super(e,{code:Xs.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(Xs,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class ms extends Xt{constructor(e){super(e,{code:ms.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
62
- `)})}}Object.defineProperty(ms,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class Ga extends Xt{constructor(e){super(e,{code:Ga.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(Ga,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class qa extends Xt{constructor(e){super(e,{code:qa.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(qa,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class Wa extends Xt{constructor(e){super(e,{code:Wa.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(Wa,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class Cs extends Xt{constructor(e,{method:r}={}){super(e,{code:Cs.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${r?` "${r}"`:""} is not supported.`})}}Object.defineProperty(Cs,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class Vi extends Xt{constructor(e){super(e,{code:Vi.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(Vi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class Ka extends Xt{constructor(e){super(e,{code:Ka.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(Ka,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class Ri extends cr{constructor(e){super(e,{code:Ri.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(Ri,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class Xa extends cr{constructor(e){super(e,{code:Xa.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(Xa,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class Ya extends cr{constructor(e,{method:r}={}){super(e,{code:Ya.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${r?` " ${r}"`:""}.`})}}Object.defineProperty(Ya,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class Ja extends cr{constructor(e){super(e,{code:Ja.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(Ja,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class Za extends cr{constructor(e){super(e,{code:Za.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(Za,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class Qa extends cr{constructor(e){super(e,{code:Qa.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(Qa,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class Gi extends cr{constructor(e){super(e,{code:Gi.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(Gi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class eo extends cr{constructor(e){super(e,{code:eo.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(eo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class to extends cr{constructor(e){super(e,{code:to.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(to,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class ro extends cr{constructor(e){super(e,{code:ro.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(ro,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class no extends cr{constructor(e){super(e,{code:no.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(no,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class so extends cr{constructor(e){super(e,{code:so.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(so,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class qi extends cr{constructor(e){super(e,{code:qi.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(qi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class IS extends Xt{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}const PS=3;function Ys(t,{abi:e,address:r,args:n,docsPath:s,functionName:i,sender:a}){const o=t instanceof lu?t:t instanceof G?t.walk(b=>"data"in b)||t.walk():{},{code:c,data:u,details:l,message:f,shortMessage:p}=o,d=t instanceof xo?new kS({functionName:i}):[PS,Xs.code].includes(c)&&(u||l||f||p)||c===ms.code&&l==="execution reverted"&&u?new id({abi:e,data:typeof u=="object"?u.data:u,functionName:i,message:o instanceof xh?l:p??f}):t;return new Rg(d,{abi:e,args:n,contractAddress:r,docsPath:s,functionName:i,sender:a})}function OS(t){const e=bt(`0x${t.substring(4)}`).substring(26);return ko(`0x${e}`)}async function BS({hash:t,signature:e}){const r=Nr(t)?t:Ft(t),{secp256k1:n}=await Promise.resolve().then(()=>lk);return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:l,v:f,yParity:p}=e,d=Number(p??f),b=Ip(d);return new n.Signature(lt(u),lt(l)).addRecoveryBit(b)}const a=Nr(e)?e:Ft(e);if(Ge(a)!==65)throw new Error("invalid signature length");const o=gr(`0x${a.slice(130)}`),c=Ip(o);return n.Signature.fromCompact(a.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function Ip(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function Ng({hash:t,signature:e}){return OS(await BS({hash:t,signature:e}))}function bs(t,e="hex"){const r=Ug(t),n=Ah(new Uint8Array(r.length));return r.encode(n),e==="hex"?tt(n.bytes):n.bytes}function Ug(t){return Array.isArray(t)?CS(t.map(e=>Ug(e))):RS(t)}function CS(t){const e=t.reduce((s,i)=>s+i.length,0),r=Fg(e);return{length:e<=55?1+e:1+r+e,encode(s){e<=55?s.pushByte(192+e):(s.pushByte(247+r),r===1?s.pushUint8(e):r===2?s.pushUint16(e):r===3?s.pushUint24(e):s.pushUint32(e));for(const{encode:i}of t)i(s)}}}function RS(t){const e=typeof t=="string"?an(t):t,r=Fg(e.length);return{length:e.length===1&&e[0]<128?1:e.length<=55?1+e.length:1+r+e.length,encode(s){e.length===1&&e[0]<128?s.pushBytes(e):e.length<=55?(s.pushByte(128+e.length),s.pushBytes(e)):(s.pushByte(183+r),r===1?s.pushUint8(e.length):r===2?s.pushUint16(e.length):r===3?s.pushUint24(e.length):s.pushUint32(e.length),s.pushBytes(e))}}}function Fg(t){if(t<2**8)return 1;if(t<2**16)return 2;if(t<2**24)return 3;if(t<2**32)return 4;throw new G("Length is too large.")}function NS(t){const{chainId:e,nonce:r,to:n}=t,s=t.contractAddress??t.address,i=bt(jr(["0x05",bs([e?Y(e):"0x",s,r?Y(r):"0x"])]));return n==="bytes"?an(i):i}async function fu(t){const{authorization:e,signature:r}=t;return Ng({hash:NS(e),signature:r??e})}class US extends G{constructor(e,{account:r,docsPath:n,chain:s,data:i,gas:a,gasPrice:o,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:l,to:f,value:p}){var b;const d=Po({from:r==null?void 0:r.address,to:f,value:typeof p<"u"&&`${Sh(p)} ${((b=s==null?void 0:s.nativeCurrency)==null?void 0:b.symbol)||"ETH"}`,data:i,gas:a,gasPrice:typeof o<"u"&&`${Gt(o)} gwei`,maxFeePerGas:typeof c<"u"&&`${Gt(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${Gt(u)} gwei`,nonce:l});super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Estimate Gas Arguments:",d].filter(Boolean),name:"EstimateGasExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class xi extends G{constructor({cause:e,message:r}={}){var s;const n=(s=r==null?void 0:r.replace("execution reverted: ",""))==null?void 0:s.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:e,name:"ExecutionRevertedError"})}}Object.defineProperty(xi,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(xi,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});class Js extends G{constructor({cause:e,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${Gt(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:e,name:"FeeCapTooHighError"})}}Object.defineProperty(Js,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});class ad extends G{constructor({cause:e,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${Gt(r)}`:""} gwei) cannot be lower than the block base fee.`,{cause:e,name:"FeeCapTooLowError"})}}Object.defineProperty(ad,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});class od extends G{constructor({cause:e,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}is higher than the next one expected.`,{cause:e,name:"NonceTooHighError"})}}Object.defineProperty(od,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class cd extends G{constructor({cause:e,nonce:r}={}){super([`Nonce provided for the transaction ${r?`(${r}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(`
63
- `),{cause:e,name:"NonceTooLowError"})}}Object.defineProperty(cd,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class ud extends G{constructor({cause:e,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}exceeds the maximum allowed nonce.`,{cause:e,name:"NonceMaxValueError"})}}Object.defineProperty(ud,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});class ld extends G{constructor({cause:e}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
64
- `),{cause:e,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}}Object.defineProperty(ld,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class fd extends G{constructor({cause:e,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:e,name:"IntrinsicGasTooHighError"})}}Object.defineProperty(fd,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class dd extends G{constructor({cause:e,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction is too low.`,{cause:e,name:"IntrinsicGasTooLowError"})}}Object.defineProperty(dd,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class hd extends G{constructor({cause:e}){super("The transaction type is not supported for this chain.",{cause:e,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(hd,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class io extends G{constructor({cause:e,maxPriorityFeePerGas:r,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${r?` = ${Gt(r)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${Gt(n)} gwei`:""}).`].join(`
65
- `),{cause:e,name:"TipAboveFeeCapError"})}}Object.defineProperty(io,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});class Oo extends G{constructor({cause:e}){super(`An error occurred while executing: ${e==null?void 0:e.shortMessage}`,{cause:e,name:"UnknownNodeError"})}}function du(t,e){const r=(t.details||"").toLowerCase(),n=t instanceof G?t.walk(s=>(s==null?void 0:s.code)===xi.code):t;return n instanceof G?new xi({cause:t,message:n.details}):xi.nodeMessage.test(r)?new xi({cause:t,message:t.details}):Js.nodeMessage.test(r)?new Js({cause:t,maxFeePerGas:e==null?void 0:e.maxFeePerGas}):ad.nodeMessage.test(r)?new ad({cause:t,maxFeePerGas:e==null?void 0:e.maxFeePerGas}):od.nodeMessage.test(r)?new od({cause:t,nonce:e==null?void 0:e.nonce}):cd.nodeMessage.test(r)?new cd({cause:t,nonce:e==null?void 0:e.nonce}):ud.nodeMessage.test(r)?new ud({cause:t,nonce:e==null?void 0:e.nonce}):ld.nodeMessage.test(r)?new ld({cause:t}):fd.nodeMessage.test(r)?new fd({cause:t,gas:e==null?void 0:e.gas}):dd.nodeMessage.test(r)?new dd({cause:t,gas:e==null?void 0:e.gas}):hd.nodeMessage.test(r)?new hd({cause:t}):io.nodeMessage.test(r)?new io({cause:t,maxFeePerGas:e==null?void 0:e.maxFeePerGas,maxPriorityFeePerGas:e==null?void 0:e.maxPriorityFeePerGas}):new Oo({cause:t})}function FS(t,{docsPath:e,...r}){const n=(()=>{const s=du(t,r);return s instanceof Oo?t:s})();return new US(n,{docsPath:e,...r})}function ea(t,{format:e}){if(!e)return{};const r={};function n(i){const a=Object.keys(i);for(const o of a)o in t&&(r[o]=t[o]),i[o]&&typeof i[o]=="object"&&!Array.isArray(i[o])&&n(i[o])}const s=e(t||{});return n(s),r}function kh(t,e){return({exclude:r,format:n})=>({exclude:r,format:(s,i)=>{const a=e(s,i);if(r)for(const o of r)delete a[o];return{...a,...n(s,i)}},type:t})}const MS={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function Es(t,e){const r={};return typeof t.authorizationList<"u"&&(r.authorizationList=$S(t.authorizationList)),typeof t.accessList<"u"&&(r.accessList=t.accessList),typeof t.blobVersionedHashes<"u"&&(r.blobVersionedHashes=t.blobVersionedHashes),typeof t.blobs<"u"&&(typeof t.blobs[0]!="string"?r.blobs=t.blobs.map(n=>tt(n)):r.blobs=t.blobs),typeof t.data<"u"&&(r.data=t.data),t.account&&(r.from=t.account.address),typeof t.from<"u"&&(r.from=t.from),typeof t.gas<"u"&&(r.gas=Y(t.gas)),typeof t.gasPrice<"u"&&(r.gasPrice=Y(t.gasPrice)),typeof t.maxFeePerBlobGas<"u"&&(r.maxFeePerBlobGas=Y(t.maxFeePerBlobGas)),typeof t.maxFeePerGas<"u"&&(r.maxFeePerGas=Y(t.maxFeePerGas)),typeof t.maxPriorityFeePerGas<"u"&&(r.maxPriorityFeePerGas=Y(t.maxPriorityFeePerGas)),typeof t.nonce<"u"&&(r.nonce=Y(t.nonce)),typeof t.to<"u"&&(r.to=t.to),typeof t.type<"u"&&(r.type=MS[t.type]),typeof t.value<"u"&&(r.value=Y(t.value)),r}function $S(t){return t.map(e=>({address:e.address,r:e.r?Y(BigInt(e.r)):e.r,s:e.s?Y(BigInt(e.s)):e.s,chainId:Y(e.chainId),nonce:Y(e.nonce),...typeof e.yParity<"u"?{yParity:Y(e.yParity)}:{},...typeof e.v<"u"&&typeof e.yParity>"u"?{v:Y(e.v)}:{}}))}function Pp(t){if(!(!t||t.length===0))return t.reduce((e,{slot:r,value:n})=>{if(r.length!==66)throw new mp({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new mp({size:n.length,targetSize:66,type:"hex"});return e[r]=n,e},{})}function jS(t){const{balance:e,nonce:r,state:n,stateDiff:s,code:i}=t,a={};if(i!==void 0&&(a.code=i),e!==void 0&&(a.balance=Y(e)),r!==void 0&&(a.nonce=Y(r)),n!==void 0&&(a.state=Pp(n)),s!==void 0){if(a.state)throw new bS;a.stateDiff=Pp(s)}return a}function Th(t){if(!t)return;const e={};for(const{address:r,...n}of t){if(!ct(r,{strict:!1}))throw new $t({address:r});if(e[r])throw new mS({address:r});e[r]=jS(n)}return e}const hu=2n**256n-1n;function $n(t){const{account:e,maxFeePerGas:r,maxPriorityFeePerGas:n,to:s}=t,i=e?Le(e):void 0;if(i&&!ct(i.address))throw new $t({address:i.address});if(s&&!ct(s))throw new $t({address:s});if(r&&r>hu)throw new Js({maxFeePerGas:r});if(n&&r&&n>r)throw new io({maxFeePerGas:r,maxPriorityFeePerGas:n})}class Mg extends G{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class _h extends G{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class HS extends G{constructor({maxPriorityFeePerGas:e}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${Gt(e)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class $g extends G{constructor({blockHash:e,blockNumber:r}){let n="Block";e&&(n=`Block at hash "${e}"`),r&&(n=`Block at number "${r}"`),super(`${n} could not be found.`,{name:"BlockNotFoundError"})}}const jg={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function Bo(t,e){const r={...t,blockHash:t.blockHash?t.blockHash:null,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,chainId:t.chainId?gr(t.chainId):void 0,gas:t.gas?BigInt(t.gas):void 0,gasPrice:t.gasPrice?BigInt(t.gasPrice):void 0,maxFeePerBlobGas:t.maxFeePerBlobGas?BigInt(t.maxFeePerBlobGas):void 0,maxFeePerGas:t.maxFeePerGas?BigInt(t.maxFeePerGas):void 0,maxPriorityFeePerGas:t.maxPriorityFeePerGas?BigInt(t.maxPriorityFeePerGas):void 0,nonce:t.nonce?gr(t.nonce):void 0,to:t.to?t.to:null,transactionIndex:t.transactionIndex?Number(t.transactionIndex):null,type:t.type?jg[t.type]:void 0,typeHex:t.type?t.type:void 0,value:t.value?BigInt(t.value):void 0,v:t.v?BigInt(t.v):void 0};return t.authorizationList&&(r.authorizationList=DS(t.authorizationList)),r.yParity=(()=>{if(t.yParity)return Number(t.yParity);if(typeof r.v=="bigint"){if(r.v===0n||r.v===27n)return 0;if(r.v===1n||r.v===28n)return 1;if(r.v>=35n)return r.v%2n===0n?1:0}})(),r.type==="legacy"&&(delete r.accessList,delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas,delete r.yParity),r.type==="eip2930"&&(delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas),r.type==="eip1559"&&delete r.maxFeePerBlobGas,r}const LS=kh("transaction",Bo);function DS(t){return t.map(e=>({address:e.address,chainId:Number(e.chainId),nonce:Number(e.nonce),r:e.r,s:e.s,yParity:Number(e.yParity)}))}function Ih(t,e){const r=(t.transactions??[]).map(n=>typeof n=="string"?n:Bo(n));return{...t,baseFeePerGas:t.baseFeePerGas?BigInt(t.baseFeePerGas):null,blobGasUsed:t.blobGasUsed?BigInt(t.blobGasUsed):void 0,difficulty:t.difficulty?BigInt(t.difficulty):void 0,excessBlobGas:t.excessBlobGas?BigInt(t.excessBlobGas):void 0,gasLimit:t.gasLimit?BigInt(t.gasLimit):void 0,gasUsed:t.gasUsed?BigInt(t.gasUsed):void 0,hash:t.hash?t.hash:null,logsBloom:t.logsBloom?t.logsBloom:null,nonce:t.nonce?t.nonce:null,number:t.number?BigInt(t.number):null,size:t.size?BigInt(t.size):void 0,timestamp:t.timestamp?BigInt(t.timestamp):void 0,transactions:r,totalDifficulty:t.totalDifficulty?BigInt(t.totalDifficulty):null}}const zS=kh("block",Ih);async function Pr(t,{blockHash:e,blockNumber:r,blockTag:n=t.experimental_blockTag??"latest",includeTransactions:s}={}){var u,l,f;const i=s??!1,a=r!==void 0?Y(r):void 0;let o=null;if(e?o=await t.request({method:"eth_getBlockByHash",params:[e,i]},{dedupe:!0}):o=await t.request({method:"eth_getBlockByNumber",params:[a||n,i]},{dedupe:!!a}),!o)throw new $g({blockHash:e,blockNumber:r});return(((f=(l=(u=t.chain)==null?void 0:u.formatters)==null?void 0:l.block)==null?void 0:f.format)||Ih)(o,"getBlock")}async function Ph(t){const e=await t.request({method:"eth_gasPrice"});return BigInt(e)}async function VS(t,e){return Hg(t,e)}async function Hg(t,e){var i,a;const{block:r,chain:n=t.chain,request:s}=e||{};try{const o=((i=n==null?void 0:n.fees)==null?void 0:i.maxPriorityFeePerGas)??((a=n==null?void 0:n.fees)==null?void 0:a.defaultPriorityFee);if(typeof o=="function"){const u=r||await re(t,Pr,"getBlock")({}),l=await o({block:u,client:t,request:s});if(l===null)throw new Error;return l}if(typeof o<"u")return o;const c=await t.request({method:"eth_maxPriorityFeePerGas"});return lt(c)}catch{const[o,c]=await Promise.all([r?Promise.resolve(r):re(t,Pr,"getBlock")({}),re(t,Ph,"getGasPrice")({})]);if(typeof o.baseFeePerGas!="bigint")throw new _h;const u=c-o.baseFeePerGas;return u<0n?0n:u}}async function GS(t,e){return pd(t,e)}async function pd(t,e){var p,d;const{block:r,chain:n=t.chain,request:s,type:i="eip1559"}=e||{},a=await(async()=>{var b,g;return typeof((b=n==null?void 0:n.fees)==null?void 0:b.baseFeeMultiplier)=="function"?n.fees.baseFeeMultiplier({block:r,client:t,request:s}):((g=n==null?void 0:n.fees)==null?void 0:g.baseFeeMultiplier)??1.2})();if(a<1)throw new Mg;const c=10**(((p=a.toString().split(".")[1])==null?void 0:p.length)??0),u=b=>b*BigInt(Math.ceil(a*c))/BigInt(c),l=r||await re(t,Pr,"getBlock")({});if(typeof((d=n==null?void 0:n.fees)==null?void 0:d.estimateFeesPerGas)=="function"){const b=await n.fees.estimateFeesPerGas({block:r,client:t,multiply:u,request:s,type:i});if(b!==null)return b}if(i==="eip1559"){if(typeof l.baseFeePerGas!="bigint")throw new _h;const b=typeof(s==null?void 0:s.maxPriorityFeePerGas)=="bigint"?s.maxPriorityFeePerGas:await Hg(t,{block:l,chain:n,request:s}),g=u(l.baseFeePerGas);return{maxFeePerGas:(s==null?void 0:s.maxFeePerGas)??g+b,maxPriorityFeePerGas:b}}return{gasPrice:(s==null?void 0:s.gasPrice)??u(await re(t,Ph,"getGasPrice")({}))}}async function Oh(t,{address:e,blockTag:r="latest",blockNumber:n}){const s=await t.request({method:"eth_getTransactionCount",params:[e,typeof n=="bigint"?Y(n):r]},{dedupe:!!n});return gr(s)}function Bh(t){const{kzg:e}=t,r=t.to??(typeof t.blobs[0]=="string"?"hex":"bytes"),n=typeof t.blobs[0]=="string"?t.blobs.map(i=>an(i)):t.blobs,s=[];for(const i of n)s.push(Uint8Array.from(e.blobToKzgCommitment(i)));return r==="bytes"?s:s.map(i=>tt(i))}function Ch(t){const{kzg:e}=t,r=t.to??(typeof t.blobs[0]=="string"?"hex":"bytes"),n=typeof t.blobs[0]=="string"?t.blobs.map(a=>an(a)):t.blobs,s=typeof t.commitments[0]=="string"?t.commitments.map(a=>an(a)):t.commitments,i=[];for(let a=0;a<n.length;a++){const o=n[a],c=s[a];i.push(Uint8Array.from(e.computeBlobKzgProof(o,c)))}return r==="bytes"?i:i.map(a=>tt(a))}function qS(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const s=BigInt(32),i=BigInt(4294967295),a=Number(r>>s&i),o=Number(r&i),c=n?4:0,u=n?0:4;t.setUint32(e+c,a,n),t.setUint32(e+u,o,n)}function WS(t,e,r){return t&e^~t&r}function KS(t,e,r){return t&e^t&r^e&r}class XS extends au{constructor(e,r,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=el(this.buffer)}update(e){ys(this),e=In(e),ps(e);const{view:r,buffer:n,blockLen:s}=this,i=e.length;for(let a=0;a<i;){const o=Math.min(s-this.pos,i-a);if(o===s){const c=el(e);for(;s<=i-a;a+=s)this.process(c,a);continue}n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ys(this),yh(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:s,isLE:i}=this;let{pos:a}=this;r[a++]=128,Rn(this.buffer.subarray(a)),this.padOffset>s-a&&(this.process(n,0),a=0);for(let f=a;f<s;f++)r[f]=0;qS(n,s-8,BigInt(this.length*8),i),this.process(n,0);const o=el(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)o.setUint32(4*f,l[f],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:s,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=s,e.pos=o,s%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Kn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),YS=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]),Xn=new Uint32Array(64);class JS extends XS{constructor(e=32){super(64,e,8,!1),this.A=Kn[0]|0,this.B=Kn[1]|0,this.C=Kn[2]|0,this.D=Kn[3]|0,this.E=Kn[4]|0,this.F=Kn[5]|0,this.G=Kn[6]|0,this.H=Kn[7]|0}get(){const{A:e,B:r,C:n,D:s,E:i,F:a,G:o,H:c}=this;return[e,r,n,s,i,a,o,c]}set(e,r,n,s,i,a,o,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=s|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=c|0}process(e,r){for(let f=0;f<16;f++,r+=4)Xn[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){const p=Xn[f-15],d=Xn[f-2],b=qr(p,7)^qr(p,18)^p>>>3,g=qr(d,17)^qr(d,19)^d>>>10;Xn[f]=g+Xn[f-7]+b+Xn[f-16]|0}let{A:n,B:s,C:i,D:a,E:o,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){const p=qr(o,6)^qr(o,11)^qr(o,25),d=l+p+WS(o,c,u)+YS[f]+Xn[f]|0,g=(qr(n,2)^qr(n,13)^qr(n,22))+KS(n,s,i)|0;l=u,u=c,c=o,o=a+d|0,a=i,i=s,s=n,n=d+g|0}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,s,i,a,o,c,u,l)}roundClean(){Rn(Xn)}destroy(){this.set(0,0,0,0,0,0,0,0),Rn(this.buffer)}}const Lg=dg(()=>new JS),ZS=Lg;function Aa(t,e){const r=e||"hex",n=ZS(Nr(t,{strict:!1})?Zi(t):t);return r==="bytes"?n:Ft(n)}function QS(t){const{commitment:e,version:r=1}=t,n=t.to??(typeof e=="string"?"hex":"bytes"),s=Aa(e,"bytes");return s.set([r],0),n==="bytes"?s:tt(s)}function Dg(t){const{commitments:e,version:r}=t,n=t.to??(typeof e[0]=="string"?"hex":"bytes"),s=[];for(const i of e)s.push(QS({commitment:i,to:n,version:r}));return s}const Op=6,zg=32,Rh=4096,Vg=zg*Rh,Bp=Vg*Op-1-1*Rh*Op,Gg=1;class e8 extends G{constructor({maxSize:e,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${e} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}}class qg extends G{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class t8 extends G{constructor({hash:e,size:r}){super(`Versioned hash "${e}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}}class r8 extends G{constructor({hash:e,version:r}){super(`Versioned hash "${e}" version is invalid.`,{metaMessages:[`Expected: ${Gg}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}function n8(t){const e=t.to??(typeof t.data=="string"?"hex":"bytes"),r=typeof t.data=="string"?an(t.data):t.data,n=Ge(r);if(!n)throw new qg;if(n>Bp)throw new e8({maxSize:Bp,size:n});const s=[];let i=!0,a=0;for(;i;){const o=Ah(new Uint8Array(Vg));let c=0;for(;c<Rh;){const u=r.slice(a,a+(zg-1));if(o.pushByte(0),o.pushBytes(u),u.length<31){o.pushByte(128),i=!1;break}c++,a+=31}s.push(o)}return e==="bytes"?s.map(o=>o.bytes):s.map(o=>tt(o.bytes))}function Wg(t){const{data:e,kzg:r,to:n}=t,s=t.blobs??n8({data:e,to:n}),i=t.commitments??Bh({blobs:s,kzg:r,to:n}),a=t.proofs??Ch({blobs:s,commitments:i,kzg:r,to:n}),o=[];for(let c=0;c<s.length;c++)o.push({blob:s[c],commitment:i[c],proof:a[c]});return o}function Kg(t){if(t.type)return t.type;if(typeof t.authorizationList<"u")return"eip7702";if(typeof t.blobs<"u"||typeof t.blobVersionedHashes<"u"||typeof t.maxFeePerBlobGas<"u"||typeof t.sidecars<"u")return"eip4844";if(typeof t.maxFeePerGas<"u"||typeof t.maxPriorityFeePerGas<"u")return"eip1559";if(typeof t.gasPrice<"u")return typeof t.accessList<"u"?"eip2930":"legacy";throw new vS({transaction:t})}function pu(t,{docsPath:e,...r}){const n=(()=>{const s=du(t,r);return s instanceof Oo?t:s})();return new AS(n,{docsPath:e,...r})}async function As(t){const e=await t.request({method:"eth_chainId"},{dedupe:!0});return gr(e)}async function Nh(t,e){var N,C,j,M,H;const{account:r=t.account,accessList:n,authorizationList:s,chain:i=t.chain,blobVersionedHashes:a,blobs:o,data:c,gas:u,gasPrice:l,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:d,nonce:b,nonceManager:g,to:A,type:S,value:T,...v}=e,w=await(async()=>{if(!r||!g||typeof b<"u")return b;const V=Le(r),Q=i?i.id:await re(t,As,"getChainId")({});return await g.consume({address:V.address,chainId:Q,client:t})})();$n(e);const x=(C=(N=i==null?void 0:i.formatters)==null?void 0:N.transactionRequest)==null?void 0:C.format,I=(x||Es)({...ea(v,{format:x}),account:r?Le(r):void 0,accessList:n,authorizationList:s,blobs:o,blobVersionedHashes:a,data:c,gas:u,gasPrice:l,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:d,nonce:w,to:A,type:S,value:T},"fillTransaction");try{const V=await t.request({method:"eth_fillTransaction",params:[I]}),U=(((M=(j=i==null?void 0:i.formatters)==null?void 0:j.transaction)==null?void 0:M.format)||Bo)(V.tx);delete U.blockHash,delete U.blockNumber,delete U.r,delete U.s,delete U.transactionIndex,delete U.v,delete U.yParity,U.data=U.input,U.gas&&(U.gas=e.gas??U.gas),U.gasPrice&&(U.gasPrice=e.gasPrice??U.gasPrice),U.maxFeePerBlobGas&&(U.maxFeePerBlobGas=e.maxFeePerBlobGas??U.maxFeePerBlobGas),U.maxFeePerGas&&(U.maxFeePerGas=e.maxFeePerGas??U.maxFeePerGas),U.maxPriorityFeePerGas&&(U.maxPriorityFeePerGas=e.maxPriorityFeePerGas??U.maxPriorityFeePerGas),U.nonce&&(U.nonce=e.nonce??U.nonce);const K=await(async()=>{var L,J;if(typeof((L=i==null?void 0:i.fees)==null?void 0:L.baseFeeMultiplier)=="function"){const B=await re(t,Pr,"getBlock")({});return i.fees.baseFeeMultiplier({block:B,client:t,request:e})}return((J=i==null?void 0:i.fees)==null?void 0:J.baseFeeMultiplier)??1.2})();if(K<1)throw new Mg;const q=10**(((H=K.toString().split(".")[1])==null?void 0:H.length)??0),O=L=>L*BigInt(Math.ceil(K*q))/BigInt(q);return U.maxFeePerGas&&!e.maxFeePerGas&&(U.maxFeePerGas=O(U.maxFeePerGas)),U.gasPrice&&!e.gasPrice&&(U.gasPrice=O(U.gasPrice)),{raw:V.raw,transaction:{from:I.from,...U}}}catch(V){throw pu(V,{...e,chain:t.chain})}}const Uh=["blobVersionedHashes","chainId","fees","gas","nonce","type"],Cp=new Map,nl=new Qi(128);async function Co(t,e){var w,x,_;let r=e;r.account??(r.account=t.account),r.parameters??(r.parameters=Uh);const{account:n,chain:s=t.chain,nonceManager:i,parameters:a}=r,o=(()=>{if(typeof(s==null?void 0:s.prepareTransactionRequest)=="function")return{fn:s.prepareTransactionRequest,runAt:["beforeFillTransaction"]};if(Array.isArray(s==null?void 0:s.prepareTransactionRequest))return{fn:s.prepareTransactionRequest[0],runAt:s.prepareTransactionRequest[1].runAt}})();let c;async function u(){return c||(typeof r.chainId<"u"?r.chainId:s?s.id:(c=await re(t,As,"getChainId")({}),c))}const l=n&&Le(n);let f=r.nonce;if(a.includes("nonce")&&typeof f>"u"&&l&&i){const I=await u();f=await i.consume({address:l.address,chainId:I,client:t})}o!=null&&o.fn&&((w=o.runAt)!=null&&w.includes("beforeFillTransaction"))&&(r=await o.fn({...r,chain:s},{phase:"beforeFillTransaction"}),f??(f=r.nonce));const d=((a.includes("blobVersionedHashes")||a.includes("sidecars"))&&r.kzg&&r.blobs||nl.get(t.uid)===!1||!["fees","gas"].some(N=>a.includes(N))?!1:!!(a.includes("chainId")&&typeof r.chainId!="number"||a.includes("nonce")&&typeof f!="number"||a.includes("fees")&&typeof r.gasPrice!="bigint"&&(typeof r.maxFeePerGas!="bigint"||typeof r.maxPriorityFeePerGas!="bigint")||a.includes("gas")&&typeof r.gas!="bigint"))?await re(t,Nh,"fillTransaction")({...r,nonce:f}).then(I=>{const{chainId:N,from:C,gas:j,gasPrice:M,nonce:H,maxFeePerBlobGas:V,maxFeePerGas:Q,maxPriorityFeePerGas:U,type:K,...ee}=I.transaction;return nl.set(t.uid,!0),{...r,...C?{from:C}:{},...K?{type:K}:{},...typeof N<"u"?{chainId:N}:{},...typeof j<"u"?{gas:j}:{},...typeof M<"u"?{gasPrice:M}:{},...typeof H<"u"?{nonce:H}:{},...typeof V<"u"?{maxFeePerBlobGas:V}:{},...typeof Q<"u"?{maxFeePerGas:Q}:{},...typeof U<"u"?{maxPriorityFeePerGas:U}:{},..."nonceKey"in ee&&typeof ee.nonceKey<"u"?{nonceKey:ee.nonceKey}:{}}}).catch(I=>{var j;const N=I;return N.name!=="TransactionExecutionError"||((j=N.walk)==null?void 0:j.call(N,M=>{const H=M;return H.name==="MethodNotFoundRpcError"||H.name==="MethodNotSupportedRpcError"}))&&nl.set(t.uid,!1),r}):r;f??(f=d.nonce),r={...d,...l?{from:l==null?void 0:l.address}:{},...f?{nonce:f}:{}};const{blobs:b,gas:g,kzg:A,type:S}=r;o!=null&&o.fn&&((x=o.runAt)!=null&&x.includes("beforeFillParameters"))&&(r=await o.fn({...r,chain:s},{phase:"beforeFillParameters"}));let T;async function v(){return T||(T=await re(t,Pr,"getBlock")({blockTag:"latest"}),T)}if(a.includes("nonce")&&typeof f>"u"&&l&&!i&&(r.nonce=await re(t,Oh,"getTransactionCount")({address:l.address,blockTag:"pending"})),(a.includes("blobVersionedHashes")||a.includes("sidecars"))&&b&&A){const I=Bh({blobs:b,kzg:A});if(a.includes("blobVersionedHashes")){const N=Dg({commitments:I,to:"hex"});r.blobVersionedHashes=N}if(a.includes("sidecars")){const N=Ch({blobs:b,commitments:I,kzg:A}),C=Wg({blobs:b,commitments:I,proofs:N,to:"hex"});r.sidecars=C}}if(a.includes("chainId")&&(r.chainId=await u()),(a.includes("fees")||a.includes("type"))&&typeof S>"u")try{r.type=Kg(r)}catch{let I=Cp.get(t.uid);if(typeof I>"u"){const N=await v();I=typeof(N==null?void 0:N.baseFeePerGas)=="bigint",Cp.set(t.uid,I)}r.type=I?"eip1559":"legacy"}if(a.includes("fees"))if(r.type!=="legacy"&&r.type!=="eip2930"){if(typeof r.maxFeePerGas>"u"||typeof r.maxPriorityFeePerGas>"u"){const I=await v(),{maxFeePerGas:N,maxPriorityFeePerGas:C}=await pd(t,{block:I,chain:s,request:r});if(typeof r.maxPriorityFeePerGas>"u"&&r.maxFeePerGas&&r.maxFeePerGas<C)throw new HS({maxPriorityFeePerGas:C});r.maxPriorityFeePerGas=C,r.maxFeePerGas=N}}else{if(typeof r.maxFeePerGas<"u"||typeof r.maxPriorityFeePerGas<"u")throw new _h;if(typeof r.gasPrice>"u"){const I=await v(),{gasPrice:N}=await pd(t,{block:I,chain:s,request:r,type:"legacy"});r.gasPrice=N}}return a.includes("gas")&&typeof g>"u"&&(r.gas=await re(t,Fh,"estimateGas")({...r,account:l,prepare:(l==null?void 0:l.type)==="local"?[]:["blobVersionedHashes"]})),o!=null&&o.fn&&((_=o.runAt)!=null&&_.includes("afterFillParameters"))&&(r=await o.fn({...r,chain:s},{phase:"afterFillParameters"})),$n(r),delete r.parameters,r}async function Fh(t,e){var a,o,c;const{account:r=t.account,prepare:n=!0}=e,s=r?Le(r):void 0,i=(()=>{if(Array.isArray(n))return n;if((s==null?void 0:s.type)!=="local")return["blobVersionedHashes"]})();try{const u=await(async()=>{if(e.to)return e.to;if(e.authorizationList&&e.authorizationList.length>0)return await fu({authorization:e.authorizationList[0]}).catch(()=>{throw new G("`to` is required. Could not infer from `authorizationList`")})})(),{accessList:l,authorizationList:f,blobs:p,blobVersionedHashes:d,blockNumber:b,blockTag:g,data:A,gas:S,gasPrice:T,maxFeePerBlobGas:v,maxFeePerGas:w,maxPriorityFeePerGas:x,nonce:_,value:I,stateOverride:N,...C}=n?await Co(t,{...e,parameters:i,to:u}):e;if(S&&e.gas!==S)return S;const M=(typeof b=="bigint"?Y(b):void 0)||g,H=Th(N);$n(e);const V=(c=(o=(a=t.chain)==null?void 0:a.formatters)==null?void 0:o.transactionRequest)==null?void 0:c.format,U=(V||Es)({...ea(C,{format:V}),account:s,accessList:l,authorizationList:f,blobs:p,blobVersionedHashes:d,data:A,gasPrice:T,maxFeePerBlobGas:v,maxFeePerGas:w,maxPriorityFeePerGas:x,nonce:_,to:u,value:I},"estimateGas");return BigInt(await t.request({method:"eth_estimateGas",params:H?[U,M??t.experimental_blockTag??"latest",H]:M?[U,M]:[U]}))}catch(u){throw FS(u,{...e,account:s,chain:t.chain})}}async function Xg(t,e){const{abi:r,address:n,args:s,functionName:i,dataSuffix:a,...o}=e,c=or({abi:r,args:s,functionName:i});try{return await re(t,Fh,"estimateGas")({data:`${c}${a?a.replace("0x",""):""}`,to:n,...o})}catch(u){const l=o.account?Le(o.account):void 0;throw Ys(u,{abi:r,address:n,args:s,docsPath:"/docs/contract/estimateContractGas",functionName:i,sender:l==null?void 0:l.address})}}function ta(t,e){if(!ct(t,{strict:!1}))throw new $t({address:t});if(!ct(e,{strict:!1}))throw new $t({address:e});return t.toLowerCase()===e.toLowerCase()}const Rp="/docs/contract/decodeEventLog";function Bc(t){const{abi:e,data:r,strict:n,topics:s}=t,i=n??!0,[a,...o]=s;if(!a)throw new KE({docsPath:Rp});const c=e.find(S=>S.type==="event"&&a===ou(Rr(S)));if(!(c&&"name"in c)||c.type!=="event")throw new XE(a,{docsPath:Rp});const{name:u,inputs:l}=c,f=l==null?void 0:l.some(S=>!("name"in S&&S.name)),p=f?[]:{},d=l.map((S,T)=>[S,T]).filter(([S])=>"indexed"in S&&S.indexed),b=[];for(let S=0;S<d.length;S++){const[T,v]=d[S],w=o[S];if(!w){if(i)throw new hh({abiItem:c,param:T});b.push([T,v]);continue}p[f?v:T.name||v]=s8({param:T,value:w})}const g=l.filter(S=>!("indexed"in S&&S.indexed)),A=i?g:[...b.map(([S])=>S),...g];if(A.length>0){if(r&&r!=="0x")try{const S=Io(A,r);if(S){let T=0;if(!i)for(const[v,w]of b)p[f?w:v.name||w]=S[T++];if(f)for(let v=0;v<l.length;v++)p[v]===void 0&&T<S.length&&(p[v]=S[T++]);else for(let v=0;v<g.length;v++)p[g[v].name]=S[T++]}}catch(S){if(i)throw S instanceof Jb||S instanceof kg?new Oc({abiItem:c,data:r,params:A,size:Ge(r)}):S}else if(i)throw new Oc({abiItem:c,data:"0x",params:A,size:0})}return{eventName:u,args:Object.values(p).length>0?p:void 0}}function s8({param:t,value:e}){return t.type==="string"||t.type==="bytes"||t.type==="tuple"||t.type.match(/^(.*)\[(\d+)?\]$/)?e:(Io([t],e)||[])[0]}function Mh(t){const{abi:e,args:r,logs:n,strict:s=!0}=t,i=(()=>{if(t.eventName)return Array.isArray(t.eventName)?t.eventName:[t.eventName]})();return n.map(a=>{var l;const o=e.filter(f=>f.type==="event"&&a.topics[0]===ou(f));if(o.length===0)return null;let c,u;for(const f of o)try{c=Bc({...a,abi:[f],strict:!0}),u=f;break}catch{}if(!c&&!s){u=o[0];try{c=Bc({...a,abi:[u],strict:!1})}catch{const f=(l=u.inputs)==null?void 0:l.some(p=>!("name"in p&&p.name));return{...a,args:f?[]:{},eventName:u.name}}}return!c||!u||i&&!i.includes(c.eventName)||!i8({args:c.args,inputs:u.inputs,matchArgs:r})?null:{...c,...a}}).filter(Boolean)}function i8(t){const{args:e,inputs:r,matchArgs:n}=t;if(!n)return!0;if(!e)return!1;function s(i,a,o){try{return i.type==="address"?ta(a,o):i.type==="string"||i.type==="bytes"?bt(Zi(a))===o:a===o}catch{return!1}}return Array.isArray(e)&&Array.isArray(n)?n.every((i,a)=>{if(i==null)return!0;const o=r[a];return o?(Array.isArray(i)?i:[i]).some(u=>s(o,u,e[a])):!1}):typeof e=="object"&&!Array.isArray(e)&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).every(([i,a])=>{if(a==null)return!0;const o=r.find(u=>u.name===i);return o?(Array.isArray(a)?a:[a]).some(u=>s(o,u,e[i])):!1}):!1}function Nn(t,{args:e,eventName:r}={}){return{...t,blockHash:t.blockHash?t.blockHash:null,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,blockTimestamp:t.blockTimestamp?BigInt(t.blockTimestamp):t.blockTimestamp===null?null:void 0,logIndex:t.logIndex?Number(t.logIndex):null,transactionHash:t.transactionHash?t.transactionHash:null,transactionIndex:t.transactionIndex?Number(t.transactionIndex):null,...r?{args:e,eventName:r}:{}}}async function $h(t,{address:e,blockHash:r,fromBlock:n,toBlock:s,event:i,events:a,args:o,strict:c}={}){const u=c??!1,l=a??(i?[i]:void 0);let f=[];l&&(f=[l.flatMap(g=>_o({abi:[g],eventName:g.name,args:a?void 0:o}))],i&&(f=f[0]));let p;r?p=await t.request({method:"eth_getLogs",params:[{address:e,topics:f,blockHash:r}]}):p=await t.request({method:"eth_getLogs",params:[{address:e,topics:f,fromBlock:typeof n=="bigint"?Y(n):n,toBlock:typeof s=="bigint"?Y(s):s}]});const d=p.map(b=>Nn(b));return l?Mh({abi:l,args:o,logs:d,strict:u}):d}async function jh(t,e){const{abi:r,address:n,args:s,blockHash:i,eventName:a,fromBlock:o,toBlock:c,strict:u}=e,l=a?oi({abi:r,name:a}):void 0,f=l?void 0:r.filter(p=>p.type==="event");return re(t,$h,"getLogs")({address:n,args:s,blockHash:i,event:l,events:f,fromBlock:o,toBlock:c,strict:u})}const sl="/docs/contract/decodeFunctionResult";function ci(t){const{abi:e,args:r,functionName:n,data:s}=t;let i=e[0];if(n){const o=oi({abi:e,args:r,name:n});if(!o)throw new Di(n,{docsPath:sl});i=o}if(i.type!=="function")throw new Di(void 0,{docsPath:sl});if(!i.outputs)throw new Qb(i.name,{docsPath:sl});const a=Io(i.outputs,s);if(a&&a.length>1)return a;if(a&&a.length===1)return a[0]}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Hh=BigInt(0),yd=BigInt(1);function Ro(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Lh(t){if(!Ro(t))throw new Error("Uint8Array expected")}function ao(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function nc(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Yg(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Hh:BigInt("0x"+t)}const Jg=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",a8=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function oo(t){if(Lh(t),Jg)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=a8[t[r]];return e}const pn={_0:48,_9:57,A:65,F:70,a:97,f:102};function Np(t){if(t>=pn._0&&t<=pn._9)return t-pn._0;if(t>=pn.A&&t<=pn.F)return t-(pn.A-10);if(t>=pn.a&&t<=pn.f)return t-(pn.a-10)}function Cc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Jg)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let s=0,i=0;s<r;s++,i+=2){const a=Np(t.charCodeAt(i)),o=Np(t.charCodeAt(i+1));if(a===void 0||o===void 0){const c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[s]=a*16+o}return n}function Ds(t){return Yg(oo(t))}function Zg(t){return Lh(t),Yg(oo(Uint8Array.from(t).reverse()))}function No(t,e){return Cc(t.toString(16).padStart(e*2,"0"))}function Qg(t,e){return No(t,e).reverse()}function hr(t,e,r){let n;if(typeof e=="string")try{n=Cc(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(Ro(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=n.length;if(typeof r=="number"&&s!==r)throw new Error(t+" of length "+r+" expected, got "+s);return n}function Rc(...t){let e=0;for(let n=0;n<t.length;n++){const s=t[n];Lh(s),e+=s.length}const r=new Uint8Array(e);for(let n=0,s=0;n<t.length;n++){const i=t[n];r.set(i,s),s+=i.length}return r}const il=t=>typeof t=="bigint"&&Hh<=t;function Dh(t,e,r){return il(t)&&il(e)&&il(r)&&e<=t&&t<r}function Ni(t,e,r,n){if(!Dh(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function o8(t){let e;for(e=0;t>Hh;t>>=yd,e+=1);return e}const yu=t=>(yd<<BigInt(t))-yd,al=t=>new Uint8Array(t),Up=t=>Uint8Array.from(t);function c8(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=al(t),s=al(t),i=0;const a=()=>{n.fill(1),s.fill(0),i=0},o=(...f)=>r(s,n,...f),c=(f=al(0))=>{s=o(Up([0]),f),n=o(),f.length!==0&&(s=o(Up([1]),f),n=o())},u=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const p=[];for(;f<e;){n=o();const d=n.slice();p.push(d),f+=n.length}return Rc(...p)};return(f,p)=>{a(),c(f);let d;for(;!(d=p(u()));)c();return a(),d}}const u8={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||Ro(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function mu(t,e,r={}){const n=(s,i,a)=>{const o=u8[i];if(typeof o!="function")throw new Error("invalid validator function");const c=t[s];if(!(a&&c===void 0)&&!o(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+i+", got "+c)};for(const[s,i]of Object.entries(e))n(s,i,!1);for(const[s,i]of Object.entries(r))n(s,i,!0);return t}function Fp(t){const e=new WeakMap;return(r,...n)=>{const s=e.get(r);if(s!==void 0)return s;const i=t(r,...n);return e.set(r,i),i}}const l8="0.1.1";function f8(){return l8}class le extends Error{static setStaticOptions(e){le.prototype.docsOrigin=e.docsOrigin,le.prototype.showVersion=e.showVersion,le.prototype.version=e.version}constructor(e,r={}){const n=(()=>{var l;if(r.cause instanceof le){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:(l=r.cause)!=null&&l.message?r.cause.message:r.details})(),s=r.cause instanceof le&&r.cause.docsPath||r.docsPath,i=r.docsOrigin??le.prototype.docsOrigin,a=`${i}${s??""}`,o=!!(r.version??le.prototype.showVersion),c=r.version??le.prototype.version,u=[e||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||s||o?["",n?`Details: ${n}`:void 0,s?`See: ${a}`:void 0,o?`Version: ${c}`:void 0]:[]].filter(l=>typeof l=="string").join(`
66
- `);super(u,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsOrigin",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"showVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.cause=r.cause,this.details=n,this.docs=a,this.docsOrigin=i,this.docsPath=s,this.shortMessage=e,this.showVersion=o,this.version=c}walk(e){return e1(this,e)}}Object.defineProperty(le,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:"https://oxlib.sh",showVersion:!1,version:`ox@${f8()}`}});le.setStaticOptions(le.defaultStaticOptions);function e1(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?e1(t.cause,e):e?null:t}function Uo(t,e){if(ki(t)>e)throw new I8({givenSize:ki(t),maxSize:e})}const yn={zero:48,nine:57,A:65,F:70,a:97,f:102};function Mp(t){if(t>=yn.zero&&t<=yn.nine)return t-yn.zero;if(t>=yn.A&&t<=yn.F)return t-(yn.A-10);if(t>=yn.a&&t<=yn.f)return t-(yn.a-10)}function d8(t,e={}){const{dir:r,size:n=32}=e;if(n===0)return t;if(t.length>n)throw new P8({size:t.length,targetSize:n,type:"Bytes"});const s=new Uint8Array(n);for(let i=0;i<n;i++){const a=r==="right";s[a?i:n-i-1]=t[a?i:t.length-i-1]}return s}function t1(t,e={}){const{dir:r="left"}=e;let n=t,s=0;for(let i=0;i<n.length-1&&n[r==="left"?i:n.length-i-1].toString()==="0";i++)s++;return n=r==="left"?n.slice(s):n.slice(0,n.length-s),n}function bu(t,e){if(ir(t)>e)throw new U8({givenSize:ir(t),maxSize:e})}function h8(t,e){if(typeof e=="number"&&e>0&&e>ir(t)-1)throw new l1({offset:e,position:"start",size:ir(t)})}function p8(t,e,r){if(typeof e=="number"&&typeof r=="number"&&ir(t)!==r-e)throw new l1({offset:r,position:"end",size:ir(t)})}function r1(t,e={}){const{dir:r,size:n=32}=e;if(n===0)return t;const s=t.replace("0x","");if(s.length>n*2)throw new F8({size:Math.ceil(s.length/2),targetSize:n,type:"Hex"});return`0x${s[r==="right"?"padEnd":"padStart"](n*2,"0")}`}const y8="#__bigint";function n1(t,e,r){return JSON.stringify(t,(n,s)=>typeof s=="bigint"?s.toString()+y8:s,r)}const m8=new TextDecoder,b8=new TextEncoder;function g8(t){return t instanceof Uint8Array?t:typeof t=="string"?s1(t):w8(t)}function w8(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function s1(t,e={}){const{size:r}=e;let n=t;r&&(bu(t,r),n=Qs(t,r));let s=n.slice(2);s.length%2&&(s=`0${s}`);const i=s.length/2,a=new Uint8Array(i);for(let o=0,c=0;o<i;o++){const u=Mp(s.charCodeAt(c++)),l=Mp(s.charCodeAt(c++));if(u===void 0||l===void 0)throw new le(`Invalid byte sequence ("${s[c-2]}${s[c-1]}" in "${s}").`);a[o]=u<<4|l}return a}function v8(t,e={}){const{size:r}=e,n=b8.encode(t);return typeof r=="number"?(Uo(n,r),E8(n,r)):n}function E8(t,e){return d8(t,{dir:"right",size:e})}function ki(t){return t.length}function A8(t,e,r,n={}){const{strict:s}=n;return t.slice(e,r)}function S8(t,e={}){const{size:r}=e;typeof r<"u"&&Uo(t,r);const n=Fr(t,e);return o1(n,e)}function x8(t,e={}){const{size:r}=e;let n=t;if(typeof r<"u"&&(Uo(n,r),n=i1(n)),n.length>1||n[0]>1)throw new _8(n);return!!n[0]}function On(t,e={}){const{size:r}=e;typeof r<"u"&&Uo(t,r);const n=Fr(t,e);return c1(n,e)}function k8(t,e={}){const{size:r}=e;let n=t;return typeof r<"u"&&(Uo(n,r),n=T8(n)),m8.decode(n)}function i1(t){return t1(t,{dir:"left"})}function T8(t){return t1(t,{dir:"right"})}class _8 extends le{constructor(e){super(`Bytes value \`${e}\` is not a valid boolean.`,{metaMessages:["The bytes array must contain a single byte of either a `0` or `1` value."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesBooleanError"})}}let I8=class extends le{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}},P8=class extends le{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}};const O8=new TextEncoder,B8=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function C8(t,e={}){const{strict:r=!1}=e;if(!t)throw new $p(t);if(typeof t!="string")throw new $p(t);if(r&&!/^0x[0-9a-fA-F]*$/.test(t))throw new jp(t);if(!t.startsWith("0x"))throw new jp(t)}function Ur(...t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function R8(t){return t instanceof Uint8Array?Fr(t):Array.isArray(t)?Fr(new Uint8Array(t)):t}function a1(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(bu(r,e.size),Zs(r,e.size)):r}function Fr(t,e={}){let r="";for(let s=0;s<t.length;s++)r+=B8[t[s]];const n=`0x${r}`;return typeof e.size=="number"?(bu(n,e.size),Qs(n,e.size)):n}function Ut(t,e={}){const{signed:r,size:n}=e,s=BigInt(t);let i;n?r?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const a=typeof i=="bigint"&&r?-i-1n:0;if(i&&s>i||s<a){const u=typeof t=="bigint"?"n":"";throw new u1({max:i?`${i}${u}`:void 0,min:`${a}${u}`,signed:r,size:n,value:`${t}${u}`})}const c=`0x${(r&&s<0?BigInt.asUintN(n*8,BigInt(s)):s).toString(16)}`;return n?Zs(c,n):c}function zh(t,e={}){return Fr(O8.encode(t),e)}function Zs(t,e){return r1(t,{dir:"left",size:e})}function Qs(t,e){return r1(t,{dir:"right",size:e})}function rn(t,e,r,n={}){const{strict:s}=n;h8(t,e);const i=`0x${t.replace("0x","").slice((e??0)*2,(r??t.length)*2)}`;return s&&p8(i,e,r),i}function ir(t){return Math.ceil((t.length-2)/2)}function o1(t,e={}){const{signed:r}=e;e.size&&bu(t,e.size);const n=BigInt(t);if(!r)return n;const s=(t.length-2)/2,i=(1n<<BigInt(s)*8n)-1n,a=i>>1n;return n<=a?n:n-i-1n}function c1(t,e={}){const{signed:r,size:n}=e;return Number(!r&&!n?t:o1(t,e))}function N8(t,e={}){const{strict:r=!1}=e;try{return C8(t,{strict:r}),!0}catch{return!1}}class u1 extends le{constructor({max:e,min:r,signed:n,size:s,value:i}){super(`Number \`${i}\` is not in safe${s?` ${s*8}-bit`:""}${n?" signed":" unsigned"} integer range ${e?`(\`${r}\` to \`${e}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class $p extends le{constructor(e){super(`Value \`${typeof e=="object"?n1(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class jp extends le{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}class U8 extends le{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class l1 extends le{constructor({offset:e,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}class F8 extends le{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}function M8(t){return{address:t.address,amount:Ut(t.amount),index:Ut(t.index),validatorIndex:Ut(t.validatorIndex)}}function f1(t){return{...typeof t.baseFeePerGas=="bigint"&&{baseFeePerGas:Ut(t.baseFeePerGas)},...typeof t.blobBaseFee=="bigint"&&{blobBaseFee:Ut(t.blobBaseFee)},...typeof t.feeRecipient=="string"&&{feeRecipient:t.feeRecipient},...typeof t.gasLimit=="bigint"&&{gasLimit:Ut(t.gasLimit)},...typeof t.number=="bigint"&&{number:Ut(t.number)},...typeof t.prevRandao=="bigint"&&{prevRandao:Ut(t.prevRandao)},...typeof t.time=="bigint"&&{time:Ut(t.time)},...t.withdrawals&&{withdrawals:t.withdrawals.map(M8)}}}const Nc=[{inputs:[{components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}],name:"calls",type:"tuple[]"}],name:"aggregate3",outputs:[{components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}],name:"returnData",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"}],md=[{name:"query",type:"function",stateMutability:"view",inputs:[{type:"tuple[]",name:"queries",components:[{type:"address",name:"sender"},{type:"string[]",name:"urls"},{type:"bytes",name:"data"}]}],outputs:[{type:"bool[]",name:"failures"},{type:"bytes[]",name:"responses"}]},{name:"HttpError",type:"error",inputs:[{type:"uint16",name:"status"},{type:"string",name:"message"}]}],d1=[{inputs:[{name:"dns",type:"bytes"}],name:"DNSDecodingFailed",type:"error"},{inputs:[{name:"ens",type:"string"}],name:"DNSEncodingFailed",type:"error"},{inputs:[],name:"EmptyAddress",type:"error"},{inputs:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"HttpError",type:"error"},{inputs:[],name:"InvalidBatchGatewayResponse",type:"error"},{inputs:[{name:"errorData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{name:"name",type:"bytes"},{name:"resolver",type:"address"}],name:"ResolverNotContract",type:"error"},{inputs:[{name:"name",type:"bytes"}],name:"ResolverNotFound",type:"error"},{inputs:[{name:"primary",type:"string"},{name:"primaryAddress",type:"bytes"}],name:"ReverseAddressMismatch",type:"error"},{inputs:[{internalType:"bytes4",name:"selector",type:"bytes4"}],name:"UnsupportedResolverProfile",type:"error"}],h1=[...d1,{name:"resolveWithGateways",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"},{name:"gateways",type:"string[]"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]}],$8=[...d1,{name:"reverseWithGateways",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"uint256",name:"coinType"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolver"},{type:"address",name:"reverseResolver"}]}],Hp=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],Lp=[{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"}],outputs:[{name:"",type:"address"}]},{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"coinType",type:"uint256"}],outputs:[{name:"",type:"bytes"}]}],p1=[{name:"isValidSignature",type:"function",stateMutability:"view",inputs:[{name:"hash",type:"bytes32"},{name:"signature",type:"bytes"}],outputs:[{name:"",type:"bytes4"}]}],Dp=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}],j8="0x82ad56cb",y1="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",H8="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",L8="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",Vh="0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033";class bd extends G{constructor({blockNumber:e,chain:r,contract:n}){super(`Chain "${r.name}" does not support contract "${n.name}".`,{metaMessages:["This could be due to any of the following:",...e&&n.blockCreated&&n.blockCreated>e?[`- The contract "${n.name}" was not deployed until block ${n.blockCreated} (current block ${e}).`]:[`- The chain does not have the contract "${n.name}" configured.`]],name:"ChainDoesNotSupportContract"})}}class D8 extends G{constructor({chain:e,currentChainId:r}){super(`The current chain of the wallet (id: ${r}) does not match the target chain for the transaction (id: ${e.id} – ${e.name}).`,{metaMessages:[`Current Chain ID: ${r}`,`Expected Chain ID: ${e.id} – ${e.name}`],name:"ChainMismatchError"})}}class z8 extends G{constructor(){super(["No chain was provided to the request.","Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient."].join(`
67
- `),{name:"ChainNotFoundError"})}}class m1 extends G{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}class gu extends G{constructor({chainId:e}){super(typeof e=="number"?`Chain ID "${e}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}const ol="/docs/contract/encodeDeployData";function wu(t){const{abi:e,args:r,bytecode:n}=t;if(!r||r.length===0)return n;const s=e.find(a=>"type"in a&&a.type==="constructor");if(!s)throw new zE({docsPath:ol});if(!("inputs"in s))throw new hp({docsPath:ol});if(!s.inputs||s.inputs.length===0)throw new hp({docsPath:ol});const i=vs(s.inputs,r);return jr([n,i])}function ra({blockNumber:t,chain:e,contract:r}){var s;const n=(s=e==null?void 0:e.contracts)==null?void 0:s[r];if(!n)throw new bd({chain:e,contract:{name:r}});if(t&&n.blockCreated&&n.blockCreated>t)throw new bd({blockNumber:t,chain:e,contract:{name:r,blockCreated:n.blockCreated}});return n.address}function b1(t,{docsPath:e,...r}){const n=(()=>{const s=du(t,r);return s instanceof Oo?t:s})();return new Cg(n,{docsPath:e,...r})}function Gh(){let t=()=>{},e=()=>{};return{promise:new Promise((n,s)=>{t=n,e=s}),resolve:t,reject:e}}const cl=new Map;function g1({fn:t,id:e,shouldSplitBatch:r,wait:n=0,sort:s}){const i=async()=>{const l=c();a();const f=l.map(({args:p})=>p);f.length!==0&&t(f).then(p=>{s&&Array.isArray(p)&&p.sort(s);for(let d=0;d<l.length;d++){const{resolve:b}=l[d];b==null||b([p[d],p])}}).catch(p=>{for(let d=0;d<l.length;d++){const{reject:b}=l[d];b==null||b(p)}})},a=()=>cl.delete(e),o=()=>c().map(({args:l})=>l),c=()=>cl.get(e)||[],u=l=>cl.set(e,[...c(),l]);return{flush:a,async schedule(l){const{promise:f,resolve:p,reject:d}=Gh();return(r==null?void 0:r([...o(),l]))&&i(),c().length>0?(u({args:l,resolve:p,reject:d}),f):(u({args:l,resolve:p,reject:d}),setTimeout(i,n),f)}}}async function Fo(t,e){var V,Q,U,K;const{account:r=t.account,authorizationList:n,batch:s=!!((V=t.batch)!=null&&V.multicall),blockNumber:i,blockTag:a=t.experimental_blockTag??"latest",accessList:o,blobs:c,blockOverrides:u,code:l,data:f,factory:p,factoryData:d,gas:b,gasPrice:g,maxFeePerBlobGas:A,maxFeePerGas:S,maxPriorityFeePerGas:T,nonce:v,to:w,value:x,stateOverride:_,...I}=e,N=r?Le(r):void 0;if(l&&(p||d))throw new G("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(l&&w)throw new G("Cannot provide both `code` & `to` as parameters.");const C=l&&f,j=p&&d&&w&&f,M=C||j,H=C?w1({code:l,data:f}):j?q8({data:f,factory:p,factoryData:d,to:w}):f;try{$n(e);const q=(typeof i=="bigint"?Y(i):void 0)||a,O=u?f1(u):void 0,L=Th(_),J=(K=(U=(Q=t.chain)==null?void 0:Q.formatters)==null?void 0:U.transactionRequest)==null?void 0:K.format,F=(J||Es)({...ea(I,{format:J}),accessList:o,account:N,authorizationList:n,blobs:c,data:H,gas:b,gasPrice:g,maxFeePerBlobGas:A,maxFeePerGas:S,maxPriorityFeePerGas:T,nonce:v,to:M?void 0:w,value:x},"call");if(s&&V8({request:F})&&!L&&!O)try{return await G8(t,{...F,blockNumber:i,blockTag:a})}catch(ae){if(!(ae instanceof m1)&&!(ae instanceof bd))throw ae}const z=(()=>{const ae=[F,q];return L&&O?[...ae,L,O]:L?[...ae,L]:O?[...ae,{},O]:ae})(),ne=await t.request({method:"eth_call",params:z});return ne==="0x"?{data:void 0}:{data:ne}}catch(ee){const q=W8(ee),{offchainLookup:O,offchainLookupSignature:L}=await Promise.resolve().then(()=>require("./ccip-BMAGhn8q.cjs"));if(t.ccipRead!==!1&&(q==null?void 0:q.slice(0,10))===L&&w)return{data:await O(t,{data:q,to:w})};throw M&&(q==null?void 0:q.slice(0,10))==="0x101bb98d"?new TS({factory:p}):b1(ee,{...e,account:N,chain:t.chain})}}function V8({request:t}){const{data:e,to:r,...n}=t;return!(!e||e.startsWith(j8)||!r||Object.values(n).filter(s=>typeof s<"u").length>0)}async function G8(t,e){var g;const{batchSize:r=1024,deployless:n=!1,wait:s=0}=typeof((g=t.batch)==null?void 0:g.multicall)=="object"?t.batch.multicall:{},{blockNumber:i,blockTag:a=t.experimental_blockTag??"latest",data:o,to:c}=e,u=(()=>{if(n)return null;if(e.multicallAddress)return e.multicallAddress;if(t.chain)return ra({blockNumber:i,chain:t.chain,contract:"multicall3"});throw new m1})(),f=(typeof i=="bigint"?Y(i):void 0)||a,{schedule:p}=g1({id:`${t.uid}.${f}`,wait:s,shouldSplitBatch(A){return A.reduce((T,{data:v})=>T+(v.length-2),0)>r*2},fn:async A=>{const S=A.map(w=>({allowFailure:!0,callData:w.data,target:w.to})),T=or({abi:Nc,args:[S],functionName:"aggregate3"}),v=await t.request({method:"eth_call",params:[{...u===null?{data:w1({code:Vh,data:T})}:{to:u,data:T}},f]});return ci({abi:Nc,args:[S],functionName:"aggregate3",data:v||"0x"})}}),[{returnData:d,success:b}]=await p({data:o,to:c});if(!b)throw new lu({data:d});return d==="0x"?{data:void 0}:{data:d}}function w1(t){const{code:e,data:r}=t;return wu({abi:Kb(["constructor(bytes, bytes)"]),bytecode:y1,args:[e,r]})}function q8(t){const{data:e,factory:r,factoryData:n,to:s}=t;return wu({abi:Kb(["constructor(address, bytes, address, bytes)"]),bytecode:H8,args:[s,e,r,n]})}function W8(t){var r;if(!(t instanceof G))return;const e=t.walk();return typeof(e==null?void 0:e.data)=="object"?(r=e.data)==null?void 0:r.data:e.data}async function wr(t,e){const{abi:r,address:n,args:s,functionName:i,...a}=e,o=or({abi:r,args:s,functionName:i});try{const{data:c}=await re(t,Fo,"call")({...a,data:o,to:n});return ci({abi:r,args:s,functionName:i,data:c||"0x"})}catch(c){throw Ys(c,{abi:r,address:n,args:s,docsPath:"/docs/contract/readContract",functionName:i})}}async function v1(t,e){const{abi:r,address:n,args:s,dataSuffix:i,functionName:a,...o}=e,c=o.account?Le(o.account):t.account,u=or({abi:r,args:s,functionName:a});try{const{data:l}=await re(t,Fo,"call")({batch:!1,data:`${u}${i?i.replace("0x",""):""}`,to:n,...o,account:c}),f=ci({abi:r,args:s,functionName:a,data:l||"0x"}),p=r.filter(d=>"name"in d&&d.name===e.functionName);return{result:f,request:{abi:p,address:n,args:s,dataSuffix:i,functionName:a,...o,account:c}}}catch(l){throw Ys(l,{abi:r,address:n,args:s,docsPath:"/docs/contract/simulateContract",functionName:a,sender:c==null?void 0:c.address})}}const ul=new Map,zp=new Map;let K8=0;function Un(t,e,r){const n=++K8,s=()=>ul.get(t)||[],i=()=>{const l=s();ul.set(t,l.filter(f=>f.id!==n))},a=()=>{const l=s();if(!l.some(p=>p.id===n))return;const f=zp.get(t);if(l.length===1&&f){const p=f();p instanceof Promise&&p.catch(()=>{})}i()},o=s();if(ul.set(t,[...o,{id:n,fns:e}]),o&&o.length>0)return a;const c={};for(const l in e)c[l]=(...f)=>{var d,b;const p=s();if(p.length!==0)for(const g of p)(b=(d=g.fns)[l])==null||b.call(d,...f)};const u=r(c);return typeof u=="function"&&zp.set(t,u),a}async function gd(t){return new Promise(e=>setTimeout(e,t))}function na(t,{emitOnBegin:e,initialWaitTime:r,interval:n}){let s=!0;const i=()=>s=!1;return(async()=>{let o;e&&(o=await t({unpoll:i}));const c=await(r==null?void 0:r(o))??n;await gd(c);const u=async()=>{s&&(await t({unpoll:i}),await gd(n),u())};u()})(),i}const X8=new Map,Y8=new Map;function J8(t){const e=(s,i)=>({clear:()=>i.delete(s),get:()=>i.get(s),set:a=>i.set(s,a)}),r=e(t,X8),n=e(t,Y8);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function Z8(t,{cacheKey:e,cacheTime:r=Number.POSITIVE_INFINITY}){const n=J8(e),s=n.response.get();if(s&&r>0&&Date.now()-s.created.getTime()<r)return s.data;let i=n.promise.get();i||(i=t(),n.promise.set(i));try{const a=await i;return n.response.set({created:new Date,data:a}),a}finally{n.promise.clear()}}const Q8=t=>`blockNumber.${t}`;async function Mo(t,{cacheTime:e=t.cacheTime}={}){const r=await Z8(()=>t.request({method:"eth_blockNumber"}),{cacheKey:Q8(t.uid),cacheTime:e});return BigInt(r)}async function vu(t,{filter:e}){const r="strict"in e&&e.strict,n=await e.request({method:"eth_getFilterChanges",params:[e.id]});if(typeof n[0]=="string")return n;const s=n.map(i=>Nn(i));return!("abi"in e)||!e.abi?s:Mh({abi:e.abi,logs:s,strict:r})}async function Eu(t,{filter:e}){return e.request({method:"eth_uninstallFilter",params:[e.id]})}function E1(t,e){const{abi:r,address:n,args:s,batch:i=!0,eventName:a,fromBlock:o,onError:c,onLogs:u,poll:l,pollingInterval:f=t.pollingInterval,strict:p}=e;return(typeof l<"u"?l:typeof o=="bigint"?!0:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc")))?(()=>{const A=p??!1,S=et(["watchContractEvent",n,s,i,t.uid,a,f,A,o]);return Un(S,{onLogs:u,onError:c},T=>{let v;o!==void 0&&(v=o-1n);let w,x=!1;const _=na(async()=>{var I;if(!x){try{w=await re(t,Eh,"createContractEventFilter")({abi:r,address:n,args:s,eventName:a,strict:A,fromBlock:o})}catch{}x=!0;return}try{let N;if(w)N=await re(t,vu,"getFilterChanges")({filter:w});else{const C=await re(t,Mo,"getBlockNumber")({});v&&v<C?N=await re(t,jh,"getContractEvents")({abi:r,address:n,args:s,eventName:a,fromBlock:v+1n,toBlock:C,strict:A}):N=[],v=C}if(N.length===0)return;if(i)T.onLogs(N);else for(const C of N)T.onLogs([C])}catch(N){w&&N instanceof ms&&(x=!1),(I=T.onError)==null||I.call(T,N)}},{emitOnBegin:!0,interval:f});return async()=>{w&&await re(t,Eu,"uninstallFilter")({filter:w}),_()}})})():(()=>{const A=p??!1,S=et(["watchContractEvent",n,s,i,t.uid,a,f,A]);let T=!0,v=()=>T=!1;return Un(S,{onLogs:u,onError:c},w=>((async()=>{try{const x=(()=>{if(t.transport.type==="fallback"){const N=t.transport.transports.find(C=>C.config.type==="webSocket"||C.config.type==="ipc");return N?N.value:t.transport}return t.transport})(),_=a?_o({abi:r,eventName:a,args:s}):[],{unsubscribe:I}=await x.subscribe({params:["logs",{address:n,topics:_}],onData(N){var j;if(!T)return;const C=N.result;try{const{eventName:M,args:H}=Bc({abi:r,data:C.data,topics:C.topics,strict:p}),V=Nn(C,{args:H,eventName:M});w.onLogs([V])}catch(M){let H,V;if(M instanceof Oc||M instanceof hh){if(p)return;H=M.abiItem.name,V=(j=M.abiItem.inputs)==null?void 0:j.some(U=>!("name"in U&&U.name))}const Q=Nn(C,{args:V?[]:{},eventName:H});w.onLogs([Q])}},onError(N){var C;(C=w.onError)==null||C.call(w,N)}});v=I,T||v()}catch(x){c==null||c(x)}})(),()=>v()))})()}class Ss extends G{constructor({docsPath:e}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(`
68
- `),{docsPath:e,docsSlug:"account",name:"AccountNotFoundError"})}}class zs extends G{constructor({docsPath:e,metaMessages:r,type:n}){super(`Account type "${n}" is not supported.`,{docsPath:e,metaMessages:r,name:"AccountTypeNotSupportedError"})}}function qh({chain:t,currentChainId:e}){if(!t)throw new z8;if(e!==t.id)throw new D8({chain:t,currentChainId:e})}async function Wh(t,{serializedTransaction:e}){return t.request({method:"eth_sendRawTransaction",params:[e]},{retryCount:0})}const ll=new Qi(128);async function Au(t,e){var v,w,x,_;const{account:r=t.account,assertChainId:n=!0,chain:s=t.chain,accessList:i,authorizationList:a,blobs:o,data:c,gas:u,gasPrice:l,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:d,nonce:b,type:g,value:A,...S}=e;if(typeof r>"u")throw new Ss({docsPath:"/docs/actions/wallet/sendTransaction"});const T=r?Le(r):null;try{$n(e);const I=await(async()=>{if(e.to)return e.to;if(e.to!==null&&a&&a.length>0)return await fu({authorization:a[0]}).catch(()=>{throw new G("`to` is required. Could not infer from `authorizationList`.")})})();if((T==null?void 0:T.type)==="json-rpc"||T===null){let N;s!==null&&(N=await re(t,As,"getChainId")({}),n&&qh({currentChainId:N,chain:s}));const C=(x=(w=(v=t.chain)==null?void 0:v.formatters)==null?void 0:w.transactionRequest)==null?void 0:x.format,M=(C||Es)({...ea(S,{format:C}),accessList:i,account:T,authorizationList:a,blobs:o,chainId:N,data:c,gas:u,gasPrice:l,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:d,nonce:b,to:I,type:g,value:A},"sendTransaction"),H=ll.get(t.uid),V=H?"wallet_sendTransaction":"eth_sendTransaction";try{return await t.request({method:V,params:[M]},{retryCount:0})}catch(Q){if(H===!1)throw Q;const U=Q;if(U.name==="InvalidInputRpcError"||U.name==="InvalidParamsRpcError"||U.name==="MethodNotFoundRpcError"||U.name==="MethodNotSupportedRpcError")return await t.request({method:"wallet_sendTransaction",params:[M]},{retryCount:0}).then(K=>(ll.set(t.uid,!0),K)).catch(K=>{const ee=K;throw ee.name==="MethodNotFoundRpcError"||ee.name==="MethodNotSupportedRpcError"?(ll.set(t.uid,!1),U):ee});throw U}}if((T==null?void 0:T.type)==="local"){const N=await re(t,Co,"prepareTransactionRequest")({account:T,accessList:i,authorizationList:a,blobs:o,chain:s,data:c,gas:u,gasPrice:l,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:d,nonce:b,nonceManager:T.nonceManager,parameters:[...Uh,"sidecars"],type:g,value:A,...S,to:I}),C=(_=s==null?void 0:s.serializers)==null?void 0:_.transaction,j=await T.signTransaction(N,{serializer:C});return await re(t,Wh,"sendRawTransaction")({serializedTransaction:j})}throw(T==null?void 0:T.type)==="smart"?new zs({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new zs({docsPath:"/docs/actions/wallet/sendTransaction",type:T==null?void 0:T.type})}catch(I){throw I instanceof zs?I:pu(I,{...e,account:T,chain:e.chain||void 0})}}async function Wi(t,e){return Wi.internal(t,Au,"sendTransaction",e)}(function(t){async function e(r,n,s,i){const{abi:a,account:o=r.account,address:c,args:u,dataSuffix:l,functionName:f,...p}=i;if(typeof o>"u")throw new Ss({docsPath:"/docs/contract/writeContract"});const d=o?Le(o):null,b=or({abi:a,args:u,functionName:f});try{return await re(r,n,s)({data:`${b}${l?l.replace("0x",""):""}`,to:c,account:d,...p})}catch(g){throw Ys(g,{abi:a,address:c,args:u,docsPath:"/docs/contract/writeContract",functionName:f,sender:d==null?void 0:d.address})}}t.internal=e})(Wi||(Wi={}));function Kh({abi:t,address:e,client:r}){const n=r,[s,i]=n?"public"in n&&"wallet"in n?[n.public,n.wallet]:"public"in n?[n.public,void 0]:"wallet"in n?[void 0,n.wallet]:[n,n]:[void 0,void 0],a=s!=null,o=i!=null,c={};let u=!1,l=!1,f=!1;for(const p of t)if(p.type==="function"?p.stateMutability==="view"||p.stateMutability==="pure"?u=!0:l=!0:p.type==="event"&&(f=!0),u&&l&&f)break;return a&&(u&&(c.read=new Proxy({},{get(p,d){return(...b)=>{const{args:g,options:A}=sc(b);return re(s,wr,"readContract")({abi:t,address:e,functionName:d,args:g,...A})}}})),l&&(c.simulate=new Proxy({},{get(p,d){return(...b)=>{const{args:g,options:A}=sc(b);return re(s,v1,"simulateContract")({abi:t,address:e,functionName:d,args:g,...A})}}})),f&&(c.createEventFilter=new Proxy({},{get(p,d){return(...b)=>{const g=t.find(T=>T.type==="event"&&T.name===d),{args:A,options:S}=fl(b,g);return re(s,Eh,"createContractEventFilter")({abi:t,address:e,eventName:d,args:A,...S})}}}),c.getEvents=new Proxy({},{get(p,d){return(...b)=>{const g=t.find(T=>T.type==="event"&&T.name===d),{args:A,options:S}=fl(b,g);return re(s,jh,"getContractEvents")({abi:t,address:e,eventName:d,args:A,...S})}}}),c.watchEvent=new Proxy({},{get(p,d){return(...b)=>{const g=t.find(T=>T.type==="event"&&T.name===d),{args:A,options:S}=fl(b,g);return re(s,E1,"watchContractEvent")({abi:t,address:e,eventName:d,args:A,...S})}}}))),o&&l&&(c.write=new Proxy({},{get(p,d){return(...b)=>{const{args:g,options:A}=sc(b);return re(i,Wi,"writeContract")({abi:t,address:e,functionName:d,args:g,...A})}}})),(a||o)&&l&&(c.estimateGas=new Proxy({},{get(p,d){return(...b)=>{const{args:g,options:A}=sc(b);return re(s??i,Xg,"estimateContractGas")({abi:t,address:e,functionName:d,args:g,...A,account:A.account??i.account})}}})),c.address=e,c.abi=t,c}function sc(t){const e=t.length&&Array.isArray(t[0]),r=e?t[0]:[],n=(e?t[1]:t[0])??{};return{args:r,options:n}}function fl(t,e){let r=!1;Array.isArray(t[0])?r=!0:t.length===1?r=e.inputs.some(i=>i.indexed):t.length===2&&(r=!0);const n=r?t[0]:void 0,s=(r?t[1]:t[0])??{};return{args:n,options:s}}class ex extends G{constructor(e){super(`Call bundle failed with status: ${e.statusCode}`,{name:"BundleFailedError"}),Object.defineProperty(this,"result",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.result=e}}function Uc(t,{delay:e=100,retryCount:r=2,shouldRetry:n=()=>!0}={}){return new Promise((s,i)=>{const a=async({count:o=0}={})=>{const c=async({error:u})=>{const l=typeof e=="function"?e({count:o,error:u}):e;l&&await gd(l),a({count:o+1})};try{const u=await t();s(u)}catch(u){if(o<r&&await n({count:o,error:u}))return c({error:u});i(u)}};a()})}const A1={"0x0":"reverted","0x1":"success"};function Xh(t,e){const r={...t,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,contractAddress:t.contractAddress?t.contractAddress:null,cumulativeGasUsed:t.cumulativeGasUsed?BigInt(t.cumulativeGasUsed):null,effectiveGasPrice:t.effectiveGasPrice?BigInt(t.effectiveGasPrice):null,gasUsed:t.gasUsed?BigInt(t.gasUsed):null,logs:t.logs?t.logs.map(n=>Nn(n)):null,to:t.to?t.to:null,transactionIndex:t.transactionIndex?gr(t.transactionIndex):null,status:t.status?A1[t.status]:null,type:t.type?jg[t.type]||t.type:null};return t.blobGasPrice&&(r.blobGasPrice=BigInt(t.blobGasPrice)),t.blobGasUsed&&(r.blobGasUsed=BigInt(t.blobGasUsed)),r}const tx=kh("transactionReceipt",Xh),S1="0x5792579257925792579257925792579257925792579257925792579257925792",x1=Y(0,{size:32});async function k1(t,e){const{account:r=t.account,capabilities:n,chain:s=t.chain,experimental_fallback:i,experimental_fallbackDelay:a=32,forceAtomic:o=!1,id:c,version:u="2.0.0"}=e,l=r?Le(r):null,f=e.calls.map(p=>{const d=p,b=d.abi?or({abi:d.abi,functionName:d.functionName,args:d.args}):d.data;return{data:d.dataSuffix&&b?sr([b,d.dataSuffix]):b,to:d.to,value:d.value?Y(d.value):void 0}});try{const p=await t.request({method:"wallet_sendCalls",params:[{atomicRequired:o,calls:f,capabilities:n,chainId:Y(s.id),from:l==null?void 0:l.address,id:c,version:u}]},{retryCount:0});return typeof p=="string"?{id:p}:p}catch(p){const d=p;if(i&&(d.name==="MethodNotFoundRpcError"||d.name==="MethodNotSupportedRpcError"||d.name==="UnknownRpcError"||d.details.toLowerCase().includes("does not exist / is not available")||d.details.toLowerCase().includes("missing or invalid. request()")||d.details.toLowerCase().includes("did not match any variant of untagged enum")||d.details.toLowerCase().includes("account upgraded to unsupported contract")||d.details.toLowerCase().includes("eip-7702 not supported")||d.details.toLowerCase().includes("unsupported wc_ method")||d.details.toLowerCase().includes("feature toggled misconfigured")||d.details.toLowerCase().includes("jsonrpcengine: response has no error or result for request"))){if(n&&Object.values(n).some(T=>!T.optional)){const T="non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";throw new Gi(new G(T,{details:T}))}if(o&&f.length>1){const S="`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";throw new qi(new G(S,{details:S}))}const b=[];for(const S of f){const T=Au(t,{account:l,chain:s,data:S.data,to:S.to,value:S.value?lt(S.value):void 0});b.push(T),a>0&&await new Promise(v=>setTimeout(v,a))}const g=await Promise.allSettled(b);if(g.every(S=>S.status==="rejected"))throw g[0].reason;const A=g.map(S=>S.status==="fulfilled"?S.value:x1);return{id:sr([...A,Y(s.id,{size:32}),S1])}}throw pu(p,{...e,account:l,chain:e.chain})}}async function T1(t,e){async function r(l){if(l.endsWith(S1.slice(2))){const p=br(rd(l,-64,-32)),d=rd(l,0,-64).slice(2).match(/.{1,64}/g),b=await Promise.all(d.map(A=>x1.slice(2)!==A?t.request({method:"eth_getTransactionReceipt",params:[`0x${A}`]},{dedupe:!0}):void 0)),g=b.some(A=>A===null)?100:b.every(A=>(A==null?void 0:A.status)==="0x1")?200:b.every(A=>(A==null?void 0:A.status)==="0x0")?500:600;return{atomic:!1,chainId:gr(p),receipts:b.filter(Boolean),status:g,version:"2.0.0"}}return t.request({method:"wallet_getCallsStatus",params:[l]})}const{atomic:n=!1,chainId:s,receipts:i,version:a="2.0.0",...o}=await r(e.id),[c,u]=(()=>{const l=o.status;return l>=100&&l<200?["pending",l]:l>=200&&l<300?["success",l]:l>=300&&l<700?["failure",l]:l==="CONFIRMED"?["success",200]:l==="PENDING"?["pending",100]:[void 0,l]})();return{...o,atomic:n,chainId:s?gr(s):void 0,receipts:(i==null?void 0:i.map(l=>({...l,blockNumber:lt(l.blockNumber),gasUsed:lt(l.gasUsed),status:A1[l.status]})))??[],statusCode:u,status:c,version:a}}async function _1(t,e){const{id:r,pollingInterval:n=t.pollingInterval,status:s=({statusCode:g})=>g===200||g>=300,retryCount:i=4,retryDelay:a=({count:g})=>~~(1<<g)*200,timeout:o=6e4,throwOnFailure:c=!1}=e,u=et(["waitForCallsStatus",t.uid,r]),{promise:l,resolve:f,reject:p}=Gh();let d;const b=Un(u,{resolve:f,reject:p},g=>{const A=na(async()=>{const S=T=>{clearTimeout(d),A(),T(),b()};try{const T=await Uc(async()=>{const v=await re(t,T1,"getCallsStatus")({id:r});if(c&&v.status==="failure")throw new ex(v);return v},{retryCount:i,delay:a});if(!s(T))return;S(()=>g.resolve(T))}catch(T){S(()=>g.reject(T))}},{interval:n,emitOnBegin:!0});return A});return d=o?setTimeout(()=>{b(),clearTimeout(d),p(new rx({id:r}))},o):void 0,await l}class rx extends G{constructor({id:e}){super(`Timed out while waiting for call bundle with id "${e}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}const wd=256;let ic=wd,ac;function I1(t=11){if(!ac||ic+t>wd*2){ac="",ic=0;for(let e=0;e<wd;e++)ac+=(256+Math.random()*256|0).toString(16).substring(1)}return ac.substring(ic,ic+++t)}function P1(t){const{batch:e,chain:r,ccipRead:n,key:s="base",name:i="Base Client",type:a="base"}=t,o=t.experimental_blockTag??(typeof(r==null?void 0:r.experimental_preconfirmationTime)=="number"?"pending":void 0),c=(r==null?void 0:r.blockTime)??12e3,u=Math.min(Math.max(Math.floor(c/2),500),4e3),l=t.pollingInterval??u,f=t.cacheTime??l,p=t.account?Le(t.account):void 0,{config:d,request:b,value:g}=t.transport({account:p,chain:r,pollingInterval:l}),A={...d,...g},S={account:p,batch:e,cacheTime:f,ccipRead:n,chain:r,key:s,name:i,pollingInterval:l,request:b,transport:A,type:a,uid:I1(),...o?{experimental_blockTag:o}:{}};function T(v){return w=>{const x=w(v);for(const I in S)delete x[I];const _={...v,...x};return Object.assign(_,{extend:T(_)})}}return Object.assign(S,{extend:T(S)})}function Yh(t){var r,n,s,i,a,o;if(!(t instanceof G))return!1;const e=t.walk(c=>c instanceof id);return e instanceof id?((r=e.data)==null?void 0:r.errorName)==="HttpError"||((n=e.data)==null?void 0:n.errorName)==="ResolverError"||((s=e.data)==null?void 0:s.errorName)==="ResolverNotContract"||((i=e.data)==null?void 0:i.errorName)==="ResolverNotFound"||((a=e.data)==null?void 0:a.errorName)==="ReverseAddressMismatch"||((o=e.data)==null?void 0:o.errorName)==="UnsupportedResolverProfile":!1}function nx(t){const{abi:e,data:r}=t,n=Ks(r,0,4),s=e.find(i=>i.type==="function"&&n===To(Rr(i)));if(!s)throw new YE(n,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:s.name,args:"inputs"in s&&s.inputs&&s.inputs.length>0?Io(s.inputs,Ks(r,4)):void 0}}const dl="/docs/contract/encodeErrorResult";function Vp(t){const{abi:e,errorName:r,args:n}=t;let s=e[0];if(r){const c=oi({abi:e,args:n,name:r});if(!c)throw new pp(r,{docsPath:dl});s=c}if(s.type!=="error")throw new pp(void 0,{docsPath:dl});const i=Rr(s),a=To(i);let o="0x";if(n&&n.length>0){if(!s.inputs)throw new WE(s.name,{docsPath:dl});o=vs(s.inputs,n)}return jr([a,o])}const hl="/docs/contract/encodeFunctionResult";function sx(t){const{abi:e,functionName:r,result:n}=t;let s=e[0];if(r){const a=oi({abi:e,name:r});if(!a)throw new Di(r,{docsPath:hl});s=a}if(s.type!=="function")throw new Di(void 0,{docsPath:hl});if(!s.outputs)throw new Qb(s.name,{docsPath:hl});const i=(()=>{if(s.outputs.length===0)return[];if(s.outputs.length===1)return[n];if(Array.isArray(n))return n;throw new eg(n)})();return vs(s.outputs,i)}const $o="x-batch-gateway:true";async function O1(t){const{data:e,ccipRequest:r}=t,{args:[n]}=nx({abi:md,data:e}),s=[],i=[];return await Promise.all(n.map(async(a,o)=>{try{i[o]=a.urls.includes($o)?await O1({data:a.data,ccipRequest:r}):await r(a),s[o]=!1}catch(c){s[o]=!0,i[o]=ix(c)}})),sx({abi:md,functionName:"query",result:[s,i]})}function ix(t){return t.name==="HttpRequestError"&&t.status?Vp({abi:md,errorName:"HttpError",args:[t.status,t.shortMessage]}):Vp({abi:[xg],errorName:"Error",args:["shortMessage"in t?t.shortMessage:t.message]})}function B1(t){if(t.length!==66||t.indexOf("[")!==0||t.indexOf("]")!==65)return null;const e=`0x${t.slice(1,65)}`;return Nr(e)?e:null}function vd(t){let e=new Uint8Array(32).fill(0);if(!t)return tt(e);const r=t.split(".");for(let n=r.length-1;n>=0;n-=1){const s=B1(r[n]),i=s?Zi(s):bt(Ls(r[n]),"bytes");e=bt(sr([e,i]),"bytes")}return tt(e)}function ax(t){return`[${t.slice(2)}]`}function ox(t){const e=new Uint8Array(32).fill(0);return t?B1(t)||bt(Ls(t)):tt(e)}function Jh(t){const e=t.replace(/^\.|\.$/gm,"");if(e.length===0)return new Uint8Array(1);const r=new Uint8Array(Ls(e).byteLength+2);let n=0;const s=e.split(".");for(let i=0;i<s.length;i++){let a=Ls(s[i]);a.byteLength>255&&(a=Ls(ax(ox(s[i])))),r[n]=a.length,r.set(a,n+1),n+=a.length+1}return r.byteLength!==n+1?r.slice(0,n+1):r}async function cx(t,e){const{blockNumber:r,blockTag:n,coinType:s,name:i,gatewayUrls:a,strict:o}=e,{chain:c}=t,u=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return ra({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),l=c==null?void 0:c.ensTlds;if(l&&!l.some(p=>i.endsWith(p)))return null;const f=s!=null?[vd(i),BigInt(s)]:[vd(i)];try{const p=or({abi:Lp,functionName:"addr",args:f}),d={address:u,abi:h1,functionName:"resolveWithGateways",args:[Ft(Jh(i)),p,a??[$o]],blockNumber:r,blockTag:n},g=await re(t,wr,"readContract")(d);if(g[0]==="0x")return null;const A=ci({abi:Lp,args:f,functionName:"addr",data:g[0]});return A==="0x"||br(A)==="0x00"?null:A}catch(p){if(o)throw p;if(Yh(p))return null;throw p}}class ux extends G{constructor({data:e}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(e)}`],name:"EnsAvatarInvalidMetadataError"})}}class ha extends G{constructor({reason:e}){super(`ENS NFT avatar URI is invalid. ${e}`,{name:"EnsAvatarInvalidNftUriError"})}}class Zh extends G{constructor({uri:e}){super(`Unable to resolve ENS avatar URI "${e}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class lx extends G{constructor({namespace:e}){super(`ENS NFT avatar namespace "${e}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}const fx=/(?<protocol>https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,dx=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?<target>[\w\-.]+))?(?<subtarget>\/.*)?$/,hx=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,px=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function yx(t){try{const e=await fetch(t,{method:"HEAD"});if(e.status===200){const r=e.headers.get("content-type");return r==null?void 0:r.startsWith("image/")}return!1}catch(e){return typeof e=="object"&&typeof e.response<"u"||!Object.hasOwn(globalThis,"Image")?!1:new Promise(r=>{const n=new Image;n.onload=()=>{r(!0)},n.onerror=()=>{r(!1)},n.src=t})}}function Gp(t,e){return t?t.endsWith("/")?t.slice(0,-1):t:e}function C1({uri:t,gatewayUrls:e}){const r=hx.test(t);if(r)return{uri:t,isOnChain:!0,isEncoded:r};const n=Gp(e==null?void 0:e.ipfs,"https://ipfs.io"),s=Gp(e==null?void 0:e.arweave,"https://arweave.net"),i=t.match(fx),{protocol:a,subpath:o,target:c,subtarget:u=""}=(i==null?void 0:i.groups)||{},l=a==="ipns:/"||o==="ipns/",f=a==="ipfs:/"||o==="ipfs/"||dx.test(t);if(t.startsWith("http")&&!l&&!f){let d=t;return e!=null&&e.arweave&&(d=t.replace(/https:\/\/arweave.net/g,e==null?void 0:e.arweave)),{uri:d,isOnChain:!1,isEncoded:!1}}if((l||f)&&c)return{uri:`${n}/${l?"ipns":"ipfs"}/${c}${u}`,isOnChain:!1,isEncoded:!1};if(a==="ar:/"&&c)return{uri:`${s}/${c}${u||""}`,isOnChain:!1,isEncoded:!1};let p=t.replace(px,"");if(p.startsWith("<svg")&&(p=`data:image/svg+xml;base64,${btoa(p)}`),p.startsWith("data:")||p.startsWith("{"))return{uri:p,isOnChain:!0,isEncoded:!1};throw new Zh({uri:t})}function R1(t){if(typeof t!="object"||!("image"in t)&&!("image_url"in t)&&!("image_data"in t))throw new ux({data:t});return t.image||t.image_url||t.image_data}async function mx({gatewayUrls:t,uri:e}){try{const r=await fetch(e).then(s=>s.json());return await Qh({gatewayUrls:t,uri:R1(r)})}catch{throw new Zh({uri:e})}}async function Qh({gatewayUrls:t,uri:e}){const{uri:r,isOnChain:n}=C1({uri:e,gatewayUrls:t});if(n||await yx(r))return r;throw new Zh({uri:e})}function bx(t){let e=t;e.startsWith("did:nft:")&&(e=e.replace("did:nft:","").replace(/_/g,"/"));const[r,n,s]=e.split("/"),[i,a]=r.split(":"),[o,c]=n.split(":");if(!i||i.toLowerCase()!=="eip155")throw new ha({reason:"Only EIP-155 supported"});if(!a)throw new ha({reason:"Chain ID not found"});if(!c)throw new ha({reason:"Contract address not found"});if(!s)throw new ha({reason:"Token ID not found"});if(!o)throw new ha({reason:"ERC namespace not found"});return{chainID:Number.parseInt(a,10),namespace:o.toLowerCase(),contractAddress:c,tokenID:s}}async function gx(t,{nft:e}){if(e.namespace==="erc721")return wr(t,{address:e.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(e.tokenID)]});if(e.namespace==="erc1155")return wr(t,{address:e.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(e.tokenID)]});throw new lx({namespace:e.namespace})}async function wx(t,{gatewayUrls:e,record:r}){return/eip155:/i.test(r)?vx(t,{gatewayUrls:e,record:r}):Qh({uri:r,gatewayUrls:e})}async function vx(t,{gatewayUrls:e,record:r}){const n=bx(r),s=await gx(t,{nft:n}),{uri:i,isOnChain:a,isEncoded:o}=C1({uri:s,gatewayUrls:e});if(a&&(i.includes("data:application/json;base64,")||i.startsWith("{"))){const u=o?atob(i.replace("data:application/json;base64,","")):i,l=JSON.parse(u);return Qh({uri:R1(l),gatewayUrls:e})}let c=n.tokenID;return n.namespace==="erc1155"&&(c=c.replace("0x","").padStart(64,"0")),mx({gatewayUrls:e,uri:i.replace(/(?:0x)?{id}/,c)})}async function N1(t,e){const{blockNumber:r,blockTag:n,key:s,name:i,gatewayUrls:a,strict:o}=e,{chain:c}=t,u=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return ra({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),l=c==null?void 0:c.ensTlds;if(l&&!l.some(f=>i.endsWith(f)))return null;try{const f={address:u,abi:h1,args:[Ft(Jh(i)),or({abi:Hp,functionName:"text",args:[vd(i),s]}),a??[$o]],functionName:"resolveWithGateways",blockNumber:r,blockTag:n},d=await re(t,wr,"readContract")(f);if(d[0]==="0x")return null;const b=ci({abi:Hp,functionName:"text",data:d[0]});return b===""?null:b}catch(f){if(o)throw f;if(Yh(f))return null;throw f}}async function Ex(t,{blockNumber:e,blockTag:r,assetGatewayUrls:n,name:s,gatewayUrls:i,strict:a,universalResolverAddress:o}){const c=await re(t,N1,"getEnsText")({blockNumber:e,blockTag:r,key:"avatar",name:s,universalResolverAddress:o,gatewayUrls:i,strict:a});if(!c)return null;try{return await wx(t,{record:c,gatewayUrls:n})}catch{return null}}async function Ax(t,e){const{address:r,blockNumber:n,blockTag:s,coinType:i=60n,gatewayUrls:a,strict:o}=e,{chain:c}=t,u=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return ra({blockNumber:n,chain:c,contract:"ensUniversalResolver"})})();try{const l={address:u,abi:$8,args:[r,i,a??[$o]],functionName:"reverseWithGateways",blockNumber:n,blockTag:s},f=re(t,wr,"readContract"),[p]=await f(l);return p||null}catch(l){if(o)throw l;if(Yh(l))return null;throw l}}async function Sx(t,e){const{blockNumber:r,blockTag:n,name:s}=e,{chain:i}=t,a=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!i)throw new Error("client chain not configured. universalResolverAddress is required.");return ra({blockNumber:r,chain:i,contract:"ensUniversalResolver"})})(),o=i==null?void 0:i.ensTlds;if(o&&!o.some(u=>s.endsWith(u)))throw new Error(`${s} is not a valid ENS TLD (${o==null?void 0:o.join(", ")}) for chain "${i.name}" (id: ${i.id}).`);const[c]=await re(t,wr,"readContract")({address:a,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[Ft(Jh(s))],blockNumber:r,blockTag:n});return c}async function U1(t,e){var A,S,T;const{account:r=t.account,blockNumber:n,blockTag:s="latest",blobs:i,data:a,gas:o,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:l,maxPriorityFeePerGas:f,to:p,value:d,...b}=e,g=r?Le(r):void 0;try{$n(e);const w=(typeof n=="bigint"?Y(n):void 0)||s,x=(T=(S=(A=t.chain)==null?void 0:A.formatters)==null?void 0:S.transactionRequest)==null?void 0:T.format,I=(x||Es)({...ea(b,{format:x}),account:g,blobs:i,data:a,gas:o,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:l,maxPriorityFeePerGas:f,to:p,value:d},"createAccessList"),N=await t.request({method:"eth_createAccessList",params:[I,w]});return{accessList:N.accessList,gasUsed:BigInt(N.gasUsed)}}catch(v){throw b1(v,{...e,account:g,chain:t.chain})}}async function xx(t){const e=cu(t,{method:"eth_newBlockFilter"}),r=await t.request({method:"eth_newBlockFilter"});return{id:r,request:e(r),type:"block"}}async function F1(t,{address:e,args:r,event:n,events:s,fromBlock:i,strict:a,toBlock:o}={}){const c=s??(n?[n]:void 0),u=cu(t,{method:"eth_newFilter"});let l=[];c&&(l=[c.flatMap(d=>_o({abi:[d],eventName:d.name,args:r}))],n&&(l=l[0]));const f=await t.request({method:"eth_newFilter",params:[{address:e,fromBlock:typeof i=="bigint"?Y(i):i,toBlock:typeof o=="bigint"?Y(o):o,...l.length?{topics:l}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:i,id:f,request:u(f),strict:!!a,toBlock:o,type:"event"}}async function M1(t){const e=cu(t,{method:"eth_newPendingTransactionFilter"}),r=await t.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:e(r),type:"transaction"}}async function kx(t,{address:e,blockNumber:r,blockTag:n=t.experimental_blockTag??"latest"}){const s=typeof r=="bigint"?Y(r):void 0,i=await t.request({method:"eth_getBalance",params:[e,s||n]});return BigInt(i)}async function Tx(t){const e=await t.request({method:"eth_blobBaseFee"});return BigInt(e)}async function _x(t,{blockHash:e,blockNumber:r,blockTag:n="latest"}={}){const s=r!==void 0?Y(r):void 0;let i;return e?i=await t.request({method:"eth_getBlockTransactionCountByHash",params:[e]},{dedupe:!0}):i=await t.request({method:"eth_getBlockTransactionCountByNumber",params:[s||n]},{dedupe:!!s}),gr(i)}async function Ed(t,{address:e,blockNumber:r,blockTag:n="latest"}){const s=r!==void 0?Y(r):void 0,i=await t.request({method:"eth_getCode",params:[e,s||n]},{dedupe:!!s});if(i!=="0x")return i}class Ix extends G{constructor({address:e}){super(`No EIP-712 domain found on contract "${e}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${e}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}async function Px(t,e){const{address:r,factory:n,factoryData:s}=e;try{const[i,a,o,c,u,l,f]=await re(t,wr,"readContract")({abi:Ox,address:r,functionName:"eip712Domain",factory:n,factoryData:s});return{domain:{name:a,version:o,chainId:Number(c),verifyingContract:u,salt:l},extensions:f,fields:i}}catch(i){const a=i;throw a.name==="ContractFunctionExecutionError"&&a.cause.name==="ContractFunctionZeroDataError"?new Ix({address:r}):a}}const Ox=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}];function Bx(t){var e;return{baseFeePerGas:t.baseFeePerGas.map(r=>BigInt(r)),gasUsedRatio:t.gasUsedRatio,oldestBlock:BigInt(t.oldestBlock),reward:(e=t.reward)==null?void 0:e.map(r=>r.map(n=>BigInt(n)))}}async function Cx(t,{blockCount:e,blockNumber:r,blockTag:n="latest",rewardPercentiles:s}){const i=typeof r=="bigint"?Y(r):void 0,a=await t.request({method:"eth_feeHistory",params:[Y(e),i||n,s]},{dedupe:!!i});return Bx(a)}async function Rx(t,{filter:e}){const r=e.strict??!1,s=(await e.request({method:"eth_getFilterLogs",params:[e.id]})).map(i=>Nn(i));return e.abi?Mh({abi:e.abi,logs:s,strict:r}):s}function Nx(t){const{authorizationList:e}=t;if(e)for(const r of e){const{chainId:n}=r,s=r.address;if(!ct(s))throw new $t({address:s});if(n<0)throw new gu({chainId:n})}e0(t)}function Ux(t){const{blobVersionedHashes:e}=t;if(e){if(e.length===0)throw new qg;for(const r of e){const n=Ge(r),s=gr(Ks(r,0,1));if(n!==32)throw new t8({hash:r,size:n});if(s!==Gg)throw new r8({hash:r,version:s})}}e0(t)}function e0(t){const{chainId:e,maxPriorityFeePerGas:r,maxFeePerGas:n,to:s}=t;if(e<=0)throw new gu({chainId:e});if(s&&!ct(s))throw new $t({address:s});if(n&&n>hu)throw new Js({maxFeePerGas:n});if(r&&n&&r>n)throw new io({maxFeePerGas:n,maxPriorityFeePerGas:r})}function Fx(t){const{chainId:e,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:s,to:i}=t;if(e<=0)throw new gu({chainId:e});if(i&&!ct(i))throw new $t({address:i});if(r||s)throw new G("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>hu)throw new Js({maxFeePerGas:n})}function Mx(t){const{chainId:e,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:s,to:i}=t;if(i&&!ct(i))throw new $t({address:i});if(typeof e<"u"&&e<=0)throw new gu({chainId:e});if(r||s)throw new G("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>hu)throw new Js({maxFeePerGas:n})}function Su(t){if(!t||t.length===0)return[];const e=[];for(let r=0;r<t.length;r++){const{address:n,storageKeys:s}=t[r];for(let i=0;i<s.length;i++)if(s[i].length-2!==64)throw new ES({storageKey:s[i]});if(!ct(n,{strict:!1}))throw new $t({address:n});e.push([n,s])}return e}function $x(t,e){const r=Kg(t);return r==="eip1559"?Lx(t,e):r==="eip2930"?Dx(t,e):r==="eip4844"?Hx(t,e):r==="eip7702"?jx(t,e):zx(t,e)}function jx(t,e){const{authorizationList:r,chainId:n,gas:s,nonce:i,to:a,value:o,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:l,data:f}=t;Nx(t);const p=Su(l),d=Vx(r);return jr(["0x04",bs([Y(n),i?Y(i):"0x",u?Y(u):"0x",c?Y(c):"0x",s?Y(s):"0x",a??"0x",o?Y(o):"0x",f??"0x",p,d,...jo(t,e)])])}function Hx(t,e){const{chainId:r,gas:n,nonce:s,to:i,value:a,maxFeePerBlobGas:o,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:l,data:f}=t;Ux(t);let p=t.blobVersionedHashes,d=t.sidecars;if(t.blobs&&(typeof p>"u"||typeof d>"u")){const v=typeof t.blobs[0]=="string"?t.blobs:t.blobs.map(_=>tt(_)),w=t.kzg,x=Bh({blobs:v,kzg:w});if(typeof p>"u"&&(p=Dg({commitments:x})),typeof d>"u"){const _=Ch({blobs:v,commitments:x,kzg:w});d=Wg({blobs:v,commitments:x,proofs:_})}}const b=Su(l),g=[Y(r),s?Y(s):"0x",u?Y(u):"0x",c?Y(c):"0x",n?Y(n):"0x",i??"0x",a?Y(a):"0x",f??"0x",b,o?Y(o):"0x",p??[],...jo(t,e)],A=[],S=[],T=[];if(d)for(let v=0;v<d.length;v++){const{blob:w,commitment:x,proof:_}=d[v];A.push(w),S.push(x),T.push(_)}return jr(["0x03",bs(d?[g,A,S,T]:g)])}function Lx(t,e){const{chainId:r,gas:n,nonce:s,to:i,value:a,maxFeePerGas:o,maxPriorityFeePerGas:c,accessList:u,data:l}=t;e0(t);const f=Su(u),p=[Y(r),s?Y(s):"0x",c?Y(c):"0x",o?Y(o):"0x",n?Y(n):"0x",i??"0x",a?Y(a):"0x",l??"0x",f,...jo(t,e)];return jr(["0x02",bs(p)])}function Dx(t,e){const{chainId:r,gas:n,data:s,nonce:i,to:a,value:o,accessList:c,gasPrice:u}=t;Fx(t);const l=Su(c),f=[Y(r),i?Y(i):"0x",u?Y(u):"0x",n?Y(n):"0x",a??"0x",o?Y(o):"0x",s??"0x",l,...jo(t,e)];return jr(["0x01",bs(f)])}function zx(t,e){const{chainId:r=0,gas:n,data:s,nonce:i,to:a,value:o,gasPrice:c}=t;Mx(t);let u=[i?Y(i):"0x",c?Y(c):"0x",n?Y(n):"0x",a??"0x",o?Y(o):"0x",s??"0x"];if(e){const l=(()=>{if(e.v>=35n)return(e.v-35n)/2n>0?e.v:27n+(e.v===35n?0n:1n);if(r>0)return BigInt(r*2)+BigInt(35n+e.v-27n);const d=27n+(e.v===27n?0n:1n);if(e.v!==d)throw new wS({v:e.v});return d})(),f=br(e.r),p=br(e.s);u=[...u,Y(l),f==="0x00"?"0x":f,p==="0x00"?"0x":p]}else r>0&&(u=[...u,Y(r),"0x","0x"]);return bs(u)}function jo(t,e){const r=e??t,{v:n,yParity:s}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof s>"u")return[];const i=br(r.r),a=br(r.s);return[typeof s=="number"?s?Y(1):"0x":n===0n?"0x":n===1n?Y(1):n===27n?"0x":Y(1),i==="0x00"?"0x":i,a==="0x00"?"0x":a]}function Vx(t){if(!t||t.length===0)return[];const e=[];for(const r of t){const{chainId:n,nonce:s,...i}=r,a=r.address;e.push([n?Ft(n):"0x",a,s?Ft(s):"0x",...jo({},i)])}return e}async function Gx({address:t,authorization:e,signature:r}){return ta(bh(t),await fu({authorization:e,signature:r}))}const oc=new Qi(8192);function qx(t,{enabled:e=!0,id:r}){if(!e||!r)return t();if(oc.get(r))return oc.get(r);const n=t().finally(()=>oc.delete(r));return oc.set(r,n),n}function Wx(t,e={}){return async(r,n={})=>{var f;const{dedupe:s=!1,methods:i,retryDelay:a=150,retryCount:o=3,uid:c}={...e,...n},{method:u}=r;if((f=i==null?void 0:i.exclude)!=null&&f.includes(u))throw new Cs(new Error("method not supported"),{method:u});if(i!=null&&i.include&&!i.include.includes(u))throw new Cs(new Error("method not supported"),{method:u});const l=s?zi(`${c}.${et(r)}`):void 0;return qx(()=>Uc(async()=>{try{return await t(r)}catch(p){const d=p;switch(d.code){case La.code:throw new La(d);case Da.code:throw new Da(d);case za.code:throw new za(d,{method:r.method});case Va.code:throw new Va(d);case Xs.code:throw new Xs(d);case ms.code:throw new ms(d);case Ga.code:throw new Ga(d);case qa.code:throw new qa(d);case Wa.code:throw new Wa(d);case Cs.code:throw new Cs(d,{method:r.method});case Vi.code:throw new Vi(d);case Ka.code:throw new Ka(d);case Ri.code:throw new Ri(d);case Xa.code:throw new Xa(d);case Ya.code:throw new Ya(d);case Ja.code:throw new Ja(d);case Za.code:throw new Za(d);case Qa.code:throw new Qa(d);case Gi.code:throw new Gi(d);case eo.code:throw new eo(d);case to.code:throw new to(d);case ro.code:throw new ro(d);case no.code:throw new no(d);case so.code:throw new so(d);case qi.code:throw new qi(d);case 5e3:throw new Ri(d);default:throw p instanceof G?p:new IS(d)}}},{delay:({count:p,error:d})=>{var b;if(d&&d instanceof Ci){const g=(b=d==null?void 0:d.headers)==null?void 0:b.get("Retry-After");if(g!=null&&g.match(/\d/))return Number.parseInt(g,10)*1e3}return~~(1<<p)*a},retryCount:o,shouldRetry:({error:p})=>Kx(p)}),{enabled:s,id:l})}}function Kx(t){return"code"in t&&typeof t.code=="number"?t.code===-1||t.code===Vi.code||t.code===Xs.code:t instanceof Ci&&t.status?t.status===403||t.status===408||t.status===413||t.status===429||t.status===500||t.status===502||t.status===503||t.status===504:!0}function ft(t){const e={formatters:void 0,fees:void 0,serializers:void 0,...t};function r(n){return s=>{const i=typeof s=="function"?s(n):s,a={...n,...i};return Object.assign(a,{extend:r(a)})}}return Object.assign(e,{extend:r(e)})}function Xx(t,{errorInstance:e=new Error("timed out"),timeout:r,signal:n}){return new Promise((s,i)=>{(async()=>{let a;try{const o=new AbortController;r>0&&(a=setTimeout(()=>{n&&o.abort()},r)),s(await t({signal:(o==null?void 0:o.signal)||null}))}catch(o){(o==null?void 0:o.name)==="AbortError"&&i(e),i(o)}finally{clearTimeout(a)}})()})}function Yx(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const qp=Yx();function Jx(t,e={}){const{url:r,headers:n}=Zx(t);return{async request(s){var b;const{body:i,fetchFn:a=e.fetchFn??fetch,onRequest:o=e.onRequest,onResponse:c=e.onResponse,timeout:u=e.timeout??1e4}=s,l={...e.fetchOptions??{},...s.fetchOptions??{}},{headers:f,method:p,signal:d}=l;try{const g=await Xx(async({signal:S})=>{const T={...l,body:Array.isArray(i)?et(i.map(_=>({jsonrpc:"2.0",id:_.id??qp.take(),..._}))):et({jsonrpc:"2.0",id:i.id??qp.take(),...i}),headers:{...n,"Content-Type":"application/json",...f},method:p||"POST",signal:d||(u>0?S:null)},v=new Request(r,T),w=await(o==null?void 0:o(v,T))??{...T,url:r};return await a(w.url??r,w)},{errorInstance:new _p({body:i,url:r}),timeout:u,signal:!0});c&&await c(g);let A;if((b=g.headers.get("Content-Type"))!=null&&b.startsWith("application/json"))A=await g.json();else{A=await g.text();try{A=JSON.parse(A||"{}")}catch(S){if(g.ok)throw S;A={error:A}}}if(!g.ok)throw new Ci({body:i,details:et(A.error)||g.statusText,headers:g.headers,status:g.status,url:r});return A}catch(g){throw g instanceof Ci||g instanceof _p?g:new Ci({body:i,cause:g,url:r})}}}}function Zx(t){try{const e=new URL(t),r=(()=>{if(e.username){const n=`${decodeURIComponent(e.username)}:${decodeURIComponent(e.password)}`;return e.username="",e.password="",{url:e.toString(),headers:{Authorization:`Basic ${btoa(n)}`}}}})();return{url:e.toString(),...r}}catch{return{url:t}}}const Qx=`Ethereum Signed Message:
69
- `;function e3(t){const e=typeof t=="string"?zi(t):typeof t.raw=="string"?t.raw:tt(t.raw),r=zi(`${Qx}${Ge(e)}`);return sr([r,e])}function $1(t,e){return bt(e3(t),e)}class t3 extends G{constructor({domain:e}){super(`Invalid domain "${et(e)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class r3 extends G{constructor({primaryType:e,types:r}){super(`Invalid primary type \`${e}\` must be one of \`${JSON.stringify(Object.keys(r))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."]})}}class n3 extends G{constructor({type:e}){super(`Struct type "${e}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function s3(t){const{domain:e,message:r,primaryType:n,types:s}=t,i=(c,u)=>{const l={...u};for(const f of c){const{name:p,type:d}=f;d==="address"&&(l[p]=l[p].toLowerCase())}return l},a=s.EIP712Domain?e?i(s.EIP712Domain,e):{}:{},o=(()=>{if(n!=="EIP712Domain")return i(s[n],r)})();return et({domain:a,message:o,primaryType:n,types:s})}function j1(t){const{domain:e,message:r,primaryType:n,types:s}=t,i=(a,o)=>{for(const c of a){const{name:u,type:l}=c,f=o[u],p=l.match(Ag);if(p&&(typeof f=="number"||typeof f=="bigint")){const[g,A,S]=p;Y(f,{signed:A==="int",size:Number.parseInt(S,10)/8})}if(l==="address"&&typeof f=="string"&&!ct(f))throw new $t({address:f});const d=l.match(VA);if(d){const[g,A]=d;if(A&&Ge(f)!==Number.parseInt(A,10))throw new ZE({expectedSize:Number.parseInt(A,10),givenSize:Ge(f)})}const b=s[l];b&&(i3(l),i(b,f))}};if(s.EIP712Domain&&e){if(typeof e!="object")throw new t3({domain:e});i(s.EIP712Domain,e)}if(n!=="EIP712Domain")if(s[n])i(s[n],r);else throw new r3({primaryType:n,types:s})}function H1({domain:t}){return[typeof(t==null?void 0:t.name)=="string"&&{name:"name",type:"string"},(t==null?void 0:t.version)&&{name:"version",type:"string"},(typeof(t==null?void 0:t.chainId)=="number"||typeof(t==null?void 0:t.chainId)=="bigint")&&{name:"chainId",type:"uint256"},(t==null?void 0:t.verifyingContract)&&{name:"verifyingContract",type:"address"},(t==null?void 0:t.salt)&&{name:"salt",type:"bytes32"}].filter(Boolean)}function i3(t){if(t==="address"||t==="bool"||t==="string"||t.startsWith("bytes")||t.startsWith("uint")||t.startsWith("int"))throw new n3({type:t})}function a3(t){const{domain:e={},message:r,primaryType:n}=t,s={EIP712Domain:H1({domain:e}),...t.types};j1({domain:e,message:r,primaryType:n,types:s});const i=["0x1901"];return e&&i.push(o3({domain:e,types:s})),n!=="EIP712Domain"&&i.push(L1({data:r,primaryType:n,types:s})),bt(sr(i))}function o3({domain:t,types:e}){return L1({data:t,primaryType:"EIP712Domain",types:e})}function L1({data:t,primaryType:e,types:r}){const n=D1({data:t,primaryType:e,types:r});return bt(n)}function D1({data:t,primaryType:e,types:r}){const n=[{type:"bytes32"}],s=[c3({primaryType:e,types:r})];for(const i of r[e]){const[a,o]=V1({types:r,name:i.name,type:i.type,value:t[i.name]});n.push(a),s.push(o)}return vs(n,s)}function c3({primaryType:t,types:e}){const r=Ft(u3({primaryType:t,types:e}));return bt(r)}function u3({primaryType:t,types:e}){let r="";const n=z1({primaryType:t,types:e});n.delete(t);const s=[t,...Array.from(n).sort()];for(const i of s)r+=`${i}(${e[i].map(({name:a,type:o})=>`${o} ${a}`).join(",")})`;return r}function z1({primaryType:t,types:e},r=new Set){const n=t.match(/^\w*/u),s=n==null?void 0:n[0];if(r.has(s)||e[s]===void 0)return r;r.add(s);for(const i of e[s])z1({primaryType:i.type,types:e},r);return r}function V1({types:t,name:e,type:r,value:n}){if(t[r]!==void 0)return[{type:"bytes32"},bt(D1({data:n,primaryType:r,types:t}))];if(r==="bytes")return[{type:"bytes32"},bt(n)];if(r==="string")return[{type:"bytes32"},bt(Ft(n))];if(r.lastIndexOf("]")===r.length-1){const s=r.slice(0,r.lastIndexOf("[")),i=n.map(a=>V1({name:e,type:s,types:t,value:a}));return[{type:"bytes32"},bt(vs(i.map(([a])=>a),i.map(([,a])=>a)))]}return[{type:r},n]}class l3 extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const f3={checksum:new l3(8192)},pl=f3.checksum;function G1(t,e={}){const{as:r=typeof t=="string"?"Hex":"Bytes"}=e,n=bg(g8(t));return r==="Bytes"?n:Fr(n)}const d3=/^0x[a-fA-F0-9]{40}$/;function xu(t,e={}){const{strict:r=!0}=e;if(!d3.test(t))throw new Wp({address:t,cause:new h3});if(r){if(t.toLowerCase()===t)return;if(q1(t)!==t)throw new Wp({address:t,cause:new p3})}}function q1(t){if(pl.has(t))return pl.get(t);xu(t,{strict:!1});const e=t.substring(2).toLowerCase(),r=G1(v8(e),{as:"Bytes"}),n=e.split("");for(let i=0;i<40;i+=2)r[i>>1]>>4>=8&&n[i]&&(n[i]=n[i].toUpperCase()),(r[i>>1]&15)>=8&&n[i+1]&&(n[i+1]=n[i+1].toUpperCase());const s=`0x${n.join("")}`;return pl.set(t,s),s}function Ad(t,e={}){const{strict:r=!0}=e??{};try{return xu(t,{strict:r}),!0}catch{return!1}}class Wp extends le{constructor({address:e,cause:r}){super(`Address "${e}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class h3 extends le{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class p3 extends le{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}const y3=/^(.*)\[([0-9]*)\]$/,m3=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,W1=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,Kp=2n**256n-1n;function Ui(t,e,r){const{checksumAddress:n,staticPosition:s}=r,i=n0(e.type);if(i){const[a,o]=i;return g3(t,{...e,type:o},{checksumAddress:n,length:a,staticPosition:s})}if(e.type==="tuple")return A3(t,e,{checksumAddress:n,staticPosition:s});if(e.type==="address")return b3(t,{checksum:n});if(e.type==="bool")return w3(t);if(e.type.startsWith("bytes"))return v3(t,e,{staticPosition:s});if(e.type.startsWith("uint")||e.type.startsWith("int"))return E3(t,e);if(e.type==="string")return S3(t,{staticPosition:s});throw new i0(e.type)}const Xp=32,Sd=32;function b3(t,e={}){const{checksum:r=!1}=e,n=t.readBytes(32);return[(i=>r?q1(i):i)(Fr(A8(n,-20))),32]}function g3(t,e,r){const{checksumAddress:n,length:s,staticPosition:i}=r;if(!s){const c=On(t.readBytes(Sd)),u=i+c,l=u+Xp;t.setPosition(u);const f=On(t.readBytes(Xp)),p=co(e);let d=0;const b=[];for(let g=0;g<f;++g){t.setPosition(l+(p?g*32:d));const[A,S]=Ui(t,e,{checksumAddress:n,staticPosition:l});d+=S,b.push(A)}return t.setPosition(i+32),[b,32]}if(co(e)){const c=On(t.readBytes(Sd)),u=i+c,l=[];for(let f=0;f<s;++f){t.setPosition(u+f*32);const[p]=Ui(t,e,{checksumAddress:n,staticPosition:u});l.push(p)}return t.setPosition(i+32),[l,32]}let a=0;const o=[];for(let c=0;c<s;++c){const[u,l]=Ui(t,e,{checksumAddress:n,staticPosition:i+a});a+=l,o.push(u)}return[o,a]}function w3(t){return[x8(t.readBytes(32),{size:32}),32]}function v3(t,e,{staticPosition:r}){const[n,s]=e.type.split("bytes");if(!s){const a=On(t.readBytes(32));t.setPosition(r+a);const o=On(t.readBytes(32));if(o===0)return t.setPosition(r+32),["0x",32];const c=t.readBytes(o);return t.setPosition(r+32),[Fr(c),32]}return[Fr(t.readBytes(Number.parseInt(s,10),32)),32]}function E3(t,e){const r=e.type.startsWith("int"),n=Number.parseInt(e.type.split("int")[1]||"256",10),s=t.readBytes(32);return[n>48?S8(s,{signed:r}):On(s,{signed:r}),32]}function A3(t,e,r){const{checksumAddress:n,staticPosition:s}=r,i=e.components.length===0||e.components.some(({name:c})=>!c),a=i?[]:{};let o=0;if(co(e)){const c=On(t.readBytes(Sd)),u=s+c;for(let l=0;l<e.components.length;++l){const f=e.components[l];t.setPosition(u+o);const[p,d]=Ui(t,f,{checksumAddress:n,staticPosition:u});o+=d,a[i?l:f==null?void 0:f.name]=p}return t.setPosition(s+32),[a,32]}for(let c=0;c<e.components.length;++c){const u=e.components[c],[l,f]=Ui(t,u,{checksumAddress:n,staticPosition:s});a[i?c:u==null?void 0:u.name]=l,o+=f}return[a,o]}function S3(t,{staticPosition:e}){const r=On(t.readBytes(32)),n=e+r;t.setPosition(n);const s=On(t.readBytes(32));if(s===0)return t.setPosition(e+32),["",32];const i=t.readBytes(s,32),a=k8(i1(i));return t.setPosition(e+32),[a,32]}function x3({checksumAddress:t,parameters:e,values:r}){const n=[];for(let s=0;s<e.length;s++)n.push(t0({checksumAddress:t,parameter:e[s],value:r[s]}));return n}function t0({checksumAddress:t=!1,parameter:e,value:r}){const n=e,s=n0(n.type);if(s){const[i,a]=s;return T3(r,{checksumAddress:t,length:i,parameter:{...n,type:a}})}if(n.type==="tuple")return B3(r,{checksumAddress:t,parameter:n});if(n.type==="address")return k3(r,{checksum:t});if(n.type==="bool")return I3(r);if(n.type.startsWith("uint")||n.type.startsWith("int")){const i=n.type.startsWith("int"),[,,a="256"]=W1.exec(n.type)??[];return P3(r,{signed:i,size:Number(a)})}if(n.type.startsWith("bytes"))return _3(r,{type:n.type});if(n.type==="string")return O3(r);throw new i0(n.type)}function r0(t){let e=0;for(let i=0;i<t.length;i++){const{dynamic:a,encoded:o}=t[i];a?e+=32:e+=ir(o)}const r=[],n=[];let s=0;for(let i=0;i<t.length;i++){const{dynamic:a,encoded:o}=t[i];a?(r.push(Ut(e+s,{size:32})),n.push(o),s+=ir(o)):r.push(o)}return Ur(...r,...n)}function k3(t,e){const{checksum:r=!1}=e;return xu(t,{strict:r}),{dynamic:!1,encoded:Zs(t.toLowerCase())}}function T3(t,e){const{checksumAddress:r,length:n,parameter:s}=e,i=n===null;if(!Array.isArray(t))throw new H3(t);if(!i&&t.length!==n)throw new j3({expectedLength:n,givenLength:t.length,type:`${s.type}[${n}]`});let a=!1;const o=[];for(let c=0;c<t.length;c++){const u=t0({checksumAddress:r,parameter:s,value:t[c]});u.dynamic&&(a=!0),o.push(u)}if(i||a){const c=r0(o);if(i){const u=Ut(o.length,{size:32});return{dynamic:!0,encoded:o.length>0?Ur(u,c):u}}if(a)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:Ur(...o.map(({encoded:c})=>c))}}function _3(t,{type:e}){const[,r]=e.split("bytes"),n=ir(t);if(!r){let s=t;return n%32!==0&&(s=Qs(s,Math.ceil((t.length-2)/2/32)*32)),{dynamic:!0,encoded:Ur(Zs(Ut(n,{size:32})),s)}}if(n!==Number.parseInt(r,10))throw new X1({expectedSize:Number.parseInt(r,10),value:t});return{dynamic:!1,encoded:Qs(t)}}function I3(t){if(typeof t!="boolean")throw new le(`Invalid boolean value: "${t}" (type: ${typeof t}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Zs(a1(t))}}function P3(t,{signed:e,size:r}){if(typeof r=="number"){const n=2n**(BigInt(r)-(e?1n:0n))-1n,s=e?-n-1n:0n;if(t>n||t<s)throw new u1({max:n.toString(),min:s.toString(),signed:e,size:r/8,value:t.toString()})}return{dynamic:!1,encoded:Ut(t,{size:32,signed:e})}}function O3(t){const e=zh(t),r=Math.ceil(ir(e)/32),n=[];for(let s=0;s<r;s++)n.push(Qs(rn(e,s*32,(s+1)*32)));return{dynamic:!0,encoded:Ur(Qs(Ut(ir(e),{size:32})),...n)}}function B3(t,e){const{checksumAddress:r,parameter:n}=e;let s=!1;const i=[];for(let a=0;a<n.components.length;a++){const o=n.components[a],c=Array.isArray(t)?a:o.name,u=t0({checksumAddress:r,parameter:o,value:t[c]});i.push(u),u.dynamic&&(s=!0)}return{dynamic:s,encoded:s?r0(i):Ur(...i.map(({encoded:a})=>a))}}function n0(t){const e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function co(t){var n;const{type:e}=t;if(e==="string"||e==="bytes"||e.endsWith("[]"))return!0;if(e==="tuple")return(n=t.components)==null?void 0:n.some(co);const r=n0(t.type);return!!(r&&co({...t,type:r[1]}))}const C3={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new U3({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(t){if(t<0||t>this.bytes.length-1)throw new N3({length:this.bytes.length,position:t})},decrementPosition(t){if(t<0)throw new Yp({offset:t});const e=this.position-t;this.assertPosition(e),this.position=e},getReadCount(t){return this.positionReadCount.get(t||this.position)||0},incrementPosition(t){if(t<0)throw new Yp({offset:t});const e=this.position+t;this.assertPosition(e),this.position=e},inspectByte(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectBytes(t,e){const r=e??this.position;return this.assertPosition(r+t-1),this.bytes.subarray(r,r+t)},inspectUint8(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectUint16(t){const e=t??this.position;return this.assertPosition(e+1),this.dataView.getUint16(e)},inspectUint24(t){const e=t??this.position;return this.assertPosition(e+2),(this.dataView.getUint16(e)<<8)+this.dataView.getUint8(e+2)},inspectUint32(t){const e=t??this.position;return this.assertPosition(e+3),this.dataView.getUint32(e)},pushByte(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushBytes(t){this.assertPosition(this.position+t.length-1),this.bytes.set(t,this.position),this.position+=t.length},pushUint8(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushUint16(t){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,t),this.position+=2},pushUint24(t){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,t>>8),this.dataView.setUint8(this.position+2,t&255),this.position+=3},pushUint32(t){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,t),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const t=this.inspectByte();return this.position++,t},readBytes(t,e){this.assertReadLimit(),this._touch();const r=this.inspectBytes(t);return this.position+=e??t,r},readUint8(){this.assertReadLimit(),this._touch();const t=this.inspectUint8();return this.position+=1,t},readUint16(){this.assertReadLimit(),this._touch();const t=this.inspectUint16();return this.position+=2,t},readUint24(){this.assertReadLimit(),this._touch();const t=this.inspectUint24();return this.position+=3,t},readUint32(){this.assertReadLimit(),this._touch();const t=this.inspectUint32();return this.position+=4,t},get remaining(){return this.bytes.length-this.position},setPosition(t){const e=this.position;return this.assertPosition(t),this.position=t,()=>this.position=e},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const t=this.getReadCount();this.positionReadCount.set(this.position,t+1),t>0&&this.recursiveReadCount++}};function R3(t,{recursiveReadLimit:e=8192}={}){const r=Object.create(C3);return r.bytes=t,r.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=e,r}class Yp extends le{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}}class N3 extends le{constructor({length:e,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${e}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"})}}class U3 extends le{constructor({count:e,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${e}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"})}}function F3(t,e,r={}){const{as:n="Array",checksumAddress:s=!1}=r,i=typeof e=="string"?s1(e):e,a=R3(i);if(ki(i)===0&&t.length>0)throw new $3;if(ki(i)&&ki(i)<32)throw new M3({data:typeof e=="string"?e:Fr(e),parameters:t,size:ki(i)});let o=0;const c=n==="Array"?[]:{};for(let u=0;u<t.length;++u){const l=t[u];a.setPosition(o);const[f,p]=Ui(a,l,{checksumAddress:s,staticPosition:0});o+=p,n==="Array"?c.push(f):c[l.name??u]=f}return c}function s0(t,e,r){const{checksumAddress:n=!1}={};if(t.length!==e.length)throw new Y1({expectedLength:t.length,givenLength:e.length});const s=x3({checksumAddress:n,parameters:t,values:e}),i=r0(s);return i.length===0?"0x":i}function xd(t,e){if(t.length!==e.length)throw new Y1({expectedLength:t.length,givenLength:e.length});const r=[];for(let n=0;n<t.length;n++){const s=t[n],i=e[n];r.push(xd.encode(s,i))}return Ur(...r)}(function(t){function e(r,n,s=!1){if(r==="address"){const c=n;return xu(c),Zs(c.toLowerCase(),s?32:0)}if(r==="string")return zh(n);if(r==="bytes")return n;if(r==="bool")return Zs(a1(n),s?32:1);const i=r.match(W1);if(i){const[c,u,l="256"]=i,f=Number.parseInt(l,10)/8;return Ut(n,{size:s?32:f,signed:u==="int"})}const a=r.match(m3);if(a){const[c,u]=a;if(Number.parseInt(u,10)!==(n.length-2)/2)throw new X1({expectedSize:Number.parseInt(u,10),value:n});return Qs(n,s?32:0)}const o=r.match(y3);if(o&&Array.isArray(n)){const[c,u]=o,l=[];for(let f=0;f<n.length;f++)l.push(e(u,n[f],!0));return l.length===0?"0x":Ur(...l)}throw new i0(r)}t.encode=e})(xd||(xd={}));function K1(t){return Array.isArray(t)&&typeof t[0]=="string"||typeof t=="string"?dp(t):t}class M3 extends le{constructor({data:e,parameters:r,size:n}){super(`Data size of ${n} bytes is too small for given parameters.`,{metaMessages:[`Params: (${Ei(r)})`,`Data: ${e} (${n} bytes)`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"})}}class $3 extends le{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.'),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ZeroDataError"})}}class j3 extends le{constructor({expectedLength:e,givenLength:r,type:n}){super(`Array length mismatch for type \`${n}\`. Expected: \`${e}\`. Given: \`${r}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}}class X1 extends le{constructor({expectedSize:e,value:r}){super(`Size of bytes "${r}" (bytes${ir(r)}) does not match expected size (bytes${e}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class Y1 extends le{constructor({expectedLength:e,givenLength:r}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${r}`].join(`
70
- `)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class H3 extends le{constructor(e){super(`Value \`${e}\` is not a valid array.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}}class i0 extends le{constructor(e){super(`Type \`${e}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}class J1 extends au{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,SA(e);const n=In(r);if(this.iHash=e.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;const s=this.blockLen,i=new Uint8Array(s);i.set(n.length>s?e.create().update(n).digest():n);for(let a=0;a<i.length;a++)i[a]^=54;this.iHash.update(i),this.oHash=e.create();for(let a=0;a<i.length;a++)i[a]^=106;this.oHash.update(i),Rn(i)}update(e){return ys(this),this.iHash.update(e),this}digestInto(e){ys(this),ps(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:n,finished:s,destroyed:i,blockLen:a,outputLen:o}=this;return e=e,e.finished=s,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Z1=(t,e,r)=>new J1(t,e).update(r).digest();Z1.create=(t,e)=>new J1(t,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Vt=BigInt(0),Mt=BigInt(1),Rs=BigInt(2),L3=BigInt(3),Q1=BigInt(4),ew=BigInt(5),tw=BigInt(8);function Ht(t,e){const r=t%e;return r>=Vt?r:e+r}function fr(t,e,r){let n=t;for(;e-- >Vt;)n*=n,n%=r;return n}function kd(t,e){if(t===Vt)throw new Error("invert: expected non-zero number");if(e<=Vt)throw new Error("invert: expected positive modulus, got "+e);let r=Ht(t,e),n=e,s=Vt,i=Mt;for(;r!==Vt;){const o=n/r,c=n%r,u=s-i*o;n=r,r=c,s=i,i=u}if(n!==Mt)throw new Error("invert: does not exist");return Ht(s,e)}function rw(t,e){const r=(t.ORDER+Mt)/Q1,n=t.pow(e,r);if(!t.eql(t.sqr(n),e))throw new Error("Cannot find square root");return n}function D3(t,e){const r=(t.ORDER-ew)/tw,n=t.mul(e,Rs),s=t.pow(n,r),i=t.mul(e,s),a=t.mul(t.mul(i,Rs),s),o=t.mul(i,t.sub(a,t.ONE));if(!t.eql(t.sqr(o),e))throw new Error("Cannot find square root");return o}function z3(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-Mt,r=0;for(;e%Rs===Vt;)e/=Rs,r++;let n=Rs;const s=a0(t);for(;Jp(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return rw;let i=s.pow(n,e);const a=(e+Mt)/Rs;return function(c,u){if(c.is0(u))return u;if(Jp(c,u)!==1)throw new Error("Cannot find square root");let l=r,f=c.mul(c.ONE,i),p=c.pow(u,e),d=c.pow(u,a);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let b=1,g=c.sqr(p);for(;!c.eql(g,c.ONE);)if(b++,g=c.sqr(g),b===l)throw new Error("Cannot find square root");const A=Mt<<BigInt(l-b-1),S=c.pow(f,A);l=b,f=c.sqr(S),p=c.mul(p,f),d=c.mul(d,S)}return d}}function V3(t){return t%Q1===L3?rw:t%tw===ew?D3:z3(t)}const G3=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function q3(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=G3.reduce((n,s)=>(n[s]="function",n),e);return mu(t,r)}function W3(t,e,r){if(r<Vt)throw new Error("invalid exponent, negatives unsupported");if(r===Vt)return t.ONE;if(r===Mt)return e;let n=t.ONE,s=e;for(;r>Vt;)r&Mt&&(n=t.mul(n,s)),s=t.sqr(s),r>>=Mt;return n}function nw(t,e,r=!1){const n=new Array(e.length).fill(r?t.ZERO:void 0),s=e.reduce((a,o,c)=>t.is0(o)?a:(n[c]=a,t.mul(a,o)),t.ONE),i=t.inv(s);return e.reduceRight((a,o,c)=>t.is0(o)?a:(n[c]=t.mul(a,n[c]),t.mul(a,o)),i),n}function Jp(t,e){const r=(t.ORDER-Mt)/Rs,n=t.pow(e,r),s=t.eql(n,t.ONE),i=t.eql(n,t.ZERO),a=t.eql(n,t.neg(t.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function sw(t,e){e!==void 0&&hs(e);const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function a0(t,e,r=!1,n={}){if(t<=Vt)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:i}=sw(t,e);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let a;const o=Object.freeze({ORDER:t,isLE:r,BITS:s,BYTES:i,MASK:yu(s),ZERO:Vt,ONE:Mt,create:c=>Ht(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Vt<=c&&c<t},is0:c=>c===Vt,isOdd:c=>(c&Mt)===Mt,neg:c=>Ht(-c,t),eql:(c,u)=>c===u,sqr:c=>Ht(c*c,t),add:(c,u)=>Ht(c+u,t),sub:(c,u)=>Ht(c-u,t),mul:(c,u)=>Ht(c*u,t),pow:(c,u)=>W3(o,c,u),div:(c,u)=>Ht(c*kd(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>kd(c,t),sqrt:n.sqrt||(c=>(a||(a=V3(t)),a(o,c))),toBytes:c=>r?Qg(c,i):No(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return r?Zg(c):Ds(c)},invertBatch:c=>nw(o,c),cmov:(c,u,l)=>l?u:c});return Object.freeze(o)}function iw(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function aw(t){const e=iw(t);return e+Math.ceil(e/2)}function K3(t,e,r=!1){const n=t.length,s=iw(e),i=aw(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const a=r?Zg(t):Ds(t),o=Ht(a,e-Mt)+Mt;return r?Qg(o,s):No(o,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Zp=BigInt(0),Td=BigInt(1);function yl(t,e){const r=e.negate();return t?r:e}function ow(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function ml(t,e){ow(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1),s=2**t,i=yu(t),a=BigInt(t);return{windows:r,windowSize:n,mask:i,maxNumber:s,shiftBy:a}}function Qp(t,e,r){const{windowSize:n,mask:s,maxNumber:i,shiftBy:a}=r;let o=Number(t&s),c=t>>a;o>n&&(o-=i,c+=Td);const u=e*n,l=u+Math.abs(o)-1,f=o===0,p=o<0,d=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:p,isNegF:d,offsetF:u}}function X3(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function Y3(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}const bl=new WeakMap,cw=new WeakMap;function gl(t){return cw.get(t)||1}function J3(t,e){return{constTimeNegate:yl,hasPrecomputes(r){return gl(r)!==1},unsafeLadder(r,n,s=t.ZERO){let i=r;for(;n>Zp;)n&Td&&(s=s.add(i)),i=i.double(),n>>=Td;return s},precomputeWindow(r,n){const{windows:s,windowSize:i}=ml(n,e),a=[];let o=r,c=o;for(let u=0;u<s;u++){c=o,a.push(c);for(let l=1;l<i;l++)c=c.add(o),a.push(c);o=c.double()}return a},wNAF(r,n,s){let i=t.ZERO,a=t.BASE;const o=ml(r,e);for(let c=0;c<o.windows;c++){const{nextN:u,offset:l,isZero:f,isNeg:p,isNegF:d,offsetF:b}=Qp(s,c,o);s=u,f?a=a.add(yl(d,n[b])):i=i.add(yl(p,n[l]))}return{p:i,f:a}},wNAFUnsafe(r,n,s,i=t.ZERO){const a=ml(r,e);for(let o=0;o<a.windows&&s!==Zp;o++){const{nextN:c,offset:u,isZero:l,isNeg:f}=Qp(s,o,a);if(s=c,!l){const p=n[u];i=i.add(f?p.negate():p)}}return i},getPrecomputes(r,n,s){let i=bl.get(n);return i||(i=this.precomputeWindow(n,r),r!==1&&bl.set(n,s(i))),i},wNAFCached(r,n,s){const i=gl(r);return this.wNAF(i,this.getPrecomputes(i,r,s),n)},wNAFCachedUnsafe(r,n,s,i){const a=gl(r);return a===1?this.unsafeLadder(r,n,i):this.wNAFUnsafe(a,this.getPrecomputes(a,r,s),n,i)},setWindowSize(r,n){ow(n,e),cw.set(r,n),bl.delete(r)}}}function Z3(t,e,r,n){X3(r,t),Y3(n,e);const s=r.length,i=n.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");const a=t.ZERO,o=o8(BigInt(s));let c=1;o>12?c=o-3:o>4?c=o-2:o>0&&(c=2);const u=yu(c),l=new Array(Number(u)+1).fill(a),f=Math.floor((e.BITS-1)/c)*c;let p=a;for(let d=f;d>=0;d-=c){l.fill(a);for(let g=0;g<i;g++){const A=n[g],S=Number(A>>BigInt(d)&u);l[S]=l[S].add(r[g])}let b=a;for(let g=l.length-1,A=a;g>0;g--)A=A.add(l[g]),b=b.add(A);if(p=p.add(b),d!==0)for(let g=0;g<c;g++)p=p.double()}return p}function uw(t){return q3(t.Fp),mu(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...sw(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ey(t){t.lowS!==void 0&&ao("lowS",t.lowS),t.prehash!==void 0&&ao("prehash",t.prehash)}function Q3(t){const e=uw(t);mu(e,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:r,Fp:n,a:s}=e;if(r){if(!n.eql(s,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...e})}class ek extends Error{constructor(e=""){super(e)}}const En={Err:ek,_tlv:{encode:(t,e)=>{const{Err:r}=En;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const n=e.length/2,s=nc(n);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const i=n>127?nc(s.length/2|128):"";return nc(t)+i+s+e},decode(t,e){const{Err:r}=En;let n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");const s=e[n++],i=!!(s&128);let a=0;if(!i)a=s;else{const c=s&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const u=e.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const l of u)a=a<<8|l;if(n+=c,a<128)throw new r("tlv.decode(long): not minimal encoding")}const o=e.subarray(n,n+a);if(o.length!==a)throw new r("tlv.decode: wrong value length");return{v:o,l:e.subarray(n+a)}}},_int:{encode(t){const{Err:e}=En;if(t<kn)throw new e("integer: negative integers are not allowed");let r=nc(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=En;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ds(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=En,s=hr("signature",t),{v:i,l:a}=n.decode(48,s);if(a.length)throw new e("invalid signature: left bytes after parsing");const{v:o,l:c}=n.decode(2,i),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(o),s:r.decode(u)}},hexFromSig(t){const{_tlv:e,_int:r}=En,n=e.encode(2,r.encode(t.r)),s=e.encode(2,r.encode(t.s)),i=n+s;return e.encode(48,i)}};function wl(t,e){return oo(No(t,e))}const kn=BigInt(0),ut=BigInt(1);BigInt(2);const vl=BigInt(3),tk=BigInt(4);function rk(t){const e=Q3(t),{Fp:r}=e,n=a0(e.n,e.nBitLength),s=e.toBytes||((v,w,x)=>{const _=w.toAffine();return Rc(Uint8Array.from([4]),r.toBytes(_.x),r.toBytes(_.y))}),i=e.fromBytes||(v=>{const w=v.subarray(1),x=r.fromBytes(w.subarray(0,r.BYTES)),_=r.fromBytes(w.subarray(r.BYTES,2*r.BYTES));return{x,y:_}});function a(v){const{a:w,b:x}=e,_=r.sqr(v),I=r.mul(_,v);return r.add(r.add(I,r.mul(v,w)),x)}function o(v,w){const x=r.sqr(w),_=a(v);return r.eql(x,_)}if(!o(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=r.mul(r.pow(e.a,vl),tk),u=r.mul(r.sqr(e.b),BigInt(27));if(r.is0(r.add(c,u)))throw new Error("bad curve params: a or b");function l(v){return Dh(v,ut,e.n)}function f(v){const{allowedPrivateKeyLengths:w,nByteLength:x,wrapPrivateKey:_,n:I}=e;if(w&&typeof v!="bigint"){if(Ro(v)&&(v=oo(v)),typeof v!="string"||!w.includes(v.length))throw new Error("invalid private key");v=v.padStart(x*2,"0")}let N;try{N=typeof v=="bigint"?v:Ds(hr("private key",v,x))}catch{throw new Error("invalid private key, expected hex or "+x+" bytes, got "+typeof v)}return _&&(N=Ht(N,I)),Ni("private key",N,ut,I),N}function p(v){if(!(v instanceof g))throw new Error("ProjectivePoint expected")}const d=Fp((v,w)=>{const{px:x,py:_,pz:I}=v;if(r.eql(I,r.ONE))return{x,y:_};const N=v.is0();w==null&&(w=N?r.ONE:r.inv(I));const C=r.mul(x,w),j=r.mul(_,w),M=r.mul(I,w);if(N)return{x:r.ZERO,y:r.ZERO};if(!r.eql(M,r.ONE))throw new Error("invZ was invalid");return{x:C,y:j}}),b=Fp(v=>{if(v.is0()){if(e.allowInfinityPoint&&!r.is0(v.py))return;throw new Error("bad point: ZERO")}const{x:w,y:x}=v.toAffine();if(!r.isValid(w)||!r.isValid(x))throw new Error("bad point: x or y not FE");if(!o(w,x))throw new Error("bad point: equation left != right");if(!v.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class g{constructor(w,x,_){if(w==null||!r.isValid(w))throw new Error("x required");if(x==null||!r.isValid(x)||r.is0(x))throw new Error("y required");if(_==null||!r.isValid(_))throw new Error("z required");this.px=w,this.py=x,this.pz=_,Object.freeze(this)}static fromAffine(w){const{x,y:_}=w||{};if(!w||!r.isValid(x)||!r.isValid(_))throw new Error("invalid affine point");if(w instanceof g)throw new Error("projective point not allowed");const I=N=>r.eql(N,r.ZERO);return I(x)&&I(_)?g.ZERO:new g(x,_,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(w){const x=nw(r,w.map(_=>_.pz));return w.map((_,I)=>_.toAffine(x[I])).map(g.fromAffine)}static fromHex(w){const x=g.fromAffine(i(hr("pointHex",w)));return x.assertValidity(),x}static fromPrivateKey(w){return g.BASE.multiply(f(w))}static msm(w,x){return Z3(g,n,w,x)}_setWindowSize(w){T.setWindowSize(this,w)}assertValidity(){b(this)}hasEvenY(){const{y:w}=this.toAffine();if(r.isOdd)return!r.isOdd(w);throw new Error("Field doesn't support isOdd")}equals(w){p(w);const{px:x,py:_,pz:I}=this,{px:N,py:C,pz:j}=w,M=r.eql(r.mul(x,j),r.mul(N,I)),H=r.eql(r.mul(_,j),r.mul(C,I));return M&&H}negate(){return new g(this.px,r.neg(this.py),this.pz)}double(){const{a:w,b:x}=e,_=r.mul(x,vl),{px:I,py:N,pz:C}=this;let j=r.ZERO,M=r.ZERO,H=r.ZERO,V=r.mul(I,I),Q=r.mul(N,N),U=r.mul(C,C),K=r.mul(I,N);return K=r.add(K,K),H=r.mul(I,C),H=r.add(H,H),j=r.mul(w,H),M=r.mul(_,U),M=r.add(j,M),j=r.sub(Q,M),M=r.add(Q,M),M=r.mul(j,M),j=r.mul(K,j),H=r.mul(_,H),U=r.mul(w,U),K=r.sub(V,U),K=r.mul(w,K),K=r.add(K,H),H=r.add(V,V),V=r.add(H,V),V=r.add(V,U),V=r.mul(V,K),M=r.add(M,V),U=r.mul(N,C),U=r.add(U,U),V=r.mul(U,K),j=r.sub(j,V),H=r.mul(U,Q),H=r.add(H,H),H=r.add(H,H),new g(j,M,H)}add(w){p(w);const{px:x,py:_,pz:I}=this,{px:N,py:C,pz:j}=w;let M=r.ZERO,H=r.ZERO,V=r.ZERO;const Q=e.a,U=r.mul(e.b,vl);let K=r.mul(x,N),ee=r.mul(_,C),q=r.mul(I,j),O=r.add(x,_),L=r.add(N,C);O=r.mul(O,L),L=r.add(K,ee),O=r.sub(O,L),L=r.add(x,I);let J=r.add(N,j);return L=r.mul(L,J),J=r.add(K,q),L=r.sub(L,J),J=r.add(_,I),M=r.add(C,j),J=r.mul(J,M),M=r.add(ee,q),J=r.sub(J,M),V=r.mul(Q,L),M=r.mul(U,q),V=r.add(M,V),M=r.sub(ee,V),V=r.add(ee,V),H=r.mul(M,V),ee=r.add(K,K),ee=r.add(ee,K),q=r.mul(Q,q),L=r.mul(U,L),ee=r.add(ee,q),q=r.sub(K,q),q=r.mul(Q,q),L=r.add(L,q),K=r.mul(ee,L),H=r.add(H,K),K=r.mul(J,L),M=r.mul(O,M),M=r.sub(M,K),K=r.mul(O,ee),V=r.mul(J,V),V=r.add(V,K),new g(M,H,V)}subtract(w){return this.add(w.negate())}is0(){return this.equals(g.ZERO)}wNAF(w){return T.wNAFCached(this,w,g.normalizeZ)}multiplyUnsafe(w){const{endo:x,n:_}=e;Ni("scalar",w,kn,_);const I=g.ZERO;if(w===kn)return I;if(this.is0()||w===ut)return this;if(!x||T.hasPrecomputes(this))return T.wNAFCachedUnsafe(this,w,g.normalizeZ);let{k1neg:N,k1:C,k2neg:j,k2:M}=x.splitScalar(w),H=I,V=I,Q=this;for(;C>kn||M>kn;)C&ut&&(H=H.add(Q)),M&ut&&(V=V.add(Q)),Q=Q.double(),C>>=ut,M>>=ut;return N&&(H=H.negate()),j&&(V=V.negate()),V=new g(r.mul(V.px,x.beta),V.py,V.pz),H.add(V)}multiply(w){const{endo:x,n:_}=e;Ni("scalar",w,ut,_);let I,N;if(x){const{k1neg:C,k1:j,k2neg:M,k2:H}=x.splitScalar(w);let{p:V,f:Q}=this.wNAF(j),{p:U,f:K}=this.wNAF(H);V=T.constTimeNegate(C,V),U=T.constTimeNegate(M,U),U=new g(r.mul(U.px,x.beta),U.py,U.pz),I=V.add(U),N=Q.add(K)}else{const{p:C,f:j}=this.wNAF(w);I=C,N=j}return g.normalizeZ([I,N])[0]}multiplyAndAddUnsafe(w,x,_){const I=g.BASE,N=(j,M)=>M===kn||M===ut||!j.equals(I)?j.multiplyUnsafe(M):j.multiply(M),C=N(this,x).add(N(w,_));return C.is0()?void 0:C}toAffine(w){return d(this,w)}isTorsionFree(){const{h:w,isTorsionFree:x}=e;if(w===ut)return!0;if(x)return x(g,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:w,clearCofactor:x}=e;return w===ut?this:x?x(g,this):this.multiplyUnsafe(e.h)}toRawBytes(w=!0){return ao("isCompressed",w),this.assertValidity(),s(g,this,w)}toHex(w=!0){return ao("isCompressed",w),oo(this.toRawBytes(w))}}g.BASE=new g(e.Gx,e.Gy,r.ONE),g.ZERO=new g(r.ZERO,r.ONE,r.ZERO);const{endo:A,nBitLength:S}=e,T=J3(g,A?Math.ceil(S/2):S);return{CURVE:e,ProjectivePoint:g,normPrivateKeyToScalar:f,weierstrassEquation:a,isWithinCurveOrder:l}}function nk(t){const e=uw(t);return mu(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function sk(t){const e=nk(t),{Fp:r,n,nByteLength:s,nBitLength:i}=e,a=r.BYTES+1,o=2*r.BYTES+1;function c(U){return Ht(U,n)}function u(U){return kd(U,n)}const{ProjectivePoint:l,normPrivateKeyToScalar:f,weierstrassEquation:p,isWithinCurveOrder:d}=rk({...e,toBytes(U,K,ee){const q=K.toAffine(),O=r.toBytes(q.x),L=Rc;return ao("isCompressed",ee),ee?L(Uint8Array.from([K.hasEvenY()?2:3]),O):L(Uint8Array.from([4]),O,r.toBytes(q.y))},fromBytes(U){const K=U.length,ee=U[0],q=U.subarray(1);if(K===a&&(ee===2||ee===3)){const O=Ds(q);if(!Dh(O,ut,r.ORDER))throw new Error("Point is not on curve");const L=p(O);let J;try{J=r.sqrt(L)}catch(z){const ne=z instanceof Error?": "+z.message:"";throw new Error("Point is not on curve"+ne)}const B=(J&ut)===ut;return(ee&1)===1!==B&&(J=r.neg(J)),{x:O,y:J}}else if(K===o&&ee===4){const O=r.fromBytes(q.subarray(0,r.BYTES)),L=r.fromBytes(q.subarray(r.BYTES,2*r.BYTES));return{x:O,y:L}}else{const O=a,L=o;throw new Error("invalid Point, expected length of "+O+", or uncompressed "+L+", got "+K)}}});function b(U){const K=n>>ut;return U>K}function g(U){return b(U)?c(-U):U}const A=(U,K,ee)=>Ds(U.slice(K,ee));class S{constructor(K,ee,q){Ni("r",K,ut,n),Ni("s",ee,ut,n),this.r=K,this.s=ee,q!=null&&(this.recovery=q),Object.freeze(this)}static fromCompact(K){const ee=s;return K=hr("compactSignature",K,ee*2),new S(A(K,0,ee),A(K,ee,2*ee))}static fromDER(K){const{r:ee,s:q}=En.toSig(hr("DER",K));return new S(ee,q)}assertValidity(){}addRecoveryBit(K){return new S(this.r,this.s,K)}recoverPublicKey(K){const{r:ee,s:q,recovery:O}=this,L=I(hr("msgHash",K));if(O==null||![0,1,2,3].includes(O))throw new Error("recovery id invalid");const J=O===2||O===3?ee+e.n:ee;if(J>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const B=O&1?"03":"02",F=l.fromHex(B+wl(J,r.BYTES)),z=u(J),ne=c(-L*z),ae=c(q*z),fe=l.BASE.multiplyAndAddUnsafe(F,ne,ae);if(!fe)throw new Error("point at infinify");return fe.assertValidity(),fe}hasHighS(){return b(this.s)}normalizeS(){return this.hasHighS()?new S(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return Cc(this.toDERHex())}toDERHex(){return En.hexFromSig(this)}toCompactRawBytes(){return Cc(this.toCompactHex())}toCompactHex(){const K=s;return wl(this.r,K)+wl(this.s,K)}}const T={isValidPrivateKey(U){try{return f(U),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{const U=aw(e.n);return K3(e.randomBytes(U),e.n)},precompute(U=8,K=l.BASE){return K._setWindowSize(U),K.multiply(BigInt(3)),K}};function v(U,K=!0){return l.fromPrivateKey(U).toRawBytes(K)}function w(U){if(typeof U=="bigint")return!1;if(U instanceof l)return!0;const ee=hr("key",U).length,q=r.BYTES,O=q+1,L=2*q+1;if(!(e.allowedPrivateKeyLengths||s===O))return ee===O||ee===L}function x(U,K,ee=!0){if(w(U)===!0)throw new Error("first arg must be private key");if(w(K)===!1)throw new Error("second arg must be public key");return l.fromHex(K).multiply(f(U)).toRawBytes(ee)}const _=e.bits2int||function(U){if(U.length>8192)throw new Error("input is too large");const K=Ds(U),ee=U.length*8-i;return ee>0?K>>BigInt(ee):K},I=e.bits2int_modN||function(U){return c(_(U))},N=yu(i);function C(U){return Ni("num < 2^"+i,U,kn,N),No(U,s)}function j(U,K,ee=M){if(["recovered","canonical"].some(ie=>ie in ee))throw new Error("sign() legacy options not supported");const{hash:q,randomBytes:O}=e;let{lowS:L,prehash:J,extraEntropy:B}=ee;L==null&&(L=!0),U=hr("msgHash",U),ey(ee),J&&(U=hr("prehashed msgHash",q(U)));const F=I(U),z=f(K),ne=[C(z),C(F)];if(B!=null&&B!==!1){const ie=B===!0?O(r.BYTES):B;ne.push(hr("extraEntropy",ie))}const ae=Rc(...ne),fe=F;function ue(ie){const se=_(ie);if(!d(se))return;const be=u(se),ge=l.BASE.multiply(se).toAffine(),Ee=c(ge.x);if(Ee===kn)return;const Te=c(be*c(fe+Ee*z));if(Te===kn)return;let rt=(ge.x===Ee?0:2)|Number(ge.y&ut),Ce=Te;return L&&b(Te)&&(Ce=g(Te),rt^=1),new S(Ee,Ce,rt)}return{seed:ae,k2sig:ue}}const M={lowS:e.lowS,prehash:!1},H={lowS:e.lowS,prehash:!1};function V(U,K,ee=M){const{seed:q,k2sig:O}=j(U,K,ee),L=e;return c8(L.hash.outputLen,L.nByteLength,L.hmac)(q,O)}l.BASE._setWindowSize(8);function Q(U,K,ee,q=H){var rt;const O=U;K=hr("msgHash",K),ee=hr("publicKey",ee);const{lowS:L,prehash:J,format:B}=q;if(ey(q),"strict"in q)throw new Error("options.strict was renamed to lowS");if(B!==void 0&&B!=="compact"&&B!=="der")throw new Error("format must be compact or der");const F=typeof O=="string"||Ro(O),z=!F&&!B&&typeof O=="object"&&O!==null&&typeof O.r=="bigint"&&typeof O.s=="bigint";if(!F&&!z)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let ne,ae;try{if(z&&(ne=new S(O.r,O.s)),F){try{B!=="compact"&&(ne=S.fromDER(O))}catch(Ce){if(!(Ce instanceof En.Err))throw Ce}!ne&&B!=="der"&&(ne=S.fromCompact(O))}ae=l.fromHex(ee)}catch{return!1}if(!ne||L&&ne.hasHighS())return!1;J&&(K=e.hash(K));const{r:fe,s:ue}=ne,ie=I(K),se=u(ue),be=c(ie*se),ge=c(fe*se),Ee=(rt=l.BASE.multiplyAndAddUnsafe(ae,be,ge))==null?void 0:rt.toAffine();return Ee?c(Ee.x)===fe:!1}return{CURVE:e,getPublicKey:v,getSharedSecret:x,sign:V,verify:Q,ProjectivePoint:l,Signature:S,utils:T}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ik(t){return{hash:t,hmac:(e,...r)=>Z1(t,e,TA(...r)),randomBytes:IA}}function ak(t,e){const r=n=>sk({...t,...ik(n)});return{...r(e),create:r}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const lw=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),ty=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),ok=BigInt(0),ck=BigInt(1),_d=BigInt(2),ry=(t,e)=>(t+e/_d)/e;function uk(t){const e=lw,r=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),a=BigInt(23),o=BigInt(44),c=BigInt(88),u=t*t*t%e,l=u*u*t%e,f=fr(l,r,e)*l%e,p=fr(f,r,e)*l%e,d=fr(p,_d,e)*u%e,b=fr(d,s,e)*d%e,g=fr(b,i,e)*b%e,A=fr(g,o,e)*g%e,S=fr(A,c,e)*A%e,T=fr(S,o,e)*g%e,v=fr(T,r,e)*l%e,w=fr(v,a,e)*b%e,x=fr(w,n,e)*u%e,_=fr(x,_d,e);if(!Id.eql(Id.sqr(_),t))throw new Error("Cannot find square root");return _}const Id=a0(lw,void 0,void 0,{sqrt:uk}),fw=ak({a:ok,b:BigInt(7),Fp:Id,n:ty,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=ty,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-ck*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,a=BigInt("0x100000000000000000000000000000000"),o=ry(i*t,e),c=ry(-n*t,e);let u=Ht(t-o*r-c*s,e),l=Ht(-o*n-c*i,e);const f=u>a,p=l>a;if(f&&(u=e-u),p&&(l=e-l),u>a||l>a)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:f,k1:u,k2neg:p,k2:l}}}},Lg),lk=Object.freeze(Object.defineProperty({__proto__:null,secp256k1:fw},Symbol.toStringTag,{value:"Module"}));function dw(t,e={}){const{recovered:r}=e;if(typeof t.r>"u")throw new El({signature:t});if(typeof t.s>"u")throw new El({signature:t});if(r&&typeof t.yParity>"u")throw new El({signature:t});if(t.r<0n||t.r>Kp)throw new bk({value:t.r});if(t.s<0n||t.s>Kp)throw new gk({value:t.s});if(typeof t.yParity=="number"&&t.yParity!==0&&t.yParity!==1)throw new c0({value:t.yParity})}function fk(t){return hw(Fr(t))}function hw(t){if(t.length!==130&&t.length!==132)throw new mk({signature:t});const e=BigInt(rn(t,0,32)),r=BigInt(rn(t,32,64)),n=(()=>{const s=+`0x${t.slice(130)}`;if(!Number.isNaN(s))try{return o0(s)}catch{throw new c0({value:s})}})();return typeof n>"u"?{r:e,s:r}:{r:e,s:r,yParity:n}}function dk(t){if(!(typeof t.r>"u")&&!(typeof t.s>"u"))return hk(t)}function hk(t){const e=typeof t=="string"?hw(t):t instanceof Uint8Array?fk(t):typeof t.r=="string"?yk(t):t.v?pk(t):{r:t.r,s:t.s,...typeof t.yParity<"u"?{yParity:t.yParity}:{}};return dw(e),e}function pk(t){return{r:t.r,s:t.s,yParity:o0(t.v)}}function yk(t){const e=(()=>{const r=t.v?Number(t.v):void 0;let n=t.yParity?Number(t.yParity):void 0;if(typeof r=="number"&&typeof n!="number"&&(n=o0(r)),typeof n!="number")throw new c0({value:t.yParity});return n})();return{r:BigInt(t.r),s:BigInt(t.s),yParity:e}}function o0(t){if(t===0||t===27)return 0;if(t===1||t===28)return 1;if(t>=35)return t%2===0?1:0;throw new wk({value:t})}class mk extends le{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${ir(R8(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class El extends le{constructor({signature:e}){super(`Signature \`${n1(e)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}}class bk extends le{constructor({value:e}){super(`Value \`${e}\` is an invalid r value. r must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}}class gk extends le{constructor({value:e}){super(`Value \`${e}\` is an invalid s value. s must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}}class c0 extends le{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class wk extends le{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}function vk(t,e={}){return typeof t.chainId=="string"?Ek(t):{...t,...e.signature}}function Ek(t){const{address:e,chainId:r,nonce:n}=t,s=dk(t);return{address:e,chainId:Number(r),nonce:BigInt(n),...s}}const Ak="0x8010801080108010801080108010801080108010801080108010801080108010",Sk=K1("(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data");function pw(t){if(typeof t=="string"){if(rn(t,-32)!==Ak)throw new Tk(t)}else dw(t.authorization)}function xk(t){pw(t);const e=c1(rn(t,-64,-32)),r=rn(t,-e-64,-64),n=rn(t,0,-e-64),[s,i,a]=F3(Sk,r);return{authorization:vk({address:s.delegation,chainId:Number(s.chainId),nonce:s.nonce,yParity:s.yParity,r:s.r,s:s.s}),signature:n,...a&&a!=="0x"?{data:a,to:i}:{}}}function kk(t){try{return pw(t),!0}catch{return!1}}let Tk=class extends le{constructor(e){super(`Value \`${e}\` is an invalid ERC-8010 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc8010.InvalidWrappedSignatureError"})}};function _k(t){return t.map(e=>({...e,value:BigInt(e.value)}))}function Ik(t){return{...t,balance:t.balance?BigInt(t.balance):void 0,nonce:t.nonce?gr(t.nonce):void 0,storageProof:t.storageProof?_k(t.storageProof):void 0}}async function Pk(t,{address:e,blockNumber:r,blockTag:n,storageKeys:s}){const i=n??"latest",a=r!==void 0?Y(r):void 0,o=await t.request({method:"eth_getProof",params:[e,s,a||i]});return Ik(o)}async function Ok(t,{address:e,blockNumber:r,blockTag:n="latest",slot:s}){const i=r!==void 0?Y(r):void 0;return await t.request({method:"eth_getStorageAt",params:[e,s,i||n]})}async function u0(t,{blockHash:e,blockNumber:r,blockTag:n,hash:s,index:i,sender:a,nonce:o}){var p,d,b;const c=n||"latest",u=r!==void 0?Y(r):void 0;let l=null;if(s?l=await t.request({method:"eth_getTransactionByHash",params:[s]},{dedupe:!0}):e?l=await t.request({method:"eth_getTransactionByBlockHashAndIndex",params:[e,Y(i)]},{dedupe:!0}):typeof i=="number"?l=await t.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[u||c,Y(i)]},{dedupe:!!u}):a&&typeof o=="number"&&(l=await t.request({method:"eth_getTransactionBySenderAndNonce",params:[a,Y(o)]},{dedupe:!0})),!l)throw new Pg({blockHash:e,blockNumber:r,blockTag:c,hash:s,index:i});return(((b=(d=(p=t.chain)==null?void 0:p.formatters)==null?void 0:d.transaction)==null?void 0:b.format)||Bo)(l,"getTransaction")}async function Bk(t,{hash:e,transactionReceipt:r}){const[n,s]=await Promise.all([re(t,Mo,"getBlockNumber")({}),e?re(t,u0,"getTransaction")({hash:e}):void 0]),i=(r==null?void 0:r.blockNumber)||(s==null?void 0:s.blockNumber);return i?n-i+1n:0n}async function Ec(t,{hash:e}){var s,i,a;const r=await t.request({method:"eth_getTransactionReceipt",params:[e]},{dedupe:!0});if(!r)throw new Og({hash:e});return(((a=(i=(s=t.chain)==null?void 0:s.formatters)==null?void 0:i.transactionReceipt)==null?void 0:a.format)||Xh)(r,"getTransactionReceipt")}async function Ck(t,e){var T;const{account:r,authorizationList:n,allowFailure:s=!0,blockNumber:i,blockOverrides:a,blockTag:o,stateOverride:c}=e,u=e.contracts,{batchSize:l=e.batchSize??1024,deployless:f=e.deployless??!1}=typeof((T=t.batch)==null?void 0:T.multicall)=="object"?t.batch.multicall:{},p=(()=>{if(e.multicallAddress)return e.multicallAddress;if(f)return null;if(t.chain)return ra({blockNumber:i,chain:t.chain,contract:"multicall3"});throw new Error("client chain not configured. multicallAddress is required.")})(),d=[[]];let b=0,g=0;for(let v=0;v<u.length;v++){const{abi:w,address:x,args:_,functionName:I}=u[v];try{const N=or({abi:w,args:_,functionName:I});g+=(N.length-2)/2,l>0&&g>l&&d[b].length>0&&(b++,g=(N.length-2)/2,d[b]=[]),d[b]=[...d[b],{allowFailure:!0,callData:N,target:x}]}catch(N){const C=Ys(N,{abi:w,address:x,args:_,docsPath:"/docs/contract/multicall",functionName:I,sender:r});if(!s)throw C;d[b]=[...d[b],{allowFailure:!0,callData:"0x",target:x}]}}const A=await Promise.allSettled(d.map(v=>re(t,wr,"readContract")({...p===null?{code:Vh}:{address:p},abi:Nc,account:r,args:[v],authorizationList:n,blockNumber:i,blockOverrides:a,blockTag:o,functionName:"aggregate3",stateOverride:c}))),S=[];for(let v=0;v<A.length;v++){const w=A[v];if(w.status==="rejected"){if(!s)throw w.reason;for(let _=0;_<d[v].length;_++)S.push({status:"failure",error:w.reason,result:void 0});continue}const x=w.value;for(let _=0;_<x.length;_++){const{returnData:I,success:N}=x[_],{callData:C}=d[v][_],{abi:j,address:M,functionName:H,args:V}=u[S.length];try{if(C==="0x")throw new xo;if(!N)throw new lu({data:I});const Q=ci({abi:j,args:V,data:I,functionName:H});S.push(s?{result:Q,status:"success"}:Q)}catch(Q){const U=Ys(Q,{abi:j,address:M,args:V,docsPath:"/docs/contract/multicall",functionName:H});if(!s)throw U;S.push({error:U,result:void 0,status:"failure"})}}}if(S.length!==u.length)throw new G("multicall results mismatch");return S}async function Pd(t,e){const{blockNumber:r,blockTag:n=t.experimental_blockTag??"latest",blocks:s,returnFullTransactions:i,traceTransfers:a,validation:o}=e;try{const c=[];for(const p of s){const d=p.blockOverrides?f1(p.blockOverrides):void 0,b=p.calls.map(A=>{const S=A,T=S.account?Le(S.account):void 0,v=S.abi?or(S):S.data,w={...S,account:T,data:S.dataSuffix?sr([v||"0x",S.dataSuffix]):v,from:S.from??(T==null?void 0:T.address)};return $n(w),Es(w)}),g=p.stateOverrides?Th(p.stateOverrides):void 0;c.push({blockOverrides:d,calls:b,stateOverrides:g})}const l=(typeof r=="bigint"?Y(r):void 0)||n;return(await t.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:i,traceTransfers:a,validation:o},l]})).map((p,d)=>({...Ih(p),calls:p.calls.map((b,g)=>{var j,M;const{abi:A,args:S,functionName:T,to:v}=s[d].calls[g],w=((j=b.error)==null?void 0:j.data)??b.returnData,x=BigInt(b.gasUsed),_=(M=b.logs)==null?void 0:M.map(H=>Nn(H)),I=b.status==="0x1"?"success":"failure",N=A&&I==="success"&&w!=="0x"?ci({abi:A,data:w,functionName:T}):null,C=(()=>{var V;if(I==="success")return;let H;if(((V=b.error)==null?void 0:V.data)==="0x"?H=new xo:b.error&&(H=new lu(b.error)),!!H)return Ys(H,{abi:A??[],address:v??"0x",args:S,functionName:T??"<unknown>"})})();return{data:w,gasUsed:x,logs:_,status:I,...I==="success"?{result:N}:{error:C}}})}))}catch(c){const u=c,l=du(u,{});throw l instanceof Oo?u:l}}function Od(t){let e=!0,r="",n=0,s="",i=!1;for(let a=0;a<t.length;a++){const o=t[a];if(["(",")",","].includes(o)&&(e=!0),o==="("&&n++,o===")"&&n--,!!e){if(n===0){if(o===" "&&["event","function","error",""].includes(s))s="";else if(s+=o,o===")"){i=!0;break}continue}if(o===" "){t[a-1]!==","&&r!==","&&r!==",("&&(r="",e=!1);continue}s+=o,r+=o}}if(!i)throw new le("Unable to normalize signature.");return s}function Bd(t,e){const r=typeof t,n=e.type;switch(n){case"address":return Ad(t,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in e?Object.values(e.components).every((s,i)=>Bd(Object.values(t)[i],s)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?r==="number"||r==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?r==="string"||t instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(t)&&t.every(s=>Bd(s,{...e,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function yw(t,e,r){for(const n in t){const s=t[n],i=e[n];if(s.type==="tuple"&&i.type==="tuple"&&"components"in s&&"components"in i)return yw(s.components,i.components,r[n]);const a=[s.type,i.type];if(a.includes("address")&&a.includes("bytes20")?!0:a.includes("address")&&a.includes("string")?Ad(r[n],{strict:!1}):a.includes("address")&&a.includes("bytes")?Ad(r[n],{strict:!1}):!1)return a}}function mw(t,e={}){const{prepare:r=!0}=e,n=Array.isArray(t)||typeof t=="string"?fp(t):t;return{...n,...r?{hash:Ti(n)}:{}}}function ku(t,e,r){const{args:n=[],prepare:s=!0}=r??{},i=N8(e,{strict:!1}),a=t.filter(u=>i?u.type==="function"||u.type==="error"?bw(u)===rn(e,0,4):u.type==="event"?Ti(u)===e:!1:"name"in u&&u.name===e);if(a.length===0)throw new Fc({name:e});if(a.length===1)return{...a[0],...s?{hash:Ti(a[0])}:{}};let o;for(const u of a){if(!("inputs"in u))continue;if(!n||n.length===0){if(!u.inputs||u.inputs.length===0)return{...u,...s?{hash:Ti(u)}:{}};continue}if(!u.inputs||u.inputs.length===0||u.inputs.length!==n.length)continue;if(n.every((f,p)=>{const d="inputs"in u&&u.inputs[p];return d?Bd(f,d):!1})){if(o&&"inputs"in o&&o.inputs){const f=yw(u.inputs,o.inputs,n);if(f)throw new Nk({abiItem:u,type:f[0]},{abiItem:o,type:f[1]})}o=u}}const c=(()=>{if(o)return o;const[u,...l]=a;return{...u,overloads:l}})();if(!c)throw new Fc({name:e});return{...c,...s?{hash:Ti(c)}:{}}}function bw(...t){const e=(()=>{if(Array.isArray(t[0])){const[r,n]=t;return ku(r,n)}return t[0]})();return rn(Ti(e),0,4)}function Rk(...t){const e=(()=>{if(Array.isArray(t[0])){const[n,s]=t;return ku(n,s)}return t[0]})(),r=typeof e=="string"?e:Pc(e);return Od(r)}function Ti(...t){const e=(()=>{if(Array.isArray(t[0])){const[r,n]=t;return ku(r,n)}return t[0]})();return typeof e!="string"&&"hash"in e&&e.hash?e.hash:G1(zh(Rk(e)))}class Nk extends le{constructor(e,r){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${e.type}\` in \`${Od(Pc(e.abiItem))}\`, and`,`\`${r.type}\` in \`${Od(Pc(r.abiItem))}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.AmbiguityError"})}}class Fc extends le{constructor({name:e,data:r,type:n="item"}){const s=e?` with name "${e}"`:r?` with data "${r}"`:"";super(`ABI ${n}${s} not found.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}function Uk(...t){var i;const[e,r]=(()=>{if(Array.isArray(t[0])){const[a,o]=t;return[Mk(a),o]}return t})(),{bytecode:n,args:s}=r;return Ur(n,(i=e.inputs)!=null&&i.length&&(s!=null&&s.length)?s0(e.inputs,s):"0x")}function Fk(t){return mw(t)}function Mk(t){const e=t.find(r=>r.type==="constructor");if(!e)throw new Fc({name:"constructor"});return e}function $k(...t){const[e,r=[]]=(()=>{if(Array.isArray(t[0])){const[u,l,f]=t;return[ny(u,l,{args:f}),f]}const[o,c]=t;return[o,c]})(),{overloads:n}=e,s=n?ny([e,...n],e.name,{args:r}):e,i=jk(s),a=r.length>0?s0(s.inputs,r):void 0;return a?Ur(i,a):i}function yi(t,e={}){return mw(t,e)}function ny(t,e,r){const n=ku(t,e,r);if(n.type!=="function")throw new Fc({name:e,type:"function"});return n}function jk(t){return bw(t)}const Hk="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Wr="0x0000000000000000000000000000000000000000",Lk="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033";async function Dk(t,e){const{blockNumber:r,blockTag:n,calls:s,stateOverrides:i,traceAssetChanges:a,traceTransfers:o,validation:c}=e,u=e.account?Le(e.account):void 0;if(a&&!u)throw new G("`account` is required when `traceAssetChanges` is true");const l=u?Uk(Fk("constructor(bytes, bytes)"),{bytecode:y1,args:[Lk,$k(yi("function getBalance(address)"),[u.address])]}):void 0,f=a?await Promise.all(e.calls.map(async q=>{if(!q.data&&!q.abi)return;const{accessList:O}=await U1(t,{account:u.address,...q,data:q.abi?or(q):q.data});return O.map(({address:L,storageKeys:J})=>J.length>0?L:null)})).then(q=>q.flat().filter(Boolean)):[],p=await Pd(t,{blockNumber:r,blockTag:n,blocks:[...a?[{calls:[{data:l}],stateOverrides:i},{calls:f.map((q,O)=>({abi:[yi("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[u.address],to:q,from:Wr,nonce:O})),stateOverrides:[{address:Wr,nonce:0}]}]:[],{calls:[...s,{}].map(q=>({...q,from:u==null?void 0:u.address})),stateOverrides:i},...a?[{calls:[{data:l}]},{calls:f.map((q,O)=>({abi:[yi("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[u.address],to:q,from:Wr,nonce:O})),stateOverrides:[{address:Wr,nonce:0}]},{calls:f.map((q,O)=>({to:q,abi:[yi("function decimals() returns (uint256)")],functionName:"decimals",from:Wr,nonce:O})),stateOverrides:[{address:Wr,nonce:0}]},{calls:f.map((q,O)=>({to:q,abi:[yi("function tokenURI(uint256) returns (string)")],functionName:"tokenURI",args:[0n],from:Wr,nonce:O})),stateOverrides:[{address:Wr,nonce:0}]},{calls:f.map((q,O)=>({to:q,abi:[yi("function symbol() returns (string)")],functionName:"symbol",from:Wr,nonce:O})),stateOverrides:[{address:Wr,nonce:0}]}]:[]],traceTransfers:o,validation:c}),d=a?p[2]:p[0],[b,g,,A,S,T,v,w]=a?p:[],{calls:x,..._}=d,I=x.slice(0,-1)??[],N=(b==null?void 0:b.calls)??[],C=(g==null?void 0:g.calls)??[],j=[...N,...C].map(q=>q.status==="success"?lt(q.data):null),M=(A==null?void 0:A.calls)??[],H=(S==null?void 0:S.calls)??[],V=[...M,...H].map(q=>q.status==="success"?lt(q.data):null),Q=((T==null?void 0:T.calls)??[]).map(q=>q.status==="success"?q.result:null),U=((w==null?void 0:w.calls)??[]).map(q=>q.status==="success"?q.result:null),K=((v==null?void 0:v.calls)??[]).map(q=>q.status==="success"?q.result:null),ee=[];for(const[q,O]of V.entries()){const L=j[q];if(typeof O!="bigint"||typeof L!="bigint")continue;const J=Q[q-1],B=U[q-1],F=K[q-1],z=q===0?{address:Hk,decimals:18,symbol:"ETH"}:{address:f[q-1],decimals:F||J?Number(J??1):void 0,symbol:B??void 0};ee.some(ne=>ne.token.address===z.address)||ee.push({token:z,value:{pre:L,post:O,diff:O-L}})}return{assetChanges:ee,block:_,results:I}}const gw="0x6492649264926492649264926492649264926492649264926492649264926492";function zk(t){if(rn(t,-32)!==gw)throw new qk(t)}function Vk(t){const{data:e,signature:r,to:n}=t;return Ur(s0(K1("address, bytes, bytes"),[n,e,r]),gw)}function Gk(t){try{return zk(t),!0}catch{return!1}}class qk extends le{constructor(e){super(`Value \`${e}\` is an invalid ERC-6492 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc6492.InvalidWrappedSignatureError"})}}function Wk({r:t,s:e,to:r="hex",v:n,yParity:s}){const i=(()=>{if(s===0||s===1)return s;if(n&&(n===27n||n===28n||n>=35n))return n%2n===0n?1:0;throw new Error("Invalid `v` or `yParity` value")})(),a=`0x${new fw.Signature(lt(t),lt(e)).toCompactHex()}${i===0?"1b":"1c"}`;return r==="hex"?a:an(a)}async function Tu(t,e){var c,u,l,f;const{address:r,chain:n=t.chain,hash:s,erc6492VerifierAddress:i=e.universalSignatureVerifierAddress??((u=(c=n==null?void 0:n.contracts)==null?void 0:c.erc6492Verifier)==null?void 0:u.address),multicallAddress:a=e.multicallAddress??((f=(l=n==null?void 0:n.contracts)==null?void 0:l.multicall3)==null?void 0:f.address)}=e;if(n!=null&&n.verifyHash)return await n.verifyHash(t,e);const o=(()=>{const p=e.signature;return Nr(p)?p:typeof p=="object"&&"r"in p&&"s"in p?Wk(p):tt(p)})();try{return kk(o)?await Kk(t,{...e,multicallAddress:a,signature:o}):await Xk(t,{...e,verifierAddress:i,signature:o})}catch(p){try{if(ta(bh(r),await Ng({hash:s,signature:o})))return!0}catch{}if(p instanceof ei)return!1;throw p}}async function Kk(t,e){var A;const{address:r,blockNumber:n,blockTag:s,hash:i,multicallAddress:a}=e,{authorization:o,data:c,signature:u,to:l}=xk(e.signature);if(await Ed(t,{address:r,blockNumber:n,blockTag:s})===jr(["0xef0100",o.address]))return await Yk(t,{address:r,blockNumber:n,blockTag:s,hash:i,signature:u});const p={address:o.address,chainId:Number(o.chainId),nonce:Number(o.nonce),r:Y(o.r,{size:32}),s:Y(o.s,{size:32}),yParity:o.yParity};if(!await Gx({address:r,authorization:p}))throw new ei;const b=await re(t,wr,"readContract")({...a?{address:a}:{code:Vh},authorizationList:[p],abi:Nc,blockNumber:n,blockTag:"pending",functionName:"aggregate3",args:[[...c?[{allowFailure:!0,target:l??r,callData:c}]:[],{allowFailure:!0,target:r,callData:or({abi:p1,functionName:"isValidSignature",args:[i,u]})}]]}),g=(A=b[b.length-1])==null?void 0:A.returnData;if(g!=null&&g.startsWith("0x1626ba7e"))return!0;throw new ei}async function Xk(t,e){const{address:r,factory:n,factoryData:s,hash:i,signature:a,verifierAddress:o,...c}=e,u=await(async()=>!n&&!s||Gk(a)?a:Vk({data:s,signature:a,to:n}))(),l=o?{to:o,data:or({abi:Dp,functionName:"isValidSig",args:[r,i,u]}),...c}:{data:wu({abi:Dp,args:[r,i,u],bytecode:L8}),...c},{data:f}=await re(t,Fo,"call")(l).catch(p=>{throw p instanceof Cg?new ei:p});if(oA(f??"0x0"))return!0;throw new ei}async function Yk(t,e){const{address:r,blockNumber:n,blockTag:s,hash:i,signature:a}=e;if((await re(t,wr,"readContract")({address:r,abi:p1,args:[i,a],blockNumber:n,blockTag:s,functionName:"isValidSignature"}).catch(c=>{throw c instanceof Rg?new ei:c})).startsWith("0x1626ba7e"))return!0;throw new ei}class ei extends Error{}async function Jk(t,{address:e,message:r,factory:n,factoryData:s,signature:i,...a}){const o=$1(r);return re(t,Tu,"verifyHash")({address:e,factory:n,factoryData:s,hash:o,signature:i,...a})}async function Zk(t,e){const{address:r,factory:n,factoryData:s,signature:i,message:a,primaryType:o,types:c,domain:u,...l}=e,f=a3({message:a,primaryType:o,types:c,domain:u});return re(t,Tu,"verifyHash")({address:r,factory:n,factoryData:s,hash:f,signature:i,...l})}function ww(t,{emitOnBegin:e=!1,emitMissed:r=!1,onBlockNumber:n,onError:s,poll:i,pollingInterval:a=t.pollingInterval}){const o=typeof i<"u"?i:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc"));let c;return o?(()=>{const f=et(["watchBlockNumber",t.uid,e,r,a]);return Un(f,{onBlockNumber:n,onError:s},p=>na(async()=>{var d;try{const b=await re(t,Mo,"getBlockNumber")({cacheTime:0});if(c!==void 0){if(b===c)return;if(b-c>1&&r)for(let g=c+1n;g<b;g++)p.onBlockNumber(g,c),c=g}(c===void 0||b>c)&&(p.onBlockNumber(b,c),c=b)}catch(b){(d=p.onError)==null||d.call(p,b)}},{emitOnBegin:e,interval:a}))})():(()=>{const f=et(["watchBlockNumber",t.uid,e,r]);return Un(f,{onBlockNumber:n,onError:s},p=>{let d=!0,b=()=>d=!1;return(async()=>{try{const g=(()=>{if(t.transport.type==="fallback"){const S=t.transport.transports.find(T=>T.config.type==="webSocket"||T.config.type==="ipc");return S?S.value:t.transport}return t.transport})(),{unsubscribe:A}=await g.subscribe({params:["newHeads"],onData(S){var v;if(!d)return;const T=lt((v=S.result)==null?void 0:v.number);p.onBlockNumber(T,c),c=T},onError(S){var T;(T=p.onError)==null||T.call(p,S)}});b=A,d||b()}catch(g){s==null||s(g)}})(),()=>b()})})()}async function vw(t,e){const{checkReplacement:r=!0,confirmations:n=1,hash:s,onReplaced:i,retryCount:a=6,retryDelay:o=({count:x})=>~~(1<<x)*200,timeout:c=18e4}=e,u=et(["waitForTransactionReceipt",t.uid,s]),l=(()=>{var x;return e.pollingInterval?e.pollingInterval:(x=t.chain)!=null&&x.experimental_preconfirmationTime?t.chain.experimental_preconfirmationTime:t.pollingInterval})();let f,p,d,b=!1,g,A;const{promise:S,resolve:T,reject:v}=Gh(),w=c?setTimeout(()=>{A==null||A(),g==null||g(),v(new SS({hash:s}))},c):void 0;return g=Un(u,{onReplaced:i,resolve:T,reject:v},async x=>{if(d=await re(t,Ec,"getTransactionReceipt")({hash:s}).catch(()=>{}),d&&n<=1){clearTimeout(w),x.resolve(d),g==null||g();return}A=re(t,ww,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:l,async onBlockNumber(_){const I=C=>{clearTimeout(w),A==null||A(),C(),g==null||g()};let N=_;if(!b)try{if(d){if(n>1&&(!d.blockNumber||N-d.blockNumber+1n<n))return;I(()=>x.resolve(d));return}if(r&&!f&&(b=!0,await Uc(async()=>{f=await re(t,u0,"getTransaction")({hash:s}),f.blockNumber&&(N=f.blockNumber)},{delay:o,retryCount:a}),b=!1),d=await re(t,Ec,"getTransactionReceipt")({hash:s}),n>1&&(!d.blockNumber||N-d.blockNumber+1n<n))return;I(()=>x.resolve(d))}catch(C){if(C instanceof Pg||C instanceof Og){if(!f){b=!1;return}try{p=f,b=!0;const j=await Uc(()=>re(t,Pr,"getBlock")({blockNumber:N,includeTransactions:!0}),{delay:o,retryCount:a,shouldRetry:({error:V})=>V instanceof $g});b=!1;const M=j.transactions.find(({from:V,nonce:Q})=>V===p.from&&Q===p.nonce);if(!M||(d=await re(t,Ec,"getTransactionReceipt")({hash:M.hash}),n>1&&(!d.blockNumber||N-d.blockNumber+1n<n)))return;let H="replaced";M.to===p.to&&M.value===p.value&&M.input===p.input?H="repriced":M.from===M.to&&M.value===0n&&(H="cancelled"),I(()=>{var V;(V=x.onReplaced)==null||V.call(x,{reason:H,replacedTransaction:p,transaction:M,transactionReceipt:d}),x.resolve(d)})}catch(j){I(()=>x.reject(j))}}else I(()=>x.reject(C))}}})}),S}function Qk(t,{blockTag:e=t.experimental_blockTag??"latest",emitMissed:r=!1,emitOnBegin:n=!1,onBlock:s,onError:i,includeTransactions:a,poll:o,pollingInterval:c=t.pollingInterval}){const u=typeof o<"u"?o:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc")),l=a??!1;let f;return u?(()=>{const b=et(["watchBlocks",t.uid,e,r,n,l,c]);return Un(b,{onBlock:s,onError:i},g=>na(async()=>{var A;try{const S=await re(t,Pr,"getBlock")({blockTag:e,includeTransactions:l});if(S.number!==null&&(f==null?void 0:f.number)!=null){if(S.number===f.number)return;if(S.number-f.number>1&&r)for(let T=(f==null?void 0:f.number)+1n;T<S.number;T++){const v=await re(t,Pr,"getBlock")({blockNumber:T,includeTransactions:l});g.onBlock(v,f),f=v}}((f==null?void 0:f.number)==null||e==="pending"&&(S==null?void 0:S.number)==null||S.number!==null&&S.number>f.number)&&(g.onBlock(S,f),f=S)}catch(S){(A=g.onError)==null||A.call(g,S)}},{emitOnBegin:n,interval:c}))})():(()=>{let b=!0,g=!0,A=()=>b=!1;return(async()=>{try{n&&re(t,Pr,"getBlock")({blockTag:e,includeTransactions:l}).then(v=>{b&&g&&(s(v,void 0),g=!1)}).catch(i);const S=(()=>{if(t.transport.type==="fallback"){const v=t.transport.transports.find(w=>w.config.type==="webSocket"||w.config.type==="ipc");return v?v.value:t.transport}return t.transport})(),{unsubscribe:T}=await S.subscribe({params:["newHeads"],async onData(v){var x;if(!b)return;const w=await re(t,Pr,"getBlock")({blockNumber:(x=v.result)==null?void 0:x.number,includeTransactions:l}).catch(()=>{});b&&(s(w,f),g=!1,f=w)},onError(v){i==null||i(v)}});A=T,b||A()}catch(S){i==null||i(S)}})(),()=>A()})()}function eT(t,{address:e,args:r,batch:n=!0,event:s,events:i,fromBlock:a,onError:o,onLogs:c,poll:u,pollingInterval:l=t.pollingInterval,strict:f}){const p=typeof u<"u"?u:typeof a=="bigint"?!0:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc")),d=f??!1;return p?(()=>{const A=et(["watchEvent",e,r,n,t.uid,s,l,a]);return Un(A,{onLogs:c,onError:o},S=>{let T;a!==void 0&&(T=a-1n);let v,w=!1;const x=na(async()=>{var _;if(!w){try{v=await re(t,F1,"createEventFilter")({address:e,args:r,event:s,events:i,strict:d,fromBlock:a})}catch{}w=!0;return}try{let I;if(v)I=await re(t,vu,"getFilterChanges")({filter:v});else{const N=await re(t,Mo,"getBlockNumber")({});T&&T!==N?I=await re(t,$h,"getLogs")({address:e,args:r,event:s,events:i,fromBlock:T+1n,toBlock:N}):I=[],T=N}if(I.length===0)return;if(n)S.onLogs(I);else for(const N of I)S.onLogs([N])}catch(I){v&&I instanceof ms&&(w=!1),(_=S.onError)==null||_.call(S,I)}},{emitOnBegin:!0,interval:l});return async()=>{v&&await re(t,Eu,"uninstallFilter")({filter:v}),x()}})})():(()=>{let A=!0,S=()=>A=!1;return(async()=>{try{const T=(()=>{if(t.transport.type==="fallback"){const _=t.transport.transports.find(I=>I.config.type==="webSocket"||I.config.type==="ipc");return _?_.value:t.transport}return t.transport})(),v=i??(s?[s]:void 0);let w=[];v&&(w=[v.flatMap(I=>_o({abi:[I],eventName:I.name,args:r}))],s&&(w=w[0]));const{unsubscribe:x}=await T.subscribe({params:["logs",{address:e,topics:w}],onData(_){var N;if(!A)return;const I=_.result;try{const{eventName:C,args:j}=Bc({abi:v??[],data:I.data,topics:I.topics,strict:d}),M=Nn(I,{args:j,eventName:C});c([M])}catch(C){let j,M;if(C instanceof Oc||C instanceof hh){if(f)return;j=C.abiItem.name,M=(N=C.abiItem.inputs)==null?void 0:N.some(V=>!("name"in V&&V.name))}const H=Nn(I,{args:M?[]:{},eventName:j});c([H])}},onError(_){o==null||o(_)}});S=x,A||S()}catch(T){o==null||o(T)}})(),()=>S()})()}function tT(t,{batch:e=!0,onError:r,onTransactions:n,poll:s,pollingInterval:i=t.pollingInterval}){return(typeof s<"u"?s:t.transport.type!=="webSocket"&&t.transport.type!=="ipc")?(()=>{const u=et(["watchPendingTransactions",t.uid,e,i]);return Un(u,{onTransactions:n,onError:r},l=>{let f;const p=na(async()=>{var d;try{if(!f)try{f=await re(t,M1,"createPendingTransactionFilter")({});return}catch(g){throw p(),g}const b=await re(t,vu,"getFilterChanges")({filter:f});if(b.length===0)return;if(e)l.onTransactions(b);else for(const g of b)l.onTransactions([g])}catch(b){(d=l.onError)==null||d.call(l,b)}},{emitOnBegin:!0,interval:i});return async()=>{f&&await re(t,Eu,"uninstallFilter")({filter:f}),p()}})})():(()=>{let u=!0,l=()=>u=!1;return(async()=>{try{const{unsubscribe:f}=await t.transport.subscribe({params:["newPendingTransactions"],onData(p){if(!u)return;const d=p.result;n([d])},onError(p){r==null||r(p)}});l=f,u||l()}catch(f){r==null||r(f)}})(),()=>l()})()}function rT(t){var f,p,d;const{scheme:e,statement:r,...n}=((f=t.match(nT))==null?void 0:f.groups)??{},{chainId:s,expirationTime:i,issuedAt:a,notBefore:o,requestId:c,...u}=((p=t.match(sT))==null?void 0:p.groups)??{},l=(d=t.split("Resources:")[1])==null?void 0:d.split(`
71
- - `).slice(1);return{...n,...u,...s?{chainId:Number(s)}:{},...i?{expirationTime:new Date(i)}:{},...a?{issuedAt:new Date(a)}:{},...o?{notBefore:new Date(o)}:{},...c?{requestId:c}:{},...l?{resources:l}:{},...e?{scheme:e}:{},...r?{statement:r}:{}}}const nT=/^(?:(?<scheme>[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?<domain>[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?<address>0x[a-fA-F0-9]{40})\n\n(?:(?<statement>.*)\n\n)?/,sT=/(?:URI: (?<uri>.+))\n(?:Version: (?<version>.+))\n(?:Chain ID: (?<chainId>\d+))\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\n(?:Issued At: (?<issuedAt>.+))(?:\nExpiration Time: (?<expirationTime>.+))?(?:\nNot Before: (?<notBefore>.+))?(?:\nRequest ID: (?<requestId>.+))?/;function iT(t){const{address:e,domain:r,message:n,nonce:s,scheme:i,time:a=new Date}=t;if(r&&n.domain!==r||s&&n.nonce!==s||i&&n.scheme!==i||n.expirationTime&&a>=n.expirationTime||n.notBefore&&a<n.notBefore)return!1;try{if(!n.address||!ct(n.address,{strict:!1})||e&&!ta(n.address,e))return!1}catch{return!1}return!0}async function aT(t,e){const{address:r,domain:n,message:s,nonce:i,scheme:a,signature:o,time:c=new Date,...u}=e,l=rT(s);if(!l.address||!iT({address:r,domain:n,message:l,nonce:i,scheme:a,time:c}))return!1;const p=$1(s);return Tu(t,{address:l.address,hash:p,signature:o,...u})}async function l0(t,{serializedTransaction:e,throwOnReceiptRevert:r,timeout:n}){var o,c,u;const s=await t.request({method:"eth_sendRawTransactionSync",params:n?[e,Y(n)]:[e]},{retryCount:0}),a=(((u=(c=(o=t.chain)==null?void 0:o.formatters)==null?void 0:c.transactionReceipt)==null?void 0:u.format)||Xh)(s);if(a.status==="reverted"&&r)throw new Bg({receipt:a});return a}function oT(t){return{call:e=>Fo(t,e),createAccessList:e=>U1(t,e),createBlockFilter:()=>xx(t),createContractEventFilter:e=>Eh(t,e),createEventFilter:e=>F1(t,e),createPendingTransactionFilter:()=>M1(t),estimateContractGas:e=>Xg(t,e),estimateGas:e=>Fh(t,e),getBalance:e=>kx(t,e),getBlobBaseFee:()=>Tx(t),getBlock:e=>Pr(t,e),getBlockNumber:e=>Mo(t,e),getBlockTransactionCount:e=>_x(t,e),getBytecode:e=>Ed(t,e),getChainId:()=>As(t),getCode:e=>Ed(t,e),getContractEvents:e=>jh(t,e),getEip712Domain:e=>Px(t,e),getEnsAddress:e=>cx(t,e),getEnsAvatar:e=>Ex(t,e),getEnsName:e=>Ax(t,e),getEnsResolver:e=>Sx(t,e),getEnsText:e=>N1(t,e),getFeeHistory:e=>Cx(t,e),estimateFeesPerGas:e=>GS(t,e),getFilterChanges:e=>vu(t,e),getFilterLogs:e=>Rx(t,e),getGasPrice:()=>Ph(t),getLogs:e=>$h(t,e),getProof:e=>Pk(t,e),estimateMaxPriorityFeePerGas:e=>VS(t,e),fillTransaction:e=>Nh(t,e),getStorageAt:e=>Ok(t,e),getTransaction:e=>u0(t,e),getTransactionConfirmations:e=>Bk(t,e),getTransactionCount:e=>Oh(t,e),getTransactionReceipt:e=>Ec(t,e),multicall:e=>Ck(t,e),prepareTransactionRequest:e=>Co(t,e),readContract:e=>wr(t,e),sendRawTransaction:e=>Wh(t,e),sendRawTransactionSync:e=>l0(t,e),simulate:e=>Pd(t,e),simulateBlocks:e=>Pd(t,e),simulateCalls:e=>Dk(t,e),simulateContract:e=>v1(t,e),verifyHash:e=>Tu(t,e),verifyMessage:e=>Jk(t,e),verifySiweMessage:e=>aT(t,e),verifyTypedData:e=>Zk(t,e),uninstallFilter:e=>Eu(t,e),waitForTransactionReceipt:e=>vw(t,e),watchBlocks:e=>Qk(t,e),watchBlockNumber:e=>ww(t,e),watchContractEvent:e=>E1(t,e),watchEvent:e=>eT(t,e),watchPendingTransactions:e=>tT(t,e)}}function cT(t){const{key:e="public",name:r="Public Client"}=t;return P1({...t,key:e,name:r,type:"publicClient"}).extend(oT)}async function uT(t,{chain:e}){const{id:r,name:n,nativeCurrency:s,rpcUrls:i,blockExplorers:a}=e;await t.request({method:"wallet_addEthereumChain",params:[{chainId:Y(r),chainName:n,nativeCurrency:s,rpcUrls:i.default.http,blockExplorerUrls:a?Object.values(a).map(({url:o})=>o):void 0}]},{dedupe:!0,retryCount:0})}function lT(t,e){const{abi:r,args:n,bytecode:s,...i}=e,a=wu({abi:r,args:n,bytecode:s});return Au(t,{...i,...i.authorizationList?{to:null}:{},data:a})}async function fT(t){var r;return((r=t.account)==null?void 0:r.type)==="local"?[t.account.address]:(await t.request({method:"eth_accounts"},{dedupe:!0})).map(n=>ko(n))}async function dT(t,e={}){const{account:r=t.account,chainId:n}=e,s=r?Le(r):void 0,i=n?[s==null?void 0:s.address,[Y(n)]]:[s==null?void 0:s.address],a=await t.request({method:"wallet_getCapabilities",params:i}),o={};for(const[c,u]of Object.entries(a)){o[Number(c)]={};for(let[l,f]of Object.entries(u))l==="addSubAccount"&&(l="unstable_addSubAccount"),o[Number(c)][l]=f}return typeof n=="number"?o[n]:o}async function hT(t){return await t.request({method:"wallet_getPermissions"},{dedupe:!0})}async function Ew(t,e){var c;const{account:r=t.account,chainId:n,nonce:s}=e;if(!r)throw new Ss({docsPath:"/docs/eip7702/prepareAuthorization"});const i=Le(r),a=(()=>{if(e.executor)return e.executor==="self"?e.executor:Le(e.executor)})(),o={address:e.contractAddress??e.address,chainId:n,nonce:s};return typeof o.chainId>"u"&&(o.chainId=((c=t.chain)==null?void 0:c.id)??await re(t,As,"getChainId")({})),typeof o.nonce>"u"&&(o.nonce=await re(t,Oh,"getTransactionCount")({address:i.address,blockTag:"pending"}),(a==="self"||a!=null&&a.address&&ta(a.address,i.address))&&(o.nonce+=1)),o}async function pT(t){return(await t.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(r=>bh(r))}async function yT(t,e){return t.request({method:"wallet_requestPermissions",params:[e]},{retryCount:0})}async function mT(t,e){const{chain:r=t.chain}=e,n=e.timeout??Math.max(((r==null?void 0:r.blockTime)??0)*3,5e3),s=await k1(t,e);return await _1(t,{...e,id:s.id,timeout:n})}const Al=new Qi(128);async function Aw(t,e){var _,I,N,C;const{account:r=t.account,assertChainId:n=!0,chain:s=t.chain,accessList:i,authorizationList:a,blobs:o,data:c,gas:u,gasPrice:l,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:d,nonce:b,pollingInterval:g,throwOnReceiptRevert:A,type:S,value:T,...v}=e,w=e.timeout??Math.max(((s==null?void 0:s.blockTime)??0)*3,5e3);if(typeof r>"u")throw new Ss({docsPath:"/docs/actions/wallet/sendTransactionSync"});const x=r?Le(r):null;try{$n(e);const j=await(async()=>{if(e.to)return e.to;if(e.to!==null&&a&&a.length>0)return await fu({authorization:a[0]}).catch(()=>{throw new G("`to` is required. Could not infer from `authorizationList`.")})})();if((x==null?void 0:x.type)==="json-rpc"||x===null){let M;s!==null&&(M=await re(t,As,"getChainId")({}),n&&qh({currentChainId:M,chain:s}));const H=(N=(I=(_=t.chain)==null?void 0:_.formatters)==null?void 0:I.transactionRequest)==null?void 0:N.format,Q=(H||Es)({...ea(v,{format:H}),accessList:i,account:x,authorizationList:a,blobs:o,chainId:M,data:c,gas:u,gasPrice:l,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:d,nonce:b,to:j,type:S,value:T},"sendTransaction"),U=Al.get(t.uid),K=U?"wallet_sendTransaction":"eth_sendTransaction",ee=await(async()=>{try{return await t.request({method:K,params:[Q]},{retryCount:0})}catch(O){if(U===!1)throw O;const L=O;if(L.name==="InvalidInputRpcError"||L.name==="InvalidParamsRpcError"||L.name==="MethodNotFoundRpcError"||L.name==="MethodNotSupportedRpcError")return await t.request({method:"wallet_sendTransaction",params:[Q]},{retryCount:0}).then(J=>(Al.set(t.uid,!0),J)).catch(J=>{const B=J;throw B.name==="MethodNotFoundRpcError"||B.name==="MethodNotSupportedRpcError"?(Al.set(t.uid,!1),L):B});throw L}})(),q=await re(t,vw,"waitForTransactionReceipt")({checkReplacement:!1,hash:ee,pollingInterval:g,timeout:w});if(A&&q.status==="reverted")throw new Bg({receipt:q});return q}if((x==null?void 0:x.type)==="local"){const M=await re(t,Co,"prepareTransactionRequest")({account:x,accessList:i,authorizationList:a,blobs:o,chain:s,data:c,gas:u,gasPrice:l,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:d,nonce:b,nonceManager:x.nonceManager,parameters:[...Uh,"sidecars"],type:S,value:T,...v,to:j}),H=(C=s==null?void 0:s.serializers)==null?void 0:C.transaction,V=await x.signTransaction(M,{serializer:H});return await re(t,l0,"sendRawTransactionSync")({serializedTransaction:V,throwOnReceiptRevert:A,timeout:e.timeout})}throw(x==null?void 0:x.type)==="smart"?new zs({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new zs({docsPath:"/docs/actions/wallet/sendTransactionSync",type:x==null?void 0:x.type})}catch(j){throw j instanceof zs?j:pu(j,{...e,account:x,chain:e.chain||void 0})}}async function bT(t,e){const{id:r}=e;await t.request({method:"wallet_showCallsStatus",params:[r]})}async function gT(t,e){const{account:r=t.account}=e;if(!r)throw new Ss({docsPath:"/docs/eip7702/signAuthorization"});const n=Le(r);if(!n.signAuthorization)throw new zs({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});const s=await Ew(t,e);return n.signAuthorization(s)}async function wT(t,{account:e=t.account,message:r}){if(!e)throw new Ss({docsPath:"/docs/actions/wallet/signMessage"});const n=Le(e);if(n.signMessage)return n.signMessage({message:r});const s=typeof r=="string"?zi(r):r.raw instanceof Uint8Array?Ft(r.raw):r.raw;return t.request({method:"personal_sign",params:[s,n.address]},{retryCount:0})}async function vT(t,e){var u,l,f,p;const{account:r=t.account,chain:n=t.chain,...s}=e;if(!r)throw new Ss({docsPath:"/docs/actions/wallet/signTransaction"});const i=Le(r);$n({account:i,...e});const a=await re(t,As,"getChainId")({});n!==null&&qh({currentChainId:a,chain:n});const o=(n==null?void 0:n.formatters)||((u=t.chain)==null?void 0:u.formatters),c=((l=o==null?void 0:o.transactionRequest)==null?void 0:l.format)||Es;return i.signTransaction?i.signTransaction({...s,chainId:a},{serializer:(p=(f=t.chain)==null?void 0:f.serializers)==null?void 0:p.transaction}):await t.request({method:"eth_signTransaction",params:[{...c({...s,account:i},"signTransaction"),chainId:Y(a),from:i.address}]},{retryCount:0})}async function ET(t,e){const{account:r=t.account,domain:n,message:s,primaryType:i}=e;if(!r)throw new Ss({docsPath:"/docs/actions/wallet/signTypedData"});const a=Le(r),o={EIP712Domain:H1({domain:n}),...e.types};if(j1({domain:n,message:s,primaryType:i,types:o}),a.signTypedData)return a.signTypedData({domain:n,message:s,primaryType:i,types:o});const c=s3({domain:n,message:s,primaryType:i,types:o});return t.request({method:"eth_signTypedData_v4",params:[a.address,c]},{retryCount:0})}async function AT(t,{id:e}){await t.request({method:"wallet_switchEthereumChain",params:[{chainId:Y(e)}]},{retryCount:0})}async function ST(t,e){return await t.request({method:"wallet_watchAsset",params:e},{retryCount:0})}async function xT(t,e){return Wi.internal(t,Aw,"sendTransactionSync",e)}function kT(t){return{addChain:e=>uT(t,e),deployContract:e=>lT(t,e),fillTransaction:e=>Nh(t,e),getAddresses:()=>fT(t),getCallsStatus:e=>T1(t,e),getCapabilities:e=>dT(t,e),getChainId:()=>As(t),getPermissions:()=>hT(t),prepareAuthorization:e=>Ew(t,e),prepareTransactionRequest:e=>Co(t,e),requestAddresses:()=>pT(t),requestPermissions:e=>yT(t,e),sendCalls:e=>k1(t,e),sendCallsSync:e=>mT(t,e),sendRawTransaction:e=>Wh(t,e),sendRawTransactionSync:e=>l0(t,e),sendTransaction:e=>Au(t,e),sendTransactionSync:e=>Aw(t,e),showCallsStatus:e=>bT(t,e),signAuthorization:e=>gT(t,e),signMessage:e=>wT(t,e),signTransaction:e=>vT(t,e),signTypedData:e=>ET(t,e),switchChain:e=>AT(t,e),waitForCallsStatus:e=>_1(t,e),watchAsset:e=>ST(t,e),writeContract:e=>Wi(t,e),writeContractSync:e=>xT(t,e)}}function Sl(t){const{key:e="wallet",name:r="Wallet Client",transport:n}=t;return P1({...t,key:e,name:r,transport:n,type:"walletClient"}).extend(kT)}function Sw({key:t,methods:e,name:r,request:n,retryCount:s=3,retryDelay:i=150,timeout:a,type:o},c){const u=I1();return{config:{key:t,methods:e,name:r,request:n,retryCount:s,retryDelay:i,timeout:a,type:o},request:Wx(n,{methods:e,retryCount:s,retryDelay:i,uid:u}),value:c}}function sy(t,e={}){const{key:r="custom",methods:n,name:s="Custom Provider",retryDelay:i}=e;return({retryCount:a})=>Sw({key:r,methods:n,name:s,request:t.request.bind(t),retryCount:e.retryCount??a,retryDelay:i,type:"custom"})}class TT extends G{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}function xw(t,e={}){const{batch:r,fetchFn:n,fetchOptions:s,key:i="http",methods:a,name:o="HTTP JSON-RPC",onFetchRequest:c,onFetchResponse:u,retryDelay:l,raw:f}=e;return({chain:p,retryCount:d,timeout:b})=>{const{batchSize:g=1e3,wait:A=0}=typeof r=="object"?r:{},S=e.retryCount??d,T=b??e.timeout??1e4,v=p==null?void 0:p.rpcUrls.default.http[0];if(!v)throw new TT;const w=Jx(v,{fetchFn:n,fetchOptions:s,onRequest:c,onResponse:u,timeout:T});return Sw({key:i,methods:a,name:o,async request({method:x,params:_}){const I={method:x,params:_},{schedule:N}=g1({id:v,wait:A,shouldSplitBatch(H){return H.length>g},fn:H=>w.request({body:H}),sort:(H,V)=>H.id-V.id}),C=async H=>r?N(H):[await w.request({body:H})],[{error:j,result:M}]=await C(I);if(f)return{error:j,result:M};if(j)throw new xh({body:I,error:j,url:v});return M},retryCount:S,retryDelay:l,timeout:T,type:"http"},{fetchOptions:s,url:v})}}const kw=[{inputs:[{internalType:"address",name:"token_",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"InvalidShortString",type:"error"},{inputs:[{internalType:"string",name:"str",type:"string"}],name:"StringTooLong",type:"error"},{anonymous:!1,inputs:[],name:"EIP712DomainChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Initiated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"secret",type:"bytes"}],name:"Redeemed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"Refunded",type:"event"},{inputs:[],name:"eip712Domain",outputs:[{internalType:"bytes1",name:"fields",type:"bytes1"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"},{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"address",name:"verifyingContract",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"uint256[]",name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"}],name:"initiate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"initiateWithSignature",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"instantRefund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"expiry",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],internalType:"struct HTLC.InitWithSig[]",name:"inits",type:"tuple[]"},{components:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"secret",type:"bytes"}],internalType:"struct HTLC.Redeem[]",name:"redeems",type:"tuple[]"},{components:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],internalType:"struct HTLC.Refund[]",name:"refunds",type:"tuple[]"}],name:"multicall",outputs:[{internalType:"bool[]",name:"results",type:"bool[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"",type:"bytes32"}],name:"orders",outputs:[{internalType:"bool",name:"isFulfilled",type:"bool"},{internalType:"address",name:"initiator",type:"address"},{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"initiatedAt",type:"uint256"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"secret",type:"bytes"}],name:"redeem",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"refund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"token",outputs:[{internalType:"contract IERC20",name:"",type:"address"}],stateMutability:"view",type:"function"}],_T=[{inputs:[{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"InvalidShortString",type:"error"},{inputs:[],name:"NativeHTLC__DuplicateOrder",type:"error"},{inputs:[],name:"NativeHTLC__IncorrectFundsRecieved",type:"error"},{inputs:[],name:"NativeHTLC__IncorrectSecret",type:"error"},{inputs:[],name:"NativeHTLC__InsufficientBalance",type:"error"},{inputs:[],name:"NativeHTLC__InvalidRedeemerSignature",type:"error"},{inputs:[],name:"NativeHTLC__OrderFulfilled",type:"error"},{inputs:[],name:"NativeHTLC__OrderNotExpired",type:"error"},{inputs:[],name:"NativeHTLC__OrderNotInitiated",type:"error"},{inputs:[],name:"NativeHTLC__SameInitiatorAndRedeemer",type:"error"},{inputs:[],name:"NativeHTLC__ZeroAddressInitiator",type:"error"},{inputs:[],name:"NativeHTLC__ZeroAddressRedeemer",type:"error"},{inputs:[],name:"NativeHTLC__ZeroAmount",type:"error"},{inputs:[],name:"NativeHTLC__ZeroTimelock",type:"error"},{inputs:[{internalType:"string",name:"str",type:"string"}],name:"StringTooLong",type:"error"},{anonymous:!1,inputs:[],name:"EIP712DomainChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Initiated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"secret",type:"bytes"}],name:"Redeemed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"Refunded",type:"event"},{inputs:[],name:"eip712Domain",outputs:[{internalType:"bytes1",name:"fields",type:"bytes1"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"},{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"address",name:"verifyingContract",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"uint256[]",name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address payable",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"}],name:"initiate",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address payable",name:"initiator",type:"address"},{internalType:"address payable",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"}],name:"initiateOnBehalf",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"instantRefund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"instantRefundDigest",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"",type:"bytes32"}],name:"orders",outputs:[{internalType:"bool",name:"isFulfilled",type:"bool"},{internalType:"address payable",name:"initiator",type:"address"},{internalType:"address payable",name:"redeemer",type:"address"},{internalType:"uint256",name:"initiatedAt",type:"uint256"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"secret",type:"bytes"}],name:"redeem",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"refund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"token",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}];class ui{constructor(e,r){this.auth=e,this.url=r instanceof m.Url?r:new m.Url(r)}async initiate(e,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return m.Err(n.error);const s=await m.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:r}),headers:{...n.val,"Content-Type":"application/json"}});return s.error||!s.result?m.Err(s.error||"Initiate failed"):m.Ok(s.result)}catch(n){return m.Err(String(n))}}async redeem(e,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return m.Err(n.error);const s=await m.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e).addSearchParams({action:"redeem"}),{body:JSON.stringify({secret:m.trim0x(r)}),headers:{...n.val,"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return s.error?m.Err(s.error):s.result?m.Ok(s.result):m.Err("Redeem: No result found")}catch(n){return m.Err(String(n))}}}const IT=async(t,e)=>{if(!t.account)return m.Err("No account found");try{const n=await Kh({address:m.with0x(e.htlc),abi:_T,client:t}).write.initiate([m.with0x(e.redeemer),e.timelock,e.amount,m.with0x(e.secretHash)],{account:t.account,chain:t.chain,value:e.amount}),s=await m.waitForTransactionReceipt(t,n);return s.ok?!s.val||s.val.status!=="success"?m.Err("Native initiate transaction failed"):m.Ok(n):m.Err(s.error)}catch(r){return Qd(r)?m.Ok("already initiated"):m.Err("Failed to initiate on native HTLC",String(r))}},PT=async(t,e,r,n)=>{if(!t.account)return m.Err("No account found");try{const s=Kh({address:m.with0x(n.htlc),abi:kw,client:t}),i=await m.checkAllowanceAndApprove(Number(n.amount),n.token,n.htlc,t);if(!i.ok)return m.Err(i.error);const a=await s.read.eip712Domain(),o=await t.signTypedData({account:t.account,domain:{name:a[1],version:a[2],chainId:Number(a[3]),verifyingContract:a[4]},types:{Initiate:[{name:"redeemer",type:"address"},{name:"timelock",type:"uint256"},{name:"amount",type:"uint256"},{name:"secretHash",type:"bytes32"}]},primaryType:"Initiate",message:{redeemer:m.with0x(n.redeemer),timelock:n.timelock,amount:n.amount,secretHash:m.with0x(n.secretHash)}}),c=new ui(r,e),u=await Fm({wallet:t,attempt:()=>c.initiate(n.orderId,o)});if(u)return m.Ok(u);const l=await s.write.initiate([m.with0x(n.redeemer),n.timelock,n.amount,m.with0x(n.secretHash)],{account:t.account,chain:t.chain}),f=await m.waitForTransactionReceipt(t,l);return f.ok?!f.val||f.val.status!=="success"?m.Err("Failed to initiate (fallback)"):m.Ok(l):m.Err(f.error)}catch(s){return Qd(s)?m.Ok("already initiated"):m.Err("Failed to initiate on ERC20 HTLC",String(s))}},OT=async(t,e)=>{if(!t.account)return m.Err("No account found");try{const r=await t.sendTransaction({account:t.account,to:m.with0x(e.to),value:BigInt(e.value),data:m.with0x(e.data),gas:BigInt(e.gas_limit),chain:t.chain}),n=await m.waitForTransactionReceipt(t,r);return n.ok?!n.val||n.val.status!=="success"?m.Err("Approval transaction failed"):m.Ok(r):m.Err(n.error)}catch(r){return m.Err("Failed to execute approval: "+String(r))}},BT={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}},CT={block:zS({format(t){var r;return{transactions:(r=t.transactions)==null?void 0:r.map(n=>{if(typeof n=="string")return n;const s=Bo(n);return s.typeHex==="0x7e"&&(s.isSystemTx=n.isSystemTx,s.mint=n.mint?lt(n.mint):void 0,s.sourceHash=n.sourceHash,s.type="deposit"),s}),stateRoot:t.stateRoot}}}),transaction:LS({format(t){const e={};return t.type==="0x7e"&&(e.isSystemTx=t.isSystemTx,e.mint=t.mint?lt(t.mint):void 0,e.sourceHash=t.sourceHash,e.type="deposit"),e}}),transactionReceipt:tx({format(t){return{l1GasPrice:t.l1GasPrice?lt(t.l1GasPrice):null,l1GasUsed:t.l1GasUsed?lt(t.l1GasUsed):null,l1Fee:t.l1Fee?lt(t.l1Fee):null,l1FeeScalar:t.l1FeeScalar?Number(t.l1FeeScalar):null}}})};function RT(t,e){return FT(t)?UT(t):$x(t,e)}const NT={transaction:RT};function UT(t){MT(t);const{sourceHash:e,data:r,from:n,gas:s,isSystemTx:i,mint:a,to:o,value:c}=t,u=[e,n,o??"0x",a?Ft(a):"0x",c?Ft(c):"0x",s?Ft(s):"0x",i?"0x1":"0x",r??"0x"];return jr(["0x7e",bs(u)])}function FT(t){return t.type==="deposit"||typeof t.sourceHash<"u"}function MT(t){const{from:e,to:r}=t;if(e&&!ct(e))throw new $t({address:e});if(r&&!ct(r))throw new $t({address:r})}const Ki={blockTime:2e3,contracts:BT,formatters:CT,serializers:NT},$T=ft({id:42161,name:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:250,rpcUrls:{default:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://arbiscan.io",apiUrl:"https://api.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:7654707}}}),jT=ft({id:421614,name:"Arbitrum Sepolia",blockTime:250,nativeCurrency:{name:"Arbitrum Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia-rollup.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://sepolia.arbiscan.io",apiUrl:"https://api-sepolia.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:81930}},testnet:!0}),Tw=ft({id:5042002,name:"Arc Testnet",nativeCurrency:{name:"USDC",symbol:"USDC",decimals:18},rpcUrls:{default:{http:["https://rpc.testnet.arc.network","https://rpc.quicknode.testnet.arc.network","https://rpc.blockdaemon.testnet.arc.network"],webSocket:["wss://rpc.testnet.arc.network","wss://rpc.quicknode.testnet.arc.network"]}},blockExplorers:{default:{name:"ArcScan",url:"https://testnet.arcscan.app",apiUrl:"https://testnet.arcscan.app/api"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:0}},testnet:!0}),pa=1,_w=ft({...Ki,id:8453,name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://basescan.org",apiUrl:"https://api.basescan.org/api"}},contracts:{...Ki.contracts,disputeGameFactory:{[pa]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[pa]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[pa]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[pa]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:pa});({..._w});const ya=11155111,Iw=ft({...Ki,id:84532,network:"base-sepolia",name:"Base Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://sepolia.basescan.org",apiUrl:"https://api-sepolia.basescan.org/api"}},contracts:{...Ki.contracts,disputeGameFactory:{[ya]:{address:"0xd6E6dBf4F7EA0ac412fD8b65ED297e64BB7a06E1"}},l2OutputOracle:{[ya]:{address:"0x84457ca9D0163FbC4bbfe4Dfbb20ba46e48DF254"}},portal:{[ya]:{address:"0x49f53e41452c74589e85ca1677426ba426459e85",blockCreated:4446677}},l1StandardBridge:{[ya]:{address:"0xfd0Bf71F60660E2f608ed56e1659C450eB113120",blockCreated:4446677}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:1059647}},testnet:!0,sourceId:ya});({...Iw});const HT=ft({id:80094,name:"Berachain",blockTime:2e3,nativeCurrency:{decimals:18,name:"BERA Token",symbol:"BERA"},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:0},ensRegistry:{address:"0x5b22280886a2f5e09a49bea7e320eab0e5320e28",blockCreated:877007},ensUniversalResolver:{address:"0x4D41762915F83c76EcaF6776d9b08076aA32b492",blockCreated:9310021}},rpcUrls:{default:{http:["https://rpc.berachain.com"]}},blockExplorers:{default:{name:"Berascan",url:"https://berascan.com"}},ensTlds:[".bera"],testnet:!1}),LT=ft({id:80084,name:"Berachain bArtio",nativeCurrency:{decimals:18,name:"BERA Token",symbol:"BERA"},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:109269},ensRegistry:{address:"0xB0eef18971290b333450586D33dcA6cE122651D2",blockCreated:7736794},ensUniversalResolver:{address:"0x41692Ef1EA0C79E6b73077E4A67572D2BDbD7057",blockCreated:7736795}},ensTlds:[".bera"],rpcUrls:{default:{http:["https://bartio.rpc.berachain.com"]}},blockExplorers:{default:{name:"Berachain bArtio Beratrail",url:"https://bartio.beratrail.io"}},testnet:!0}),DT=ft({id:56,name:"BNB Smart Chain",blockTime:750,nativeCurrency:{decimals:18,name:"BNB",symbol:"BNB"},rpcUrls:{default:{http:["https://56.rpc.thirdweb.com"]}},blockExplorers:{default:{name:"BscScan",url:"https://bscscan.com",apiUrl:"https://api.bscscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:15921452}}}),zT=ft({id:97,name:"BNB Smart Chain Testnet",nativeCurrency:{decimals:18,name:"BNB",symbol:"tBNB"},rpcUrls:{default:{http:["https://data-seed-prebsc-1-s1.bnbchain.org:8545"]}},blockExplorers:{default:{name:"BscScan",url:"https://testnet.bscscan.com",apiUrl:"https://api-testnet.bscscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:17422483}},testnet:!0}),VT=ft({id:5115,name:"Citrea Testnet",nativeCurrency:{name:"cBTC",symbol:"cBTC",decimals:18},rpcUrls:{default:{http:["https://rpc.testnet.citrea.xyz"]}},blockExplorers:{default:{name:"Citrea Explorer",url:"https://explorer.testnet.citrea.xyz",apiUrl:"https://explorer.testnet.citrea.xyz/api"}},testnet:!0}),GT=ft({id:1116,name:"Core Dao",nativeCurrency:{decimals:18,name:"Core",symbol:"CORE"},rpcUrls:{default:{http:["https://rpc.coredao.org"]}},blockExplorers:{default:{name:"CoreDao",url:"https://scan.coredao.org"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:11907934}},testnet:!1}),qT=1,WT=ft({id:21e6,name:"Corn",nativeCurrency:{decimals:18,name:"Bitcorn",symbol:"BTCN"},rpcUrls:{default:{http:["https://21000000.rpc.thirdweb.com"]}},blockExplorers:{default:{name:"Corn Explorer",url:"https://cornscan.io",apiUrl:"https://api.routescan.io/v2/network/mainnet/evm/21000000/etherscan/api"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:3228}},sourceId:qT}),KT=ft({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:12e3,rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensUniversalResolver:{address:"0xeeeeeeee14d718c2b47d9923deab1335e144eeee",blockCreated:23085558},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),XT=ft({id:10143,name:"Monad Testnet",blockTime:400,nativeCurrency:{name:"Testnet MON Token",symbol:"MON",decimals:18},rpcUrls:{default:{http:["https://testnet-rpc.monad.xyz"]}},blockExplorers:{default:{name:"Monad Testnet explorer",url:"https://testnet.monadexplorer.com"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:251449}},testnet:!0}),YT=ft({id:11155111,name:"Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://11155111.rpc.thirdweb.com"]}},blockExplorers:{default:{name:"Etherscan",url:"https://sepolia.etherscan.io",apiUrl:"https://api-sepolia.etherscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:751532},ensUniversalResolver:{address:"0xeeeeeeee14d718c2b47d9923deab1335e144eeee",blockCreated:8928790}},testnet:!0}),cc=1,JT=ft({...Ki,id:130,name:"Unichain",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:1e3,rpcUrls:{default:{http:["https://mainnet.unichain.org/"]}},blockExplorers:{default:{name:"Uniscan",url:"https://uniscan.xyz",apiUrl:"https://api.uniscan.xyz/api"}},contracts:{...Ki.contracts,multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:0},disputeGameFactory:{[cc]:{address:"0x2F12d621a16e2d3285929C9996f478508951dFe4"}},portal:{[cc]:{address:"0x0bd48f6B86a26D3a217d0Fa6FfE2B491B956A7a2"}},l1StandardBridge:{[cc]:{address:"0x81014F44b0a345033bB2b3B21C7a1A308B35fEeA"}}},sourceId:cc}),ZT={...YT,rpcUrls:{default:{http:["https://ethereum-sepolia-rpc.publicnode.com"]}}},Pw={id:3637,name:"Botanix",nativeCurrency:{name:"Botanix",symbol:"BOTX",decimals:18},blockExplorers:{default:{name:"Botanix Explorer",url:"https://botanixscan.io/"}},rpcUrls:{default:{http:["https://rpc.botanixlabs.com/"]}}},Cd={id:998,name:"Hyperliquid EVM Testnet",nativeCurrency:{name:"Hyperliquid",symbol:"HYPE",decimals:18},blockExplorers:{default:{name:"Hyperliquid Explorer",url:"https://testnet.purrsec.com/"}},rpcUrls:{default:{http:["https://rpc.hyperliquid-testnet.xyz/evm"]}}},Rd={id:999,name:"HyperEVM",nativeCurrency:{name:"Hyperliquid",symbol:"HYPE",decimals:18},blockExplorers:{default:{name:"Hyperliquid Explorer",url:"https://hyperscan.gas.zip/"}},rpcUrls:{default:{http:["https://rpc.hyperliquid.xyz/evm"]}}},Ow={id:8150,name:"Alpen Network",nativeCurrency:{name:"Signet bitcoin",symbol:"sBTC",decimals:18},blockExplorers:{default:{name:"Alpen Explorer",url:"https://explorer.pectra-testnet.alpenlabs.io"}},rpcUrls:{default:{http:["https://rpc.pectra-testnet.alpenlabs.io"]}}},QT={id:143,name:"Monad",nativeCurrency:{name:"Monad",symbol:"MON",decimals:18},blockExplorers:{default:{name:"Monad Explorer",url:"https://monadvision.com/"}},rpcUrls:{default:{http:["https://rpc1.monad.xyz"]}}},e_={id:4114,name:"Citrea Mainnet",nativeCurrency:{name:"Citrea Bitcoin",symbol:"cBTC",decimals:18},rpcUrls:{default:{http:["https://rpc.mainnet.citrea.xyz"]}},blockExplorers:{default:{name:"Citrea Explorer",url:"https://explorer.mainnet.citrea.xyz",apiUrl:"https://explorer.mainnet.citrea.xyz/api"}},testnet:!1},Bw={id:4326,name:"MegaETH",nativeCurrency:{name:"MegaETH",symbol:"MEGA",decimals:18},rpcUrls:{default:{http:["https://mainnet.megaeth.com/rpc"]}},blockExplorers:{default:{name:"MegaETH Explorer",url:"https://megaeth.blockscout.com/"}},testnet:!1},_u={ethereum:KT,arbitrum:$T,ethereum_sepolia:ZT,arbitrum_sepolia:jT,ethereum_localnet:D.EthereumLocalnet,arbitrum_localnet:D.ArbitrumLocalnet,base_sepolia:Iw,base:_w,bera_testnet:LT,citrea:e_,citrea_testnet:VT,core:GT,bera:HT,monad:QT,monad_testnet:XT,hyperliquid_testnet:Cd,hyperevm:Rd,unichain:JT,corn:WT,botanix:Pw,bnbchain:DT,bnbchain_testnet:zT,alpen_testnet:Ow,hypercore:{},hypercore_testnet:{},arc_testnet:Tw,hyperliquid:Rd,megaeth:Bw,hyperevm_testnet:Cd},Cw=t=>{for(const[e,r]of Object.entries(_u))if(r.id===t)return e;return null},Nd=async(t,e)=>{var s,i,a;const r=_u[t],n=await e.getChainId();if(r)try{if(r.id===n)return m.Ok({message:"Already on the network",walletClient:e});await e.switchChain({id:r.id});const o=Sl({account:e.account,chain:r,transport:sy(e.transport)});return m.Ok({message:"Switched chain",walletClient:o})}catch(o){if(t_(o))if(o.code===4902||o.code===-32603)try{await e.addChain({chain:r});const c=Sl({account:e.account,chain:r,transport:sy(e.transport)});return m.Ok({message:"Added network",walletClient:c})}catch{return m.Err("Failed to add network")}else if((i=(s=o.body)==null?void 0:s.method)!=null&&i.includes("wallet_switchEthereumChain")||(a=o.message)!=null&&a.includes("wallet_switchEthereumChain")){const c=Sl({account:e.account,chain:r,transport:xw()});return m.Ok({message:"Added network",walletClient:c})}else return m.Err("Failed to switch network");else return m.Err("Failed to switch network")}else return m.Err("Chain not supported")},t_=t=>typeof t=="object"&&t!=null&&("code"in t||"message"in t||"body"in t),r_=async(t,e)=>{if(!t.account)return m.Err("No account found");try{const r=await t.sendTransaction({account:t.account,to:m.with0x(e.to),value:BigInt(e.value),data:m.with0x(e.data),gas:BigInt(e.gas_limit),chain:t.chain}),n=await m.waitForTransactionReceipt(t,r);return n.ok?!n.val||n.val.status!=="success"?m.Err("Hypercore to EVM bridge transaction failed"):m.Ok(r):m.Err(n.error)}catch(r){return m.Err("Failed to execute hypercore to evm bridge: "+String(r))}};class Rw{constructor(e,r,n){this.wallet=r,this.auth=n,this.url=e instanceof m.Url?e:new m.Url(e),this.relayer=new ui(this.auth,this.url)}get htlcActorAddress(){if(!this.wallet.account)throw new Error("No account found");return this.wallet.account.address}async initiate(e){if(D.isEvmOrderResponse(e))return this.initiateFromAPI(e);if(!this.wallet.account)return m.Err("No account found");if(!D.isEVM(e.source_swap.chain))return m.Err("Not an EVM chain");if(this.wallet.account.address.toLowerCase()!==e.source_swap.initiator.toLowerCase())return m.Err("Account address and order initiator mismatch");const r=e.source_swap.chain,n=await Nd(r,this.wallet);if(!n.ok)return m.Err(n.error);this.wallet=n.val.walletClient;const{source_swap:s}=e;if(!s.amount||!s.timelock||!s.redeemer||!s.secret_hash)return m.Err("Invalid order");const i=await $i(s.asset,this.url,this.auth);if(!i.ok)return m.Err(i.error);const a=D.ChainAsset.fromString(s.asset),o={redeemer:m.with0x(s.redeemer),timelock:BigInt(s.timelock),amount:BigInt(s.amount),secretHash:m.with0x(s.secret_hash)};return D.isEvmNativeToken(a.chain,a.symbol)?IT(this.wallet,{...o,htlc:i.val.htlcAddress}):PT(this.wallet,this.url,this.auth,{...o,htlc:i.val.htlcAddress,token:i.val.tokenAddress,orderId:e.order_id})}async initiateFromAPI(e){const r=Cw(e.initiate_transaction.chain_id);if(!r)return m.Err("Unsupported chain");const n=await Nd(r,this.wallet);if(!n.ok)return m.Err(n.error);if(this.wallet=n.val.walletClient,!this.wallet.account)return m.Err("No account found");if(!e.typed_data){const a=e.initiate_transaction,o=await this.wallet.sendTransaction({account:this.wallet.account,chain:this.wallet.chain,to:m.with0x(a.to),value:BigInt(a.value),data:m.with0x(a.data),gas:BigInt(a.gas_limit)}),c=await m.waitForTransactionReceipt(this.wallet,o);return c.ok?!c.val||c.val.status!=="success"?m.Err("Native initiate transaction failed"):m.Ok(o):m.Err(c.error)}if(e.core_to_evm_transfer){const a=await r_(this.wallet,e.core_to_evm_transfer);if(a.error)return m.Err(`Internal bridge failed: ${a.error}`);console.log("Internal bridge completed:",a.val)}if(e.approval_transaction){const a=await OT(this.wallet,e.approval_transaction);if(a.error)return m.Err(`Approval failed: ${a.error}`);console.log("Approval transaction completed:",a.val)}const s=await this.wallet.signTypedData({account:this.wallet.account,...e.typed_data}),i=await Fm({wallet:this.wallet,attempt:()=>this.relayer.initiate(e.order_id,s)});if(i)return m.Ok(i);try{const a=Kh({address:m.with0x(e.initiate_transaction.to),abi:kw,client:this.wallet}),o=e.typed_data.message,c=await a.write.initiate([m.with0x(o.redeemer),BigInt(o.timelock),BigInt(o.amount),m.with0x(o.secretHash)],{account:this.wallet.account,chain:this.wallet.chain}),u=await m.waitForTransactionReceipt(this.wallet,c);return u.ok?!u.val||u.val.status!=="success"?m.Err("Failed to initiate via contract"):m.Ok(c):m.Err(u.error)}catch(a){return Qd(a)?m.Ok("already initiated"):m.Err(`Failed to initiate via contract: ${String(a)}`)}}async redeem(e,r){const n=await this.relayer.redeem(e.order_id,r);if(n.error)return m.Err(n.error);try{const s=await this.relayer.redeem(e.order_id,r);if(s.error)return m.Err(s.error);const i=_u[e.destination_swap.chain],o=await cT({chain:i,transport:xw()}).waitForTransactionReceipt({hash:s.val,confirmations:1,timeout:3e5});return o&&o.status==="success"?m.Ok(s.val?s.val:"Redeem hash not found"):m.Err("Redeem failed: Transaction receipt not successful")}catch(s){return m.Err(String(s))}}async refund(){return m.Err("Refund not supported")}}const Nw=[{name:"LockingContract",type:"impl",interface_name:"src::mintable_lock_interface::ILockingContract"},{name:"src::mintable_lock_interface::ILockingContract",type:"interface",items:[{name:"set_locking_contract",type:"function",inputs:[{name:"locking_contract",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"get_locking_contract",type:"function",inputs:[],outputs:[{type:"core::starknet::contract_address::ContractAddress"}],state_mutability:"view"}]},{name:"LockAndDelegate",type:"impl",interface_name:"src::mintable_lock_interface::ILockAndDelegate"},{name:"core::integer::u256",type:"struct",members:[{name:"low",type:"core::integer::u128"},{name:"high",type:"core::integer::u128"}]},{name:"src::mintable_lock_interface::ILockAndDelegate",type:"interface",items:[{name:"lock_and_delegate",type:"function",inputs:[{name:"delegatee",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"},{name:"lock_and_delegate_by_sig",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"delegatee",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"},{name:"nonce",type:"core::felt252"},{name:"expiry",type:"core::integer::u64"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"}]},{name:"MintableToken",type:"impl",interface_name:"src::mintable_token_interface::IMintableToken"},{name:"src::mintable_token_interface::IMintableToken",type:"interface",items:[{name:"permissioned_mint",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"},{name:"permissioned_burn",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"}]},{name:"MintableTokenCamelImpl",type:"impl",interface_name:"src::mintable_token_interface::IMintableTokenCamel"},{name:"src::mintable_token_interface::IMintableTokenCamel",type:"interface",items:[{name:"permissionedMint",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"},{name:"permissionedBurn",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"}]},{name:"Replaceable",type:"impl",interface_name:"src::replaceability_interface::IReplaceable"},{name:"core::array::Span::<core::felt252>",type:"struct",members:[{name:"snapshot",type:"@core::array::Array::<core::felt252>"}]},{name:"src::replaceability_interface::EICData",type:"struct",members:[{name:"eic_hash",type:"core::starknet::class_hash::ClassHash"},{name:"eic_init_data",type:"core::array::Span::<core::felt252>"}]},{name:"core::option::Option::<src::replaceability_interface::EICData>",type:"enum",variants:[{name:"Some",type:"src::replaceability_interface::EICData"},{name:"None",type:"()"}]},{name:"core::bool",type:"enum",variants:[{name:"False",type:"()"},{name:"True",type:"()"}]},{name:"src::replaceability_interface::ImplementationData",type:"struct",members:[{name:"impl_hash",type:"core::starknet::class_hash::ClassHash"},{name:"eic_data",type:"core::option::Option::<src::replaceability_interface::EICData>"},{name:"final",type:"core::bool"}]},{name:"src::replaceability_interface::IReplaceable",type:"interface",items:[{name:"get_upgrade_delay",type:"function",inputs:[],outputs:[{type:"core::integer::u64"}],state_mutability:"view"},{name:"get_impl_activation_time",type:"function",inputs:[{name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}],outputs:[{type:"core::integer::u64"}],state_mutability:"view"},{name:"add_new_implementation",type:"function",inputs:[{name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}],outputs:[],state_mutability:"external"},{name:"remove_implementation",type:"function",inputs:[{name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}],outputs:[],state_mutability:"external"},{name:"replace_to",type:"function",inputs:[{name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}],outputs:[],state_mutability:"external"}]},{name:"AccessControlImplExternal",type:"impl",interface_name:"src::access_control_interface::IAccessControl"},{name:"src::access_control_interface::IAccessControl",type:"interface",items:[{name:"has_role",type:"function",inputs:[{name:"role",type:"core::felt252"},{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::bool"}],state_mutability:"view"},{name:"get_role_admin",type:"function",inputs:[{name:"role",type:"core::felt252"}],outputs:[{type:"core::felt252"}],state_mutability:"view"}]},{name:"RolesImpl",type:"impl",interface_name:"src::roles_interface::IMinimalRoles"},{name:"src::roles_interface::IMinimalRoles",type:"interface",items:[{name:"is_governance_admin",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::bool"}],state_mutability:"view"},{name:"is_upgrade_governor",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::bool"}],state_mutability:"view"},{name:"register_governance_admin",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"remove_governance_admin",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"register_upgrade_governor",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"remove_upgrade_governor",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"renounce",type:"function",inputs:[{name:"role",type:"core::felt252"}],outputs:[],state_mutability:"external"}]},{name:"ERC20Impl",type:"impl",interface_name:"openzeppelin::token::erc20::interface::IERC20"},{name:"openzeppelin::token::erc20::interface::IERC20",type:"interface",items:[{name:"name",type:"function",inputs:[],outputs:[{type:"core::felt252"}],state_mutability:"view"},{name:"symbol",type:"function",inputs:[],outputs:[{type:"core::felt252"}],state_mutability:"view"},{name:"decimals",type:"function",inputs:[],outputs:[{type:"core::integer::u8"}],state_mutability:"view"},{name:"total_supply",type:"function",inputs:[],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"balance_of",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"allowance",type:"function",inputs:[{name:"owner",type:"core::starknet::contract_address::ContractAddress"},{name:"spender",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"transfer",type:"function",inputs:[{name:"recipient",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"transfer_from",type:"function",inputs:[{name:"sender",type:"core::starknet::contract_address::ContractAddress"},{name:"recipient",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"approve",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"}]},{name:"ERC20CamelOnlyImpl",type:"impl",interface_name:"openzeppelin::token::erc20::interface::IERC20CamelOnly"},{name:"openzeppelin::token::erc20::interface::IERC20CamelOnly",type:"interface",items:[{name:"totalSupply",type:"function",inputs:[],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"balanceOf",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"transferFrom",type:"function",inputs:[{name:"sender",type:"core::starknet::contract_address::ContractAddress"},{name:"recipient",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"}]},{name:"constructor",type:"constructor",inputs:[{name:"name",type:"core::felt252"},{name:"symbol",type:"core::felt252"},{name:"decimals",type:"core::integer::u8"},{name:"initial_supply",type:"core::integer::u256"},{name:"recipient",type:"core::starknet::contract_address::ContractAddress"},{name:"permitted_minter",type:"core::starknet::contract_address::ContractAddress"},{name:"provisional_governance_admin",type:"core::starknet::contract_address::ContractAddress"},{name:"upgrade_delay",type:"core::integer::u64"}]},{name:"increase_allowance",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"added_value",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"decrease_allowance",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"subtracted_value",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"increaseAllowance",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"addedValue",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"decreaseAllowance",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"subtractedValue",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{kind:"struct",name:"src::strk::erc20_lockable::ERC20Lockable::Transfer",type:"event",members:[{kind:"data",name:"from",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"to",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"value",type:"core::integer::u256"}]},{kind:"struct",name:"src::strk::erc20_lockable::ERC20Lockable::Approval",type:"event",members:[{kind:"data",name:"owner",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"spender",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"value",type:"core::integer::u256"}]},{kind:"struct",name:"src::replaceability_interface::ImplementationAdded",type:"event",members:[{kind:"data",name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}]},{kind:"struct",name:"src::replaceability_interface::ImplementationRemoved",type:"event",members:[{kind:"data",name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}]},{kind:"struct",name:"src::replaceability_interface::ImplementationReplaced",type:"event",members:[{kind:"data",name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}]},{kind:"struct",name:"src::replaceability_interface::ImplementationFinalized",type:"event",members:[{kind:"data",name:"impl_hash",type:"core::starknet::class_hash::ClassHash"}]},{kind:"struct",name:"src::access_control_interface::RoleGranted",type:"event",members:[{kind:"data",name:"role",type:"core::felt252"},{kind:"data",name:"account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"sender",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::access_control_interface::RoleRevoked",type:"event",members:[{kind:"data",name:"role",type:"core::felt252"},{kind:"data",name:"account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"sender",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::access_control_interface::RoleAdminChanged",type:"event",members:[{kind:"data",name:"role",type:"core::felt252"},{kind:"data",name:"previous_admin_role",type:"core::felt252"},{kind:"data",name:"new_admin_role",type:"core::felt252"}]},{kind:"struct",name:"src::roles_interface::GovernanceAdminAdded",type:"event",members:[{kind:"data",name:"added_account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"added_by",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::roles_interface::GovernanceAdminRemoved",type:"event",members:[{kind:"data",name:"removed_account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"removed_by",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::roles_interface::UpgradeGovernorAdded",type:"event",members:[{kind:"data",name:"added_account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"added_by",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::roles_interface::UpgradeGovernorRemoved",type:"event",members:[{kind:"data",name:"removed_account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"removed_by",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"enum",name:"src::strk::erc20_lockable::ERC20Lockable::Event",type:"event",variants:[{kind:"nested",name:"Transfer",type:"src::strk::erc20_lockable::ERC20Lockable::Transfer"},{kind:"nested",name:"Approval",type:"src::strk::erc20_lockable::ERC20Lockable::Approval"},{kind:"nested",name:"ImplementationAdded",type:"src::replaceability_interface::ImplementationAdded"},{kind:"nested",name:"ImplementationRemoved",type:"src::replaceability_interface::ImplementationRemoved"},{kind:"nested",name:"ImplementationReplaced",type:"src::replaceability_interface::ImplementationReplaced"},{kind:"nested",name:"ImplementationFinalized",type:"src::replaceability_interface::ImplementationFinalized"},{kind:"nested",name:"RoleGranted",type:"src::access_control_interface::RoleGranted"},{kind:"nested",name:"RoleRevoked",type:"src::access_control_interface::RoleRevoked"},{kind:"nested",name:"RoleAdminChanged",type:"src::access_control_interface::RoleAdminChanged"},{kind:"nested",name:"GovernanceAdminAdded",type:"src::roles_interface::GovernanceAdminAdded"},{kind:"nested",name:"GovernanceAdminRemoved",type:"src::roles_interface::GovernanceAdminRemoved"},{kind:"nested",name:"UpgradeGovernorAdded",type:"src::roles_interface::UpgradeGovernorAdded"},{kind:"nested",name:"UpgradeGovernorRemoved",type:"src::roles_interface::UpgradeGovernorRemoved"}]}],Uw=async(t,e,r,n,s)=>{try{const i=await Pa(t.address,e,r,s);if(!i.ok)return m.Err(i.error);if(i.val>=n)return m.Ok("Allowance already approved");const o=Qe.cairo.uint256(BigInt(n)),c=await t.execute([{contractAddress:m.with0x(e),entrypoint:"approve",calldata:[m.with0x(r),o.low,o.high]}]);await s.waitForTransaction(c.transaction_hash,{retryInterval:3e3,successStates:[Qe.TransactionExecutionStatus.SUCCEEDED]}),await m.sleep(2e3);for(let u=0;u<20;u++){const l=await Pa(t.address,e,r,s);if(!l.ok)return m.Err(l.error);if(l.val>=n)return m.Ok(c.transaction_hash);await m.sleep(2e3);let f=0n;for(let p=0;p<20;p++){const d=await Pa(t.address,e,r,s);if(!d.ok)return m.Err(d.error);if(f=d.val,f>=n)break;await m.sleep(2e3)}return f<n?m.Err("Allowance not approved"):m.Ok(c.transaction_hash)}return m.Err("Allowance not approved after transaction.")}catch(i){return m.Err(`Failed to check or approve allowance: ${i instanceof Error?i.message:String(i)}`)}},Pa=async(t,e,r,n)=>{try{const i=await new Qe.Contract({abi:Nw,address:m.with0x(e),providerOrAccount:n}).call("allowance",[m.with0x(t),m.with0x(r)]);return m.Ok(BigInt((i==null?void 0:i.toString())||"0"))}catch(s){return m.Err(`Failed to check allowance: ${s instanceof Error?s.message:String(s)}`)}},Fw=async(t,e,r,n,s)=>{const i=await Pa(t,e,r,n);return i.ok?m.Ok(i.val>=s):m.Err(i.error)},Mw=[{type:"impl",name:"HTLC",interface_name:"starknet_htlc::interface::IHTLC"},{type:"struct",name:"core::integer::u256",members:[{name:"low",type:"core::integer::u128"},{name:"high",type:"core::integer::u128"}]},{type:"struct",name:"starknet_htlc::htlc::HTLC::Order",members:[{name:"fulfilled_at",type:"core::integer::u128"},{name:"initiator",type:"core::starknet::contract_address::ContractAddress"},{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"initiated_at",type:"core::integer::u128"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"}]},{type:"interface",name:"starknet_htlc::interface::IHTLC",items:[{type:"function",name:"token",inputs:[],outputs:[{type:"core::starknet::contract_address::ContractAddress"}],state_mutability:"view"},{type:"function",name:"get_order",inputs:[{name:"order_id",type:"core::felt252"}],outputs:[{type:"starknet_htlc::htlc::HTLC::Order"}],state_mutability:"view"},{type:"function",name:"initiate",inputs:[{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"},{name:"secret_hash",type:"[core::integer::u128; 2]"}],outputs:[],state_mutability:"external"},{type:"function",name:"initiate_with_destination_data",inputs:[{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"},{name:"secret_hash",type:"[core::integer::u128; 2]"},{name:"destination_data",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"},{type:"function",name:"initiate_on_behalf",inputs:[{name:"initiator",type:"core::starknet::contract_address::ContractAddress"},{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"},{name:"secret_hash",type:"[core::integer::u128; 2]"}],outputs:[],state_mutability:"external"},{type:"function",name:"initiate_on_behalf_with_destination_data",inputs:[{name:"initiator",type:"core::starknet::contract_address::ContractAddress"},{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"},{name:"secret_hash",type:"[core::integer::u128; 2]"},{name:"destination_data",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"},{type:"function",name:"initiate_with_signature",inputs:[{name:"initiator",type:"core::starknet::contract_address::ContractAddress"},{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"},{name:"secret_hash",type:"[core::integer::u128; 2]"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"},{type:"function",name:"redeem",inputs:[{name:"order_id",type:"core::felt252"},{name:"secret",type:"[core::integer::u32; 8]"}],outputs:[],state_mutability:"external"},{type:"function",name:"refund",inputs:[{name:"order_id",type:"core::felt252"}],outputs:[],state_mutability:"external"},{type:"function",name:"instant_refund",inputs:[{name:"order_id",type:"core::felt252"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"}]},{type:"constructor",name:"constructor",inputs:[{name:"token",type:"core::starknet::contract_address::ContractAddress"}]},{type:"event",name:"starknet_htlc::interface::events::Initiated",kind:"struct",members:[{name:"order_id",type:"core::felt252",kind:"key"},{name:"secret_hash",type:"[core::integer::u128; 2]",kind:"data"},{name:"amount",type:"core::integer::u256",kind:"data"}]},{type:"event",name:"starknet_htlc::interface::events::Redeemed",kind:"struct",members:[{name:"order_id",type:"core::felt252",kind:"key"},{name:"secret_hash",type:"[core::integer::u128; 2]",kind:"data"},{name:"secret",type:"[core::integer::u32; 8]",kind:"data"}]},{type:"event",name:"starknet_htlc::interface::events::Refunded",kind:"struct",members:[{name:"order_id",type:"core::felt252",kind:"key"}]},{type:"event",name:"starknet_htlc::interface::events::InitiatedWithDestinationData",kind:"struct",members:[{name:"order_id",type:"core::felt252",kind:"key"},{name:"secret_hash",type:"[core::integer::u128; 2]",kind:"data"},{name:"amount",type:"core::integer::u256",kind:"data"},{name:"destination_data",type:"core::array::Array::<core::felt252>",kind:"data"}]},{type:"event",name:"starknet_htlc::htlc::HTLC::Event",kind:"enum",variants:[{name:"Initiated",type:"starknet_htlc::interface::events::Initiated",kind:"nested"},{name:"Redeemed",type:"starknet_htlc::interface::events::Redeemed",kind:"nested"},{name:"Refunded",type:"starknet_htlc::interface::events::Refunded",kind:"nested"},{name:"InitiatedWithDestinationData",type:"starknet_htlc::interface::events::InitiatedWithDestinationData",kind:"nested"}]}],n_={StarknetDomain:[{name:"name",type:"shortstring"},{name:"version",type:"shortstring"},{name:"chainId",type:"shortstring"},{name:"revision",type:"shortstring"}],Initiate:[{name:"redeemer",type:"ContractAddress"},{name:"amount",type:"u256"},{name:"timelock",type:"u128"},{name:"secretHash",type:"u128*"},{name:"verifyingContract",type:"ContractAddress"}]};class $w{constructor(e,r,n,s,i){this.url=e instanceof m.Url?e:new m.Url(e),this.starknetProvider=new Qe.RpcProvider({nodeUrl:i||Fa[n].nodeUrl}),this.account=r,this.chainId=Fa[n].chainId,this.auth=s,this.relayer=new ui(this.auth,this.url)}get htlcActorAddress(){if(!this.account.address)throw new Error("No account found");return this.account.address}async initiate(e){if(D.isStarknetOrderResponse(e))return this.initiateWithCreateOrderResponse(e);if(!this.account.address)return m.Err("No account address");const{source_swap:r}=e,{redeemer:n,amount:s}=r;if(!s||!n||!r.secret_hash||!r.timelock)return m.Err("Invalid order");const i=await $i(r.asset,this.url,this.auth);if(!i.ok)return m.Err(i.error);try{const a=new Qe.Contract({providerOrAccount:this.starknetProvider,abi:Mw,address:i.val.htlcAddress}),o=await(a==null?void 0:a.token()),c=Qe.num.toHex(o),u=await Fw(this.account.address,c,i.val.htlcAddress,this.starknetProvider,BigInt(r.amount));return u.error?m.Err(u.error):u.val?this.initiateRelay(e):this.approveAndInitiate(c,e)}catch(a){return m.Err(String(a))}}async approveAndInitiate(e,r){const{source_swap:n}=r,{redeemer:s,amount:i}=n,{secret_hash:a,timelock:o}=n,c=n.asset;try{const u=Qe.cairo.uint256(BigInt(i)),l={contractAddress:m.with0x(e),entrypoint:"approve",calldata:[c,u.low,u.high]},f=Qe.cairo.uint256(i),p=m.hexToU128Array(a),d={contractAddress:m.with0x(c),entrypoint:"initiate",calldata:[s,o.toString(),f.low.toString(),f.high.toString(),...p.map(g=>g.toString())]},b=await this.account.execute([l,d]);return await this.starknetProvider.waitForTransaction(b.transaction_hash,{retryInterval:2e3,successStates:[Qe.TransactionExecutionStatus.SUCCEEDED]}),m.Ok(b.transaction_hash)}catch(u){return m.Err(`Failed to approve and initiate: ${String(u)}`)}}async initiateRelay(e){const{source_swap:r}=e,n=await $i(r.asset,this.url,this.auth);if(!n.ok)return m.Err(n.error);const{redeemer:s,amount:i}=r;if(!r.secret_hash)return m.Err("Invalid order: secret_hash is undefined");const a=m.with0x(r.secret_hash),o={name:"HTLC",version:Qe.shortString.encodeShortString("2"),chainId:this.chainId,revision:Qe.TypedDataRevision.ACTIVE},c=m.hexToU128Array(a),u={domain:o,primaryType:"Initiate",types:n_,message:{redeemer:s,amount:Qe.cairo.uint256(i),timelock:e.source_swap.timelock.toString(),secretHash:c.map(l=>l.toString()),verifyingContract:n.val.htlcAddress}};try{const l=await this.account.signMessage(u),f=M0(l);if(f.error||!f.val)return m.Err(f.error||"Invalid signature");const p=await this.relayer.initiate(e.order_id,f.val);return p.ok?m.Ok(p.val):m.Err(p.error)}catch(l){return m.Err(`Failed to initiate relayer: ${String(l)}`)}}async redeem(e,r){try{const n=await this.relayer.redeem(e.order_id,r);return n.error?m.Err(n.error):m.Ok(n.val)}catch(n){return m.Err(String(n))}}async executeApprovalTransaction(e){if(!this.account.address)return m.Err("No account address");if(!e.approval_transaction)return m.Ok("No approval transaction required");try{const r=e.approval_transaction,n=await this.account.execute([{contractAddress:m.with0x(r.to),entrypoint:"approve",calldata:r.calldata}]);return await this.starknetProvider.waitForTransaction(n.transaction_hash,{retryInterval:2e3,successStates:[Qe.TransactionExecutionStatus.SUCCEEDED]}),m.Ok(n.transaction_hash)}catch(r){return console.error("executeApprovalTransaction error:",r),m.Err("Failed to execute approval: "+(r instanceof Error&&(r==null?void 0:r.message)||String(r)))}}async initiateWithCreateOrderResponse(e){const r=await this.auth.getAuthHeaders();if(!r.ok)return m.Err(r.error);if(!this.account.address)return m.Err("No account address");const n=await this.executeApprovalTransaction(e);if(n.error)return m.Err(n.error);const{typed_data:s}=e;if(s===null){const c=e.initiate_transaction;if(!c)return m.Err("No initiate_transaction found for native initiate");const u=await this.account.execute([{contractAddress:m.with0x(c.to),entrypoint:"initiate",calldata:c.calldata}]);return await this.starknetProvider.waitForTransaction(u.transaction_hash,{retryInterval:2e3,successStates:[Qe.TransactionExecutionStatus.SUCCEEDED]}),m.Ok(u.transaction_hash)}const i=await this.account.signMessage(s),a=M0(i);if(a.error)return m.Err(a.error);const o=await m.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:Array.isArray(a.val)?a.val.join(","):a.val}),headers:{...r.val,"Content-Type":"application/json"}});return o.error?m.Err(o.error):m.Ok(o.result)}async refund(){return m.Err("Refund is taken care of by the relayer")}}const s_="2WXpY8havGjfRxme9LUxtjFHTh1EfU3ur4v6wiK4KdNC",i_={name:"solana_spl_swaps",version:"0.4.0",spec:"0.1.0",description:"Created with Anchor"},a_=[{name:"initiate",docs:["Initiates the atomic swap. Funds are transferred from the initiator to the token vault.","As such, the initiator's signature is required for this instruction.","A sponsor may be involved, who pays PDA rent and transaction fees in SOL, allowing for the","initiator to participate without holding SOL. As such, the sponsor must also sign this transaction.","`swap_amount` represents the quantity of tokens to be transferred through this atomic swap","in base units of the token mint.",'E.g: A quantity of $1 represented by the token "USDC" with "6" decimals',"must be provided as 1,000,000.","`expires_in_slots` represents the number of slots after which (non-instant) refunds are allowed.","`destination_data` can hold optional information regarding the destination chain","in the atomic swap, to be emitted in the logs as-is."],discriminator:[5,63,123,113,153,75,148,14],accounts:[{name:"identity_pda",docs:["the token transfers of the `token_vault` PDA.","This PDA will be created during the first most invocation of the `initiate()` function","using the `init_if_needed` attribute, and be reused for all succeeding instructions."],writable:!0,pda:{seeds:[]}},{name:"swap_data",docs:["A PDA that maintains the on-chain state of the atomic swap throughout its lifecycle.","The choice of seeds ensure that any swap with equal `initiator` and","`secret_hash` wont be created until an existing one completes.","This PDA will be deleted upon completion of the swap."],writable:!0,pda:{seeds:[{kind:"account",path:"initiator"},{kind:"arg",path:"secret_hash"}]}},{name:"token_vault",docs:["A permanent PDA that is controlled by the program through the `identity_pda`, as implied",'by the value of the `authority` field below. As such, it serves as the "vault" by escrowing tokens',"of type `mint` for the atomic swap.","It is intended to be reused for all swaps involving the same mint.","Just like `identity_pda`, it will be created during the first most invocation of `initiate()`","of every distinct mint using the `init_if_needed` attribute."],writable:!0,pda:{seeds:[{kind:"account",path:"mint"}]}},{name:"initiator",docs:["The initiator of the atomic swap. They must sign this transaction."],signer:!0},{name:"initiator_token_account",docs:["The token account of the initiator"],writable:!0},{name:"mint",docs:["The mint of the tokens involved in this swap. As this is a parameter, this program can thus be reused","for atomic swaps with different mints."]},{name:"sponsor",docs:["Any entity that pays the PDA rent.","Upon completion of the swap, the PDA rent refund resulting from the","deletion of `swap_data` will be refunded to this address."],writable:!0,signer:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"},{name:"system_program",address:"11111111111111111111111111111111"}],args:[{name:"expires_in_slots",type:"u64"},{name:"redeemer",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}},{name:"swap_amount",type:"u64"},{name:"destination_data",type:{option:"bytes"}}]},{name:"instant_refund",docs:["Funds are returned to the initiator, with the redeemer's consent.","As such, the redeemer's signature is required for this instruction.","This allows for refunds before the expiry slot."],discriminator:[211,202,103,41,183,147,59,251],accounts:[{name:"identity_pda",pda:{seeds:[]}},{name:"swap_data",docs:["The PDA holding the state information of the atomic swap. Will be closed upon successful execution","and the resulting rent refund will be sent to the sponsor."],writable:!0},{name:"token_vault",docs:["A token account controlled by the program, escrowing the tokens for this atomic swap"],writable:!0},{name:"initiator_token_account",writable:!0},{name:"redeemer",docs:["The redeemer of the atomic swap. They must sign this transaction."],writable:!0,signer:!0},{name:"sponsor",writable:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"}],args:[]},{name:"redeem",docs:["Funds are transferred to the redeemer. This instruction does not require any signatures."],discriminator:[184,12,86,149,70,196,97,225],accounts:[{name:"identity_pda",pda:{seeds:[]}},{name:"swap_data",docs:["The PDA holding the state information of the atomic swap. Will be closed upon successful execution","and the resulting rent refund will be sent to the sponsor."],writable:!0},{name:"token_vault",docs:["A token account controlled by the program, escrowing the tokens for this atomic swap"],writable:!0},{name:"redeemer_token_account",writable:!0},{name:"sponsor",writable:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"}],args:[{name:"secret",type:{array:["u8",32]}}]},{name:"refund",docs:["Funds are returned to the initiator, given that no redeems have occured","and the expiry slot has been reached.","This instruction does not require any signatures."],discriminator:[2,96,183,251,63,208,46,46],accounts:[{name:"identity_pda",pda:{seeds:[]}},{name:"swap_data",docs:["The PDA holding the state information of the atomic swap. Will be closed upon successful execution","and the resulting rent refund will be sent to the sponsor."],writable:!0},{name:"token_vault",docs:["A token account controlled by the program, escrowing the tokens for this atomic swap"],writable:!0},{name:"initiator_token_account",writable:!0},{name:"sponsor",writable:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"}],args:[]}],o_=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],c_=[{name:"Initiated",discriminator:[6,108,212,91,67,60,207,221]},{name:"InstantRefunded",discriminator:[220,50,18,207,183,232,218,25]},{name:"Redeemed",discriminator:[14,29,183,71,31,165,107,38]},{name:"Refunded",discriminator:[35,103,149,246,196,123,221,99]}],u_=[{code:6e3,name:"InvalidRedeemer",msg:"The provider redeemer is not the original redeemer of this swap"},{code:6001,name:"InvalidSecret",msg:"The provided secret does not correspond to the secret hash of this swap"},{code:6002,name:"InvalidSponsor",msg:"The provided sponsor is not the original sponsor of this swap"},{code:6003,name:"RefundBeforeExpiry",msg:"Attempt to perform a refund before expiry time"}],l_=[{name:"Initiated",docs:["Represents the initiated state of the swap where the initiator has deposited funds into the vault"],type:{kind:"struct",fields:[{name:"swap_amount",docs:["The quantity of tokens transferred through this atomic swap in base units of the token mint.",'E.g: A quantity of $1 represented by the token "USDC" with "6" decimals will be represented as 1,000,000.'],type:"u64"},{name:"expires_in_slots",docs:["`expires_in_slots` represents the number of slots after which (non-instant) refunds are allowed"],type:"u64"},{name:"initiator",type:"pubkey"},{name:"mint",type:"pubkey"},{name:"redeemer",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}},{name:"destination_data",docs:["Information regarding the destination chain in the atomic swap"],type:{option:"bytes"}}]}},{name:"InstantRefunded",docs:["Represents the instant refund state of the swap, where the initiator has withdrawn funds the vault","with the redeemer's consent"],type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}},{name:"Redeemed",docs:["Represents the redeemed state of the swap, where the redeemer has withdrawn funds from the vault"],type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret",type:{array:["u8",32]}}]}},{name:"Refunded",docs:["Represents the refund state of the swap, where the initiator has withdrawn funds from the vault past expiry"],type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}},{name:"SwapAccount",docs:["Stores the state information of the atomic swap on-chain"],type:{kind:"struct",fields:[{name:"expiry_slot",docs:["The exact slot after which (non-instant) refunds are allowed"],type:"u64"},{name:"initiator",docs:["The initiator of the atomic swap"],type:"pubkey"},{name:"redeemer",docs:["The redeemer of the atomic swap"],type:"pubkey"},{name:"secret_hash",docs:["The secret hash associated with the atomic swap"],type:{array:["u8",32]}},{name:"swap_amount",docs:["The quantity tokens to be transferred through this atomic swap","in base units of the token mint.",'E.g: A quantity of $1 represented by the token "USDC" with "6" decimals',"must be provided as 1,000,000."],type:"u64"},{name:"identity_pda_bump",docs:["The bump associated with the identity pda.","This is needed by the program to authorize token transfers via the token vault."],type:"u8"},{name:"sponsor",docs:["The entity that paid the rent fees for the creation of this PDA.","This will be referenced during the refund of the same upon closing this PDA."],type:"pubkey"}]}}],iy={address:s_,metadata:i_,instructions:a_,accounts:o_,events:c_,errors:u_,types:l_},f_="2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",d_={name:"solana_native_swaps",version:"0.3.0",spec:"0.1.0",description:"Created with Anchor"},h_=[{name:"initiate",discriminator:[5,63,123,113,153,75,148,14],accounts:[{name:"swap_account",writable:!0,pda:{seeds:[{kind:"const",value:[115,119,97,112,95,97,99,99,111,117,110,116]},{kind:"account",path:"initiator"},{kind:"arg",path:"secret_hash"}]}},{name:"initiator",docs:["Initiator must sign this transaction"],writable:!0,signer:!0},{name:"system_program",address:"11111111111111111111111111111111"}],args:[{name:"amount_lamports",type:"u64"},{name:"expires_in_slots",type:"u64"},{name:"redeemer",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]},{name:"instant_refund",discriminator:[211,202,103,41,183,147,59,251],accounts:[{name:"swap_account",writable:!0},{name:"initiator",writable:!0},{name:"redeemer",docs:["Redeemer must sign this transaction"],signer:!0}],args:[]},{name:"redeem",discriminator:[184,12,86,149,70,196,97,225],accounts:[{name:"swap_account",writable:!0},{name:"initiator",docs:["This is included here for the PDA rent refund using the `close` attribute above"],writable:!0},{name:"redeemer",writable:!0}],args:[{name:"secret",type:{array:["u8",32]}}]},{name:"refund",discriminator:[2,96,183,251,63,208,46,46],accounts:[{name:"swap_account",writable:!0},{name:"initiator",writable:!0}],args:[]}],p_=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],y_=[{name:"Initiated",discriminator:[6,108,212,91,67,60,207,221]},{name:"InstantRefunded",discriminator:[220,50,18,207,183,232,218,25]},{name:"Redeemed",discriminator:[14,29,183,71,31,165,107,38]},{name:"Refunded",discriminator:[35,103,149,246,196,123,221,99]}],m_=[{code:6e3,name:"InvalidInitiator",msg:"The provided initiator is not the original initiator of this swap account"},{code:6001,name:"InvalidRedeemer",msg:"The provided redeemer is not the original redeemer of this swap amount"},{code:6002,name:"InvalidSecret",msg:"The provided secret does not correspond to the secret hash in the swap account"},{code:6003,name:"RefundBeforeExpiry",msg:"Attempt to perform a refund before expiry time"}],b_=[{name:"Initiated",type:{kind:"struct",fields:[{name:"amount_lamports",type:"u64"},{name:"expires_in_slots",type:"u64"},{name:"initiator",type:"pubkey"},{name:"redeemer",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}},{name:"InstantRefunded",type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}},{name:"Redeemed",type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret",type:{array:["u8",32]}}]}},{name:"Refunded",type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}},{name:"SwapAccount",type:{kind:"struct",fields:[{name:"amount_lamports",type:"u64"},{name:"expiry_slot",type:"u64"},{name:"initiator",type:"pubkey"},{name:"redeemer",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}}],Ud={address:f_,metadata:d_,instructions:h_,accounts:p_,events:y_,errors:m_,types:b_};var Tn={},Iu={};Object.defineProperty(Iu,"__esModule",{value:!0});Iu.encode=g_;Iu.decode=w_;const ay=si;function g_(t){return t.reduce((e,r)=>e+r.toString(16).padStart(2,"0"),"0x")}function w_(t){t.indexOf("0x")===0&&(t=t.substr(2)),t.length%2===1&&(t="0"+t);let e=t.match(/.{2}/g);return e===null?ay.Buffer.from([]):ay.Buffer.from(e.map(r=>parseInt(r,16)))}var Pu={},ti={},xl;Object.defineProperty(ti,"__esModule",{value:!0});ti.isVersionedTransaction=ti.isBrowser=void 0;ti.chunks=v_;ti.isBrowser=process.env.ANCHOR_BROWSER||typeof window<"u"&&!(!((xl=window.process)===null||xl===void 0)&&xl.hasOwnProperty("type"));function v_(t,e){return Array.apply(0,new Array(Math.ceil(t.length/e))).map((r,n)=>t.slice(n*e,(n+1)*e))}const E_=t=>"version"in t;ti.isVersionedTransaction=E_;var kl={},Tl={},_l,oy;function jw(){return oy||(oy=1,_l=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var s=42;e[r]=s;for(var i in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var a=Object.getOwnPropertySymbols(e);if(a.length!==1||a[0]!==r||!Object.prototype.propertyIsEnumerable.call(e,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var o=Object.getOwnPropertyDescriptor(e,r);if(o.value!==s||o.enumerable!==!0)return!1}return!0}),_l}var Il,cy;function Ou(){if(cy)return Il;cy=1;var t=jw();return Il=function(){return t()&&!!Symbol.toStringTag},Il}var Pl,uy;function Hw(){return uy||(uy=1,Pl=Object),Pl}var Ol,ly;function A_(){return ly||(ly=1,Ol=Error),Ol}var Bl,fy;function S_(){return fy||(fy=1,Bl=EvalError),Bl}var Cl,dy;function x_(){return dy||(dy=1,Cl=RangeError),Cl}var Rl,hy;function k_(){return hy||(hy=1,Rl=ReferenceError),Rl}var Nl,py;function Lw(){return py||(py=1,Nl=SyntaxError),Nl}var Ul,yy;function Ho(){return yy||(yy=1,Ul=TypeError),Ul}var Fl,my;function T_(){return my||(my=1,Fl=URIError),Fl}var Ml,by;function __(){return by||(by=1,Ml=Math.abs),Ml}var $l,gy;function I_(){return gy||(gy=1,$l=Math.floor),$l}var jl,wy;function P_(){return wy||(wy=1,jl=Math.max),jl}var Hl,vy;function O_(){return vy||(vy=1,Hl=Math.min),Hl}var Ll,Ey;function B_(){return Ey||(Ey=1,Ll=Math.pow),Ll}var Dl,Ay;function C_(){return Ay||(Ay=1,Dl=Math.round),Dl}var zl,Sy;function R_(){return Sy||(Sy=1,zl=Number.isNaN||function(e){return e!==e}),zl}var Vl,xy;function N_(){if(xy)return Vl;xy=1;var t=R_();return Vl=function(r){return t(r)||r===0?r:r<0?-1:1},Vl}var Gl,ky;function U_(){return ky||(ky=1,Gl=Object.getOwnPropertyDescriptor),Gl}var ql,Ty;function sa(){if(Ty)return ql;Ty=1;var t=U_();if(t)try{t([],"length")}catch{t=null}return ql=t,ql}var Wl,_y;function Bu(){if(_y)return Wl;_y=1;var t=Object.defineProperty||!1;if(t)try{t({},"a",{value:1})}catch{t=!1}return Wl=t,Wl}var Kl,Iy;function F_(){if(Iy)return Kl;Iy=1;var t=typeof Symbol<"u"&&Symbol,e=jw();return Kl=function(){return typeof t!="function"||typeof Symbol!="function"||typeof t("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},Kl}var Xl,Py;function Dw(){return Py||(Py=1,Xl=typeof Reflect<"u"&&Reflect.getPrototypeOf||null),Xl}var Yl,Oy;function zw(){if(Oy)return Yl;Oy=1;var t=Hw();return Yl=t.getPrototypeOf||null,Yl}var Jl,By;function M_(){if(By)return Jl;By=1;var t="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,r=Math.max,n="[object Function]",s=function(c,u){for(var l=[],f=0;f<c.length;f+=1)l[f]=c[f];for(var p=0;p<u.length;p+=1)l[p+c.length]=u[p];return l},i=function(c,u){for(var l=[],f=u,p=0;f<c.length;f+=1,p+=1)l[p]=c[f];return l},a=function(o,c){for(var u="",l=0;l<o.length;l+=1)u+=o[l],l+1<o.length&&(u+=c);return u};return Jl=function(c){var u=this;if(typeof u!="function"||e.apply(u)!==n)throw new TypeError(t+u);for(var l=i(arguments,1),f,p=function(){if(this instanceof f){var S=u.apply(this,s(l,arguments));return Object(S)===S?S:this}return u.apply(c,s(l,arguments))},d=r(0,u.length-l.length),b=[],g=0;g<d;g++)b[g]="$"+g;if(f=Function("binder","return function ("+a(b,",")+"){ return binder.apply(this,arguments); }")(p),u.prototype){var A=function(){};A.prototype=u.prototype,f.prototype=new A,A.prototype=null}return f},Jl}var Zl,Cy;function Lo(){if(Cy)return Zl;Cy=1;var t=M_();return Zl=Function.prototype.bind||t,Zl}var Ql,Ry;function f0(){return Ry||(Ry=1,Ql=Function.prototype.call),Ql}var ef,Ny;function d0(){return Ny||(Ny=1,ef=Function.prototype.apply),ef}var tf,Uy;function $_(){return Uy||(Uy=1,tf=typeof Reflect<"u"&&Reflect&&Reflect.apply),tf}var rf,Fy;function Vw(){if(Fy)return rf;Fy=1;var t=Lo(),e=d0(),r=f0(),n=$_();return rf=n||t.call(r,e),rf}var nf,My;function h0(){if(My)return nf;My=1;var t=Lo(),e=Ho(),r=f0(),n=Vw();return nf=function(i){if(i.length<1||typeof i[0]!="function")throw new e("a function is required");return n(t,r,i)},nf}var sf,$y;function j_(){if($y)return sf;$y=1;var t=h0(),e=sa(),r;try{r=[].__proto__===Array.prototype}catch(a){if(!a||typeof a!="object"||!("code"in a)||a.code!=="ERR_PROTO_ACCESS")throw a}var n=!!r&&e&&e(Object.prototype,"__proto__"),s=Object,i=s.getPrototypeOf;return sf=n&&typeof n.get=="function"?t([n.get]):typeof i=="function"?function(o){return i(o==null?o:s(o))}:!1,sf}var af,jy;function p0(){if(jy)return af;jy=1;var t=Dw(),e=zw(),r=j_();return af=t?function(s){return t(s)}:e?function(s){if(!s||typeof s!="object"&&typeof s!="function")throw new TypeError("getProto: not an object");return e(s)}:r?function(s){return r(s)}:null,af}var of,Hy;function Gw(){if(Hy)return of;Hy=1;var t=Function.prototype.call,e=Object.prototype.hasOwnProperty,r=Lo();return of=r.call(t,e),of}var cf,Ly;function qw(){if(Ly)return cf;Ly=1;var t,e=Hw(),r=A_(),n=S_(),s=x_(),i=k_(),a=Lw(),o=Ho(),c=T_(),u=__(),l=I_(),f=P_(),p=O_(),d=B_(),b=C_(),g=N_(),A=Function,S=function(ie){try{return A('"use strict"; return ('+ie+").constructor;")()}catch{}},T=sa(),v=Bu(),w=function(){throw new o},x=T?function(){try{return arguments.callee,w}catch{try{return T(arguments,"callee").get}catch{return w}}}():w,_=F_()(),I=p0(),N=zw(),C=Dw(),j=d0(),M=f0(),H={},V=typeof Uint8Array>"u"||!I?t:I(Uint8Array),Q={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?t:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?t:ArrayBuffer,"%ArrayIteratorPrototype%":_&&I?I([][Symbol.iterator]()):t,"%AsyncFromSyncIteratorPrototype%":t,"%AsyncFunction%":H,"%AsyncGenerator%":H,"%AsyncGeneratorFunction%":H,"%AsyncIteratorPrototype%":H,"%Atomics%":typeof Atomics>"u"?t:Atomics,"%BigInt%":typeof BigInt>"u"?t:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?t:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?t:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?t:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":r,"%eval%":eval,"%EvalError%":n,"%Float16Array%":typeof Float16Array>"u"?t:Float16Array,"%Float32Array%":typeof Float32Array>"u"?t:Float32Array,"%Float64Array%":typeof Float64Array>"u"?t:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?t:FinalizationRegistry,"%Function%":A,"%GeneratorFunction%":H,"%Int8Array%":typeof Int8Array>"u"?t:Int8Array,"%Int16Array%":typeof Int16Array>"u"?t:Int16Array,"%Int32Array%":typeof Int32Array>"u"?t:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":_&&I?I(I([][Symbol.iterator]())):t,"%JSON%":typeof JSON=="object"?JSON:t,"%Map%":typeof Map>"u"?t:Map,"%MapIteratorPrototype%":typeof Map>"u"||!_||!I?t:I(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":e,"%Object.getOwnPropertyDescriptor%":T,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?t:Promise,"%Proxy%":typeof Proxy>"u"?t:Proxy,"%RangeError%":s,"%ReferenceError%":i,"%Reflect%":typeof Reflect>"u"?t:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?t:Set,"%SetIteratorPrototype%":typeof Set>"u"||!_||!I?t:I(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?t:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":_&&I?I(""[Symbol.iterator]()):t,"%Symbol%":_?Symbol:t,"%SyntaxError%":a,"%ThrowTypeError%":x,"%TypedArray%":V,"%TypeError%":o,"%Uint8Array%":typeof Uint8Array>"u"?t:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?t:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?t:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?t:Uint32Array,"%URIError%":c,"%WeakMap%":typeof WeakMap>"u"?t:WeakMap,"%WeakRef%":typeof WeakRef>"u"?t:WeakRef,"%WeakSet%":typeof WeakSet>"u"?t:WeakSet,"%Function.prototype.call%":M,"%Function.prototype.apply%":j,"%Object.defineProperty%":v,"%Object.getPrototypeOf%":N,"%Math.abs%":u,"%Math.floor%":l,"%Math.max%":f,"%Math.min%":p,"%Math.pow%":d,"%Math.round%":b,"%Math.sign%":g,"%Reflect.getPrototypeOf%":C};if(I)try{null.error}catch(ie){var U=I(I(ie));Q["%Error.prototype%"]=U}var K=function ie(se){var be;if(se==="%AsyncFunction%")be=S("async function () {}");else if(se==="%GeneratorFunction%")be=S("function* () {}");else if(se==="%AsyncGeneratorFunction%")be=S("async function* () {}");else if(se==="%AsyncGenerator%"){var ge=ie("%AsyncGeneratorFunction%");ge&&(be=ge.prototype)}else if(se==="%AsyncIteratorPrototype%"){var Ee=ie("%AsyncGenerator%");Ee&&I&&(be=I(Ee.prototype))}return Q[se]=be,be},ee={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},q=Lo(),O=Gw(),L=q.call(M,Array.prototype.concat),J=q.call(j,Array.prototype.splice),B=q.call(M,String.prototype.replace),F=q.call(M,String.prototype.slice),z=q.call(M,RegExp.prototype.exec),ne=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,ae=/\\(\\)?/g,fe=function(se){var be=F(se,0,1),ge=F(se,-1);if(be==="%"&&ge!=="%")throw new a("invalid intrinsic syntax, expected closing `%`");if(ge==="%"&&be!=="%")throw new a("invalid intrinsic syntax, expected opening `%`");var Ee=[];return B(se,ne,function(Te,rt,Ce,Hr){Ee[Ee.length]=Ce?B(Hr,ae,"$1"):rt||Te}),Ee},ue=function(se,be){var ge=se,Ee;if(O(ee,ge)&&(Ee=ee[ge],ge="%"+Ee[0]+"%"),O(Q,ge)){var Te=Q[ge];if(Te===H&&(Te=K(ge)),typeof Te>"u"&&!be)throw new o("intrinsic "+se+" exists, but is not available. Please file an issue!");return{alias:Ee,name:ge,value:Te}}throw new a("intrinsic "+se+" does not exist!")};return cf=function(se,be){if(typeof se!="string"||se.length===0)throw new o("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof be!="boolean")throw new o('"allowMissing" argument must be a boolean');if(z(/^%?[^%]*%?$/,se)===null)throw new a("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var ge=fe(se),Ee=ge.length>0?ge[0]:"",Te=ue("%"+Ee+"%",be),rt=Te.name,Ce=Te.value,Hr=!1,xs=Te.alias;xs&&(Ee=xs[0],J(ge,L([0,1],xs)));for(var X=1,Lr=!0;X<ge.length;X+=1){var _t=ge[X],It=F(_t,0,1),jn=F(_t,-1);if((It==='"'||It==="'"||It==="`"||jn==='"'||jn==="'"||jn==="`")&&It!==jn)throw new a("property names with quotes must have matching quotes");if((_t==="constructor"||!Lr)&&(Hr=!0),Ee+="."+_t,rt="%"+Ee+"%",O(Q,rt))Ce=Q[rt];else if(Ce!=null){if(!(_t in Ce)){if(!be)throw new o("base intrinsic for "+se+" exists, but the property is not available.");return}if(T&&X+1>=ge.length){var fi=T(Ce,_t);Lr=!!fi,Lr&&"get"in fi&&!("originalValue"in fi.get)?Ce=fi.get:Ce=Ce[_t]}else Lr=O(Ce,_t),Ce=Ce[_t];Lr&&!Hr&&(Q[rt]=Ce)}}return Ce},cf}var uf,Dy;function Do(){if(Dy)return uf;Dy=1;var t=qw(),e=h0(),r=e([t("%String.prototype.indexOf%")]);return uf=function(s,i){var a=t(s,!!i);return typeof a=="function"&&r(s,".prototype.")>-1?e([a]):a},uf}var lf,zy;function H_(){if(zy)return lf;zy=1;var t=Ou()(),e=Do(),r=e("Object.prototype.toString"),n=function(o){return t&&o&&typeof o=="object"&&Symbol.toStringTag in o?!1:r(o)==="[object Arguments]"},s=function(o){return n(o)?!0:o!==null&&typeof o=="object"&&"length"in o&&typeof o.length=="number"&&o.length>=0&&r(o)!=="[object Array]"&&"callee"in o&&r(o.callee)==="[object Function]"},i=function(){return n(arguments)}();return n.isLegacyArguments=s,lf=i?n:s,lf}var ff,Vy;function L_(){if(Vy)return ff;Vy=1;var t=Do(),e=Ou()(),r=Gw(),n=sa(),s;if(e){var i=t("RegExp.prototype.exec"),a={},o=function(){throw a},c={toString:o,valueOf:o};typeof Symbol.toPrimitive=="symbol"&&(c[Symbol.toPrimitive]=o),s=function(p){if(!p||typeof p!="object")return!1;var d=n(p,"lastIndex"),b=d&&r(d,"value");if(!b)return!1;try{i(p,c)}catch(g){return g===a}}}else{var u=t("Object.prototype.toString"),l="[object RegExp]";s=function(p){return!p||typeof p!="object"&&typeof p!="function"?!1:u(p)===l}}return ff=s,ff}var df,Gy;function D_(){if(Gy)return df;Gy=1;var t=Do(),e=L_(),r=t("RegExp.prototype.exec"),n=Ho();return df=function(i){if(!e(i))throw new n("`regex` must be a RegExp");return function(o){return r(i,o)!==null}},df}var hf,qy;function z_(){if(qy)return hf;qy=1;const t=(function*(){}).constructor;return hf=()=>t,hf}var pf,Wy;function V_(){if(Wy)return pf;Wy=1;var t=Do(),e=D_(),r=e(/^\s*(?:function)?\*/),n=Ou()(),s=p0(),i=t("Object.prototype.toString"),a=t("Function.prototype.toString"),o=z_();return pf=function(u){if(typeof u!="function")return!1;if(r(a(u)))return!0;if(!n){var l=i(u);return l==="[object GeneratorFunction]"}if(!s)return!1;var f=o();return f&&s(u)===f.prototype},pf}var yf,Ky;function G_(){if(Ky)return yf;Ky=1;var t=Function.prototype.toString,e=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,r,n;if(typeof e=="function"&&typeof Object.defineProperty=="function")try{r=Object.defineProperty({},"length",{get:function(){throw n}}),n={},e(function(){throw 42},null,r)}catch(T){T!==n&&(e=null)}else e=null;var s=/^\s*class\b/,i=function(v){try{var w=t.call(v);return s.test(w)}catch{return!1}},a=function(v){try{return i(v)?!1:(t.call(v),!0)}catch{return!1}},o=Object.prototype.toString,c="[object Object]",u="[object Function]",l="[object GeneratorFunction]",f="[object HTMLAllCollection]",p="[object HTML document.all class]",d="[object HTMLCollection]",b=typeof Symbol=="function"&&!!Symbol.toStringTag,g=!(0 in[,]),A=function(){return!1};if(typeof document=="object"){var S=document.all;o.call(S)===o.call(document.all)&&(A=function(v){if((g||!v)&&(typeof v>"u"||typeof v=="object"))try{var w=o.call(v);return(w===f||w===p||w===d||w===c)&&v("")==null}catch{}return!1})}return yf=e?function(v){if(A(v))return!0;if(!v||typeof v!="function"&&typeof v!="object")return!1;try{e(v,null,r)}catch(w){if(w!==n)return!1}return!i(v)&&a(v)}:function(v){if(A(v))return!0;if(!v||typeof v!="function"&&typeof v!="object")return!1;if(b)return a(v);if(i(v))return!1;var w=o.call(v);return w!==u&&w!==l&&!/^\[object HTML/.test(w)?!1:a(v)},yf}var mf,Xy;function q_(){if(Xy)return mf;Xy=1;var t=G_(),e=Object.prototype.toString,r=Object.prototype.hasOwnProperty,n=function(c,u,l){for(var f=0,p=c.length;f<p;f++)r.call(c,f)&&(l==null?u(c[f],f,c):u.call(l,c[f],f,c))},s=function(c,u,l){for(var f=0,p=c.length;f<p;f++)l==null?u(c.charAt(f),f,c):u.call(l,c.charAt(f),f,c)},i=function(c,u,l){for(var f in c)r.call(c,f)&&(l==null?u(c[f],f,c):u.call(l,c[f],f,c))};function a(o){return e.call(o)==="[object Array]"}return mf=function(c,u,l){if(!t(u))throw new TypeError("iterator must be a function");var f;arguments.length>=3&&(f=l),a(c)?n(c,u,f):typeof c=="string"?s(c,u,f):i(c,u,f)},mf}var bf,Yy;function W_(){return Yy||(Yy=1,bf=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]),bf}var gf,Jy;function K_(){if(Jy)return gf;Jy=1;var t=W_(),e=typeof globalThis>"u"?sn:globalThis;return gf=function(){for(var n=[],s=0;s<t.length;s++)typeof e[t[s]]=="function"&&(n[n.length]=t[s]);return n},gf}var wf={exports:{}},vf,Zy;function X_(){if(Zy)return vf;Zy=1;var t=Bu(),e=Lw(),r=Ho(),n=sa();return vf=function(i,a,o){if(!i||typeof i!="object"&&typeof i!="function")throw new r("`obj` must be an object or a function`");if(typeof a!="string"&&typeof a!="symbol")throw new r("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new r("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new r("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new r("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new r("`loose`, if provided, must be a boolean");var c=arguments.length>3?arguments[3]:null,u=arguments.length>4?arguments[4]:null,l=arguments.length>5?arguments[5]:null,f=arguments.length>6?arguments[6]:!1,p=!!n&&n(i,a);if(t)t(i,a,{configurable:l===null&&p?p.configurable:!l,enumerable:c===null&&p?p.enumerable:!c,value:o,writable:u===null&&p?p.writable:!u});else if(f||!c&&!u&&!l)i[a]=o;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},vf}var Ef,Qy;function Y_(){if(Qy)return Ef;Qy=1;var t=Bu(),e=function(){return!!t};return e.hasArrayLengthDefineBug=function(){if(!t)return null;try{return t([],"length",{value:1}).length!==1}catch{return!0}},Ef=e,Ef}var Af,em;function J_(){if(em)return Af;em=1;var t=qw(),e=X_(),r=Y_()(),n=sa(),s=Ho(),i=t("%Math.floor%");return Af=function(o,c){if(typeof o!="function")throw new s("`fn` is not a function");if(typeof c!="number"||c<0||c>4294967295||i(c)!==c)throw new s("`length` must be a positive 32-bit integer");var u=arguments.length>2&&!!arguments[2],l=!0,f=!0;if("length"in o&&n){var p=n(o,"length");p&&!p.configurable&&(l=!1),p&&!p.writable&&(f=!1)}return(l||f||!u)&&(r?e(o,"length",c,!0,!0):e(o,"length",c)),o},Af}var Sf,tm;function Z_(){if(tm)return Sf;tm=1;var t=Lo(),e=d0(),r=Vw();return Sf=function(){return r(t,e,arguments)},Sf}var rm;function Q_(){return rm||(rm=1,function(t){var e=J_(),r=Bu(),n=h0(),s=Z_();t.exports=function(a){var o=n(arguments),c=a.length-(arguments.length-1);return e(o,1+(c>0?c:0),!0)},r?r(t.exports,"apply",{value:s}):t.exports.apply=s}(wf)),wf.exports}var xf,nm;function Ww(){if(nm)return xf;nm=1;var t=q_(),e=K_(),r=Q_(),n=Do(),s=sa(),i=p0(),a=n("Object.prototype.toString"),o=Ou()(),c=typeof globalThis>"u"?sn:globalThis,u=e(),l=n("String.prototype.slice"),f=n("Array.prototype.indexOf",!0)||function(A,S){for(var T=0;T<A.length;T+=1)if(A[T]===S)return T;return-1},p={__proto__:null};o&&s&&i?t(u,function(g){var A=new c[g];if(Symbol.toStringTag in A&&i){var S=i(A),T=s(S,Symbol.toStringTag);if(!T&&S){var v=i(S);T=s(v,Symbol.toStringTag)}if(T&&T.get){var w=r(T.get);p["$"+g]=w}}}):t(u,function(g){var A=new c[g],S=A.slice||A.set;if(S){var T=r(S);p["$"+g]=T}});var d=function(A){var S=!1;return t(p,function(T,v){if(!S)try{"$"+T(A)===v&&(S=l(v,1))}catch{}}),S},b=function(A){var S=!1;return t(p,function(T,v){if(!S)try{T(A),S=l(v,1)}catch{}}),S};return xf=function(A){if(!A||typeof A!="object")return!1;if(!o){var S=l(a(A),8,-1);return f(u,S)>-1?S:S!=="Object"?!1:b(A)}return s?d(A):null},xf}var kf,sm;function eI(){if(sm)return kf;sm=1;var t=Ww();return kf=function(r){return!!t(r)},kf}var im;function tI(){return im||(im=1,function(t){var e=H_(),r=V_(),n=Ww(),s=eI();function i(X){return X.call.bind(X)}var a=typeof BigInt<"u",o=typeof Symbol<"u",c=i(Object.prototype.toString),u=i(Number.prototype.valueOf),l=i(String.prototype.valueOf),f=i(Boolean.prototype.valueOf);if(a)var p=i(BigInt.prototype.valueOf);if(o)var d=i(Symbol.prototype.valueOf);function b(X,Lr){if(typeof X!="object")return!1;try{return Lr(X),!0}catch{return!1}}t.isArgumentsObject=e,t.isGeneratorFunction=r,t.isTypedArray=s;function g(X){return typeof Promise<"u"&&X instanceof Promise||X!==null&&typeof X=="object"&&typeof X.then=="function"&&typeof X.catch=="function"}t.isPromise=g;function A(X){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(X):s(X)||F(X)}t.isArrayBufferView=A;function S(X){return n(X)==="Uint8Array"}t.isUint8Array=S;function T(X){return n(X)==="Uint8ClampedArray"}t.isUint8ClampedArray=T;function v(X){return n(X)==="Uint16Array"}t.isUint16Array=v;function w(X){return n(X)==="Uint32Array"}t.isUint32Array=w;function x(X){return n(X)==="Int8Array"}t.isInt8Array=x;function _(X){return n(X)==="Int16Array"}t.isInt16Array=_;function I(X){return n(X)==="Int32Array"}t.isInt32Array=I;function N(X){return n(X)==="Float32Array"}t.isFloat32Array=N;function C(X){return n(X)==="Float64Array"}t.isFloat64Array=C;function j(X){return n(X)==="BigInt64Array"}t.isBigInt64Array=j;function M(X){return n(X)==="BigUint64Array"}t.isBigUint64Array=M;function H(X){return c(X)==="[object Map]"}H.working=typeof Map<"u"&&H(new Map);function V(X){return typeof Map>"u"?!1:H.working?H(X):X instanceof Map}t.isMap=V;function Q(X){return c(X)==="[object Set]"}Q.working=typeof Set<"u"&&Q(new Set);function U(X){return typeof Set>"u"?!1:Q.working?Q(X):X instanceof Set}t.isSet=U;function K(X){return c(X)==="[object WeakMap]"}K.working=typeof WeakMap<"u"&&K(new WeakMap);function ee(X){return typeof WeakMap>"u"?!1:K.working?K(X):X instanceof WeakMap}t.isWeakMap=ee;function q(X){return c(X)==="[object WeakSet]"}q.working=typeof WeakSet<"u"&&q(new WeakSet);function O(X){return q(X)}t.isWeakSet=O;function L(X){return c(X)==="[object ArrayBuffer]"}L.working=typeof ArrayBuffer<"u"&&L(new ArrayBuffer);function J(X){return typeof ArrayBuffer>"u"?!1:L.working?L(X):X instanceof ArrayBuffer}t.isArrayBuffer=J;function B(X){return c(X)==="[object DataView]"}B.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&B(new DataView(new ArrayBuffer(1),0,1));function F(X){return typeof DataView>"u"?!1:B.working?B(X):X instanceof DataView}t.isDataView=F;var z=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function ne(X){return c(X)==="[object SharedArrayBuffer]"}function ae(X){return typeof z>"u"?!1:(typeof ne.working>"u"&&(ne.working=ne(new z)),ne.working?ne(X):X instanceof z)}t.isSharedArrayBuffer=ae;function fe(X){return c(X)==="[object AsyncFunction]"}t.isAsyncFunction=fe;function ue(X){return c(X)==="[object Map Iterator]"}t.isMapIterator=ue;function ie(X){return c(X)==="[object Set Iterator]"}t.isSetIterator=ie;function se(X){return c(X)==="[object Generator]"}t.isGeneratorObject=se;function be(X){return c(X)==="[object WebAssembly.Module]"}t.isWebAssemblyCompiledModule=be;function ge(X){return b(X,u)}t.isNumberObject=ge;function Ee(X){return b(X,l)}t.isStringObject=Ee;function Te(X){return b(X,f)}t.isBooleanObject=Te;function rt(X){return a&&b(X,p)}t.isBigIntObject=rt;function Ce(X){return o&&b(X,d)}t.isSymbolObject=Ce;function Hr(X){return ge(X)||Ee(X)||Te(X)||rt(X)||Ce(X)}t.isBoxedPrimitive=Hr;function xs(X){return typeof Uint8Array<"u"&&(J(X)||ae(X))}t.isAnyArrayBuffer=xs,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(X){Object.defineProperty(t,X,{enumerable:!1,value:function(){throw new Error(X+" is not supported in userland")}})})}(Tl)),Tl}var Tf,am;function rI(){return am||(am=1,Tf=function(e){return e&&typeof e=="object"&&typeof e.copy=="function"&&typeof e.fill=="function"&&typeof e.readUInt8=="function"}),Tf}var uc={exports:{}},om;function nI(){return om||(om=1,typeof Object.create=="function"?uc.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:uc.exports=function(e,r){if(r){e.super_=r;var n=function(){};n.prototype=r.prototype,e.prototype=new n,e.prototype.constructor=e}}),uc.exports}var cm;function Kw(){return cm||(cm=1,function(t){var e=Object.getOwnPropertyDescriptors||function(F){for(var z=Object.keys(F),ne={},ae=0;ae<z.length;ae++)ne[z[ae]]=Object.getOwnPropertyDescriptor(F,z[ae]);return ne},r=/%[sdj%]/g;t.format=function(B){if(!x(B)){for(var F=[],z=0;z<arguments.length;z++)F.push(a(arguments[z]));return F.join(" ")}for(var z=1,ne=arguments,ae=ne.length,fe=String(B).replace(r,function(ie){if(ie==="%%")return"%";if(z>=ae)return ie;switch(ie){case"%s":return String(ne[z++]);case"%d":return Number(ne[z++]);case"%j":try{return JSON.stringify(ne[z++])}catch{return"[Circular]"}default:return ie}}),ue=ne[z];z<ae;ue=ne[++z])T(ue)||!C(ue)?fe+=" "+ue:fe+=" "+a(ue);return fe},t.deprecate=function(B,F){if(typeof process<"u"&&process.noDeprecation===!0)return B;if(typeof process>"u")return function(){return t.deprecate(B,F).apply(this,arguments)};var z=!1;function ne(){if(!z){if(process.throwDeprecation)throw new Error(F);process.traceDeprecation?console.trace(F):console.error(F),z=!0}return B.apply(this,arguments)}return ne};var n={},s=/^$/;if(process.env.NODE_DEBUG){var i=process.env.NODE_DEBUG;i=i.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),s=new RegExp("^"+i+"$","i")}t.debuglog=function(B){if(B=B.toUpperCase(),!n[B])if(s.test(B)){var F=process.pid;n[B]=function(){var z=t.format.apply(t,arguments);console.error("%s %d: %s",B,F,z)}}else n[B]=function(){};return n[B]};function a(B,F){var z={seen:[],stylize:c};return arguments.length>=3&&(z.depth=arguments[2]),arguments.length>=4&&(z.colors=arguments[3]),S(F)?z.showHidden=F:F&&t._extend(z,F),I(z.showHidden)&&(z.showHidden=!1),I(z.depth)&&(z.depth=2),I(z.colors)&&(z.colors=!1),I(z.customInspect)&&(z.customInspect=!0),z.colors&&(z.stylize=o),l(z,B,z.depth)}t.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function o(B,F){var z=a.styles[F];return z?"\x1B["+a.colors[z][0]+"m"+B+"\x1B["+a.colors[z][1]+"m":B}function c(B,F){return B}function u(B){var F={};return B.forEach(function(z,ne){F[z]=!0}),F}function l(B,F,z){if(B.customInspect&&F&&H(F.inspect)&&F.inspect!==t.inspect&&!(F.constructor&&F.constructor.prototype===F)){var ne=F.inspect(z,B);return x(ne)||(ne=l(B,ne,z)),ne}var ae=f(B,F);if(ae)return ae;var fe=Object.keys(F),ue=u(fe);if(B.showHidden&&(fe=Object.getOwnPropertyNames(F)),M(F)&&(fe.indexOf("message")>=0||fe.indexOf("description")>=0))return p(F);if(fe.length===0){if(H(F)){var ie=F.name?": "+F.name:"";return B.stylize("[Function"+ie+"]","special")}if(N(F))return B.stylize(RegExp.prototype.toString.call(F),"regexp");if(j(F))return B.stylize(Date.prototype.toString.call(F),"date");if(M(F))return p(F)}var se="",be=!1,ge=["{","}"];if(A(F)&&(be=!0,ge=["[","]"]),H(F)){var Ee=F.name?": "+F.name:"";se=" [Function"+Ee+"]"}if(N(F)&&(se=" "+RegExp.prototype.toString.call(F)),j(F)&&(se=" "+Date.prototype.toUTCString.call(F)),M(F)&&(se=" "+p(F)),fe.length===0&&(!be||F.length==0))return ge[0]+se+ge[1];if(z<0)return N(F)?B.stylize(RegExp.prototype.toString.call(F),"regexp"):B.stylize("[Object]","special");B.seen.push(F);var Te;return be?Te=d(B,F,z,ue,fe):Te=fe.map(function(rt){return b(B,F,z,ue,rt,be)}),B.seen.pop(),g(Te,se,ge)}function f(B,F){if(I(F))return B.stylize("undefined","undefined");if(x(F)){var z="'"+JSON.stringify(F).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return B.stylize(z,"string")}if(w(F))return B.stylize(""+F,"number");if(S(F))return B.stylize(""+F,"boolean");if(T(F))return B.stylize("null","null")}function p(B){return"["+Error.prototype.toString.call(B)+"]"}function d(B,F,z,ne,ae){for(var fe=[],ue=0,ie=F.length;ue<ie;++ue)q(F,String(ue))?fe.push(b(B,F,z,ne,String(ue),!0)):fe.push("");return ae.forEach(function(se){se.match(/^\d+$/)||fe.push(b(B,F,z,ne,se,!0))}),fe}function b(B,F,z,ne,ae,fe){var ue,ie,se;if(se=Object.getOwnPropertyDescriptor(F,ae)||{value:F[ae]},se.get?se.set?ie=B.stylize("[Getter/Setter]","special"):ie=B.stylize("[Getter]","special"):se.set&&(ie=B.stylize("[Setter]","special")),q(ne,ae)||(ue="["+ae+"]"),ie||(B.seen.indexOf(se.value)<0?(T(z)?ie=l(B,se.value,null):ie=l(B,se.value,z-1),ie.indexOf(`
58
+ `)}class ES extends G{constructor({v:e}){super(`Invalid \`v\` value "${e}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}}class AS extends G{constructor({transaction:e}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",Po(e),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}class SS extends G{constructor({storageKey:e}){super(`Size for storage key "${e}" is invalid. Expected 32 bytes. Got ${Math.floor((e.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}}class xS extends G{constructor(e,{account:r,docsPath:n,chain:s,data:i,gas:a,gasPrice:o,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:l,to:f,value:p}){var b;const d=Po({chain:s&&`${s==null?void 0:s.name} (id: ${s==null?void 0:s.id})`,from:r==null?void 0:r.address,to:f,value:typeof p<"u"&&`${kh(p)} ${((b=s==null?void 0:s.nativeCurrency)==null?void 0:b.symbol)||"ETH"}`,data:i,gas:a,gasPrice:typeof o<"u"&&`${Gt(o)} gwei`,maxFeePerGas:typeof c<"u"&&`${Gt(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${Gt(u)} gwei`,nonce:l});super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Request Arguments:",d].filter(Boolean),name:"TransactionExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class Bg extends G{constructor({blockHash:e,blockNumber:r,blockTag:n,hash:s,index:i}){let a="Transaction";n&&i!==void 0&&(a=`Transaction at block time "${n}" at index "${i}"`),e&&i!==void 0&&(a=`Transaction at block hash "${e}" at index "${i}"`),r&&i!==void 0&&(a=`Transaction at block number "${r}" at index "${i}"`),s&&(a=`Transaction with hash "${s}"`),super(`${a} could not be found.`,{name:"TransactionNotFoundError"})}}class Cg extends G{constructor({hash:e}){super(`Transaction receipt with hash "${e}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}}class Rg extends G{constructor({receipt:e}){super(`Transaction with hash "${e.transactionHash}" reverted.`,{metaMessages:['The receipt marked the transaction as "reverted". This could mean that the function on the contract you are trying to call threw an error.'," ","You can attempt to extract the revert reason by:","- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract","- using the `call` Action with raw `data`"],name:"TransactionReceiptRevertedError"}),Object.defineProperty(this,"receipt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.receipt=e}}class kS extends G{constructor({hash:e}){super(`Timed out while waiting for transaction with hash "${e}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}const TS=t=>t,fu=t=>t;class Ng extends G{constructor(e,{account:r,docsPath:n,chain:s,data:i,gas:a,gasPrice:o,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:l,to:f,value:p,stateOverride:d}){var A;const b=r?Le(r):void 0;let g=Po({from:b==null?void 0:b.address,to:f,value:typeof p<"u"&&`${kh(p)} ${((A=s==null?void 0:s.nativeCurrency)==null?void 0:A.symbol)||"ETH"}`,data:i,gas:a,gasPrice:typeof o<"u"&&`${Gt(o)} gwei`,maxFeePerGas:typeof c<"u"&&`${Gt(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${Gt(u)} gwei`,nonce:l});d&&(g+=`
59
+ ${vS(d)}`),super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Raw Call Arguments:",g].filter(Boolean),name:"CallExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class Ug extends G{constructor(e,{abi:r,args:n,contractAddress:s,docsPath:i,functionName:a,sender:o}){const c=ci({abi:r,args:n,name:a}),u=c?Pg({abiItem:c,args:n,includeFunctionName:!1,includeName:!1}):void 0,l=c?Rr(c,{includeName:!0}):void 0,f=Po({address:s&&TS(s),function:l,args:u&&u!=="()"&&`${[...Array((a==null?void 0:a.length)??0).keys()].map(()=>" ").join("")}${u}`,sender:o});super(e.shortMessage||`An unknown error occurred while executing the contract function "${a}".`,{cause:e,docsPath:i,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],f&&"Contract Call:",f].filter(Boolean),name:"ContractFunctionExecutionError"}),Object.defineProperty(this,"abi",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"contractAddress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"formattedArgs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abi=r,this.args=n,this.cause=e,this.contractAddress=s,this.functionName=a,this.sender=o}}class od extends G{constructor({abi:e,data:r,functionName:n,message:s}){let i,a,o,c;if(r&&r!=="0x")try{a=Ig({abi:e,data:r});const{abiItem:l,errorName:f,args:p}=a;if(f==="Error")c=p[0];else if(f==="Panic"){const[d]=p;c=rS[d]}else{const d=l?Rr(l,{includeName:!0}):void 0,b=l&&p?Pg({abiItem:l,args:p,includeFunctionName:!1,includeName:!1}):void 0;o=[d?`Error: ${d}`:"",b&&b!=="()"?` ${[...Array((f==null?void 0:f.length)??0).keys()].map(()=>" ").join("")}${b}`:""]}}catch(l){i=l}else s&&(c=s);let u;i instanceof eg&&(u=i.signature,o=[`Unable to decode signature "${u}" as it was not found on the provided ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://openchain.xyz/signatures?query=${u}.`]),super(c&&c!=="execution reverted"||u?[`The contract function "${n}" reverted with the following ${u?"signature":"reason"}:`,c||u].join(`
60
+ `):`The contract function "${n}" reverted.`,{cause:i,metaMessages:o,name:"ContractFunctionRevertedError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"raw",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=a,this.raw=r,this.reason=c,this.signature=u}}class _S extends G{constructor({functionName:e}){super(`The contract function "${e}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${e}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError"})}}class IS extends G{constructor({factory:e}){super(`Deployment for counterfactual contract call failed${e?` for factory "${e}".`:""}`,{metaMessages:["Please ensure:","- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).","- The `factoryData` is a valid encoded function call for contract deployment function on the factory."],name:"CounterfactualDeploymentFailedError"})}}class du extends G{constructor({data:e,message:r}){super(r||"",{name:"RawContractError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=e}}class Ri extends G{constructor({body:e,cause:r,details:n,headers:s,status:i,url:a}){super("HTTP request failed.",{cause:r,details:n,metaMessages:[i&&`Status: ${i}`,`URL: ${fu(a)}`,e&&`Request body: ${et(e)}`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=e,this.headers=s,this.status=i,this.url=a}}class Th extends G{constructor({body:e,error:r,url:n}){super("RPC Request failed.",{cause:r,details:r.message,metaMessages:[`URL: ${fu(n)}`,`Request body: ${et(e)}`],name:"RpcRequestError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=r.code,this.data=r.data,this.url=n}}class Pp extends G{constructor({body:e,url:r}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${fu(r)}`,`Request body: ${et(e)}`],name:"TimeoutError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=r}}const PS=-1;class Xt extends G{constructor(e,{code:r,docsPath:n,metaMessages:s,name:i,shortMessage:a}){super(a,{cause:e,docsPath:n,metaMessages:s||(e==null?void 0:e.metaMessages),name:i||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=i||e.name,this.code=e instanceof Th?e.code:r??PS}}class cr extends Xt{constructor(e,r){super(e,r),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=r.data}}class La extends Xt{constructor(e){super(e,{code:La.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(La,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class Da extends Xt{constructor(e){super(e,{code:Da.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(Da,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class za extends Xt{constructor(e,{method:r}={}){super(e,{code:za.code,name:"MethodNotFoundRpcError",shortMessage:`The method${r?` "${r}"`:""} does not exist / is not available.`})}}Object.defineProperty(za,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class Va extends Xt{constructor(e){super(e,{code:Va.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
61
+ `)})}}Object.defineProperty(Va,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class Ys extends Xt{constructor(e){super(e,{code:Ys.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(Ys,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class bs extends Xt{constructor(e){super(e,{code:bs.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
62
+ `)})}}Object.defineProperty(bs,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class Ga extends Xt{constructor(e){super(e,{code:Ga.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(Ga,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class qa extends Xt{constructor(e){super(e,{code:qa.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(qa,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class Wa extends Xt{constructor(e){super(e,{code:Wa.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(Wa,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class Rs extends Xt{constructor(e,{method:r}={}){super(e,{code:Rs.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${r?` "${r}"`:""} is not supported.`})}}Object.defineProperty(Rs,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class Gi extends Xt{constructor(e){super(e,{code:Gi.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(Gi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class Ka extends Xt{constructor(e){super(e,{code:Ka.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(Ka,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class Ni extends cr{constructor(e){super(e,{code:Ni.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(Ni,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class Xa extends cr{constructor(e){super(e,{code:Xa.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(Xa,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class Ya extends cr{constructor(e,{method:r}={}){super(e,{code:Ya.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${r?` " ${r}"`:""}.`})}}Object.defineProperty(Ya,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class Ja extends cr{constructor(e){super(e,{code:Ja.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(Ja,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class Za extends cr{constructor(e){super(e,{code:Za.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(Za,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class Qa extends cr{constructor(e){super(e,{code:Qa.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(Qa,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class qi extends cr{constructor(e){super(e,{code:qi.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(qi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class eo extends cr{constructor(e){super(e,{code:eo.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(eo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class to extends cr{constructor(e){super(e,{code:to.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(to,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class ro extends cr{constructor(e){super(e,{code:ro.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(ro,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class no extends cr{constructor(e){super(e,{code:no.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(no,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class so extends cr{constructor(e){super(e,{code:so.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(so,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class Wi extends cr{constructor(e){super(e,{code:Wi.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(Wi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class OS extends Xt{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}const BS=3;function Js(t,{abi:e,address:r,args:n,docsPath:s,functionName:i,sender:a}){const o=t instanceof du?t:t instanceof G?t.walk(b=>"data"in b)||t.walk():{},{code:c,data:u,details:l,message:f,shortMessage:p}=o,d=t instanceof xo?new _S({functionName:i}):[BS,Ys.code].includes(c)&&(u||l||f||p)||c===bs.code&&l==="execution reverted"&&u?new od({abi:e,data:typeof u=="object"?u.data:u,functionName:i,message:o instanceof Th?l:p??f}):t;return new Ug(d,{abi:e,args:n,contractAddress:r,docsPath:s,functionName:i,sender:a})}function CS(t){const e=bt(`0x${t.substring(4)}`).substring(26);return ko(`0x${e}`)}async function RS({hash:t,signature:e}){const r=Nr(t)?t:Ft(t),{secp256k1:n}=await Promise.resolve().then(()=>dk);return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:l,v:f,yParity:p}=e,d=Number(p??f),b=Op(d);return new n.Signature(ft(u),ft(l)).addRecoveryBit(b)}const a=Nr(e)?e:Ft(e);if(Ge(a)!==65)throw new Error("invalid signature length");const o=gr(`0x${a.slice(130)}`),c=Op(o);return n.Signature.fromCompact(a.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function Op(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function Fg({hash:t,signature:e}){return CS(await RS({hash:t,signature:e}))}function gs(t,e="hex"){const r=Mg(t),n=xh(new Uint8Array(r.length));return r.encode(n),e==="hex"?tt(n.bytes):n.bytes}function Mg(t){return Array.isArray(t)?NS(t.map(e=>Mg(e))):US(t)}function NS(t){const e=t.reduce((s,i)=>s+i.length,0),r=$g(e);return{length:e<=55?1+e:1+r+e,encode(s){e<=55?s.pushByte(192+e):(s.pushByte(247+r),r===1?s.pushUint8(e):r===2?s.pushUint16(e):r===3?s.pushUint24(e):s.pushUint32(e));for(const{encode:i}of t)i(s)}}}function US(t){const e=typeof t=="string"?an(t):t,r=$g(e.length);return{length:e.length===1&&e[0]<128?1:e.length<=55?1+e.length:1+r+e.length,encode(s){e.length===1&&e[0]<128?s.pushBytes(e):e.length<=55?(s.pushByte(128+e.length),s.pushBytes(e)):(s.pushByte(183+r),r===1?s.pushUint8(e.length):r===2?s.pushUint16(e.length):r===3?s.pushUint24(e.length):s.pushUint32(e.length),s.pushBytes(e))}}}function $g(t){if(t<2**8)return 1;if(t<2**16)return 2;if(t<2**24)return 3;if(t<2**32)return 4;throw new G("Length is too large.")}function FS(t){const{chainId:e,nonce:r,to:n}=t,s=t.contractAddress??t.address,i=bt(jr(["0x05",gs([e?Y(e):"0x",s,r?Y(r):"0x"])]));return n==="bytes"?an(i):i}async function hu(t){const{authorization:e,signature:r}=t;return Fg({hash:FS(e),signature:r??e})}class MS extends G{constructor(e,{account:r,docsPath:n,chain:s,data:i,gas:a,gasPrice:o,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:l,to:f,value:p}){var b;const d=Po({from:r==null?void 0:r.address,to:f,value:typeof p<"u"&&`${kh(p)} ${((b=s==null?void 0:s.nativeCurrency)==null?void 0:b.symbol)||"ETH"}`,data:i,gas:a,gasPrice:typeof o<"u"&&`${Gt(o)} gwei`,maxFeePerGas:typeof c<"u"&&`${Gt(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${Gt(u)} gwei`,nonce:l});super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Estimate Gas Arguments:",d].filter(Boolean),name:"EstimateGasExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class ki extends G{constructor({cause:e,message:r}={}){var s;const n=(s=r==null?void 0:r.replace("execution reverted: ",""))==null?void 0:s.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:e,name:"ExecutionRevertedError"})}}Object.defineProperty(ki,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(ki,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});class Zs extends G{constructor({cause:e,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${Gt(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:e,name:"FeeCapTooHighError"})}}Object.defineProperty(Zs,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});class cd extends G{constructor({cause:e,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${Gt(r)}`:""} gwei) cannot be lower than the block base fee.`,{cause:e,name:"FeeCapTooLowError"})}}Object.defineProperty(cd,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});class ud extends G{constructor({cause:e,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}is higher than the next one expected.`,{cause:e,name:"NonceTooHighError"})}}Object.defineProperty(ud,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class ld extends G{constructor({cause:e,nonce:r}={}){super([`Nonce provided for the transaction ${r?`(${r}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(`
63
+ `),{cause:e,name:"NonceTooLowError"})}}Object.defineProperty(ld,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class fd extends G{constructor({cause:e,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}exceeds the maximum allowed nonce.`,{cause:e,name:"NonceMaxValueError"})}}Object.defineProperty(fd,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});class dd extends G{constructor({cause:e}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
64
+ `),{cause:e,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}}Object.defineProperty(dd,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class hd extends G{constructor({cause:e,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:e,name:"IntrinsicGasTooHighError"})}}Object.defineProperty(hd,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class pd extends G{constructor({cause:e,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction is too low.`,{cause:e,name:"IntrinsicGasTooLowError"})}}Object.defineProperty(pd,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class yd extends G{constructor({cause:e}){super("The transaction type is not supported for this chain.",{cause:e,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(yd,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class io extends G{constructor({cause:e,maxPriorityFeePerGas:r,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${r?` = ${Gt(r)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${Gt(n)} gwei`:""}).`].join(`
65
+ `),{cause:e,name:"TipAboveFeeCapError"})}}Object.defineProperty(io,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});class Oo extends G{constructor({cause:e}){super(`An error occurred while executing: ${e==null?void 0:e.shortMessage}`,{cause:e,name:"UnknownNodeError"})}}function pu(t,e){const r=(t.details||"").toLowerCase(),n=t instanceof G?t.walk(s=>(s==null?void 0:s.code)===ki.code):t;return n instanceof G?new ki({cause:t,message:n.details}):ki.nodeMessage.test(r)?new ki({cause:t,message:t.details}):Zs.nodeMessage.test(r)?new Zs({cause:t,maxFeePerGas:e==null?void 0:e.maxFeePerGas}):cd.nodeMessage.test(r)?new cd({cause:t,maxFeePerGas:e==null?void 0:e.maxFeePerGas}):ud.nodeMessage.test(r)?new ud({cause:t,nonce:e==null?void 0:e.nonce}):ld.nodeMessage.test(r)?new ld({cause:t,nonce:e==null?void 0:e.nonce}):fd.nodeMessage.test(r)?new fd({cause:t,nonce:e==null?void 0:e.nonce}):dd.nodeMessage.test(r)?new dd({cause:t}):hd.nodeMessage.test(r)?new hd({cause:t,gas:e==null?void 0:e.gas}):pd.nodeMessage.test(r)?new pd({cause:t,gas:e==null?void 0:e.gas}):yd.nodeMessage.test(r)?new yd({cause:t}):io.nodeMessage.test(r)?new io({cause:t,maxFeePerGas:e==null?void 0:e.maxFeePerGas,maxPriorityFeePerGas:e==null?void 0:e.maxPriorityFeePerGas}):new Oo({cause:t})}function $S(t,{docsPath:e,...r}){const n=(()=>{const s=pu(t,r);return s instanceof Oo?t:s})();return new MS(n,{docsPath:e,...r})}function ea(t,{format:e}){if(!e)return{};const r={};function n(i){const a=Object.keys(i);for(const o of a)o in t&&(r[o]=t[o]),i[o]&&typeof i[o]=="object"&&!Array.isArray(i[o])&&n(i[o])}const s=e(t||{});return n(s),r}function _h(t,e){return({exclude:r,format:n})=>({exclude:r,format:(s,i)=>{const a=e(s,i);if(r)for(const o of r)delete a[o];return{...a,...n(s,i)}},type:t})}const jS={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function As(t,e){const r={};return typeof t.authorizationList<"u"&&(r.authorizationList=HS(t.authorizationList)),typeof t.accessList<"u"&&(r.accessList=t.accessList),typeof t.blobVersionedHashes<"u"&&(r.blobVersionedHashes=t.blobVersionedHashes),typeof t.blobs<"u"&&(typeof t.blobs[0]!="string"?r.blobs=t.blobs.map(n=>tt(n)):r.blobs=t.blobs),typeof t.data<"u"&&(r.data=t.data),t.account&&(r.from=t.account.address),typeof t.from<"u"&&(r.from=t.from),typeof t.gas<"u"&&(r.gas=Y(t.gas)),typeof t.gasPrice<"u"&&(r.gasPrice=Y(t.gasPrice)),typeof t.maxFeePerBlobGas<"u"&&(r.maxFeePerBlobGas=Y(t.maxFeePerBlobGas)),typeof t.maxFeePerGas<"u"&&(r.maxFeePerGas=Y(t.maxFeePerGas)),typeof t.maxPriorityFeePerGas<"u"&&(r.maxPriorityFeePerGas=Y(t.maxPriorityFeePerGas)),typeof t.nonce<"u"&&(r.nonce=Y(t.nonce)),typeof t.to<"u"&&(r.to=t.to),typeof t.type<"u"&&(r.type=jS[t.type]),typeof t.value<"u"&&(r.value=Y(t.value)),r}function HS(t){return t.map(e=>({address:e.address,r:e.r?Y(BigInt(e.r)):e.r,s:e.s?Y(BigInt(e.s)):e.s,chainId:Y(e.chainId),nonce:Y(e.nonce),...typeof e.yParity<"u"?{yParity:Y(e.yParity)}:{},...typeof e.v<"u"&&typeof e.yParity>"u"?{v:Y(e.v)}:{}}))}function Bp(t){if(!(!t||t.length===0))return t.reduce((e,{slot:r,value:n})=>{if(r.length!==66)throw new gp({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new gp({size:n.length,targetSize:66,type:"hex"});return e[r]=n,e},{})}function LS(t){const{balance:e,nonce:r,state:n,stateDiff:s,code:i}=t,a={};if(i!==void 0&&(a.code=i),e!==void 0&&(a.balance=Y(e)),r!==void 0&&(a.nonce=Y(r)),n!==void 0&&(a.state=Bp(n)),s!==void 0){if(a.state)throw new wS;a.stateDiff=Bp(s)}return a}function Ih(t){if(!t)return;const e={};for(const{address:r,...n}of t){if(!ut(r,{strict:!1}))throw new $t({address:r});if(e[r])throw new gS({address:r});e[r]=LS(n)}return e}const yu=2n**256n-1n;function jn(t){const{account:e,maxFeePerGas:r,maxPriorityFeePerGas:n,to:s}=t,i=e?Le(e):void 0;if(i&&!ut(i.address))throw new $t({address:i.address});if(s&&!ut(s))throw new $t({address:s});if(r&&r>yu)throw new Zs({maxFeePerGas:r});if(n&&r&&n>r)throw new io({maxFeePerGas:r,maxPriorityFeePerGas:n})}class jg extends G{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class Ph extends G{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class DS extends G{constructor({maxPriorityFeePerGas:e}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${Gt(e)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class Hg extends G{constructor({blockHash:e,blockNumber:r}){let n="Block";e&&(n=`Block at hash "${e}"`),r&&(n=`Block at number "${r}"`),super(`${n} could not be found.`,{name:"BlockNotFoundError"})}}const Lg={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function Bo(t,e){const r={...t,blockHash:t.blockHash?t.blockHash:null,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,chainId:t.chainId?gr(t.chainId):void 0,gas:t.gas?BigInt(t.gas):void 0,gasPrice:t.gasPrice?BigInt(t.gasPrice):void 0,maxFeePerBlobGas:t.maxFeePerBlobGas?BigInt(t.maxFeePerBlobGas):void 0,maxFeePerGas:t.maxFeePerGas?BigInt(t.maxFeePerGas):void 0,maxPriorityFeePerGas:t.maxPriorityFeePerGas?BigInt(t.maxPriorityFeePerGas):void 0,nonce:t.nonce?gr(t.nonce):void 0,to:t.to?t.to:null,transactionIndex:t.transactionIndex?Number(t.transactionIndex):null,type:t.type?Lg[t.type]:void 0,typeHex:t.type?t.type:void 0,value:t.value?BigInt(t.value):void 0,v:t.v?BigInt(t.v):void 0};return t.authorizationList&&(r.authorizationList=VS(t.authorizationList)),r.yParity=(()=>{if(t.yParity)return Number(t.yParity);if(typeof r.v=="bigint"){if(r.v===0n||r.v===27n)return 0;if(r.v===1n||r.v===28n)return 1;if(r.v>=35n)return r.v%2n===0n?1:0}})(),r.type==="legacy"&&(delete r.accessList,delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas,delete r.yParity),r.type==="eip2930"&&(delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas),r.type==="eip1559"&&delete r.maxFeePerBlobGas,r}const zS=_h("transaction",Bo);function VS(t){return t.map(e=>({address:e.address,chainId:Number(e.chainId),nonce:Number(e.nonce),r:e.r,s:e.s,yParity:Number(e.yParity)}))}function Oh(t,e){const r=(t.transactions??[]).map(n=>typeof n=="string"?n:Bo(n));return{...t,baseFeePerGas:t.baseFeePerGas?BigInt(t.baseFeePerGas):null,blobGasUsed:t.blobGasUsed?BigInt(t.blobGasUsed):void 0,difficulty:t.difficulty?BigInt(t.difficulty):void 0,excessBlobGas:t.excessBlobGas?BigInt(t.excessBlobGas):void 0,gasLimit:t.gasLimit?BigInt(t.gasLimit):void 0,gasUsed:t.gasUsed?BigInt(t.gasUsed):void 0,hash:t.hash?t.hash:null,logsBloom:t.logsBloom?t.logsBloom:null,nonce:t.nonce?t.nonce:null,number:t.number?BigInt(t.number):null,size:t.size?BigInt(t.size):void 0,timestamp:t.timestamp?BigInt(t.timestamp):void 0,transactions:r,totalDifficulty:t.totalDifficulty?BigInt(t.totalDifficulty):null}}const GS=_h("block",Oh);async function Pr(t,{blockHash:e,blockNumber:r,blockTag:n=t.experimental_blockTag??"latest",includeTransactions:s}={}){var u,l,f;const i=s??!1,a=r!==void 0?Y(r):void 0;let o=null;if(e?o=await t.request({method:"eth_getBlockByHash",params:[e,i]},{dedupe:!0}):o=await t.request({method:"eth_getBlockByNumber",params:[a||n,i]},{dedupe:!!a}),!o)throw new Hg({blockHash:e,blockNumber:r});return(((f=(l=(u=t.chain)==null?void 0:u.formatters)==null?void 0:l.block)==null?void 0:f.format)||Oh)(o,"getBlock")}async function Bh(t){const e=await t.request({method:"eth_gasPrice"});return BigInt(e)}async function qS(t,e){return Dg(t,e)}async function Dg(t,e){var i,a;const{block:r,chain:n=t.chain,request:s}=e||{};try{const o=((i=n==null?void 0:n.fees)==null?void 0:i.maxPriorityFeePerGas)??((a=n==null?void 0:n.fees)==null?void 0:a.defaultPriorityFee);if(typeof o=="function"){const u=r||await re(t,Pr,"getBlock")({}),l=await o({block:u,client:t,request:s});if(l===null)throw new Error;return l}if(typeof o<"u")return o;const c=await t.request({method:"eth_maxPriorityFeePerGas"});return ft(c)}catch{const[o,c]=await Promise.all([r?Promise.resolve(r):re(t,Pr,"getBlock")({}),re(t,Bh,"getGasPrice")({})]);if(typeof o.baseFeePerGas!="bigint")throw new Ph;const u=c-o.baseFeePerGas;return u<0n?0n:u}}async function WS(t,e){return md(t,e)}async function md(t,e){var p,d;const{block:r,chain:n=t.chain,request:s,type:i="eip1559"}=e||{},a=await(async()=>{var b,g;return typeof((b=n==null?void 0:n.fees)==null?void 0:b.baseFeeMultiplier)=="function"?n.fees.baseFeeMultiplier({block:r,client:t,request:s}):((g=n==null?void 0:n.fees)==null?void 0:g.baseFeeMultiplier)??1.2})();if(a<1)throw new jg;const c=10**(((p=a.toString().split(".")[1])==null?void 0:p.length)??0),u=b=>b*BigInt(Math.ceil(a*c))/BigInt(c),l=r||await re(t,Pr,"getBlock")({});if(typeof((d=n==null?void 0:n.fees)==null?void 0:d.estimateFeesPerGas)=="function"){const b=await n.fees.estimateFeesPerGas({block:r,client:t,multiply:u,request:s,type:i});if(b!==null)return b}if(i==="eip1559"){if(typeof l.baseFeePerGas!="bigint")throw new Ph;const b=typeof(s==null?void 0:s.maxPriorityFeePerGas)=="bigint"?s.maxPriorityFeePerGas:await Dg(t,{block:l,chain:n,request:s}),g=u(l.baseFeePerGas);return{maxFeePerGas:(s==null?void 0:s.maxFeePerGas)??g+b,maxPriorityFeePerGas:b}}return{gasPrice:(s==null?void 0:s.gasPrice)??u(await re(t,Bh,"getGasPrice")({}))}}async function Ch(t,{address:e,blockTag:r="latest",blockNumber:n}){const s=await t.request({method:"eth_getTransactionCount",params:[e,typeof n=="bigint"?Y(n):r]},{dedupe:!!n});return gr(s)}function Rh(t){const{kzg:e}=t,r=t.to??(typeof t.blobs[0]=="string"?"hex":"bytes"),n=typeof t.blobs[0]=="string"?t.blobs.map(i=>an(i)):t.blobs,s=[];for(const i of n)s.push(Uint8Array.from(e.blobToKzgCommitment(i)));return r==="bytes"?s:s.map(i=>tt(i))}function Nh(t){const{kzg:e}=t,r=t.to??(typeof t.blobs[0]=="string"?"hex":"bytes"),n=typeof t.blobs[0]=="string"?t.blobs.map(a=>an(a)):t.blobs,s=typeof t.commitments[0]=="string"?t.commitments.map(a=>an(a)):t.commitments,i=[];for(let a=0;a<n.length;a++){const o=n[a],c=s[a];i.push(Uint8Array.from(e.computeBlobKzgProof(o,c)))}return r==="bytes"?i:i.map(a=>tt(a))}function KS(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const s=BigInt(32),i=BigInt(4294967295),a=Number(r>>s&i),o=Number(r&i),c=n?4:0,u=n?0:4;t.setUint32(e+c,a,n),t.setUint32(e+u,o,n)}function XS(t,e,r){return t&e^~t&r}function YS(t,e,r){return t&e^t&r^e&r}class JS extends cu{constructor(e,r,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=rl(this.buffer)}update(e){ms(this),e=Pn(e),ys(e);const{view:r,buffer:n,blockLen:s}=this,i=e.length;for(let a=0;a<i;){const o=Math.min(s-this.pos,i-a);if(o===s){const c=rl(e);for(;s<=i-a;a+=s)this.process(c,a);continue}n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ms(this),bh(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:s,isLE:i}=this;let{pos:a}=this;r[a++]=128,Nn(this.buffer.subarray(a)),this.padOffset>s-a&&(this.process(n,0),a=0);for(let f=a;f<s;f++)r[f]=0;KS(n,s-8,BigInt(this.length*8),i),this.process(n,0);const o=rl(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)o.setUint32(4*f,l[f],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:s,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=s,e.pos=o,s%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Xn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ZS=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]),Yn=new Uint32Array(64);class QS extends JS{constructor(e=32){super(64,e,8,!1),this.A=Xn[0]|0,this.B=Xn[1]|0,this.C=Xn[2]|0,this.D=Xn[3]|0,this.E=Xn[4]|0,this.F=Xn[5]|0,this.G=Xn[6]|0,this.H=Xn[7]|0}get(){const{A:e,B:r,C:n,D:s,E:i,F:a,G:o,H:c}=this;return[e,r,n,s,i,a,o,c]}set(e,r,n,s,i,a,o,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=s|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=c|0}process(e,r){for(let f=0;f<16;f++,r+=4)Yn[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){const p=Yn[f-15],d=Yn[f-2],b=qr(p,7)^qr(p,18)^p>>>3,g=qr(d,17)^qr(d,19)^d>>>10;Yn[f]=g+Yn[f-7]+b+Yn[f-16]|0}let{A:n,B:s,C:i,D:a,E:o,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){const p=qr(o,6)^qr(o,11)^qr(o,25),d=l+p+XS(o,c,u)+ZS[f]+Yn[f]|0,g=(qr(n,2)^qr(n,13)^qr(n,22))+YS(n,s,i)|0;l=u,u=c,c=o,o=a+d|0,a=i,i=s,s=n,n=d+g|0}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,s,i,a,o,c,u,l)}roundClean(){Nn(Yn)}destroy(){this.set(0,0,0,0,0,0,0,0),Nn(this.buffer)}}const zg=pg(()=>new QS),e8=zg;function Aa(t,e){const r=e||"hex",n=e8(Nr(t,{strict:!1})?Zi(t):t);return r==="bytes"?n:Ft(n)}function t8(t){const{commitment:e,version:r=1}=t,n=t.to??(typeof e=="string"?"hex":"bytes"),s=Aa(e,"bytes");return s.set([r],0),n==="bytes"?s:tt(s)}function Vg(t){const{commitments:e,version:r}=t,n=t.to??(typeof e[0]=="string"?"hex":"bytes"),s=[];for(const i of e)s.push(t8({commitment:i,to:n,version:r}));return s}const Cp=6,Gg=32,Uh=4096,qg=Gg*Uh,Rp=qg*Cp-1-1*Uh*Cp,Wg=1;class r8 extends G{constructor({maxSize:e,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${e} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}}class Kg extends G{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class n8 extends G{constructor({hash:e,size:r}){super(`Versioned hash "${e}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}}class s8 extends G{constructor({hash:e,version:r}){super(`Versioned hash "${e}" version is invalid.`,{metaMessages:[`Expected: ${Wg}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}function i8(t){const e=t.to??(typeof t.data=="string"?"hex":"bytes"),r=typeof t.data=="string"?an(t.data):t.data,n=Ge(r);if(!n)throw new Kg;if(n>Rp)throw new r8({maxSize:Rp,size:n});const s=[];let i=!0,a=0;for(;i;){const o=xh(new Uint8Array(qg));let c=0;for(;c<Uh;){const u=r.slice(a,a+(Gg-1));if(o.pushByte(0),o.pushBytes(u),u.length<31){o.pushByte(128),i=!1;break}c++,a+=31}s.push(o)}return e==="bytes"?s.map(o=>o.bytes):s.map(o=>tt(o.bytes))}function Xg(t){const{data:e,kzg:r,to:n}=t,s=t.blobs??i8({data:e,to:n}),i=t.commitments??Rh({blobs:s,kzg:r,to:n}),a=t.proofs??Nh({blobs:s,commitments:i,kzg:r,to:n}),o=[];for(let c=0;c<s.length;c++)o.push({blob:s[c],commitment:i[c],proof:a[c]});return o}function Yg(t){if(t.type)return t.type;if(typeof t.authorizationList<"u")return"eip7702";if(typeof t.blobs<"u"||typeof t.blobVersionedHashes<"u"||typeof t.maxFeePerBlobGas<"u"||typeof t.sidecars<"u")return"eip4844";if(typeof t.maxFeePerGas<"u"||typeof t.maxPriorityFeePerGas<"u")return"eip1559";if(typeof t.gasPrice<"u")return typeof t.accessList<"u"?"eip2930":"legacy";throw new AS({transaction:t})}function mu(t,{docsPath:e,...r}){const n=(()=>{const s=pu(t,r);return s instanceof Oo?t:s})();return new xS(n,{docsPath:e,...r})}async function Ss(t){const e=await t.request({method:"eth_chainId"},{dedupe:!0});return gr(e)}async function Fh(t,e){var N,C,j,M,H;const{account:r=t.account,accessList:n,authorizationList:s,chain:i=t.chain,blobVersionedHashes:a,blobs:o,data:c,gas:u,gasPrice:l,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:d,nonce:b,nonceManager:g,to:A,type:S,value:T,...v}=e,w=await(async()=>{if(!r||!g||typeof b<"u")return b;const V=Le(r),Q=i?i.id:await re(t,Ss,"getChainId")({});return await g.consume({address:V.address,chainId:Q,client:t})})();jn(e);const x=(C=(N=i==null?void 0:i.formatters)==null?void 0:N.transactionRequest)==null?void 0:C.format,I=(x||As)({...ea(v,{format:x}),account:r?Le(r):void 0,accessList:n,authorizationList:s,blobs:o,blobVersionedHashes:a,data:c,gas:u,gasPrice:l,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:d,nonce:w,to:A,type:S,value:T},"fillTransaction");try{const V=await t.request({method:"eth_fillTransaction",params:[I]}),U=(((M=(j=i==null?void 0:i.formatters)==null?void 0:j.transaction)==null?void 0:M.format)||Bo)(V.tx);delete U.blockHash,delete U.blockNumber,delete U.r,delete U.s,delete U.transactionIndex,delete U.v,delete U.yParity,U.data=U.input,U.gas&&(U.gas=e.gas??U.gas),U.gasPrice&&(U.gasPrice=e.gasPrice??U.gasPrice),U.maxFeePerBlobGas&&(U.maxFeePerBlobGas=e.maxFeePerBlobGas??U.maxFeePerBlobGas),U.maxFeePerGas&&(U.maxFeePerGas=e.maxFeePerGas??U.maxFeePerGas),U.maxPriorityFeePerGas&&(U.maxPriorityFeePerGas=e.maxPriorityFeePerGas??U.maxPriorityFeePerGas),U.nonce&&(U.nonce=e.nonce??U.nonce);const K=await(async()=>{var L,J;if(typeof((L=i==null?void 0:i.fees)==null?void 0:L.baseFeeMultiplier)=="function"){const B=await re(t,Pr,"getBlock")({});return i.fees.baseFeeMultiplier({block:B,client:t,request:e})}return((J=i==null?void 0:i.fees)==null?void 0:J.baseFeeMultiplier)??1.2})();if(K<1)throw new jg;const q=10**(((H=K.toString().split(".")[1])==null?void 0:H.length)??0),O=L=>L*BigInt(Math.ceil(K*q))/BigInt(q);return U.maxFeePerGas&&!e.maxFeePerGas&&(U.maxFeePerGas=O(U.maxFeePerGas)),U.gasPrice&&!e.gasPrice&&(U.gasPrice=O(U.gasPrice)),{raw:V.raw,transaction:{from:I.from,...U}}}catch(V){throw mu(V,{...e,chain:t.chain})}}const Mh=["blobVersionedHashes","chainId","fees","gas","nonce","type"],Np=new Map,il=new Qi(128);async function Co(t,e){var w,x,_;let r=e;r.account??(r.account=t.account),r.parameters??(r.parameters=Mh);const{account:n,chain:s=t.chain,nonceManager:i,parameters:a}=r,o=(()=>{if(typeof(s==null?void 0:s.prepareTransactionRequest)=="function")return{fn:s.prepareTransactionRequest,runAt:["beforeFillTransaction"]};if(Array.isArray(s==null?void 0:s.prepareTransactionRequest))return{fn:s.prepareTransactionRequest[0],runAt:s.prepareTransactionRequest[1].runAt}})();let c;async function u(){return c||(typeof r.chainId<"u"?r.chainId:s?s.id:(c=await re(t,Ss,"getChainId")({}),c))}const l=n&&Le(n);let f=r.nonce;if(a.includes("nonce")&&typeof f>"u"&&l&&i){const I=await u();f=await i.consume({address:l.address,chainId:I,client:t})}o!=null&&o.fn&&((w=o.runAt)!=null&&w.includes("beforeFillTransaction"))&&(r=await o.fn({...r,chain:s},{phase:"beforeFillTransaction"}),f??(f=r.nonce));const d=((a.includes("blobVersionedHashes")||a.includes("sidecars"))&&r.kzg&&r.blobs||il.get(t.uid)===!1||!["fees","gas"].some(N=>a.includes(N))?!1:!!(a.includes("chainId")&&typeof r.chainId!="number"||a.includes("nonce")&&typeof f!="number"||a.includes("fees")&&typeof r.gasPrice!="bigint"&&(typeof r.maxFeePerGas!="bigint"||typeof r.maxPriorityFeePerGas!="bigint")||a.includes("gas")&&typeof r.gas!="bigint"))?await re(t,Fh,"fillTransaction")({...r,nonce:f}).then(I=>{const{chainId:N,from:C,gas:j,gasPrice:M,nonce:H,maxFeePerBlobGas:V,maxFeePerGas:Q,maxPriorityFeePerGas:U,type:K,...ee}=I.transaction;return il.set(t.uid,!0),{...r,...C?{from:C}:{},...K?{type:K}:{},...typeof N<"u"?{chainId:N}:{},...typeof j<"u"?{gas:j}:{},...typeof M<"u"?{gasPrice:M}:{},...typeof H<"u"?{nonce:H}:{},...typeof V<"u"?{maxFeePerBlobGas:V}:{},...typeof Q<"u"?{maxFeePerGas:Q}:{},...typeof U<"u"?{maxPriorityFeePerGas:U}:{},..."nonceKey"in ee&&typeof ee.nonceKey<"u"?{nonceKey:ee.nonceKey}:{}}}).catch(I=>{var j;const N=I;return N.name!=="TransactionExecutionError"||((j=N.walk)==null?void 0:j.call(N,M=>{const H=M;return H.name==="MethodNotFoundRpcError"||H.name==="MethodNotSupportedRpcError"}))&&il.set(t.uid,!1),r}):r;f??(f=d.nonce),r={...d,...l?{from:l==null?void 0:l.address}:{},...f?{nonce:f}:{}};const{blobs:b,gas:g,kzg:A,type:S}=r;o!=null&&o.fn&&((x=o.runAt)!=null&&x.includes("beforeFillParameters"))&&(r=await o.fn({...r,chain:s},{phase:"beforeFillParameters"}));let T;async function v(){return T||(T=await re(t,Pr,"getBlock")({blockTag:"latest"}),T)}if(a.includes("nonce")&&typeof f>"u"&&l&&!i&&(r.nonce=await re(t,Ch,"getTransactionCount")({address:l.address,blockTag:"pending"})),(a.includes("blobVersionedHashes")||a.includes("sidecars"))&&b&&A){const I=Rh({blobs:b,kzg:A});if(a.includes("blobVersionedHashes")){const N=Vg({commitments:I,to:"hex"});r.blobVersionedHashes=N}if(a.includes("sidecars")){const N=Nh({blobs:b,commitments:I,kzg:A}),C=Xg({blobs:b,commitments:I,proofs:N,to:"hex"});r.sidecars=C}}if(a.includes("chainId")&&(r.chainId=await u()),(a.includes("fees")||a.includes("type"))&&typeof S>"u")try{r.type=Yg(r)}catch{let I=Np.get(t.uid);if(typeof I>"u"){const N=await v();I=typeof(N==null?void 0:N.baseFeePerGas)=="bigint",Np.set(t.uid,I)}r.type=I?"eip1559":"legacy"}if(a.includes("fees"))if(r.type!=="legacy"&&r.type!=="eip2930"){if(typeof r.maxFeePerGas>"u"||typeof r.maxPriorityFeePerGas>"u"){const I=await v(),{maxFeePerGas:N,maxPriorityFeePerGas:C}=await md(t,{block:I,chain:s,request:r});if(typeof r.maxPriorityFeePerGas>"u"&&r.maxFeePerGas&&r.maxFeePerGas<C)throw new DS({maxPriorityFeePerGas:C});r.maxPriorityFeePerGas=C,r.maxFeePerGas=N}}else{if(typeof r.maxFeePerGas<"u"||typeof r.maxPriorityFeePerGas<"u")throw new Ph;if(typeof r.gasPrice>"u"){const I=await v(),{gasPrice:N}=await md(t,{block:I,chain:s,request:r,type:"legacy"});r.gasPrice=N}}return a.includes("gas")&&typeof g>"u"&&(r.gas=await re(t,$h,"estimateGas")({...r,account:l,prepare:(l==null?void 0:l.type)==="local"?[]:["blobVersionedHashes"]})),o!=null&&o.fn&&((_=o.runAt)!=null&&_.includes("afterFillParameters"))&&(r=await o.fn({...r,chain:s},{phase:"afterFillParameters"})),jn(r),delete r.parameters,r}async function $h(t,e){var a,o,c;const{account:r=t.account,prepare:n=!0}=e,s=r?Le(r):void 0,i=(()=>{if(Array.isArray(n))return n;if((s==null?void 0:s.type)!=="local")return["blobVersionedHashes"]})();try{const u=await(async()=>{if(e.to)return e.to;if(e.authorizationList&&e.authorizationList.length>0)return await hu({authorization:e.authorizationList[0]}).catch(()=>{throw new G("`to` is required. Could not infer from `authorizationList`")})})(),{accessList:l,authorizationList:f,blobs:p,blobVersionedHashes:d,blockNumber:b,blockTag:g,data:A,gas:S,gasPrice:T,maxFeePerBlobGas:v,maxFeePerGas:w,maxPriorityFeePerGas:x,nonce:_,value:I,stateOverride:N,...C}=n?await Co(t,{...e,parameters:i,to:u}):e;if(S&&e.gas!==S)return S;const M=(typeof b=="bigint"?Y(b):void 0)||g,H=Ih(N);jn(e);const V=(c=(o=(a=t.chain)==null?void 0:a.formatters)==null?void 0:o.transactionRequest)==null?void 0:c.format,U=(V||As)({...ea(C,{format:V}),account:s,accessList:l,authorizationList:f,blobs:p,blobVersionedHashes:d,data:A,gasPrice:T,maxFeePerBlobGas:v,maxFeePerGas:w,maxPriorityFeePerGas:x,nonce:_,to:u,value:I},"estimateGas");return BigInt(await t.request({method:"eth_estimateGas",params:H?[U,M??t.experimental_blockTag??"latest",H]:M?[U,M]:[U]}))}catch(u){throw $S(u,{...e,account:s,chain:t.chain})}}async function Jg(t,e){const{abi:r,address:n,args:s,functionName:i,dataSuffix:a,...o}=e,c=or({abi:r,args:s,functionName:i});try{return await re(t,$h,"estimateGas")({data:`${c}${a?a.replace("0x",""):""}`,to:n,...o})}catch(u){const l=o.account?Le(o.account):void 0;throw Js(u,{abi:r,address:n,args:s,docsPath:"/docs/contract/estimateContractGas",functionName:i,sender:l==null?void 0:l.address})}}function ta(t,e){if(!ut(t,{strict:!1}))throw new $t({address:t});if(!ut(e,{strict:!1}))throw new $t({address:e});return t.toLowerCase()===e.toLowerCase()}const Up="/docs/contract/decodeEventLog";function Rc(t){const{abi:e,data:r,strict:n,topics:s}=t,i=n??!0,[a,...o]=s;if(!a)throw new YE({docsPath:Up});const c=e.find(S=>S.type==="event"&&a===uu(Rr(S)));if(!(c&&"name"in c)||c.type!=="event")throw new JE(a,{docsPath:Up});const{name:u,inputs:l}=c,f=l==null?void 0:l.some(S=>!("name"in S&&S.name)),p=f?[]:{},d=l.map((S,T)=>[S,T]).filter(([S])=>"indexed"in S&&S.indexed),b=[];for(let S=0;S<d.length;S++){const[T,v]=d[S],w=o[S];if(!w){if(i)throw new yh({abiItem:c,param:T});b.push([T,v]);continue}p[f?v:T.name||v]=a8({param:T,value:w})}const g=l.filter(S=>!("indexed"in S&&S.indexed)),A=i?g:[...b.map(([S])=>S),...g];if(A.length>0){if(r&&r!=="0x")try{const S=Io(A,r);if(S){let T=0;if(!i)for(const[v,w]of b)p[f?w:v.name||w]=S[T++];if(f)for(let v=0;v<l.length;v++)p[v]===void 0&&T<S.length&&(p[v]=S[T++]);else for(let v=0;v<g.length;v++)p[g[v].name]=S[T++]}}catch(S){if(i)throw S instanceof Qb||S instanceof _g?new Cc({abiItem:c,data:r,params:A,size:Ge(r)}):S}else if(i)throw new Cc({abiItem:c,data:"0x",params:A,size:0})}return{eventName:u,args:Object.values(p).length>0?p:void 0}}function a8({param:t,value:e}){return t.type==="string"||t.type==="bytes"||t.type==="tuple"||t.type.match(/^(.*)\[(\d+)?\]$/)?e:(Io([t],e)||[])[0]}function jh(t){const{abi:e,args:r,logs:n,strict:s=!0}=t,i=(()=>{if(t.eventName)return Array.isArray(t.eventName)?t.eventName:[t.eventName]})();return n.map(a=>{var l;const o=e.filter(f=>f.type==="event"&&a.topics[0]===uu(f));if(o.length===0)return null;let c,u;for(const f of o)try{c=Rc({...a,abi:[f],strict:!0}),u=f;break}catch{}if(!c&&!s){u=o[0];try{c=Rc({...a,abi:[u],strict:!1})}catch{const f=(l=u.inputs)==null?void 0:l.some(p=>!("name"in p&&p.name));return{...a,args:f?[]:{},eventName:u.name}}}return!c||!u||i&&!i.includes(c.eventName)||!o8({args:c.args,inputs:u.inputs,matchArgs:r})?null:{...c,...a}}).filter(Boolean)}function o8(t){const{args:e,inputs:r,matchArgs:n}=t;if(!n)return!0;if(!e)return!1;function s(i,a,o){try{return i.type==="address"?ta(a,o):i.type==="string"||i.type==="bytes"?bt(Zi(a))===o:a===o}catch{return!1}}return Array.isArray(e)&&Array.isArray(n)?n.every((i,a)=>{if(i==null)return!0;const o=r[a];return o?(Array.isArray(i)?i:[i]).some(u=>s(o,u,e[a])):!1}):typeof e=="object"&&!Array.isArray(e)&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).every(([i,a])=>{if(a==null)return!0;const o=r.find(u=>u.name===i);return o?(Array.isArray(a)?a:[a]).some(u=>s(o,u,e[i])):!1}):!1}function Un(t,{args:e,eventName:r}={}){return{...t,blockHash:t.blockHash?t.blockHash:null,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,blockTimestamp:t.blockTimestamp?BigInt(t.blockTimestamp):t.blockTimestamp===null?null:void 0,logIndex:t.logIndex?Number(t.logIndex):null,transactionHash:t.transactionHash?t.transactionHash:null,transactionIndex:t.transactionIndex?Number(t.transactionIndex):null,...r?{args:e,eventName:r}:{}}}async function Hh(t,{address:e,blockHash:r,fromBlock:n,toBlock:s,event:i,events:a,args:o,strict:c}={}){const u=c??!1,l=a??(i?[i]:void 0);let f=[];l&&(f=[l.flatMap(g=>_o({abi:[g],eventName:g.name,args:a?void 0:o}))],i&&(f=f[0]));let p;r?p=await t.request({method:"eth_getLogs",params:[{address:e,topics:f,blockHash:r}]}):p=await t.request({method:"eth_getLogs",params:[{address:e,topics:f,fromBlock:typeof n=="bigint"?Y(n):n,toBlock:typeof s=="bigint"?Y(s):s}]});const d=p.map(b=>Un(b));return l?jh({abi:l,args:o,logs:d,strict:u}):d}async function Lh(t,e){const{abi:r,address:n,args:s,blockHash:i,eventName:a,fromBlock:o,toBlock:c,strict:u}=e,l=a?ci({abi:r,name:a}):void 0,f=l?void 0:r.filter(p=>p.type==="event");return re(t,Hh,"getLogs")({address:n,args:s,blockHash:i,event:l,events:f,fromBlock:o,toBlock:c,strict:u})}const al="/docs/contract/decodeFunctionResult";function ui(t){const{abi:e,args:r,functionName:n,data:s}=t;let i=e[0];if(n){const o=ci({abi:e,args:r,name:n});if(!o)throw new zi(n,{docsPath:al});i=o}if(i.type!=="function")throw new zi(void 0,{docsPath:al});if(!i.outputs)throw new tg(i.name,{docsPath:al});const a=Io(i.outputs,s);if(a&&a.length>1)return a;if(a&&a.length===1)return a[0]}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Dh=BigInt(0),bd=BigInt(1);function Ro(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function zh(t){if(!Ro(t))throw new Error("Uint8Array expected")}function ao(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function nc(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Zg(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Dh:BigInt("0x"+t)}const Qg=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",c8=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function oo(t){if(zh(t),Qg)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=c8[t[r]];return e}const yn={_0:48,_9:57,A:65,F:70,a:97,f:102};function Fp(t){if(t>=yn._0&&t<=yn._9)return t-yn._0;if(t>=yn.A&&t<=yn.F)return t-(yn.A-10);if(t>=yn.a&&t<=yn.f)return t-(yn.a-10)}function Nc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Qg)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let s=0,i=0;s<r;s++,i+=2){const a=Fp(t.charCodeAt(i)),o=Fp(t.charCodeAt(i+1));if(a===void 0||o===void 0){const c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[s]=a*16+o}return n}function zs(t){return Zg(oo(t))}function e1(t){return zh(t),Zg(oo(Uint8Array.from(t).reverse()))}function No(t,e){return Nc(t.toString(16).padStart(e*2,"0"))}function t1(t,e){return No(t,e).reverse()}function hr(t,e,r){let n;if(typeof e=="string")try{n=Nc(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(Ro(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=n.length;if(typeof r=="number"&&s!==r)throw new Error(t+" of length "+r+" expected, got "+s);return n}function Uc(...t){let e=0;for(let n=0;n<t.length;n++){const s=t[n];zh(s),e+=s.length}const r=new Uint8Array(e);for(let n=0,s=0;n<t.length;n++){const i=t[n];r.set(i,s),s+=i.length}return r}const ol=t=>typeof t=="bigint"&&Dh<=t;function Vh(t,e,r){return ol(t)&&ol(e)&&ol(r)&&e<=t&&t<r}function Ui(t,e,r,n){if(!Vh(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function u8(t){let e;for(e=0;t>Dh;t>>=bd,e+=1);return e}const bu=t=>(bd<<BigInt(t))-bd,cl=t=>new Uint8Array(t),Mp=t=>Uint8Array.from(t);function l8(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=cl(t),s=cl(t),i=0;const a=()=>{n.fill(1),s.fill(0),i=0},o=(...f)=>r(s,n,...f),c=(f=cl(0))=>{s=o(Mp([0]),f),n=o(),f.length!==0&&(s=o(Mp([1]),f),n=o())},u=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const p=[];for(;f<e;){n=o();const d=n.slice();p.push(d),f+=n.length}return Uc(...p)};return(f,p)=>{a(),c(f);let d;for(;!(d=p(u()));)c();return a(),d}}const f8={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||Ro(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function gu(t,e,r={}){const n=(s,i,a)=>{const o=f8[i];if(typeof o!="function")throw new Error("invalid validator function");const c=t[s];if(!(a&&c===void 0)&&!o(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+i+", got "+c)};for(const[s,i]of Object.entries(e))n(s,i,!1);for(const[s,i]of Object.entries(r))n(s,i,!0);return t}function $p(t){const e=new WeakMap;return(r,...n)=>{const s=e.get(r);if(s!==void 0)return s;const i=t(r,...n);return e.set(r,i),i}}const d8="0.1.1";function h8(){return d8}class le extends Error{static setStaticOptions(e){le.prototype.docsOrigin=e.docsOrigin,le.prototype.showVersion=e.showVersion,le.prototype.version=e.version}constructor(e,r={}){const n=(()=>{var l;if(r.cause instanceof le){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:(l=r.cause)!=null&&l.message?r.cause.message:r.details})(),s=r.cause instanceof le&&r.cause.docsPath||r.docsPath,i=r.docsOrigin??le.prototype.docsOrigin,a=`${i}${s??""}`,o=!!(r.version??le.prototype.showVersion),c=r.version??le.prototype.version,u=[e||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||s||o?["",n?`Details: ${n}`:void 0,s?`See: ${a}`:void 0,o?`Version: ${c}`:void 0]:[]].filter(l=>typeof l=="string").join(`
66
+ `);super(u,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsOrigin",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"showVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.cause=r.cause,this.details=n,this.docs=a,this.docsOrigin=i,this.docsPath=s,this.shortMessage=e,this.showVersion=o,this.version=c}walk(e){return r1(this,e)}}Object.defineProperty(le,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:"https://oxlib.sh",showVersion:!1,version:`ox@${h8()}`}});le.setStaticOptions(le.defaultStaticOptions);function r1(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?r1(t.cause,e):e?null:t}function Uo(t,e){if(Ti(t)>e)throw new O8({givenSize:Ti(t),maxSize:e})}const mn={zero:48,nine:57,A:65,F:70,a:97,f:102};function jp(t){if(t>=mn.zero&&t<=mn.nine)return t-mn.zero;if(t>=mn.A&&t<=mn.F)return t-(mn.A-10);if(t>=mn.a&&t<=mn.f)return t-(mn.a-10)}function p8(t,e={}){const{dir:r,size:n=32}=e;if(n===0)return t;if(t.length>n)throw new B8({size:t.length,targetSize:n,type:"Bytes"});const s=new Uint8Array(n);for(let i=0;i<n;i++){const a=r==="right";s[a?i:n-i-1]=t[a?i:t.length-i-1]}return s}function n1(t,e={}){const{dir:r="left"}=e;let n=t,s=0;for(let i=0;i<n.length-1&&n[r==="left"?i:n.length-i-1].toString()==="0";i++)s++;return n=r==="left"?n.slice(s):n.slice(0,n.length-s),n}function wu(t,e){if(ir(t)>e)throw new M8({givenSize:ir(t),maxSize:e})}function y8(t,e){if(typeof e=="number"&&e>0&&e>ir(t)-1)throw new d1({offset:e,position:"start",size:ir(t)})}function m8(t,e,r){if(typeof e=="number"&&typeof r=="number"&&ir(t)!==r-e)throw new d1({offset:r,position:"end",size:ir(t)})}function s1(t,e={}){const{dir:r,size:n=32}=e;if(n===0)return t;const s=t.replace("0x","");if(s.length>n*2)throw new $8({size:Math.ceil(s.length/2),targetSize:n,type:"Hex"});return`0x${s[r==="right"?"padEnd":"padStart"](n*2,"0")}`}const b8="#__bigint";function i1(t,e,r){return JSON.stringify(t,(n,s)=>typeof s=="bigint"?s.toString()+b8:s,r)}const g8=new TextDecoder,w8=new TextEncoder;function v8(t){return t instanceof Uint8Array?t:typeof t=="string"?a1(t):E8(t)}function E8(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function a1(t,e={}){const{size:r}=e;let n=t;r&&(wu(t,r),n=ei(t,r));let s=n.slice(2);s.length%2&&(s=`0${s}`);const i=s.length/2,a=new Uint8Array(i);for(let o=0,c=0;o<i;o++){const u=jp(s.charCodeAt(c++)),l=jp(s.charCodeAt(c++));if(u===void 0||l===void 0)throw new le(`Invalid byte sequence ("${s[c-2]}${s[c-1]}" in "${s}").`);a[o]=u<<4|l}return a}function A8(t,e={}){const{size:r}=e,n=w8.encode(t);return typeof r=="number"?(Uo(n,r),S8(n,r)):n}function S8(t,e){return p8(t,{dir:"right",size:e})}function Ti(t){return t.length}function x8(t,e,r,n={}){const{strict:s}=n;return t.slice(e,r)}function k8(t,e={}){const{size:r}=e;typeof r<"u"&&Uo(t,r);const n=Fr(t,e);return u1(n,e)}function T8(t,e={}){const{size:r}=e;let n=t;if(typeof r<"u"&&(Uo(n,r),n=o1(n)),n.length>1||n[0]>1)throw new P8(n);return!!n[0]}function Bn(t,e={}){const{size:r}=e;typeof r<"u"&&Uo(t,r);const n=Fr(t,e);return l1(n,e)}function _8(t,e={}){const{size:r}=e;let n=t;return typeof r<"u"&&(Uo(n,r),n=I8(n)),g8.decode(n)}function o1(t){return n1(t,{dir:"left"})}function I8(t){return n1(t,{dir:"right"})}class P8 extends le{constructor(e){super(`Bytes value \`${e}\` is not a valid boolean.`,{metaMessages:["The bytes array must contain a single byte of either a `0` or `1` value."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesBooleanError"})}}let O8=class extends le{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}},B8=class extends le{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}};const C8=new TextEncoder,R8=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function N8(t,e={}){const{strict:r=!1}=e;if(!t)throw new Hp(t);if(typeof t!="string")throw new Hp(t);if(r&&!/^0x[0-9a-fA-F]*$/.test(t))throw new Lp(t);if(!t.startsWith("0x"))throw new Lp(t)}function Ur(...t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function U8(t){return t instanceof Uint8Array?Fr(t):Array.isArray(t)?Fr(new Uint8Array(t)):t}function c1(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(wu(r,e.size),Qs(r,e.size)):r}function Fr(t,e={}){let r="";for(let s=0;s<t.length;s++)r+=R8[t[s]];const n=`0x${r}`;return typeof e.size=="number"?(wu(n,e.size),ei(n,e.size)):n}function Ut(t,e={}){const{signed:r,size:n}=e,s=BigInt(t);let i;n?r?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const a=typeof i=="bigint"&&r?-i-1n:0;if(i&&s>i||s<a){const u=typeof t=="bigint"?"n":"";throw new f1({max:i?`${i}${u}`:void 0,min:`${a}${u}`,signed:r,size:n,value:`${t}${u}`})}const c=`0x${(r&&s<0?BigInt.asUintN(n*8,BigInt(s)):s).toString(16)}`;return n?Qs(c,n):c}function Gh(t,e={}){return Fr(C8.encode(t),e)}function Qs(t,e){return s1(t,{dir:"left",size:e})}function ei(t,e){return s1(t,{dir:"right",size:e})}function rn(t,e,r,n={}){const{strict:s}=n;y8(t,e);const i=`0x${t.replace("0x","").slice((e??0)*2,(r??t.length)*2)}`;return s&&m8(i,e,r),i}function ir(t){return Math.ceil((t.length-2)/2)}function u1(t,e={}){const{signed:r}=e;e.size&&wu(t,e.size);const n=BigInt(t);if(!r)return n;const s=(t.length-2)/2,i=(1n<<BigInt(s)*8n)-1n,a=i>>1n;return n<=a?n:n-i-1n}function l1(t,e={}){const{signed:r,size:n}=e;return Number(!r&&!n?t:u1(t,e))}function F8(t,e={}){const{strict:r=!1}=e;try{return N8(t,{strict:r}),!0}catch{return!1}}class f1 extends le{constructor({max:e,min:r,signed:n,size:s,value:i}){super(`Number \`${i}\` is not in safe${s?` ${s*8}-bit`:""}${n?" signed":" unsigned"} integer range ${e?`(\`${r}\` to \`${e}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class Hp extends le{constructor(e){super(`Value \`${typeof e=="object"?i1(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class Lp extends le{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}class M8 extends le{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class d1 extends le{constructor({offset:e,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}class $8 extends le{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}function j8(t){return{address:t.address,amount:Ut(t.amount),index:Ut(t.index),validatorIndex:Ut(t.validatorIndex)}}function h1(t){return{...typeof t.baseFeePerGas=="bigint"&&{baseFeePerGas:Ut(t.baseFeePerGas)},...typeof t.blobBaseFee=="bigint"&&{blobBaseFee:Ut(t.blobBaseFee)},...typeof t.feeRecipient=="string"&&{feeRecipient:t.feeRecipient},...typeof t.gasLimit=="bigint"&&{gasLimit:Ut(t.gasLimit)},...typeof t.number=="bigint"&&{number:Ut(t.number)},...typeof t.prevRandao=="bigint"&&{prevRandao:Ut(t.prevRandao)},...typeof t.time=="bigint"&&{time:Ut(t.time)},...t.withdrawals&&{withdrawals:t.withdrawals.map(j8)}}}const Fc=[{inputs:[{components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}],name:"calls",type:"tuple[]"}],name:"aggregate3",outputs:[{components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}],name:"returnData",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"}],gd=[{name:"query",type:"function",stateMutability:"view",inputs:[{type:"tuple[]",name:"queries",components:[{type:"address",name:"sender"},{type:"string[]",name:"urls"},{type:"bytes",name:"data"}]}],outputs:[{type:"bool[]",name:"failures"},{type:"bytes[]",name:"responses"}]},{name:"HttpError",type:"error",inputs:[{type:"uint16",name:"status"},{type:"string",name:"message"}]}],p1=[{inputs:[{name:"dns",type:"bytes"}],name:"DNSDecodingFailed",type:"error"},{inputs:[{name:"ens",type:"string"}],name:"DNSEncodingFailed",type:"error"},{inputs:[],name:"EmptyAddress",type:"error"},{inputs:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"HttpError",type:"error"},{inputs:[],name:"InvalidBatchGatewayResponse",type:"error"},{inputs:[{name:"errorData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{name:"name",type:"bytes"},{name:"resolver",type:"address"}],name:"ResolverNotContract",type:"error"},{inputs:[{name:"name",type:"bytes"}],name:"ResolverNotFound",type:"error"},{inputs:[{name:"primary",type:"string"},{name:"primaryAddress",type:"bytes"}],name:"ReverseAddressMismatch",type:"error"},{inputs:[{internalType:"bytes4",name:"selector",type:"bytes4"}],name:"UnsupportedResolverProfile",type:"error"}],y1=[...p1,{name:"resolveWithGateways",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"},{name:"gateways",type:"string[]"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]}],H8=[...p1,{name:"reverseWithGateways",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"uint256",name:"coinType"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolver"},{type:"address",name:"reverseResolver"}]}],Dp=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],zp=[{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"}],outputs:[{name:"",type:"address"}]},{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"coinType",type:"uint256"}],outputs:[{name:"",type:"bytes"}]}],m1=[{name:"isValidSignature",type:"function",stateMutability:"view",inputs:[{name:"hash",type:"bytes32"},{name:"signature",type:"bytes"}],outputs:[{name:"",type:"bytes4"}]}],Vp=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}],L8="0x82ad56cb",b1="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",D8="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",z8="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",qh="0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033";class wd extends G{constructor({blockNumber:e,chain:r,contract:n}){super(`Chain "${r.name}" does not support contract "${n.name}".`,{metaMessages:["This could be due to any of the following:",...e&&n.blockCreated&&n.blockCreated>e?[`- The contract "${n.name}" was not deployed until block ${n.blockCreated} (current block ${e}).`]:[`- The chain does not have the contract "${n.name}" configured.`]],name:"ChainDoesNotSupportContract"})}}class V8 extends G{constructor({chain:e,currentChainId:r}){super(`The current chain of the wallet (id: ${r}) does not match the target chain for the transaction (id: ${e.id} – ${e.name}).`,{metaMessages:[`Current Chain ID: ${r}`,`Expected Chain ID: ${e.id} – ${e.name}`],name:"ChainMismatchError"})}}class G8 extends G{constructor(){super(["No chain was provided to the request.","Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient."].join(`
67
+ `),{name:"ChainNotFoundError"})}}class g1 extends G{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}class vu extends G{constructor({chainId:e}){super(typeof e=="number"?`Chain ID "${e}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}const ul="/docs/contract/encodeDeployData";function Eu(t){const{abi:e,args:r,bytecode:n}=t;if(!r||r.length===0)return n;const s=e.find(a=>"type"in a&&a.type==="constructor");if(!s)throw new GE({docsPath:ul});if(!("inputs"in s))throw new yp({docsPath:ul});if(!s.inputs||s.inputs.length===0)throw new yp({docsPath:ul});const i=Es(s.inputs,r);return jr([n,i])}function ra({blockNumber:t,chain:e,contract:r}){var s;const n=(s=e==null?void 0:e.contracts)==null?void 0:s[r];if(!n)throw new wd({chain:e,contract:{name:r}});if(t&&n.blockCreated&&n.blockCreated>t)throw new wd({blockNumber:t,chain:e,contract:{name:r,blockCreated:n.blockCreated}});return n.address}function w1(t,{docsPath:e,...r}){const n=(()=>{const s=pu(t,r);return s instanceof Oo?t:s})();return new Ng(n,{docsPath:e,...r})}function Wh(){let t=()=>{},e=()=>{};return{promise:new Promise((n,s)=>{t=n,e=s}),resolve:t,reject:e}}const ll=new Map;function v1({fn:t,id:e,shouldSplitBatch:r,wait:n=0,sort:s}){const i=async()=>{const l=c();a();const f=l.map(({args:p})=>p);f.length!==0&&t(f).then(p=>{s&&Array.isArray(p)&&p.sort(s);for(let d=0;d<l.length;d++){const{resolve:b}=l[d];b==null||b([p[d],p])}}).catch(p=>{for(let d=0;d<l.length;d++){const{reject:b}=l[d];b==null||b(p)}})},a=()=>ll.delete(e),o=()=>c().map(({args:l})=>l),c=()=>ll.get(e)||[],u=l=>ll.set(e,[...c(),l]);return{flush:a,async schedule(l){const{promise:f,resolve:p,reject:d}=Wh();return(r==null?void 0:r([...o(),l]))&&i(),c().length>0?(u({args:l,resolve:p,reject:d}),f):(u({args:l,resolve:p,reject:d}),setTimeout(i,n),f)}}}async function Fo(t,e){var V,Q,U,K;const{account:r=t.account,authorizationList:n,batch:s=!!((V=t.batch)!=null&&V.multicall),blockNumber:i,blockTag:a=t.experimental_blockTag??"latest",accessList:o,blobs:c,blockOverrides:u,code:l,data:f,factory:p,factoryData:d,gas:b,gasPrice:g,maxFeePerBlobGas:A,maxFeePerGas:S,maxPriorityFeePerGas:T,nonce:v,to:w,value:x,stateOverride:_,...I}=e,N=r?Le(r):void 0;if(l&&(p||d))throw new G("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(l&&w)throw new G("Cannot provide both `code` & `to` as parameters.");const C=l&&f,j=p&&d&&w&&f,M=C||j,H=C?E1({code:l,data:f}):j?K8({data:f,factory:p,factoryData:d,to:w}):f;try{jn(e);const q=(typeof i=="bigint"?Y(i):void 0)||a,O=u?h1(u):void 0,L=Ih(_),J=(K=(U=(Q=t.chain)==null?void 0:Q.formatters)==null?void 0:U.transactionRequest)==null?void 0:K.format,F=(J||As)({...ea(I,{format:J}),accessList:o,account:N,authorizationList:n,blobs:c,data:H,gas:b,gasPrice:g,maxFeePerBlobGas:A,maxFeePerGas:S,maxPriorityFeePerGas:T,nonce:v,to:M?void 0:w,value:x},"call");if(s&&q8({request:F})&&!L&&!O)try{return await W8(t,{...F,blockNumber:i,blockTag:a})}catch(ae){if(!(ae instanceof g1)&&!(ae instanceof wd))throw ae}const z=(()=>{const ae=[F,q];return L&&O?[...ae,L,O]:L?[...ae,L]:O?[...ae,{},O]:ae})(),ne=await t.request({method:"eth_call",params:z});return ne==="0x"?{data:void 0}:{data:ne}}catch(ee){const q=X8(ee),{offchainLookup:O,offchainLookupSignature:L}=await Promise.resolve().then(()=>require("./ccip-kK3_rmwt.cjs"));if(t.ccipRead!==!1&&(q==null?void 0:q.slice(0,10))===L&&w)return{data:await O(t,{data:q,to:w})};throw M&&(q==null?void 0:q.slice(0,10))==="0x101bb98d"?new IS({factory:p}):w1(ee,{...e,account:N,chain:t.chain})}}function q8({request:t}){const{data:e,to:r,...n}=t;return!(!e||e.startsWith(L8)||!r||Object.values(n).filter(s=>typeof s<"u").length>0)}async function W8(t,e){var g;const{batchSize:r=1024,deployless:n=!1,wait:s=0}=typeof((g=t.batch)==null?void 0:g.multicall)=="object"?t.batch.multicall:{},{blockNumber:i,blockTag:a=t.experimental_blockTag??"latest",data:o,to:c}=e,u=(()=>{if(n)return null;if(e.multicallAddress)return e.multicallAddress;if(t.chain)return ra({blockNumber:i,chain:t.chain,contract:"multicall3"});throw new g1})(),f=(typeof i=="bigint"?Y(i):void 0)||a,{schedule:p}=v1({id:`${t.uid}.${f}`,wait:s,shouldSplitBatch(A){return A.reduce((T,{data:v})=>T+(v.length-2),0)>r*2},fn:async A=>{const S=A.map(w=>({allowFailure:!0,callData:w.data,target:w.to})),T=or({abi:Fc,args:[S],functionName:"aggregate3"}),v=await t.request({method:"eth_call",params:[{...u===null?{data:E1({code:qh,data:T})}:{to:u,data:T}},f]});return ui({abi:Fc,args:[S],functionName:"aggregate3",data:v||"0x"})}}),[{returnData:d,success:b}]=await p({data:o,to:c});if(!b)throw new du({data:d});return d==="0x"?{data:void 0}:{data:d}}function E1(t){const{code:e,data:r}=t;return Eu({abi:Yb(["constructor(bytes, bytes)"]),bytecode:b1,args:[e,r]})}function K8(t){const{data:e,factory:r,factoryData:n,to:s}=t;return Eu({abi:Yb(["constructor(address, bytes, address, bytes)"]),bytecode:D8,args:[s,e,r,n]})}function X8(t){var r;if(!(t instanceof G))return;const e=t.walk();return typeof(e==null?void 0:e.data)=="object"?(r=e.data)==null?void 0:r.data:e.data}async function wr(t,e){const{abi:r,address:n,args:s,functionName:i,...a}=e,o=or({abi:r,args:s,functionName:i});try{const{data:c}=await re(t,Fo,"call")({...a,data:o,to:n});return ui({abi:r,args:s,functionName:i,data:c||"0x"})}catch(c){throw Js(c,{abi:r,address:n,args:s,docsPath:"/docs/contract/readContract",functionName:i})}}async function A1(t,e){const{abi:r,address:n,args:s,dataSuffix:i,functionName:a,...o}=e,c=o.account?Le(o.account):t.account,u=or({abi:r,args:s,functionName:a});try{const{data:l}=await re(t,Fo,"call")({batch:!1,data:`${u}${i?i.replace("0x",""):""}`,to:n,...o,account:c}),f=ui({abi:r,args:s,functionName:a,data:l||"0x"}),p=r.filter(d=>"name"in d&&d.name===e.functionName);return{result:f,request:{abi:p,address:n,args:s,dataSuffix:i,functionName:a,...o,account:c}}}catch(l){throw Js(l,{abi:r,address:n,args:s,docsPath:"/docs/contract/simulateContract",functionName:a,sender:c==null?void 0:c.address})}}const fl=new Map,Gp=new Map;let Y8=0;function Fn(t,e,r){const n=++Y8,s=()=>fl.get(t)||[],i=()=>{const l=s();fl.set(t,l.filter(f=>f.id!==n))},a=()=>{const l=s();if(!l.some(p=>p.id===n))return;const f=Gp.get(t);if(l.length===1&&f){const p=f();p instanceof Promise&&p.catch(()=>{})}i()},o=s();if(fl.set(t,[...o,{id:n,fns:e}]),o&&o.length>0)return a;const c={};for(const l in e)c[l]=(...f)=>{var d,b;const p=s();if(p.length!==0)for(const g of p)(b=(d=g.fns)[l])==null||b.call(d,...f)};const u=r(c);return typeof u=="function"&&Gp.set(t,u),a}async function vd(t){return new Promise(e=>setTimeout(e,t))}function na(t,{emitOnBegin:e,initialWaitTime:r,interval:n}){let s=!0;const i=()=>s=!1;return(async()=>{let o;e&&(o=await t({unpoll:i}));const c=await(r==null?void 0:r(o))??n;await vd(c);const u=async()=>{s&&(await t({unpoll:i}),await vd(n),u())};u()})(),i}const J8=new Map,Z8=new Map;function Q8(t){const e=(s,i)=>({clear:()=>i.delete(s),get:()=>i.get(s),set:a=>i.set(s,a)}),r=e(t,J8),n=e(t,Z8);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function ex(t,{cacheKey:e,cacheTime:r=Number.POSITIVE_INFINITY}){const n=Q8(e),s=n.response.get();if(s&&r>0&&Date.now()-s.created.getTime()<r)return s.data;let i=n.promise.get();i||(i=t(),n.promise.set(i));try{const a=await i;return n.response.set({created:new Date,data:a}),a}finally{n.promise.clear()}}const tx=t=>`blockNumber.${t}`;async function Mo(t,{cacheTime:e=t.cacheTime}={}){const r=await ex(()=>t.request({method:"eth_blockNumber"}),{cacheKey:tx(t.uid),cacheTime:e});return BigInt(r)}async function Au(t,{filter:e}){const r="strict"in e&&e.strict,n=await e.request({method:"eth_getFilterChanges",params:[e.id]});if(typeof n[0]=="string")return n;const s=n.map(i=>Un(i));return!("abi"in e)||!e.abi?s:jh({abi:e.abi,logs:s,strict:r})}async function Su(t,{filter:e}){return e.request({method:"eth_uninstallFilter",params:[e.id]})}function S1(t,e){const{abi:r,address:n,args:s,batch:i=!0,eventName:a,fromBlock:o,onError:c,onLogs:u,poll:l,pollingInterval:f=t.pollingInterval,strict:p}=e;return(typeof l<"u"?l:typeof o=="bigint"?!0:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc")))?(()=>{const A=p??!1,S=et(["watchContractEvent",n,s,i,t.uid,a,f,A,o]);return Fn(S,{onLogs:u,onError:c},T=>{let v;o!==void 0&&(v=o-1n);let w,x=!1;const _=na(async()=>{var I;if(!x){try{w=await re(t,Sh,"createContractEventFilter")({abi:r,address:n,args:s,eventName:a,strict:A,fromBlock:o})}catch{}x=!0;return}try{let N;if(w)N=await re(t,Au,"getFilterChanges")({filter:w});else{const C=await re(t,Mo,"getBlockNumber")({});v&&v<C?N=await re(t,Lh,"getContractEvents")({abi:r,address:n,args:s,eventName:a,fromBlock:v+1n,toBlock:C,strict:A}):N=[],v=C}if(N.length===0)return;if(i)T.onLogs(N);else for(const C of N)T.onLogs([C])}catch(N){w&&N instanceof bs&&(x=!1),(I=T.onError)==null||I.call(T,N)}},{emitOnBegin:!0,interval:f});return async()=>{w&&await re(t,Su,"uninstallFilter")({filter:w}),_()}})})():(()=>{const A=p??!1,S=et(["watchContractEvent",n,s,i,t.uid,a,f,A]);let T=!0,v=()=>T=!1;return Fn(S,{onLogs:u,onError:c},w=>((async()=>{try{const x=(()=>{if(t.transport.type==="fallback"){const N=t.transport.transports.find(C=>C.config.type==="webSocket"||C.config.type==="ipc");return N?N.value:t.transport}return t.transport})(),_=a?_o({abi:r,eventName:a,args:s}):[],{unsubscribe:I}=await x.subscribe({params:["logs",{address:n,topics:_}],onData(N){var j;if(!T)return;const C=N.result;try{const{eventName:M,args:H}=Rc({abi:r,data:C.data,topics:C.topics,strict:p}),V=Un(C,{args:H,eventName:M});w.onLogs([V])}catch(M){let H,V;if(M instanceof Cc||M instanceof yh){if(p)return;H=M.abiItem.name,V=(j=M.abiItem.inputs)==null?void 0:j.some(U=>!("name"in U&&U.name))}const Q=Un(C,{args:V?[]:{},eventName:H});w.onLogs([Q])}},onError(N){var C;(C=w.onError)==null||C.call(w,N)}});v=I,T||v()}catch(x){c==null||c(x)}})(),()=>v()))})()}class xs extends G{constructor({docsPath:e}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(`
68
+ `),{docsPath:e,docsSlug:"account",name:"AccountNotFoundError"})}}class Vs extends G{constructor({docsPath:e,metaMessages:r,type:n}){super(`Account type "${n}" is not supported.`,{docsPath:e,metaMessages:r,name:"AccountTypeNotSupportedError"})}}function Kh({chain:t,currentChainId:e}){if(!t)throw new G8;if(e!==t.id)throw new V8({chain:t,currentChainId:e})}async function Xh(t,{serializedTransaction:e}){return t.request({method:"eth_sendRawTransaction",params:[e]},{retryCount:0})}const dl=new Qi(128);async function xu(t,e){var v,w,x,_;const{account:r=t.account,assertChainId:n=!0,chain:s=t.chain,accessList:i,authorizationList:a,blobs:o,data:c,gas:u,gasPrice:l,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:d,nonce:b,type:g,value:A,...S}=e;if(typeof r>"u")throw new xs({docsPath:"/docs/actions/wallet/sendTransaction"});const T=r?Le(r):null;try{jn(e);const I=await(async()=>{if(e.to)return e.to;if(e.to!==null&&a&&a.length>0)return await hu({authorization:a[0]}).catch(()=>{throw new G("`to` is required. Could not infer from `authorizationList`.")})})();if((T==null?void 0:T.type)==="json-rpc"||T===null){let N;s!==null&&(N=await re(t,Ss,"getChainId")({}),n&&Kh({currentChainId:N,chain:s}));const C=(x=(w=(v=t.chain)==null?void 0:v.formatters)==null?void 0:w.transactionRequest)==null?void 0:x.format,M=(C||As)({...ea(S,{format:C}),accessList:i,account:T,authorizationList:a,blobs:o,chainId:N,data:c,gas:u,gasPrice:l,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:d,nonce:b,to:I,type:g,value:A},"sendTransaction"),H=dl.get(t.uid),V=H?"wallet_sendTransaction":"eth_sendTransaction";try{return await t.request({method:V,params:[M]},{retryCount:0})}catch(Q){if(H===!1)throw Q;const U=Q;if(U.name==="InvalidInputRpcError"||U.name==="InvalidParamsRpcError"||U.name==="MethodNotFoundRpcError"||U.name==="MethodNotSupportedRpcError")return await t.request({method:"wallet_sendTransaction",params:[M]},{retryCount:0}).then(K=>(dl.set(t.uid,!0),K)).catch(K=>{const ee=K;throw ee.name==="MethodNotFoundRpcError"||ee.name==="MethodNotSupportedRpcError"?(dl.set(t.uid,!1),U):ee});throw U}}if((T==null?void 0:T.type)==="local"){const N=await re(t,Co,"prepareTransactionRequest")({account:T,accessList:i,authorizationList:a,blobs:o,chain:s,data:c,gas:u,gasPrice:l,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:d,nonce:b,nonceManager:T.nonceManager,parameters:[...Mh,"sidecars"],type:g,value:A,...S,to:I}),C=(_=s==null?void 0:s.serializers)==null?void 0:_.transaction,j=await T.signTransaction(N,{serializer:C});return await re(t,Xh,"sendRawTransaction")({serializedTransaction:j})}throw(T==null?void 0:T.type)==="smart"?new Vs({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new Vs({docsPath:"/docs/actions/wallet/sendTransaction",type:T==null?void 0:T.type})}catch(I){throw I instanceof Vs?I:mu(I,{...e,account:T,chain:e.chain||void 0})}}async function Ki(t,e){return Ki.internal(t,xu,"sendTransaction",e)}(function(t){async function e(r,n,s,i){const{abi:a,account:o=r.account,address:c,args:u,dataSuffix:l,functionName:f,...p}=i;if(typeof o>"u")throw new xs({docsPath:"/docs/contract/writeContract"});const d=o?Le(o):null,b=or({abi:a,args:u,functionName:f});try{return await re(r,n,s)({data:`${b}${l?l.replace("0x",""):""}`,to:c,account:d,...p})}catch(g){throw Js(g,{abi:a,address:c,args:u,docsPath:"/docs/contract/writeContract",functionName:f,sender:d==null?void 0:d.address})}}t.internal=e})(Ki||(Ki={}));function Yh({abi:t,address:e,client:r}){const n=r,[s,i]=n?"public"in n&&"wallet"in n?[n.public,n.wallet]:"public"in n?[n.public,void 0]:"wallet"in n?[void 0,n.wallet]:[n,n]:[void 0,void 0],a=s!=null,o=i!=null,c={};let u=!1,l=!1,f=!1;for(const p of t)if(p.type==="function"?p.stateMutability==="view"||p.stateMutability==="pure"?u=!0:l=!0:p.type==="event"&&(f=!0),u&&l&&f)break;return a&&(u&&(c.read=new Proxy({},{get(p,d){return(...b)=>{const{args:g,options:A}=sc(b);return re(s,wr,"readContract")({abi:t,address:e,functionName:d,args:g,...A})}}})),l&&(c.simulate=new Proxy({},{get(p,d){return(...b)=>{const{args:g,options:A}=sc(b);return re(s,A1,"simulateContract")({abi:t,address:e,functionName:d,args:g,...A})}}})),f&&(c.createEventFilter=new Proxy({},{get(p,d){return(...b)=>{const g=t.find(T=>T.type==="event"&&T.name===d),{args:A,options:S}=hl(b,g);return re(s,Sh,"createContractEventFilter")({abi:t,address:e,eventName:d,args:A,...S})}}}),c.getEvents=new Proxy({},{get(p,d){return(...b)=>{const g=t.find(T=>T.type==="event"&&T.name===d),{args:A,options:S}=hl(b,g);return re(s,Lh,"getContractEvents")({abi:t,address:e,eventName:d,args:A,...S})}}}),c.watchEvent=new Proxy({},{get(p,d){return(...b)=>{const g=t.find(T=>T.type==="event"&&T.name===d),{args:A,options:S}=hl(b,g);return re(s,S1,"watchContractEvent")({abi:t,address:e,eventName:d,args:A,...S})}}}))),o&&l&&(c.write=new Proxy({},{get(p,d){return(...b)=>{const{args:g,options:A}=sc(b);return re(i,Ki,"writeContract")({abi:t,address:e,functionName:d,args:g,...A})}}})),(a||o)&&l&&(c.estimateGas=new Proxy({},{get(p,d){return(...b)=>{const{args:g,options:A}=sc(b);return re(s??i,Jg,"estimateContractGas")({abi:t,address:e,functionName:d,args:g,...A,account:A.account??i.account})}}})),c.address=e,c.abi=t,c}function sc(t){const e=t.length&&Array.isArray(t[0]),r=e?t[0]:[],n=(e?t[1]:t[0])??{};return{args:r,options:n}}function hl(t,e){let r=!1;Array.isArray(t[0])?r=!0:t.length===1?r=e.inputs.some(i=>i.indexed):t.length===2&&(r=!0);const n=r?t[0]:void 0,s=(r?t[1]:t[0])??{};return{args:n,options:s}}class rx extends G{constructor(e){super(`Call bundle failed with status: ${e.statusCode}`,{name:"BundleFailedError"}),Object.defineProperty(this,"result",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.result=e}}function Mc(t,{delay:e=100,retryCount:r=2,shouldRetry:n=()=>!0}={}){return new Promise((s,i)=>{const a=async({count:o=0}={})=>{const c=async({error:u})=>{const l=typeof e=="function"?e({count:o,error:u}):e;l&&await vd(l),a({count:o+1})};try{const u=await t();s(u)}catch(u){if(o<r&&await n({count:o,error:u}))return c({error:u});i(u)}};a()})}const x1={"0x0":"reverted","0x1":"success"};function Jh(t,e){const r={...t,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,contractAddress:t.contractAddress?t.contractAddress:null,cumulativeGasUsed:t.cumulativeGasUsed?BigInt(t.cumulativeGasUsed):null,effectiveGasPrice:t.effectiveGasPrice?BigInt(t.effectiveGasPrice):null,gasUsed:t.gasUsed?BigInt(t.gasUsed):null,logs:t.logs?t.logs.map(n=>Un(n)):null,to:t.to?t.to:null,transactionIndex:t.transactionIndex?gr(t.transactionIndex):null,status:t.status?x1[t.status]:null,type:t.type?Lg[t.type]||t.type:null};return t.blobGasPrice&&(r.blobGasPrice=BigInt(t.blobGasPrice)),t.blobGasUsed&&(r.blobGasUsed=BigInt(t.blobGasUsed)),r}const nx=_h("transactionReceipt",Jh),k1="0x5792579257925792579257925792579257925792579257925792579257925792",T1=Y(0,{size:32});async function _1(t,e){const{account:r=t.account,capabilities:n,chain:s=t.chain,experimental_fallback:i,experimental_fallbackDelay:a=32,forceAtomic:o=!1,id:c,version:u="2.0.0"}=e,l=r?Le(r):null,f=e.calls.map(p=>{const d=p,b=d.abi?or({abi:d.abi,functionName:d.functionName,args:d.args}):d.data;return{data:d.dataSuffix&&b?sr([b,d.dataSuffix]):b,to:d.to,value:d.value?Y(d.value):void 0}});try{const p=await t.request({method:"wallet_sendCalls",params:[{atomicRequired:o,calls:f,capabilities:n,chainId:Y(s.id),from:l==null?void 0:l.address,id:c,version:u}]},{retryCount:0});return typeof p=="string"?{id:p}:p}catch(p){const d=p;if(i&&(d.name==="MethodNotFoundRpcError"||d.name==="MethodNotSupportedRpcError"||d.name==="UnknownRpcError"||d.details.toLowerCase().includes("does not exist / is not available")||d.details.toLowerCase().includes("missing or invalid. request()")||d.details.toLowerCase().includes("did not match any variant of untagged enum")||d.details.toLowerCase().includes("account upgraded to unsupported contract")||d.details.toLowerCase().includes("eip-7702 not supported")||d.details.toLowerCase().includes("unsupported wc_ method")||d.details.toLowerCase().includes("feature toggled misconfigured")||d.details.toLowerCase().includes("jsonrpcengine: response has no error or result for request"))){if(n&&Object.values(n).some(T=>!T.optional)){const T="non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";throw new qi(new G(T,{details:T}))}if(o&&f.length>1){const S="`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";throw new Wi(new G(S,{details:S}))}const b=[];for(const S of f){const T=xu(t,{account:l,chain:s,data:S.data,to:S.to,value:S.value?ft(S.value):void 0});b.push(T),a>0&&await new Promise(v=>setTimeout(v,a))}const g=await Promise.allSettled(b);if(g.every(S=>S.status==="rejected"))throw g[0].reason;const A=g.map(S=>S.status==="fulfilled"?S.value:T1);return{id:sr([...A,Y(s.id,{size:32}),k1])}}throw mu(p,{...e,account:l,chain:e.chain})}}async function I1(t,e){async function r(l){if(l.endsWith(k1.slice(2))){const p=br(sd(l,-64,-32)),d=sd(l,0,-64).slice(2).match(/.{1,64}/g),b=await Promise.all(d.map(A=>T1.slice(2)!==A?t.request({method:"eth_getTransactionReceipt",params:[`0x${A}`]},{dedupe:!0}):void 0)),g=b.some(A=>A===null)?100:b.every(A=>(A==null?void 0:A.status)==="0x1")?200:b.every(A=>(A==null?void 0:A.status)==="0x0")?500:600;return{atomic:!1,chainId:gr(p),receipts:b.filter(Boolean),status:g,version:"2.0.0"}}return t.request({method:"wallet_getCallsStatus",params:[l]})}const{atomic:n=!1,chainId:s,receipts:i,version:a="2.0.0",...o}=await r(e.id),[c,u]=(()=>{const l=o.status;return l>=100&&l<200?["pending",l]:l>=200&&l<300?["success",l]:l>=300&&l<700?["failure",l]:l==="CONFIRMED"?["success",200]:l==="PENDING"?["pending",100]:[void 0,l]})();return{...o,atomic:n,chainId:s?gr(s):void 0,receipts:(i==null?void 0:i.map(l=>({...l,blockNumber:ft(l.blockNumber),gasUsed:ft(l.gasUsed),status:x1[l.status]})))??[],statusCode:u,status:c,version:a}}async function P1(t,e){const{id:r,pollingInterval:n=t.pollingInterval,status:s=({statusCode:g})=>g===200||g>=300,retryCount:i=4,retryDelay:a=({count:g})=>~~(1<<g)*200,timeout:o=6e4,throwOnFailure:c=!1}=e,u=et(["waitForCallsStatus",t.uid,r]),{promise:l,resolve:f,reject:p}=Wh();let d;const b=Fn(u,{resolve:f,reject:p},g=>{const A=na(async()=>{const S=T=>{clearTimeout(d),A(),T(),b()};try{const T=await Mc(async()=>{const v=await re(t,I1,"getCallsStatus")({id:r});if(c&&v.status==="failure")throw new rx(v);return v},{retryCount:i,delay:a});if(!s(T))return;S(()=>g.resolve(T))}catch(T){S(()=>g.reject(T))}},{interval:n,emitOnBegin:!0});return A});return d=o?setTimeout(()=>{b(),clearTimeout(d),p(new sx({id:r}))},o):void 0,await l}class sx extends G{constructor({id:e}){super(`Timed out while waiting for call bundle with id "${e}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}const Ed=256;let ic=Ed,ac;function O1(t=11){if(!ac||ic+t>Ed*2){ac="",ic=0;for(let e=0;e<Ed;e++)ac+=(256+Math.random()*256|0).toString(16).substring(1)}return ac.substring(ic,ic+++t)}function B1(t){const{batch:e,chain:r,ccipRead:n,key:s="base",name:i="Base Client",type:a="base"}=t,o=t.experimental_blockTag??(typeof(r==null?void 0:r.experimental_preconfirmationTime)=="number"?"pending":void 0),c=(r==null?void 0:r.blockTime)??12e3,u=Math.min(Math.max(Math.floor(c/2),500),4e3),l=t.pollingInterval??u,f=t.cacheTime??l,p=t.account?Le(t.account):void 0,{config:d,request:b,value:g}=t.transport({account:p,chain:r,pollingInterval:l}),A={...d,...g},S={account:p,batch:e,cacheTime:f,ccipRead:n,chain:r,key:s,name:i,pollingInterval:l,request:b,transport:A,type:a,uid:O1(),...o?{experimental_blockTag:o}:{}};function T(v){return w=>{const x=w(v);for(const I in S)delete x[I];const _={...v,...x};return Object.assign(_,{extend:T(_)})}}return Object.assign(S,{extend:T(S)})}function Zh(t){var r,n,s,i,a,o;if(!(t instanceof G))return!1;const e=t.walk(c=>c instanceof od);return e instanceof od?((r=e.data)==null?void 0:r.errorName)==="HttpError"||((n=e.data)==null?void 0:n.errorName)==="ResolverError"||((s=e.data)==null?void 0:s.errorName)==="ResolverNotContract"||((i=e.data)==null?void 0:i.errorName)==="ResolverNotFound"||((a=e.data)==null?void 0:a.errorName)==="ReverseAddressMismatch"||((o=e.data)==null?void 0:o.errorName)==="UnsupportedResolverProfile":!1}function ix(t){const{abi:e,data:r}=t,n=Xs(r,0,4),s=e.find(i=>i.type==="function"&&n===To(Rr(i)));if(!s)throw new ZE(n,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:s.name,args:"inputs"in s&&s.inputs&&s.inputs.length>0?Io(s.inputs,Xs(r,4)):void 0}}const pl="/docs/contract/encodeErrorResult";function qp(t){const{abi:e,errorName:r,args:n}=t;let s=e[0];if(r){const c=ci({abi:e,args:n,name:r});if(!c)throw new mp(r,{docsPath:pl});s=c}if(s.type!=="error")throw new mp(void 0,{docsPath:pl});const i=Rr(s),a=To(i);let o="0x";if(n&&n.length>0){if(!s.inputs)throw new XE(s.name,{docsPath:pl});o=Es(s.inputs,n)}return jr([a,o])}const yl="/docs/contract/encodeFunctionResult";function ax(t){const{abi:e,functionName:r,result:n}=t;let s=e[0];if(r){const a=ci({abi:e,name:r});if(!a)throw new zi(r,{docsPath:yl});s=a}if(s.type!=="function")throw new zi(void 0,{docsPath:yl});if(!s.outputs)throw new tg(s.name,{docsPath:yl});const i=(()=>{if(s.outputs.length===0)return[];if(s.outputs.length===1)return[n];if(Array.isArray(n))return n;throw new rg(n)})();return Es(s.outputs,i)}const $o="x-batch-gateway:true";async function C1(t){const{data:e,ccipRequest:r}=t,{args:[n]}=ix({abi:gd,data:e}),s=[],i=[];return await Promise.all(n.map(async(a,o)=>{try{i[o]=a.urls.includes($o)?await C1({data:a.data,ccipRequest:r}):await r(a),s[o]=!1}catch(c){s[o]=!0,i[o]=ox(c)}})),ax({abi:gd,functionName:"query",result:[s,i]})}function ox(t){return t.name==="HttpRequestError"&&t.status?qp({abi:gd,errorName:"HttpError",args:[t.status,t.shortMessage]}):qp({abi:[Tg],errorName:"Error",args:["shortMessage"in t?t.shortMessage:t.message]})}function R1(t){if(t.length!==66||t.indexOf("[")!==0||t.indexOf("]")!==65)return null;const e=`0x${t.slice(1,65)}`;return Nr(e)?e:null}function Ad(t){let e=new Uint8Array(32).fill(0);if(!t)return tt(e);const r=t.split(".");for(let n=r.length-1;n>=0;n-=1){const s=R1(r[n]),i=s?Zi(s):bt(Ds(r[n]),"bytes");e=bt(sr([e,i]),"bytes")}return tt(e)}function cx(t){return`[${t.slice(2)}]`}function ux(t){const e=new Uint8Array(32).fill(0);return t?R1(t)||bt(Ds(t)):tt(e)}function Qh(t){const e=t.replace(/^\.|\.$/gm,"");if(e.length===0)return new Uint8Array(1);const r=new Uint8Array(Ds(e).byteLength+2);let n=0;const s=e.split(".");for(let i=0;i<s.length;i++){let a=Ds(s[i]);a.byteLength>255&&(a=Ds(cx(ux(s[i])))),r[n]=a.length,r.set(a,n+1),n+=a.length+1}return r.byteLength!==n+1?r.slice(0,n+1):r}async function lx(t,e){const{blockNumber:r,blockTag:n,coinType:s,name:i,gatewayUrls:a,strict:o}=e,{chain:c}=t,u=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return ra({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),l=c==null?void 0:c.ensTlds;if(l&&!l.some(p=>i.endsWith(p)))return null;const f=s!=null?[Ad(i),BigInt(s)]:[Ad(i)];try{const p=or({abi:zp,functionName:"addr",args:f}),d={address:u,abi:y1,functionName:"resolveWithGateways",args:[Ft(Qh(i)),p,a??[$o]],blockNumber:r,blockTag:n},g=await re(t,wr,"readContract")(d);if(g[0]==="0x")return null;const A=ui({abi:zp,args:f,functionName:"addr",data:g[0]});return A==="0x"||br(A)==="0x00"?null:A}catch(p){if(o)throw p;if(Zh(p))return null;throw p}}class fx extends G{constructor({data:e}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(e)}`],name:"EnsAvatarInvalidMetadataError"})}}class ha extends G{constructor({reason:e}){super(`ENS NFT avatar URI is invalid. ${e}`,{name:"EnsAvatarInvalidNftUriError"})}}class e0 extends G{constructor({uri:e}){super(`Unable to resolve ENS avatar URI "${e}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class dx extends G{constructor({namespace:e}){super(`ENS NFT avatar namespace "${e}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}const hx=/(?<protocol>https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,px=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?<target>[\w\-.]+))?(?<subtarget>\/.*)?$/,yx=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,mx=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function bx(t){try{const e=await fetch(t,{method:"HEAD"});if(e.status===200){const r=e.headers.get("content-type");return r==null?void 0:r.startsWith("image/")}return!1}catch(e){return typeof e=="object"&&typeof e.response<"u"||!Object.hasOwn(globalThis,"Image")?!1:new Promise(r=>{const n=new Image;n.onload=()=>{r(!0)},n.onerror=()=>{r(!1)},n.src=t})}}function Wp(t,e){return t?t.endsWith("/")?t.slice(0,-1):t:e}function N1({uri:t,gatewayUrls:e}){const r=yx.test(t);if(r)return{uri:t,isOnChain:!0,isEncoded:r};const n=Wp(e==null?void 0:e.ipfs,"https://ipfs.io"),s=Wp(e==null?void 0:e.arweave,"https://arweave.net"),i=t.match(hx),{protocol:a,subpath:o,target:c,subtarget:u=""}=(i==null?void 0:i.groups)||{},l=a==="ipns:/"||o==="ipns/",f=a==="ipfs:/"||o==="ipfs/"||px.test(t);if(t.startsWith("http")&&!l&&!f){let d=t;return e!=null&&e.arweave&&(d=t.replace(/https:\/\/arweave.net/g,e==null?void 0:e.arweave)),{uri:d,isOnChain:!1,isEncoded:!1}}if((l||f)&&c)return{uri:`${n}/${l?"ipns":"ipfs"}/${c}${u}`,isOnChain:!1,isEncoded:!1};if(a==="ar:/"&&c)return{uri:`${s}/${c}${u||""}`,isOnChain:!1,isEncoded:!1};let p=t.replace(mx,"");if(p.startsWith("<svg")&&(p=`data:image/svg+xml;base64,${btoa(p)}`),p.startsWith("data:")||p.startsWith("{"))return{uri:p,isOnChain:!0,isEncoded:!1};throw new e0({uri:t})}function U1(t){if(typeof t!="object"||!("image"in t)&&!("image_url"in t)&&!("image_data"in t))throw new fx({data:t});return t.image||t.image_url||t.image_data}async function gx({gatewayUrls:t,uri:e}){try{const r=await fetch(e).then(s=>s.json());return await t0({gatewayUrls:t,uri:U1(r)})}catch{throw new e0({uri:e})}}async function t0({gatewayUrls:t,uri:e}){const{uri:r,isOnChain:n}=N1({uri:e,gatewayUrls:t});if(n||await bx(r))return r;throw new e0({uri:e})}function wx(t){let e=t;e.startsWith("did:nft:")&&(e=e.replace("did:nft:","").replace(/_/g,"/"));const[r,n,s]=e.split("/"),[i,a]=r.split(":"),[o,c]=n.split(":");if(!i||i.toLowerCase()!=="eip155")throw new ha({reason:"Only EIP-155 supported"});if(!a)throw new ha({reason:"Chain ID not found"});if(!c)throw new ha({reason:"Contract address not found"});if(!s)throw new ha({reason:"Token ID not found"});if(!o)throw new ha({reason:"ERC namespace not found"});return{chainID:Number.parseInt(a,10),namespace:o.toLowerCase(),contractAddress:c,tokenID:s}}async function vx(t,{nft:e}){if(e.namespace==="erc721")return wr(t,{address:e.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(e.tokenID)]});if(e.namespace==="erc1155")return wr(t,{address:e.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(e.tokenID)]});throw new dx({namespace:e.namespace})}async function Ex(t,{gatewayUrls:e,record:r}){return/eip155:/i.test(r)?Ax(t,{gatewayUrls:e,record:r}):t0({uri:r,gatewayUrls:e})}async function Ax(t,{gatewayUrls:e,record:r}){const n=wx(r),s=await vx(t,{nft:n}),{uri:i,isOnChain:a,isEncoded:o}=N1({uri:s,gatewayUrls:e});if(a&&(i.includes("data:application/json;base64,")||i.startsWith("{"))){const u=o?atob(i.replace("data:application/json;base64,","")):i,l=JSON.parse(u);return t0({uri:U1(l),gatewayUrls:e})}let c=n.tokenID;return n.namespace==="erc1155"&&(c=c.replace("0x","").padStart(64,"0")),gx({gatewayUrls:e,uri:i.replace(/(?:0x)?{id}/,c)})}async function F1(t,e){const{blockNumber:r,blockTag:n,key:s,name:i,gatewayUrls:a,strict:o}=e,{chain:c}=t,u=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return ra({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),l=c==null?void 0:c.ensTlds;if(l&&!l.some(f=>i.endsWith(f)))return null;try{const f={address:u,abi:y1,args:[Ft(Qh(i)),or({abi:Dp,functionName:"text",args:[Ad(i),s]}),a??[$o]],functionName:"resolveWithGateways",blockNumber:r,blockTag:n},d=await re(t,wr,"readContract")(f);if(d[0]==="0x")return null;const b=ui({abi:Dp,functionName:"text",data:d[0]});return b===""?null:b}catch(f){if(o)throw f;if(Zh(f))return null;throw f}}async function Sx(t,{blockNumber:e,blockTag:r,assetGatewayUrls:n,name:s,gatewayUrls:i,strict:a,universalResolverAddress:o}){const c=await re(t,F1,"getEnsText")({blockNumber:e,blockTag:r,key:"avatar",name:s,universalResolverAddress:o,gatewayUrls:i,strict:a});if(!c)return null;try{return await Ex(t,{record:c,gatewayUrls:n})}catch{return null}}async function xx(t,e){const{address:r,blockNumber:n,blockTag:s,coinType:i=60n,gatewayUrls:a,strict:o}=e,{chain:c}=t,u=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return ra({blockNumber:n,chain:c,contract:"ensUniversalResolver"})})();try{const l={address:u,abi:H8,args:[r,i,a??[$o]],functionName:"reverseWithGateways",blockNumber:n,blockTag:s},f=re(t,wr,"readContract"),[p]=await f(l);return p||null}catch(l){if(o)throw l;if(Zh(l))return null;throw l}}async function kx(t,e){const{blockNumber:r,blockTag:n,name:s}=e,{chain:i}=t,a=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!i)throw new Error("client chain not configured. universalResolverAddress is required.");return ra({blockNumber:r,chain:i,contract:"ensUniversalResolver"})})(),o=i==null?void 0:i.ensTlds;if(o&&!o.some(u=>s.endsWith(u)))throw new Error(`${s} is not a valid ENS TLD (${o==null?void 0:o.join(", ")}) for chain "${i.name}" (id: ${i.id}).`);const[c]=await re(t,wr,"readContract")({address:a,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[Ft(Qh(s))],blockNumber:r,blockTag:n});return c}async function M1(t,e){var A,S,T;const{account:r=t.account,blockNumber:n,blockTag:s="latest",blobs:i,data:a,gas:o,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:l,maxPriorityFeePerGas:f,to:p,value:d,...b}=e,g=r?Le(r):void 0;try{jn(e);const w=(typeof n=="bigint"?Y(n):void 0)||s,x=(T=(S=(A=t.chain)==null?void 0:A.formatters)==null?void 0:S.transactionRequest)==null?void 0:T.format,I=(x||As)({...ea(b,{format:x}),account:g,blobs:i,data:a,gas:o,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:l,maxPriorityFeePerGas:f,to:p,value:d},"createAccessList"),N=await t.request({method:"eth_createAccessList",params:[I,w]});return{accessList:N.accessList,gasUsed:BigInt(N.gasUsed)}}catch(v){throw w1(v,{...e,account:g,chain:t.chain})}}async function Tx(t){const e=lu(t,{method:"eth_newBlockFilter"}),r=await t.request({method:"eth_newBlockFilter"});return{id:r,request:e(r),type:"block"}}async function $1(t,{address:e,args:r,event:n,events:s,fromBlock:i,strict:a,toBlock:o}={}){const c=s??(n?[n]:void 0),u=lu(t,{method:"eth_newFilter"});let l=[];c&&(l=[c.flatMap(d=>_o({abi:[d],eventName:d.name,args:r}))],n&&(l=l[0]));const f=await t.request({method:"eth_newFilter",params:[{address:e,fromBlock:typeof i=="bigint"?Y(i):i,toBlock:typeof o=="bigint"?Y(o):o,...l.length?{topics:l}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:i,id:f,request:u(f),strict:!!a,toBlock:o,type:"event"}}async function j1(t){const e=lu(t,{method:"eth_newPendingTransactionFilter"}),r=await t.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:e(r),type:"transaction"}}async function _x(t,{address:e,blockNumber:r,blockTag:n=t.experimental_blockTag??"latest"}){const s=typeof r=="bigint"?Y(r):void 0,i=await t.request({method:"eth_getBalance",params:[e,s||n]});return BigInt(i)}async function Ix(t){const e=await t.request({method:"eth_blobBaseFee"});return BigInt(e)}async function Px(t,{blockHash:e,blockNumber:r,blockTag:n="latest"}={}){const s=r!==void 0?Y(r):void 0;let i;return e?i=await t.request({method:"eth_getBlockTransactionCountByHash",params:[e]},{dedupe:!0}):i=await t.request({method:"eth_getBlockTransactionCountByNumber",params:[s||n]},{dedupe:!!s}),gr(i)}async function Sd(t,{address:e,blockNumber:r,blockTag:n="latest"}){const s=r!==void 0?Y(r):void 0,i=await t.request({method:"eth_getCode",params:[e,s||n]},{dedupe:!!s});if(i!=="0x")return i}class Ox extends G{constructor({address:e}){super(`No EIP-712 domain found on contract "${e}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${e}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}async function Bx(t,e){const{address:r,factory:n,factoryData:s}=e;try{const[i,a,o,c,u,l,f]=await re(t,wr,"readContract")({abi:Cx,address:r,functionName:"eip712Domain",factory:n,factoryData:s});return{domain:{name:a,version:o,chainId:Number(c),verifyingContract:u,salt:l},extensions:f,fields:i}}catch(i){const a=i;throw a.name==="ContractFunctionExecutionError"&&a.cause.name==="ContractFunctionZeroDataError"?new Ox({address:r}):a}}const Cx=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}];function Rx(t){var e;return{baseFeePerGas:t.baseFeePerGas.map(r=>BigInt(r)),gasUsedRatio:t.gasUsedRatio,oldestBlock:BigInt(t.oldestBlock),reward:(e=t.reward)==null?void 0:e.map(r=>r.map(n=>BigInt(n)))}}async function Nx(t,{blockCount:e,blockNumber:r,blockTag:n="latest",rewardPercentiles:s}){const i=typeof r=="bigint"?Y(r):void 0,a=await t.request({method:"eth_feeHistory",params:[Y(e),i||n,s]},{dedupe:!!i});return Rx(a)}async function Ux(t,{filter:e}){const r=e.strict??!1,s=(await e.request({method:"eth_getFilterLogs",params:[e.id]})).map(i=>Un(i));return e.abi?jh({abi:e.abi,logs:s,strict:r}):s}function Fx(t){const{authorizationList:e}=t;if(e)for(const r of e){const{chainId:n}=r,s=r.address;if(!ut(s))throw new $t({address:s});if(n<0)throw new vu({chainId:n})}r0(t)}function Mx(t){const{blobVersionedHashes:e}=t;if(e){if(e.length===0)throw new Kg;for(const r of e){const n=Ge(r),s=gr(Xs(r,0,1));if(n!==32)throw new n8({hash:r,size:n});if(s!==Wg)throw new s8({hash:r,version:s})}}r0(t)}function r0(t){const{chainId:e,maxPriorityFeePerGas:r,maxFeePerGas:n,to:s}=t;if(e<=0)throw new vu({chainId:e});if(s&&!ut(s))throw new $t({address:s});if(n&&n>yu)throw new Zs({maxFeePerGas:n});if(r&&n&&r>n)throw new io({maxFeePerGas:n,maxPriorityFeePerGas:r})}function $x(t){const{chainId:e,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:s,to:i}=t;if(e<=0)throw new vu({chainId:e});if(i&&!ut(i))throw new $t({address:i});if(r||s)throw new G("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>yu)throw new Zs({maxFeePerGas:n})}function jx(t){const{chainId:e,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:s,to:i}=t;if(i&&!ut(i))throw new $t({address:i});if(typeof e<"u"&&e<=0)throw new vu({chainId:e});if(r||s)throw new G("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>yu)throw new Zs({maxFeePerGas:n})}function ku(t){if(!t||t.length===0)return[];const e=[];for(let r=0;r<t.length;r++){const{address:n,storageKeys:s}=t[r];for(let i=0;i<s.length;i++)if(s[i].length-2!==64)throw new SS({storageKey:s[i]});if(!ut(n,{strict:!1}))throw new $t({address:n});e.push([n,s])}return e}function Hx(t,e){const r=Yg(t);return r==="eip1559"?zx(t,e):r==="eip2930"?Vx(t,e):r==="eip4844"?Dx(t,e):r==="eip7702"?Lx(t,e):Gx(t,e)}function Lx(t,e){const{authorizationList:r,chainId:n,gas:s,nonce:i,to:a,value:o,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:l,data:f}=t;Fx(t);const p=ku(l),d=qx(r);return jr(["0x04",gs([Y(n),i?Y(i):"0x",u?Y(u):"0x",c?Y(c):"0x",s?Y(s):"0x",a??"0x",o?Y(o):"0x",f??"0x",p,d,...jo(t,e)])])}function Dx(t,e){const{chainId:r,gas:n,nonce:s,to:i,value:a,maxFeePerBlobGas:o,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:l,data:f}=t;Mx(t);let p=t.blobVersionedHashes,d=t.sidecars;if(t.blobs&&(typeof p>"u"||typeof d>"u")){const v=typeof t.blobs[0]=="string"?t.blobs:t.blobs.map(_=>tt(_)),w=t.kzg,x=Rh({blobs:v,kzg:w});if(typeof p>"u"&&(p=Vg({commitments:x})),typeof d>"u"){const _=Nh({blobs:v,commitments:x,kzg:w});d=Xg({blobs:v,commitments:x,proofs:_})}}const b=ku(l),g=[Y(r),s?Y(s):"0x",u?Y(u):"0x",c?Y(c):"0x",n?Y(n):"0x",i??"0x",a?Y(a):"0x",f??"0x",b,o?Y(o):"0x",p??[],...jo(t,e)],A=[],S=[],T=[];if(d)for(let v=0;v<d.length;v++){const{blob:w,commitment:x,proof:_}=d[v];A.push(w),S.push(x),T.push(_)}return jr(["0x03",gs(d?[g,A,S,T]:g)])}function zx(t,e){const{chainId:r,gas:n,nonce:s,to:i,value:a,maxFeePerGas:o,maxPriorityFeePerGas:c,accessList:u,data:l}=t;r0(t);const f=ku(u),p=[Y(r),s?Y(s):"0x",c?Y(c):"0x",o?Y(o):"0x",n?Y(n):"0x",i??"0x",a?Y(a):"0x",l??"0x",f,...jo(t,e)];return jr(["0x02",gs(p)])}function Vx(t,e){const{chainId:r,gas:n,data:s,nonce:i,to:a,value:o,accessList:c,gasPrice:u}=t;$x(t);const l=ku(c),f=[Y(r),i?Y(i):"0x",u?Y(u):"0x",n?Y(n):"0x",a??"0x",o?Y(o):"0x",s??"0x",l,...jo(t,e)];return jr(["0x01",gs(f)])}function Gx(t,e){const{chainId:r=0,gas:n,data:s,nonce:i,to:a,value:o,gasPrice:c}=t;jx(t);let u=[i?Y(i):"0x",c?Y(c):"0x",n?Y(n):"0x",a??"0x",o?Y(o):"0x",s??"0x"];if(e){const l=(()=>{if(e.v>=35n)return(e.v-35n)/2n>0?e.v:27n+(e.v===35n?0n:1n);if(r>0)return BigInt(r*2)+BigInt(35n+e.v-27n);const d=27n+(e.v===27n?0n:1n);if(e.v!==d)throw new ES({v:e.v});return d})(),f=br(e.r),p=br(e.s);u=[...u,Y(l),f==="0x00"?"0x":f,p==="0x00"?"0x":p]}else r>0&&(u=[...u,Y(r),"0x","0x"]);return gs(u)}function jo(t,e){const r=e??t,{v:n,yParity:s}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof s>"u")return[];const i=br(r.r),a=br(r.s);return[typeof s=="number"?s?Y(1):"0x":n===0n?"0x":n===1n?Y(1):n===27n?"0x":Y(1),i==="0x00"?"0x":i,a==="0x00"?"0x":a]}function qx(t){if(!t||t.length===0)return[];const e=[];for(const r of t){const{chainId:n,nonce:s,...i}=r,a=r.address;e.push([n?Ft(n):"0x",a,s?Ft(s):"0x",...jo({},i)])}return e}async function Wx({address:t,authorization:e,signature:r}){return ta(wh(t),await hu({authorization:e,signature:r}))}const oc=new Qi(8192);function Kx(t,{enabled:e=!0,id:r}){if(!e||!r)return t();if(oc.get(r))return oc.get(r);const n=t().finally(()=>oc.delete(r));return oc.set(r,n),n}function Xx(t,e={}){return async(r,n={})=>{var f;const{dedupe:s=!1,methods:i,retryDelay:a=150,retryCount:o=3,uid:c}={...e,...n},{method:u}=r;if((f=i==null?void 0:i.exclude)!=null&&f.includes(u))throw new Rs(new Error("method not supported"),{method:u});if(i!=null&&i.include&&!i.include.includes(u))throw new Rs(new Error("method not supported"),{method:u});const l=s?Vi(`${c}.${et(r)}`):void 0;return Kx(()=>Mc(async()=>{try{return await t(r)}catch(p){const d=p;switch(d.code){case La.code:throw new La(d);case Da.code:throw new Da(d);case za.code:throw new za(d,{method:r.method});case Va.code:throw new Va(d);case Ys.code:throw new Ys(d);case bs.code:throw new bs(d);case Ga.code:throw new Ga(d);case qa.code:throw new qa(d);case Wa.code:throw new Wa(d);case Rs.code:throw new Rs(d,{method:r.method});case Gi.code:throw new Gi(d);case Ka.code:throw new Ka(d);case Ni.code:throw new Ni(d);case Xa.code:throw new Xa(d);case Ya.code:throw new Ya(d);case Ja.code:throw new Ja(d);case Za.code:throw new Za(d);case Qa.code:throw new Qa(d);case qi.code:throw new qi(d);case eo.code:throw new eo(d);case to.code:throw new to(d);case ro.code:throw new ro(d);case no.code:throw new no(d);case so.code:throw new so(d);case Wi.code:throw new Wi(d);case 5e3:throw new Ni(d);default:throw p instanceof G?p:new OS(d)}}},{delay:({count:p,error:d})=>{var b;if(d&&d instanceof Ri){const g=(b=d==null?void 0:d.headers)==null?void 0:b.get("Retry-After");if(g!=null&&g.match(/\d/))return Number.parseInt(g,10)*1e3}return~~(1<<p)*a},retryCount:o,shouldRetry:({error:p})=>Yx(p)}),{enabled:s,id:l})}}function Yx(t){return"code"in t&&typeof t.code=="number"?t.code===-1||t.code===Gi.code||t.code===Ys.code:t instanceof Ri&&t.status?t.status===403||t.status===408||t.status===413||t.status===429||t.status===500||t.status===502||t.status===503||t.status===504:!0}function rt(t){const e={formatters:void 0,fees:void 0,serializers:void 0,...t};function r(n){return s=>{const i=typeof s=="function"?s(n):s,a={...n,...i};return Object.assign(a,{extend:r(a)})}}return Object.assign(e,{extend:r(e)})}function Jx(t,{errorInstance:e=new Error("timed out"),timeout:r,signal:n}){return new Promise((s,i)=>{(async()=>{let a;try{const o=new AbortController;r>0&&(a=setTimeout(()=>{n&&o.abort()},r)),s(await t({signal:(o==null?void 0:o.signal)||null}))}catch(o){(o==null?void 0:o.name)==="AbortError"&&i(e),i(o)}finally{clearTimeout(a)}})()})}function Zx(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const Kp=Zx();function Qx(t,e={}){const{url:r,headers:n}=e3(t);return{async request(s){var b;const{body:i,fetchFn:a=e.fetchFn??fetch,onRequest:o=e.onRequest,onResponse:c=e.onResponse,timeout:u=e.timeout??1e4}=s,l={...e.fetchOptions??{},...s.fetchOptions??{}},{headers:f,method:p,signal:d}=l;try{const g=await Jx(async({signal:S})=>{const T={...l,body:Array.isArray(i)?et(i.map(_=>({jsonrpc:"2.0",id:_.id??Kp.take(),..._}))):et({jsonrpc:"2.0",id:i.id??Kp.take(),...i}),headers:{...n,"Content-Type":"application/json",...f},method:p||"POST",signal:d||(u>0?S:null)},v=new Request(r,T),w=await(o==null?void 0:o(v,T))??{...T,url:r};return await a(w.url??r,w)},{errorInstance:new Pp({body:i,url:r}),timeout:u,signal:!0});c&&await c(g);let A;if((b=g.headers.get("Content-Type"))!=null&&b.startsWith("application/json"))A=await g.json();else{A=await g.text();try{A=JSON.parse(A||"{}")}catch(S){if(g.ok)throw S;A={error:A}}}if(!g.ok)throw new Ri({body:i,details:et(A.error)||g.statusText,headers:g.headers,status:g.status,url:r});return A}catch(g){throw g instanceof Ri||g instanceof Pp?g:new Ri({body:i,cause:g,url:r})}}}}function e3(t){try{const e=new URL(t),r=(()=>{if(e.username){const n=`${decodeURIComponent(e.username)}:${decodeURIComponent(e.password)}`;return e.username="",e.password="",{url:e.toString(),headers:{Authorization:`Basic ${btoa(n)}`}}}})();return{url:e.toString(),...r}}catch{return{url:t}}}const t3=`Ethereum Signed Message:
69
+ `;function r3(t){const e=typeof t=="string"?Vi(t):typeof t.raw=="string"?t.raw:tt(t.raw),r=Vi(`${t3}${Ge(e)}`);return sr([r,e])}function H1(t,e){return bt(r3(t),e)}class n3 extends G{constructor({domain:e}){super(`Invalid domain "${et(e)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class s3 extends G{constructor({primaryType:e,types:r}){super(`Invalid primary type \`${e}\` must be one of \`${JSON.stringify(Object.keys(r))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."]})}}class i3 extends G{constructor({type:e}){super(`Struct type "${e}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function a3(t){const{domain:e,message:r,primaryType:n,types:s}=t,i=(c,u)=>{const l={...u};for(const f of c){const{name:p,type:d}=f;d==="address"&&(l[p]=l[p].toLowerCase())}return l},a=s.EIP712Domain?e?i(s.EIP712Domain,e):{}:{},o=(()=>{if(n!=="EIP712Domain")return i(s[n],r)})();return et({domain:a,message:o,primaryType:n,types:s})}function L1(t){const{domain:e,message:r,primaryType:n,types:s}=t,i=(a,o)=>{for(const c of a){const{name:u,type:l}=c,f=o[u],p=l.match(xg);if(p&&(typeof f=="number"||typeof f=="bigint")){const[g,A,S]=p;Y(f,{signed:A==="int",size:Number.parseInt(S,10)/8})}if(l==="address"&&typeof f=="string"&&!ut(f))throw new $t({address:f});const d=l.match(qA);if(d){const[g,A]=d;if(A&&Ge(f)!==Number.parseInt(A,10))throw new eA({expectedSize:Number.parseInt(A,10),givenSize:Ge(f)})}const b=s[l];b&&(o3(l),i(b,f))}};if(s.EIP712Domain&&e){if(typeof e!="object")throw new n3({domain:e});i(s.EIP712Domain,e)}if(n!=="EIP712Domain")if(s[n])i(s[n],r);else throw new s3({primaryType:n,types:s})}function D1({domain:t}){return[typeof(t==null?void 0:t.name)=="string"&&{name:"name",type:"string"},(t==null?void 0:t.version)&&{name:"version",type:"string"},(typeof(t==null?void 0:t.chainId)=="number"||typeof(t==null?void 0:t.chainId)=="bigint")&&{name:"chainId",type:"uint256"},(t==null?void 0:t.verifyingContract)&&{name:"verifyingContract",type:"address"},(t==null?void 0:t.salt)&&{name:"salt",type:"bytes32"}].filter(Boolean)}function o3(t){if(t==="address"||t==="bool"||t==="string"||t.startsWith("bytes")||t.startsWith("uint")||t.startsWith("int"))throw new i3({type:t})}function c3(t){const{domain:e={},message:r,primaryType:n}=t,s={EIP712Domain:D1({domain:e}),...t.types};L1({domain:e,message:r,primaryType:n,types:s});const i=["0x1901"];return e&&i.push(u3({domain:e,types:s})),n!=="EIP712Domain"&&i.push(z1({data:r,primaryType:n,types:s})),bt(sr(i))}function u3({domain:t,types:e}){return z1({data:t,primaryType:"EIP712Domain",types:e})}function z1({data:t,primaryType:e,types:r}){const n=V1({data:t,primaryType:e,types:r});return bt(n)}function V1({data:t,primaryType:e,types:r}){const n=[{type:"bytes32"}],s=[l3({primaryType:e,types:r})];for(const i of r[e]){const[a,o]=q1({types:r,name:i.name,type:i.type,value:t[i.name]});n.push(a),s.push(o)}return Es(n,s)}function l3({primaryType:t,types:e}){const r=Ft(f3({primaryType:t,types:e}));return bt(r)}function f3({primaryType:t,types:e}){let r="";const n=G1({primaryType:t,types:e});n.delete(t);const s=[t,...Array.from(n).sort()];for(const i of s)r+=`${i}(${e[i].map(({name:a,type:o})=>`${o} ${a}`).join(",")})`;return r}function G1({primaryType:t,types:e},r=new Set){const n=t.match(/^\w*/u),s=n==null?void 0:n[0];if(r.has(s)||e[s]===void 0)return r;r.add(s);for(const i of e[s])G1({primaryType:i.type,types:e},r);return r}function q1({types:t,name:e,type:r,value:n}){if(t[r]!==void 0)return[{type:"bytes32"},bt(V1({data:n,primaryType:r,types:t}))];if(r==="bytes")return[{type:"bytes32"},bt(n)];if(r==="string")return[{type:"bytes32"},bt(Ft(n))];if(r.lastIndexOf("]")===r.length-1){const s=r.slice(0,r.lastIndexOf("[")),i=n.map(a=>q1({name:e,type:s,types:t,value:a}));return[{type:"bytes32"},bt(Es(i.map(([a])=>a),i.map(([,a])=>a)))]}return[{type:r},n]}class d3 extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const h3={checksum:new d3(8192)},ml=h3.checksum;function W1(t,e={}){const{as:r=typeof t=="string"?"Hex":"Bytes"}=e,n=wg(v8(t));return r==="Bytes"?n:Fr(n)}const p3=/^0x[a-fA-F0-9]{40}$/;function Tu(t,e={}){const{strict:r=!0}=e;if(!p3.test(t))throw new Xp({address:t,cause:new y3});if(r){if(t.toLowerCase()===t)return;if(K1(t)!==t)throw new Xp({address:t,cause:new m3})}}function K1(t){if(ml.has(t))return ml.get(t);Tu(t,{strict:!1});const e=t.substring(2).toLowerCase(),r=W1(A8(e),{as:"Bytes"}),n=e.split("");for(let i=0;i<40;i+=2)r[i>>1]>>4>=8&&n[i]&&(n[i]=n[i].toUpperCase()),(r[i>>1]&15)>=8&&n[i+1]&&(n[i+1]=n[i+1].toUpperCase());const s=`0x${n.join("")}`;return ml.set(t,s),s}function xd(t,e={}){const{strict:r=!0}=e??{};try{return Tu(t,{strict:r}),!0}catch{return!1}}class Xp extends le{constructor({address:e,cause:r}){super(`Address "${e}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class y3 extends le{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class m3 extends le{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}const b3=/^(.*)\[([0-9]*)\]$/,g3=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,X1=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,Yp=2n**256n-1n;function Fi(t,e,r){const{checksumAddress:n,staticPosition:s}=r,i=i0(e.type);if(i){const[a,o]=i;return v3(t,{...e,type:o},{checksumAddress:n,length:a,staticPosition:s})}if(e.type==="tuple")return x3(t,e,{checksumAddress:n,staticPosition:s});if(e.type==="address")return w3(t,{checksum:n});if(e.type==="bool")return E3(t);if(e.type.startsWith("bytes"))return A3(t,e,{staticPosition:s});if(e.type.startsWith("uint")||e.type.startsWith("int"))return S3(t,e);if(e.type==="string")return k3(t,{staticPosition:s});throw new o0(e.type)}const Jp=32,kd=32;function w3(t,e={}){const{checksum:r=!1}=e,n=t.readBytes(32);return[(i=>r?K1(i):i)(Fr(x8(n,-20))),32]}function v3(t,e,r){const{checksumAddress:n,length:s,staticPosition:i}=r;if(!s){const c=Bn(t.readBytes(kd)),u=i+c,l=u+Jp;t.setPosition(u);const f=Bn(t.readBytes(Jp)),p=co(e);let d=0;const b=[];for(let g=0;g<f;++g){t.setPosition(l+(p?g*32:d));const[A,S]=Fi(t,e,{checksumAddress:n,staticPosition:l});d+=S,b.push(A)}return t.setPosition(i+32),[b,32]}if(co(e)){const c=Bn(t.readBytes(kd)),u=i+c,l=[];for(let f=0;f<s;++f){t.setPosition(u+f*32);const[p]=Fi(t,e,{checksumAddress:n,staticPosition:u});l.push(p)}return t.setPosition(i+32),[l,32]}let a=0;const o=[];for(let c=0;c<s;++c){const[u,l]=Fi(t,e,{checksumAddress:n,staticPosition:i+a});a+=l,o.push(u)}return[o,a]}function E3(t){return[T8(t.readBytes(32),{size:32}),32]}function A3(t,e,{staticPosition:r}){const[n,s]=e.type.split("bytes");if(!s){const a=Bn(t.readBytes(32));t.setPosition(r+a);const o=Bn(t.readBytes(32));if(o===0)return t.setPosition(r+32),["0x",32];const c=t.readBytes(o);return t.setPosition(r+32),[Fr(c),32]}return[Fr(t.readBytes(Number.parseInt(s,10),32)),32]}function S3(t,e){const r=e.type.startsWith("int"),n=Number.parseInt(e.type.split("int")[1]||"256",10),s=t.readBytes(32);return[n>48?k8(s,{signed:r}):Bn(s,{signed:r}),32]}function x3(t,e,r){const{checksumAddress:n,staticPosition:s}=r,i=e.components.length===0||e.components.some(({name:c})=>!c),a=i?[]:{};let o=0;if(co(e)){const c=Bn(t.readBytes(kd)),u=s+c;for(let l=0;l<e.components.length;++l){const f=e.components[l];t.setPosition(u+o);const[p,d]=Fi(t,f,{checksumAddress:n,staticPosition:u});o+=d,a[i?l:f==null?void 0:f.name]=p}return t.setPosition(s+32),[a,32]}for(let c=0;c<e.components.length;++c){const u=e.components[c],[l,f]=Fi(t,u,{checksumAddress:n,staticPosition:s});a[i?c:u==null?void 0:u.name]=l,o+=f}return[a,o]}function k3(t,{staticPosition:e}){const r=Bn(t.readBytes(32)),n=e+r;t.setPosition(n);const s=Bn(t.readBytes(32));if(s===0)return t.setPosition(e+32),["",32];const i=t.readBytes(s,32),a=_8(o1(i));return t.setPosition(e+32),[a,32]}function T3({checksumAddress:t,parameters:e,values:r}){const n=[];for(let s=0;s<e.length;s++)n.push(n0({checksumAddress:t,parameter:e[s],value:r[s]}));return n}function n0({checksumAddress:t=!1,parameter:e,value:r}){const n=e,s=i0(n.type);if(s){const[i,a]=s;return I3(r,{checksumAddress:t,length:i,parameter:{...n,type:a}})}if(n.type==="tuple")return R3(r,{checksumAddress:t,parameter:n});if(n.type==="address")return _3(r,{checksum:t});if(n.type==="bool")return O3(r);if(n.type.startsWith("uint")||n.type.startsWith("int")){const i=n.type.startsWith("int"),[,,a="256"]=X1.exec(n.type)??[];return B3(r,{signed:i,size:Number(a)})}if(n.type.startsWith("bytes"))return P3(r,{type:n.type});if(n.type==="string")return C3(r);throw new o0(n.type)}function s0(t){let e=0;for(let i=0;i<t.length;i++){const{dynamic:a,encoded:o}=t[i];a?e+=32:e+=ir(o)}const r=[],n=[];let s=0;for(let i=0;i<t.length;i++){const{dynamic:a,encoded:o}=t[i];a?(r.push(Ut(e+s,{size:32})),n.push(o),s+=ir(o)):r.push(o)}return Ur(...r,...n)}function _3(t,e){const{checksum:r=!1}=e;return Tu(t,{strict:r}),{dynamic:!1,encoded:Qs(t.toLowerCase())}}function I3(t,e){const{checksumAddress:r,length:n,parameter:s}=e,i=n===null;if(!Array.isArray(t))throw new D3(t);if(!i&&t.length!==n)throw new L3({expectedLength:n,givenLength:t.length,type:`${s.type}[${n}]`});let a=!1;const o=[];for(let c=0;c<t.length;c++){const u=n0({checksumAddress:r,parameter:s,value:t[c]});u.dynamic&&(a=!0),o.push(u)}if(i||a){const c=s0(o);if(i){const u=Ut(o.length,{size:32});return{dynamic:!0,encoded:o.length>0?Ur(u,c):u}}if(a)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:Ur(...o.map(({encoded:c})=>c))}}function P3(t,{type:e}){const[,r]=e.split("bytes"),n=ir(t);if(!r){let s=t;return n%32!==0&&(s=ei(s,Math.ceil((t.length-2)/2/32)*32)),{dynamic:!0,encoded:Ur(Qs(Ut(n,{size:32})),s)}}if(n!==Number.parseInt(r,10))throw new J1({expectedSize:Number.parseInt(r,10),value:t});return{dynamic:!1,encoded:ei(t)}}function O3(t){if(typeof t!="boolean")throw new le(`Invalid boolean value: "${t}" (type: ${typeof t}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Qs(c1(t))}}function B3(t,{signed:e,size:r}){if(typeof r=="number"){const n=2n**(BigInt(r)-(e?1n:0n))-1n,s=e?-n-1n:0n;if(t>n||t<s)throw new f1({max:n.toString(),min:s.toString(),signed:e,size:r/8,value:t.toString()})}return{dynamic:!1,encoded:Ut(t,{size:32,signed:e})}}function C3(t){const e=Gh(t),r=Math.ceil(ir(e)/32),n=[];for(let s=0;s<r;s++)n.push(ei(rn(e,s*32,(s+1)*32)));return{dynamic:!0,encoded:Ur(ei(Ut(ir(e),{size:32})),...n)}}function R3(t,e){const{checksumAddress:r,parameter:n}=e;let s=!1;const i=[];for(let a=0;a<n.components.length;a++){const o=n.components[a],c=Array.isArray(t)?a:o.name,u=n0({checksumAddress:r,parameter:o,value:t[c]});i.push(u),u.dynamic&&(s=!0)}return{dynamic:s,encoded:s?s0(i):Ur(...i.map(({encoded:a})=>a))}}function i0(t){const e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function co(t){var n;const{type:e}=t;if(e==="string"||e==="bytes"||e.endsWith("[]"))return!0;if(e==="tuple")return(n=t.components)==null?void 0:n.some(co);const r=i0(t.type);return!!(r&&co({...t,type:r[1]}))}const N3={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new M3({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(t){if(t<0||t>this.bytes.length-1)throw new F3({length:this.bytes.length,position:t})},decrementPosition(t){if(t<0)throw new Zp({offset:t});const e=this.position-t;this.assertPosition(e),this.position=e},getReadCount(t){return this.positionReadCount.get(t||this.position)||0},incrementPosition(t){if(t<0)throw new Zp({offset:t});const e=this.position+t;this.assertPosition(e),this.position=e},inspectByte(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectBytes(t,e){const r=e??this.position;return this.assertPosition(r+t-1),this.bytes.subarray(r,r+t)},inspectUint8(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectUint16(t){const e=t??this.position;return this.assertPosition(e+1),this.dataView.getUint16(e)},inspectUint24(t){const e=t??this.position;return this.assertPosition(e+2),(this.dataView.getUint16(e)<<8)+this.dataView.getUint8(e+2)},inspectUint32(t){const e=t??this.position;return this.assertPosition(e+3),this.dataView.getUint32(e)},pushByte(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushBytes(t){this.assertPosition(this.position+t.length-1),this.bytes.set(t,this.position),this.position+=t.length},pushUint8(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushUint16(t){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,t),this.position+=2},pushUint24(t){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,t>>8),this.dataView.setUint8(this.position+2,t&255),this.position+=3},pushUint32(t){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,t),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const t=this.inspectByte();return this.position++,t},readBytes(t,e){this.assertReadLimit(),this._touch();const r=this.inspectBytes(t);return this.position+=e??t,r},readUint8(){this.assertReadLimit(),this._touch();const t=this.inspectUint8();return this.position+=1,t},readUint16(){this.assertReadLimit(),this._touch();const t=this.inspectUint16();return this.position+=2,t},readUint24(){this.assertReadLimit(),this._touch();const t=this.inspectUint24();return this.position+=3,t},readUint32(){this.assertReadLimit(),this._touch();const t=this.inspectUint32();return this.position+=4,t},get remaining(){return this.bytes.length-this.position},setPosition(t){const e=this.position;return this.assertPosition(t),this.position=t,()=>this.position=e},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const t=this.getReadCount();this.positionReadCount.set(this.position,t+1),t>0&&this.recursiveReadCount++}};function U3(t,{recursiveReadLimit:e=8192}={}){const r=Object.create(N3);return r.bytes=t,r.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=e,r}class Zp extends le{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}}class F3 extends le{constructor({length:e,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${e}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"})}}class M3 extends le{constructor({count:e,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${e}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"})}}function $3(t,e,r={}){const{as:n="Array",checksumAddress:s=!1}=r,i=typeof e=="string"?a1(e):e,a=U3(i);if(Ti(i)===0&&t.length>0)throw new H3;if(Ti(i)&&Ti(i)<32)throw new j3({data:typeof e=="string"?e:Fr(e),parameters:t,size:Ti(i)});let o=0;const c=n==="Array"?[]:{};for(let u=0;u<t.length;++u){const l=t[u];a.setPosition(o);const[f,p]=Fi(a,l,{checksumAddress:s,staticPosition:0});o+=p,n==="Array"?c.push(f):c[l.name??u]=f}return c}function a0(t,e,r){const{checksumAddress:n=!1}={};if(t.length!==e.length)throw new Z1({expectedLength:t.length,givenLength:e.length});const s=T3({checksumAddress:n,parameters:t,values:e}),i=s0(s);return i.length===0?"0x":i}function Td(t,e){if(t.length!==e.length)throw new Z1({expectedLength:t.length,givenLength:e.length});const r=[];for(let n=0;n<t.length;n++){const s=t[n],i=e[n];r.push(Td.encode(s,i))}return Ur(...r)}(function(t){function e(r,n,s=!1){if(r==="address"){const c=n;return Tu(c),Qs(c.toLowerCase(),s?32:0)}if(r==="string")return Gh(n);if(r==="bytes")return n;if(r==="bool")return Qs(c1(n),s?32:1);const i=r.match(X1);if(i){const[c,u,l="256"]=i,f=Number.parseInt(l,10)/8;return Ut(n,{size:s?32:f,signed:u==="int"})}const a=r.match(g3);if(a){const[c,u]=a;if(Number.parseInt(u,10)!==(n.length-2)/2)throw new J1({expectedSize:Number.parseInt(u,10),value:n});return ei(n,s?32:0)}const o=r.match(b3);if(o&&Array.isArray(n)){const[c,u]=o,l=[];for(let f=0;f<n.length;f++)l.push(e(u,n[f],!0));return l.length===0?"0x":Ur(...l)}throw new o0(r)}t.encode=e})(Td||(Td={}));function Y1(t){return Array.isArray(t)&&typeof t[0]=="string"||typeof t=="string"?pp(t):t}class j3 extends le{constructor({data:e,parameters:r,size:n}){super(`Data size of ${n} bytes is too small for given parameters.`,{metaMessages:[`Params: (${Ai(r)})`,`Data: ${e} (${n} bytes)`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"})}}class H3 extends le{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.'),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ZeroDataError"})}}class L3 extends le{constructor({expectedLength:e,givenLength:r,type:n}){super(`Array length mismatch for type \`${n}\`. Expected: \`${e}\`. Given: \`${r}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}}class J1 extends le{constructor({expectedSize:e,value:r}){super(`Size of bytes "${r}" (bytes${ir(r)}) does not match expected size (bytes${e}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class Z1 extends le{constructor({expectedLength:e,givenLength:r}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${r}`].join(`
70
+ `)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class D3 extends le{constructor(e){super(`Value \`${e}\` is not a valid array.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}}class o0 extends le{constructor(e){super(`Type \`${e}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}class Q1 extends cu{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,kA(e);const n=Pn(r);if(this.iHash=e.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;const s=this.blockLen,i=new Uint8Array(s);i.set(n.length>s?e.create().update(n).digest():n);for(let a=0;a<i.length;a++)i[a]^=54;this.iHash.update(i),this.oHash=e.create();for(let a=0;a<i.length;a++)i[a]^=106;this.oHash.update(i),Nn(i)}update(e){return ms(this),this.iHash.update(e),this}digestInto(e){ms(this),ys(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:n,finished:s,destroyed:i,blockLen:a,outputLen:o}=this;return e=e,e.finished=s,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const ew=(t,e,r)=>new Q1(t,e).update(r).digest();ew.create=(t,e)=>new Q1(t,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Vt=BigInt(0),Mt=BigInt(1),Ns=BigInt(2),z3=BigInt(3),tw=BigInt(4),rw=BigInt(5),nw=BigInt(8);function Ht(t,e){const r=t%e;return r>=Vt?r:e+r}function fr(t,e,r){let n=t;for(;e-- >Vt;)n*=n,n%=r;return n}function _d(t,e){if(t===Vt)throw new Error("invert: expected non-zero number");if(e<=Vt)throw new Error("invert: expected positive modulus, got "+e);let r=Ht(t,e),n=e,s=Vt,i=Mt;for(;r!==Vt;){const o=n/r,c=n%r,u=s-i*o;n=r,r=c,s=i,i=u}if(n!==Mt)throw new Error("invert: does not exist");return Ht(s,e)}function sw(t,e){const r=(t.ORDER+Mt)/tw,n=t.pow(e,r);if(!t.eql(t.sqr(n),e))throw new Error("Cannot find square root");return n}function V3(t,e){const r=(t.ORDER-rw)/nw,n=t.mul(e,Ns),s=t.pow(n,r),i=t.mul(e,s),a=t.mul(t.mul(i,Ns),s),o=t.mul(i,t.sub(a,t.ONE));if(!t.eql(t.sqr(o),e))throw new Error("Cannot find square root");return o}function G3(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-Mt,r=0;for(;e%Ns===Vt;)e/=Ns,r++;let n=Ns;const s=c0(t);for(;Qp(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return sw;let i=s.pow(n,e);const a=(e+Mt)/Ns;return function(c,u){if(c.is0(u))return u;if(Qp(c,u)!==1)throw new Error("Cannot find square root");let l=r,f=c.mul(c.ONE,i),p=c.pow(u,e),d=c.pow(u,a);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let b=1,g=c.sqr(p);for(;!c.eql(g,c.ONE);)if(b++,g=c.sqr(g),b===l)throw new Error("Cannot find square root");const A=Mt<<BigInt(l-b-1),S=c.pow(f,A);l=b,f=c.sqr(S),p=c.mul(p,f),d=c.mul(d,S)}return d}}function q3(t){return t%tw===z3?sw:t%nw===rw?V3:G3(t)}const W3=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function K3(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=W3.reduce((n,s)=>(n[s]="function",n),e);return gu(t,r)}function X3(t,e,r){if(r<Vt)throw new Error("invalid exponent, negatives unsupported");if(r===Vt)return t.ONE;if(r===Mt)return e;let n=t.ONE,s=e;for(;r>Vt;)r&Mt&&(n=t.mul(n,s)),s=t.sqr(s),r>>=Mt;return n}function iw(t,e,r=!1){const n=new Array(e.length).fill(r?t.ZERO:void 0),s=e.reduce((a,o,c)=>t.is0(o)?a:(n[c]=a,t.mul(a,o)),t.ONE),i=t.inv(s);return e.reduceRight((a,o,c)=>t.is0(o)?a:(n[c]=t.mul(a,n[c]),t.mul(a,o)),i),n}function Qp(t,e){const r=(t.ORDER-Mt)/Ns,n=t.pow(e,r),s=t.eql(n,t.ONE),i=t.eql(n,t.ZERO),a=t.eql(n,t.neg(t.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function aw(t,e){e!==void 0&&ps(e);const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function c0(t,e,r=!1,n={}){if(t<=Vt)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:i}=aw(t,e);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let a;const o=Object.freeze({ORDER:t,isLE:r,BITS:s,BYTES:i,MASK:bu(s),ZERO:Vt,ONE:Mt,create:c=>Ht(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Vt<=c&&c<t},is0:c=>c===Vt,isOdd:c=>(c&Mt)===Mt,neg:c=>Ht(-c,t),eql:(c,u)=>c===u,sqr:c=>Ht(c*c,t),add:(c,u)=>Ht(c+u,t),sub:(c,u)=>Ht(c-u,t),mul:(c,u)=>Ht(c*u,t),pow:(c,u)=>X3(o,c,u),div:(c,u)=>Ht(c*_d(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>_d(c,t),sqrt:n.sqrt||(c=>(a||(a=q3(t)),a(o,c))),toBytes:c=>r?t1(c,i):No(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return r?e1(c):zs(c)},invertBatch:c=>iw(o,c),cmov:(c,u,l)=>l?u:c});return Object.freeze(o)}function ow(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function cw(t){const e=ow(t);return e+Math.ceil(e/2)}function Y3(t,e,r=!1){const n=t.length,s=ow(e),i=cw(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const a=r?e1(t):zs(t),o=Ht(a,e-Mt)+Mt;return r?t1(o,s):No(o,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ey=BigInt(0),Id=BigInt(1);function bl(t,e){const r=e.negate();return t?r:e}function uw(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function gl(t,e){uw(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1),s=2**t,i=bu(t),a=BigInt(t);return{windows:r,windowSize:n,mask:i,maxNumber:s,shiftBy:a}}function ty(t,e,r){const{windowSize:n,mask:s,maxNumber:i,shiftBy:a}=r;let o=Number(t&s),c=t>>a;o>n&&(o-=i,c+=Id);const u=e*n,l=u+Math.abs(o)-1,f=o===0,p=o<0,d=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:p,isNegF:d,offsetF:u}}function J3(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function Z3(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}const wl=new WeakMap,lw=new WeakMap;function vl(t){return lw.get(t)||1}function Q3(t,e){return{constTimeNegate:bl,hasPrecomputes(r){return vl(r)!==1},unsafeLadder(r,n,s=t.ZERO){let i=r;for(;n>ey;)n&Id&&(s=s.add(i)),i=i.double(),n>>=Id;return s},precomputeWindow(r,n){const{windows:s,windowSize:i}=gl(n,e),a=[];let o=r,c=o;for(let u=0;u<s;u++){c=o,a.push(c);for(let l=1;l<i;l++)c=c.add(o),a.push(c);o=c.double()}return a},wNAF(r,n,s){let i=t.ZERO,a=t.BASE;const o=gl(r,e);for(let c=0;c<o.windows;c++){const{nextN:u,offset:l,isZero:f,isNeg:p,isNegF:d,offsetF:b}=ty(s,c,o);s=u,f?a=a.add(bl(d,n[b])):i=i.add(bl(p,n[l]))}return{p:i,f:a}},wNAFUnsafe(r,n,s,i=t.ZERO){const a=gl(r,e);for(let o=0;o<a.windows&&s!==ey;o++){const{nextN:c,offset:u,isZero:l,isNeg:f}=ty(s,o,a);if(s=c,!l){const p=n[u];i=i.add(f?p.negate():p)}}return i},getPrecomputes(r,n,s){let i=wl.get(n);return i||(i=this.precomputeWindow(n,r),r!==1&&wl.set(n,s(i))),i},wNAFCached(r,n,s){const i=vl(r);return this.wNAF(i,this.getPrecomputes(i,r,s),n)},wNAFCachedUnsafe(r,n,s,i){const a=vl(r);return a===1?this.unsafeLadder(r,n,i):this.wNAFUnsafe(a,this.getPrecomputes(a,r,s),n,i)},setWindowSize(r,n){uw(n,e),lw.set(r,n),wl.delete(r)}}}function ek(t,e,r,n){J3(r,t),Z3(n,e);const s=r.length,i=n.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");const a=t.ZERO,o=u8(BigInt(s));let c=1;o>12?c=o-3:o>4?c=o-2:o>0&&(c=2);const u=bu(c),l=new Array(Number(u)+1).fill(a),f=Math.floor((e.BITS-1)/c)*c;let p=a;for(let d=f;d>=0;d-=c){l.fill(a);for(let g=0;g<i;g++){const A=n[g],S=Number(A>>BigInt(d)&u);l[S]=l[S].add(r[g])}let b=a;for(let g=l.length-1,A=a;g>0;g--)A=A.add(l[g]),b=b.add(A);if(p=p.add(b),d!==0)for(let g=0;g<c;g++)p=p.double()}return p}function fw(t){return K3(t.Fp),gu(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...aw(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ry(t){t.lowS!==void 0&&ao("lowS",t.lowS),t.prehash!==void 0&&ao("prehash",t.prehash)}function tk(t){const e=fw(t);gu(e,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:r,Fp:n,a:s}=e;if(r){if(!n.eql(s,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...e})}class rk extends Error{constructor(e=""){super(e)}}const An={Err:rk,_tlv:{encode:(t,e)=>{const{Err:r}=An;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const n=e.length/2,s=nc(n);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const i=n>127?nc(s.length/2|128):"";return nc(t)+i+s+e},decode(t,e){const{Err:r}=An;let n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");const s=e[n++],i=!!(s&128);let a=0;if(!i)a=s;else{const c=s&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const u=e.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const l of u)a=a<<8|l;if(n+=c,a<128)throw new r("tlv.decode(long): not minimal encoding")}const o=e.subarray(n,n+a);if(o.length!==a)throw new r("tlv.decode: wrong value length");return{v:o,l:e.subarray(n+a)}}},_int:{encode(t){const{Err:e}=An;if(t<Tn)throw new e("integer: negative integers are not allowed");let r=nc(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=An;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return zs(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=An,s=hr("signature",t),{v:i,l:a}=n.decode(48,s);if(a.length)throw new e("invalid signature: left bytes after parsing");const{v:o,l:c}=n.decode(2,i),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(o),s:r.decode(u)}},hexFromSig(t){const{_tlv:e,_int:r}=An,n=e.encode(2,r.encode(t.r)),s=e.encode(2,r.encode(t.s)),i=n+s;return e.encode(48,i)}};function El(t,e){return oo(No(t,e))}const Tn=BigInt(0),lt=BigInt(1);BigInt(2);const Al=BigInt(3),nk=BigInt(4);function sk(t){const e=tk(t),{Fp:r}=e,n=c0(e.n,e.nBitLength),s=e.toBytes||((v,w,x)=>{const _=w.toAffine();return Uc(Uint8Array.from([4]),r.toBytes(_.x),r.toBytes(_.y))}),i=e.fromBytes||(v=>{const w=v.subarray(1),x=r.fromBytes(w.subarray(0,r.BYTES)),_=r.fromBytes(w.subarray(r.BYTES,2*r.BYTES));return{x,y:_}});function a(v){const{a:w,b:x}=e,_=r.sqr(v),I=r.mul(_,v);return r.add(r.add(I,r.mul(v,w)),x)}function o(v,w){const x=r.sqr(w),_=a(v);return r.eql(x,_)}if(!o(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=r.mul(r.pow(e.a,Al),nk),u=r.mul(r.sqr(e.b),BigInt(27));if(r.is0(r.add(c,u)))throw new Error("bad curve params: a or b");function l(v){return Vh(v,lt,e.n)}function f(v){const{allowedPrivateKeyLengths:w,nByteLength:x,wrapPrivateKey:_,n:I}=e;if(w&&typeof v!="bigint"){if(Ro(v)&&(v=oo(v)),typeof v!="string"||!w.includes(v.length))throw new Error("invalid private key");v=v.padStart(x*2,"0")}let N;try{N=typeof v=="bigint"?v:zs(hr("private key",v,x))}catch{throw new Error("invalid private key, expected hex or "+x+" bytes, got "+typeof v)}return _&&(N=Ht(N,I)),Ui("private key",N,lt,I),N}function p(v){if(!(v instanceof g))throw new Error("ProjectivePoint expected")}const d=$p((v,w)=>{const{px:x,py:_,pz:I}=v;if(r.eql(I,r.ONE))return{x,y:_};const N=v.is0();w==null&&(w=N?r.ONE:r.inv(I));const C=r.mul(x,w),j=r.mul(_,w),M=r.mul(I,w);if(N)return{x:r.ZERO,y:r.ZERO};if(!r.eql(M,r.ONE))throw new Error("invZ was invalid");return{x:C,y:j}}),b=$p(v=>{if(v.is0()){if(e.allowInfinityPoint&&!r.is0(v.py))return;throw new Error("bad point: ZERO")}const{x:w,y:x}=v.toAffine();if(!r.isValid(w)||!r.isValid(x))throw new Error("bad point: x or y not FE");if(!o(w,x))throw new Error("bad point: equation left != right");if(!v.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class g{constructor(w,x,_){if(w==null||!r.isValid(w))throw new Error("x required");if(x==null||!r.isValid(x)||r.is0(x))throw new Error("y required");if(_==null||!r.isValid(_))throw new Error("z required");this.px=w,this.py=x,this.pz=_,Object.freeze(this)}static fromAffine(w){const{x,y:_}=w||{};if(!w||!r.isValid(x)||!r.isValid(_))throw new Error("invalid affine point");if(w instanceof g)throw new Error("projective point not allowed");const I=N=>r.eql(N,r.ZERO);return I(x)&&I(_)?g.ZERO:new g(x,_,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(w){const x=iw(r,w.map(_=>_.pz));return w.map((_,I)=>_.toAffine(x[I])).map(g.fromAffine)}static fromHex(w){const x=g.fromAffine(i(hr("pointHex",w)));return x.assertValidity(),x}static fromPrivateKey(w){return g.BASE.multiply(f(w))}static msm(w,x){return ek(g,n,w,x)}_setWindowSize(w){T.setWindowSize(this,w)}assertValidity(){b(this)}hasEvenY(){const{y:w}=this.toAffine();if(r.isOdd)return!r.isOdd(w);throw new Error("Field doesn't support isOdd")}equals(w){p(w);const{px:x,py:_,pz:I}=this,{px:N,py:C,pz:j}=w,M=r.eql(r.mul(x,j),r.mul(N,I)),H=r.eql(r.mul(_,j),r.mul(C,I));return M&&H}negate(){return new g(this.px,r.neg(this.py),this.pz)}double(){const{a:w,b:x}=e,_=r.mul(x,Al),{px:I,py:N,pz:C}=this;let j=r.ZERO,M=r.ZERO,H=r.ZERO,V=r.mul(I,I),Q=r.mul(N,N),U=r.mul(C,C),K=r.mul(I,N);return K=r.add(K,K),H=r.mul(I,C),H=r.add(H,H),j=r.mul(w,H),M=r.mul(_,U),M=r.add(j,M),j=r.sub(Q,M),M=r.add(Q,M),M=r.mul(j,M),j=r.mul(K,j),H=r.mul(_,H),U=r.mul(w,U),K=r.sub(V,U),K=r.mul(w,K),K=r.add(K,H),H=r.add(V,V),V=r.add(H,V),V=r.add(V,U),V=r.mul(V,K),M=r.add(M,V),U=r.mul(N,C),U=r.add(U,U),V=r.mul(U,K),j=r.sub(j,V),H=r.mul(U,Q),H=r.add(H,H),H=r.add(H,H),new g(j,M,H)}add(w){p(w);const{px:x,py:_,pz:I}=this,{px:N,py:C,pz:j}=w;let M=r.ZERO,H=r.ZERO,V=r.ZERO;const Q=e.a,U=r.mul(e.b,Al);let K=r.mul(x,N),ee=r.mul(_,C),q=r.mul(I,j),O=r.add(x,_),L=r.add(N,C);O=r.mul(O,L),L=r.add(K,ee),O=r.sub(O,L),L=r.add(x,I);let J=r.add(N,j);return L=r.mul(L,J),J=r.add(K,q),L=r.sub(L,J),J=r.add(_,I),M=r.add(C,j),J=r.mul(J,M),M=r.add(ee,q),J=r.sub(J,M),V=r.mul(Q,L),M=r.mul(U,q),V=r.add(M,V),M=r.sub(ee,V),V=r.add(ee,V),H=r.mul(M,V),ee=r.add(K,K),ee=r.add(ee,K),q=r.mul(Q,q),L=r.mul(U,L),ee=r.add(ee,q),q=r.sub(K,q),q=r.mul(Q,q),L=r.add(L,q),K=r.mul(ee,L),H=r.add(H,K),K=r.mul(J,L),M=r.mul(O,M),M=r.sub(M,K),K=r.mul(O,ee),V=r.mul(J,V),V=r.add(V,K),new g(M,H,V)}subtract(w){return this.add(w.negate())}is0(){return this.equals(g.ZERO)}wNAF(w){return T.wNAFCached(this,w,g.normalizeZ)}multiplyUnsafe(w){const{endo:x,n:_}=e;Ui("scalar",w,Tn,_);const I=g.ZERO;if(w===Tn)return I;if(this.is0()||w===lt)return this;if(!x||T.hasPrecomputes(this))return T.wNAFCachedUnsafe(this,w,g.normalizeZ);let{k1neg:N,k1:C,k2neg:j,k2:M}=x.splitScalar(w),H=I,V=I,Q=this;for(;C>Tn||M>Tn;)C&lt&&(H=H.add(Q)),M&lt&&(V=V.add(Q)),Q=Q.double(),C>>=lt,M>>=lt;return N&&(H=H.negate()),j&&(V=V.negate()),V=new g(r.mul(V.px,x.beta),V.py,V.pz),H.add(V)}multiply(w){const{endo:x,n:_}=e;Ui("scalar",w,lt,_);let I,N;if(x){const{k1neg:C,k1:j,k2neg:M,k2:H}=x.splitScalar(w);let{p:V,f:Q}=this.wNAF(j),{p:U,f:K}=this.wNAF(H);V=T.constTimeNegate(C,V),U=T.constTimeNegate(M,U),U=new g(r.mul(U.px,x.beta),U.py,U.pz),I=V.add(U),N=Q.add(K)}else{const{p:C,f:j}=this.wNAF(w);I=C,N=j}return g.normalizeZ([I,N])[0]}multiplyAndAddUnsafe(w,x,_){const I=g.BASE,N=(j,M)=>M===Tn||M===lt||!j.equals(I)?j.multiplyUnsafe(M):j.multiply(M),C=N(this,x).add(N(w,_));return C.is0()?void 0:C}toAffine(w){return d(this,w)}isTorsionFree(){const{h:w,isTorsionFree:x}=e;if(w===lt)return!0;if(x)return x(g,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:w,clearCofactor:x}=e;return w===lt?this:x?x(g,this):this.multiplyUnsafe(e.h)}toRawBytes(w=!0){return ao("isCompressed",w),this.assertValidity(),s(g,this,w)}toHex(w=!0){return ao("isCompressed",w),oo(this.toRawBytes(w))}}g.BASE=new g(e.Gx,e.Gy,r.ONE),g.ZERO=new g(r.ZERO,r.ONE,r.ZERO);const{endo:A,nBitLength:S}=e,T=Q3(g,A?Math.ceil(S/2):S);return{CURVE:e,ProjectivePoint:g,normPrivateKeyToScalar:f,weierstrassEquation:a,isWithinCurveOrder:l}}function ik(t){const e=fw(t);return gu(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function ak(t){const e=ik(t),{Fp:r,n,nByteLength:s,nBitLength:i}=e,a=r.BYTES+1,o=2*r.BYTES+1;function c(U){return Ht(U,n)}function u(U){return _d(U,n)}const{ProjectivePoint:l,normPrivateKeyToScalar:f,weierstrassEquation:p,isWithinCurveOrder:d}=sk({...e,toBytes(U,K,ee){const q=K.toAffine(),O=r.toBytes(q.x),L=Uc;return ao("isCompressed",ee),ee?L(Uint8Array.from([K.hasEvenY()?2:3]),O):L(Uint8Array.from([4]),O,r.toBytes(q.y))},fromBytes(U){const K=U.length,ee=U[0],q=U.subarray(1);if(K===a&&(ee===2||ee===3)){const O=zs(q);if(!Vh(O,lt,r.ORDER))throw new Error("Point is not on curve");const L=p(O);let J;try{J=r.sqrt(L)}catch(z){const ne=z instanceof Error?": "+z.message:"";throw new Error("Point is not on curve"+ne)}const B=(J&lt)===lt;return(ee&1)===1!==B&&(J=r.neg(J)),{x:O,y:J}}else if(K===o&&ee===4){const O=r.fromBytes(q.subarray(0,r.BYTES)),L=r.fromBytes(q.subarray(r.BYTES,2*r.BYTES));return{x:O,y:L}}else{const O=a,L=o;throw new Error("invalid Point, expected length of "+O+", or uncompressed "+L+", got "+K)}}});function b(U){const K=n>>lt;return U>K}function g(U){return b(U)?c(-U):U}const A=(U,K,ee)=>zs(U.slice(K,ee));class S{constructor(K,ee,q){Ui("r",K,lt,n),Ui("s",ee,lt,n),this.r=K,this.s=ee,q!=null&&(this.recovery=q),Object.freeze(this)}static fromCompact(K){const ee=s;return K=hr("compactSignature",K,ee*2),new S(A(K,0,ee),A(K,ee,2*ee))}static fromDER(K){const{r:ee,s:q}=An.toSig(hr("DER",K));return new S(ee,q)}assertValidity(){}addRecoveryBit(K){return new S(this.r,this.s,K)}recoverPublicKey(K){const{r:ee,s:q,recovery:O}=this,L=I(hr("msgHash",K));if(O==null||![0,1,2,3].includes(O))throw new Error("recovery id invalid");const J=O===2||O===3?ee+e.n:ee;if(J>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const B=O&1?"03":"02",F=l.fromHex(B+El(J,r.BYTES)),z=u(J),ne=c(-L*z),ae=c(q*z),fe=l.BASE.multiplyAndAddUnsafe(F,ne,ae);if(!fe)throw new Error("point at infinify");return fe.assertValidity(),fe}hasHighS(){return b(this.s)}normalizeS(){return this.hasHighS()?new S(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return Nc(this.toDERHex())}toDERHex(){return An.hexFromSig(this)}toCompactRawBytes(){return Nc(this.toCompactHex())}toCompactHex(){const K=s;return El(this.r,K)+El(this.s,K)}}const T={isValidPrivateKey(U){try{return f(U),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{const U=cw(e.n);return Y3(e.randomBytes(U),e.n)},precompute(U=8,K=l.BASE){return K._setWindowSize(U),K.multiply(BigInt(3)),K}};function v(U,K=!0){return l.fromPrivateKey(U).toRawBytes(K)}function w(U){if(typeof U=="bigint")return!1;if(U instanceof l)return!0;const ee=hr("key",U).length,q=r.BYTES,O=q+1,L=2*q+1;if(!(e.allowedPrivateKeyLengths||s===O))return ee===O||ee===L}function x(U,K,ee=!0){if(w(U)===!0)throw new Error("first arg must be private key");if(w(K)===!1)throw new Error("second arg must be public key");return l.fromHex(K).multiply(f(U)).toRawBytes(ee)}const _=e.bits2int||function(U){if(U.length>8192)throw new Error("input is too large");const K=zs(U),ee=U.length*8-i;return ee>0?K>>BigInt(ee):K},I=e.bits2int_modN||function(U){return c(_(U))},N=bu(i);function C(U){return Ui("num < 2^"+i,U,Tn,N),No(U,s)}function j(U,K,ee=M){if(["recovered","canonical"].some(ie=>ie in ee))throw new Error("sign() legacy options not supported");const{hash:q,randomBytes:O}=e;let{lowS:L,prehash:J,extraEntropy:B}=ee;L==null&&(L=!0),U=hr("msgHash",U),ry(ee),J&&(U=hr("prehashed msgHash",q(U)));const F=I(U),z=f(K),ne=[C(z),C(F)];if(B!=null&&B!==!1){const ie=B===!0?O(r.BYTES):B;ne.push(hr("extraEntropy",ie))}const ae=Uc(...ne),fe=F;function ue(ie){const se=_(ie);if(!d(se))return;const be=u(se),ge=l.BASE.multiply(se).toAffine(),Ee=c(ge.x);if(Ee===Tn)return;const Te=c(be*c(fe+Ee*z));if(Te===Tn)return;let nt=(ge.x===Ee?0:2)|Number(ge.y&lt),Ce=Te;return L&&b(Te)&&(Ce=g(Te),nt^=1),new S(Ee,Ce,nt)}return{seed:ae,k2sig:ue}}const M={lowS:e.lowS,prehash:!1},H={lowS:e.lowS,prehash:!1};function V(U,K,ee=M){const{seed:q,k2sig:O}=j(U,K,ee),L=e;return l8(L.hash.outputLen,L.nByteLength,L.hmac)(q,O)}l.BASE._setWindowSize(8);function Q(U,K,ee,q=H){var nt;const O=U;K=hr("msgHash",K),ee=hr("publicKey",ee);const{lowS:L,prehash:J,format:B}=q;if(ry(q),"strict"in q)throw new Error("options.strict was renamed to lowS");if(B!==void 0&&B!=="compact"&&B!=="der")throw new Error("format must be compact or der");const F=typeof O=="string"||Ro(O),z=!F&&!B&&typeof O=="object"&&O!==null&&typeof O.r=="bigint"&&typeof O.s=="bigint";if(!F&&!z)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let ne,ae;try{if(z&&(ne=new S(O.r,O.s)),F){try{B!=="compact"&&(ne=S.fromDER(O))}catch(Ce){if(!(Ce instanceof An.Err))throw Ce}!ne&&B!=="der"&&(ne=S.fromCompact(O))}ae=l.fromHex(ee)}catch{return!1}if(!ne||L&&ne.hasHighS())return!1;J&&(K=e.hash(K));const{r:fe,s:ue}=ne,ie=I(K),se=u(ue),be=c(ie*se),ge=c(fe*se),Ee=(nt=l.BASE.multiplyAndAddUnsafe(ae,be,ge))==null?void 0:nt.toAffine();return Ee?c(Ee.x)===fe:!1}return{CURVE:e,getPublicKey:v,getSharedSecret:x,sign:V,verify:Q,ProjectivePoint:l,Signature:S,utils:T}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ok(t){return{hash:t,hmac:(e,...r)=>ew(t,e,IA(...r)),randomBytes:OA}}function ck(t,e){const r=n=>ak({...t,...ok(n)});return{...r(e),create:r}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const dw=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),ny=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),uk=BigInt(0),lk=BigInt(1),Pd=BigInt(2),sy=(t,e)=>(t+e/Pd)/e;function fk(t){const e=dw,r=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),a=BigInt(23),o=BigInt(44),c=BigInt(88),u=t*t*t%e,l=u*u*t%e,f=fr(l,r,e)*l%e,p=fr(f,r,e)*l%e,d=fr(p,Pd,e)*u%e,b=fr(d,s,e)*d%e,g=fr(b,i,e)*b%e,A=fr(g,o,e)*g%e,S=fr(A,c,e)*A%e,T=fr(S,o,e)*g%e,v=fr(T,r,e)*l%e,w=fr(v,a,e)*b%e,x=fr(w,n,e)*u%e,_=fr(x,Pd,e);if(!Od.eql(Od.sqr(_),t))throw new Error("Cannot find square root");return _}const Od=c0(dw,void 0,void 0,{sqrt:fk}),hw=ck({a:uk,b:BigInt(7),Fp:Od,n:ny,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=ny,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-lk*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,a=BigInt("0x100000000000000000000000000000000"),o=sy(i*t,e),c=sy(-n*t,e);let u=Ht(t-o*r-c*s,e),l=Ht(-o*n-c*i,e);const f=u>a,p=l>a;if(f&&(u=e-u),p&&(l=e-l),u>a||l>a)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:f,k1:u,k2neg:p,k2:l}}}},zg),dk=Object.freeze(Object.defineProperty({__proto__:null,secp256k1:hw},Symbol.toStringTag,{value:"Module"}));function pw(t,e={}){const{recovered:r}=e;if(typeof t.r>"u")throw new Sl({signature:t});if(typeof t.s>"u")throw new Sl({signature:t});if(r&&typeof t.yParity>"u")throw new Sl({signature:t});if(t.r<0n||t.r>Yp)throw new wk({value:t.r});if(t.s<0n||t.s>Yp)throw new vk({value:t.s});if(typeof t.yParity=="number"&&t.yParity!==0&&t.yParity!==1)throw new l0({value:t.yParity})}function hk(t){return yw(Fr(t))}function yw(t){if(t.length!==130&&t.length!==132)throw new gk({signature:t});const e=BigInt(rn(t,0,32)),r=BigInt(rn(t,32,64)),n=(()=>{const s=+`0x${t.slice(130)}`;if(!Number.isNaN(s))try{return u0(s)}catch{throw new l0({value:s})}})();return typeof n>"u"?{r:e,s:r}:{r:e,s:r,yParity:n}}function pk(t){if(!(typeof t.r>"u")&&!(typeof t.s>"u"))return yk(t)}function yk(t){const e=typeof t=="string"?yw(t):t instanceof Uint8Array?hk(t):typeof t.r=="string"?bk(t):t.v?mk(t):{r:t.r,s:t.s,...typeof t.yParity<"u"?{yParity:t.yParity}:{}};return pw(e),e}function mk(t){return{r:t.r,s:t.s,yParity:u0(t.v)}}function bk(t){const e=(()=>{const r=t.v?Number(t.v):void 0;let n=t.yParity?Number(t.yParity):void 0;if(typeof r=="number"&&typeof n!="number"&&(n=u0(r)),typeof n!="number")throw new l0({value:t.yParity});return n})();return{r:BigInt(t.r),s:BigInt(t.s),yParity:e}}function u0(t){if(t===0||t===27)return 0;if(t===1||t===28)return 1;if(t>=35)return t%2===0?1:0;throw new Ek({value:t})}class gk extends le{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${ir(U8(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class Sl extends le{constructor({signature:e}){super(`Signature \`${i1(e)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}}class wk extends le{constructor({value:e}){super(`Value \`${e}\` is an invalid r value. r must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}}class vk extends le{constructor({value:e}){super(`Value \`${e}\` is an invalid s value. s must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}}class l0 extends le{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class Ek extends le{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}function Ak(t,e={}){return typeof t.chainId=="string"?Sk(t):{...t,...e.signature}}function Sk(t){const{address:e,chainId:r,nonce:n}=t,s=pk(t);return{address:e,chainId:Number(r),nonce:BigInt(n),...s}}const xk="0x8010801080108010801080108010801080108010801080108010801080108010",kk=Y1("(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data");function mw(t){if(typeof t=="string"){if(rn(t,-32)!==xk)throw new Ik(t)}else pw(t.authorization)}function Tk(t){mw(t);const e=l1(rn(t,-64,-32)),r=rn(t,-e-64,-64),n=rn(t,0,-e-64),[s,i,a]=$3(kk,r);return{authorization:Ak({address:s.delegation,chainId:Number(s.chainId),nonce:s.nonce,yParity:s.yParity,r:s.r,s:s.s}),signature:n,...a&&a!=="0x"?{data:a,to:i}:{}}}function _k(t){try{return mw(t),!0}catch{return!1}}let Ik=class extends le{constructor(e){super(`Value \`${e}\` is an invalid ERC-8010 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc8010.InvalidWrappedSignatureError"})}};function Pk(t){return t.map(e=>({...e,value:BigInt(e.value)}))}function Ok(t){return{...t,balance:t.balance?BigInt(t.balance):void 0,nonce:t.nonce?gr(t.nonce):void 0,storageProof:t.storageProof?Pk(t.storageProof):void 0}}async function Bk(t,{address:e,blockNumber:r,blockTag:n,storageKeys:s}){const i=n??"latest",a=r!==void 0?Y(r):void 0,o=await t.request({method:"eth_getProof",params:[e,s,a||i]});return Ok(o)}async function Ck(t,{address:e,blockNumber:r,blockTag:n="latest",slot:s}){const i=r!==void 0?Y(r):void 0;return await t.request({method:"eth_getStorageAt",params:[e,s,i||n]})}async function f0(t,{blockHash:e,blockNumber:r,blockTag:n,hash:s,index:i,sender:a,nonce:o}){var p,d,b;const c=n||"latest",u=r!==void 0?Y(r):void 0;let l=null;if(s?l=await t.request({method:"eth_getTransactionByHash",params:[s]},{dedupe:!0}):e?l=await t.request({method:"eth_getTransactionByBlockHashAndIndex",params:[e,Y(i)]},{dedupe:!0}):typeof i=="number"?l=await t.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[u||c,Y(i)]},{dedupe:!!u}):a&&typeof o=="number"&&(l=await t.request({method:"eth_getTransactionBySenderAndNonce",params:[a,Y(o)]},{dedupe:!0})),!l)throw new Bg({blockHash:e,blockNumber:r,blockTag:c,hash:s,index:i});return(((b=(d=(p=t.chain)==null?void 0:p.formatters)==null?void 0:d.transaction)==null?void 0:b.format)||Bo)(l,"getTransaction")}async function Rk(t,{hash:e,transactionReceipt:r}){const[n,s]=await Promise.all([re(t,Mo,"getBlockNumber")({}),e?re(t,f0,"getTransaction")({hash:e}):void 0]),i=(r==null?void 0:r.blockNumber)||(s==null?void 0:s.blockNumber);return i?n-i+1n:0n}async function Sc(t,{hash:e}){var s,i,a;const r=await t.request({method:"eth_getTransactionReceipt",params:[e]},{dedupe:!0});if(!r)throw new Cg({hash:e});return(((a=(i=(s=t.chain)==null?void 0:s.formatters)==null?void 0:i.transactionReceipt)==null?void 0:a.format)||Jh)(r,"getTransactionReceipt")}async function Nk(t,e){var T;const{account:r,authorizationList:n,allowFailure:s=!0,blockNumber:i,blockOverrides:a,blockTag:o,stateOverride:c}=e,u=e.contracts,{batchSize:l=e.batchSize??1024,deployless:f=e.deployless??!1}=typeof((T=t.batch)==null?void 0:T.multicall)=="object"?t.batch.multicall:{},p=(()=>{if(e.multicallAddress)return e.multicallAddress;if(f)return null;if(t.chain)return ra({blockNumber:i,chain:t.chain,contract:"multicall3"});throw new Error("client chain not configured. multicallAddress is required.")})(),d=[[]];let b=0,g=0;for(let v=0;v<u.length;v++){const{abi:w,address:x,args:_,functionName:I}=u[v];try{const N=or({abi:w,args:_,functionName:I});g+=(N.length-2)/2,l>0&&g>l&&d[b].length>0&&(b++,g=(N.length-2)/2,d[b]=[]),d[b]=[...d[b],{allowFailure:!0,callData:N,target:x}]}catch(N){const C=Js(N,{abi:w,address:x,args:_,docsPath:"/docs/contract/multicall",functionName:I,sender:r});if(!s)throw C;d[b]=[...d[b],{allowFailure:!0,callData:"0x",target:x}]}}const A=await Promise.allSettled(d.map(v=>re(t,wr,"readContract")({...p===null?{code:qh}:{address:p},abi:Fc,account:r,args:[v],authorizationList:n,blockNumber:i,blockOverrides:a,blockTag:o,functionName:"aggregate3",stateOverride:c}))),S=[];for(let v=0;v<A.length;v++){const w=A[v];if(w.status==="rejected"){if(!s)throw w.reason;for(let _=0;_<d[v].length;_++)S.push({status:"failure",error:w.reason,result:void 0});continue}const x=w.value;for(let _=0;_<x.length;_++){const{returnData:I,success:N}=x[_],{callData:C}=d[v][_],{abi:j,address:M,functionName:H,args:V}=u[S.length];try{if(C==="0x")throw new xo;if(!N)throw new du({data:I});const Q=ui({abi:j,args:V,data:I,functionName:H});S.push(s?{result:Q,status:"success"}:Q)}catch(Q){const U=Js(Q,{abi:j,address:M,args:V,docsPath:"/docs/contract/multicall",functionName:H});if(!s)throw U;S.push({error:U,result:void 0,status:"failure"})}}}if(S.length!==u.length)throw new G("multicall results mismatch");return S}async function Bd(t,e){const{blockNumber:r,blockTag:n=t.experimental_blockTag??"latest",blocks:s,returnFullTransactions:i,traceTransfers:a,validation:o}=e;try{const c=[];for(const p of s){const d=p.blockOverrides?h1(p.blockOverrides):void 0,b=p.calls.map(A=>{const S=A,T=S.account?Le(S.account):void 0,v=S.abi?or(S):S.data,w={...S,account:T,data:S.dataSuffix?sr([v||"0x",S.dataSuffix]):v,from:S.from??(T==null?void 0:T.address)};return jn(w),As(w)}),g=p.stateOverrides?Ih(p.stateOverrides):void 0;c.push({blockOverrides:d,calls:b,stateOverrides:g})}const l=(typeof r=="bigint"?Y(r):void 0)||n;return(await t.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:i,traceTransfers:a,validation:o},l]})).map((p,d)=>({...Oh(p),calls:p.calls.map((b,g)=>{var j,M;const{abi:A,args:S,functionName:T,to:v}=s[d].calls[g],w=((j=b.error)==null?void 0:j.data)??b.returnData,x=BigInt(b.gasUsed),_=(M=b.logs)==null?void 0:M.map(H=>Un(H)),I=b.status==="0x1"?"success":"failure",N=A&&I==="success"&&w!=="0x"?ui({abi:A,data:w,functionName:T}):null,C=(()=>{var V;if(I==="success")return;let H;if(((V=b.error)==null?void 0:V.data)==="0x"?H=new xo:b.error&&(H=new du(b.error)),!!H)return Js(H,{abi:A??[],address:v??"0x",args:S,functionName:T??"<unknown>"})})();return{data:w,gasUsed:x,logs:_,status:I,...I==="success"?{result:N}:{error:C}}})}))}catch(c){const u=c,l=pu(u,{});throw l instanceof Oo?u:l}}function Cd(t){let e=!0,r="",n=0,s="",i=!1;for(let a=0;a<t.length;a++){const o=t[a];if(["(",")",","].includes(o)&&(e=!0),o==="("&&n++,o===")"&&n--,!!e){if(n===0){if(o===" "&&["event","function","error",""].includes(s))s="";else if(s+=o,o===")"){i=!0;break}continue}if(o===" "){t[a-1]!==","&&r!==","&&r!==",("&&(r="",e=!1);continue}s+=o,r+=o}}if(!i)throw new le("Unable to normalize signature.");return s}function Rd(t,e){const r=typeof t,n=e.type;switch(n){case"address":return xd(t,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in e?Object.values(e.components).every((s,i)=>Rd(Object.values(t)[i],s)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?r==="number"||r==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?r==="string"||t instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(t)&&t.every(s=>Rd(s,{...e,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function bw(t,e,r){for(const n in t){const s=t[n],i=e[n];if(s.type==="tuple"&&i.type==="tuple"&&"components"in s&&"components"in i)return bw(s.components,i.components,r[n]);const a=[s.type,i.type];if(a.includes("address")&&a.includes("bytes20")?!0:a.includes("address")&&a.includes("string")?xd(r[n],{strict:!1}):a.includes("address")&&a.includes("bytes")?xd(r[n],{strict:!1}):!1)return a}}function gw(t,e={}){const{prepare:r=!0}=e,n=Array.isArray(t)||typeof t=="string"?hp(t):t;return{...n,...r?{hash:_i(n)}:{}}}function _u(t,e,r){const{args:n=[],prepare:s=!0}=r??{},i=F8(e,{strict:!1}),a=t.filter(u=>i?u.type==="function"||u.type==="error"?ww(u)===rn(e,0,4):u.type==="event"?_i(u)===e:!1:"name"in u&&u.name===e);if(a.length===0)throw new $c({name:e});if(a.length===1)return{...a[0],...s?{hash:_i(a[0])}:{}};let o;for(const u of a){if(!("inputs"in u))continue;if(!n||n.length===0){if(!u.inputs||u.inputs.length===0)return{...u,...s?{hash:_i(u)}:{}};continue}if(!u.inputs||u.inputs.length===0||u.inputs.length!==n.length)continue;if(n.every((f,p)=>{const d="inputs"in u&&u.inputs[p];return d?Rd(f,d):!1})){if(o&&"inputs"in o&&o.inputs){const f=bw(u.inputs,o.inputs,n);if(f)throw new Fk({abiItem:u,type:f[0]},{abiItem:o,type:f[1]})}o=u}}const c=(()=>{if(o)return o;const[u,...l]=a;return{...u,overloads:l}})();if(!c)throw new $c({name:e});return{...c,...s?{hash:_i(c)}:{}}}function ww(...t){const e=(()=>{if(Array.isArray(t[0])){const[r,n]=t;return _u(r,n)}return t[0]})();return rn(_i(e),0,4)}function Uk(...t){const e=(()=>{if(Array.isArray(t[0])){const[n,s]=t;return _u(n,s)}return t[0]})(),r=typeof e=="string"?e:Bc(e);return Cd(r)}function _i(...t){const e=(()=>{if(Array.isArray(t[0])){const[r,n]=t;return _u(r,n)}return t[0]})();return typeof e!="string"&&"hash"in e&&e.hash?e.hash:W1(Gh(Uk(e)))}class Fk extends le{constructor(e,r){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${e.type}\` in \`${Cd(Bc(e.abiItem))}\`, and`,`\`${r.type}\` in \`${Cd(Bc(r.abiItem))}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.AmbiguityError"})}}class $c extends le{constructor({name:e,data:r,type:n="item"}){const s=e?` with name "${e}"`:r?` with data "${r}"`:"";super(`ABI ${n}${s} not found.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}function Mk(...t){var i;const[e,r]=(()=>{if(Array.isArray(t[0])){const[a,o]=t;return[jk(a),o]}return t})(),{bytecode:n,args:s}=r;return Ur(n,(i=e.inputs)!=null&&i.length&&(s!=null&&s.length)?a0(e.inputs,s):"0x")}function $k(t){return gw(t)}function jk(t){const e=t.find(r=>r.type==="constructor");if(!e)throw new $c({name:"constructor"});return e}function Hk(...t){const[e,r=[]]=(()=>{if(Array.isArray(t[0])){const[u,l,f]=t;return[iy(u,l,{args:f}),f]}const[o,c]=t;return[o,c]})(),{overloads:n}=e,s=n?iy([e,...n],e.name,{args:r}):e,i=Lk(s),a=r.length>0?a0(s.inputs,r):void 0;return a?Ur(i,a):i}function mi(t,e={}){return gw(t,e)}function iy(t,e,r){const n=_u(t,e,r);if(n.type!=="function")throw new $c({name:e,type:"function"});return n}function Lk(t){return ww(t)}const Dk="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Wr="0x0000000000000000000000000000000000000000",zk="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033";async function Vk(t,e){const{blockNumber:r,blockTag:n,calls:s,stateOverrides:i,traceAssetChanges:a,traceTransfers:o,validation:c}=e,u=e.account?Le(e.account):void 0;if(a&&!u)throw new G("`account` is required when `traceAssetChanges` is true");const l=u?Mk($k("constructor(bytes, bytes)"),{bytecode:b1,args:[zk,Hk(mi("function getBalance(address)"),[u.address])]}):void 0,f=a?await Promise.all(e.calls.map(async q=>{if(!q.data&&!q.abi)return;const{accessList:O}=await M1(t,{account:u.address,...q,data:q.abi?or(q):q.data});return O.map(({address:L,storageKeys:J})=>J.length>0?L:null)})).then(q=>q.flat().filter(Boolean)):[],p=await Bd(t,{blockNumber:r,blockTag:n,blocks:[...a?[{calls:[{data:l}],stateOverrides:i},{calls:f.map((q,O)=>({abi:[mi("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[u.address],to:q,from:Wr,nonce:O})),stateOverrides:[{address:Wr,nonce:0}]}]:[],{calls:[...s,{}].map(q=>({...q,from:u==null?void 0:u.address})),stateOverrides:i},...a?[{calls:[{data:l}]},{calls:f.map((q,O)=>({abi:[mi("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[u.address],to:q,from:Wr,nonce:O})),stateOverrides:[{address:Wr,nonce:0}]},{calls:f.map((q,O)=>({to:q,abi:[mi("function decimals() returns (uint256)")],functionName:"decimals",from:Wr,nonce:O})),stateOverrides:[{address:Wr,nonce:0}]},{calls:f.map((q,O)=>({to:q,abi:[mi("function tokenURI(uint256) returns (string)")],functionName:"tokenURI",args:[0n],from:Wr,nonce:O})),stateOverrides:[{address:Wr,nonce:0}]},{calls:f.map((q,O)=>({to:q,abi:[mi("function symbol() returns (string)")],functionName:"symbol",from:Wr,nonce:O})),stateOverrides:[{address:Wr,nonce:0}]}]:[]],traceTransfers:o,validation:c}),d=a?p[2]:p[0],[b,g,,A,S,T,v,w]=a?p:[],{calls:x,..._}=d,I=x.slice(0,-1)??[],N=(b==null?void 0:b.calls)??[],C=(g==null?void 0:g.calls)??[],j=[...N,...C].map(q=>q.status==="success"?ft(q.data):null),M=(A==null?void 0:A.calls)??[],H=(S==null?void 0:S.calls)??[],V=[...M,...H].map(q=>q.status==="success"?ft(q.data):null),Q=((T==null?void 0:T.calls)??[]).map(q=>q.status==="success"?q.result:null),U=((w==null?void 0:w.calls)??[]).map(q=>q.status==="success"?q.result:null),K=((v==null?void 0:v.calls)??[]).map(q=>q.status==="success"?q.result:null),ee=[];for(const[q,O]of V.entries()){const L=j[q];if(typeof O!="bigint"||typeof L!="bigint")continue;const J=Q[q-1],B=U[q-1],F=K[q-1],z=q===0?{address:Dk,decimals:18,symbol:"ETH"}:{address:f[q-1],decimals:F||J?Number(J??1):void 0,symbol:B??void 0};ee.some(ne=>ne.token.address===z.address)||ee.push({token:z,value:{pre:L,post:O,diff:O-L}})}return{assetChanges:ee,block:_,results:I}}const vw="0x6492649264926492649264926492649264926492649264926492649264926492";function Gk(t){if(rn(t,-32)!==vw)throw new Kk(t)}function qk(t){const{data:e,signature:r,to:n}=t;return Ur(a0(Y1("address, bytes, bytes"),[n,e,r]),vw)}function Wk(t){try{return Gk(t),!0}catch{return!1}}class Kk extends le{constructor(e){super(`Value \`${e}\` is an invalid ERC-6492 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc6492.InvalidWrappedSignatureError"})}}function Xk({r:t,s:e,to:r="hex",v:n,yParity:s}){const i=(()=>{if(s===0||s===1)return s;if(n&&(n===27n||n===28n||n>=35n))return n%2n===0n?1:0;throw new Error("Invalid `v` or `yParity` value")})(),a=`0x${new hw.Signature(ft(t),ft(e)).toCompactHex()}${i===0?"1b":"1c"}`;return r==="hex"?a:an(a)}async function Iu(t,e){var c,u,l,f;const{address:r,chain:n=t.chain,hash:s,erc6492VerifierAddress:i=e.universalSignatureVerifierAddress??((u=(c=n==null?void 0:n.contracts)==null?void 0:c.erc6492Verifier)==null?void 0:u.address),multicallAddress:a=e.multicallAddress??((f=(l=n==null?void 0:n.contracts)==null?void 0:l.multicall3)==null?void 0:f.address)}=e;if(n!=null&&n.verifyHash)return await n.verifyHash(t,e);const o=(()=>{const p=e.signature;return Nr(p)?p:typeof p=="object"&&"r"in p&&"s"in p?Xk(p):tt(p)})();try{return _k(o)?await Yk(t,{...e,multicallAddress:a,signature:o}):await Jk(t,{...e,verifierAddress:i,signature:o})}catch(p){try{if(ta(wh(r),await Fg({hash:s,signature:o})))return!0}catch{}if(p instanceof ti)return!1;throw p}}async function Yk(t,e){var A;const{address:r,blockNumber:n,blockTag:s,hash:i,multicallAddress:a}=e,{authorization:o,data:c,signature:u,to:l}=Tk(e.signature);if(await Sd(t,{address:r,blockNumber:n,blockTag:s})===jr(["0xef0100",o.address]))return await Zk(t,{address:r,blockNumber:n,blockTag:s,hash:i,signature:u});const p={address:o.address,chainId:Number(o.chainId),nonce:Number(o.nonce),r:Y(o.r,{size:32}),s:Y(o.s,{size:32}),yParity:o.yParity};if(!await Wx({address:r,authorization:p}))throw new ti;const b=await re(t,wr,"readContract")({...a?{address:a}:{code:qh},authorizationList:[p],abi:Fc,blockNumber:n,blockTag:"pending",functionName:"aggregate3",args:[[...c?[{allowFailure:!0,target:l??r,callData:c}]:[],{allowFailure:!0,target:r,callData:or({abi:m1,functionName:"isValidSignature",args:[i,u]})}]]}),g=(A=b[b.length-1])==null?void 0:A.returnData;if(g!=null&&g.startsWith("0x1626ba7e"))return!0;throw new ti}async function Jk(t,e){const{address:r,factory:n,factoryData:s,hash:i,signature:a,verifierAddress:o,...c}=e,u=await(async()=>!n&&!s||Wk(a)?a:qk({data:s,signature:a,to:n}))(),l=o?{to:o,data:or({abi:Vp,functionName:"isValidSig",args:[r,i,u]}),...c}:{data:Eu({abi:Vp,args:[r,i,u],bytecode:z8}),...c},{data:f}=await re(t,Fo,"call")(l).catch(p=>{throw p instanceof Ng?new ti:p});if(uA(f??"0x0"))return!0;throw new ti}async function Zk(t,e){const{address:r,blockNumber:n,blockTag:s,hash:i,signature:a}=e;if((await re(t,wr,"readContract")({address:r,abi:m1,args:[i,a],blockNumber:n,blockTag:s,functionName:"isValidSignature"}).catch(c=>{throw c instanceof Ug?new ti:c})).startsWith("0x1626ba7e"))return!0;throw new ti}class ti extends Error{}async function Qk(t,{address:e,message:r,factory:n,factoryData:s,signature:i,...a}){const o=H1(r);return re(t,Iu,"verifyHash")({address:e,factory:n,factoryData:s,hash:o,signature:i,...a})}async function eT(t,e){const{address:r,factory:n,factoryData:s,signature:i,message:a,primaryType:o,types:c,domain:u,...l}=e,f=c3({message:a,primaryType:o,types:c,domain:u});return re(t,Iu,"verifyHash")({address:r,factory:n,factoryData:s,hash:f,signature:i,...l})}function Ew(t,{emitOnBegin:e=!1,emitMissed:r=!1,onBlockNumber:n,onError:s,poll:i,pollingInterval:a=t.pollingInterval}){const o=typeof i<"u"?i:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc"));let c;return o?(()=>{const f=et(["watchBlockNumber",t.uid,e,r,a]);return Fn(f,{onBlockNumber:n,onError:s},p=>na(async()=>{var d;try{const b=await re(t,Mo,"getBlockNumber")({cacheTime:0});if(c!==void 0){if(b===c)return;if(b-c>1&&r)for(let g=c+1n;g<b;g++)p.onBlockNumber(g,c),c=g}(c===void 0||b>c)&&(p.onBlockNumber(b,c),c=b)}catch(b){(d=p.onError)==null||d.call(p,b)}},{emitOnBegin:e,interval:a}))})():(()=>{const f=et(["watchBlockNumber",t.uid,e,r]);return Fn(f,{onBlockNumber:n,onError:s},p=>{let d=!0,b=()=>d=!1;return(async()=>{try{const g=(()=>{if(t.transport.type==="fallback"){const S=t.transport.transports.find(T=>T.config.type==="webSocket"||T.config.type==="ipc");return S?S.value:t.transport}return t.transport})(),{unsubscribe:A}=await g.subscribe({params:["newHeads"],onData(S){var v;if(!d)return;const T=ft((v=S.result)==null?void 0:v.number);p.onBlockNumber(T,c),c=T},onError(S){var T;(T=p.onError)==null||T.call(p,S)}});b=A,d||b()}catch(g){s==null||s(g)}})(),()=>b()})})()}async function Aw(t,e){const{checkReplacement:r=!0,confirmations:n=1,hash:s,onReplaced:i,retryCount:a=6,retryDelay:o=({count:x})=>~~(1<<x)*200,timeout:c=18e4}=e,u=et(["waitForTransactionReceipt",t.uid,s]),l=(()=>{var x;return e.pollingInterval?e.pollingInterval:(x=t.chain)!=null&&x.experimental_preconfirmationTime?t.chain.experimental_preconfirmationTime:t.pollingInterval})();let f,p,d,b=!1,g,A;const{promise:S,resolve:T,reject:v}=Wh(),w=c?setTimeout(()=>{A==null||A(),g==null||g(),v(new kS({hash:s}))},c):void 0;return g=Fn(u,{onReplaced:i,resolve:T,reject:v},async x=>{if(d=await re(t,Sc,"getTransactionReceipt")({hash:s}).catch(()=>{}),d&&n<=1){clearTimeout(w),x.resolve(d),g==null||g();return}A=re(t,Ew,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:l,async onBlockNumber(_){const I=C=>{clearTimeout(w),A==null||A(),C(),g==null||g()};let N=_;if(!b)try{if(d){if(n>1&&(!d.blockNumber||N-d.blockNumber+1n<n))return;I(()=>x.resolve(d));return}if(r&&!f&&(b=!0,await Mc(async()=>{f=await re(t,f0,"getTransaction")({hash:s}),f.blockNumber&&(N=f.blockNumber)},{delay:o,retryCount:a}),b=!1),d=await re(t,Sc,"getTransactionReceipt")({hash:s}),n>1&&(!d.blockNumber||N-d.blockNumber+1n<n))return;I(()=>x.resolve(d))}catch(C){if(C instanceof Bg||C instanceof Cg){if(!f){b=!1;return}try{p=f,b=!0;const j=await Mc(()=>re(t,Pr,"getBlock")({blockNumber:N,includeTransactions:!0}),{delay:o,retryCount:a,shouldRetry:({error:V})=>V instanceof Hg});b=!1;const M=j.transactions.find(({from:V,nonce:Q})=>V===p.from&&Q===p.nonce);if(!M||(d=await re(t,Sc,"getTransactionReceipt")({hash:M.hash}),n>1&&(!d.blockNumber||N-d.blockNumber+1n<n)))return;let H="replaced";M.to===p.to&&M.value===p.value&&M.input===p.input?H="repriced":M.from===M.to&&M.value===0n&&(H="cancelled"),I(()=>{var V;(V=x.onReplaced)==null||V.call(x,{reason:H,replacedTransaction:p,transaction:M,transactionReceipt:d}),x.resolve(d)})}catch(j){I(()=>x.reject(j))}}else I(()=>x.reject(C))}}})}),S}function tT(t,{blockTag:e=t.experimental_blockTag??"latest",emitMissed:r=!1,emitOnBegin:n=!1,onBlock:s,onError:i,includeTransactions:a,poll:o,pollingInterval:c=t.pollingInterval}){const u=typeof o<"u"?o:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc")),l=a??!1;let f;return u?(()=>{const b=et(["watchBlocks",t.uid,e,r,n,l,c]);return Fn(b,{onBlock:s,onError:i},g=>na(async()=>{var A;try{const S=await re(t,Pr,"getBlock")({blockTag:e,includeTransactions:l});if(S.number!==null&&(f==null?void 0:f.number)!=null){if(S.number===f.number)return;if(S.number-f.number>1&&r)for(let T=(f==null?void 0:f.number)+1n;T<S.number;T++){const v=await re(t,Pr,"getBlock")({blockNumber:T,includeTransactions:l});g.onBlock(v,f),f=v}}((f==null?void 0:f.number)==null||e==="pending"&&(S==null?void 0:S.number)==null||S.number!==null&&S.number>f.number)&&(g.onBlock(S,f),f=S)}catch(S){(A=g.onError)==null||A.call(g,S)}},{emitOnBegin:n,interval:c}))})():(()=>{let b=!0,g=!0,A=()=>b=!1;return(async()=>{try{n&&re(t,Pr,"getBlock")({blockTag:e,includeTransactions:l}).then(v=>{b&&g&&(s(v,void 0),g=!1)}).catch(i);const S=(()=>{if(t.transport.type==="fallback"){const v=t.transport.transports.find(w=>w.config.type==="webSocket"||w.config.type==="ipc");return v?v.value:t.transport}return t.transport})(),{unsubscribe:T}=await S.subscribe({params:["newHeads"],async onData(v){var x;if(!b)return;const w=await re(t,Pr,"getBlock")({blockNumber:(x=v.result)==null?void 0:x.number,includeTransactions:l}).catch(()=>{});b&&(s(w,f),g=!1,f=w)},onError(v){i==null||i(v)}});A=T,b||A()}catch(S){i==null||i(S)}})(),()=>A()})()}function rT(t,{address:e,args:r,batch:n=!0,event:s,events:i,fromBlock:a,onError:o,onLogs:c,poll:u,pollingInterval:l=t.pollingInterval,strict:f}){const p=typeof u<"u"?u:typeof a=="bigint"?!0:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc")),d=f??!1;return p?(()=>{const A=et(["watchEvent",e,r,n,t.uid,s,l,a]);return Fn(A,{onLogs:c,onError:o},S=>{let T;a!==void 0&&(T=a-1n);let v,w=!1;const x=na(async()=>{var _;if(!w){try{v=await re(t,$1,"createEventFilter")({address:e,args:r,event:s,events:i,strict:d,fromBlock:a})}catch{}w=!0;return}try{let I;if(v)I=await re(t,Au,"getFilterChanges")({filter:v});else{const N=await re(t,Mo,"getBlockNumber")({});T&&T!==N?I=await re(t,Hh,"getLogs")({address:e,args:r,event:s,events:i,fromBlock:T+1n,toBlock:N}):I=[],T=N}if(I.length===0)return;if(n)S.onLogs(I);else for(const N of I)S.onLogs([N])}catch(I){v&&I instanceof bs&&(w=!1),(_=S.onError)==null||_.call(S,I)}},{emitOnBegin:!0,interval:l});return async()=>{v&&await re(t,Su,"uninstallFilter")({filter:v}),x()}})})():(()=>{let A=!0,S=()=>A=!1;return(async()=>{try{const T=(()=>{if(t.transport.type==="fallback"){const _=t.transport.transports.find(I=>I.config.type==="webSocket"||I.config.type==="ipc");return _?_.value:t.transport}return t.transport})(),v=i??(s?[s]:void 0);let w=[];v&&(w=[v.flatMap(I=>_o({abi:[I],eventName:I.name,args:r}))],s&&(w=w[0]));const{unsubscribe:x}=await T.subscribe({params:["logs",{address:e,topics:w}],onData(_){var N;if(!A)return;const I=_.result;try{const{eventName:C,args:j}=Rc({abi:v??[],data:I.data,topics:I.topics,strict:d}),M=Un(I,{args:j,eventName:C});c([M])}catch(C){let j,M;if(C instanceof Cc||C instanceof yh){if(f)return;j=C.abiItem.name,M=(N=C.abiItem.inputs)==null?void 0:N.some(V=>!("name"in V&&V.name))}const H=Un(I,{args:M?[]:{},eventName:j});c([H])}},onError(_){o==null||o(_)}});S=x,A||S()}catch(T){o==null||o(T)}})(),()=>S()})()}function nT(t,{batch:e=!0,onError:r,onTransactions:n,poll:s,pollingInterval:i=t.pollingInterval}){return(typeof s<"u"?s:t.transport.type!=="webSocket"&&t.transport.type!=="ipc")?(()=>{const u=et(["watchPendingTransactions",t.uid,e,i]);return Fn(u,{onTransactions:n,onError:r},l=>{let f;const p=na(async()=>{var d;try{if(!f)try{f=await re(t,j1,"createPendingTransactionFilter")({});return}catch(g){throw p(),g}const b=await re(t,Au,"getFilterChanges")({filter:f});if(b.length===0)return;if(e)l.onTransactions(b);else for(const g of b)l.onTransactions([g])}catch(b){(d=l.onError)==null||d.call(l,b)}},{emitOnBegin:!0,interval:i});return async()=>{f&&await re(t,Su,"uninstallFilter")({filter:f}),p()}})})():(()=>{let u=!0,l=()=>u=!1;return(async()=>{try{const{unsubscribe:f}=await t.transport.subscribe({params:["newPendingTransactions"],onData(p){if(!u)return;const d=p.result;n([d])},onError(p){r==null||r(p)}});l=f,u||l()}catch(f){r==null||r(f)}})(),()=>l()})()}function sT(t){var f,p,d;const{scheme:e,statement:r,...n}=((f=t.match(iT))==null?void 0:f.groups)??{},{chainId:s,expirationTime:i,issuedAt:a,notBefore:o,requestId:c,...u}=((p=t.match(aT))==null?void 0:p.groups)??{},l=(d=t.split("Resources:")[1])==null?void 0:d.split(`
71
+ - `).slice(1);return{...n,...u,...s?{chainId:Number(s)}:{},...i?{expirationTime:new Date(i)}:{},...a?{issuedAt:new Date(a)}:{},...o?{notBefore:new Date(o)}:{},...c?{requestId:c}:{},...l?{resources:l}:{},...e?{scheme:e}:{},...r?{statement:r}:{}}}const iT=/^(?:(?<scheme>[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?<domain>[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?<address>0x[a-fA-F0-9]{40})\n\n(?:(?<statement>.*)\n\n)?/,aT=/(?:URI: (?<uri>.+))\n(?:Version: (?<version>.+))\n(?:Chain ID: (?<chainId>\d+))\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\n(?:Issued At: (?<issuedAt>.+))(?:\nExpiration Time: (?<expirationTime>.+))?(?:\nNot Before: (?<notBefore>.+))?(?:\nRequest ID: (?<requestId>.+))?/;function oT(t){const{address:e,domain:r,message:n,nonce:s,scheme:i,time:a=new Date}=t;if(r&&n.domain!==r||s&&n.nonce!==s||i&&n.scheme!==i||n.expirationTime&&a>=n.expirationTime||n.notBefore&&a<n.notBefore)return!1;try{if(!n.address||!ut(n.address,{strict:!1})||e&&!ta(n.address,e))return!1}catch{return!1}return!0}async function cT(t,e){const{address:r,domain:n,message:s,nonce:i,scheme:a,signature:o,time:c=new Date,...u}=e,l=sT(s);if(!l.address||!oT({address:r,domain:n,message:l,nonce:i,scheme:a,time:c}))return!1;const p=H1(s);return Iu(t,{address:l.address,hash:p,signature:o,...u})}async function d0(t,{serializedTransaction:e,throwOnReceiptRevert:r,timeout:n}){var o,c,u;const s=await t.request({method:"eth_sendRawTransactionSync",params:n?[e,Y(n)]:[e]},{retryCount:0}),a=(((u=(c=(o=t.chain)==null?void 0:o.formatters)==null?void 0:c.transactionReceipt)==null?void 0:u.format)||Jh)(s);if(a.status==="reverted"&&r)throw new Rg({receipt:a});return a}function uT(t){return{call:e=>Fo(t,e),createAccessList:e=>M1(t,e),createBlockFilter:()=>Tx(t),createContractEventFilter:e=>Sh(t,e),createEventFilter:e=>$1(t,e),createPendingTransactionFilter:()=>j1(t),estimateContractGas:e=>Jg(t,e),estimateGas:e=>$h(t,e),getBalance:e=>_x(t,e),getBlobBaseFee:()=>Ix(t),getBlock:e=>Pr(t,e),getBlockNumber:e=>Mo(t,e),getBlockTransactionCount:e=>Px(t,e),getBytecode:e=>Sd(t,e),getChainId:()=>Ss(t),getCode:e=>Sd(t,e),getContractEvents:e=>Lh(t,e),getEip712Domain:e=>Bx(t,e),getEnsAddress:e=>lx(t,e),getEnsAvatar:e=>Sx(t,e),getEnsName:e=>xx(t,e),getEnsResolver:e=>kx(t,e),getEnsText:e=>F1(t,e),getFeeHistory:e=>Nx(t,e),estimateFeesPerGas:e=>WS(t,e),getFilterChanges:e=>Au(t,e),getFilterLogs:e=>Ux(t,e),getGasPrice:()=>Bh(t),getLogs:e=>Hh(t,e),getProof:e=>Bk(t,e),estimateMaxPriorityFeePerGas:e=>qS(t,e),fillTransaction:e=>Fh(t,e),getStorageAt:e=>Ck(t,e),getTransaction:e=>f0(t,e),getTransactionConfirmations:e=>Rk(t,e),getTransactionCount:e=>Ch(t,e),getTransactionReceipt:e=>Sc(t,e),multicall:e=>Nk(t,e),prepareTransactionRequest:e=>Co(t,e),readContract:e=>wr(t,e),sendRawTransaction:e=>Xh(t,e),sendRawTransactionSync:e=>d0(t,e),simulate:e=>Bd(t,e),simulateBlocks:e=>Bd(t,e),simulateCalls:e=>Vk(t,e),simulateContract:e=>A1(t,e),verifyHash:e=>Iu(t,e),verifyMessage:e=>Qk(t,e),verifySiweMessage:e=>cT(t,e),verifyTypedData:e=>eT(t,e),uninstallFilter:e=>Su(t,e),waitForTransactionReceipt:e=>Aw(t,e),watchBlocks:e=>tT(t,e),watchBlockNumber:e=>Ew(t,e),watchContractEvent:e=>S1(t,e),watchEvent:e=>rT(t,e),watchPendingTransactions:e=>nT(t,e)}}function lT(t){const{key:e="public",name:r="Public Client"}=t;return B1({...t,key:e,name:r,type:"publicClient"}).extend(uT)}async function fT(t,{chain:e}){const{id:r,name:n,nativeCurrency:s,rpcUrls:i,blockExplorers:a}=e;await t.request({method:"wallet_addEthereumChain",params:[{chainId:Y(r),chainName:n,nativeCurrency:s,rpcUrls:i.default.http,blockExplorerUrls:a?Object.values(a).map(({url:o})=>o):void 0}]},{dedupe:!0,retryCount:0})}function dT(t,e){const{abi:r,args:n,bytecode:s,...i}=e,a=Eu({abi:r,args:n,bytecode:s});return xu(t,{...i,...i.authorizationList?{to:null}:{},data:a})}async function hT(t){var r;return((r=t.account)==null?void 0:r.type)==="local"?[t.account.address]:(await t.request({method:"eth_accounts"},{dedupe:!0})).map(n=>ko(n))}async function pT(t,e={}){const{account:r=t.account,chainId:n}=e,s=r?Le(r):void 0,i=n?[s==null?void 0:s.address,[Y(n)]]:[s==null?void 0:s.address],a=await t.request({method:"wallet_getCapabilities",params:i}),o={};for(const[c,u]of Object.entries(a)){o[Number(c)]={};for(let[l,f]of Object.entries(u))l==="addSubAccount"&&(l="unstable_addSubAccount"),o[Number(c)][l]=f}return typeof n=="number"?o[n]:o}async function yT(t){return await t.request({method:"wallet_getPermissions"},{dedupe:!0})}async function Sw(t,e){var c;const{account:r=t.account,chainId:n,nonce:s}=e;if(!r)throw new xs({docsPath:"/docs/eip7702/prepareAuthorization"});const i=Le(r),a=(()=>{if(e.executor)return e.executor==="self"?e.executor:Le(e.executor)})(),o={address:e.contractAddress??e.address,chainId:n,nonce:s};return typeof o.chainId>"u"&&(o.chainId=((c=t.chain)==null?void 0:c.id)??await re(t,Ss,"getChainId")({})),typeof o.nonce>"u"&&(o.nonce=await re(t,Ch,"getTransactionCount")({address:i.address,blockTag:"pending"}),(a==="self"||a!=null&&a.address&&ta(a.address,i.address))&&(o.nonce+=1)),o}async function mT(t){return(await t.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(r=>wh(r))}async function bT(t,e){return t.request({method:"wallet_requestPermissions",params:[e]},{retryCount:0})}async function gT(t,e){const{chain:r=t.chain}=e,n=e.timeout??Math.max(((r==null?void 0:r.blockTime)??0)*3,5e3),s=await _1(t,e);return await P1(t,{...e,id:s.id,timeout:n})}const xl=new Qi(128);async function xw(t,e){var _,I,N,C;const{account:r=t.account,assertChainId:n=!0,chain:s=t.chain,accessList:i,authorizationList:a,blobs:o,data:c,gas:u,gasPrice:l,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:d,nonce:b,pollingInterval:g,throwOnReceiptRevert:A,type:S,value:T,...v}=e,w=e.timeout??Math.max(((s==null?void 0:s.blockTime)??0)*3,5e3);if(typeof r>"u")throw new xs({docsPath:"/docs/actions/wallet/sendTransactionSync"});const x=r?Le(r):null;try{jn(e);const j=await(async()=>{if(e.to)return e.to;if(e.to!==null&&a&&a.length>0)return await hu({authorization:a[0]}).catch(()=>{throw new G("`to` is required. Could not infer from `authorizationList`.")})})();if((x==null?void 0:x.type)==="json-rpc"||x===null){let M;s!==null&&(M=await re(t,Ss,"getChainId")({}),n&&Kh({currentChainId:M,chain:s}));const H=(N=(I=(_=t.chain)==null?void 0:_.formatters)==null?void 0:I.transactionRequest)==null?void 0:N.format,Q=(H||As)({...ea(v,{format:H}),accessList:i,account:x,authorizationList:a,blobs:o,chainId:M,data:c,gas:u,gasPrice:l,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:d,nonce:b,to:j,type:S,value:T},"sendTransaction"),U=xl.get(t.uid),K=U?"wallet_sendTransaction":"eth_sendTransaction",ee=await(async()=>{try{return await t.request({method:K,params:[Q]},{retryCount:0})}catch(O){if(U===!1)throw O;const L=O;if(L.name==="InvalidInputRpcError"||L.name==="InvalidParamsRpcError"||L.name==="MethodNotFoundRpcError"||L.name==="MethodNotSupportedRpcError")return await t.request({method:"wallet_sendTransaction",params:[Q]},{retryCount:0}).then(J=>(xl.set(t.uid,!0),J)).catch(J=>{const B=J;throw B.name==="MethodNotFoundRpcError"||B.name==="MethodNotSupportedRpcError"?(xl.set(t.uid,!1),L):B});throw L}})(),q=await re(t,Aw,"waitForTransactionReceipt")({checkReplacement:!1,hash:ee,pollingInterval:g,timeout:w});if(A&&q.status==="reverted")throw new Rg({receipt:q});return q}if((x==null?void 0:x.type)==="local"){const M=await re(t,Co,"prepareTransactionRequest")({account:x,accessList:i,authorizationList:a,blobs:o,chain:s,data:c,gas:u,gasPrice:l,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:d,nonce:b,nonceManager:x.nonceManager,parameters:[...Mh,"sidecars"],type:S,value:T,...v,to:j}),H=(C=s==null?void 0:s.serializers)==null?void 0:C.transaction,V=await x.signTransaction(M,{serializer:H});return await re(t,d0,"sendRawTransactionSync")({serializedTransaction:V,throwOnReceiptRevert:A,timeout:e.timeout})}throw(x==null?void 0:x.type)==="smart"?new Vs({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new Vs({docsPath:"/docs/actions/wallet/sendTransactionSync",type:x==null?void 0:x.type})}catch(j){throw j instanceof Vs?j:mu(j,{...e,account:x,chain:e.chain||void 0})}}async function wT(t,e){const{id:r}=e;await t.request({method:"wallet_showCallsStatus",params:[r]})}async function vT(t,e){const{account:r=t.account}=e;if(!r)throw new xs({docsPath:"/docs/eip7702/signAuthorization"});const n=Le(r);if(!n.signAuthorization)throw new Vs({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});const s=await Sw(t,e);return n.signAuthorization(s)}async function ET(t,{account:e=t.account,message:r}){if(!e)throw new xs({docsPath:"/docs/actions/wallet/signMessage"});const n=Le(e);if(n.signMessage)return n.signMessage({message:r});const s=typeof r=="string"?Vi(r):r.raw instanceof Uint8Array?Ft(r.raw):r.raw;return t.request({method:"personal_sign",params:[s,n.address]},{retryCount:0})}async function AT(t,e){var u,l,f,p;const{account:r=t.account,chain:n=t.chain,...s}=e;if(!r)throw new xs({docsPath:"/docs/actions/wallet/signTransaction"});const i=Le(r);jn({account:i,...e});const a=await re(t,Ss,"getChainId")({});n!==null&&Kh({currentChainId:a,chain:n});const o=(n==null?void 0:n.formatters)||((u=t.chain)==null?void 0:u.formatters),c=((l=o==null?void 0:o.transactionRequest)==null?void 0:l.format)||As;return i.signTransaction?i.signTransaction({...s,chainId:a},{serializer:(p=(f=t.chain)==null?void 0:f.serializers)==null?void 0:p.transaction}):await t.request({method:"eth_signTransaction",params:[{...c({...s,account:i},"signTransaction"),chainId:Y(a),from:i.address}]},{retryCount:0})}async function ST(t,e){const{account:r=t.account,domain:n,message:s,primaryType:i}=e;if(!r)throw new xs({docsPath:"/docs/actions/wallet/signTypedData"});const a=Le(r),o={EIP712Domain:D1({domain:n}),...e.types};if(L1({domain:n,message:s,primaryType:i,types:o}),a.signTypedData)return a.signTypedData({domain:n,message:s,primaryType:i,types:o});const c=a3({domain:n,message:s,primaryType:i,types:o});return t.request({method:"eth_signTypedData_v4",params:[a.address,c]},{retryCount:0})}async function xT(t,{id:e}){await t.request({method:"wallet_switchEthereumChain",params:[{chainId:Y(e)}]},{retryCount:0})}async function kT(t,e){return await t.request({method:"wallet_watchAsset",params:e},{retryCount:0})}async function TT(t,e){return Ki.internal(t,xw,"sendTransactionSync",e)}function _T(t){return{addChain:e=>fT(t,e),deployContract:e=>dT(t,e),fillTransaction:e=>Fh(t,e),getAddresses:()=>hT(t),getCallsStatus:e=>I1(t,e),getCapabilities:e=>pT(t,e),getChainId:()=>Ss(t),getPermissions:()=>yT(t),prepareAuthorization:e=>Sw(t,e),prepareTransactionRequest:e=>Co(t,e),requestAddresses:()=>mT(t),requestPermissions:e=>bT(t,e),sendCalls:e=>_1(t,e),sendCallsSync:e=>gT(t,e),sendRawTransaction:e=>Xh(t,e),sendRawTransactionSync:e=>d0(t,e),sendTransaction:e=>xu(t,e),sendTransactionSync:e=>xw(t,e),showCallsStatus:e=>wT(t,e),signAuthorization:e=>vT(t,e),signMessage:e=>ET(t,e),signTransaction:e=>AT(t,e),signTypedData:e=>ST(t,e),switchChain:e=>xT(t,e),waitForCallsStatus:e=>P1(t,e),watchAsset:e=>kT(t,e),writeContract:e=>Ki(t,e),writeContractSync:e=>TT(t,e)}}function kl(t){const{key:e="wallet",name:r="Wallet Client",transport:n}=t;return B1({...t,key:e,name:r,transport:n,type:"walletClient"}).extend(_T)}function kw({key:t,methods:e,name:r,request:n,retryCount:s=3,retryDelay:i=150,timeout:a,type:o},c){const u=O1();return{config:{key:t,methods:e,name:r,request:n,retryCount:s,retryDelay:i,timeout:a,type:o},request:Xx(n,{methods:e,retryCount:s,retryDelay:i,uid:u}),value:c}}function ay(t,e={}){const{key:r="custom",methods:n,name:s="Custom Provider",retryDelay:i}=e;return({retryCount:a})=>kw({key:r,methods:n,name:s,request:t.request.bind(t),retryCount:e.retryCount??a,retryDelay:i,type:"custom"})}class IT extends G{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}function Tw(t,e={}){const{batch:r,fetchFn:n,fetchOptions:s,key:i="http",methods:a,name:o="HTTP JSON-RPC",onFetchRequest:c,onFetchResponse:u,retryDelay:l,raw:f}=e;return({chain:p,retryCount:d,timeout:b})=>{const{batchSize:g=1e3,wait:A=0}=typeof r=="object"?r:{},S=e.retryCount??d,T=b??e.timeout??1e4,v=p==null?void 0:p.rpcUrls.default.http[0];if(!v)throw new IT;const w=Qx(v,{fetchFn:n,fetchOptions:s,onRequest:c,onResponse:u,timeout:T});return kw({key:i,methods:a,name:o,async request({method:x,params:_}){const I={method:x,params:_},{schedule:N}=v1({id:v,wait:A,shouldSplitBatch(H){return H.length>g},fn:H=>w.request({body:H}),sort:(H,V)=>H.id-V.id}),C=async H=>r?N(H):[await w.request({body:H})],[{error:j,result:M}]=await C(I);if(f)return{error:j,result:M};if(j)throw new Th({body:I,error:j,url:v});return M},retryCount:S,retryDelay:l,timeout:T,type:"http"},{fetchOptions:s,url:v})}}const _w=[{inputs:[{internalType:"address",name:"token_",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"InvalidShortString",type:"error"},{inputs:[{internalType:"string",name:"str",type:"string"}],name:"StringTooLong",type:"error"},{anonymous:!1,inputs:[],name:"EIP712DomainChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Initiated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"secret",type:"bytes"}],name:"Redeemed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"Refunded",type:"event"},{inputs:[],name:"eip712Domain",outputs:[{internalType:"bytes1",name:"fields",type:"bytes1"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"},{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"address",name:"verifyingContract",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"uint256[]",name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"}],name:"initiate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"initiateWithSignature",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"instantRefund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"expiry",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],internalType:"struct HTLC.InitWithSig[]",name:"inits",type:"tuple[]"},{components:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"secret",type:"bytes"}],internalType:"struct HTLC.Redeem[]",name:"redeems",type:"tuple[]"},{components:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],internalType:"struct HTLC.Refund[]",name:"refunds",type:"tuple[]"}],name:"multicall",outputs:[{internalType:"bool[]",name:"results",type:"bool[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"",type:"bytes32"}],name:"orders",outputs:[{internalType:"bool",name:"isFulfilled",type:"bool"},{internalType:"address",name:"initiator",type:"address"},{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"initiatedAt",type:"uint256"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"secret",type:"bytes"}],name:"redeem",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"refund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"token",outputs:[{internalType:"contract IERC20",name:"",type:"address"}],stateMutability:"view",type:"function"}],PT=[{inputs:[{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"InvalidShortString",type:"error"},{inputs:[],name:"NativeHTLC__DuplicateOrder",type:"error"},{inputs:[],name:"NativeHTLC__IncorrectFundsRecieved",type:"error"},{inputs:[],name:"NativeHTLC__IncorrectSecret",type:"error"},{inputs:[],name:"NativeHTLC__InsufficientBalance",type:"error"},{inputs:[],name:"NativeHTLC__InvalidRedeemerSignature",type:"error"},{inputs:[],name:"NativeHTLC__OrderFulfilled",type:"error"},{inputs:[],name:"NativeHTLC__OrderNotExpired",type:"error"},{inputs:[],name:"NativeHTLC__OrderNotInitiated",type:"error"},{inputs:[],name:"NativeHTLC__SameInitiatorAndRedeemer",type:"error"},{inputs:[],name:"NativeHTLC__ZeroAddressInitiator",type:"error"},{inputs:[],name:"NativeHTLC__ZeroAddressRedeemer",type:"error"},{inputs:[],name:"NativeHTLC__ZeroAmount",type:"error"},{inputs:[],name:"NativeHTLC__ZeroTimelock",type:"error"},{inputs:[{internalType:"string",name:"str",type:"string"}],name:"StringTooLong",type:"error"},{anonymous:!1,inputs:[],name:"EIP712DomainChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Initiated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"secret",type:"bytes"}],name:"Redeemed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"Refunded",type:"event"},{inputs:[],name:"eip712Domain",outputs:[{internalType:"bytes1",name:"fields",type:"bytes1"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"},{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"address",name:"verifyingContract",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"uint256[]",name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address payable",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"}],name:"initiate",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address payable",name:"initiator",type:"address"},{internalType:"address payable",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"}],name:"initiateOnBehalf",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"instantRefund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"instantRefundDigest",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"",type:"bytes32"}],name:"orders",outputs:[{internalType:"bool",name:"isFulfilled",type:"bool"},{internalType:"address payable",name:"initiator",type:"address"},{internalType:"address payable",name:"redeemer",type:"address"},{internalType:"uint256",name:"initiatedAt",type:"uint256"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"secret",type:"bytes"}],name:"redeem",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"refund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"token",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}];class li{constructor(e,r){this.auth=e,this.url=r instanceof m.Url?r:new m.Url(r)}async initiate(e,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return m.Err(n.error);const s=await m.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:r}),headers:{...n.val,"Content-Type":"application/json"}});return s.error||!s.result?m.Err(s.error||"Initiate failed"):m.Ok(s.result)}catch(n){return m.Err(String(n))}}async redeem(e,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return m.Err(n.error);const s=await m.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e).addSearchParams({action:"redeem"}),{body:JSON.stringify({secret:m.trim0x(r)}),headers:{...n.val,"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return s.error?m.Err(s.error):s.result?m.Ok(s.result):m.Err("Redeem: No result found")}catch(n){return m.Err(String(n))}}}const OT=async(t,e)=>{if(!t.account)return m.Err("No account found");try{const n=await Yh({address:m.with0x(e.htlc),abi:PT,client:t}).write.initiate([m.with0x(e.redeemer),e.timelock,e.amount,m.with0x(e.secretHash)],{account:t.account,chain:t.chain,value:e.amount}),s=await m.waitForTransactionReceipt(t,n);return s.ok?!s.val||s.val.status!=="success"?m.Err("Native initiate transaction failed"):m.Ok(n):m.Err(s.error)}catch(r){return th(r)?m.Ok("already initiated"):m.Err("Failed to initiate on native HTLC",String(r))}},BT=async(t,e,r,n)=>{if(!t.account)return m.Err("No account found");try{const s=Yh({address:m.with0x(n.htlc),abi:_w,client:t}),i=await m.checkAllowanceAndApprove(Number(n.amount),n.token,n.htlc,t);if(!i.ok)return m.Err(i.error);const a=await s.read.eip712Domain(),o=await t.signTypedData({account:t.account,domain:{name:a[1],version:a[2],chainId:Number(a[3]),verifyingContract:a[4]},types:{Initiate:[{name:"redeemer",type:"address"},{name:"timelock",type:"uint256"},{name:"amount",type:"uint256"},{name:"secretHash",type:"bytes32"}]},primaryType:"Initiate",message:{redeemer:m.with0x(n.redeemer),timelock:n.timelock,amount:n.amount,secretHash:m.with0x(n.secretHash)}}),c=new li(r,e),u=await $m({wallet:t,attempt:()=>c.initiate(n.orderId,o)});if(u)return m.Ok(u);const l=await s.write.initiate([m.with0x(n.redeemer),n.timelock,n.amount,m.with0x(n.secretHash)],{account:t.account,chain:t.chain}),f=await m.waitForTransactionReceipt(t,l);return f.ok?!f.val||f.val.status!=="success"?m.Err("Failed to initiate (fallback)"):m.Ok(l):m.Err(f.error)}catch(s){return th(s)?m.Ok("already initiated"):m.Err("Failed to initiate on ERC20 HTLC",String(s))}},CT=async(t,e)=>{if(!t.account)return m.Err("No account found");try{const r=await t.sendTransaction({account:t.account,to:m.with0x(e.to),value:BigInt(e.value),data:m.with0x(e.data),gas:BigInt(e.gas_limit),chain:t.chain}),n=await m.waitForTransactionReceipt(t,r);return n.ok?!n.val||n.val.status!=="success"?m.Err("Approval transaction failed"):m.Ok(r):m.Err(n.error)}catch(r){return m.Err("Failed to execute approval: "+String(r))}},RT={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}},NT={block:GS({format(t){var r;return{transactions:(r=t.transactions)==null?void 0:r.map(n=>{if(typeof n=="string")return n;const s=Bo(n);return s.typeHex==="0x7e"&&(s.isSystemTx=n.isSystemTx,s.mint=n.mint?ft(n.mint):void 0,s.sourceHash=n.sourceHash,s.type="deposit"),s}),stateRoot:t.stateRoot}}}),transaction:zS({format(t){const e={};return t.type==="0x7e"&&(e.isSystemTx=t.isSystemTx,e.mint=t.mint?ft(t.mint):void 0,e.sourceHash=t.sourceHash,e.type="deposit"),e}}),transactionReceipt:nx({format(t){return{l1GasPrice:t.l1GasPrice?ft(t.l1GasPrice):null,l1GasUsed:t.l1GasUsed?ft(t.l1GasUsed):null,l1Fee:t.l1Fee?ft(t.l1Fee):null,l1FeeScalar:t.l1FeeScalar?Number(t.l1FeeScalar):null}}})};function UT(t,e){return $T(t)?MT(t):Hx(t,e)}const FT={transaction:UT};function MT(t){jT(t);const{sourceHash:e,data:r,from:n,gas:s,isSystemTx:i,mint:a,to:o,value:c}=t,u=[e,n,o??"0x",a?Ft(a):"0x",c?Ft(c):"0x",s?Ft(s):"0x",i?"0x1":"0x",r??"0x"];return jr(["0x7e",gs(u)])}function $T(t){return t.type==="deposit"||typeof t.sourceHash<"u"}function jT(t){const{from:e,to:r}=t;if(e&&!ut(e))throw new $t({address:e});if(r&&!ut(r))throw new $t({address:r})}const on={blockTime:2e3,contracts:RT,formatters:NT,serializers:FT},HT=rt({id:42161,name:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:250,rpcUrls:{default:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://arbiscan.io",apiUrl:"https://api.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:7654707}}}),LT=rt({id:421614,name:"Arbitrum Sepolia",blockTime:250,nativeCurrency:{name:"Arbitrum Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia-rollup.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://sepolia.arbiscan.io",apiUrl:"https://api-sepolia.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:81930}},testnet:!0}),Iw=rt({id:5042002,name:"Arc Testnet",nativeCurrency:{name:"USDC",symbol:"USDC",decimals:18},rpcUrls:{default:{http:["https://rpc.testnet.arc.network","https://rpc.quicknode.testnet.arc.network","https://rpc.blockdaemon.testnet.arc.network"],webSocket:["wss://rpc.testnet.arc.network","wss://rpc.quicknode.testnet.arc.network"]}},blockExplorers:{default:{name:"ArcScan",url:"https://testnet.arcscan.app",apiUrl:"https://testnet.arcscan.app/api"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:0}},testnet:!0}),pa=1,Pw=rt({...on,id:8453,name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://basescan.org",apiUrl:"https://api.basescan.org/api"}},contracts:{...on.contracts,disputeGameFactory:{[pa]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[pa]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[pa]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[pa]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:pa});({...Pw});const ya=11155111,Ow=rt({...on,id:84532,network:"base-sepolia",name:"Base Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://sepolia.basescan.org",apiUrl:"https://api-sepolia.basescan.org/api"}},contracts:{...on.contracts,disputeGameFactory:{[ya]:{address:"0xd6E6dBf4F7EA0ac412fD8b65ED297e64BB7a06E1"}},l2OutputOracle:{[ya]:{address:"0x84457ca9D0163FbC4bbfe4Dfbb20ba46e48DF254"}},portal:{[ya]:{address:"0x49f53e41452c74589e85ca1677426ba426459e85",blockCreated:4446677}},l1StandardBridge:{[ya]:{address:"0xfd0Bf71F60660E2f608ed56e1659C450eB113120",blockCreated:4446677}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:1059647}},testnet:!0,sourceId:ya});({...Ow});const DT=rt({id:80094,name:"Berachain",blockTime:2e3,nativeCurrency:{decimals:18,name:"BERA Token",symbol:"BERA"},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:0},ensRegistry:{address:"0x5b22280886a2f5e09a49bea7e320eab0e5320e28",blockCreated:877007},ensUniversalResolver:{address:"0x4D41762915F83c76EcaF6776d9b08076aA32b492",blockCreated:9310021}},rpcUrls:{default:{http:["https://rpc.berachain.com"]}},blockExplorers:{default:{name:"Berascan",url:"https://berascan.com"}},ensTlds:[".bera"],testnet:!1}),zT=rt({id:80084,name:"Berachain bArtio",nativeCurrency:{decimals:18,name:"BERA Token",symbol:"BERA"},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:109269},ensRegistry:{address:"0xB0eef18971290b333450586D33dcA6cE122651D2",blockCreated:7736794},ensUniversalResolver:{address:"0x41692Ef1EA0C79E6b73077E4A67572D2BDbD7057",blockCreated:7736795}},ensTlds:[".bera"],rpcUrls:{default:{http:["https://bartio.rpc.berachain.com"]}},blockExplorers:{default:{name:"Berachain bArtio Beratrail",url:"https://bartio.beratrail.io"}},testnet:!0}),VT=rt({id:56,name:"BNB Smart Chain",blockTime:750,nativeCurrency:{decimals:18,name:"BNB",symbol:"BNB"},rpcUrls:{default:{http:["https://56.rpc.thirdweb.com"]}},blockExplorers:{default:{name:"BscScan",url:"https://bscscan.com",apiUrl:"https://api.bscscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:15921452}}}),GT=rt({id:97,name:"BNB Smart Chain Testnet",nativeCurrency:{decimals:18,name:"BNB",symbol:"tBNB"},rpcUrls:{default:{http:["https://data-seed-prebsc-1-s1.bnbchain.org:8545"]}},blockExplorers:{default:{name:"BscScan",url:"https://testnet.bscscan.com",apiUrl:"https://api-testnet.bscscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:17422483}},testnet:!0}),qT=rt({id:5115,name:"Citrea Testnet",nativeCurrency:{name:"cBTC",symbol:"cBTC",decimals:18},rpcUrls:{default:{http:["https://rpc.testnet.citrea.xyz"]}},blockExplorers:{default:{name:"Citrea Explorer",url:"https://explorer.testnet.citrea.xyz",apiUrl:"https://explorer.testnet.citrea.xyz/api"}},testnet:!0}),WT=rt({id:1116,name:"Core Dao",nativeCurrency:{decimals:18,name:"Core",symbol:"CORE"},rpcUrls:{default:{http:["https://rpc.coredao.org"]}},blockExplorers:{default:{name:"CoreDao",url:"https://scan.coredao.org"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:11907934}},testnet:!1}),KT=1,XT=rt({id:21e6,name:"Corn",nativeCurrency:{decimals:18,name:"Bitcorn",symbol:"BTCN"},rpcUrls:{default:{http:["https://21000000.rpc.thirdweb.com"]}},blockExplorers:{default:{name:"Corn Explorer",url:"https://cornscan.io",apiUrl:"https://api.routescan.io/v2/network/mainnet/evm/21000000/etherscan/api"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:3228}},sourceId:KT}),cc=1,YT=rt({...on,id:57073,name:"Ink",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc-gel.inkonchain.com","https://rpc-qnd.inkonchain.com"],webSocket:["wss://rpc-gel.inkonchain.com","wss://rpc-qnd.inkonchain.com"]}},blockExplorers:{default:{name:"Blockscout",url:"https://explorer.inkonchain.com",apiUrl:"https://explorer.inkonchain.com/api/v2"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:0},...on.contracts,disputeGameFactory:{[cc]:{address:"0x10d7b35078d3baabb96dd45a9143b94be65b12cd"}},portal:{[cc]:{address:"0x5d66c1782664115999c47c9fa5cd031f495d3e4f"}},l1StandardBridge:{[cc]:{address:"0x88ff1e5b602916615391f55854588efcbb7663f0"}}},testnet:!1,sourceId:cc}),uc=11155111,JT=rt({...on,id:763373,name:"Ink Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc-gel-sepolia.inkonchain.com"]}},blockExplorers:{default:{name:"Blockscout",url:"https://explorer-sepolia.inkonchain.com/",apiUrl:"https://explorer-sepolia.inkonchain.com/api/v2"}},contracts:{...on.contracts,multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:0},disputeGameFactory:{[uc]:{address:"0x860e626c700af381133d9f4af31412a2d1db3d5d"}},portal:{[uc]:{address:"0x5c1d29c6c9c8b0800692acc95d700bcb4966a1d7"}},l1StandardBridge:{[uc]:{address:"0x33f60714bbd74d62b66d79213c348614de51901c"}}},testnet:!0,sourceId:uc}),ZT=rt({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:12e3,rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensUniversalResolver:{address:"0xeeeeeeee14d718c2b47d9923deab1335e144eeee",blockCreated:23085558},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),QT=rt({id:10143,name:"Monad Testnet",blockTime:400,nativeCurrency:{name:"Testnet MON Token",symbol:"MON",decimals:18},rpcUrls:{default:{http:["https://testnet-rpc.monad.xyz"]}},blockExplorers:{default:{name:"Monad Testnet explorer",url:"https://testnet.monadexplorer.com"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:251449}},testnet:!0}),e_=rt({id:11155111,name:"Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://11155111.rpc.thirdweb.com"]}},blockExplorers:{default:{name:"Etherscan",url:"https://sepolia.etherscan.io",apiUrl:"https://api-sepolia.etherscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:751532},ensUniversalResolver:{address:"0xeeeeeeee14d718c2b47d9923deab1335e144eeee",blockCreated:8928790}},testnet:!0}),lc=1,t_=rt({...on,id:130,name:"Unichain",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:1e3,rpcUrls:{default:{http:["https://mainnet.unichain.org/"]}},blockExplorers:{default:{name:"Uniscan",url:"https://uniscan.xyz",apiUrl:"https://api.uniscan.xyz/api"}},contracts:{...on.contracts,multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:0},disputeGameFactory:{[lc]:{address:"0x2F12d621a16e2d3285929C9996f478508951dFe4"}},portal:{[lc]:{address:"0x0bd48f6B86a26D3a217d0Fa6FfE2B491B956A7a2"}},l1StandardBridge:{[lc]:{address:"0x81014F44b0a345033bB2b3B21C7a1A308B35fEeA"}}},sourceId:lc}),r_={...e_,rpcUrls:{default:{http:["https://ethereum-sepolia-rpc.publicnode.com"]}}},Bw={id:3637,name:"Botanix",nativeCurrency:{name:"Botanix",symbol:"BOTX",decimals:18},blockExplorers:{default:{name:"Botanix Explorer",url:"https://botanixscan.io/"}},rpcUrls:{default:{http:["https://rpc.botanixlabs.com/"]}}},Nd={id:998,name:"Hyperliquid EVM Testnet",nativeCurrency:{name:"Hyperliquid",symbol:"HYPE",decimals:18},blockExplorers:{default:{name:"Hyperliquid Explorer",url:"https://testnet.purrsec.com/"}},rpcUrls:{default:{http:["https://rpc.hyperliquid-testnet.xyz/evm"]}}},Ud={id:999,name:"HyperEVM",nativeCurrency:{name:"Hyperliquid",symbol:"HYPE",decimals:18},blockExplorers:{default:{name:"Hyperliquid Explorer",url:"https://hyperscan.gas.zip/"}},rpcUrls:{default:{http:["https://rpc.hyperliquid.xyz/evm"]}}},Cw={id:8150,name:"Alpen Network",nativeCurrency:{name:"Signet bitcoin",symbol:"sBTC",decimals:18},blockExplorers:{default:{name:"Alpen Explorer",url:"https://explorer.pectra-testnet.alpenlabs.io"}},rpcUrls:{default:{http:["https://rpc.pectra-testnet.alpenlabs.io"]}}},n_={id:143,name:"Monad",nativeCurrency:{name:"Monad",symbol:"MON",decimals:18},blockExplorers:{default:{name:"Monad Explorer",url:"https://monadvision.com/"}},rpcUrls:{default:{http:["https://rpc1.monad.xyz"]}}},s_={id:4114,name:"Citrea Mainnet",nativeCurrency:{name:"Citrea Bitcoin",symbol:"cBTC",decimals:18},rpcUrls:{default:{http:["https://rpc.mainnet.citrea.xyz"]}},blockExplorers:{default:{name:"Citrea Explorer",url:"https://explorer.mainnet.citrea.xyz",apiUrl:"https://explorer.mainnet.citrea.xyz/api"}},testnet:!1},Rw={id:4326,name:"MegaETH",nativeCurrency:{name:"MegaETH",symbol:"MEGA",decimals:18},rpcUrls:{default:{http:["https://mainnet.megaeth.com/rpc"]}},blockExplorers:{default:{name:"MegaETH Explorer",url:"https://megaeth.blockscout.com/"}},testnet:!1},Pu={ethereum:ZT,arbitrum:HT,ethereum_sepolia:r_,arbitrum_sepolia:LT,ethereum_localnet:D.EthereumLocalnet,arbitrum_localnet:D.ArbitrumLocalnet,base_sepolia:Ow,base:Pw,bera_testnet:zT,citrea:s_,citrea_testnet:qT,core:WT,bera:DT,monad:n_,monad_testnet:QT,hyperliquid_testnet:Nd,hyperevm:Ud,unichain:t_,corn:XT,botanix:Bw,bnbchain:VT,bnbchain_testnet:GT,alpen_testnet:Cw,hypercore:{},hypercore_testnet:{},arc_testnet:Iw,hyperliquid:Ud,megaeth:Rw,hyperevm_testnet:Nd,ink_sepolia:JT,ink:YT},Nw=t=>{for(const[e,r]of Object.entries(Pu))if(r.id===t)return e;return null},Fd=async(t,e)=>{var s,i,a;const r=Pu[t],n=await e.getChainId();if(r)try{if(r.id===n)return m.Ok({message:"Already on the network",walletClient:e});await e.switchChain({id:r.id});const o=kl({account:e.account,chain:r,transport:ay(e.transport)});return m.Ok({message:"Switched chain",walletClient:o})}catch(o){if(i_(o))if(o.code===4902||o.code===-32603)try{await e.addChain({chain:r});const c=kl({account:e.account,chain:r,transport:ay(e.transport)});return m.Ok({message:"Added network",walletClient:c})}catch{return m.Err("Failed to add network")}else if((i=(s=o.body)==null?void 0:s.method)!=null&&i.includes("wallet_switchEthereumChain")||(a=o.message)!=null&&a.includes("wallet_switchEthereumChain")){const c=kl({account:e.account,chain:r,transport:Tw()});return m.Ok({message:"Added network",walletClient:c})}else return m.Err("Failed to switch network");else return m.Err("Failed to switch network")}else return m.Err("Chain not supported")},i_=t=>typeof t=="object"&&t!=null&&("code"in t||"message"in t||"body"in t),a_=async(t,e)=>{if(!t.account)return m.Err("No account found");try{const r=await t.sendTransaction({account:t.account,to:m.with0x(e.to),value:BigInt(e.value),data:m.with0x(e.data),gas:BigInt(e.gas_limit),chain:t.chain}),n=await m.waitForTransactionReceipt(t,r);return n.ok?!n.val||n.val.status!=="success"?m.Err("Hypercore to EVM bridge transaction failed"):m.Ok(r):m.Err(n.error)}catch(r){return m.Err("Failed to execute hypercore to evm bridge: "+String(r))}};class Uw{constructor(e,r,n){this.wallet=r,this.auth=n,this.url=e instanceof m.Url?e:new m.Url(e),this.relayer=new li(this.auth,this.url)}get htlcActorAddress(){if(!this.wallet.account)throw new Error("No account found");return this.wallet.account.address}async initiate(e){if(D.isEvmOrderResponse(e))return this.initiateFromAPI(e);if(!this.wallet.account)return m.Err("No account found");if(!D.isEVM(e.source_swap.chain))return m.Err("Not an EVM chain");if(this.wallet.account.address.toLowerCase()!==e.source_swap.initiator.toLowerCase())return m.Err("Account address and order initiator mismatch");const r=e.source_swap.chain,n=await Fd(r,this.wallet);if(!n.ok)return m.Err(n.error);this.wallet=n.val.walletClient;const{source_swap:s}=e;if(!s.amount||!s.timelock||!s.redeemer||!s.secret_hash)return m.Err("Invalid order");const i=await ji(s.asset,this.url,this.auth);if(!i.ok)return m.Err(i.error);const a=D.ChainAsset.fromString(s.asset),o={redeemer:m.with0x(s.redeemer),timelock:BigInt(s.timelock),amount:BigInt(s.amount),secretHash:m.with0x(s.secret_hash)};return D.isEvmNativeToken(a.chain,a.symbol)?OT(this.wallet,{...o,htlc:i.val.htlcAddress}):BT(this.wallet,this.url,this.auth,{...o,htlc:i.val.htlcAddress,token:i.val.tokenAddress,orderId:e.order_id})}async initiateFromAPI(e){const r=Nw(e.initiate_transaction.chain_id);if(!r)return m.Err("Unsupported chain");const n=await Fd(r,this.wallet);if(!n.ok)return m.Err(n.error);if(this.wallet=n.val.walletClient,!this.wallet.account)return m.Err("No account found");if(!e.typed_data){const a=e.initiate_transaction,o=await this.wallet.sendTransaction({account:this.wallet.account,chain:this.wallet.chain,to:m.with0x(a.to),value:BigInt(a.value),data:m.with0x(a.data),gas:BigInt(a.gas_limit)}),c=await m.waitForTransactionReceipt(this.wallet,o);return c.ok?!c.val||c.val.status!=="success"?m.Err("Native initiate transaction failed"):m.Ok(o):m.Err(c.error)}if(e.core_to_evm_transfer){const a=await a_(this.wallet,e.core_to_evm_transfer);if(a.error)return m.Err(`Internal bridge failed: ${a.error}`);console.log("Internal bridge completed:",a.val)}if(e.approval_transaction){const a=await CT(this.wallet,e.approval_transaction);if(a.error)return m.Err(`Approval failed: ${a.error}`);console.log("Approval transaction completed:",a.val)}const s=await this.wallet.signTypedData({account:this.wallet.account,...e.typed_data}),i=await $m({wallet:this.wallet,attempt:()=>this.relayer.initiate(e.order_id,s)});if(i)return m.Ok(i);try{const a=Yh({address:m.with0x(e.initiate_transaction.to),abi:_w,client:this.wallet}),o=e.typed_data.message,c=await a.write.initiate([m.with0x(o.redeemer),BigInt(o.timelock),BigInt(o.amount),m.with0x(o.secretHash)],{account:this.wallet.account,chain:this.wallet.chain}),u=await m.waitForTransactionReceipt(this.wallet,c);return u.ok?!u.val||u.val.status!=="success"?m.Err("Failed to initiate via contract"):m.Ok(c):m.Err(u.error)}catch(a){return th(a)?m.Ok("already initiated"):m.Err(`Failed to initiate via contract: ${String(a)}`)}}async redeem(e,r){const n=await this.relayer.redeem(e.order_id,r);if(n.error)return m.Err(n.error);try{const s=await this.relayer.redeem(e.order_id,r);if(s.error)return m.Err(s.error);const i=Pu[e.destination_swap.chain],o=await lT({chain:i,transport:Tw()}).waitForTransactionReceipt({hash:s.val,confirmations:1,timeout:3e5});return o&&o.status==="success"?m.Ok(s.val?s.val:"Redeem hash not found"):m.Err("Redeem failed: Transaction receipt not successful")}catch(s){return m.Err(String(s))}}async refund(){return m.Err("Refund not supported")}}const Fw=[{name:"LockingContract",type:"impl",interface_name:"src::mintable_lock_interface::ILockingContract"},{name:"src::mintable_lock_interface::ILockingContract",type:"interface",items:[{name:"set_locking_contract",type:"function",inputs:[{name:"locking_contract",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"get_locking_contract",type:"function",inputs:[],outputs:[{type:"core::starknet::contract_address::ContractAddress"}],state_mutability:"view"}]},{name:"LockAndDelegate",type:"impl",interface_name:"src::mintable_lock_interface::ILockAndDelegate"},{name:"core::integer::u256",type:"struct",members:[{name:"low",type:"core::integer::u128"},{name:"high",type:"core::integer::u128"}]},{name:"src::mintable_lock_interface::ILockAndDelegate",type:"interface",items:[{name:"lock_and_delegate",type:"function",inputs:[{name:"delegatee",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"},{name:"lock_and_delegate_by_sig",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"delegatee",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"},{name:"nonce",type:"core::felt252"},{name:"expiry",type:"core::integer::u64"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"}]},{name:"MintableToken",type:"impl",interface_name:"src::mintable_token_interface::IMintableToken"},{name:"src::mintable_token_interface::IMintableToken",type:"interface",items:[{name:"permissioned_mint",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"},{name:"permissioned_burn",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"}]},{name:"MintableTokenCamelImpl",type:"impl",interface_name:"src::mintable_token_interface::IMintableTokenCamel"},{name:"src::mintable_token_interface::IMintableTokenCamel",type:"interface",items:[{name:"permissionedMint",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"},{name:"permissionedBurn",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"}]},{name:"Replaceable",type:"impl",interface_name:"src::replaceability_interface::IReplaceable"},{name:"core::array::Span::<core::felt252>",type:"struct",members:[{name:"snapshot",type:"@core::array::Array::<core::felt252>"}]},{name:"src::replaceability_interface::EICData",type:"struct",members:[{name:"eic_hash",type:"core::starknet::class_hash::ClassHash"},{name:"eic_init_data",type:"core::array::Span::<core::felt252>"}]},{name:"core::option::Option::<src::replaceability_interface::EICData>",type:"enum",variants:[{name:"Some",type:"src::replaceability_interface::EICData"},{name:"None",type:"()"}]},{name:"core::bool",type:"enum",variants:[{name:"False",type:"()"},{name:"True",type:"()"}]},{name:"src::replaceability_interface::ImplementationData",type:"struct",members:[{name:"impl_hash",type:"core::starknet::class_hash::ClassHash"},{name:"eic_data",type:"core::option::Option::<src::replaceability_interface::EICData>"},{name:"final",type:"core::bool"}]},{name:"src::replaceability_interface::IReplaceable",type:"interface",items:[{name:"get_upgrade_delay",type:"function",inputs:[],outputs:[{type:"core::integer::u64"}],state_mutability:"view"},{name:"get_impl_activation_time",type:"function",inputs:[{name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}],outputs:[{type:"core::integer::u64"}],state_mutability:"view"},{name:"add_new_implementation",type:"function",inputs:[{name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}],outputs:[],state_mutability:"external"},{name:"remove_implementation",type:"function",inputs:[{name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}],outputs:[],state_mutability:"external"},{name:"replace_to",type:"function",inputs:[{name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}],outputs:[],state_mutability:"external"}]},{name:"AccessControlImplExternal",type:"impl",interface_name:"src::access_control_interface::IAccessControl"},{name:"src::access_control_interface::IAccessControl",type:"interface",items:[{name:"has_role",type:"function",inputs:[{name:"role",type:"core::felt252"},{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::bool"}],state_mutability:"view"},{name:"get_role_admin",type:"function",inputs:[{name:"role",type:"core::felt252"}],outputs:[{type:"core::felt252"}],state_mutability:"view"}]},{name:"RolesImpl",type:"impl",interface_name:"src::roles_interface::IMinimalRoles"},{name:"src::roles_interface::IMinimalRoles",type:"interface",items:[{name:"is_governance_admin",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::bool"}],state_mutability:"view"},{name:"is_upgrade_governor",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::bool"}],state_mutability:"view"},{name:"register_governance_admin",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"remove_governance_admin",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"register_upgrade_governor",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"remove_upgrade_governor",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"renounce",type:"function",inputs:[{name:"role",type:"core::felt252"}],outputs:[],state_mutability:"external"}]},{name:"ERC20Impl",type:"impl",interface_name:"openzeppelin::token::erc20::interface::IERC20"},{name:"openzeppelin::token::erc20::interface::IERC20",type:"interface",items:[{name:"name",type:"function",inputs:[],outputs:[{type:"core::felt252"}],state_mutability:"view"},{name:"symbol",type:"function",inputs:[],outputs:[{type:"core::felt252"}],state_mutability:"view"},{name:"decimals",type:"function",inputs:[],outputs:[{type:"core::integer::u8"}],state_mutability:"view"},{name:"total_supply",type:"function",inputs:[],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"balance_of",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"allowance",type:"function",inputs:[{name:"owner",type:"core::starknet::contract_address::ContractAddress"},{name:"spender",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"transfer",type:"function",inputs:[{name:"recipient",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"transfer_from",type:"function",inputs:[{name:"sender",type:"core::starknet::contract_address::ContractAddress"},{name:"recipient",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"approve",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"}]},{name:"ERC20CamelOnlyImpl",type:"impl",interface_name:"openzeppelin::token::erc20::interface::IERC20CamelOnly"},{name:"openzeppelin::token::erc20::interface::IERC20CamelOnly",type:"interface",items:[{name:"totalSupply",type:"function",inputs:[],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"balanceOf",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"transferFrom",type:"function",inputs:[{name:"sender",type:"core::starknet::contract_address::ContractAddress"},{name:"recipient",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"}]},{name:"constructor",type:"constructor",inputs:[{name:"name",type:"core::felt252"},{name:"symbol",type:"core::felt252"},{name:"decimals",type:"core::integer::u8"},{name:"initial_supply",type:"core::integer::u256"},{name:"recipient",type:"core::starknet::contract_address::ContractAddress"},{name:"permitted_minter",type:"core::starknet::contract_address::ContractAddress"},{name:"provisional_governance_admin",type:"core::starknet::contract_address::ContractAddress"},{name:"upgrade_delay",type:"core::integer::u64"}]},{name:"increase_allowance",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"added_value",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"decrease_allowance",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"subtracted_value",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"increaseAllowance",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"addedValue",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"decreaseAllowance",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"subtractedValue",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{kind:"struct",name:"src::strk::erc20_lockable::ERC20Lockable::Transfer",type:"event",members:[{kind:"data",name:"from",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"to",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"value",type:"core::integer::u256"}]},{kind:"struct",name:"src::strk::erc20_lockable::ERC20Lockable::Approval",type:"event",members:[{kind:"data",name:"owner",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"spender",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"value",type:"core::integer::u256"}]},{kind:"struct",name:"src::replaceability_interface::ImplementationAdded",type:"event",members:[{kind:"data",name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}]},{kind:"struct",name:"src::replaceability_interface::ImplementationRemoved",type:"event",members:[{kind:"data",name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}]},{kind:"struct",name:"src::replaceability_interface::ImplementationReplaced",type:"event",members:[{kind:"data",name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}]},{kind:"struct",name:"src::replaceability_interface::ImplementationFinalized",type:"event",members:[{kind:"data",name:"impl_hash",type:"core::starknet::class_hash::ClassHash"}]},{kind:"struct",name:"src::access_control_interface::RoleGranted",type:"event",members:[{kind:"data",name:"role",type:"core::felt252"},{kind:"data",name:"account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"sender",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::access_control_interface::RoleRevoked",type:"event",members:[{kind:"data",name:"role",type:"core::felt252"},{kind:"data",name:"account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"sender",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::access_control_interface::RoleAdminChanged",type:"event",members:[{kind:"data",name:"role",type:"core::felt252"},{kind:"data",name:"previous_admin_role",type:"core::felt252"},{kind:"data",name:"new_admin_role",type:"core::felt252"}]},{kind:"struct",name:"src::roles_interface::GovernanceAdminAdded",type:"event",members:[{kind:"data",name:"added_account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"added_by",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::roles_interface::GovernanceAdminRemoved",type:"event",members:[{kind:"data",name:"removed_account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"removed_by",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::roles_interface::UpgradeGovernorAdded",type:"event",members:[{kind:"data",name:"added_account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"added_by",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::roles_interface::UpgradeGovernorRemoved",type:"event",members:[{kind:"data",name:"removed_account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"removed_by",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"enum",name:"src::strk::erc20_lockable::ERC20Lockable::Event",type:"event",variants:[{kind:"nested",name:"Transfer",type:"src::strk::erc20_lockable::ERC20Lockable::Transfer"},{kind:"nested",name:"Approval",type:"src::strk::erc20_lockable::ERC20Lockable::Approval"},{kind:"nested",name:"ImplementationAdded",type:"src::replaceability_interface::ImplementationAdded"},{kind:"nested",name:"ImplementationRemoved",type:"src::replaceability_interface::ImplementationRemoved"},{kind:"nested",name:"ImplementationReplaced",type:"src::replaceability_interface::ImplementationReplaced"},{kind:"nested",name:"ImplementationFinalized",type:"src::replaceability_interface::ImplementationFinalized"},{kind:"nested",name:"RoleGranted",type:"src::access_control_interface::RoleGranted"},{kind:"nested",name:"RoleRevoked",type:"src::access_control_interface::RoleRevoked"},{kind:"nested",name:"RoleAdminChanged",type:"src::access_control_interface::RoleAdminChanged"},{kind:"nested",name:"GovernanceAdminAdded",type:"src::roles_interface::GovernanceAdminAdded"},{kind:"nested",name:"GovernanceAdminRemoved",type:"src::roles_interface::GovernanceAdminRemoved"},{kind:"nested",name:"UpgradeGovernorAdded",type:"src::roles_interface::UpgradeGovernorAdded"},{kind:"nested",name:"UpgradeGovernorRemoved",type:"src::roles_interface::UpgradeGovernorRemoved"}]}],Mw=async(t,e,r,n,s)=>{try{const i=await Pa(t.address,e,r,s);if(!i.ok)return m.Err(i.error);if(i.val>=n)return m.Ok("Allowance already approved");const o=Qe.cairo.uint256(BigInt(n)),c=await t.execute([{contractAddress:m.with0x(e),entrypoint:"approve",calldata:[m.with0x(r),o.low,o.high]}]);await s.waitForTransaction(c.transaction_hash,{retryInterval:3e3,successStates:[Qe.TransactionExecutionStatus.SUCCEEDED]}),await m.sleep(2e3);for(let u=0;u<20;u++){const l=await Pa(t.address,e,r,s);if(!l.ok)return m.Err(l.error);if(l.val>=n)return m.Ok(c.transaction_hash);await m.sleep(2e3);let f=0n;for(let p=0;p<20;p++){const d=await Pa(t.address,e,r,s);if(!d.ok)return m.Err(d.error);if(f=d.val,f>=n)break;await m.sleep(2e3)}return f<n?m.Err("Allowance not approved"):m.Ok(c.transaction_hash)}return m.Err("Allowance not approved after transaction.")}catch(i){return m.Err(`Failed to check or approve allowance: ${i instanceof Error?i.message:String(i)}`)}},Pa=async(t,e,r,n)=>{try{const i=await new Qe.Contract({abi:Fw,address:m.with0x(e),providerOrAccount:n}).call("allowance",[m.with0x(t),m.with0x(r)]);return m.Ok(BigInt((i==null?void 0:i.toString())||"0"))}catch(s){return m.Err(`Failed to check allowance: ${s instanceof Error?s.message:String(s)}`)}},$w=async(t,e,r,n,s)=>{const i=await Pa(t,e,r,n);return i.ok?m.Ok(i.val>=s):m.Err(i.error)},jw=[{type:"impl",name:"HTLC",interface_name:"starknet_htlc::interface::IHTLC"},{type:"struct",name:"core::integer::u256",members:[{name:"low",type:"core::integer::u128"},{name:"high",type:"core::integer::u128"}]},{type:"struct",name:"starknet_htlc::htlc::HTLC::Order",members:[{name:"fulfilled_at",type:"core::integer::u128"},{name:"initiator",type:"core::starknet::contract_address::ContractAddress"},{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"initiated_at",type:"core::integer::u128"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"}]},{type:"interface",name:"starknet_htlc::interface::IHTLC",items:[{type:"function",name:"token",inputs:[],outputs:[{type:"core::starknet::contract_address::ContractAddress"}],state_mutability:"view"},{type:"function",name:"get_order",inputs:[{name:"order_id",type:"core::felt252"}],outputs:[{type:"starknet_htlc::htlc::HTLC::Order"}],state_mutability:"view"},{type:"function",name:"initiate",inputs:[{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"},{name:"secret_hash",type:"[core::integer::u128; 2]"}],outputs:[],state_mutability:"external"},{type:"function",name:"initiate_with_destination_data",inputs:[{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"},{name:"secret_hash",type:"[core::integer::u128; 2]"},{name:"destination_data",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"},{type:"function",name:"initiate_on_behalf",inputs:[{name:"initiator",type:"core::starknet::contract_address::ContractAddress"},{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"},{name:"secret_hash",type:"[core::integer::u128; 2]"}],outputs:[],state_mutability:"external"},{type:"function",name:"initiate_on_behalf_with_destination_data",inputs:[{name:"initiator",type:"core::starknet::contract_address::ContractAddress"},{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"},{name:"secret_hash",type:"[core::integer::u128; 2]"},{name:"destination_data",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"},{type:"function",name:"initiate_with_signature",inputs:[{name:"initiator",type:"core::starknet::contract_address::ContractAddress"},{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"},{name:"secret_hash",type:"[core::integer::u128; 2]"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"},{type:"function",name:"redeem",inputs:[{name:"order_id",type:"core::felt252"},{name:"secret",type:"[core::integer::u32; 8]"}],outputs:[],state_mutability:"external"},{type:"function",name:"refund",inputs:[{name:"order_id",type:"core::felt252"}],outputs:[],state_mutability:"external"},{type:"function",name:"instant_refund",inputs:[{name:"order_id",type:"core::felt252"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"}]},{type:"constructor",name:"constructor",inputs:[{name:"token",type:"core::starknet::contract_address::ContractAddress"}]},{type:"event",name:"starknet_htlc::interface::events::Initiated",kind:"struct",members:[{name:"order_id",type:"core::felt252",kind:"key"},{name:"secret_hash",type:"[core::integer::u128; 2]",kind:"data"},{name:"amount",type:"core::integer::u256",kind:"data"}]},{type:"event",name:"starknet_htlc::interface::events::Redeemed",kind:"struct",members:[{name:"order_id",type:"core::felt252",kind:"key"},{name:"secret_hash",type:"[core::integer::u128; 2]",kind:"data"},{name:"secret",type:"[core::integer::u32; 8]",kind:"data"}]},{type:"event",name:"starknet_htlc::interface::events::Refunded",kind:"struct",members:[{name:"order_id",type:"core::felt252",kind:"key"}]},{type:"event",name:"starknet_htlc::interface::events::InitiatedWithDestinationData",kind:"struct",members:[{name:"order_id",type:"core::felt252",kind:"key"},{name:"secret_hash",type:"[core::integer::u128; 2]",kind:"data"},{name:"amount",type:"core::integer::u256",kind:"data"},{name:"destination_data",type:"core::array::Array::<core::felt252>",kind:"data"}]},{type:"event",name:"starknet_htlc::htlc::HTLC::Event",kind:"enum",variants:[{name:"Initiated",type:"starknet_htlc::interface::events::Initiated",kind:"nested"},{name:"Redeemed",type:"starknet_htlc::interface::events::Redeemed",kind:"nested"},{name:"Refunded",type:"starknet_htlc::interface::events::Refunded",kind:"nested"},{name:"InitiatedWithDestinationData",type:"starknet_htlc::interface::events::InitiatedWithDestinationData",kind:"nested"}]}],o_={StarknetDomain:[{name:"name",type:"shortstring"},{name:"version",type:"shortstring"},{name:"chainId",type:"shortstring"},{name:"revision",type:"shortstring"}],Initiate:[{name:"redeemer",type:"ContractAddress"},{name:"amount",type:"u256"},{name:"timelock",type:"u128"},{name:"secretHash",type:"u128*"},{name:"verifyingContract",type:"ContractAddress"}]};class Hw{constructor(e,r,n,s,i){this.url=e instanceof m.Url?e:new m.Url(e),this.starknetProvider=new Qe.RpcProvider({nodeUrl:i||Fa[n].nodeUrl}),this.account=r,this.chainId=Fa[n].chainId,this.auth=s,this.relayer=new li(this.auth,this.url)}get htlcActorAddress(){if(!this.account.address)throw new Error("No account found");return this.account.address}async initiate(e){if(D.isStarknetOrderResponse(e))return this.initiateWithCreateOrderResponse(e);if(!this.account.address)return m.Err("No account address");const{source_swap:r}=e,{redeemer:n,amount:s}=r;if(!s||!n||!r.secret_hash||!r.timelock)return m.Err("Invalid order");const i=await ji(r.asset,this.url,this.auth);if(!i.ok)return m.Err(i.error);try{const a=new Qe.Contract({providerOrAccount:this.starknetProvider,abi:jw,address:i.val.htlcAddress}),o=await(a==null?void 0:a.token()),c=Qe.num.toHex(o),u=await $w(this.account.address,c,i.val.htlcAddress,this.starknetProvider,BigInt(r.amount));return u.error?m.Err(u.error):u.val?this.initiateRelay(e):this.approveAndInitiate(c,e)}catch(a){return m.Err(String(a))}}async approveAndInitiate(e,r){const{source_swap:n}=r,{redeemer:s,amount:i}=n,{secret_hash:a,timelock:o}=n,c=n.asset;try{const u=Qe.cairo.uint256(BigInt(i)),l={contractAddress:m.with0x(e),entrypoint:"approve",calldata:[c,u.low,u.high]},f=Qe.cairo.uint256(i),p=m.hexToU128Array(a),d={contractAddress:m.with0x(c),entrypoint:"initiate",calldata:[s,o.toString(),f.low.toString(),f.high.toString(),...p.map(g=>g.toString())]},b=await this.account.execute([l,d]);return await this.starknetProvider.waitForTransaction(b.transaction_hash,{retryInterval:2e3,successStates:[Qe.TransactionExecutionStatus.SUCCEEDED]}),m.Ok(b.transaction_hash)}catch(u){return m.Err(`Failed to approve and initiate: ${String(u)}`)}}async initiateRelay(e){const{source_swap:r}=e,n=await ji(r.asset,this.url,this.auth);if(!n.ok)return m.Err(n.error);const{redeemer:s,amount:i}=r;if(!r.secret_hash)return m.Err("Invalid order: secret_hash is undefined");const a=m.with0x(r.secret_hash),o={name:"HTLC",version:Qe.shortString.encodeShortString("2"),chainId:this.chainId,revision:Qe.TypedDataRevision.ACTIVE},c=m.hexToU128Array(a),u={domain:o,primaryType:"Initiate",types:o_,message:{redeemer:s,amount:Qe.cairo.uint256(i),timelock:e.source_swap.timelock.toString(),secretHash:c.map(l=>l.toString()),verifyingContract:n.val.htlcAddress}};try{const l=await this.account.signMessage(u),f=j0(l);if(f.error||!f.val)return m.Err(f.error||"Invalid signature");const p=await this.relayer.initiate(e.order_id,f.val);return p.ok?m.Ok(p.val):m.Err(p.error)}catch(l){return m.Err(`Failed to initiate relayer: ${String(l)}`)}}async redeem(e,r){try{const n=await this.relayer.redeem(e.order_id,r);return n.error?m.Err(n.error):m.Ok(n.val)}catch(n){return m.Err(String(n))}}async executeApprovalTransaction(e){if(!this.account.address)return m.Err("No account address");if(!e.approval_transaction)return m.Ok("No approval transaction required");try{const r=e.approval_transaction,n=await this.account.execute([{contractAddress:m.with0x(r.to),entrypoint:"approve",calldata:r.calldata}]);return await this.starknetProvider.waitForTransaction(n.transaction_hash,{retryInterval:2e3,successStates:[Qe.TransactionExecutionStatus.SUCCEEDED]}),m.Ok(n.transaction_hash)}catch(r){return console.error("executeApprovalTransaction error:",r),m.Err("Failed to execute approval: "+(r instanceof Error&&(r==null?void 0:r.message)||String(r)))}}async initiateWithCreateOrderResponse(e){const r=await this.auth.getAuthHeaders();if(!r.ok)return m.Err(r.error);if(!this.account.address)return m.Err("No account address");const n=await this.executeApprovalTransaction(e);if(n.error)return m.Err(n.error);const{typed_data:s}=e;if(s===null){const c=e.initiate_transaction;if(!c)return m.Err("No initiate_transaction found for native initiate");const u=await this.account.execute([{contractAddress:m.with0x(c.to),entrypoint:"initiate",calldata:c.calldata}]);return await this.starknetProvider.waitForTransaction(u.transaction_hash,{retryInterval:2e3,successStates:[Qe.TransactionExecutionStatus.SUCCEEDED]}),m.Ok(u.transaction_hash)}const i=await this.account.signMessage(s),a=j0(i);if(a.error)return m.Err(a.error);const o=await m.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(e.order_id).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:Array.isArray(a.val)?a.val.join(","):a.val}),headers:{...r.val,"Content-Type":"application/json"}});return o.error?m.Err(o.error):m.Ok(o.result)}async refund(){return m.Err("Refund is taken care of by the relayer")}}const c_="2WXpY8havGjfRxme9LUxtjFHTh1EfU3ur4v6wiK4KdNC",u_={name:"solana_spl_swaps",version:"0.4.0",spec:"0.1.0",description:"Created with Anchor"},l_=[{name:"initiate",docs:["Initiates the atomic swap. Funds are transferred from the initiator to the token vault.","As such, the initiator's signature is required for this instruction.","A sponsor may be involved, who pays PDA rent and transaction fees in SOL, allowing for the","initiator to participate without holding SOL. As such, the sponsor must also sign this transaction.","`swap_amount` represents the quantity of tokens to be transferred through this atomic swap","in base units of the token mint.",'E.g: A quantity of $1 represented by the token "USDC" with "6" decimals',"must be provided as 1,000,000.","`expires_in_slots` represents the number of slots after which (non-instant) refunds are allowed.","`destination_data` can hold optional information regarding the destination chain","in the atomic swap, to be emitted in the logs as-is."],discriminator:[5,63,123,113,153,75,148,14],accounts:[{name:"identity_pda",docs:["the token transfers of the `token_vault` PDA.","This PDA will be created during the first most invocation of the `initiate()` function","using the `init_if_needed` attribute, and be reused for all succeeding instructions."],writable:!0,pda:{seeds:[]}},{name:"swap_data",docs:["A PDA that maintains the on-chain state of the atomic swap throughout its lifecycle.","The choice of seeds ensure that any swap with equal `initiator` and","`secret_hash` wont be created until an existing one completes.","This PDA will be deleted upon completion of the swap."],writable:!0,pda:{seeds:[{kind:"account",path:"initiator"},{kind:"arg",path:"secret_hash"}]}},{name:"token_vault",docs:["A permanent PDA that is controlled by the program through the `identity_pda`, as implied",'by the value of the `authority` field below. As such, it serves as the "vault" by escrowing tokens',"of type `mint` for the atomic swap.","It is intended to be reused for all swaps involving the same mint.","Just like `identity_pda`, it will be created during the first most invocation of `initiate()`","of every distinct mint using the `init_if_needed` attribute."],writable:!0,pda:{seeds:[{kind:"account",path:"mint"}]}},{name:"initiator",docs:["The initiator of the atomic swap. They must sign this transaction."],signer:!0},{name:"initiator_token_account",docs:["The token account of the initiator"],writable:!0},{name:"mint",docs:["The mint of the tokens involved in this swap. As this is a parameter, this program can thus be reused","for atomic swaps with different mints."]},{name:"sponsor",docs:["Any entity that pays the PDA rent.","Upon completion of the swap, the PDA rent refund resulting from the","deletion of `swap_data` will be refunded to this address."],writable:!0,signer:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"},{name:"system_program",address:"11111111111111111111111111111111"}],args:[{name:"expires_in_slots",type:"u64"},{name:"redeemer",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}},{name:"swap_amount",type:"u64"},{name:"destination_data",type:{option:"bytes"}}]},{name:"instant_refund",docs:["Funds are returned to the initiator, with the redeemer's consent.","As such, the redeemer's signature is required for this instruction.","This allows for refunds before the expiry slot."],discriminator:[211,202,103,41,183,147,59,251],accounts:[{name:"identity_pda",pda:{seeds:[]}},{name:"swap_data",docs:["The PDA holding the state information of the atomic swap. Will be closed upon successful execution","and the resulting rent refund will be sent to the sponsor."],writable:!0},{name:"token_vault",docs:["A token account controlled by the program, escrowing the tokens for this atomic swap"],writable:!0},{name:"initiator_token_account",writable:!0},{name:"redeemer",docs:["The redeemer of the atomic swap. They must sign this transaction."],writable:!0,signer:!0},{name:"sponsor",writable:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"}],args:[]},{name:"redeem",docs:["Funds are transferred to the redeemer. This instruction does not require any signatures."],discriminator:[184,12,86,149,70,196,97,225],accounts:[{name:"identity_pda",pda:{seeds:[]}},{name:"swap_data",docs:["The PDA holding the state information of the atomic swap. Will be closed upon successful execution","and the resulting rent refund will be sent to the sponsor."],writable:!0},{name:"token_vault",docs:["A token account controlled by the program, escrowing the tokens for this atomic swap"],writable:!0},{name:"redeemer_token_account",writable:!0},{name:"sponsor",writable:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"}],args:[{name:"secret",type:{array:["u8",32]}}]},{name:"refund",docs:["Funds are returned to the initiator, given that no redeems have occured","and the expiry slot has been reached.","This instruction does not require any signatures."],discriminator:[2,96,183,251,63,208,46,46],accounts:[{name:"identity_pda",pda:{seeds:[]}},{name:"swap_data",docs:["The PDA holding the state information of the atomic swap. Will be closed upon successful execution","and the resulting rent refund will be sent to the sponsor."],writable:!0},{name:"token_vault",docs:["A token account controlled by the program, escrowing the tokens for this atomic swap"],writable:!0},{name:"initiator_token_account",writable:!0},{name:"sponsor",writable:!0},{name:"token_program",address:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"}],args:[]}],f_=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],d_=[{name:"Initiated",discriminator:[6,108,212,91,67,60,207,221]},{name:"InstantRefunded",discriminator:[220,50,18,207,183,232,218,25]},{name:"Redeemed",discriminator:[14,29,183,71,31,165,107,38]},{name:"Refunded",discriminator:[35,103,149,246,196,123,221,99]}],h_=[{code:6e3,name:"InvalidRedeemer",msg:"The provider redeemer is not the original redeemer of this swap"},{code:6001,name:"InvalidSecret",msg:"The provided secret does not correspond to the secret hash of this swap"},{code:6002,name:"InvalidSponsor",msg:"The provided sponsor is not the original sponsor of this swap"},{code:6003,name:"RefundBeforeExpiry",msg:"Attempt to perform a refund before expiry time"}],p_=[{name:"Initiated",docs:["Represents the initiated state of the swap where the initiator has deposited funds into the vault"],type:{kind:"struct",fields:[{name:"swap_amount",docs:["The quantity of tokens transferred through this atomic swap in base units of the token mint.",'E.g: A quantity of $1 represented by the token "USDC" with "6" decimals will be represented as 1,000,000.'],type:"u64"},{name:"expires_in_slots",docs:["`expires_in_slots` represents the number of slots after which (non-instant) refunds are allowed"],type:"u64"},{name:"initiator",type:"pubkey"},{name:"mint",type:"pubkey"},{name:"redeemer",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}},{name:"destination_data",docs:["Information regarding the destination chain in the atomic swap"],type:{option:"bytes"}}]}},{name:"InstantRefunded",docs:["Represents the instant refund state of the swap, where the initiator has withdrawn funds the vault","with the redeemer's consent"],type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}},{name:"Redeemed",docs:["Represents the redeemed state of the swap, where the redeemer has withdrawn funds from the vault"],type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret",type:{array:["u8",32]}}]}},{name:"Refunded",docs:["Represents the refund state of the swap, where the initiator has withdrawn funds from the vault past expiry"],type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}},{name:"SwapAccount",docs:["Stores the state information of the atomic swap on-chain"],type:{kind:"struct",fields:[{name:"expiry_slot",docs:["The exact slot after which (non-instant) refunds are allowed"],type:"u64"},{name:"initiator",docs:["The initiator of the atomic swap"],type:"pubkey"},{name:"redeemer",docs:["The redeemer of the atomic swap"],type:"pubkey"},{name:"secret_hash",docs:["The secret hash associated with the atomic swap"],type:{array:["u8",32]}},{name:"swap_amount",docs:["The quantity tokens to be transferred through this atomic swap","in base units of the token mint.",'E.g: A quantity of $1 represented by the token "USDC" with "6" decimals',"must be provided as 1,000,000."],type:"u64"},{name:"identity_pda_bump",docs:["The bump associated with the identity pda.","This is needed by the program to authorize token transfers via the token vault."],type:"u8"},{name:"sponsor",docs:["The entity that paid the rent fees for the creation of this PDA.","This will be referenced during the refund of the same upon closing this PDA."],type:"pubkey"}]}}],oy={address:c_,metadata:u_,instructions:l_,accounts:f_,events:d_,errors:h_,types:p_},y_="2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",m_={name:"solana_native_swaps",version:"0.3.0",spec:"0.1.0",description:"Created with Anchor"},b_=[{name:"initiate",discriminator:[5,63,123,113,153,75,148,14],accounts:[{name:"swap_account",writable:!0,pda:{seeds:[{kind:"const",value:[115,119,97,112,95,97,99,99,111,117,110,116]},{kind:"account",path:"initiator"},{kind:"arg",path:"secret_hash"}]}},{name:"initiator",docs:["Initiator must sign this transaction"],writable:!0,signer:!0},{name:"system_program",address:"11111111111111111111111111111111"}],args:[{name:"amount_lamports",type:"u64"},{name:"expires_in_slots",type:"u64"},{name:"redeemer",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]},{name:"instant_refund",discriminator:[211,202,103,41,183,147,59,251],accounts:[{name:"swap_account",writable:!0},{name:"initiator",writable:!0},{name:"redeemer",docs:["Redeemer must sign this transaction"],signer:!0}],args:[]},{name:"redeem",discriminator:[184,12,86,149,70,196,97,225],accounts:[{name:"swap_account",writable:!0},{name:"initiator",docs:["This is included here for the PDA rent refund using the `close` attribute above"],writable:!0},{name:"redeemer",writable:!0}],args:[{name:"secret",type:{array:["u8",32]}}]},{name:"refund",discriminator:[2,96,183,251,63,208,46,46],accounts:[{name:"swap_account",writable:!0},{name:"initiator",writable:!0}],args:[]}],g_=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],w_=[{name:"Initiated",discriminator:[6,108,212,91,67,60,207,221]},{name:"InstantRefunded",discriminator:[220,50,18,207,183,232,218,25]},{name:"Redeemed",discriminator:[14,29,183,71,31,165,107,38]},{name:"Refunded",discriminator:[35,103,149,246,196,123,221,99]}],v_=[{code:6e3,name:"InvalidInitiator",msg:"The provided initiator is not the original initiator of this swap account"},{code:6001,name:"InvalidRedeemer",msg:"The provided redeemer is not the original redeemer of this swap amount"},{code:6002,name:"InvalidSecret",msg:"The provided secret does not correspond to the secret hash in the swap account"},{code:6003,name:"RefundBeforeExpiry",msg:"Attempt to perform a refund before expiry time"}],E_=[{name:"Initiated",type:{kind:"struct",fields:[{name:"amount_lamports",type:"u64"},{name:"expires_in_slots",type:"u64"},{name:"initiator",type:"pubkey"},{name:"redeemer",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}},{name:"InstantRefunded",type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}},{name:"Redeemed",type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret",type:{array:["u8",32]}}]}},{name:"Refunded",type:{kind:"struct",fields:[{name:"initiator",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}},{name:"SwapAccount",type:{kind:"struct",fields:[{name:"amount_lamports",type:"u64"},{name:"expiry_slot",type:"u64"},{name:"initiator",type:"pubkey"},{name:"redeemer",type:"pubkey"},{name:"secret_hash",type:{array:["u8",32]}}]}}],Md={address:y_,metadata:m_,instructions:b_,accounts:g_,events:w_,errors:v_,types:E_};var _n={},Ou={};Object.defineProperty(Ou,"__esModule",{value:!0});Ou.encode=A_;Ou.decode=S_;const cy=ii;function A_(t){return t.reduce((e,r)=>e+r.toString(16).padStart(2,"0"),"0x")}function S_(t){t.indexOf("0x")===0&&(t=t.substr(2)),t.length%2===1&&(t="0"+t);let e=t.match(/.{2}/g);return e===null?cy.Buffer.from([]):cy.Buffer.from(e.map(r=>parseInt(r,16)))}var Bu={},ri={},Tl;Object.defineProperty(ri,"__esModule",{value:!0});ri.isVersionedTransaction=ri.isBrowser=void 0;ri.chunks=x_;ri.isBrowser=process.env.ANCHOR_BROWSER||typeof window<"u"&&!(!((Tl=window.process)===null||Tl===void 0)&&Tl.hasOwnProperty("type"));function x_(t,e){return Array.apply(0,new Array(Math.ceil(t.length/e))).map((r,n)=>t.slice(n*e,(n+1)*e))}const k_=t=>"version"in t;ri.isVersionedTransaction=k_;var _l={},Il={},Pl,uy;function Lw(){return uy||(uy=1,Pl=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var s=42;e[r]=s;for(var i in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var a=Object.getOwnPropertySymbols(e);if(a.length!==1||a[0]!==r||!Object.prototype.propertyIsEnumerable.call(e,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var o=Object.getOwnPropertyDescriptor(e,r);if(o.value!==s||o.enumerable!==!0)return!1}return!0}),Pl}var Ol,ly;function Cu(){if(ly)return Ol;ly=1;var t=Lw();return Ol=function(){return t()&&!!Symbol.toStringTag},Ol}var Bl,fy;function Dw(){return fy||(fy=1,Bl=Object),Bl}var Cl,dy;function T_(){return dy||(dy=1,Cl=Error),Cl}var Rl,hy;function __(){return hy||(hy=1,Rl=EvalError),Rl}var Nl,py;function I_(){return py||(py=1,Nl=RangeError),Nl}var Ul,yy;function P_(){return yy||(yy=1,Ul=ReferenceError),Ul}var Fl,my;function zw(){return my||(my=1,Fl=SyntaxError),Fl}var Ml,by;function Ho(){return by||(by=1,Ml=TypeError),Ml}var $l,gy;function O_(){return gy||(gy=1,$l=URIError),$l}var jl,wy;function B_(){return wy||(wy=1,jl=Math.abs),jl}var Hl,vy;function C_(){return vy||(vy=1,Hl=Math.floor),Hl}var Ll,Ey;function R_(){return Ey||(Ey=1,Ll=Math.max),Ll}var Dl,Ay;function N_(){return Ay||(Ay=1,Dl=Math.min),Dl}var zl,Sy;function U_(){return Sy||(Sy=1,zl=Math.pow),zl}var Vl,xy;function F_(){return xy||(xy=1,Vl=Math.round),Vl}var Gl,ky;function M_(){return ky||(ky=1,Gl=Number.isNaN||function(e){return e!==e}),Gl}var ql,Ty;function $_(){if(Ty)return ql;Ty=1;var t=M_();return ql=function(r){return t(r)||r===0?r:r<0?-1:1},ql}var Wl,_y;function j_(){return _y||(_y=1,Wl=Object.getOwnPropertyDescriptor),Wl}var Kl,Iy;function sa(){if(Iy)return Kl;Iy=1;var t=j_();if(t)try{t([],"length")}catch{t=null}return Kl=t,Kl}var Xl,Py;function Ru(){if(Py)return Xl;Py=1;var t=Object.defineProperty||!1;if(t)try{t({},"a",{value:1})}catch{t=!1}return Xl=t,Xl}var Yl,Oy;function H_(){if(Oy)return Yl;Oy=1;var t=typeof Symbol<"u"&&Symbol,e=Lw();return Yl=function(){return typeof t!="function"||typeof Symbol!="function"||typeof t("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},Yl}var Jl,By;function Vw(){return By||(By=1,Jl=typeof Reflect<"u"&&Reflect.getPrototypeOf||null),Jl}var Zl,Cy;function Gw(){if(Cy)return Zl;Cy=1;var t=Dw();return Zl=t.getPrototypeOf||null,Zl}var Ql,Ry;function L_(){if(Ry)return Ql;Ry=1;var t="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,r=Math.max,n="[object Function]",s=function(c,u){for(var l=[],f=0;f<c.length;f+=1)l[f]=c[f];for(var p=0;p<u.length;p+=1)l[p+c.length]=u[p];return l},i=function(c,u){for(var l=[],f=u,p=0;f<c.length;f+=1,p+=1)l[p]=c[f];return l},a=function(o,c){for(var u="",l=0;l<o.length;l+=1)u+=o[l],l+1<o.length&&(u+=c);return u};return Ql=function(c){var u=this;if(typeof u!="function"||e.apply(u)!==n)throw new TypeError(t+u);for(var l=i(arguments,1),f,p=function(){if(this instanceof f){var S=u.apply(this,s(l,arguments));return Object(S)===S?S:this}return u.apply(c,s(l,arguments))},d=r(0,u.length-l.length),b=[],g=0;g<d;g++)b[g]="$"+g;if(f=Function("binder","return function ("+a(b,",")+"){ return binder.apply(this,arguments); }")(p),u.prototype){var A=function(){};A.prototype=u.prototype,f.prototype=new A,A.prototype=null}return f},Ql}var ef,Ny;function Lo(){if(Ny)return ef;Ny=1;var t=L_();return ef=Function.prototype.bind||t,ef}var tf,Uy;function h0(){return Uy||(Uy=1,tf=Function.prototype.call),tf}var rf,Fy;function p0(){return Fy||(Fy=1,rf=Function.prototype.apply),rf}var nf,My;function D_(){return My||(My=1,nf=typeof Reflect<"u"&&Reflect&&Reflect.apply),nf}var sf,$y;function qw(){if($y)return sf;$y=1;var t=Lo(),e=p0(),r=h0(),n=D_();return sf=n||t.call(r,e),sf}var af,jy;function y0(){if(jy)return af;jy=1;var t=Lo(),e=Ho(),r=h0(),n=qw();return af=function(i){if(i.length<1||typeof i[0]!="function")throw new e("a function is required");return n(t,r,i)},af}var of,Hy;function z_(){if(Hy)return of;Hy=1;var t=y0(),e=sa(),r;try{r=[].__proto__===Array.prototype}catch(a){if(!a||typeof a!="object"||!("code"in a)||a.code!=="ERR_PROTO_ACCESS")throw a}var n=!!r&&e&&e(Object.prototype,"__proto__"),s=Object,i=s.getPrototypeOf;return of=n&&typeof n.get=="function"?t([n.get]):typeof i=="function"?function(o){return i(o==null?o:s(o))}:!1,of}var cf,Ly;function m0(){if(Ly)return cf;Ly=1;var t=Vw(),e=Gw(),r=z_();return cf=t?function(s){return t(s)}:e?function(s){if(!s||typeof s!="object"&&typeof s!="function")throw new TypeError("getProto: not an object");return e(s)}:r?function(s){return r(s)}:null,cf}var uf,Dy;function Ww(){if(Dy)return uf;Dy=1;var t=Function.prototype.call,e=Object.prototype.hasOwnProperty,r=Lo();return uf=r.call(t,e),uf}var lf,zy;function Kw(){if(zy)return lf;zy=1;var t,e=Dw(),r=T_(),n=__(),s=I_(),i=P_(),a=zw(),o=Ho(),c=O_(),u=B_(),l=C_(),f=R_(),p=N_(),d=U_(),b=F_(),g=$_(),A=Function,S=function(ie){try{return A('"use strict"; return ('+ie+").constructor;")()}catch{}},T=sa(),v=Ru(),w=function(){throw new o},x=T?function(){try{return arguments.callee,w}catch{try{return T(arguments,"callee").get}catch{return w}}}():w,_=H_()(),I=m0(),N=Gw(),C=Vw(),j=p0(),M=h0(),H={},V=typeof Uint8Array>"u"||!I?t:I(Uint8Array),Q={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?t:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?t:ArrayBuffer,"%ArrayIteratorPrototype%":_&&I?I([][Symbol.iterator]()):t,"%AsyncFromSyncIteratorPrototype%":t,"%AsyncFunction%":H,"%AsyncGenerator%":H,"%AsyncGeneratorFunction%":H,"%AsyncIteratorPrototype%":H,"%Atomics%":typeof Atomics>"u"?t:Atomics,"%BigInt%":typeof BigInt>"u"?t:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?t:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?t:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?t:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":r,"%eval%":eval,"%EvalError%":n,"%Float16Array%":typeof Float16Array>"u"?t:Float16Array,"%Float32Array%":typeof Float32Array>"u"?t:Float32Array,"%Float64Array%":typeof Float64Array>"u"?t:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?t:FinalizationRegistry,"%Function%":A,"%GeneratorFunction%":H,"%Int8Array%":typeof Int8Array>"u"?t:Int8Array,"%Int16Array%":typeof Int16Array>"u"?t:Int16Array,"%Int32Array%":typeof Int32Array>"u"?t:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":_&&I?I(I([][Symbol.iterator]())):t,"%JSON%":typeof JSON=="object"?JSON:t,"%Map%":typeof Map>"u"?t:Map,"%MapIteratorPrototype%":typeof Map>"u"||!_||!I?t:I(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":e,"%Object.getOwnPropertyDescriptor%":T,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?t:Promise,"%Proxy%":typeof Proxy>"u"?t:Proxy,"%RangeError%":s,"%ReferenceError%":i,"%Reflect%":typeof Reflect>"u"?t:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?t:Set,"%SetIteratorPrototype%":typeof Set>"u"||!_||!I?t:I(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?t:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":_&&I?I(""[Symbol.iterator]()):t,"%Symbol%":_?Symbol:t,"%SyntaxError%":a,"%ThrowTypeError%":x,"%TypedArray%":V,"%TypeError%":o,"%Uint8Array%":typeof Uint8Array>"u"?t:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?t:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?t:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?t:Uint32Array,"%URIError%":c,"%WeakMap%":typeof WeakMap>"u"?t:WeakMap,"%WeakRef%":typeof WeakRef>"u"?t:WeakRef,"%WeakSet%":typeof WeakSet>"u"?t:WeakSet,"%Function.prototype.call%":M,"%Function.prototype.apply%":j,"%Object.defineProperty%":v,"%Object.getPrototypeOf%":N,"%Math.abs%":u,"%Math.floor%":l,"%Math.max%":f,"%Math.min%":p,"%Math.pow%":d,"%Math.round%":b,"%Math.sign%":g,"%Reflect.getPrototypeOf%":C};if(I)try{null.error}catch(ie){var U=I(I(ie));Q["%Error.prototype%"]=U}var K=function ie(se){var be;if(se==="%AsyncFunction%")be=S("async function () {}");else if(se==="%GeneratorFunction%")be=S("function* () {}");else if(se==="%AsyncGeneratorFunction%")be=S("async function* () {}");else if(se==="%AsyncGenerator%"){var ge=ie("%AsyncGeneratorFunction%");ge&&(be=ge.prototype)}else if(se==="%AsyncIteratorPrototype%"){var Ee=ie("%AsyncGenerator%");Ee&&I&&(be=I(Ee.prototype))}return Q[se]=be,be},ee={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},q=Lo(),O=Ww(),L=q.call(M,Array.prototype.concat),J=q.call(j,Array.prototype.splice),B=q.call(M,String.prototype.replace),F=q.call(M,String.prototype.slice),z=q.call(M,RegExp.prototype.exec),ne=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,ae=/\\(\\)?/g,fe=function(se){var be=F(se,0,1),ge=F(se,-1);if(be==="%"&&ge!=="%")throw new a("invalid intrinsic syntax, expected closing `%`");if(ge==="%"&&be!=="%")throw new a("invalid intrinsic syntax, expected opening `%`");var Ee=[];return B(se,ne,function(Te,nt,Ce,Hr){Ee[Ee.length]=Ce?B(Hr,ae,"$1"):nt||Te}),Ee},ue=function(se,be){var ge=se,Ee;if(O(ee,ge)&&(Ee=ee[ge],ge="%"+Ee[0]+"%"),O(Q,ge)){var Te=Q[ge];if(Te===H&&(Te=K(ge)),typeof Te>"u"&&!be)throw new o("intrinsic "+se+" exists, but is not available. Please file an issue!");return{alias:Ee,name:ge,value:Te}}throw new a("intrinsic "+se+" does not exist!")};return lf=function(se,be){if(typeof se!="string"||se.length===0)throw new o("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof be!="boolean")throw new o('"allowMissing" argument must be a boolean');if(z(/^%?[^%]*%?$/,se)===null)throw new a("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var ge=fe(se),Ee=ge.length>0?ge[0]:"",Te=ue("%"+Ee+"%",be),nt=Te.name,Ce=Te.value,Hr=!1,ks=Te.alias;ks&&(Ee=ks[0],J(ge,L([0,1],ks)));for(var X=1,Lr=!0;X<ge.length;X+=1){var _t=ge[X],It=F(_t,0,1),Hn=F(_t,-1);if((It==='"'||It==="'"||It==="`"||Hn==='"'||Hn==="'"||Hn==="`")&&It!==Hn)throw new a("property names with quotes must have matching quotes");if((_t==="constructor"||!Lr)&&(Hr=!0),Ee+="."+_t,nt="%"+Ee+"%",O(Q,nt))Ce=Q[nt];else if(Ce!=null){if(!(_t in Ce)){if(!be)throw new o("base intrinsic for "+se+" exists, but the property is not available.");return}if(T&&X+1>=ge.length){var di=T(Ce,_t);Lr=!!di,Lr&&"get"in di&&!("originalValue"in di.get)?Ce=di.get:Ce=Ce[_t]}else Lr=O(Ce,_t),Ce=Ce[_t];Lr&&!Hr&&(Q[nt]=Ce)}}return Ce},lf}var ff,Vy;function Do(){if(Vy)return ff;Vy=1;var t=Kw(),e=y0(),r=e([t("%String.prototype.indexOf%")]);return ff=function(s,i){var a=t(s,!!i);return typeof a=="function"&&r(s,".prototype.")>-1?e([a]):a},ff}var df,Gy;function V_(){if(Gy)return df;Gy=1;var t=Cu()(),e=Do(),r=e("Object.prototype.toString"),n=function(o){return t&&o&&typeof o=="object"&&Symbol.toStringTag in o?!1:r(o)==="[object Arguments]"},s=function(o){return n(o)?!0:o!==null&&typeof o=="object"&&"length"in o&&typeof o.length=="number"&&o.length>=0&&r(o)!=="[object Array]"&&"callee"in o&&r(o.callee)==="[object Function]"},i=function(){return n(arguments)}();return n.isLegacyArguments=s,df=i?n:s,df}var hf,qy;function G_(){if(qy)return hf;qy=1;var t=Do(),e=Cu()(),r=Ww(),n=sa(),s;if(e){var i=t("RegExp.prototype.exec"),a={},o=function(){throw a},c={toString:o,valueOf:o};typeof Symbol.toPrimitive=="symbol"&&(c[Symbol.toPrimitive]=o),s=function(p){if(!p||typeof p!="object")return!1;var d=n(p,"lastIndex"),b=d&&r(d,"value");if(!b)return!1;try{i(p,c)}catch(g){return g===a}}}else{var u=t("Object.prototype.toString"),l="[object RegExp]";s=function(p){return!p||typeof p!="object"&&typeof p!="function"?!1:u(p)===l}}return hf=s,hf}var pf,Wy;function q_(){if(Wy)return pf;Wy=1;var t=Do(),e=G_(),r=t("RegExp.prototype.exec"),n=Ho();return pf=function(i){if(!e(i))throw new n("`regex` must be a RegExp");return function(o){return r(i,o)!==null}},pf}var yf,Ky;function W_(){if(Ky)return yf;Ky=1;const t=(function*(){}).constructor;return yf=()=>t,yf}var mf,Xy;function K_(){if(Xy)return mf;Xy=1;var t=Do(),e=q_(),r=e(/^\s*(?:function)?\*/),n=Cu()(),s=m0(),i=t("Object.prototype.toString"),a=t("Function.prototype.toString"),o=W_();return mf=function(u){if(typeof u!="function")return!1;if(r(a(u)))return!0;if(!n){var l=i(u);return l==="[object GeneratorFunction]"}if(!s)return!1;var f=o();return f&&s(u)===f.prototype},mf}var bf,Yy;function X_(){if(Yy)return bf;Yy=1;var t=Function.prototype.toString,e=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,r,n;if(typeof e=="function"&&typeof Object.defineProperty=="function")try{r=Object.defineProperty({},"length",{get:function(){throw n}}),n={},e(function(){throw 42},null,r)}catch(T){T!==n&&(e=null)}else e=null;var s=/^\s*class\b/,i=function(v){try{var w=t.call(v);return s.test(w)}catch{return!1}},a=function(v){try{return i(v)?!1:(t.call(v),!0)}catch{return!1}},o=Object.prototype.toString,c="[object Object]",u="[object Function]",l="[object GeneratorFunction]",f="[object HTMLAllCollection]",p="[object HTML document.all class]",d="[object HTMLCollection]",b=typeof Symbol=="function"&&!!Symbol.toStringTag,g=!(0 in[,]),A=function(){return!1};if(typeof document=="object"){var S=document.all;o.call(S)===o.call(document.all)&&(A=function(v){if((g||!v)&&(typeof v>"u"||typeof v=="object"))try{var w=o.call(v);return(w===f||w===p||w===d||w===c)&&v("")==null}catch{}return!1})}return bf=e?function(v){if(A(v))return!0;if(!v||typeof v!="function"&&typeof v!="object")return!1;try{e(v,null,r)}catch(w){if(w!==n)return!1}return!i(v)&&a(v)}:function(v){if(A(v))return!0;if(!v||typeof v!="function"&&typeof v!="object")return!1;if(b)return a(v);if(i(v))return!1;var w=o.call(v);return w!==u&&w!==l&&!/^\[object HTML/.test(w)?!1:a(v)},bf}var gf,Jy;function Y_(){if(Jy)return gf;Jy=1;var t=X_(),e=Object.prototype.toString,r=Object.prototype.hasOwnProperty,n=function(c,u,l){for(var f=0,p=c.length;f<p;f++)r.call(c,f)&&(l==null?u(c[f],f,c):u.call(l,c[f],f,c))},s=function(c,u,l){for(var f=0,p=c.length;f<p;f++)l==null?u(c.charAt(f),f,c):u.call(l,c.charAt(f),f,c)},i=function(c,u,l){for(var f in c)r.call(c,f)&&(l==null?u(c[f],f,c):u.call(l,c[f],f,c))};function a(o){return e.call(o)==="[object Array]"}return gf=function(c,u,l){if(!t(u))throw new TypeError("iterator must be a function");var f;arguments.length>=3&&(f=l),a(c)?n(c,u,f):typeof c=="string"?s(c,u,f):i(c,u,f)},gf}var wf,Zy;function J_(){return Zy||(Zy=1,wf=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]),wf}var vf,Qy;function Z_(){if(Qy)return vf;Qy=1;var t=J_(),e=typeof globalThis>"u"?sn:globalThis;return vf=function(){for(var n=[],s=0;s<t.length;s++)typeof e[t[s]]=="function"&&(n[n.length]=t[s]);return n},vf}var Ef={exports:{}},Af,em;function Q_(){if(em)return Af;em=1;var t=Ru(),e=zw(),r=Ho(),n=sa();return Af=function(i,a,o){if(!i||typeof i!="object"&&typeof i!="function")throw new r("`obj` must be an object or a function`");if(typeof a!="string"&&typeof a!="symbol")throw new r("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new r("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new r("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new r("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new r("`loose`, if provided, must be a boolean");var c=arguments.length>3?arguments[3]:null,u=arguments.length>4?arguments[4]:null,l=arguments.length>5?arguments[5]:null,f=arguments.length>6?arguments[6]:!1,p=!!n&&n(i,a);if(t)t(i,a,{configurable:l===null&&p?p.configurable:!l,enumerable:c===null&&p?p.enumerable:!c,value:o,writable:u===null&&p?p.writable:!u});else if(f||!c&&!u&&!l)i[a]=o;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},Af}var Sf,tm;function eI(){if(tm)return Sf;tm=1;var t=Ru(),e=function(){return!!t};return e.hasArrayLengthDefineBug=function(){if(!t)return null;try{return t([],"length",{value:1}).length!==1}catch{return!0}},Sf=e,Sf}var xf,rm;function tI(){if(rm)return xf;rm=1;var t=Kw(),e=Q_(),r=eI()(),n=sa(),s=Ho(),i=t("%Math.floor%");return xf=function(o,c){if(typeof o!="function")throw new s("`fn` is not a function");if(typeof c!="number"||c<0||c>4294967295||i(c)!==c)throw new s("`length` must be a positive 32-bit integer");var u=arguments.length>2&&!!arguments[2],l=!0,f=!0;if("length"in o&&n){var p=n(o,"length");p&&!p.configurable&&(l=!1),p&&!p.writable&&(f=!1)}return(l||f||!u)&&(r?e(o,"length",c,!0,!0):e(o,"length",c)),o},xf}var kf,nm;function rI(){if(nm)return kf;nm=1;var t=Lo(),e=p0(),r=qw();return kf=function(){return r(t,e,arguments)},kf}var sm;function nI(){return sm||(sm=1,function(t){var e=tI(),r=Ru(),n=y0(),s=rI();t.exports=function(a){var o=n(arguments),c=a.length-(arguments.length-1);return e(o,1+(c>0?c:0),!0)},r?r(t.exports,"apply",{value:s}):t.exports.apply=s}(Ef)),Ef.exports}var Tf,im;function Xw(){if(im)return Tf;im=1;var t=Y_(),e=Z_(),r=nI(),n=Do(),s=sa(),i=m0(),a=n("Object.prototype.toString"),o=Cu()(),c=typeof globalThis>"u"?sn:globalThis,u=e(),l=n("String.prototype.slice"),f=n("Array.prototype.indexOf",!0)||function(A,S){for(var T=0;T<A.length;T+=1)if(A[T]===S)return T;return-1},p={__proto__:null};o&&s&&i?t(u,function(g){var A=new c[g];if(Symbol.toStringTag in A&&i){var S=i(A),T=s(S,Symbol.toStringTag);if(!T&&S){var v=i(S);T=s(v,Symbol.toStringTag)}if(T&&T.get){var w=r(T.get);p["$"+g]=w}}}):t(u,function(g){var A=new c[g],S=A.slice||A.set;if(S){var T=r(S);p["$"+g]=T}});var d=function(A){var S=!1;return t(p,function(T,v){if(!S)try{"$"+T(A)===v&&(S=l(v,1))}catch{}}),S},b=function(A){var S=!1;return t(p,function(T,v){if(!S)try{T(A),S=l(v,1)}catch{}}),S};return Tf=function(A){if(!A||typeof A!="object")return!1;if(!o){var S=l(a(A),8,-1);return f(u,S)>-1?S:S!=="Object"?!1:b(A)}return s?d(A):null},Tf}var _f,am;function sI(){if(am)return _f;am=1;var t=Xw();return _f=function(r){return!!t(r)},_f}var om;function iI(){return om||(om=1,function(t){var e=V_(),r=K_(),n=Xw(),s=sI();function i(X){return X.call.bind(X)}var a=typeof BigInt<"u",o=typeof Symbol<"u",c=i(Object.prototype.toString),u=i(Number.prototype.valueOf),l=i(String.prototype.valueOf),f=i(Boolean.prototype.valueOf);if(a)var p=i(BigInt.prototype.valueOf);if(o)var d=i(Symbol.prototype.valueOf);function b(X,Lr){if(typeof X!="object")return!1;try{return Lr(X),!0}catch{return!1}}t.isArgumentsObject=e,t.isGeneratorFunction=r,t.isTypedArray=s;function g(X){return typeof Promise<"u"&&X instanceof Promise||X!==null&&typeof X=="object"&&typeof X.then=="function"&&typeof X.catch=="function"}t.isPromise=g;function A(X){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(X):s(X)||F(X)}t.isArrayBufferView=A;function S(X){return n(X)==="Uint8Array"}t.isUint8Array=S;function T(X){return n(X)==="Uint8ClampedArray"}t.isUint8ClampedArray=T;function v(X){return n(X)==="Uint16Array"}t.isUint16Array=v;function w(X){return n(X)==="Uint32Array"}t.isUint32Array=w;function x(X){return n(X)==="Int8Array"}t.isInt8Array=x;function _(X){return n(X)==="Int16Array"}t.isInt16Array=_;function I(X){return n(X)==="Int32Array"}t.isInt32Array=I;function N(X){return n(X)==="Float32Array"}t.isFloat32Array=N;function C(X){return n(X)==="Float64Array"}t.isFloat64Array=C;function j(X){return n(X)==="BigInt64Array"}t.isBigInt64Array=j;function M(X){return n(X)==="BigUint64Array"}t.isBigUint64Array=M;function H(X){return c(X)==="[object Map]"}H.working=typeof Map<"u"&&H(new Map);function V(X){return typeof Map>"u"?!1:H.working?H(X):X instanceof Map}t.isMap=V;function Q(X){return c(X)==="[object Set]"}Q.working=typeof Set<"u"&&Q(new Set);function U(X){return typeof Set>"u"?!1:Q.working?Q(X):X instanceof Set}t.isSet=U;function K(X){return c(X)==="[object WeakMap]"}K.working=typeof WeakMap<"u"&&K(new WeakMap);function ee(X){return typeof WeakMap>"u"?!1:K.working?K(X):X instanceof WeakMap}t.isWeakMap=ee;function q(X){return c(X)==="[object WeakSet]"}q.working=typeof WeakSet<"u"&&q(new WeakSet);function O(X){return q(X)}t.isWeakSet=O;function L(X){return c(X)==="[object ArrayBuffer]"}L.working=typeof ArrayBuffer<"u"&&L(new ArrayBuffer);function J(X){return typeof ArrayBuffer>"u"?!1:L.working?L(X):X instanceof ArrayBuffer}t.isArrayBuffer=J;function B(X){return c(X)==="[object DataView]"}B.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&B(new DataView(new ArrayBuffer(1),0,1));function F(X){return typeof DataView>"u"?!1:B.working?B(X):X instanceof DataView}t.isDataView=F;var z=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function ne(X){return c(X)==="[object SharedArrayBuffer]"}function ae(X){return typeof z>"u"?!1:(typeof ne.working>"u"&&(ne.working=ne(new z)),ne.working?ne(X):X instanceof z)}t.isSharedArrayBuffer=ae;function fe(X){return c(X)==="[object AsyncFunction]"}t.isAsyncFunction=fe;function ue(X){return c(X)==="[object Map Iterator]"}t.isMapIterator=ue;function ie(X){return c(X)==="[object Set Iterator]"}t.isSetIterator=ie;function se(X){return c(X)==="[object Generator]"}t.isGeneratorObject=se;function be(X){return c(X)==="[object WebAssembly.Module]"}t.isWebAssemblyCompiledModule=be;function ge(X){return b(X,u)}t.isNumberObject=ge;function Ee(X){return b(X,l)}t.isStringObject=Ee;function Te(X){return b(X,f)}t.isBooleanObject=Te;function nt(X){return a&&b(X,p)}t.isBigIntObject=nt;function Ce(X){return o&&b(X,d)}t.isSymbolObject=Ce;function Hr(X){return ge(X)||Ee(X)||Te(X)||nt(X)||Ce(X)}t.isBoxedPrimitive=Hr;function ks(X){return typeof Uint8Array<"u"&&(J(X)||ae(X))}t.isAnyArrayBuffer=ks,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(X){Object.defineProperty(t,X,{enumerable:!1,value:function(){throw new Error(X+" is not supported in userland")}})})}(Il)),Il}var If,cm;function aI(){return cm||(cm=1,If=function(e){return e&&typeof e=="object"&&typeof e.copy=="function"&&typeof e.fill=="function"&&typeof e.readUInt8=="function"}),If}var fc={exports:{}},um;function oI(){return um||(um=1,typeof Object.create=="function"?fc.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:fc.exports=function(e,r){if(r){e.super_=r;var n=function(){};n.prototype=r.prototype,e.prototype=new n,e.prototype.constructor=e}}),fc.exports}var lm;function Yw(){return lm||(lm=1,function(t){var e=Object.getOwnPropertyDescriptors||function(F){for(var z=Object.keys(F),ne={},ae=0;ae<z.length;ae++)ne[z[ae]]=Object.getOwnPropertyDescriptor(F,z[ae]);return ne},r=/%[sdj%]/g;t.format=function(B){if(!x(B)){for(var F=[],z=0;z<arguments.length;z++)F.push(a(arguments[z]));return F.join(" ")}for(var z=1,ne=arguments,ae=ne.length,fe=String(B).replace(r,function(ie){if(ie==="%%")return"%";if(z>=ae)return ie;switch(ie){case"%s":return String(ne[z++]);case"%d":return Number(ne[z++]);case"%j":try{return JSON.stringify(ne[z++])}catch{return"[Circular]"}default:return ie}}),ue=ne[z];z<ae;ue=ne[++z])T(ue)||!C(ue)?fe+=" "+ue:fe+=" "+a(ue);return fe},t.deprecate=function(B,F){if(typeof process<"u"&&process.noDeprecation===!0)return B;if(typeof process>"u")return function(){return t.deprecate(B,F).apply(this,arguments)};var z=!1;function ne(){if(!z){if(process.throwDeprecation)throw new Error(F);process.traceDeprecation?console.trace(F):console.error(F),z=!0}return B.apply(this,arguments)}return ne};var n={},s=/^$/;if(process.env.NODE_DEBUG){var i=process.env.NODE_DEBUG;i=i.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),s=new RegExp("^"+i+"$","i")}t.debuglog=function(B){if(B=B.toUpperCase(),!n[B])if(s.test(B)){var F=process.pid;n[B]=function(){var z=t.format.apply(t,arguments);console.error("%s %d: %s",B,F,z)}}else n[B]=function(){};return n[B]};function a(B,F){var z={seen:[],stylize:c};return arguments.length>=3&&(z.depth=arguments[2]),arguments.length>=4&&(z.colors=arguments[3]),S(F)?z.showHidden=F:F&&t._extend(z,F),I(z.showHidden)&&(z.showHidden=!1),I(z.depth)&&(z.depth=2),I(z.colors)&&(z.colors=!1),I(z.customInspect)&&(z.customInspect=!0),z.colors&&(z.stylize=o),l(z,B,z.depth)}t.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function o(B,F){var z=a.styles[F];return z?"\x1B["+a.colors[z][0]+"m"+B+"\x1B["+a.colors[z][1]+"m":B}function c(B,F){return B}function u(B){var F={};return B.forEach(function(z,ne){F[z]=!0}),F}function l(B,F,z){if(B.customInspect&&F&&H(F.inspect)&&F.inspect!==t.inspect&&!(F.constructor&&F.constructor.prototype===F)){var ne=F.inspect(z,B);return x(ne)||(ne=l(B,ne,z)),ne}var ae=f(B,F);if(ae)return ae;var fe=Object.keys(F),ue=u(fe);if(B.showHidden&&(fe=Object.getOwnPropertyNames(F)),M(F)&&(fe.indexOf("message")>=0||fe.indexOf("description")>=0))return p(F);if(fe.length===0){if(H(F)){var ie=F.name?": "+F.name:"";return B.stylize("[Function"+ie+"]","special")}if(N(F))return B.stylize(RegExp.prototype.toString.call(F),"regexp");if(j(F))return B.stylize(Date.prototype.toString.call(F),"date");if(M(F))return p(F)}var se="",be=!1,ge=["{","}"];if(A(F)&&(be=!0,ge=["[","]"]),H(F)){var Ee=F.name?": "+F.name:"";se=" [Function"+Ee+"]"}if(N(F)&&(se=" "+RegExp.prototype.toString.call(F)),j(F)&&(se=" "+Date.prototype.toUTCString.call(F)),M(F)&&(se=" "+p(F)),fe.length===0&&(!be||F.length==0))return ge[0]+se+ge[1];if(z<0)return N(F)?B.stylize(RegExp.prototype.toString.call(F),"regexp"):B.stylize("[Object]","special");B.seen.push(F);var Te;return be?Te=d(B,F,z,ue,fe):Te=fe.map(function(nt){return b(B,F,z,ue,nt,be)}),B.seen.pop(),g(Te,se,ge)}function f(B,F){if(I(F))return B.stylize("undefined","undefined");if(x(F)){var z="'"+JSON.stringify(F).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return B.stylize(z,"string")}if(w(F))return B.stylize(""+F,"number");if(S(F))return B.stylize(""+F,"boolean");if(T(F))return B.stylize("null","null")}function p(B){return"["+Error.prototype.toString.call(B)+"]"}function d(B,F,z,ne,ae){for(var fe=[],ue=0,ie=F.length;ue<ie;++ue)q(F,String(ue))?fe.push(b(B,F,z,ne,String(ue),!0)):fe.push("");return ae.forEach(function(se){se.match(/^\d+$/)||fe.push(b(B,F,z,ne,se,!0))}),fe}function b(B,F,z,ne,ae,fe){var ue,ie,se;if(se=Object.getOwnPropertyDescriptor(F,ae)||{value:F[ae]},se.get?se.set?ie=B.stylize("[Getter/Setter]","special"):ie=B.stylize("[Getter]","special"):se.set&&(ie=B.stylize("[Setter]","special")),q(ne,ae)||(ue="["+ae+"]"),ie||(B.seen.indexOf(se.value)<0?(T(z)?ie=l(B,se.value,null):ie=l(B,se.value,z-1),ie.indexOf(`
72
72
  `)>-1&&(fe?ie=ie.split(`
73
73
  `).map(function(be){return" "+be}).join(`
74
74
  `).slice(2):ie=`
@@ -77,13 +77,13 @@ ${gS(d)}`),super(e.shortMessage,{cause:e,docsPath:n,metaMessages:[...e.metaMessa
77
77
  `))):ie=B.stylize("[Circular]","special")),I(ue)){if(fe&&ae.match(/^\d+$/))return ie;ue=JSON.stringify(""+ae),ue.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(ue=ue.slice(1,-1),ue=B.stylize(ue,"name")):(ue=ue.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),ue=B.stylize(ue,"string"))}return ue+": "+ie}function g(B,F,z){var ne=B.reduce(function(ae,fe){return fe.indexOf(`
78
78
  `)>=0,ae+fe.replace(/\u001b\[\d\d?m/g,"").length+1},0);return ne>60?z[0]+(F===""?"":F+`
79
79
  `)+" "+B.join(`,
80
- `)+" "+z[1]:z[0]+F+" "+B.join(", ")+" "+z[1]}t.types=tI();function A(B){return Array.isArray(B)}t.isArray=A;function S(B){return typeof B=="boolean"}t.isBoolean=S;function T(B){return B===null}t.isNull=T;function v(B){return B==null}t.isNullOrUndefined=v;function w(B){return typeof B=="number"}t.isNumber=w;function x(B){return typeof B=="string"}t.isString=x;function _(B){return typeof B=="symbol"}t.isSymbol=_;function I(B){return B===void 0}t.isUndefined=I;function N(B){return C(B)&&Q(B)==="[object RegExp]"}t.isRegExp=N,t.types.isRegExp=N;function C(B){return typeof B=="object"&&B!==null}t.isObject=C;function j(B){return C(B)&&Q(B)==="[object Date]"}t.isDate=j,t.types.isDate=j;function M(B){return C(B)&&(Q(B)==="[object Error]"||B instanceof Error)}t.isError=M,t.types.isNativeError=M;function H(B){return typeof B=="function"}t.isFunction=H;function V(B){return B===null||typeof B=="boolean"||typeof B=="number"||typeof B=="string"||typeof B=="symbol"||typeof B>"u"}t.isPrimitive=V,t.isBuffer=rI();function Q(B){return Object.prototype.toString.call(B)}function U(B){return B<10?"0"+B.toString(10):B.toString(10)}var K=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ee(){var B=new Date,F=[U(B.getHours()),U(B.getMinutes()),U(B.getSeconds())].join(":");return[B.getDate(),K[B.getMonth()],F].join(" ")}t.log=function(){console.log("%s - %s",ee(),t.format.apply(t,arguments))},t.inherits=nI(),t._extend=function(B,F){if(!F||!C(F))return B;for(var z=Object.keys(F),ne=z.length;ne--;)B[z[ne]]=F[z[ne]];return B};function q(B,F){return Object.prototype.hasOwnProperty.call(B,F)}var O=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;t.promisify=function(F){if(typeof F!="function")throw new TypeError('The "original" argument must be of type Function');if(O&&F[O]){var z=F[O];if(typeof z!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(z,O,{value:z,enumerable:!1,writable:!1,configurable:!0}),z}function z(){for(var ne,ae,fe=new Promise(function(se,be){ne=se,ae=be}),ue=[],ie=0;ie<arguments.length;ie++)ue.push(arguments[ie]);ue.push(function(se,be){se?ae(se):ne(be)});try{F.apply(this,ue)}catch(se){ae(se)}return fe}return Object.setPrototypeOf(z,Object.getPrototypeOf(F)),O&&Object.defineProperty(z,O,{value:z,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(z,e(F))},t.promisify.custom=O;function L(B,F){if(!B){var z=new Error("Promise was rejected with a falsy value");z.reason=B,B=z}return F(B)}function J(B){if(typeof B!="function")throw new TypeError('The "original" argument must be of type Function');function F(){for(var z=[],ne=0;ne<arguments.length;ne++)z.push(arguments[ne]);var ae=z.pop();if(typeof ae!="function")throw new TypeError("The last argument must be of type Function");var fe=this,ue=function(){return ae.apply(fe,arguments)};B.apply(this,z).then(function(ie){process.nextTick(ue.bind(null,null,ie))},function(ie){process.nextTick(L.bind(null,ie,ue))})}return Object.setPrototypeOf(F,Object.getPrototypeOf(B)),Object.defineProperties(F,e(B)),F}t.callbackify=J}(kl)),kl}Object.defineProperty(Pu,"__esModule",{value:!0});Pu.decode=sI;Pu.encode=iI;const Xw=ti;function sI(t){return(Xw.isBrowser?new TextDecoder("utf-8"):new(Kw()).TextDecoder("utf-8")).decode(t)}function iI(t){return(Xw.isBrowser?new TextEncoder:new(Kw()).TextEncoder("utf-8")).encode(t)}var Cu={},Fd={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */(function(t,e){var r=si,n=r.Buffer;function s(a,o){for(var c in a)o[c]=a[c]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?t.exports=r:(s(r,e),e.Buffer=i);function i(a,o,c){return n(a,o,c)}i.prototype=Object.create(n.prototype),s(n,i),i.from=function(a,o,c){if(typeof a=="number")throw new TypeError("Argument must not be a number");return n(a,o,c)},i.alloc=function(a,o,c){if(typeof a!="number")throw new TypeError("Argument must be a number");var u=n(a);return o!==void 0?typeof c=="string"?u.fill(o,c):u.fill(o):u.fill(0),u},i.allocUnsafe=function(a){if(typeof a!="number")throw new TypeError("Argument must be a number");return n(a)},i.allocUnsafeSlow=function(a){if(typeof a!="number")throw new TypeError("Argument must be a number");return r.SlowBuffer(a)}})(Fd,Fd.exports);var aI=Fd.exports,lc=aI.Buffer;function oI(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r<e.length;r++)e[r]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=n}var a=t.length,o=t.charAt(0),c=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function l(d){if((Array.isArray(d)||d instanceof Uint8Array)&&(d=lc.from(d)),!lc.isBuffer(d))throw new TypeError("Expected Buffer");if(d.length===0)return"";for(var b=0,g=0,A=0,S=d.length;A!==S&&d[A]===0;)A++,b++;for(var T=(S-A)*u+1>>>0,v=new Uint8Array(T);A!==S;){for(var w=d[A],x=0,_=T-1;(w!==0||x<g)&&_!==-1;_--,x++)w+=256*v[_]>>>0,v[_]=w%a>>>0,w=w/a>>>0;if(w!==0)throw new Error("Non-zero carry");g=x,A++}for(var I=T-g;I!==T&&v[I]===0;)I++;for(var N=o.repeat(b);I<T;++I)N+=t.charAt(v[I]);return N}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return lc.alloc(0);for(var b=0,g=0,A=0;d[b]===o;)g++,b++;for(var S=(d.length-b)*c+1>>>0,T=new Uint8Array(S);b<d.length;){var v=d.charCodeAt(b);if(v>255)return;var w=e[v];if(w===255)return;for(var x=0,_=S-1;(w!==0||x<A)&&_!==-1;_--,x++)w+=a*T[_]>>>0,T[_]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");A=x,b++}for(var I=S-A;I!==S&&T[I]===0;)I++;var N=lc.allocUnsafe(g+(S-I));N.fill(0,0,g);for(var C=g;I!==S;)N[C++]=T[I++];return N}function p(d){var b=f(d);if(b)return b;throw new Error("Non-base"+a+" character")}return{encode:l,decodeUnsafe:f,decode:p}}var cI=oI,uI=cI,lI="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",fI=uI(lI),dI=sn&&sn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Cu,"__esModule",{value:!0});Cu.encode=hI;Cu.decode=pI;const Yw=dI(fI);function hI(t){return Yw.default.encode(t)}function pI(t){return Yw.default.decode(t)}var Ru={};Object.defineProperty(Ru,"__esModule",{value:!0});Ru.encode=mI;Ru.decode=bI;const yI=si;function mI(t){return t.toString("base64")}function bI(t){return yI.Buffer.from(t,"base64")}var gI=sn&&sn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),wI=sn&&sn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Nu=sn&&sn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&gI(e,t,r);return wI(e,t),e};Object.defineProperty(Tn,"__esModule",{value:!0});Tn.base64=Tn.bs58=Tn.utf8=Jw=Tn.hex=void 0;var Jw=Tn.hex=Nu(Iu);Tn.utf8=Nu(Pu);Tn.bs58=Nu(Cu);Tn.base64=Nu(Ru);class os{constructor(e,r,n,s,i){try{this.swapId=Array.from(Buffer.from(e,"hex")),this.secretHash=Array.from(Buffer.from(n,"hex"))}catch(a){throw new Error("Error decoding swapId or secretHash",{cause:a})}if(this.secretHash.length!=32||this.swapId.length!=32)throw new Error("swapId or secretHash must be exactly 32 bits in size");try{this.redeemer=new Ar.web3.PublicKey(r)}catch(a){throw new Error("Error decoding redeemer. Ensure it is a valid base58 encoded",{cause:a})}try{this.amount=new Lf.BigNumber(s.toString(10),10),this.expiresIn=new Lf.BigNumber(i)}catch(a){throw new Error("Error decoding amount. Invalid value for amount",{cause:a})}if(!(Number.isInteger(i)&&i>0))throw new Error("expiresIn must be a positive integer.")}static from(e){let r;if(e.source_swap.chain.includes("solana"))r=e.source_swap;else if(e.destination_swap.chain.includes("solana"))r=e.destination_swap;else throw new Error("Expected source_swap or destination_swap to be one of 'solana', 'solana_localnet', 'solana_devnet'");const{swap_id:n,redeemer:s,secret_hash:i,timelock:a}=r,o=BigInt(r.amount);return new os(n,s,i,o,a)}}function Zw(t){let e;try{e=[...Jw.decode(t)]}catch(r){throw new Error("Error decoding secret. Ensure it is a hex string",{cause:r})}if(e.length!=32)throw new Error("Invalid Secret size. Expected 32 bytes, got "+e.length);return e}class Qw{constructor(e,r,n,s,i){var f,p;if(this.provider=e,this.url=r,!e)throw new Error("Provider is required");if(!r)throw new Error("Endpoint URL is required");if(n==null)throw new Error("Network is required");const a=n===m.Network.MAINNET?Df.mainnet:Df.staging,o={native:((f=i==null?void 0:i.programAddress)==null?void 0:f.native)??a.native,spl:((p=i==null?void 0:i.programAddress)==null?void 0:p.spl)??a.spl},c=(i==null?void 0:i.relayer)??Rm[n];this.auth=s;try{this.relayer=new Ar.web3.PublicKey(c)}catch(d){throw new Error("Error decoding relayer public key. Ensure it is base58 encoded.",{cause:d})}this.relayerClient=new ui(this.auth,this.url);const u=o.spl?{...iy,metadata:{...iy.metadata??{}},address:o.spl}:void 0,l=o.native?{...Ud,metadata:{...Ud.metadata??{}},address:o.native}:void 0;try{this.splProgram=u?new Ar.Program(u,this.provider):void 0,this.nativeProgram=l?new Ar.Program(l,this.provider):void 0}catch(d){throw new Error("Error creating Program instances. Ensure the IDLs and provider are correct.",{cause:d})}}get htlcActorAddress(){if(!this.provider.publicKey)throw new Error("No provider public key found");return this.provider.publicKey.toBase58()}async initiate(e){if(!e)return m.Err("Order is required");if(D.isSolanaOrderResponse(e))return this.initiateWithCreateOrderResponse(e);try{const r=D.ChainAsset.fromString(e.source_swap.asset);return D.isSolanaNativeToken(r.chain,r.symbol)?this.nativeProgram?await this.initiateNativeSwap(e):m.Err("Native program is not initialized"):this.splProgram?await this.initiateSplSwap(e):m.Err("SPL program is not initialized")}catch(r){return m.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async sendSplViaRelayer(e,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return m.Err(n.error);e.recentBlockhash=(await this.provider.connection.getLatestBlockhash()).blockhash,e.feePayer=this.relayer;const i=(await this.provider.wallet.signTransaction(e)).serialize({requireAllSignatures:!1}).toString("base64"),a=await m.Fetcher.post(this.url.endpoint("/initiate"),{body:JSON.stringify({order_id:r,serialized_tx:i}),headers:{...n.val,"Content-Type":"application/json"}});return a.error||!a.result?m.Err(`Error from Relayer: ${a.error}`):await qo(this.provider.connection,a.result)?m.Ok(a.result):m.Err("Relayer: Failed to Initiate swap, confirmation timed out")}catch(n){return m.Err(`Failed to send SPL transaction: ${n instanceof Error?n.message:String(n)}`)}}async initiateViaHTLC(e,r){if(!r)return m.Err("Order is required");try{const n=await this.provider.sendAndConfirm(e);return n?await qo(this.provider.connection,n)?m.Ok(n):m.Err("HTLC: Failed to Initiate swap, confirmation timed out"):m.Err("Failed to initiate HTLC transaction")}catch(n){return m.Err(`Error initiating swap: ${n instanceof Error?n.message:String(n)}`)}}async initiateSplSwap(e){if(!this.splProgram)return m.Err("SPL program is not initialized");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=os.from(e),a=this.splProgram.methods.initiate(i,r,n,s,null),o=await $i(e.source_swap.asset,this.url,this.auth);if(!o.ok)return m.Err(o.error);const{tokenAddress:c}=o.val,u=new Ar.web3.PublicKey(c),l={initiator:this.provider.publicKey,mint:u,initiatorTokenAccount:O6.getAssociatedTokenAddressSync(u,this.provider.publicKey),sponsor:this.relayer},f=await a.accounts(l).transaction();return this.sendSplViaRelayer(f,e.order_id)}catch(r){return m.Err(`Error initiating SPL swap: ${r instanceof Error?r.message:String(r)}`)}}async initiateNativeSwap(e){if(!this.nativeProgram)return m.Err("Native program is not initialized");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=os.from(e),a=await this.nativeProgram.methods.initiate(s,i,r,n).accounts({initiator:this.provider.publicKey}).transaction();return this.initiateViaHTLC(a,e)}catch(r){return m.Err(`Error initiating native swap: ${r instanceof Error?r.message:String(r)}`)}}async initiateWithCreateOrderResponse(e){if(!this.relayer)return m.Err("No relayer address");const{versioned_tx:r,versioned_tx_gasless:n}=e;if(n===null)try{const i=Buffer.from(r,"base64"),a=Ar.web3.VersionedTransaction.deserialize(i),o=await this.provider.sendAndConfirm(a);return await qo(this.provider.connection,o)?m.Ok(o):m.Err("Failed to initiate HTLC transaction")}catch(i){return m.Err(`Error in non-gasless flow: ${i}`)}const s=await this.auth.getAuthHeaders();if(!s.ok)return m.Err(s.error);try{const i=Ar.web3.VersionedTransaction.deserialize(Buffer.from(n,"base64")),a=await this.provider.wallet.signTransaction(i);if(!a.signatures[0])return m.Err("No signature found after signing transaction");const c=Buffer.from(a.serialize()).toString("base64"),u=await this.relayerClient.initiate(e.order_id,c);return u.error?m.Err(u.error):u.val?m.Ok(u.val):m.Err("Initiate: No result found")}catch(i){return m.Err(`Error initiating with create order response: ${i}`)}}async redeem(e,r){try{const n=Zw(r),s=await this.relayerClient.redeem(e.order_id,Buffer.from(n).toString("hex"));if(s.error||!s.val)return m.Err(`Redeem: Error from relayer: ${s.error}`);const i=s.val;return await qo(this.provider.connection,i)?m.Ok(i):m.Err("Redeem: Timed out waiting for confirmation")}catch(n){return console.error("Redeem: Caught exception:",n),m.Err(`Error redeeming: ${n}`)}}async refund(){return m.Err("Refund is automatically handled by the relayer.")}}const e2="1.45.2",vI="1.62.0",EI={"-32700":"ParseError","-32701":"OversizedRequest","-32702":"OversizedResponse","-32600":"InvalidRequest","-32601":"MethodNotFound","-32602":"InvalidParams","-32603":"InternalError","-32604":"ServerBusy","-32000":"CallExecutionFailed","-32001":"UnknownError","-32003":"SubscriptionClosed","-32004":"SubscriptionClosedWithError","-32005":"BatchesNotSupported","-32006":"TooManySubscriptions","-32050":"TransientError","-32002":"TransactionExecutionClientError"};class t2 extends Error{}class r2 extends t2{constructor(e,r){super(e),this.code=r,this.type=EI[r]??"ServerError"}}class AI extends t2{constructor(e,r,n){super(e),this.status=r,this.statusText=n}}var n2=t=>{throw TypeError(t)},y0=(t,e,r)=>e.has(t)||n2("Cannot "+r),He=(t,e,r)=>(y0(t,e,"read from private field"),r?r.call(t):e.get(t)),Is=(t,e,r)=>e.has(t)?n2("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Fi=(t,e,r,n)=>(y0(t,e,"write to private field"),e.set(t,r),r),s2=(t,e,r)=>(y0(t,e,"access private method"),r),SI=(t,e,r,n)=>({set _(s){Fi(t,e,s)},get _(){return He(t,e,n)}}),Qn,Oa,An,Ns,uo,Us,Mc,i2,a2;function xI(t){const e=new URL(t);return e.protocol=e.protocol.replace("http","ws"),e.toString()}const kI={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5};class TI{constructor(e,r={}){if(Is(this,Mc),Is(this,Qn,0),Is(this,Oa,0),Is(this,An,null),Is(this,Ns,null),Is(this,uo,new Set),Is(this,Us,new Map),this.endpoint=e,this.options={...kI,...r},!this.options.WebSocketConstructor)throw new Error("Missing WebSocket constructor");this.endpoint.startsWith("http")&&(this.endpoint=xI(this.endpoint))}async makeRequest(e,r,n){const s=await s2(this,Mc,i2).call(this);return new Promise((i,a)=>{Fi(this,Qn,He(this,Qn)+1),He(this,Us).set(He(this,Qn),{resolve:i,reject:a,timeout:setTimeout(()=>{He(this,Us).delete(He(this,Qn)),a(new Error(`Request timeout: ${e}`))},this.options.callTimeout)}),n==null||n.addEventListener("abort",()=>{He(this,Us).delete(He(this,Qn)),a(n.reason)}),s.send(JSON.stringify({jsonrpc:"2.0",id:He(this,Qn),method:e,params:r}))}).then(({error:i,result:a})=>{if(i)throw new r2(i.message,i.code);return a})}async subscribe(e){const r=new _I(e);return He(this,uo).add(r),await r.subscribe(this),()=>r.unsubscribe(this)}}Qn=new WeakMap;Oa=new WeakMap;An=new WeakMap;Ns=new WeakMap;uo=new WeakMap;Us=new WeakMap;Mc=new WeakSet;i2=function(){return He(this,Ns)?He(this,Ns):(Fi(this,Ns,new Promise(t=>{var e;(e=He(this,An))==null||e.close(),Fi(this,An,new this.options.WebSocketConstructor(this.endpoint)),He(this,An).addEventListener("open",()=>{Fi(this,Oa,0),t(He(this,An))}),He(this,An).addEventListener("close",()=>{SI(this,Oa)._++,He(this,Oa)<=this.options.maxReconnects&&setTimeout(()=>{s2(this,Mc,a2).call(this)},this.options.reconnectTimeout)}),He(this,An).addEventListener("message",({data:r})=>{let n;try{n=JSON.parse(r)}catch(s){console.error(new Error(`Failed to parse RPC message: ${r}`,{cause:s}));return}if("id"in n&&n.id!=null&&He(this,Us).has(n.id)){const{resolve:s,timeout:i}=He(this,Us).get(n.id);clearTimeout(i),s(n)}else if("params"in n){const{params:s}=n;He(this,uo).forEach(i=>{i.subscriptionId===s.subscription&&s.subscription===i.subscriptionId&&i.onMessage(s.result)})}})})),He(this,Ns))};a2=async function(){var t;return(t=He(this,An))==null||t.close(),Fi(this,Ns,null),Promise.allSettled([...He(this,uo)].map(e=>e.subscribe(this)))};class _I{constructor(e){this.subscriptionId=null,this.subscribed=!1,this.input=e}onMessage(e){this.subscribed&&this.input.onMessage(e)}async unsubscribe(e){const{subscriptionId:r}=this;return this.subscribed=!1,r==null?!1:(this.subscriptionId=null,e.makeRequest(this.input.unsubscribe,[r]))}async subscribe(e){this.subscriptionId=null,this.subscribed=!0;const r=await e.makeRequest(this.input.method,this.input.params,this.input.signal);this.subscribed&&(this.subscriptionId=r)}}var o2=t=>{throw TypeError(t)},m0=(t,e,r)=>e.has(t)||o2("Cannot "+r),yr=(t,e,r)=>(m0(t,e,"read from private field"),r?r.call(t):e.get(t)),fc=(t,e,r)=>e.has(t)?o2("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Md=(t,e,r,n)=>(m0(t,e,"write to private field"),e.set(t,r),r),II=(t,e,r)=>(m0(t,e,"access private method"),r),Sa,Sr,Ba,$d,c2;class PI{constructor(e){fc(this,$d),fc(this,Sa,0),fc(this,Sr),fc(this,Ba),Md(this,Sr,e)}fetch(e,r){const n=yr(this,Sr).fetch??fetch;if(!n)throw new Error("The current environment does not support fetch, you can provide a fetch implementation in the options for SuiHTTPTransport.");return n(e,r)}async request(e){var s,i;Md(this,Sa,yr(this,Sa)+1);const r=await this.fetch(((s=yr(this,Sr).rpc)==null?void 0:s.url)??yr(this,Sr).url,{method:"POST",signal:e.signal,headers:{"Content-Type":"application/json","Client-Sdk-Type":"typescript","Client-Sdk-Version":e2,"Client-Target-Api-Version":vI,"Client-Request-Method":e.method,...(i=yr(this,Sr).rpc)==null?void 0:i.headers},body:JSON.stringify({jsonrpc:"2.0",id:yr(this,Sa),method:e.method,params:e.params})});if(!r.ok)throw new AI(`Unexpected status code: ${r.status}`,r.status,r.statusText);const n=await r.json();if("error"in n&&n.error!=null)throw new r2(n.error.message,n.error.code);return n.result}async subscribe(e){const r=await II(this,$d,c2).call(this).subscribe(e);return e.signal&&(e.signal.throwIfAborted(),e.signal.addEventListener("abort",()=>{r()})),async()=>!!await r()}}Sa=new WeakMap;Sr=new WeakMap;Ba=new WeakMap;$d=new WeakSet;c2=function(){var t;if(!yr(this,Ba)){const e=yr(this,Sr).WebSocketConstructor??WebSocket;if(!e)throw new Error("The current environment does not support WebSocket, you can provide a WebSocketConstructor in the options for SuiHTTPTransport.");Md(this,Ba,new TI(((t=yr(this,Sr).websocket)==null?void 0:t.url)??yr(this,Sr).url,{WebSocketConstructor:e,...yr(this,Sr).websocket}))}return yr(this,Ba)};function um(t){switch(t){case"mainnet":return"https://fullnode.mainnet.sui.io:443";case"testnet":return"https://fullnode.testnet.sui.io:443";case"devnet":return"https://fullnode.devnet.sui.io:443";case"localnet":return"http://127.0.0.1:9000";default:throw new Error(`Unknown network: ${t}`)}}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function OI(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function u2(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function jd(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function l2(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Hd(t){if(!Array.isArray(t))throw new Error("array expected")}function f2(t,e){if(!u2(!0,e))throw new Error(`${t}: array of strings expected`)}function BI(t,e){if(!u2(!1,e))throw new Error(`${t}: array of numbers expected`)}function CI(...t){const e=i=>i,r=(i,a)=>o=>i(a(o)),n=t.map(i=>i.encode).reduceRight(r,e),s=t.map(i=>i.decode).reduce(r,e);return{encode:n,decode:s}}function RI(t){const e=typeof t=="string"?t.split(""):t,r=e.length;f2("alphabet",e);const n=new Map(e.map((s,i)=>[s,i]));return{encode:s=>(Hd(s),s.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${t}`);return e[i]})),decode:s=>(Hd(s),s.map(i=>{jd("alphabet.decode",i);const a=n.get(i);if(a===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${t}`);return a}))}}function NI(t=""){return jd("join",t),{encode:e=>(f2("join.decode",e),e.join(t)),decode:e=>(jd("join.decode",e),e.split(t))}}function lm(t,e,r){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(Hd(t),!t.length)return[];let n=0;const s=[],i=Array.from(t,o=>{if(l2(o),o<0||o>=e)throw new Error(`invalid integer: ${o}`);return o}),a=i.length;for(;;){let o=0,c=!0;for(let u=n;u<a;u++){const l=i[u],f=e*o,p=f+l;if(!Number.isSafeInteger(p)||f/e!==o||p-l!==f)throw new Error("convertRadix: carry overflow");const d=p/r;o=p%r;const b=Math.floor(d);if(i[u]=b,!Number.isSafeInteger(b)||b*r+o!==p)throw new Error("convertRadix: carry overflow");if(c)b?c=!1:n=u;else continue}if(s.push(o),c)break}for(let o=0;o<t.length-1&&t[o]===0;o++)s.push(0);return s.reverse()}function UI(t){l2(t);const e=2**8;return{encode:r=>{if(!OI(r))throw new Error("radix.encode input should be Uint8Array");return lm(Array.from(r),e,t)},decode:r=>(BI("radix.decode",r),Uint8Array.from(lm(r,t,e)))}}const FI=t=>CI(UI(58),RI(t),NI("")),d2=FI("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),Uu=t=>d2.encode(t),lo=t=>d2.decode(t);function tr(t){return Uint8Array.from(atob(t),e=>e.charCodeAt(0))}const _f=8192;function St(t){if(t.length<_f)return btoa(String.fromCharCode(...t));let e="";for(var r=0;r<t.length;r+=_f){const n=t.slice(r,r+_f);e+=String.fromCharCode(...n)}return btoa(e)}function h2(t){var s;const e=t.startsWith("0x")?t.slice(2):t,r=e.length%2===0?e:`0${e}`,n=((s=r.match(/[0-9a-fA-F]{2}/g))==null?void 0:s.map(i=>parseInt(i,16)))??[];if(n.length!==r.length/2)throw new Error(`Invalid hex string ${t}`);return Uint8Array.from(n)}function Xi(t){return t.reduce((e,r)=>e+r.toString(16).padStart(2,"0"),"")}function Fu(t,e){return Array.from({length:Math.ceil(t.length/e)},(r,n)=>t.slice(n*e,(n+1)*e))}class p2{constructor(e,r){if(typeof e!="function")throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but got: ${e}.`);this._batchLoadFn=e,this._maxBatchSize=HI(r),this._batchScheduleFn=LI(r),this._cacheKeyFn=DI(r),this._cacheMap=zI(r),this._batch=null,this.name=VI(r)}load(e){if(e==null)throw new TypeError(`The loader.load() function must be called with a value, but got: ${String(e)}.`);const r=$I(this),n=this._cacheMap;let s;if(n){s=this._cacheKeyFn(e);const a=n.get(s);if(a){const o=r.cacheHits||(r.cacheHits=[]);return new Promise(c=>{o.push(()=>{c(a)})})}}r.keys.push(e);const i=new Promise((a,o)=>{r.callbacks.push({resolve:a,reject:o})});return n&&n.set(s,i),i}loadMany(e){if(!y2(e))throw new TypeError(`The loader.loadMany() function must be called with Array<key>, but got: ${e}.`);const r=[];for(let n=0;n<e.length;n++)r.push(this.load(e[n]).catch(s=>s));return Promise.all(r)}clear(e){const r=this._cacheMap;if(r){const n=this._cacheKeyFn(e);r.delete(n)}return this}clearAll(){const e=this._cacheMap;return e&&e.clear(),this}prime(e,r){const n=this._cacheMap;if(n){const s=this._cacheKeyFn(e);if(n.get(s)===void 0){let i;r instanceof Error?(i=Promise.reject(r),i.catch(()=>{})):i=Promise.resolve(r),n.set(s,i)}}return this}}const MI=typeof process=="object"&&typeof process.nextTick=="function"?function(t){If||(If=Promise.resolve()),If.then(()=>{process.nextTick(t)})}:typeof setImmediate=="function"?function(t){setImmediate(t)}:function(t){setTimeout(t)};let If;function $I(t){const e=t._batch;if(e!==null&&!e.hasDispatched&&e.keys.length<t._maxBatchSize)return e;const r={hasDispatched:!1,keys:[],callbacks:[]};return t._batch=r,t._batchScheduleFn(()=>{jI(t,r)}),r}function jI(t,e){if(e.hasDispatched=!0,e.keys.length===0){Ld(e);return}let r;try{r=t._batchLoadFn(e.keys)}catch(n){return Pf(t,e,new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function errored synchronously: ${String(n)}.`))}if(!r||typeof r.then!="function")return Pf(t,e,new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise: ${String(r)}.`));Promise.resolve(r).then(n=>{if(!y2(n))throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array: ${String(n)}.`);if(n.length!==e.keys.length)throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys.
80
+ `)+" "+z[1]:z[0]+F+" "+B.join(", ")+" "+z[1]}t.types=iI();function A(B){return Array.isArray(B)}t.isArray=A;function S(B){return typeof B=="boolean"}t.isBoolean=S;function T(B){return B===null}t.isNull=T;function v(B){return B==null}t.isNullOrUndefined=v;function w(B){return typeof B=="number"}t.isNumber=w;function x(B){return typeof B=="string"}t.isString=x;function _(B){return typeof B=="symbol"}t.isSymbol=_;function I(B){return B===void 0}t.isUndefined=I;function N(B){return C(B)&&Q(B)==="[object RegExp]"}t.isRegExp=N,t.types.isRegExp=N;function C(B){return typeof B=="object"&&B!==null}t.isObject=C;function j(B){return C(B)&&Q(B)==="[object Date]"}t.isDate=j,t.types.isDate=j;function M(B){return C(B)&&(Q(B)==="[object Error]"||B instanceof Error)}t.isError=M,t.types.isNativeError=M;function H(B){return typeof B=="function"}t.isFunction=H;function V(B){return B===null||typeof B=="boolean"||typeof B=="number"||typeof B=="string"||typeof B=="symbol"||typeof B>"u"}t.isPrimitive=V,t.isBuffer=aI();function Q(B){return Object.prototype.toString.call(B)}function U(B){return B<10?"0"+B.toString(10):B.toString(10)}var K=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ee(){var B=new Date,F=[U(B.getHours()),U(B.getMinutes()),U(B.getSeconds())].join(":");return[B.getDate(),K[B.getMonth()],F].join(" ")}t.log=function(){console.log("%s - %s",ee(),t.format.apply(t,arguments))},t.inherits=oI(),t._extend=function(B,F){if(!F||!C(F))return B;for(var z=Object.keys(F),ne=z.length;ne--;)B[z[ne]]=F[z[ne]];return B};function q(B,F){return Object.prototype.hasOwnProperty.call(B,F)}var O=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;t.promisify=function(F){if(typeof F!="function")throw new TypeError('The "original" argument must be of type Function');if(O&&F[O]){var z=F[O];if(typeof z!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(z,O,{value:z,enumerable:!1,writable:!1,configurable:!0}),z}function z(){for(var ne,ae,fe=new Promise(function(se,be){ne=se,ae=be}),ue=[],ie=0;ie<arguments.length;ie++)ue.push(arguments[ie]);ue.push(function(se,be){se?ae(se):ne(be)});try{F.apply(this,ue)}catch(se){ae(se)}return fe}return Object.setPrototypeOf(z,Object.getPrototypeOf(F)),O&&Object.defineProperty(z,O,{value:z,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(z,e(F))},t.promisify.custom=O;function L(B,F){if(!B){var z=new Error("Promise was rejected with a falsy value");z.reason=B,B=z}return F(B)}function J(B){if(typeof B!="function")throw new TypeError('The "original" argument must be of type Function');function F(){for(var z=[],ne=0;ne<arguments.length;ne++)z.push(arguments[ne]);var ae=z.pop();if(typeof ae!="function")throw new TypeError("The last argument must be of type Function");var fe=this,ue=function(){return ae.apply(fe,arguments)};B.apply(this,z).then(function(ie){process.nextTick(ue.bind(null,null,ie))},function(ie){process.nextTick(L.bind(null,ie,ue))})}return Object.setPrototypeOf(F,Object.getPrototypeOf(B)),Object.defineProperties(F,e(B)),F}t.callbackify=J}(_l)),_l}Object.defineProperty(Bu,"__esModule",{value:!0});Bu.decode=cI;Bu.encode=uI;const Jw=ri;function cI(t){return(Jw.isBrowser?new TextDecoder("utf-8"):new(Yw()).TextDecoder("utf-8")).decode(t)}function uI(t){return(Jw.isBrowser?new TextEncoder:new(Yw()).TextEncoder("utf-8")).encode(t)}var Nu={},$d={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */(function(t,e){var r=ii,n=r.Buffer;function s(a,o){for(var c in a)o[c]=a[c]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?t.exports=r:(s(r,e),e.Buffer=i);function i(a,o,c){return n(a,o,c)}i.prototype=Object.create(n.prototype),s(n,i),i.from=function(a,o,c){if(typeof a=="number")throw new TypeError("Argument must not be a number");return n(a,o,c)},i.alloc=function(a,o,c){if(typeof a!="number")throw new TypeError("Argument must be a number");var u=n(a);return o!==void 0?typeof c=="string"?u.fill(o,c):u.fill(o):u.fill(0),u},i.allocUnsafe=function(a){if(typeof a!="number")throw new TypeError("Argument must be a number");return n(a)},i.allocUnsafeSlow=function(a){if(typeof a!="number")throw new TypeError("Argument must be a number");return r.SlowBuffer(a)}})($d,$d.exports);var lI=$d.exports,dc=lI.Buffer;function fI(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r<e.length;r++)e[r]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=n}var a=t.length,o=t.charAt(0),c=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function l(d){if((Array.isArray(d)||d instanceof Uint8Array)&&(d=dc.from(d)),!dc.isBuffer(d))throw new TypeError("Expected Buffer");if(d.length===0)return"";for(var b=0,g=0,A=0,S=d.length;A!==S&&d[A]===0;)A++,b++;for(var T=(S-A)*u+1>>>0,v=new Uint8Array(T);A!==S;){for(var w=d[A],x=0,_=T-1;(w!==0||x<g)&&_!==-1;_--,x++)w+=256*v[_]>>>0,v[_]=w%a>>>0,w=w/a>>>0;if(w!==0)throw new Error("Non-zero carry");g=x,A++}for(var I=T-g;I!==T&&v[I]===0;)I++;for(var N=o.repeat(b);I<T;++I)N+=t.charAt(v[I]);return N}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return dc.alloc(0);for(var b=0,g=0,A=0;d[b]===o;)g++,b++;for(var S=(d.length-b)*c+1>>>0,T=new Uint8Array(S);b<d.length;){var v=d.charCodeAt(b);if(v>255)return;var w=e[v];if(w===255)return;for(var x=0,_=S-1;(w!==0||x<A)&&_!==-1;_--,x++)w+=a*T[_]>>>0,T[_]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");A=x,b++}for(var I=S-A;I!==S&&T[I]===0;)I++;var N=dc.allocUnsafe(g+(S-I));N.fill(0,0,g);for(var C=g;I!==S;)N[C++]=T[I++];return N}function p(d){var b=f(d);if(b)return b;throw new Error("Non-base"+a+" character")}return{encode:l,decodeUnsafe:f,decode:p}}var dI=fI,hI=dI,pI="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",yI=hI(pI),mI=sn&&sn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Nu,"__esModule",{value:!0});Nu.encode=bI;Nu.decode=gI;const Zw=mI(yI);function bI(t){return Zw.default.encode(t)}function gI(t){return Zw.default.decode(t)}var Uu={};Object.defineProperty(Uu,"__esModule",{value:!0});Uu.encode=vI;Uu.decode=EI;const wI=ii;function vI(t){return t.toString("base64")}function EI(t){return wI.Buffer.from(t,"base64")}var AI=sn&&sn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),SI=sn&&sn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Fu=sn&&sn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&AI(e,t,r);return SI(e,t),e};Object.defineProperty(_n,"__esModule",{value:!0});_n.base64=_n.bs58=_n.utf8=Qw=_n.hex=void 0;var Qw=_n.hex=Fu(Ou);_n.utf8=Fu(Bu);_n.bs58=Fu(Nu);_n.base64=Fu(Uu);class cs{constructor(e,r,n,s,i){try{this.swapId=Array.from(Buffer.from(e,"hex")),this.secretHash=Array.from(Buffer.from(n,"hex"))}catch(a){throw new Error("Error decoding swapId or secretHash",{cause:a})}if(this.secretHash.length!=32||this.swapId.length!=32)throw new Error("swapId or secretHash must be exactly 32 bits in size");try{this.redeemer=new Ar.web3.PublicKey(r)}catch(a){throw new Error("Error decoding redeemer. Ensure it is a valid base58 encoded",{cause:a})}try{this.amount=new zf.BigNumber(s.toString(10),10),this.expiresIn=new zf.BigNumber(i)}catch(a){throw new Error("Error decoding amount. Invalid value for amount",{cause:a})}if(!(Number.isInteger(i)&&i>0))throw new Error("expiresIn must be a positive integer.")}static from(e){let r;if(e.source_swap.chain.includes("solana"))r=e.source_swap;else if(e.destination_swap.chain.includes("solana"))r=e.destination_swap;else throw new Error("Expected source_swap or destination_swap to be one of 'solana', 'solana_localnet', 'solana_devnet'");const{swap_id:n,redeemer:s,secret_hash:i,timelock:a}=r,o=BigInt(r.amount);return new cs(n,s,i,o,a)}}function e2(t){let e;try{e=[...Qw.decode(t)]}catch(r){throw new Error("Error decoding secret. Ensure it is a hex string",{cause:r})}if(e.length!=32)throw new Error("Invalid Secret size. Expected 32 bytes, got "+e.length);return e}class t2{constructor(e,r,n,s,i){var f,p;if(this.provider=e,this.url=r,!e)throw new Error("Provider is required");if(!r)throw new Error("Endpoint URL is required");if(n==null)throw new Error("Network is required");const a=n===m.Network.MAINNET?Vf.mainnet:Vf.staging,o={native:((f=i==null?void 0:i.programAddress)==null?void 0:f.native)??a.native,spl:((p=i==null?void 0:i.programAddress)==null?void 0:p.spl)??a.spl},c=(i==null?void 0:i.relayer)??Um[n];this.auth=s;try{this.relayer=new Ar.web3.PublicKey(c)}catch(d){throw new Error("Error decoding relayer public key. Ensure it is base58 encoded.",{cause:d})}this.relayerClient=new li(this.auth,this.url);const u=o.spl?{...oy,metadata:{...oy.metadata??{}},address:o.spl}:void 0,l=o.native?{...Md,metadata:{...Md.metadata??{}},address:o.native}:void 0;try{this.splProgram=u?new Ar.Program(u,this.provider):void 0,this.nativeProgram=l?new Ar.Program(l,this.provider):void 0}catch(d){throw new Error("Error creating Program instances. Ensure the IDLs and provider are correct.",{cause:d})}}get htlcActorAddress(){if(!this.provider.publicKey)throw new Error("No provider public key found");return this.provider.publicKey.toBase58()}async initiate(e){if(!e)return m.Err("Order is required");if(D.isSolanaOrderResponse(e))return this.initiateWithCreateOrderResponse(e);try{const r=D.ChainAsset.fromString(e.source_swap.asset);return D.isSolanaNativeToken(r.chain,r.symbol)?this.nativeProgram?await this.initiateNativeSwap(e):m.Err("Native program is not initialized"):this.splProgram?await this.initiateSplSwap(e):m.Err("SPL program is not initialized")}catch(r){return m.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async sendSplViaRelayer(e,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return m.Err(n.error);e.recentBlockhash=(await this.provider.connection.getLatestBlockhash()).blockhash,e.feePayer=this.relayer;const i=(await this.provider.wallet.signTransaction(e)).serialize({requireAllSignatures:!1}).toString("base64"),a=await m.Fetcher.post(this.url.endpoint("/initiate"),{body:JSON.stringify({order_id:r,serialized_tx:i}),headers:{...n.val,"Content-Type":"application/json"}});return a.error||!a.result?m.Err(`Error from Relayer: ${a.error}`):await qo(this.provider.connection,a.result)?m.Ok(a.result):m.Err("Relayer: Failed to Initiate swap, confirmation timed out")}catch(n){return m.Err(`Failed to send SPL transaction: ${n instanceof Error?n.message:String(n)}`)}}async initiateViaHTLC(e,r){if(!r)return m.Err("Order is required");try{const n=await this.provider.sendAndConfirm(e);return n?await qo(this.provider.connection,n)?m.Ok(n):m.Err("HTLC: Failed to Initiate swap, confirmation timed out"):m.Err("Failed to initiate HTLC transaction")}catch(n){return m.Err(`Error initiating swap: ${n instanceof Error?n.message:String(n)}`)}}async initiateSplSwap(e){if(!this.splProgram)return m.Err("SPL program is not initialized");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=cs.from(e),a=this.splProgram.methods.initiate(i,r,n,s,null),o=await ji(e.source_swap.asset,this.url,this.auth);if(!o.ok)return m.Err(o.error);const{tokenAddress:c}=o.val,u=new Ar.web3.PublicKey(c),l={initiator:this.provider.publicKey,mint:u,initiatorTokenAccount:C6.getAssociatedTokenAddressSync(u,this.provider.publicKey),sponsor:this.relayer},f=await a.accounts(l).transaction();return this.sendSplViaRelayer(f,e.order_id)}catch(r){return m.Err(`Error initiating SPL swap: ${r instanceof Error?r.message:String(r)}`)}}async initiateNativeSwap(e){if(!this.nativeProgram)return m.Err("Native program is not initialized");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=cs.from(e),a=await this.nativeProgram.methods.initiate(s,i,r,n).accounts({initiator:this.provider.publicKey}).transaction();return this.initiateViaHTLC(a,e)}catch(r){return m.Err(`Error initiating native swap: ${r instanceof Error?r.message:String(r)}`)}}async initiateWithCreateOrderResponse(e){if(!this.relayer)return m.Err("No relayer address");const{versioned_tx:r,versioned_tx_gasless:n}=e;if(n===null)try{const i=Buffer.from(r,"base64"),a=Ar.web3.VersionedTransaction.deserialize(i),o=await this.provider.sendAndConfirm(a);return await qo(this.provider.connection,o)?m.Ok(o):m.Err("Failed to initiate HTLC transaction")}catch(i){return m.Err(`Error in non-gasless flow: ${i}`)}const s=await this.auth.getAuthHeaders();if(!s.ok)return m.Err(s.error);try{const i=Ar.web3.VersionedTransaction.deserialize(Buffer.from(n,"base64")),a=await this.provider.wallet.signTransaction(i);if(!a.signatures[0])return m.Err("No signature found after signing transaction");const c=Buffer.from(a.serialize()).toString("base64"),u=await this.relayerClient.initiate(e.order_id,c);return u.error?m.Err(u.error):u.val?m.Ok(u.val):m.Err("Initiate: No result found")}catch(i){return m.Err(`Error initiating with create order response: ${i}`)}}async redeem(e,r){try{const n=e2(r),s=await this.relayerClient.redeem(e.order_id,Buffer.from(n).toString("hex"));if(s.error||!s.val)return m.Err(`Redeem: Error from relayer: ${s.error}`);const i=s.val;return await qo(this.provider.connection,i)?m.Ok(i):m.Err("Redeem: Timed out waiting for confirmation")}catch(n){return console.error("Redeem: Caught exception:",n),m.Err(`Error redeeming: ${n}`)}}async refund(){return m.Err("Refund is automatically handled by the relayer.")}}const r2="1.45.2",xI="1.62.0",kI={"-32700":"ParseError","-32701":"OversizedRequest","-32702":"OversizedResponse","-32600":"InvalidRequest","-32601":"MethodNotFound","-32602":"InvalidParams","-32603":"InternalError","-32604":"ServerBusy","-32000":"CallExecutionFailed","-32001":"UnknownError","-32003":"SubscriptionClosed","-32004":"SubscriptionClosedWithError","-32005":"BatchesNotSupported","-32006":"TooManySubscriptions","-32050":"TransientError","-32002":"TransactionExecutionClientError"};class n2 extends Error{}class s2 extends n2{constructor(e,r){super(e),this.code=r,this.type=kI[r]??"ServerError"}}class TI extends n2{constructor(e,r,n){super(e),this.status=r,this.statusText=n}}var i2=t=>{throw TypeError(t)},b0=(t,e,r)=>e.has(t)||i2("Cannot "+r),He=(t,e,r)=>(b0(t,e,"read from private field"),r?r.call(t):e.get(t)),Ps=(t,e,r)=>e.has(t)?i2("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Mi=(t,e,r,n)=>(b0(t,e,"write to private field"),e.set(t,r),r),a2=(t,e,r)=>(b0(t,e,"access private method"),r),_I=(t,e,r,n)=>({set _(s){Mi(t,e,s)},get _(){return He(t,e,n)}}),es,Oa,Sn,Us,uo,Fs,jc,o2,c2;function II(t){const e=new URL(t);return e.protocol=e.protocol.replace("http","ws"),e.toString()}const PI={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5};class OI{constructor(e,r={}){if(Ps(this,jc),Ps(this,es,0),Ps(this,Oa,0),Ps(this,Sn,null),Ps(this,Us,null),Ps(this,uo,new Set),Ps(this,Fs,new Map),this.endpoint=e,this.options={...PI,...r},!this.options.WebSocketConstructor)throw new Error("Missing WebSocket constructor");this.endpoint.startsWith("http")&&(this.endpoint=II(this.endpoint))}async makeRequest(e,r,n){const s=await a2(this,jc,o2).call(this);return new Promise((i,a)=>{Mi(this,es,He(this,es)+1),He(this,Fs).set(He(this,es),{resolve:i,reject:a,timeout:setTimeout(()=>{He(this,Fs).delete(He(this,es)),a(new Error(`Request timeout: ${e}`))},this.options.callTimeout)}),n==null||n.addEventListener("abort",()=>{He(this,Fs).delete(He(this,es)),a(n.reason)}),s.send(JSON.stringify({jsonrpc:"2.0",id:He(this,es),method:e,params:r}))}).then(({error:i,result:a})=>{if(i)throw new s2(i.message,i.code);return a})}async subscribe(e){const r=new BI(e);return He(this,uo).add(r),await r.subscribe(this),()=>r.unsubscribe(this)}}es=new WeakMap;Oa=new WeakMap;Sn=new WeakMap;Us=new WeakMap;uo=new WeakMap;Fs=new WeakMap;jc=new WeakSet;o2=function(){return He(this,Us)?He(this,Us):(Mi(this,Us,new Promise(t=>{var e;(e=He(this,Sn))==null||e.close(),Mi(this,Sn,new this.options.WebSocketConstructor(this.endpoint)),He(this,Sn).addEventListener("open",()=>{Mi(this,Oa,0),t(He(this,Sn))}),He(this,Sn).addEventListener("close",()=>{_I(this,Oa)._++,He(this,Oa)<=this.options.maxReconnects&&setTimeout(()=>{a2(this,jc,c2).call(this)},this.options.reconnectTimeout)}),He(this,Sn).addEventListener("message",({data:r})=>{let n;try{n=JSON.parse(r)}catch(s){console.error(new Error(`Failed to parse RPC message: ${r}`,{cause:s}));return}if("id"in n&&n.id!=null&&He(this,Fs).has(n.id)){const{resolve:s,timeout:i}=He(this,Fs).get(n.id);clearTimeout(i),s(n)}else if("params"in n){const{params:s}=n;He(this,uo).forEach(i=>{i.subscriptionId===s.subscription&&s.subscription===i.subscriptionId&&i.onMessage(s.result)})}})})),He(this,Us))};c2=async function(){var t;return(t=He(this,Sn))==null||t.close(),Mi(this,Us,null),Promise.allSettled([...He(this,uo)].map(e=>e.subscribe(this)))};class BI{constructor(e){this.subscriptionId=null,this.subscribed=!1,this.input=e}onMessage(e){this.subscribed&&this.input.onMessage(e)}async unsubscribe(e){const{subscriptionId:r}=this;return this.subscribed=!1,r==null?!1:(this.subscriptionId=null,e.makeRequest(this.input.unsubscribe,[r]))}async subscribe(e){this.subscriptionId=null,this.subscribed=!0;const r=await e.makeRequest(this.input.method,this.input.params,this.input.signal);this.subscribed&&(this.subscriptionId=r)}}var u2=t=>{throw TypeError(t)},g0=(t,e,r)=>e.has(t)||u2("Cannot "+r),yr=(t,e,r)=>(g0(t,e,"read from private field"),r?r.call(t):e.get(t)),hc=(t,e,r)=>e.has(t)?u2("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),jd=(t,e,r,n)=>(g0(t,e,"write to private field"),e.set(t,r),r),CI=(t,e,r)=>(g0(t,e,"access private method"),r),Sa,Sr,Ba,Hd,l2;class RI{constructor(e){hc(this,Hd),hc(this,Sa,0),hc(this,Sr),hc(this,Ba),jd(this,Sr,e)}fetch(e,r){const n=yr(this,Sr).fetch??fetch;if(!n)throw new Error("The current environment does not support fetch, you can provide a fetch implementation in the options for SuiHTTPTransport.");return n(e,r)}async request(e){var s,i;jd(this,Sa,yr(this,Sa)+1);const r=await this.fetch(((s=yr(this,Sr).rpc)==null?void 0:s.url)??yr(this,Sr).url,{method:"POST",signal:e.signal,headers:{"Content-Type":"application/json","Client-Sdk-Type":"typescript","Client-Sdk-Version":r2,"Client-Target-Api-Version":xI,"Client-Request-Method":e.method,...(i=yr(this,Sr).rpc)==null?void 0:i.headers},body:JSON.stringify({jsonrpc:"2.0",id:yr(this,Sa),method:e.method,params:e.params})});if(!r.ok)throw new TI(`Unexpected status code: ${r.status}`,r.status,r.statusText);const n=await r.json();if("error"in n&&n.error!=null)throw new s2(n.error.message,n.error.code);return n.result}async subscribe(e){const r=await CI(this,Hd,l2).call(this).subscribe(e);return e.signal&&(e.signal.throwIfAborted(),e.signal.addEventListener("abort",()=>{r()})),async()=>!!await r()}}Sa=new WeakMap;Sr=new WeakMap;Ba=new WeakMap;Hd=new WeakSet;l2=function(){var t;if(!yr(this,Ba)){const e=yr(this,Sr).WebSocketConstructor??WebSocket;if(!e)throw new Error("The current environment does not support WebSocket, you can provide a WebSocketConstructor in the options for SuiHTTPTransport.");jd(this,Ba,new OI(((t=yr(this,Sr).websocket)==null?void 0:t.url)??yr(this,Sr).url,{WebSocketConstructor:e,...yr(this,Sr).websocket}))}return yr(this,Ba)};function fm(t){switch(t){case"mainnet":return"https://fullnode.mainnet.sui.io:443";case"testnet":return"https://fullnode.testnet.sui.io:443";case"devnet":return"https://fullnode.devnet.sui.io:443";case"localnet":return"http://127.0.0.1:9000";default:throw new Error(`Unknown network: ${t}`)}}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function NI(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function f2(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function Ld(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function d2(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Dd(t){if(!Array.isArray(t))throw new Error("array expected")}function h2(t,e){if(!f2(!0,e))throw new Error(`${t}: array of strings expected`)}function UI(t,e){if(!f2(!1,e))throw new Error(`${t}: array of numbers expected`)}function FI(...t){const e=i=>i,r=(i,a)=>o=>i(a(o)),n=t.map(i=>i.encode).reduceRight(r,e),s=t.map(i=>i.decode).reduce(r,e);return{encode:n,decode:s}}function MI(t){const e=typeof t=="string"?t.split(""):t,r=e.length;h2("alphabet",e);const n=new Map(e.map((s,i)=>[s,i]));return{encode:s=>(Dd(s),s.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${t}`);return e[i]})),decode:s=>(Dd(s),s.map(i=>{Ld("alphabet.decode",i);const a=n.get(i);if(a===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${t}`);return a}))}}function $I(t=""){return Ld("join",t),{encode:e=>(h2("join.decode",e),e.join(t)),decode:e=>(Ld("join.decode",e),e.split(t))}}function dm(t,e,r){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(Dd(t),!t.length)return[];let n=0;const s=[],i=Array.from(t,o=>{if(d2(o),o<0||o>=e)throw new Error(`invalid integer: ${o}`);return o}),a=i.length;for(;;){let o=0,c=!0;for(let u=n;u<a;u++){const l=i[u],f=e*o,p=f+l;if(!Number.isSafeInteger(p)||f/e!==o||p-l!==f)throw new Error("convertRadix: carry overflow");const d=p/r;o=p%r;const b=Math.floor(d);if(i[u]=b,!Number.isSafeInteger(b)||b*r+o!==p)throw new Error("convertRadix: carry overflow");if(c)b?c=!1:n=u;else continue}if(s.push(o),c)break}for(let o=0;o<t.length-1&&t[o]===0;o++)s.push(0);return s.reverse()}function jI(t){d2(t);const e=2**8;return{encode:r=>{if(!NI(r))throw new Error("radix.encode input should be Uint8Array");return dm(Array.from(r),e,t)},decode:r=>(UI("radix.decode",r),Uint8Array.from(dm(r,t,e)))}}const HI=t=>FI(jI(58),MI(t),$I("")),p2=HI("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),Mu=t=>p2.encode(t),lo=t=>p2.decode(t);function tr(t){return Uint8Array.from(atob(t),e=>e.charCodeAt(0))}const Pf=8192;function St(t){if(t.length<Pf)return btoa(String.fromCharCode(...t));let e="";for(var r=0;r<t.length;r+=Pf){const n=t.slice(r,r+Pf);e+=String.fromCharCode(...n)}return btoa(e)}function y2(t){var s;const e=t.startsWith("0x")?t.slice(2):t,r=e.length%2===0?e:`0${e}`,n=((s=r.match(/[0-9a-fA-F]{2}/g))==null?void 0:s.map(i=>parseInt(i,16)))??[];if(n.length!==r.length/2)throw new Error(`Invalid hex string ${t}`);return Uint8Array.from(n)}function Xi(t){return t.reduce((e,r)=>e+r.toString(16).padStart(2,"0"),"")}function $u(t,e){return Array.from({length:Math.ceil(t.length/e)},(r,n)=>t.slice(n*e,(n+1)*e))}class m2{constructor(e,r){if(typeof e!="function")throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but got: ${e}.`);this._batchLoadFn=e,this._maxBatchSize=VI(r),this._batchScheduleFn=GI(r),this._cacheKeyFn=qI(r),this._cacheMap=WI(r),this._batch=null,this.name=KI(r)}load(e){if(e==null)throw new TypeError(`The loader.load() function must be called with a value, but got: ${String(e)}.`);const r=DI(this),n=this._cacheMap;let s;if(n){s=this._cacheKeyFn(e);const a=n.get(s);if(a){const o=r.cacheHits||(r.cacheHits=[]);return new Promise(c=>{o.push(()=>{c(a)})})}}r.keys.push(e);const i=new Promise((a,o)=>{r.callbacks.push({resolve:a,reject:o})});return n&&n.set(s,i),i}loadMany(e){if(!b2(e))throw new TypeError(`The loader.loadMany() function must be called with Array<key>, but got: ${e}.`);const r=[];for(let n=0;n<e.length;n++)r.push(this.load(e[n]).catch(s=>s));return Promise.all(r)}clear(e){const r=this._cacheMap;if(r){const n=this._cacheKeyFn(e);r.delete(n)}return this}clearAll(){const e=this._cacheMap;return e&&e.clear(),this}prime(e,r){const n=this._cacheMap;if(n){const s=this._cacheKeyFn(e);if(n.get(s)===void 0){let i;r instanceof Error?(i=Promise.reject(r),i.catch(()=>{})):i=Promise.resolve(r),n.set(s,i)}}return this}}const LI=typeof process=="object"&&typeof process.nextTick=="function"?function(t){Of||(Of=Promise.resolve()),Of.then(()=>{process.nextTick(t)})}:typeof setImmediate=="function"?function(t){setImmediate(t)}:function(t){setTimeout(t)};let Of;function DI(t){const e=t._batch;if(e!==null&&!e.hasDispatched&&e.keys.length<t._maxBatchSize)return e;const r={hasDispatched:!1,keys:[],callbacks:[]};return t._batch=r,t._batchScheduleFn(()=>{zI(t,r)}),r}function zI(t,e){if(e.hasDispatched=!0,e.keys.length===0){zd(e);return}let r;try{r=t._batchLoadFn(e.keys)}catch(n){return Bf(t,e,new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function errored synchronously: ${String(n)}.`))}if(!r||typeof r.then!="function")return Bf(t,e,new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise: ${String(r)}.`));Promise.resolve(r).then(n=>{if(!b2(n))throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array: ${String(n)}.`);if(n.length!==e.keys.length)throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys.
81
81
 
82
82
  Keys:
83
83
  ${String(e.keys)}
84
84
 
85
85
  Values:
86
- ${String(n)}`);Ld(e);for(let s=0;s<e.callbacks.length;s++){const i=n[s];i instanceof Error?e.callbacks[s].reject(i):e.callbacks[s].resolve(i)}}).catch(n=>{Pf(t,e,n)})}function Pf(t,e,r){Ld(e);for(let n=0;n<e.keys.length;n++)t.clear(e.keys[n]),e.callbacks[n].reject(r)}function Ld(t){if(t.cacheHits)for(let e=0;e<t.cacheHits.length;e++)t.cacheHits[e]()}function HI(t){if(!(!t||t.batch!==!1))return 1;const r=t&&t.maxBatchSize;if(r===void 0)return 1/0;if(typeof r!="number"||r<1)throw new TypeError(`maxBatchSize must be a positive number: ${r}`);return r}function LI(t){const e=t&&t.batchScheduleFn;if(e===void 0)return MI;if(typeof e!="function")throw new TypeError(`batchScheduleFn must be a function: ${e}`);return e}function DI(t){const e=t&&t.cacheKeyFn;if(e===void 0)return r=>r;if(typeof e!="function")throw new TypeError(`cacheKeyFn must be a function: ${e}`);return e}function zI(t){if(!(!t||t.cache!==!1))return null;const r=t&&t.cacheMap;if(r===void 0)return new Map;if(r!==null){const s=["get","set","delete","clear"].filter(i=>r&&typeof r[i]!="function");if(s.length!==0)throw new TypeError("Custom cacheMap missing methods: "+s.join(", "))}return r}function VI(t){return t&&t.name?t.name:null}function y2(t){return typeof t=="object"&&t!==null&&"length"in t&&typeof t.length=="number"&&(t.length===0||t.length>0&&Object.prototype.hasOwnProperty.call(t,t.length-1))}function $c(t){let e=BigInt(t);const r=[];let n=0;if(e===0n)return[0];for(;e>0;)r[n]=Number(e&0x7fn),e>>=7n,e>0n&&(r[n]|=128),n+=1;return r}function GI(t){let e=0n,r=0n,n=0;for(;;){if(n>=t.length)throw new Error("ULEB decode error: buffer overflow");const s=t[n];if(n+=1,e+=BigInt(s&127)<<r,!(s&128))break;r+=7n}if(e>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("ULEB decode error: value exceeds MAX_SAFE_INTEGER");return{value:Number(e),length:n}}class qI{constructor(e){this.bytePosition=0,this.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength)}shift(e){return this.bytePosition+=e,this}read8(){const e=this.dataView.getUint8(this.bytePosition);return this.shift(1),e}read16(){const e=this.dataView.getUint16(this.bytePosition,!0);return this.shift(2),e}read32(){const e=this.dataView.getUint32(this.bytePosition,!0);return this.shift(4),e}read64(){const e=this.read32(),n=this.read32().toString(16)+e.toString(16).padStart(8,"0");return BigInt("0x"+n).toString(10)}read128(){const e=BigInt(this.read64()),n=BigInt(this.read64()).toString(16)+e.toString(16).padStart(16,"0");return BigInt("0x"+n).toString(10)}read256(){const e=BigInt(this.read128()),n=BigInt(this.read128()).toString(16)+e.toString(16).padStart(32,"0");return BigInt("0x"+n).toString(10)}readBytes(e){const r=this.bytePosition+this.dataView.byteOffset,n=new Uint8Array(this.dataView.buffer,r,e);return this.shift(e),n}readULEB(){const e=this.bytePosition+this.dataView.byteOffset,r=new Uint8Array(this.dataView.buffer,e),{value:n,length:s}=GI(r);return this.shift(s),n}readVec(e){const r=this.readULEB(),n=[];for(let s=0;s<r;s++)n.push(e(this,s,r));return n}}function WI(t,e){switch(e){case"base58":return Uu(t);case"base64":return St(t);case"hex":return Xi(t);default:throw new Error("Unsupported encoding, supported values are: base64, hex")}}function m2(t,e=["<",">"]){const[r,n]=e,s=[];let i="",a=0;for(let o=0;o<t.length;o++){const c=t[o];if(c===r&&a++,c===n&&a--,a===0&&c===","){s.push(i.trim()),i="";continue}i+=c}return s.push(i.trim()),s}class KI{constructor({initialSize:e=1024,maxSize:r=1/0,allocateSize:n=1024}={}){this.bytePosition=0,this.size=e,this.maxSize=r,this.allocateSize=n,this.dataView=new DataView(new ArrayBuffer(e))}ensureSizeOrGrow(e){const r=this.bytePosition+e;if(r>this.size){const n=Math.min(this.maxSize,Math.max(this.size+r,this.size+this.allocateSize));if(r>n)throw new Error(`Attempting to serialize to BCS, but buffer does not have enough size. Allocated size: ${this.size}, Max size: ${this.maxSize}, Required size: ${r}`);this.size=n;const s=new ArrayBuffer(this.size);new Uint8Array(s).set(new Uint8Array(this.dataView.buffer)),this.dataView=new DataView(s)}}shift(e){return this.bytePosition+=e,this}write8(e){return this.ensureSizeOrGrow(1),this.dataView.setUint8(this.bytePosition,Number(e)),this.shift(1)}writeBytes(e){this.ensureSizeOrGrow(e.length);for(let r=0;r<e.length;r++)this.dataView.setUint8(this.bytePosition+r,e[r]);return this.shift(e.length)}write16(e){return this.ensureSizeOrGrow(2),this.dataView.setUint16(this.bytePosition,Number(e),!0),this.shift(2)}write32(e){return this.ensureSizeOrGrow(4),this.dataView.setUint32(this.bytePosition,Number(e),!0),this.shift(4)}write64(e){return Of(BigInt(e),8).forEach(r=>this.write8(r)),this}write128(e){return Of(BigInt(e),16).forEach(r=>this.write8(r)),this}write256(e){return Of(BigInt(e),32).forEach(r=>this.write8(r)),this}writeULEB(e){return $c(e).forEach(r=>this.write8(r)),this}writeVec(e,r){return this.writeULEB(e.length),Array.from(e).forEach((n,s)=>r(this,n,s,e.length)),this}*[Symbol.iterator](){for(let e=0;e<this.bytePosition;e++)yield this.dataView.getUint8(e);return this.toBytes()}toBytes(){return new Uint8Array(this.dataView.buffer.slice(0,this.bytePosition))}toString(e){return WI(this.toBytes(),e)}}function Of(t,e){const r=new Uint8Array(e);let n=0;for(;t>0;)r[n]=Number(t%BigInt(256)),t=t/BigInt(256),n+=1;return r}var b2=t=>{throw TypeError(t)},g2=(t,e,r)=>e.has(t)||b2("Cannot "+r),xr=(t,e,r)=>(g2(t,e,"read from private field"),r?r.call(t):e.get(t)),jc=(t,e,r)=>e.has(t)?b2("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Hc=(t,e,r,n)=>(g2(t,e,"write to private field"),e.set(t,r),r),Ai,xa,Ac,es;const XI=class w2{constructor(e){jc(this,Ai),jc(this,xa),this.name=e.name,this.read=e.read,this.serializedSize=e.serializedSize??(()=>null),Hc(this,Ai,e.write),Hc(this,xa,e.serialize??((r,n)=>{const s=new KI({initialSize:this.serializedSize(r)??void 0,...n});return xr(this,Ai).call(this,r,s),s.toBytes()})),this.validate=e.validate??(()=>{})}write(e,r){this.validate(e),xr(this,Ai).call(this,e,r)}serialize(e,r){return this.validate(e),new YI(this,xr(this,xa).call(this,e,r))}parse(e){const r=new qI(e);return this.read(r)}fromHex(e){return this.parse(h2(e))}fromBase58(e){return this.parse(lo(e))}fromBase64(e){return this.parse(tr(e))}transform({name:e,input:r,output:n,validate:s}){return new w2({name:e??this.name,read:i=>n?n(this.read(i)):this.read(i),write:(i,a)=>xr(this,Ai).call(this,r?r(i):i,a),serializedSize:i=>this.serializedSize(r?r(i):i),serialize:(i,a)=>xr(this,xa).call(this,r?r(i):i,a),validate:i=>{s==null||s(i),this.validate(r?r(i):i)}})}};Ai=new WeakMap;xa=new WeakMap;let on=XI;const v2=Symbol.for("@mysten/serialized-bcs");function b0(t){return!!t&&typeof t=="object"&&t[v2]===!0}class YI{constructor(e,r){jc(this,Ac),jc(this,es),Hc(this,Ac,e),Hc(this,es,r)}get[v2](){return!0}toBytes(){return xr(this,es)}toHex(){return Xi(xr(this,es))}toBase64(){return St(xr(this,es))}toBase58(){return Uu(xr(this,es))}parse(){return xr(this,Ac).parse(xr(this,es))}}Ac=new WeakMap;es=new WeakMap;function Lc({size:t,...e}){return new on({...e,serializedSize:()=>t})}function Bf({readMethod:t,writeMethod:e,...r}){return Lc({...r,read:n=>n[t](),write:(n,s)=>s[e](n),validate:n=>{var s;if(n<0||n>r.maxValue)throw new TypeError(`Invalid ${r.name} value: ${n}. Expected value in range 0-${r.maxValue}`);(s=r.validate)==null||s.call(r,n)}})}function Cf({readMethod:t,writeMethod:e,...r}){return Lc({...r,read:n=>n[t](),write:(n,s)=>s[e](BigInt(n)),validate:n=>{var i;const s=BigInt(n);if(s<0||s>r.maxValue)throw new TypeError(`Invalid ${r.name} value: ${s}. Expected value in range 0-${r.maxValue}`);(i=r.validate)==null||i.call(r,s)}})}function JI({serialize:t,...e}){const r=new on({...e,serialize:t,write:(n,s)=>{for(const i of r.serialize(n).toBytes())s.write8(i)}});return r}function ZI({toBytes:t,fromBytes:e,...r}){return new on({...r,read:n=>{const s=n.readULEB(),i=n.readBytes(s);return e(i)},write:(n,s)=>{const i=t(n);s.writeULEB(i.length);for(let a=0;a<i.length;a++)s.write8(i[a])},serialize:n=>{const s=t(n),i=$c(s.length),a=new Uint8Array(i.length+s.length);return a.set(i,0),a.set(s,i.length),a},validate:n=>{var s;if(typeof n!="string")throw new TypeError(`Invalid ${r.name} value: ${n}. Expected string`);(s=r.validate)==null||s.call(r,n)}})}function QI(t){let e=null;function r(){return e||(e=t()),e}return new on({name:"lazy",read:n=>r().read(n),serializedSize:n=>r().serializedSize(n),write:(n,s)=>r().write(n,s),serialize:(n,s)=>r().serialize(n,s).toBytes()})}class eP extends on{constructor({name:e,fields:r,...n}){const s=Object.entries(r);super({name:e,serializedSize:i=>{let a=0;for(const[o,c]of s){const u=c.serializedSize(i[o]);if(u==null)return null;a+=u}return a},read:i=>{const a={};for(const[o,c]of s)a[o]=c.read(i);return a},write:(i,a)=>{for(const[o,c]of s)c.write(i[o],a)},...n,validate:i=>{var a;if((a=n==null?void 0:n.validate)==null||a.call(n,i),typeof i!="object"||i==null)throw new TypeError(`Expected object, found ${typeof i}`)}})}}class tP extends on{constructor({fields:e,...r}){const n=Object.entries(e);super({read:s=>{const i=s.readULEB(),a=n[i];if(!a)throw new TypeError(`Unknown value ${i} for enum ${r.name}`);const[o,c]=a;return{[o]:(c==null?void 0:c.read(s))??!0,$kind:o}},write:(s,i)=>{const[a,o]=Object.entries(s).filter(([c])=>Object.hasOwn(e,c))[0];for(let c=0;c<n.length;c++){const[u,l]=n[c];if(u===a){i.writeULEB(c),l==null||l.write(o,i);return}}},...r,validate:s=>{var o;if((o=r==null?void 0:r.validate)==null||o.call(r,s),typeof s!="object"||s==null)throw new TypeError(`Expected object, found ${typeof s}`);const i=Object.keys(s).filter(c=>s[c]!==void 0&&Object.hasOwn(e,c));if(i.length!==1)throw new TypeError(`Expected object with one key, but found ${i.length} for type ${r.name}}`);const[a]=i;if(!Object.hasOwn(e,a))throw new TypeError(`Invalid enum variant ${a}`)}})}}class rP extends on{constructor({fields:e,name:r,...n}){super({name:r??`(${e.map(s=>s.name).join(", ")})`,serializedSize:s=>{let i=0;for(let a=0;a<e.length;a++){const o=e[a].serializedSize(s[a]);if(o==null)return null;i+=o}return i},read:s=>{const i=[];for(const a of e)i.push(a.read(s));return i},write:(s,i)=>{for(let a=0;a<e.length;a++)e[a].write(s[a],i)},...n,validate:s=>{var i;if((i=n==null?void 0:n.validate)==null||i.call(n,s),!Array.isArray(s))throw new TypeError(`Expected array, found ${typeof s}`);if(s.length!==e.length)throw new TypeError(`Expected array of length ${e.length}, found ${s.length}`)}})}}function nP(t,e,r){return new on({read:n=>{const s=new Array(t);for(let i=0;i<t;i++)s[i]=e.read(n);return s},write:(n,s)=>{for(const i of n)e.write(i,s)},...r,name:(r==null?void 0:r.name)??`${e.name}[${t}]`,validate:n=>{var s;if((s=r==null?void 0:r.validate)==null||s.call(r,n),!n||typeof n!="object"||!("length"in n))throw new TypeError(`Expected array, found ${typeof n}`);if(n.length!==t)throw new TypeError(`Expected array of length ${t}, found ${n.length}`)}})}function sP(t){return P.enum(`Option<${t.name}>`,{None:null,Some:t}).transform({input:e=>e==null?{None:!0}:{Some:e},output:e=>e.$kind==="Some"?e.Some:null})}function iP(t,e){return new on({read:r=>{const n=r.readULEB(),s=new Array(n);for(let i=0;i<n;i++)s[i]=t.read(r);return s},write:(r,n)=>{n.writeULEB(r.length);for(const s of r)t.write(s,n)},...e,name:(e==null?void 0:e.name)??`vector<${t.name}>`,validate:r=>{var n;if((n=e==null?void 0:e.validate)==null||n.call(e,r),!r||typeof r!="object"||!("length"in r))throw new TypeError(`Expected array, found ${typeof r}`)}})}function aP(t,e){return P.vector(P.tuple([t,e])).transform({name:`Map<${t.name}, ${e.name}>`,input:r=>[...r.entries()],output:r=>{const n=new Map;for(const[s,i]of r)n.set(s,i);return n}})}const P={u8(t){return Bf({readMethod:"read8",writeMethod:"write8",size:1,maxValue:2**8-1,...t,name:(t==null?void 0:t.name)??"u8"})},u16(t){return Bf({readMethod:"read16",writeMethod:"write16",size:2,maxValue:2**16-1,...t,name:(t==null?void 0:t.name)??"u16"})},u32(t){return Bf({readMethod:"read32",writeMethod:"write32",size:4,maxValue:2**32-1,...t,name:(t==null?void 0:t.name)??"u32"})},u64(t){return Cf({readMethod:"read64",writeMethod:"write64",size:8,maxValue:2n**64n-1n,...t,name:(t==null?void 0:t.name)??"u64"})},u128(t){return Cf({readMethod:"read128",writeMethod:"write128",size:16,maxValue:2n**128n-1n,...t,name:(t==null?void 0:t.name)??"u128"})},u256(t){return Cf({readMethod:"read256",writeMethod:"write256",size:32,maxValue:2n**256n-1n,...t,name:(t==null?void 0:t.name)??"u256"})},bool(t){return Lc({size:1,read:e=>e.read8()===1,write:(e,r)=>r.write8(e?1:0),...t,name:(t==null?void 0:t.name)??"bool",validate:e=>{var r;if((r=t==null?void 0:t.validate)==null||r.call(t,e),typeof e!="boolean")throw new TypeError(`Expected boolean, found ${typeof e}`)}})},uleb128(t){return JI({read:e=>e.readULEB(),serialize:e=>Uint8Array.from($c(e)),...t,name:(t==null?void 0:t.name)??"uleb128"})},bytes(t,e){return Lc({size:t,read:r=>r.readBytes(t),write:(r,n)=>{n.writeBytes(new Uint8Array(r))},...e,name:(e==null?void 0:e.name)??`bytes[${t}]`,validate:r=>{var n;if((n=e==null?void 0:e.validate)==null||n.call(e,r),!r||typeof r!="object"||!("length"in r))throw new TypeError(`Expected array, found ${typeof r}`);if(r.length!==t)throw new TypeError(`Expected array of length ${t}, found ${r.length}`)}})},byteVector(t){return new on({read:e=>{const r=e.readULEB();return e.readBytes(r)},write:(e,r)=>{const n=new Uint8Array(e);r.writeULEB(n.length),r.writeBytes(n)},...t,name:(t==null?void 0:t.name)??"vector<u8>",serializedSize:e=>{const r="length"in e?e.length:null;return r==null?null:$c(r).length+r},validate:e=>{var r;if((r=t==null?void 0:t.validate)==null||r.call(t,e),!e||typeof e!="object"||!("length"in e))throw new TypeError(`Expected array, found ${typeof e}`)}})},string(t){return ZI({toBytes:e=>new TextEncoder().encode(e),fromBytes:e=>new TextDecoder().decode(e),...t,name:(t==null?void 0:t.name)??"string"})},fixedArray:nP,option:sP,vector:iP,tuple(t,e){return new rP({fields:t,...e})},struct(t,e,r){return new eP({name:t,fields:e,...r})},enum(t,e,r){return new tP({name:t,fields:e,...r})},map:aP,lazy(t){return QI(t)}};var E2=t=>{throw TypeError(t)},A2=(t,e,r)=>e.has(t)||E2("Cannot "+r),vt=(t,e,r)=>(A2(t,e,"read from private field"),e.get(t)),fm=(t,e,r)=>e.has(t)?E2("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),dm=(t,e,r,n)=>(A2(t,e,"write to private field"),e.set(t,r),r),Os,Ct;const oP=class S2{constructor({prefix:e,cache:r}={}){fm(this,Os),fm(this,Ct),dm(this,Os,e??[]),dm(this,Ct,r??new Map)}read(e,r){const n=[vt(this,Os),...e].join(":");if(vt(this,Ct).has(n))return vt(this,Ct).get(n);const s=r();return vt(this,Ct).set(n,s),typeof s=="object"&&s!==null&&"then"in s?Promise.resolve(s).then(i=>(vt(this,Ct).set(n,i),i)).catch(i=>{throw vt(this,Ct).delete(n),i}):s}readSync(e,r){const n=[vt(this,Os),...e].join(":");if(vt(this,Ct).has(n))return vt(this,Ct).get(n);const s=r();return vt(this,Ct).set(n,s),s}clear(e){const r=[...vt(this,Os),...e??[]].join(":");if(!r){vt(this,Ct).clear();return}for(const n of vt(this,Ct).keys())n.startsWith(r)&&vt(this,Ct).delete(n)}scope(e){return new S2({prefix:[...vt(this,Os),...Array.isArray(e)?e:[e]],cache:vt(this,Ct)})}};Os=new WeakMap;Ct=new WeakMap;let cP=oP;class x2{constructor({network:e,base:r,cache:n=(r==null?void 0:r.cache)??new cP}){this.network=e,this.base=r??this,this.cache=n}$extend(...e){return Object.create(this,Object.fromEntries(e.map(r=>[r.name,{value:r.register(this)}])))}}let mn;function k2(t){return{lang:(t==null?void 0:t.lang)??(mn==null?void 0:mn.lang),message:t==null?void 0:t.message,abortEarly:(t==null?void 0:t.abortEarly)??(mn==null?void 0:mn.abortEarly),abortPipeEarly:(t==null?void 0:t.abortPipeEarly)??(mn==null?void 0:mn.abortPipeEarly)}}let Rf;function uP(t){return Rf==null?void 0:Rf.get(t)}let Nf;function lP(t){return Nf==null?void 0:Nf.get(t)}let Uf;function fP(t,e){var r;return(r=Uf==null?void 0:Uf.get(t))==null?void 0:r.get(e)}function T2(t){var r,n;const e=typeof t;return e==="string"?`"${t}"`:e==="number"||e==="bigint"||e==="boolean"?`${t}`:e==="object"||e==="function"?(t&&((n=(r=Object.getPrototypeOf(t))==null?void 0:r.constructor)==null?void 0:n.name))??"null":e}function qt(t,e,r,n,s){const i=s&&"input"in s?s.input:r.value,a=(s==null?void 0:s.expected)??t.expects??null,o=(s==null?void 0:s.received)??T2(i),c={kind:t.kind,type:t.type,input:i,expected:a,received:o,message:`Invalid ${e}: ${a?`Expected ${a} but r`:"R"}eceived ${o}`,requirement:t.requirement,path:s==null?void 0:s.path,issues:s==null?void 0:s.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},u=t.kind==="schema",l=(s==null?void 0:s.message)??t.message??fP(t.reference,c.lang)??(u?lP(c.lang):null)??n.message??uP(c.lang);l!==void 0&&(c.message=typeof l=="function"?l(c):l),u&&(r.typed=!1),r.issues?r.issues.push(c):r.issues=[c]}function Tt(t){return{version:1,vendor:"valibot",validate(e){return t["~run"]({value:e},k2())}}}function dP(t,e){return Object.hasOwn(t,e)&&e!=="__proto__"&&e!=="prototype"&&e!=="constructor"}function hP(t,e){const r=[...new Set(t)];return r.length>1?`(${r.join(` ${e} `)})`:r[0]??"never"}var pP=class extends Error{constructor(t){super(t[0].message),this.name="ValiError",this.issues=t}};function g0(t,e){return{kind:"validation",type:"check",reference:g0,async:!1,expects:null,requirement:t,message:e,"~run"(r,n){return r.typed&&!this.requirement(r.value)&&qt(this,"input",r,n),r}}}function Dt(t){return{kind:"validation",type:"integer",reference:Dt,async:!1,expects:null,requirement:Number.isInteger,message:t,"~run"(e,r){return e.typed&&!this.requirement(e.value)&&qt(this,"integer",e,r),e}}}function Mu(t){return{kind:"transformation",type:"transform",reference:Mu,async:!1,operation:t,"~run"(e){return e.value=this.operation(e.value),e}}}function yP(t,e,r){return typeof t.fallback=="function"?t.fallback(e,r):t.fallback}function $u(t,e,r){return typeof t.default=="function"?t.default(e,r):t.default}function Dd(t,e){return!t["~run"]({value:e},{abortEarly:!0}).issues}function xe(t,e){return{kind:"schema",type:"array",reference:xe,expects:"Array",async:!1,item:t,message:e,get"~standard"(){return Tt(this)},"~run"(r,n){var i;const s=r.value;if(Array.isArray(s)){r.typed=!0,r.value=[];for(let a=0;a<s.length;a++){const o=s[a],c=this.item["~run"]({value:o},n);if(c.issues){const u={type:"array",origin:"value",input:s,key:a,value:o};for(const l of c.issues)l.path?l.path.unshift(u):l.path=[u],(i=r.issues)==null||i.push(l);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value.push(c.value)}}else qt(this,"type",r,n);return r}}}function _2(t){return{kind:"schema",type:"bigint",reference:_2,expects:"bigint",async:!1,message:t,get"~standard"(){return Tt(this)},"~run"(e,r){return typeof e.value=="bigint"?e.typed=!0:qt(this,"type",e,r),e}}}function ia(t){return{kind:"schema",type:"boolean",reference:ia,expects:"boolean",async:!1,message:t,get"~standard"(){return Tt(this)},"~run"(e,r){return typeof e.value=="boolean"?e.typed=!0:qt(this,"type",e,r),e}}}function zd(t){return{kind:"schema",type:"lazy",reference:zd,expects:"unknown",async:!1,getter:t,get"~standard"(){return Tt(this)},"~run"(e,r){return this.getter(e.value)["~run"](e,r)}}}function at(t,e){return{kind:"schema",type:"literal",reference:at,expects:T2(t),async:!1,literal:t,message:e,get"~standard"(){return Tt(this)},"~run"(r,n){return r.value===this.literal?r.typed=!0:qt(this,"type",r,n),r}}}function Ke(t,e){return{kind:"schema",type:"nullable",reference:Ke,expects:`(${t.expects} | null)`,async:!1,wrapped:t,default:e,get"~standard"(){return Tt(this)},"~run"(r,n){return r.value===null&&(this.default!==void 0&&(r.value=$u(this,r,n)),r.value===null)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}function fo(t,e){return{kind:"schema",type:"nullish",reference:fo,expects:`(${t.expects} | null | undefined)`,async:!1,wrapped:t,default:e,get"~standard"(){return Tt(this)},"~run"(r,n){return(r.value===null||r.value===void 0)&&(this.default!==void 0&&(r.value=$u(this,r,n)),r.value===null||r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}function zt(t){return{kind:"schema",type:"number",reference:zt,expects:"number",async:!1,message:t,get"~standard"(){return Tt(this)},"~run"(e,r){return typeof e.value=="number"&&!isNaN(e.value)?e.typed=!0:qt(this,"type",e,r),e}}}function de(t,e){return{kind:"schema",type:"object",reference:de,expects:"Object",async:!1,entries:t,message:e,get"~standard"(){return Tt(this)},"~run"(r,n){var i;const s=r.value;if(s&&typeof s=="object"){r.typed=!0,r.value={};for(const a in this.entries){const o=this.entries[a];if(a in s||(o.type==="exact_optional"||o.type==="optional"||o.type==="nullish")&&o.default!==void 0){const c=a in s?s[a]:$u(o),u=o["~run"]({value:c},n);if(u.issues){const l={type:"object",origin:"value",input:s,key:a,value:c};for(const f of u.issues)f.path?f.path.unshift(l):f.path=[l],(i=r.issues)==null||i.push(f);if(r.issues||(r.issues=u.issues),n.abortEarly){r.typed=!1;break}}u.typed||(r.typed=!1),r.value[a]=u.value}else if(o.fallback!==void 0)r.value[a]=yP(o);else if(o.type!=="exact_optional"&&o.type!=="optional"&&o.type!=="nullish"&&(qt(this,"key",r,n,{input:void 0,expected:`"${a}"`,path:[{type:"object",origin:"key",input:s,key:a,value:s[a]}]}),n.abortEarly))break}}else qt(this,"type",r,n);return r}}}function er(t,e){return{kind:"schema",type:"optional",reference:er,expects:`(${t.expects} | undefined)`,async:!1,wrapped:t,default:e,get"~standard"(){return Tt(this)},"~run"(r,n){return r.value===void 0&&(this.default!==void 0&&(r.value=$u(this,r,n)),r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}function ho(t,e,r){return{kind:"schema",type:"record",reference:ho,expects:"Object",async:!1,key:t,value:e,message:r,get"~standard"(){return Tt(this)},"~run"(n,s){var a,o;const i=n.value;if(i&&typeof i=="object"){n.typed=!0,n.value={};for(const c in i)if(dP(i,c)){const u=i[c],l=this.key["~run"]({value:c},s);if(l.issues){const p={type:"object",origin:"key",input:i,key:c,value:u};for(const d of l.issues)d.path=[p],(a=n.issues)==null||a.push(d);if(n.issues||(n.issues=l.issues),s.abortEarly){n.typed=!1;break}}const f=this.value["~run"]({value:u},s);if(f.issues){const p={type:"object",origin:"value",input:i,key:c,value:u};for(const d of f.issues)d.path?d.path.unshift(p):d.path=[p],(o=n.issues)==null||o.push(d);if(n.issues||(n.issues=f.issues),s.abortEarly){n.typed=!1;break}}(!l.typed||!f.typed)&&(n.typed=!1),l.typed&&(n.value[l.value]=f.value)}}else qt(this,"type",n,s);return n}}}function _e(t){return{kind:"schema",type:"string",reference:_e,expects:"string",async:!1,message:t,get"~standard"(){return Tt(this)},"~run"(e,r){return typeof e.value=="string"?e.typed=!0:qt(this,"type",e,r),e}}}function w0(t,e){return{kind:"schema",type:"tuple",reference:w0,expects:"Array",async:!1,items:t,message:e,get"~standard"(){return Tt(this)},"~run"(r,n){var i;const s=r.value;if(Array.isArray(s)){r.typed=!0,r.value=[];for(let a=0;a<this.items.length;a++){const o=s[a],c=this.items[a]["~run"]({value:o},n);if(c.issues){const u={type:"array",origin:"value",input:s,key:a,value:o};for(const l of c.issues)l.path?l.path.unshift(u):l.path=[u],(i=r.issues)==null||i.push(l);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value.push(c.value)}}else qt(this,"type",r,n);return r}}}function hm(t){let e;if(t)for(const r of t)e?e.push(...r.issues):e=r.issues;return e}function cn(t,e){return{kind:"schema",type:"union",reference:cn,expects:hP(t.map(r=>r.expects),"|"),async:!1,options:t,message:e,get"~standard"(){return Tt(this)},"~run"(r,n){let s,i,a;for(const o of this.options){const c=o["~run"]({value:r.value},n);if(c.typed)if(c.issues)i?i.push(c):i=[c];else{s=c;break}else a?a.push(c):a=[c]}if(s)return s;if(i){if(i.length===1)return i[0];qt(this,"type",r,n,{issues:hm(i)}),r.typed=!0}else{if((a==null?void 0:a.length)===1)return a[0];qt(this,"type",r,n,{issues:hm(a)})}return r}}}function zo(){return{kind:"schema",type:"unknown",reference:zo,expects:"unknown",async:!1,get"~standard"(){return Tt(this)},"~run"(t){return t.typed=!0,t}}}function Ve(t,e,r){const n=t["~run"]({value:e},k2(r));if(n.issues)throw new pP(n.issues);return n.value}function mt(...t){return{...t[0],pipe:t,get"~standard"(){return Tt(this)},"~run"(e,r){for(const n of t)if(n.kind!=="metadata"){if(e.issues&&(n.kind==="schema"||n.kind==="transformation")){e.typed=!1;break}(!e.issues||!r.abortEarly&&!r.abortPipeEarly)&&(e=n["~run"](e,r))}return e}}}const I2=/^(?!.*(^(?!@)|[-.@])($|[-.@]))(?:[a-z0-9-]{0,63}(?:\.[a-z0-9-]{0,63})*)?@[a-z0-9-]{0,63}$/i,P2=/^(?!.*(^|[-.])($|[-.]))(?:[a-z0-9-]{0,63}\.)+sui$/i,mP=235;function bP(t){return t.length>mP?!1:t.includes("@")?I2.test(t):P2.test(t)}function gP(t,e="at"){const r=t.toLowerCase();let n;if(r.includes("@")){if(!I2.test(r))throw new Error(`Invalid SuiNS name ${t}`);const[s,i]=r.split("@");n=[...s?s.split("."):[],i]}else{if(!P2.test(r))throw new Error(`Invalid SuiNS name ${t}`);n=r.split(".").slice(0,-1)}return e==="dot"?`${n.join(".")}.sui`:`${n.slice(0,-1).join(".")}@${n[n.length-1]}`}const wP=/^([a-z0-9]+(?:-[a-z0-9]+)*)$/,vP=/^\d+$/,EP=64,O2="/",Yt=t=>{const e=t.split(O2);if(e.length<2||e.length>3)return!1;const[r,n,s]=e;return s!==void 0&&!vP.test(s)||!bP(r)?!1:wP.test(n)&&n.length<EP},AP=t=>{const e=t.split(/::|<|>|,/);for(const r of e)if(r.includes(O2)&&!Yt(r))return!1;return!0},SP=32;function pm(t){try{return lo(t).length===SP}catch{return!1}}const ju=32;function kr(t){return kP(t)&&TP(t)===ju}function dc(t){return kr(t)}function xP(t){return t.includes("::")?ri(t):t}function ri(t){const[e,r]=t.split("::"),n=Yt(e),s=t.slice(e.length+r.length+4),i=s.includes("<")?s.slice(0,s.indexOf("<")):s,a=s.includes("<")?m2(s.slice(s.indexOf("<")+1,s.lastIndexOf(">"))).map(o=>xP(o.trim())):[];return{address:n?e:ve(e),module:r,name:i,typeParams:a}}function Dc(t){const{address:e,module:r,name:n,typeParams:s}=typeof t=="string"?ri(t):t,i=(s==null?void 0:s.length)>0?`<${s.map(a=>typeof a=="string"?a:Dc(a)).join(",")}>`:"";return`${e}::${r}::${n}${i}`}function ve(t,e=!1){let r=t.toLowerCase();return!e&&r.startsWith("0x")&&(r=r.slice(2)),`0x${r.padStart(ju*2,"0")}`}function tn(t,e=!1){return ve(t,e)}function kP(t){return/^(0x|0X)?[a-fA-F0-9]+$/.test(t)&&t.length%2===0}function TP(t){return/^(0x|0X)/.test(t)?(t.length-2)/2:t.length/2}function li(t){const e=Object.entries(t).map(([r,n])=>de({[r]:n}));return mt(cn(e),Mu(r=>({...r,$kind:Object.keys(r)[0]})))}const aa=mt(_e(),Mu(t=>ve(t)),g0(kr)),rr=aa,ni=_e(),Wt=mt(cn([_e(),mt(zt(),Dt())]),g0(t=>{try{return BigInt(t),BigInt(t)>=0&&BigInt(t)<=18446744073709551615n}catch{return!1}},"Invalid u64")),gs=de({objectId:aa,version:Wt,digest:_e()}),Me=mt(cn([de({GasCoin:at(!0)}),de({Input:mt(zt(),Dt()),type:er(at("pure"))}),de({Input:mt(zt(),Dt()),type:er(at("object"))}),de({Result:mt(zt(),Dt())}),de({NestedResult:w0([mt(zt(),Dt()),mt(zt(),Dt())])})]),Mu(t=>({...t,$kind:Object.keys(t)[0]}))),_P=de({budget:Ke(Wt),price:Ke(Wt),owner:Ke(aa),payment:Ke(xe(gs))}),Vd=cn([at("address"),at("bool"),at("u8"),at("u16"),at("u32"),at("u64"),at("u128"),at("u256"),de({vector:zd(()=>Vd)}),de({datatype:de({package:_e(),module:_e(),type:_e(),typeParameters:xe(zd(()=>Vd))})}),de({typeParameter:mt(zt(),Dt())})]),IP=de({ref:Ke(cn([at("&"),at("&mut")])),body:Vd}),PP=de({package:rr,module:_e(),function:_e(),typeArguments:xe(_e()),arguments:xe(Me),_argumentTypes:er(Ke(xe(IP)))}),OP=de({name:_e(),inputs:ho(_e(),cn([Me,xe(Me)])),data:ho(_e(),zo())}),BP=li({MoveCall:PP,TransferObjects:de({objects:xe(Me),address:Me}),SplitCoins:de({coin:Me,amounts:xe(Me)}),MergeCoins:de({destination:Me,sources:xe(Me)}),Publish:de({modules:xe(ni),dependencies:xe(rr)}),MakeMoveVec:de({type:Ke(_e()),elements:xe(Me)}),Upgrade:de({modules:xe(ni),dependencies:xe(rr),package:rr,ticket:Me}),$Intent:OP}),B2=li({ImmOrOwnedObject:gs,SharedObject:de({objectId:rr,initialSharedVersion:Wt,mutable:ia()}),Receiving:gs}),CP=li({Object:B2,Pure:de({bytes:ni}),UnresolvedPure:de({value:zo()}),UnresolvedObject:de({objectId:rr,version:er(Ke(Wt)),digest:er(Ke(_e())),initialSharedVersion:er(Ke(Wt)),mutable:er(Ke(ia()))})}),ym=li({Object:B2,Pure:de({bytes:ni})}),C2=li({None:at(!0),Epoch:Wt}),Sc=de({version:at(2),sender:fo(aa),expiration:fo(C2),gasData:_P,inputs:xe(CP),commands:xe(BP)}),Ps={MoveCall(t){const[e,r="",n=""]="target"in t?t.target.split("::"):[t.package,t.module,t.function];return{$kind:"MoveCall",MoveCall:{package:e,module:r,function:n,typeArguments:t.typeArguments??[],arguments:t.arguments??[]}}},TransferObjects(t,e){return{$kind:"TransferObjects",TransferObjects:{objects:t.map(r=>Ve(Me,r)),address:Ve(Me,e)}}},SplitCoins(t,e){return{$kind:"SplitCoins",SplitCoins:{coin:Ve(Me,t),amounts:e.map(r=>Ve(Me,r))}}},MergeCoins(t,e){return{$kind:"MergeCoins",MergeCoins:{destination:Ve(Me,t),sources:e.map(r=>Ve(Me,r))}}},Publish({modules:t,dependencies:e}){return{$kind:"Publish",Publish:{modules:t.map(r=>typeof r=="string"?r:St(new Uint8Array(r))),dependencies:e.map(r=>tn(r))}}},Upgrade({modules:t,dependencies:e,package:r,ticket:n}){return{$kind:"Upgrade",Upgrade:{modules:t.map(s=>typeof s=="string"?s:St(new Uint8Array(s))),dependencies:e.map(s=>tn(s)),package:r,ticket:Ve(Me,n)}}},MakeMoveVec({type:t,elements:e}){return{$kind:"MakeMoveVec",MakeMoveVec:{type:t??null,elements:e.map(r=>Ve(Me,r))}}},Intent({name:t,inputs:e={},data:r={}}){return{$kind:"$Intent",$Intent:{name:t,inputs:Object.fromEntries(Object.entries(e).map(([n,s])=>[n,Array.isArray(s)?s.map(i=>Ve(Me,i)):Ve(Me,s)])),data:r}}}},RP=/^vector<(.+)>$/,NP=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;class Tr{static parseFromStr(e,r=!1){if(e==="address")return{address:null};if(e==="bool")return{bool:null};if(e==="u8")return{u8:null};if(e==="u16")return{u16:null};if(e==="u32")return{u32:null};if(e==="u64")return{u64:null};if(e==="u128")return{u128:null};if(e==="u256")return{u256:null};if(e==="signer")return{signer:null};const n=e.match(RP);if(n)return{vector:Tr.parseFromStr(n[1],r)};const s=e.match(NP);if(s)return{struct:{address:r?ve(s[1]):s[1],module:s[2],name:s[3],typeParams:s[5]===void 0?[]:Tr.parseStructTypeArgs(s[5],r)}};throw new Error(`Encountered unexpected token when parsing type args for ${e}`)}static parseStructTypeArgs(e,r=!1){return m2(e).map(n=>Tr.parseFromStr(n,r))}static tagToString(e){if("bool"in e)return"bool";if("u8"in e)return"u8";if("u16"in e)return"u16";if("u32"in e)return"u32";if("u64"in e)return"u64";if("u128"in e)return"u128";if("u256"in e)return"u256";if("address"in e)return"address";if("signer"in e)return"signer";if("vector"in e)return`vector<${Tr.tagToString(e.vector)}>`;if("struct"in e){const r=e.struct,n=r.typeParams.map(Tr.tagToString).join(", ");return`${r.address}::${r.module}::${r.name}${n?`<${n}>`:""}`}throw new Error("Invalid TypeTag")}}function UP(t){return P.u64({name:"unsafe_u64",...t}).transform({input:e=>e,output:e=>Number(e)})}function FP(t){return P.enum("Option",{None:null,Some:t})}const $e=P.bytes(ju).transform({validate:t=>{const e=typeof t=="string"?t:Xi(t);if(!e||!kr(ve(e)))throw new Error(`Invalid Sui address ${e}`)},input:t=>typeof t=="string"?h2(ve(t)):t,output:t=>ve(Xi(t))}),Or=P.byteVector().transform({name:"ObjectDigest",input:t=>lo(t),output:t=>Uu(new Uint8Array(t)),validate:t=>{if(lo(t).length!==32)throw new Error("ObjectDigest must be 32 bytes")}}),pr=P.struct("SuiObjectRef",{objectId:$e,version:P.u64(),digest:Or}),R2=P.struct("SharedObjectRef",{objectId:$e,initialSharedVersion:P.u64(),mutable:P.bool()}),N2=P.enum("ObjectArg",{ImmOrOwnedObject:pr,SharedObject:R2,Receiving:pr}),Fs=P.enum("Owner",{AddressOwner:$e,ObjectOwner:$e,Shared:P.struct("Shared",{initialSharedVersion:P.u64()}),Immutable:null,ConsensusAddressOwner:P.struct("ConsensusAddressOwner",{owner:$e,startVersion:P.u64()})}),U2=P.enum("CallArg",{Pure:P.struct("Pure",{bytes:P.byteVector().transform({input:t=>typeof t=="string"?tr(t):t,output:t=>St(new Uint8Array(t))})}),Object:N2}),v0=P.enum("TypeTag",{bool:null,u8:null,u64:null,u128:null,address:null,signer:null,vector:P.lazy(()=>v0),struct:P.lazy(()=>L2),u16:null,u32:null,u256:null}),E0=v0.transform({input:t=>typeof t=="string"?Tr.parseFromStr(t,!0):t,output:t=>Tr.tagToString(t)}),Zr=P.enum("Argument",{GasCoin:null,Input:P.u16(),Result:P.u16(),NestedResult:P.tuple([P.u16(),P.u16()])}),F2=P.struct("ProgrammableMoveCall",{package:$e,module:P.string(),function:P.string(),typeArguments:P.vector(E0),arguments:P.vector(Zr)}),M2=P.enum("Command",{MoveCall:F2,TransferObjects:P.struct("TransferObjects",{objects:P.vector(Zr),address:Zr}),SplitCoins:P.struct("SplitCoins",{coin:Zr,amounts:P.vector(Zr)}),MergeCoins:P.struct("MergeCoins",{destination:Zr,sources:P.vector(Zr)}),Publish:P.struct("Publish",{modules:P.vector(P.byteVector().transform({input:t=>typeof t=="string"?tr(t):t,output:t=>St(new Uint8Array(t))})),dependencies:P.vector($e)}),MakeMoveVec:P.struct("MakeMoveVec",{type:FP(E0).transform({input:t=>t===null?{None:!0}:{Some:t},output:t=>t.Some??null}),elements:P.vector(Zr)}),Upgrade:P.struct("Upgrade",{modules:P.vector(P.byteVector().transform({input:t=>typeof t=="string"?tr(t):t,output:t=>St(new Uint8Array(t))})),dependencies:P.vector($e),package:$e,ticket:Zr})}),$2=P.struct("ProgrammableTransaction",{inputs:P.vector(U2),commands:P.vector(M2)}),j2=P.enum("TransactionKind",{ProgrammableTransaction:$2,ChangeEpoch:null,Genesis:null,ConsensusCommitPrologue:null}),H2=P.enum("TransactionExpiration",{None:null,Epoch:UP()}),L2=P.struct("StructTag",{address:$e,module:P.string(),name:P.string(),typeParams:P.vector(v0)}),D2=P.struct("GasData",{payment:P.vector(pr),owner:$e,price:P.u64(),budget:P.u64()}),z2=P.struct("TransactionDataV1",{kind:j2,sender:$e,gasData:D2,expiration:H2}),V2=P.enum("TransactionData",{V1:z2}),G2=P.enum("IntentScope",{TransactionData:null,TransactionEffects:null,CheckpointSummary:null,PersonalMessage:null}),q2=P.enum("IntentVersion",{V0:null}),W2=P.enum("AppId",{Sui:null}),K2=P.struct("Intent",{scope:G2,version:q2,appId:W2});function X2(t){return P.struct(`IntentMessage<${t.name}>`,{intent:K2,value:t})}const Y2=P.enum("CompressedSignature",{ED25519:P.bytes(64),Secp256k1:P.bytes(64),Secp256r1:P.bytes(64),ZkLogin:P.byteVector(),Passkey:P.byteVector()}),J2=P.enum("PublicKey",{ED25519:P.bytes(32),Secp256k1:P.bytes(33),Secp256r1:P.bytes(33),ZkLogin:P.byteVector(),Passkey:P.bytes(33)}),Z2=P.struct("MultiSigPkMap",{pubKey:J2,weight:P.u8()}),Q2=P.struct("MultiSigPublicKey",{pk_map:P.vector(Z2),threshold:P.u16()}),MP=P.struct("MultiSig",{sigs:P.vector(Y2),bitmap:P.u16(),multisig_pk:Q2}),$P=P.byteVector().transform({input:t=>typeof t=="string"?tr(t):t,output:t=>St(new Uint8Array(t))}),e6=P.struct("SenderSignedTransaction",{intentMessage:X2(V2),txSignatures:P.vector($P)}),jP=P.vector(e6,{name:"SenderSignedData"}),HP=P.struct("PasskeyAuthenticator",{authenticatorData:P.byteVector(),clientDataJson:P.string(),userSignature:P.byteVector()}),LP=P.enum("PackageUpgradeError",{UnableToFetchPackage:P.struct("UnableToFetchPackage",{packageId:$e}),NotAPackage:P.struct("NotAPackage",{objectId:$e}),IncompatibleUpgrade:null,DigestDoesNotMatch:P.struct("DigestDoesNotMatch",{digest:P.byteVector()}),UnknownUpgradePolicy:P.struct("UnknownUpgradePolicy",{policy:P.u8()}),PackageIDDoesNotMatch:P.struct("PackageIDDoesNotMatch",{packageId:$e,ticketId:$e})}),DP=P.struct("ModuleId",{address:$e,name:P.string()}),mm=P.struct("MoveLocation",{module:DP,function:P.u16(),instruction:P.u16(),functionName:P.option(P.string())}),zP=P.enum("CommandArgumentError",{TypeMismatch:null,InvalidBCSBytes:null,InvalidUsageOfPureArg:null,InvalidArgumentToPrivateEntryFunction:null,IndexOutOfBounds:P.struct("IndexOutOfBounds",{idx:P.u16()}),SecondaryIndexOutOfBounds:P.struct("SecondaryIndexOutOfBounds",{resultIdx:P.u16(),secondaryIdx:P.u16()}),InvalidResultArity:P.struct("InvalidResultArity",{resultIdx:P.u16()}),InvalidGasCoinUsage:null,InvalidValueUsage:null,InvalidObjectByValue:null,InvalidObjectByMutRef:null,SharedObjectOperationNotAllowed:null}),VP=P.enum("TypeArgumentError",{TypeNotFound:null,ConstraintNotSatisfied:null}),GP=P.enum("ExecutionFailureStatus",{InsufficientGas:null,InvalidGasObject:null,InvariantViolation:null,FeatureNotYetSupported:null,MoveObjectTooBig:P.struct("MoveObjectTooBig",{objectSize:P.u64(),maxObjectSize:P.u64()}),MovePackageTooBig:P.struct("MovePackageTooBig",{objectSize:P.u64(),maxObjectSize:P.u64()}),CircularObjectOwnership:P.struct("CircularObjectOwnership",{object:$e}),InsufficientCoinBalance:null,CoinBalanceOverflow:null,PublishErrorNonZeroAddress:null,SuiMoveVerificationError:null,MovePrimitiveRuntimeError:P.option(mm),MoveAbort:P.tuple([mm,P.u64()]),VMVerificationOrDeserializationError:null,VMInvariantViolation:null,FunctionNotFound:null,ArityMismatch:null,TypeArityMismatch:null,NonEntryFunctionInvoked:null,CommandArgumentError:P.struct("CommandArgumentError",{argIdx:P.u16(),kind:zP}),TypeArgumentError:P.struct("TypeArgumentError",{argumentIdx:P.u16(),kind:VP}),UnusedValueWithoutDrop:P.struct("UnusedValueWithoutDrop",{resultIdx:P.u16(),secondaryIdx:P.u16()}),InvalidPublicFunctionReturnType:P.struct("InvalidPublicFunctionReturnType",{idx:P.u16()}),InvalidTransferObject:null,EffectsTooLarge:P.struct("EffectsTooLarge",{currentSize:P.u64(),maxSize:P.u64()}),PublishUpgradeMissingDependency:null,PublishUpgradeDependencyDowngrade:null,PackageUpgradeError:P.struct("PackageUpgradeError",{upgradeError:LP}),WrittenObjectsTooLarge:P.struct("WrittenObjectsTooLarge",{currentSize:P.u64(),maxSize:P.u64()}),CertificateDenied:null,SuiMoveVerificationTimedout:null,SharedObjectOperationNotAllowed:null,InputObjectDeleted:null,ExecutionCancelledDueToSharedObjectCongestion:P.struct("ExecutionCancelledDueToSharedObjectCongestion",{congestedObjects:P.vector($e)}),AddressDeniedForCoin:P.struct("AddressDeniedForCoin",{address:$e,coinType:P.string()}),CoinTypeGlobalPause:P.struct("CoinTypeGlobalPause",{coinType:P.string()}),ExecutionCancelledDueToRandomnessUnavailable:null}),t6=P.enum("ExecutionStatus",{Success:null,Failed:P.struct("ExecutionFailed",{error:GP,command:P.option(P.u64())})}),r6=P.struct("GasCostSummary",{computationCost:P.u64(),storageCost:P.u64(),storageRebate:P.u64(),nonRefundableStorageFee:P.u64()}),qP=P.struct("TransactionEffectsV1",{status:t6,executedEpoch:P.u64(),gasUsed:r6,modifiedAtVersions:P.vector(P.tuple([$e,P.u64()])),sharedObjects:P.vector(pr),transactionDigest:Or,created:P.vector(P.tuple([pr,Fs])),mutated:P.vector(P.tuple([pr,Fs])),unwrapped:P.vector(P.tuple([pr,Fs])),deleted:P.vector(pr),unwrappedThenDeleted:P.vector(pr),wrapped:P.vector(pr),gasObject:P.tuple([pr,Fs]),eventsDigest:P.option(Or),dependencies:P.vector(Or)}),A0=P.tuple([P.u64(),Or]),WP=P.enum("ObjectIn",{NotExist:null,Exist:P.tuple([A0,Fs])}),KP=P.enum("ObjectOut",{NotExist:null,ObjectWrite:P.tuple([Or,Fs]),PackageWrite:A0}),XP=P.enum("IDOperation",{None:null,Created:null,Deleted:null}),YP=P.struct("EffectsObjectChange",{inputState:WP,outputState:KP,idOperation:XP}),JP=P.enum("UnchangedSharedKind",{ReadOnlyRoot:A0,MutateDeleted:P.u64(),ReadDeleted:P.u64(),Cancelled:P.u64(),PerEpochConfig:null}),ZP=P.struct("TransactionEffectsV2",{status:t6,executedEpoch:P.u64(),gasUsed:r6,transactionDigest:Or,gasObjectIndex:P.option(P.u32()),eventsDigest:P.option(Or),dependencies:P.vector(Or),lamportVersion:P.u64(),changedObjects:P.vector(P.tuple([$e,YP])),unchangedSharedObjects:P.vector(P.tuple([$e,JP])),auxDataDigest:P.option(Or)}),QP=P.enum("TransactionEffects",{V1:qP,V2:ZP});function Ca(t){switch(t){case"u8":return P.u8();case"u16":return P.u16();case"u32":return P.u32();case"u64":return P.u64();case"u128":return P.u128();case"u256":return P.u256();case"bool":return P.bool();case"string":return P.string();case"id":case"address":return $e}const e=t.match(/^(vector|option)<(.+)>$/);if(e){const[r,n]=e.slice(1);return r==="vector"?P.vector(Ca(n)):P.option(Ca(n))}throw new Error(`Invalid Pure type name: ${t}`)}const pe={...P,U8:P.u8(),U16:P.u16(),U32:P.u32(),U64:P.u64(),U128:P.u128(),U256:P.u256(),ULEB128:P.uleb128(),Bool:P.bool(),String:P.string(),Address:$e,AppId:W2,Argument:Zr,CallArg:U2,Command:M2,CompressedSignature:Y2,GasData:D2,Intent:K2,IntentMessage:X2,IntentScope:G2,IntentVersion:q2,MultiSig:MP,MultiSigPkMap:Z2,MultiSigPublicKey:Q2,ObjectArg:N2,ObjectDigest:Or,Owner:Fs,PasskeyAuthenticator:HP,ProgrammableMoveCall:F2,ProgrammableTransaction:$2,PublicKey:J2,SenderSignedData:jP,SenderSignedTransaction:e6,SharedObjectRef:R2,StructTag:L2,SuiObjectRef:pr,TransactionData:V2,TransactionDataV1:z2,TransactionEffects:QP,TransactionExpiration:H2,TransactionKind:j2,TypeTag:E0},bm=de({digest:_e(),objectId:_e(),version:cn([mt(zt(),Dt()),_e(),_2()])}),eO=li({ImmOrOwned:bm,Shared:de({objectId:rr,initialSharedVersion:Wt,mutable:ia()}),Receiving:bm}),gm=li({Object:eO,Pure:xe(mt(zt(),Dt()))});function wm(t){var r;const e=t.inputs.map((n,s)=>{if(n.Object)return{kind:"Input",index:s,value:{Object:n.Object.ImmOrOwnedObject?{ImmOrOwned:n.Object.ImmOrOwnedObject}:n.Object.Receiving?{Receiving:{digest:n.Object.Receiving.digest,version:n.Object.Receiving.version,objectId:n.Object.Receiving.objectId}}:{Shared:{mutable:n.Object.SharedObject.mutable,initialSharedVersion:n.Object.SharedObject.initialSharedVersion,objectId:n.Object.SharedObject.objectId}}},type:"object"};if(n.Pure)return{kind:"Input",index:s,value:{Pure:Array.from(tr(n.Pure.bytes))},type:"pure"};if(n.UnresolvedPure)return{kind:"Input",type:"pure",index:s,value:n.UnresolvedPure.value};if(n.UnresolvedObject)return{kind:"Input",type:"object",index:s,value:n.UnresolvedObject.objectId};throw new Error("Invalid input")});return{version:1,sender:t.sender??void 0,expiration:((r=t.expiration)==null?void 0:r.$kind)==="Epoch"?{Epoch:Number(t.expiration.Epoch)}:t.expiration?{None:!0}:null,gasConfig:{owner:t.gasData.owner??void 0,budget:t.gasData.budget??void 0,price:t.gasData.price??void 0,payment:t.gasData.payment??void 0},inputs:e,transactions:t.commands.map(n=>{if(n.MakeMoveVec)return{kind:"MakeMoveVec",type:n.MakeMoveVec.type===null?{None:!0}:{Some:Tr.parseFromStr(n.MakeMoveVec.type)},objects:n.MakeMoveVec.elements.map(s=>bn(s,e))};if(n.MergeCoins)return{kind:"MergeCoins",destination:bn(n.MergeCoins.destination,e),sources:n.MergeCoins.sources.map(s=>bn(s,e))};if(n.MoveCall)return{kind:"MoveCall",target:`${n.MoveCall.package}::${n.MoveCall.module}::${n.MoveCall.function}`,typeArguments:n.MoveCall.typeArguments,arguments:n.MoveCall.arguments.map(s=>bn(s,e))};if(n.Publish)return{kind:"Publish",modules:n.Publish.modules.map(s=>Array.from(tr(s))),dependencies:n.Publish.dependencies};if(n.SplitCoins)return{kind:"SplitCoins",coin:bn(n.SplitCoins.coin,e),amounts:n.SplitCoins.amounts.map(s=>bn(s,e))};if(n.TransferObjects)return{kind:"TransferObjects",objects:n.TransferObjects.objects.map(s=>bn(s,e)),address:bn(n.TransferObjects.address,e)};if(n.Upgrade)return{kind:"Upgrade",modules:n.Upgrade.modules.map(s=>Array.from(tr(s))),dependencies:n.Upgrade.dependencies,packageId:n.Upgrade.package,ticket:bn(n.Upgrade.ticket,e)};throw new Error(`Unknown transaction ${Object.keys(n)}`)})}}function bn(t,e){if(t.$kind==="GasCoin")return{kind:"GasCoin"};if(t.$kind==="Result")return{kind:"Result",index:t.Result};if(t.$kind==="NestedResult")return{kind:"NestedResult",index:t.NestedResult[0],resultIndex:t.NestedResult[1]};if(t.$kind==="Input")return e[t.Input];throw new Error(`Invalid argument ${Object.keys(t)}`)}function tO(t){var e,r,n;return Ve(Sc,{version:2,sender:t.sender??null,expiration:t.expiration?"Epoch"in t.expiration?{Epoch:t.expiration.Epoch}:{None:!0}:null,gasData:{owner:t.gasConfig.owner??null,budget:((e=t.gasConfig.budget)==null?void 0:e.toString())??null,price:((r=t.gasConfig.price)==null?void 0:r.toString())??null,payment:((n=t.gasConfig.payment)==null?void 0:n.map(s=>({digest:s.digest,objectId:s.objectId,version:s.version.toString()})))??null},inputs:t.inputs.map(s=>{if(s.kind==="Input"){if(Dd(gm,s.value)){const i=Ve(gm,s.value);if(i.Object){if(i.Object.ImmOrOwned)return{Object:{ImmOrOwnedObject:{objectId:i.Object.ImmOrOwned.objectId,version:String(i.Object.ImmOrOwned.version),digest:i.Object.ImmOrOwned.digest}}};if(i.Object.Shared)return{Object:{SharedObject:{mutable:i.Object.Shared.mutable??null,initialSharedVersion:i.Object.Shared.initialSharedVersion,objectId:i.Object.Shared.objectId}}};if(i.Object.Receiving)return{Object:{Receiving:{digest:i.Object.Receiving.digest,version:String(i.Object.Receiving.version),objectId:i.Object.Receiving.objectId}}};throw new Error("Invalid object input")}return{Pure:{bytes:St(new Uint8Array(i.Pure))}}}return s.type==="object"?{UnresolvedObject:{objectId:s.value}}:{UnresolvedPure:{value:s.value}}}throw new Error("Invalid input")}),commands:t.transactions.map(s=>{switch(s.kind){case"MakeMoveVec":return{MakeMoveVec:{type:"Some"in s.type?Tr.tagToString(s.type.Some):null,elements:s.objects.map(i=>gn(i))}};case"MergeCoins":return{MergeCoins:{destination:gn(s.destination),sources:s.sources.map(i=>gn(i))}};case"MoveCall":{const[i,a,o]=s.target.split("::");return{MoveCall:{package:i,module:a,function:o,typeArguments:s.typeArguments,arguments:s.arguments.map(c=>gn(c))}}}case"Publish":return{Publish:{modules:s.modules.map(i=>St(Uint8Array.from(i))),dependencies:s.dependencies}};case"SplitCoins":return{SplitCoins:{coin:gn(s.coin),amounts:s.amounts.map(i=>gn(i))}};case"TransferObjects":return{TransferObjects:{objects:s.objects.map(i=>gn(i)),address:gn(s.address)}};case"Upgrade":return{Upgrade:{modules:s.modules.map(i=>St(Uint8Array.from(i))),dependencies:s.dependencies,package:s.packageId,ticket:gn(s.ticket)}}}throw new Error(`Unknown transaction ${Object.keys(s)}`)})})}function gn(t){switch(t.kind){case"GasCoin":return{GasCoin:!0};case"Result":return{Result:t.index};case"NestedResult":return{NestedResult:[t.index,t.resultIndex]};case"Input":return{Input:t.index}}}function Vo(t){return cn(Object.entries(t).map(([e,r])=>de({[e]:r})))}const Er=Vo({GasCoin:at(!0),Input:mt(zt(),Dt()),Result:mt(zt(),Dt()),NestedResult:w0([mt(zt(),Dt()),mt(zt(),Dt())])}),rO=de({budget:Ke(Wt),price:Ke(Wt),owner:Ke(aa),payment:Ke(xe(gs))}),nO=de({package:rr,module:_e(),function:_e(),typeArguments:xe(_e()),arguments:xe(Er)}),sO=de({name:_e(),inputs:ho(_e(),cn([Er,xe(Er)])),data:ho(_e(),zo())}),iO=Vo({MoveCall:nO,TransferObjects:de({objects:xe(Er),address:Er}),SplitCoins:de({coin:Er,amounts:xe(Er)}),MergeCoins:de({destination:Er,sources:xe(Er)}),Publish:de({modules:xe(ni),dependencies:xe(rr)}),MakeMoveVec:de({type:Ke(_e()),elements:xe(Er)}),Upgrade:de({modules:xe(ni),dependencies:xe(rr),package:rr,ticket:Er}),$Intent:sO}),aO=Vo({ImmOrOwnedObject:gs,SharedObject:de({objectId:rr,initialSharedVersion:Wt,mutable:ia()}),Receiving:gs}),oO=Vo({Object:aO,Pure:de({bytes:ni}),UnresolvedPure:de({value:zo()}),UnresolvedObject:de({objectId:rr,version:er(Ke(Wt)),digest:er(Ke(_e())),initialSharedVersion:er(Ke(Wt)),mutable:er(Ke(ia()))})}),cO=Vo({None:at(!0),Epoch:Wt}),uO=de({version:at(2),sender:fo(aa),expiration:fo(cO),gasData:rO,inputs:xe(oO),commands:xe(iO),digest:er(Ke(_e()))});function lO(t){return{$kind:"Pure",Pure:{bytes:t instanceof Uint8Array?St(t):t.toBase64()}}}const Br={Pure:lO,ObjectRef({objectId:t,digest:e,version:r}){return{$kind:"Object",Object:{$kind:"ImmOrOwnedObject",ImmOrOwnedObject:{digest:e,version:r,objectId:ve(t)}}}},SharedObjectRef({objectId:t,mutable:e,initialSharedVersion:r}){return{$kind:"Object",Object:{$kind:"SharedObject",SharedObject:{mutable:e,initialSharedVersion:r,objectId:ve(t)}}}},ReceivingRef({objectId:t,digest:e,version:r}){return{$kind:"Object",Object:{$kind:"Receiving",Receiving:{digest:e,version:r,objectId:ve(t)}}}}};BigInt(1e9);const fO="0x1",n6="0x2",dO=tn("0x6"),hO=`${n6}::sui::SUI`;tn("0x5");tn("0x8");const pO=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),st=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),te=new Uint32Array(32);function Yn(t,e,r,n,s,i){const a=s[i],o=s[i+1];let c=te[2*t],u=te[2*t+1],l=te[2*e],f=te[2*e+1],p=te[2*r],d=te[2*r+1],b=te[2*n],g=te[2*n+1],A=cg(c,l,a);u=ug(A,u,f,o),c=A|0,{Dh:g,Dl:b}={Dh:g^u,Dl:b^c},{Dh:g,Dl:b}={Dh:mA(g,b),Dl:bA(g)},{h:d,l:p}=og(d,p,g,b),{Bh:f,Bl:l}={Bh:f^d,Bl:l^p},{Bh:f,Bl:l}={Bh:ig(f,l,24),Bl:ag(f,l,24)},te[2*t]=c,te[2*t+1]=u,te[2*e]=l,te[2*e+1]=f,te[2*r]=p,te[2*r+1]=d,te[2*n]=b,te[2*n+1]=g}function Jn(t,e,r,n,s,i){const a=s[i],o=s[i+1];let c=te[2*t],u=te[2*t+1],l=te[2*e],f=te[2*e+1],p=te[2*r],d=te[2*r+1],b=te[2*n],g=te[2*n+1],A=cg(c,l,a);u=ug(A,u,f,o),c=A|0,{Dh:g,Dl:b}={Dh:g^u,Dl:b^c},{Dh:g,Dl:b}={Dh:ig(g,b,16),Dl:ag(g,b,16)},{h:d,l:p}=og(d,p,g,b),{Bh:f,Bl:l}={Bh:f^d,Bl:l^p},{Bh:f,Bl:l}={Bh:pA(f,l,63),Bl:yA(f,l,63)},te[2*t]=c,te[2*t+1]=u,te[2*e]=l,te[2*e+1]=f,te[2*r]=p,te[2*r+1]=d,te[2*n]=b,te[2*n+1]=g}function yO(t,e={},r,n,s){if(hs(r),t<0||t>r)throw new Error("outputLen bigger than keyLen");const{key:i,salt:a,personalization:o}=e;if(i!==void 0&&(i.length<1||i.length>r))throw new Error("key length must be undefined or 1.."+r);if(a!==void 0&&a.length!==n)throw new Error("salt must be undefined or "+n);if(o!==void 0&&o.length!==s)throw new Error("personalization must be undefined or "+s)}class mO extends au{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,hs(e),hs(r),this.blockLen=e,this.outputLen=r,this.buffer=new Uint8Array(e),this.buffer32=ja(this.buffer)}update(e){ys(this),e=In(e),ps(e);const{blockLen:r,buffer:n,buffer32:s}=this,i=e.length,a=e.byteOffset,o=e.buffer;for(let c=0;c<i;){this.pos===r&&(ts(s),this.compress(s,0,!1),ts(s),this.pos=0);const u=Math.min(r-this.pos,i-c),l=a+c;if(u===r&&!(l%4)&&c+u<i){const f=new Uint32Array(o,l,Math.floor((i-c)/4));ts(f);for(let p=0;c+r<i;p+=s.length,c+=r)this.length+=r,this.compress(f,p,!1);ts(f);continue}n.set(e.subarray(c,c+u),this.pos),this.pos+=u,this.length+=u,c+=u}return this}digestInto(e){ys(this),yh(e,this);const{pos:r,buffer32:n}=this;this.finished=!0,Rn(this.buffer.subarray(r)),ts(n),this.compress(n,0,!0),ts(n);const s=ja(e);this.get().forEach((i,a)=>s[a]=vn(i))}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){const{buffer:r,length:n,finished:s,destroyed:i,outputLen:a,pos:o}=this;return e||(e=new this.constructor({dkLen:a})),e.set(...this.get()),e.buffer.set(r),e.destroyed=i,e.finished=s,e.length=n,e.pos=o,e.outputLen=a,e}clone(){return this._cloneInto()}}class bO extends mO{constructor(e={}){const r=e.dkLen===void 0?64:e.dkLen;super(128,r),this.v0l=st[0]|0,this.v0h=st[1]|0,this.v1l=st[2]|0,this.v1h=st[3]|0,this.v2l=st[4]|0,this.v2h=st[5]|0,this.v3l=st[6]|0,this.v3h=st[7]|0,this.v4l=st[8]|0,this.v4h=st[9]|0,this.v5l=st[10]|0,this.v5h=st[11]|0,this.v6l=st[12]|0,this.v6h=st[13]|0,this.v7l=st[14]|0,this.v7h=st[15]|0,yO(r,e,64,16,16);let{key:n,personalization:s,salt:i}=e,a=0;if(n!==void 0&&(n=In(n),a=n.length),this.v0l^=this.outputLen|a<<8|65536|1<<24,i!==void 0){i=In(i);const o=ja(i);this.v4l^=vn(o[0]),this.v4h^=vn(o[1]),this.v5l^=vn(o[2]),this.v5h^=vn(o[3])}if(s!==void 0){s=In(s);const o=ja(s);this.v6l^=vn(o[0]),this.v6h^=vn(o[1]),this.v7l^=vn(o[2]),this.v7h^=vn(o[3])}if(n!==void 0){const o=new Uint8Array(this.blockLen);o.set(n),this.update(o)}}get(){let{v0l:e,v0h:r,v1l:n,v1h:s,v2l:i,v2h:a,v3l:o,v3h:c,v4l:u,v4h:l,v5l:f,v5h:p,v6l:d,v6h:b,v7l:g,v7h:A}=this;return[e,r,n,s,i,a,o,c,u,l,f,p,d,b,g,A]}set(e,r,n,s,i,a,o,c,u,l,f,p,d,b,g,A){this.v0l=e|0,this.v0h=r|0,this.v1l=n|0,this.v1h=s|0,this.v2l=i|0,this.v2h=a|0,this.v3l=o|0,this.v3h=c|0,this.v4l=u|0,this.v4h=l|0,this.v5l=f|0,this.v5h=p|0,this.v6l=d|0,this.v6h=b|0,this.v7l=g|0,this.v7h=A|0}compress(e,r,n){this.get().forEach((c,u)=>te[u]=c),te.set(st,16);let{h:s,l:i}=sg(BigInt(this.length));te[24]=st[8]^i,te[25]=st[9]^s,n&&(te[28]=~te[28],te[29]=~te[29]);let a=0;const o=pO;for(let c=0;c<12;c++)Yn(0,4,8,12,e,r+2*o[a++]),Jn(0,4,8,12,e,r+2*o[a++]),Yn(1,5,9,13,e,r+2*o[a++]),Jn(1,5,9,13,e,r+2*o[a++]),Yn(2,6,10,14,e,r+2*o[a++]),Jn(2,6,10,14,e,r+2*o[a++]),Yn(3,7,11,15,e,r+2*o[a++]),Jn(3,7,11,15,e,r+2*o[a++]),Yn(0,5,10,15,e,r+2*o[a++]),Jn(0,5,10,15,e,r+2*o[a++]),Yn(1,6,11,12,e,r+2*o[a++]),Jn(1,6,11,12,e,r+2*o[a++]),Yn(2,7,8,13,e,r+2*o[a++]),Jn(2,7,8,13,e,r+2*o[a++]),Yn(3,4,9,14,e,r+2*o[a++]),Jn(3,4,9,14,e,r+2*o[a++]);this.v0l^=te[0]^te[16],this.v0h^=te[1]^te[17],this.v1l^=te[2]^te[18],this.v1h^=te[3]^te[19],this.v2l^=te[4]^te[20],this.v2h^=te[5]^te[21],this.v3l^=te[6]^te[22],this.v3h^=te[7]^te[23],this.v4l^=te[8]^te[24],this.v4h^=te[9]^te[25],this.v5l^=te[10]^te[26],this.v5h^=te[11]^te[27],this.v6l^=te[12]^te[28],this.v6h^=te[13]^te[29],this.v7l^=te[14]^te[30],this.v7h^=te[15]^te[31],Rn(te)}destroy(){this.destroyed=!0,Rn(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const gO=_A(t=>new bO(t)),s6=gO;function wO(t,e,r){const n=pe.Address.serialize(t).toBytes(),s=pe.TypeTag.serialize(e).toBytes(),i=pe.u64().serialize(r.length).toBytes(),a=s6.create({dkLen:32});return a.update(new Uint8Array([240])),a.update(n),a.update(i),a.update(r),a.update(s),`0x${Xi(a.digest().slice(0,32))}`}const vO="object",EO="ID",AO="ascii",SO="String",xO="string",kO="String",TO="option",_O="Option";function IO(t){const e=typeof t.body=="object"&&"datatype"in t.body?t.body.datatype:null;return!!e&&ve(e.package)===ve("0x2")&&e.module==="tx_context"&&e.type==="TxContext"}function Gd(t){if(typeof t=="string")switch(t){case"address":return pe.Address;case"bool":return pe.Bool;case"u8":return pe.U8;case"u16":return pe.U16;case"u32":return pe.U32;case"u64":return pe.U64;case"u128":return pe.U128;case"u256":return pe.U256;default:throw new Error(`Unknown type signature ${t}`)}if("vector"in t){if(t.vector==="u8")return pe.byteVector().transform({input:r=>typeof r=="string"?new TextEncoder().encode(r):r,output:r=>r});const e=Gd(t.vector);return e?pe.vector(e):null}if("datatype"in t){const e=ve(t.datatype.package);if(e===ve(fO)){if(t.datatype.module===AO&&t.datatype.type===SO||t.datatype.module===xO&&t.datatype.type===kO)return pe.String;if(t.datatype.module===TO&&t.datatype.type===_O){const r=Gd(t.datatype.typeParameters[0]);return r?pe.vector(r):null}}if(e===ve(n6)&&t.datatype.module===vO&&t.datatype.type===EO)return pe.Address}return null}function PO(t){return typeof t=="object"&&"Reference"in t?{ref:"&",body:Ra(t.Reference)}:typeof t=="object"&&"MutableReference"in t?{ref:"&mut",body:Ra(t.MutableReference)}:{ref:null,body:Ra(t)}}function Ra(t){if(typeof t=="string")switch(t){case"Address":return"address";case"Bool":return"bool";case"U8":return"u8";case"U16":return"u16";case"U32":return"u32";case"U64":return"u64";case"U128":return"u128";case"U256":return"u256";default:throw new Error(`Unexpected type ${t}`)}if("Vector"in t)return{vector:Ra(t.Vector)};if("Struct"in t)return{datatype:{package:t.Struct.address,module:t.Struct.module,type:t.Struct.name,typeParameters:t.Struct.typeArguments.map(Ra)}};if("TypeParameter"in t)return{typeParameter:t.TypeParameter};throw new Error(`Unexpected type ${JSON.stringify(t)}`)}const OO=50,BO=1000n,CO=5e10;function i6(t){return async function(r,n,s){return await MO(r,t),await FO(r,t),n.onlyTransactionKind||(await RO(r,t),await NO(r,t),await UO(r,t)),await s()}}async function RO(t,e){t.gasConfig.price||(t.gasConfig.price=String(await e.getReferenceGasPrice()))}async function NO(t,e){if(t.gasConfig.budget)return;const r=await e.dryRunTransactionBlock({transactionBlock:t.build({overrides:{gasData:{budget:String(CO),payment:[]}}})});if(r.effects.status.status!=="success")throw new Error(`Dry run failed, could not automatically determine a budget: ${r.effects.status.error}`,{cause:r});const n=BO*BigInt(t.gasConfig.price||1n),s=BigInt(r.effects.gasUsed.computationCost)+n,i=s+BigInt(r.effects.gasUsed.storageCost)-BigInt(r.effects.gasUsed.storageRebate);t.gasConfig.budget=String(i>s?i:s)}async function UO(t,e){if(!t.gasConfig.payment){const n=(await e.getCoins({owner:t.gasConfig.owner||t.sender,coinType:hO})).data.filter(s=>!t.inputs.find(a=>{var o;return(o=a.Object)!=null&&o.ImmOrOwnedObject?s.coinObjectId===a.Object.ImmOrOwnedObject.objectId:!1})).map(s=>({objectId:s.coinObjectId,digest:s.digest,version:s.version}));if(!n.length)throw new Error("No valid gas coins found for the transaction.");t.gasConfig.payment=n.map(s=>Ve(gs,s))}}async function FO(t,e){const r=t.inputs.filter(l=>{var f;return l.UnresolvedObject&&!(l.UnresolvedObject.version||(f=l.UnresolvedObject)!=null&&f.initialSharedVersion)}),n=[...new Set(r.map(l=>tn(l.UnresolvedObject.objectId)))],s=n.length?Fu(n,OO):[],i=(await Promise.all(s.map(l=>e.multiGetObjects({ids:l,options:{showOwner:!0}})))).flat(),a=new Map(n.map((l,f)=>[l,i[f]])),o=Array.from(a).filter(([l,f])=>f.error).map(([l,f])=>JSON.stringify(f.error));if(o.length)throw new Error(`The following input objects are invalid: ${o.join(", ")}`);const c=i.map(l=>{if(l.error||!l.data)throw new Error(`Failed to fetch object: ${l.error}`);const f=l.data.owner,p=f&&typeof f=="object"?"Shared"in f?f.Shared.initial_shared_version:"ConsensusAddressOwner"in f?f.ConsensusAddressOwner.start_version:null:null;return{objectId:l.data.objectId,digest:l.data.digest,version:l.data.version,initialSharedVersion:p}}),u=new Map(n.map((l,f)=>[l,c[f]]));for(const[l,f]of t.inputs.entries()){if(!f.UnresolvedObject)continue;let p;const d=ve(f.UnresolvedObject.objectId),b=u.get(d);f.UnresolvedObject.initialSharedVersion??(b==null?void 0:b.initialSharedVersion)?p=Br.SharedObjectRef({objectId:d,initialSharedVersion:f.UnresolvedObject.initialSharedVersion||(b==null?void 0:b.initialSharedVersion),mutable:f.UnresolvedObject.mutable||$O(t,l)}):jO(t,l)&&(p=Br.ReceivingRef({objectId:d,digest:f.UnresolvedObject.digest??(b==null?void 0:b.digest),version:f.UnresolvedObject.version??(b==null?void 0:b.version)})),t.inputs[t.inputs.indexOf(f)]=p??Br.ObjectRef({objectId:d,digest:f.UnresolvedObject.digest??(b==null?void 0:b.digest),version:f.UnresolvedObject.version??(b==null?void 0:b.version)})}}async function MO(t,e){const{inputs:r,commands:n}=t,s=[],i=new Set;n.forEach(o=>{if(o.MoveCall){if(o.MoveCall._argumentTypes)return;if(o.MoveCall.arguments.map(l=>l.$kind==="Input"?t.inputs[l.Input]:null).some(l=>(l==null?void 0:l.UnresolvedPure)||(l==null?void 0:l.UnresolvedObject)&&typeof(l==null?void 0:l.UnresolvedObject.mutable)!="boolean")){const l=`${o.MoveCall.package}::${o.MoveCall.module}::${o.MoveCall.function}`;i.add(l),s.push(o.MoveCall)}}});const a=new Map;i.size>0&&await Promise.all([...i].map(async o=>{const[c,u,l]=o.split("::"),f=await e.getNormalizedMoveFunction({package:c,module:u,function:l});a.set(o,f.parameters.map(p=>PO(p)))})),s.length&&await Promise.all(s.map(async o=>{const c=a.get(`${o.package}::${o.module}::${o.function}`);if(!c)return;const l=c.length>0&&IO(c.at(-1))?c.slice(0,c.length-1):c;o._argumentTypes=l})),n.forEach(o=>{if(!o.MoveCall)return;const c=o.MoveCall,u=`${c.package}::${c.module}::${c.function}`,l=c._argumentTypes;if(l){if(l.length!==o.MoveCall.arguments.length)throw new Error(`Incorrect number of arguments for ${u}`);l.forEach((f,p)=>{var T,v;const d=c.arguments[p];if(d.$kind!=="Input")return;const b=r[d.Input];if(!b.UnresolvedPure&&!b.UnresolvedObject)return;const g=((T=b.UnresolvedPure)==null?void 0:T.value)??((v=b.UnresolvedObject)==null?void 0:v.objectId),A=Gd(f.body);if(A){d.type="pure",r[r.indexOf(b)]=Br.Pure(A.serialize(g));return}if(typeof g!="string")throw new Error(`Expect the argument to be an object id string, got ${JSON.stringify(g,null,2)}`);d.type="object";const S=b.UnresolvedPure?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:g}}:b;r[d.Input]=S})}})}function $O(t,e){let r=!1;return t.getInputUses(e,(n,s)=>{if(s.MoveCall&&s.MoveCall._argumentTypes){const i=s.MoveCall.arguments.indexOf(n);r=s.MoveCall._argumentTypes[i].ref!=="&"||r}(s.$kind==="MakeMoveVec"||s.$kind==="MergeCoins"||s.$kind==="SplitCoins"||s.$kind==="TransferObjects")&&(r=!0)}),r}function jO(t,e){let r=!1;return t.getInputUses(e,(n,s)=>{if(s.MoveCall&&s.MoveCall._argumentTypes){const i=s.MoveCall.arguments.indexOf(n);r=HO(s.MoveCall._argumentTypes[i])||r}}),r}function HO(t){return typeof t.body!="object"||!("datatype"in t.body)?!1:t.body.datatype.package==="0x2"&&t.body.datatype.module==="transfer"&&t.body.datatype.type==="Receiving"}function a6(t,e){return!!(t.inputs.some(r=>r.UnresolvedObject||r.UnresolvedPure)||!e.onlyTransactionKind&&(!t.gasConfig.price||!t.gasConfig.budget||!t.gasConfig.payment))}async function LO(t,e,r){var i;if(zO(t),!a6(t,e))return await vm(t),r();const n=DO(e);return(((i=n.core)==null?void 0:i.resolveTransactionPlugin())??i6(n))(t,e,async()=>{await vm(t),await r()})}function vm(t){t.inputs.forEach((e,r)=>{if(e.$kind!=="Object"&&e.$kind!=="Pure")throw new Error(`Input at index ${r} has not been resolved. Expected a Pure or Object input, but found ${JSON.stringify(e)}`)})}function DO(t){if(!t.client)throw new Error("No sui client passed to Transaction#build, but transaction data was not sufficient to build offline.");return t.client}function zO(t){for(const e of t.commands)switch(e.$kind){case"SplitCoins":e.SplitCoins.amounts.forEach(r=>{Em(r,pe.U64,t)});break;case"TransferObjects":Em(e.TransferObjects.address,pe.Address,t);break}}function Em(t,e,r){if(t.$kind!=="Input")return;const n=r.inputs[t.Input];n.$kind==="UnresolvedPure"&&(r.inputs[t.Input]=Br.Pure(e.serialize(n.UnresolvedPure.value)))}function VO(t){function e(r){return t(r)}return e.system=r=>{const n=r==null?void 0:r.mutable;return e(n!==void 0?Br.SharedObjectRef({objectId:"0x5",initialSharedVersion:1,mutable:n}):{$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x5",initialSharedVersion:1}})},e.clock=()=>e(Br.SharedObjectRef({objectId:"0x6",initialSharedVersion:1,mutable:!1})),e.random=()=>e({$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x8",mutable:!1}}),e.denyList=r=>e({$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x403",mutable:r==null?void 0:r.mutable}}),e.option=({type:r,value:n})=>s=>s.moveCall({typeArguments:[r],target:`0x1::option::${n===null?"none":"some"}`,arguments:n===null?[]:[s.object(n)]}),e}function GO(t){function e(r,n){if(typeof r=="string")return t(Ca(r).serialize(n));if(r instanceof Uint8Array||b0(r))return t(r);throw new Error("tx.pure must be called either a bcs type name, or a serialized bcs value")}return e.u8=r=>t(pe.U8.serialize(r)),e.u16=r=>t(pe.U16.serialize(r)),e.u32=r=>t(pe.U32.serialize(r)),e.u64=r=>t(pe.U64.serialize(r)),e.u128=r=>t(pe.U128.serialize(r)),e.u256=r=>t(pe.U256.serialize(r)),e.bool=r=>t(pe.Bool.serialize(r)),e.string=r=>t(pe.String.serialize(r)),e.address=r=>t(pe.Address.serialize(r)),e.id=e.address,e.vector=(r,n)=>t(pe.vector(Ca(r)).serialize(n)),e.option=(r,n)=>t(pe.option(Ca(r)).serialize(n)),e}function qO(t,e){const r=Array.from(`${t}::`).map(s=>s.charCodeAt(0)),n=new Uint8Array(r.length+e.length);return n.set(r),n.set(e,r.length),s6(n,{dkLen:32})}function zc(t){if(typeof t=="string")return ve(t);if(t.Object)return t.Object.ImmOrOwnedObject?ve(t.Object.ImmOrOwnedObject.objectId):t.Object.Receiving?ve(t.Object.Receiving.objectId):ve(t.Object.SharedObject.objectId);if(t.UnresolvedObject)return ve(t.UnresolvedObject.objectId)}function WO(t,e,r){const n=s=>{switch(s.$kind){case"Input":{const i=e.get(s.Input);if(i===void 0)throw new Error(`Input ${s.Input} not found in input mapping`);return{...s,Input:i}}case"Result":{const i=r.get(s.Result);return i!==void 0?{...s,Result:i}:s}case"NestedResult":{const i=r.get(s.NestedResult[0]);return i!==void 0?{...s,NestedResult:[i,s.NestedResult[1]]}:s}default:return s}};switch(t.$kind){case"MoveCall":t.MoveCall.arguments=t.MoveCall.arguments.map(n);break;case"TransferObjects":t.TransferObjects.objects=t.TransferObjects.objects.map(n),t.TransferObjects.address=n(t.TransferObjects.address);break;case"SplitCoins":t.SplitCoins.coin=n(t.SplitCoins.coin),t.SplitCoins.amounts=t.SplitCoins.amounts.map(n);break;case"MergeCoins":t.MergeCoins.destination=n(t.MergeCoins.destination),t.MergeCoins.sources=t.MergeCoins.sources.map(n);break;case"MakeMoveVec":t.MakeMoveVec.elements=t.MakeMoveVec.elements.map(n);break;case"Upgrade":t.Upgrade.ticket=n(t.Upgrade.ticket);break;case"$Intent":{const s=t.$Intent.inputs;t.$Intent.inputs={};for(const[i,a]of Object.entries(s))t.$Intent.inputs[i]=Array.isArray(a)?a.map(n):n(a);break}}}function Am(t){return ve(t).replace("0x","")}class Lt{constructor(e){this.version=2,this.sender=(e==null?void 0:e.sender)??null,this.expiration=(e==null?void 0:e.expiration)??null,this.inputs=(e==null?void 0:e.inputs)??[],this.commands=(e==null?void 0:e.commands)??[],this.gasData=(e==null?void 0:e.gasData)??{budget:null,price:null,owner:null,payment:null}}static fromKindBytes(e){const n=pe.TransactionKind.parse(e).ProgrammableTransaction;if(!n)throw new Error("Unable to deserialize from bytes.");return Lt.restore({version:2,sender:null,expiration:null,gasData:{budget:null,owner:null,payment:null,price:null},inputs:n.inputs,commands:n.commands})}static fromBytes(e){const r=pe.TransactionData.parse(e),n=r==null?void 0:r.V1,s=n.kind.ProgrammableTransaction;if(!n||!s)throw new Error("Unable to deserialize from bytes.");return Lt.restore({version:2,sender:n.sender,expiration:n.expiration,gasData:n.gasData,inputs:s.inputs,commands:s.commands})}static restore(e){return e.version===2?new Lt(Ve(Sc,e)):new Lt(Ve(Sc,tO(e)))}static getDigestFromBytes(e){const r=qO("TransactionData",e);return Uu(r)}get gasConfig(){return this.gasData}set gasConfig(e){this.gasData=e}build({maxSizeBytes:e=1/0,overrides:r,onlyTransactionKind:n}={}){const s=this.inputs,i=this.commands,a={ProgrammableTransaction:{inputs:s,commands:i}};if(n)return pe.TransactionKind.serialize(a,{maxSize:e}).toBytes();const o=(r==null?void 0:r.expiration)??this.expiration,c=(r==null?void 0:r.sender)??this.sender,u={...this.gasData,...r==null?void 0:r.gasConfig,...r==null?void 0:r.gasData};if(!c)throw new Error("Missing transaction sender");if(!u.budget)throw new Error("Missing gas budget");if(!u.payment)throw new Error("Missing gas payment");if(!u.price)throw new Error("Missing gas price");const l={sender:Am(c),expiration:o||{None:!0},gasData:{payment:u.payment,owner:Am(this.gasData.owner??c),price:BigInt(u.price),budget:BigInt(u.budget)},kind:{ProgrammableTransaction:{inputs:s,commands:i}}};return pe.TransactionData.serialize({V1:l},{maxSize:e}).toBytes()}addInput(e,r){const n=this.inputs.length;return this.inputs.push(r),{Input:n,type:e,$kind:"Input"}}getInputUses(e,r){this.mapArguments((n,s)=>(n.$kind==="Input"&&n.Input===e&&r(n,s),n))}mapCommandArguments(e,r){const n=this.commands[e];switch(n.$kind){case"MoveCall":n.MoveCall.arguments=n.MoveCall.arguments.map(i=>r(i,n,e));break;case"TransferObjects":n.TransferObjects.objects=n.TransferObjects.objects.map(i=>r(i,n,e)),n.TransferObjects.address=r(n.TransferObjects.address,n,e);break;case"SplitCoins":n.SplitCoins.coin=r(n.SplitCoins.coin,n,e),n.SplitCoins.amounts=n.SplitCoins.amounts.map(i=>r(i,n,e));break;case"MergeCoins":n.MergeCoins.destination=r(n.MergeCoins.destination,n,e),n.MergeCoins.sources=n.MergeCoins.sources.map(i=>r(i,n,e));break;case"MakeMoveVec":n.MakeMoveVec.elements=n.MakeMoveVec.elements.map(i=>r(i,n,e));break;case"Upgrade":n.Upgrade.ticket=r(n.Upgrade.ticket,n,e);break;case"$Intent":const s=n.$Intent.inputs;n.$Intent.inputs={};for(const[i,a]of Object.entries(s))n.$Intent.inputs[i]=Array.isArray(a)?a.map(o=>r(o,n,e)):r(a,n,e);break;case"Publish":break;default:throw new Error(`Unexpected transaction kind: ${n.$kind}`)}}mapArguments(e){for(const r of this.commands.keys())this.mapCommandArguments(r,e)}replaceCommand(e,r,n=e){if(!Array.isArray(r)){this.commands[e]=r;return}const s=r.length-1;this.commands.splice(e,1,...structuredClone(r)),this.mapArguments((i,a,o)=>{if(o<e+r.length)return i;if(typeof n!="number"&&(i.$kind==="Result"&&i.Result===e||i.$kind==="NestedResult"&&i.NestedResult[0]===e)){if(!("NestedResult"in i)||i.NestedResult[1]===0)return Ve(Me,structuredClone(n));throw new Error(`Cannot replace command ${e} with a specific result type: NestedResult[${e}, ${i.NestedResult[1]}] references a nested element that cannot be mapped to the replacement result`)}switch(i.$kind){case"Result":i.Result===e&&typeof n=="number"&&(i.Result=n),i.Result>e&&(i.Result+=s);break;case"NestedResult":if(i.NestedResult[0]===e&&typeof n=="number")return{$kind:"NestedResult",NestedResult:[n,i.NestedResult[1]]};i.NestedResult[0]>e&&(i.NestedResult[0]+=s);break}return i})}replaceCommandWithTransaction(e,r,n){if(n.$kind!=="Result"&&n.$kind!=="NestedResult")throw new Error("Result must be of kind Result or NestedResult");this.insertTransaction(e,r),this.replaceCommand(e+r.commands.length,[],"Result"in n?{NestedResult:[n.Result+e,0]}:{NestedResult:[n.NestedResult[0]+e,n.NestedResult[1]]})}insertTransaction(e,r){var o,c;const n=new Map,s=new Map;for(let u=0;u<r.inputs.length;u++){const l=r.inputs[u],f=zc(l);let p=-1;if(f!==void 0&&(p=this.inputs.findIndex(d=>zc(d)===f),p!==-1&&((o=this.inputs[p].Object)!=null&&o.SharedObject)&&((c=l.Object)!=null&&c.SharedObject)&&(this.inputs[p].Object.SharedObject.mutable=this.inputs[p].Object.SharedObject.mutable||l.Object.SharedObject.mutable)),p!==-1)n.set(u,p);else{const d=this.inputs.length;this.inputs.push(l),n.set(u,d)}}for(let u=0;u<r.commands.length;u++)s.set(u,e+u);const i=[];for(let u=0;u<r.commands.length;u++){const l=structuredClone(r.commands[u]);WO(l,n,s),i.push(l)}this.commands.splice(e,0,...i);const a=i.length;a>0&&this.mapArguments((u,l,f)=>{if(f>=e&&f<e+i.length)return u;switch(u.$kind){case"Result":u.Result>=e&&(u.Result+=a);break;case"NestedResult":u.NestedResult[0]>=e&&(u.NestedResult[0]+=a);break}return u})}getDigest(){const e=this.build({onlyTransactionKind:!1});return Lt.getDigestFromBytes(e)}snapshot(){return Ve(Sc,this)}shallowClone(){return new Lt({version:this.version,sender:this.sender,expiration:this.expiration,gasData:{...this.gasData},inputs:[...this.inputs],commands:[...this.commands]})}applyResolvedData(e){this.sender||(this.sender=e.sender??null),this.expiration||(this.expiration=e.expiration??null),this.gasData.budget||(this.gasData.budget=e.gasData.budget),this.gasData.owner||(this.gasData.owner=e.gasData.owner??null),this.gasData.payment||(this.gasData.payment=e.gasData.payment),this.gasData.price||(this.gasData.price=e.gasData.price);for(let r=0;r<this.inputs.length;r++){const n=this.inputs[r],s=e.inputs[r];switch(n.$kind){case"UnresolvedPure":if(s.$kind!=="Pure")throw new Error(`Expected input at index ${r} to resolve to a Pure argument, but got ${JSON.stringify(s)}`);this.inputs[r]=s;break;case"UnresolvedObject":if(s.$kind!=="Object")throw new Error(`Expected input at index ${r} to resolve to an Object argument, but got ${JSON.stringify(s)}`);if(s.Object.$kind==="ImmOrOwnedObject"||s.Object.$kind==="Receiving"){const i=n.UnresolvedObject,a=s.Object.ImmOrOwnedObject??s.Object.Receiving;if(ve(i.objectId)!==ve(a.objectId)||i.version!=null&&i.version!==a.version||i.digest!=null&&i.digest!==a.digest||i.mutable!=null||i.initialSharedVersion!=null)throw new Error(`Input at index ${r} did not match unresolved object. ${JSON.stringify(i)} is not compatible with ${JSON.stringify(a)}`)}else if(s.Object.$kind==="SharedObject"){const i=n.UnresolvedObject,a=s.Object.SharedObject;if(ve(i.objectId)!==ve(a.objectId)||i.initialSharedVersion!=null&&i.initialSharedVersion!==a.initialSharedVersion||i.mutable!=null&&i.mutable!==a.mutable||i.version!=null||i.digest!=null)throw new Error(`Input at index ${r} did not match unresolved object. ${JSON.stringify(i)} is not compatible with ${JSON.stringify(a)}`)}else throw new Error(`Input at index ${r} resolved to an unexpected Object kind: ${JSON.stringify(s.Object)}`);this.inputs[r]=s;break}}}}var o6=t=>{throw TypeError(t)},S0=(t,e,r)=>e.has(t)||o6("Cannot "+r),ot=(t,e,r)=>(S0(t,e,"read from private field"),r?r.call(t):e.get(t)),ma=(t,e,r)=>e.has(t)?o6("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),hc=(t,e,r,n)=>(S0(t,e,"write to private field"),e.set(t,r),r),Hu=(t,e,r)=>(S0(t,e,"access private method"),r),po,Fn,yo,rs,en,qd,Wd,c6,u6,x0;const KO="/",XO={"Mvr-Source":`@mysten/sui@${e2}`};class YO{constructor({cache:e,url:r,pageSize:n=50,overrides:s}){ma(this,en),ma(this,po),ma(this,Fn),ma(this,yo),ma(this,rs),hc(this,po,e),hc(this,Fn,r),hc(this,yo,n),hc(this,rs,{packages:s==null?void 0:s.packages,types:s==null?void 0:s.types}),JO(ot(this,rs))}async resolvePackage({package:e}){return Et(e)?{package:await ot(this,en,qd).load(e)}:{package:e}}async resolveType({type:e}){if(!Et(e))return{type:e};const r=[...Kd(e)],n=await ot(this,en,Wd).loadMany(r),s={};for(let i=0;i<r.length;i++){const a=n[i];if(a instanceof Error)throw a;s[r[i]]=a}return{type:Xd(e,s)}}async resolve({types:e=[],packages:r=[]}){var l,f,p;const n=new Set;for(const d of e??[])Kd(d,n);const s=[...n],[i,a]=await Promise.all([s.length>0?ot(this,en,Wd).loadMany(s):[],r.length>0?ot(this,en,qd).loadMany(r):[]]),o={...(l=ot(this,rs))==null?void 0:l.types};for(const[d,b]of s.entries()){const g=i[d];if(g instanceof Error)throw g;o[b]=g}const c={};for(const d of e??[]){const b=Xd(d,o);c[d]={type:b}}const u={};for(const[d,b]of(r??[]).entries()){const g=((p=(f=ot(this,rs))==null?void 0:f.packages)==null?void 0:p[b])??a[d];if(g instanceof Error)throw g;u[b]={package:g}}return{types:c,packages:u}}}po=new WeakMap;Fn=new WeakMap;yo=new WeakMap;rs=new WeakMap;en=new WeakSet;qd=function(){return ot(this,po).readSync(["#mvrPackageDataLoader",ot(this,Fn)??""],()=>{var r;const t=new p2(async n=>{if(!ot(this,Fn))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const s=await Hu(this,en,c6).call(this,n);return n.map(i=>s[i]??new Error(`Failed to resolve package: ${i}`))}),e=(r=ot(this,rs))==null?void 0:r.packages;if(e)for(const[n,s]of Object.entries(e))t.prime(n,s);return t})};Wd=function(){return ot(this,po).readSync(["#mvrTypeDataLoader",ot(this,Fn)??""],()=>{var r;const t=new p2(async n=>{if(!ot(this,Fn))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const s=await Hu(this,en,u6).call(this,n);return n.map(i=>s[i]??new Error(`Failed to resolve type: ${i}`))}),e=(r=ot(this,rs))==null?void 0:r.types;if(e)for(const[n,s]of Object.entries(e))t.prime(n,s);return t})};c6=async function(t){if(t.length===0)return{};const e=Fu(t,ot(this,yo)),r={};return await Promise.all(e.map(async n=>{var i;const s=await Hu(this,en,x0).call(this,"/v1/resolution/bulk",{names:n});if(s!=null&&s.resolution)for(const a of Object.keys(s==null?void 0:s.resolution)){const o=(i=s.resolution[a])==null?void 0:i.package_id;o&&(r[a]=o)}})),r};u6=async function(t){if(t.length===0)return{};const e=Fu(t,ot(this,yo)),r={};return await Promise.all(e.map(async n=>{var i;const s=await Hu(this,en,x0).call(this,"/v1/struct-definition/bulk",{types:n});if(s!=null&&s.resolution)for(const a of Object.keys(s==null?void 0:s.resolution)){const o=(i=s.resolution[a])==null?void 0:i.type_tag;o&&(r[a]=o)}})),r};x0=async function(t,e){if(!ot(this,Fn))throw new Error("MVR Api URL is not set for the current client");const r=await fetch(`${ot(this,Fn)}${t}`,{method:"POST",headers:{"Content-Type":"application/json",...XO},body:JSON.stringify(e)});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(`Failed to resolve types: ${n==null?void 0:n.message}`)}return r.json()};function JO(t){if(t!=null&&t.packages)for(const[e,r]of Object.entries(t.packages)){if(!Yt(e))throw new Error(`Invalid package name: ${e}`);if(!kr(ve(r)))throw new Error(`Invalid package ID: ${r}`)}if(t!=null&&t.types)for(const[e,r]of Object.entries(t.types)){if(ri(e).typeParams.length>0)throw new Error("Type overrides must be first-level only. If you want to supply generic types, just pass each type individually.");const n=ri(r);if(!kr(n.address))throw new Error(`Invalid type: ${r}`)}}function Kd(t,e=new Set){if(typeof t=="string"&&!Et(t))return e;const r=l6(t)?t:ri(t);Et(r.address)&&e.add(`${r.address}::${r.module}::${r.name}`);for(const n of r.typeParams)Kd(n,e);return e}function Xd(t,e){const r=l6(t)?t:ri(t),n=`${r.address}::${r.module}::${r.name}`,s=e[n];return Dc({...r,address:s?s.split("::")[0]:r.address,typeParams:r.typeParams.map(i=>Xd(i,e))})}function Et(t){return t.includes(KO)||t.includes("@")||t.includes(".sui")}function l6(t){return typeof t=="object"&&"address"in t&&"module"in t&&"name"in t&&"typeParams"in t}function ZO(t){const e=new Set,r=new Set;for(const n of t.commands)switch(n.$kind){case"MakeMoveVec":n.MakeMoveVec.type&&Sm([n.MakeMoveVec.type]).forEach(a=>{r.add(a)});break;case"MoveCall":const s=n.MoveCall,i=s.package.split("::")[0];if(Et(i)){if(!Yt(i))throw new Error(`Invalid package name: ${i}`);e.add(i)}Sm(s.typeArguments??[]).forEach(a=>{r.add(a)});break}return{packages:[...e],types:[...r]}}function QO(t,e){var r;for(const n of t.commands){if((r=n.MakeMoveVec)!=null&&r.type){if(!Et(n.MakeMoveVec.type))continue;if(!e.types[n.MakeMoveVec.type])throw new Error(`No resolution found for type: ${n.MakeMoveVec.type}`);n.MakeMoveVec.type=e.types[n.MakeMoveVec.type].type}const s=n.MoveCall;if(!s)continue;const i=s.package.split("::"),a=i[0];if(Et(a)&&!e.packages[a])throw new Error(`No address found for package: ${a}`);Et(a)&&(i[0]=e.packages[a].package,s.package=i.join("::"));const o=s.typeArguments;if(o){for(let c=0;c<o.length;c++)if(Et(o[c])){if(!e.types[o[c]])throw new Error(`No resolution found for type: ${o[c]}`);o[c]=e.types[o[c]].type}s.typeArguments=o}}}function Sm(t){const e=new Set;for(const r of t)if(Et(r)){if(!AP(r))throw new Error(`Invalid type with names: ${r}`);e.add(r)}return e}const e4=t=>async(e,r,n)=>{const s=ZO(e);if(s.types.length===0&&s.packages.length===0)return n();const i=await t4(r).core.mvr.resolve({types:s.types,packages:s.packages});QO(e,i),await n()};function t4(t){if(!t.client)throw new Error("No sui client passed to Transaction#build, but transaction data was not sufficient to build offline.");return t.client}var f6=t=>{throw TypeError(t)},k0=(t,e,r)=>e.has(t)||f6("Cannot "+r),Z=(t,e,r)=>(k0(t,e,"read from private field"),r?r.call(t):e.get(t)),Kr=(t,e,r)=>e.has(t)?f6("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Oe=(t,e,r,n)=>(k0(t,e,"write to private field"),e.set(t,r),r),it=(t,e,r)=>(k0(t,e,"access private method"),r),Ms,Vs,Sn,nn,Zt,Qt,_r,ns,oe,Ye,d6,xc,kc,Tc,Vc,Yd,T0,h6,p6;function Ff(t,e=1/0){const r={$kind:"Result",get Result(){return typeof t=="function"?t():t}},n=[],s=i=>n[i]??(n[i]={$kind:"NestedResult",get NestedResult(){return[typeof t=="function"?t():t,i]}});return new Proxy(r,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(i,a){if(a in i)return Reflect.get(i,a);if(a===Symbol.iterator)return function*(){let c=0;for(;c<e;)yield s(c),c++};if(typeof a=="symbol")return;const o=parseInt(a,10);if(!(Number.isNaN(o)||o<0))return s(o)}})}const y6=Symbol.for("@mysten/transaction");function m6(t){return!!t&&typeof t=="object"&&t[y6]===!0}const xm={buildPlugins:new Map,serializationPlugins:new Map},Mf=Symbol.for("@mysten/transaction/registry");function ba(){try{const t=globalThis;return t[Mf]||(t[Mf]=xm),t[Mf]}catch{return xm}}const b6=class Jd{constructor(){Kr(this,Ye),Kr(this,Ms),Kr(this,Vs),Kr(this,Sn,new Map),Kr(this,nn,[]),Kr(this,Zt,[]),Kr(this,Qt,new Set),Kr(this,_r,new Set),Kr(this,ns,new Map),Kr(this,oe),this.object=VO(r=>{var i,a;if(typeof r=="function")return this.object(this.add(r));if(typeof r=="object"&&Dd(Me,r))return r;const n=zc(r),s=Z(this,oe).inputs.find(o=>n===zc(o));return(i=s==null?void 0:s.Object)!=null&&i.SharedObject&&typeof r=="object"&&((a=r.Object)!=null&&a.SharedObject)&&(s.Object.SharedObject.mutable=s.Object.SharedObject.mutable||r.Object.SharedObject.mutable),s?{$kind:"Input",Input:Z(this,oe).inputs.indexOf(s),type:"object"}:it(this,Ye,kc).call(this,"object",typeof r=="string"?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:ve(r)}}:r)});const e=ba();Oe(this,oe,new Lt),Oe(this,Vs,[...e.buildPlugins.values()]),Oe(this,Ms,[...e.serializationPlugins.values()])}static fromKind(e){const r=new Jd;return Oe(r,oe,Lt.fromKindBytes(typeof e=="string"?tr(e):e)),Oe(r,nn,Z(r,oe).inputs.slice()),Oe(r,Zt,Z(r,oe).commands.slice()),Oe(r,Qt,new Set(Z(r,Zt).map((n,s)=>s))),r}static from(e){const r=new Jd;return m6(e)?Oe(r,oe,Lt.restore(e.getData())):typeof e!="string"||!e.startsWith("{")?Oe(r,oe,Lt.fromBytes(typeof e=="string"?tr(e):e)):Oe(r,oe,Lt.restore(JSON.parse(e))),Oe(r,nn,Z(r,oe).inputs.slice()),Oe(r,Zt,Z(r,oe).commands.slice()),Oe(r,Qt,new Set(Z(r,Zt).map((n,s)=>s))),r}static registerGlobalSerializationPlugin(e,r){ba().serializationPlugins.set(e,r??e)}static unregisterGlobalSerializationPlugin(e){ba().serializationPlugins.delete(e)}static registerGlobalBuildPlugin(e,r){ba().buildPlugins.set(e,r??e)}static unregisterGlobalBuildPlugin(e){ba().buildPlugins.delete(e)}addSerializationPlugin(e){Z(this,Ms).push(e)}addBuildPlugin(e){Z(this,Vs).push(e)}addIntentResolver(e,r){if(Z(this,Sn).has(e)&&Z(this,Sn).get(e)!==r)throw new Error(`Intent resolver for ${e} already exists`);Z(this,Sn).set(e,r)}setSender(e){Z(this,oe).sender=e}setSenderIfNotSet(e){Z(this,oe).sender||(Z(this,oe).sender=e)}setExpiration(e){Z(this,oe).expiration=e?Ve(C2,e):null}setGasPrice(e){Z(this,oe).gasConfig.price=String(e)}setGasBudget(e){Z(this,oe).gasConfig.budget=String(e)}setGasBudgetIfNotSet(e){Z(this,oe).gasData.budget==null&&(Z(this,oe).gasConfig.budget=String(e))}setGasOwner(e){Z(this,oe).gasConfig.owner=e}setGasPayment(e){Z(this,oe).gasConfig.payment=e.map(r=>Ve(gs,r))}get blockData(){return wm(Z(this,oe).snapshot())}getData(){return Z(this,oe).snapshot()}get[y6](){return!0}get pure(){return Object.defineProperty(this,"pure",{enumerable:!1,value:GO(e=>b0(e)?it(this,Ye,kc).call(this,"pure",{$kind:"Pure",Pure:{bytes:e.toBase64()}}):it(this,Ye,kc).call(this,"pure",Dd(ym,e)?Ve(ym,e):e instanceof Uint8Array?Br.Pure(e):{$kind:"UnresolvedPure",UnresolvedPure:{value:e}}))}),this.pure}get gas(){return{$kind:"GasCoin",GasCoin:!0}}objectRef(...e){return this.object(Br.ObjectRef(...e))}receivingRef(...e){return this.object(Br.ReceivingRef(...e))}sharedObjectRef(...e){return this.object(Br.SharedObjectRef(...e))}add(e){if(typeof e=="function"){if(Z(this,ns).has(e))return Z(this,ns).get(e);const r=it(this,Ye,d6).call(this),n=e(r);if(!(n&&typeof n=="object"&&"then"in n))return Oe(this,Qt,Z(r,Qt)),Z(this,ns).set(e,n),n;const s=it(this,Ye,xc).call(this,{$kind:"$Intent",$Intent:{name:"AsyncTransactionThunk",inputs:{},data:{resultIndex:Z(this,oe).commands.length,result:null}}});Z(this,_r).add(Promise.resolve(n).then(a=>{s.$Intent.data.result=a}));const i=Ff(()=>s.$Intent.data.resultIndex);return Z(this,ns).set(e,i),i}else it(this,Ye,xc).call(this,e);return Ff(Z(this,oe).commands.length-1)}splitCoins(e,r){const n=Ps.SplitCoins(typeof e=="string"?this.object(e):it(this,Ye,Vc).call(this,e),r.map(s=>typeof s=="number"||typeof s=="bigint"||typeof s=="string"?this.pure.u64(s):it(this,Ye,Tc).call(this,s)));return it(this,Ye,xc).call(this,n),Ff(Z(this,oe).commands.length-1,r.length)}mergeCoins(e,r){return this.add(Ps.MergeCoins(this.object(e),r.map(n=>this.object(n))))}publish({modules:e,dependencies:r}){return this.add(Ps.Publish({modules:e,dependencies:r}))}upgrade({modules:e,dependencies:r,package:n,ticket:s}){return this.add(Ps.Upgrade({modules:e,dependencies:r,package:n,ticket:this.object(s)}))}moveCall({arguments:e,...r}){return this.add(Ps.MoveCall({...r,arguments:e==null?void 0:e.map(n=>it(this,Ye,Tc).call(this,n))}))}transferObjects(e,r){return this.add(Ps.TransferObjects(e.map(n=>this.object(n)),typeof r=="string"?this.pure.address(r):it(this,Ye,Tc).call(this,r)))}makeMoveVec({type:e,elements:r}){return this.add(Ps.MakeMoveVec({type:e,elements:r.map(n=>this.object(n))}))}serialize(){return JSON.stringify(wm(Z(this,oe).snapshot()))}async toJSON(e={}){await this.prepareForSerialization(e);const r=this.isFullyResolved();return JSON.stringify(Ve(uO,r?{...Z(this,oe).snapshot(),digest:Z(this,oe).getDigest()}:Z(this,oe).snapshot()),(n,s)=>typeof s=="bigint"?s.toString():s,2)}async sign(e){const{signer:r,...n}=e,s=await this.build(n);return r.signTransaction(s)}isFullyResolved(){return!(!Z(this,oe).sender||Z(this,_r).size>0||Z(this,oe).commands.some(e=>e.$Intent)||a6(Z(this,oe),{}))}async build(e={}){return await this.prepareForSerialization(e),await it(this,Ye,Yd).call(this,e),Z(this,oe).build({onlyTransactionKind:e.onlyTransactionKind})}async getDigest(e={}){return await this.prepareForSerialization(e),await it(this,Ye,Yd).call(this,e),Z(this,oe).getDigest()}async prepareForSerialization(e){var s;await it(this,Ye,h6).call(this),it(this,Ye,p6).call(this);const r=new Set;for(const i of Z(this,oe).commands)i.$Intent&&r.add(i.$Intent.name);const n=[...Z(this,Ms)];for(const i of r)if(!((s=e.supportedIntents)!=null&&s.includes(i))){if(!Z(this,Sn).has(i))throw new Error(`Missing intent resolver for ${i}`);n.push(Z(this,Sn).get(i))}n.push(e4()),await it(this,Ye,T0).call(this,n,e)}};Ms=new WeakMap;Vs=new WeakMap;Sn=new WeakMap;nn=new WeakMap;Zt=new WeakMap;Qt=new WeakMap;_r=new WeakMap;ns=new WeakMap;oe=new WeakMap;Ye=new WeakSet;d6=function(){const t=new b6;return Oe(t,oe,Z(this,oe)),Oe(t,Ms,Z(this,Ms)),Oe(t,Vs,Z(this,Vs)),Oe(t,Sn,Z(this,Sn)),Oe(t,_r,Z(this,_r)),Oe(t,Qt,new Set(Z(this,Qt))),Oe(t,ns,Z(this,ns)),Z(this,nn).push(Z(t,nn)),Z(this,Zt).push(Z(t,Zt)),t};xc=function(t){const e=Z(this,oe).commands.length;return Z(this,Zt).push(t),Z(this,Qt).add(e),Z(this,oe).commands.push(t),Z(this,oe).mapCommandArguments(e,r=>{if(r.$kind==="Result"&&!Z(this,Qt).has(r.Result))throw new Error(`Result { Result: ${r.Result} } is not available to use in the current transaction`);if(r.$kind==="NestedResult"&&!Z(this,Qt).has(r.NestedResult[0]))throw new Error(`Result { NestedResult: [${r.NestedResult[0]}, ${r.NestedResult[1]}] } is not available to use in the current transaction`);if(r.$kind==="Input"&&r.Input>=Z(this,oe).inputs.length)throw new Error(`Input { Input: ${r.Input} } references an input that does not exist in the current transaction`);return r}),t};kc=function(t,e){return Z(this,nn).push(e),Z(this,oe).addInput(t,e)};Tc=function(t){return b0(t)?this.pure(t):it(this,Ye,Vc).call(this,t)};Vc=function(t){if(typeof t=="function"){const e=this.add(t);return typeof e=="function"?it(this,Ye,Vc).call(this,e):Ve(Me,e)}return Ve(Me,t)};Yd=async function(t){if(!t.onlyTransactionKind&&!Z(this,oe).sender)throw new Error("Missing transaction sender");await it(this,Ye,T0).call(this,[...Z(this,Vs),LO],t)};T0=async function(t,e){try{const r=n=>{if(n>=t.length)return()=>{};const s=t[n];return async()=>{const i=r(n+1);let a=!1,o=!1;if(await s(Z(this,oe),e,async()=>{if(a)throw new Error(`next() was call multiple times in TransactionPlugin ${n}`);a=!0,await i(),o=!0}),!a)throw new Error(`next() was not called in TransactionPlugin ${n}`);if(!o)throw new Error(`next() was not awaited in TransactionPlugin ${n}`)}};await r(0)()}finally{Oe(this,nn,Z(this,oe).inputs.slice()),Oe(this,Zt,Z(this,oe).commands.slice()),Oe(this,Qt,new Set(Z(this,Zt).map((r,n)=>n)))}};h6=async function(){for(;Z(this,_r).size>0;){const t=Promise.all(Z(this,_r));Z(this,_r).clear(),Z(this,_r).add(t),await t,Z(this,_r).delete(t)}};p6=function(){var a;const t=Z(this,oe).commands,e=Z(this,oe).inputs,r=Z(this,Zt).flat(1/0),n=Z(this,nn).flat(1/0);if(r.length!==t.length)throw new Error("Unexpected number of commands found in transaction data");if(n.length!==e.length)throw new Error("Unexpected number of inputs found in transaction data");const s=r.filter(o=>{var c;return((c=o.$Intent)==null?void 0:c.name)!=="AsyncTransactionThunk"});Z(this,oe).commands=s,Z(this,oe).inputs=n,Oe(this,Zt,s),Oe(this,nn,n),Oe(this,Qt,new Set(s.map((o,c)=>c)));function i(o){var l;const c=t[o];if(((l=c.$Intent)==null?void 0:l.name)==="AsyncTransactionThunk"){const f=c.$Intent.data.result;if(f==null)throw new Error("AsyncTransactionThunk has not been resolved");return i(f.Result)}const u=s.indexOf(c);if(u===-1)throw new Error("Unable to find original index for command");return u}Z(this,oe).mapArguments(o=>{if(o.$kind==="Input"){const c=n.indexOf(e[o.Input]);if(c===-1)throw new Error("Input has not been resolved");return{...o,Input:c}}else if(o.$kind==="Result"){const c=i(o.Result);return{...o,Result:c}}else if(o.$kind==="NestedResult"){const c=i(o.NestedResult[0]);return{...o,NestedResult:[c,o.NestedResult[1]]}}return o});for(const[o,c]of t.entries())if(((a=c.$Intent)==null?void 0:a.name)==="AsyncTransactionThunk")try{c.$Intent.data.resultIndex=i(o)}catch{}};let Zd=b6;const r4={mainnet:"https://mainnet.mvr.mystenlabs.com",testnet:"https://testnet.mvr.mystenlabs.com"};class n4 extends x2{constructor(e){var r,n,s;super(e),this.core=this,this.mvr=new YO({cache:this.cache.scope("core.mvr"),url:((r=e.mvr)==null?void 0:r.url)??r4[this.network],pageSize:(n=e.mvr)==null?void 0:n.pageSize,overrides:(s=e.mvr)==null?void 0:s.overrides})}async getObject(e){const{objectId:r}=e,{objects:[n]}=await this.getObjects({objectIds:[r],signal:e.signal});if(n instanceof Error)throw n;return{object:n}}async getDynamicField(e){const r=Tr.parseFromStr((await this.core.mvr.resolveType({type:e.name.type})).type),n=wO(e.parentId,r,e.name.bcs),{objects:[s]}=await this.getObjects({objectIds:[n],signal:e.signal});if(s instanceof Error)throw s;const i=ri(s.type),a=await s.content;return{dynamicField:{id:s.id,digest:s.digest,version:s.version,type:s.type,previousTransaction:s.previousTransaction,name:{type:typeof i.typeParams[0]=="string"?i.typeParams[0]:Dc(i.typeParams[0]),bcs:e.name.bcs},value:{type:typeof i.typeParams[1]=="string"?i.typeParams[1]:Dc(i.typeParams[1]),bcs:a.slice(ju+e.name.bcs.length)}}}}async waitForTransaction({signal:e,timeout:r=60*1e3,...n}){const s=e?AbortSignal.any([AbortSignal.timeout(r),e]):AbortSignal.timeout(r),i=new Promise((a,o)=>{s.addEventListener("abort",()=>o(s.reason))});for(i.catch(()=>{});;){s.throwIfAborted();try{return await this.getTransaction({...n,signal:s})}catch{await Promise.race([new Promise(a=>setTimeout(a,2e3)),i])}}}}class s4 extends Error{}class ss extends s4{constructor(e,r){super(r),this.code=e}static fromResponse(e,r){switch(e.code){case"notExists":return new ss(e.code,`Object ${e.object_id} does not exist`);case"dynamicFieldNotFound":return new ss(e.code,`Dynamic field not found for object ${e.parent_object_id}`);case"deleted":return new ss(e.code,`Object ${e.object_id} has been deleted`);case"displayError":return new ss(e.code,`Display error: ${e.error}`);case"unknown":default:return new ss(e.code,`Unknown error while loading object${r?` ${r}`:""}`)}}}function i4(t){return{...Lt.fromBytes(t).snapshot(),bcs:t}}function a4(t){const e=pe.TransactionEffects.parse(t);switch(e.$kind){case"V1":return o4({effects:e.V1});case"V2":return c4({bytes:t,effects:e.V2});default:throw new Error(`Unknown transaction effects version: ${e.$kind}`)}}function o4(t){throw new Error("V1 effects are not supported yet")}function c4({bytes:t,effects:e}){const r=e.changedObjects.map(([n,s])=>{var i,a,o,c,u,l;return{id:n,inputState:s.inputState.$kind==="Exist"?"Exists":"DoesNotExist",inputVersion:((i=s.inputState.Exist)==null?void 0:i[0][0])??null,inputDigest:((a=s.inputState.Exist)==null?void 0:a[0][1])??null,inputOwner:((o=s.inputState.Exist)==null?void 0:o[1])??null,outputState:s.outputState.$kind==="NotExist"?"DoesNotExist":s.outputState.$kind,outputVersion:s.outputState.$kind==="PackageWrite"?(c=s.outputState.PackageWrite)==null?void 0:c[0]:s.outputState.ObjectWrite?e.lamportVersion:null,outputDigest:s.outputState.$kind==="PackageWrite"?(u=s.outputState.PackageWrite)==null?void 0:u[1]:((l=s.outputState.ObjectWrite)==null?void 0:l[0])??null,outputOwner:s.outputState.ObjectWrite?s.outputState.ObjectWrite[1]:null,idOperation:s.idOperation.$kind}});return{bcs:t,digest:e.transactionDigest,version:2,status:e.status.$kind==="Success"?{success:!0,error:null}:{success:!1,error:e.status.Failed.error.$kind},gasUsed:e.gasUsed,transactionDigest:e.transactionDigest,gasObject:e.gasObjectIndex===null?null:r[e.gasObjectIndex]??null,eventsDigest:e.eventsDigest,dependencies:e.dependencies,lamportVersion:e.lamportVersion,changedObjects:r,unchangedConsensusObjects:e.unchangedSharedObjects.map(([n,s])=>({kind:s.$kind==="MutateDeleted"?"MutateConsensusStreamEnded":s.$kind==="ReadDeleted"?"ReadConsensusStreamEnded":s.$kind,objectId:n,version:s.$kind==="ReadOnlyRoot"?s.ReadOnlyRoot[0]:s[s.$kind],digest:s.$kind==="ReadOnlyRoot"?s.ReadOnlyRoot[1]:null})),auxiliaryDataDigest:e.auxDataDigest}}var g6=t=>{throw TypeError(t)},w6=(t,e,r)=>e.has(t)||g6("Cannot "+r),jt=(t,e,r)=>(w6(t,e,"read from private field"),r?r.call(t):e.get(t)),u4=(t,e,r)=>e.has(t)?g6("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),l4=(t,e,r,n)=>(w6(t,e,"write to private field"),e.set(t,r),r),dt;class f4 extends n4{constructor({jsonRpcClient:e,mvr:r}){super({network:e.network,base:e,mvr:r}),u4(this,dt),l4(this,dt,e)}async getObjects(e){const r=Fu(e.objectIds,50),n=[];for(const s of r){const i=await jt(this,dt).multiGetObjects({ids:s,options:{showOwner:!0,showType:!0,showBcs:!0,showPreviousTransaction:!0},signal:e.signal});for(const[a,o]of i.entries())o.error?n.push(ss.fromResponse(o.error,s[a])):n.push(km(o.data))}return{objects:n}}async getOwnedObjects(e){const r=await jt(this,dt).getOwnedObjects({owner:e.address,limit:e.limit,cursor:e.cursor,options:{showOwner:!0,showType:!0,showBcs:!0,showPreviousTransaction:!0},filter:e.type?{StructType:e.type}:null,signal:e.signal});return{objects:r.data.map(n=>{if(n.error)throw ss.fromResponse(n.error);return km(n.data)}),hasNextPage:r.hasNextPage,cursor:r.nextCursor??null}}async getCoins(e){const r=await jt(this,dt).getCoins({owner:e.address,coinType:e.coinType,limit:e.limit,cursor:e.cursor,signal:e.signal});return{objects:r.data.map(n=>({id:n.coinObjectId,version:n.version,digest:n.digest,balance:n.balance,type:`0x2::coin::Coin<${n.coinType}>`,content:Promise.resolve(p4.serialize({id:n.coinObjectId,balance:{value:n.balance}}).toBytes()),owner:{$kind:"ObjectOwner",ObjectOwner:e.address},previousTransaction:n.previousTransaction})),hasNextPage:r.hasNextPage,cursor:r.nextCursor??null}}async getBalance(e){const r=await jt(this,dt).getBalance({owner:e.address,coinType:e.coinType,signal:e.signal});return{balance:{coinType:r.coinType,balance:r.totalBalance}}}async getAllBalances(e){return{balances:(await jt(this,dt).getAllBalances({owner:e.address,signal:e.signal})).map(n=>({coinType:n.coinType,balance:n.totalBalance})),hasNextPage:!1,cursor:null}}async getTransaction(e){const r=await jt(this,dt).getTransactionBlock({digest:e.digest,options:{showRawInput:!0,showObjectChanges:!0,showRawEffects:!0,showEvents:!0,showEffects:!0,showBalanceChanges:!0},signal:e.signal});return{transaction:Tm(r)}}async executeTransaction(e){const r=await jt(this,dt).executeTransactionBlock({transactionBlock:e.transaction,signature:e.signatures,options:{showRawEffects:!0,showEvents:!0,showObjectChanges:!0,showRawInput:!0,showEffects:!0,showBalanceChanges:!0},signal:e.signal});return{transaction:Tm(r)}}async dryRunTransaction(e){const r=Zd.from(e.transaction),n=await jt(this,dt).dryRunTransactionBlock({transactionBlock:e.transaction,signal:e.signal}),{effects:s,objectTypes:i}=d4({effects:n.effects,objectChanges:n.objectChanges});return{transaction:{digest:await r.getDigest(),epoch:null,effects:s,objectTypes:Promise.resolve(i),signatures:[],transaction:i4(e.transaction),balanceChanges:n.balanceChanges.map(a=>({coinType:a.coinType,address:v6(a.owner),amount:a.amount}))}}}async getReferenceGasPrice(e){const r=await jt(this,dt).getReferenceGasPrice({signal:e==null?void 0:e.signal});return{referenceGasPrice:String(r)}}async getDynamicFields(e){const r=await jt(this,dt).getDynamicFields({parentId:e.parentId,limit:e.limit,cursor:e.cursor});return{dynamicFields:r.data.map(n=>({id:n.objectId,type:n.objectType,name:{type:n.name.type,bcs:tr(n.bcsName)}})),hasNextPage:r.hasNextPage,cursor:r.nextCursor}}async verifyZkLoginSignature(e){const r=await jt(this,dt).verifyZkLoginSignature({bytes:e.bytes,signature:e.signature,intentScope:e.intentScope,author:e.author});return{success:r.success,errors:r.errors}}async defaultNameServiceName(e){return{data:{name:(await jt(this,dt).resolveNameServiceNames(e)).data[0]}}}resolveTransactionPlugin(){return i6(jt(this,dt))}async getMoveFunction(e){const r=await jt(this,dt).getNormalizedMoveFunction({package:(await this.mvr.resolvePackage({package:e.packageId})).package,module:e.moduleName,function:e.name});return{function:{packageId:ve(e.packageId),moduleName:e.moduleName,name:e.name,visibility:m4(r.visibility),isEntry:r.isEntry,typeParameters:r.typeParameters.map(n=>({isPhantom:!1,constraints:y4(n)})),parameters:r.parameters.map(n=>_m(n)),returns:r.return.map(n=>_m(n))}}}}dt=new WeakMap;function km(t){var e;return{id:t.objectId,version:t.version,digest:t.digest,type:t.type,content:Promise.resolve(((e=t.bcs)==null?void 0:e.dataType)==="moveObject"?tr(t.bcs.bcsBytes):new Uint8Array),owner:Si(t.owner),previousTransaction:t.previousTransaction??null}}function Si(t){if(t==="Immutable")return{$kind:"Immutable",Immutable:!0};if("ConsensusAddressOwner"in t)return{$kind:"ConsensusAddressOwner",ConsensusAddressOwner:{owner:t.ConsensusAddressOwner.owner,startVersion:t.ConsensusAddressOwner.start_version}};if("AddressOwner"in t)return{$kind:"AddressOwner",AddressOwner:t.AddressOwner};if("ObjectOwner"in t)return{$kind:"ObjectOwner",ObjectOwner:t.ObjectOwner};if("Shared"in t)return{$kind:"Shared",Shared:{initialSharedVersion:t.Shared.initial_shared_version}};throw new Error(`Unknown owner type: ${JSON.stringify(t)}`)}function v6(t){if(t==="Immutable")return null;if("ConsensusAddressOwner"in t)return t.ConsensusAddressOwner.owner;if("AddressOwner"in t)return t.AddressOwner;if("ObjectOwner"in t)return t.ObjectOwner;if("Shared"in t)return null;throw new Error(`Unknown owner type: ${JSON.stringify(t)}`)}function Tm(t){var i,a,o;const e=pe.SenderSignedData.parse(tr(t.rawTransaction))[0],r={};(i=t.objectChanges)==null||i.forEach(c=>{c.type!=="published"&&(r[c.objectId]=c.objectType)});const n=pe.TransactionData.serialize(e.intentMessage.value).toBytes(),s=Lt.restore({version:2,sender:e.intentMessage.value.V1.sender,expiration:e.intentMessage.value.V1.expiration,gasData:e.intentMessage.value.V1.gasData,inputs:e.intentMessage.value.V1.kind.ProgrammableTransaction.inputs,commands:e.intentMessage.value.V1.kind.ProgrammableTransaction.commands});return{digest:t.digest,epoch:((a=t.effects)==null?void 0:a.executedEpoch)??null,effects:a4(new Uint8Array(t.rawEffects)),objectTypes:Promise.resolve(r),transaction:{...s,bcs:n},signatures:e.txSignatures,balanceChanges:((o=t.balanceChanges)==null?void 0:o.map(c=>({coinType:c.coinType,address:v6(c.owner),amount:c.amount})))??[]}}function d4({bytes:t,effects:e,objectChanges:r}){var a;const n=[],s=[],i={};return r==null||r.forEach(o=>{var c,u,l,f;switch(o.type){case"published":n.push({id:o.packageId,inputState:"DoesNotExist",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"PackageWrite",outputVersion:o.version,outputDigest:o.digest,outputOwner:null,idOperation:"Created"});break;case"transferred":n.push({id:o.objectId,inputState:"Exists",inputVersion:o.version,inputDigest:o.digest,inputOwner:{$kind:"AddressOwner",AddressOwner:o.sender},outputState:"ObjectWrite",outputVersion:o.version,outputDigest:o.digest,outputOwner:Si(o.recipient),idOperation:"None"}),i[o.objectId]=o.objectType;break;case"mutated":n.push({id:o.objectId,inputState:"Exists",inputVersion:o.previousVersion,inputDigest:null,inputOwner:Si(o.owner),outputState:"ObjectWrite",outputVersion:o.version,outputDigest:o.digest,outputOwner:Si(o.owner),idOperation:"None"}),i[o.objectId]=o.objectType;break;case"deleted":n.push({id:o.objectId,inputState:"Exists",inputVersion:o.version,inputDigest:((u=(c=e.deleted)==null?void 0:c.find(p=>p.objectId===o.objectId))==null?void 0:u.digest)??null,inputOwner:null,outputState:"DoesNotExist",outputVersion:null,outputDigest:null,outputOwner:null,idOperation:"Deleted"}),i[o.objectId]=o.objectType;break;case"wrapped":n.push({id:o.objectId,inputState:"Exists",inputVersion:o.version,inputDigest:null,inputOwner:{$kind:"AddressOwner",AddressOwner:o.sender},outputState:"ObjectWrite",outputVersion:o.version,outputDigest:((f=(l=e.wrapped)==null?void 0:l.find(p=>p.objectId===o.objectId))==null?void 0:f.digest)??null,outputOwner:{$kind:"ObjectOwner",ObjectOwner:o.sender},idOperation:"None"}),i[o.objectId]=o.objectType;break;case"created":n.push({id:o.objectId,inputState:"DoesNotExist",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"ObjectWrite",outputVersion:o.version,outputDigest:o.digest,outputOwner:Si(o.owner),idOperation:"Created"}),i[o.objectId]=o.objectType;break}}),{objectTypes:i,effects:{bcs:t??null,digest:e.transactionDigest,version:2,status:e.status.status==="success"?{success:!0,error:null}:{success:!1,error:e.status.error},gasUsed:e.gasUsed,transactionDigest:e.transactionDigest,gasObject:{id:(a=e.gasObject)==null?void 0:a.reference.objectId,inputState:"Exists",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"ObjectWrite",outputVersion:e.gasObject.reference.version,outputDigest:e.gasObject.reference.digest,outputOwner:Si(e.gasObject.owner),idOperation:"None"},eventsDigest:e.eventsDigest??null,dependencies:e.dependencies??[],lamportVersion:e.gasObject.reference.version,changedObjects:n,unchangedConsensusObjects:s,auxiliaryDataDigest:null}}}const h4=pe.struct("Balance",{value:pe.u64()}),p4=pe.struct("Coin",{id:pe.Address,balance:h4});function _m(t){if(typeof t!="string"){if("Reference"in t)return{reference:"immutable",body:Na(t.Reference)};if("MutableReference"in t)return{reference:"mutable",body:Na(t.MutableReference)}}return{reference:null,body:Na(t)}}function Na(t){switch(t){case"Address":return{$kind:"address"};case"Bool":return{$kind:"bool"};case"U8":return{$kind:"u8"};case"U16":return{$kind:"u16"};case"U32":return{$kind:"u32"};case"U64":return{$kind:"u64"};case"U128":return{$kind:"u128"};case"U256":return{$kind:"u256"}}if(typeof t=="string")throw new Error(`Unknown type: ${t}`);if("Vector"in t)return{$kind:"vector",vector:Na(t.Vector)};if("Struct"in t)return{$kind:"datatype",datatype:{typeName:`${ve(t.Struct.address)}::${t.Struct.module}::${t.Struct.name}`,typeParameters:t.Struct.typeArguments.map(e=>Na(e))}};if("TypeParameter"in t)return{$kind:"typeParameter",index:t.TypeParameter};throw new Error(`Unknown type: ${JSON.stringify(t)}`)}function y4(t){return t.abilities.map(e=>{switch(e){case"Copy":return"copy";case"Drop":return"drop";case"Store":return"store";case"Key":return"key";default:return"unknown"}})}function m4(t){switch(t){case"Public":return"public";case"Private":return"private";case"Friend":return"friend";default:return"unknown"}}const b4=Symbol.for("@mysten/SuiClient");class Im extends x2{constructor(e){super({network:e.network??"unknown"}),this.jsonRpc=this,this.transport=e.transport??new PI({url:e.url}),this.core=new f4({jsonRpcClient:this,mvr:e.mvr})}get[b4](){return!0}async getRpcApiVersion({signal:e}={}){return(await this.transport.request({method:"rpc.discover",params:[],signal:e})).info.version}async getCoins({coinType:e,owner:r,cursor:n,limit:s,signal:i}){if(!r||!kr(ve(r)))throw new Error("Invalid Sui address");return e&&Et(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getCoins",params:[r,e,n,s],signal:i})}async getAllCoins(e){if(!e.owner||!kr(ve(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getAllCoins",params:[e.owner,e.cursor,e.limit],signal:e.signal})}async getBalance({owner:e,coinType:r,signal:n}){if(!e||!kr(ve(e)))throw new Error("Invalid Sui address");return r&&Et(r)&&(r=(await this.core.mvr.resolveType({type:r})).type),await this.transport.request({method:"suix_getBalance",params:[e,r],signal:n})}async getAllBalances(e){if(!e.owner||!kr(ve(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getAllBalances",params:[e.owner],signal:e.signal})}async getCoinMetadata({coinType:e,signal:r}){return e&&Et(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getCoinMetadata",params:[e],signal:r})}async getTotalSupply({coinType:e,signal:r}){return e&&Et(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getTotalSupply",params:[e],signal:r})}async call(e,r,{signal:n}={}){return await this.transport.request({method:e,params:r,signal:n})}async getMoveFunctionArgTypes({package:e,module:r,function:n,signal:s}){return e&&Yt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getMoveFunctionArgTypes",params:[e,r,n],signal:s})}async getNormalizedMoveModulesByPackage({package:e,signal:r}){return e&&Yt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveModulesByPackage",params:[e],signal:r})}async getNormalizedMoveModule({package:e,module:r,signal:n}){return e&&Yt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveModule",params:[e,r],signal:n})}async getNormalizedMoveFunction({package:e,module:r,function:n,signal:s}){return e&&Yt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveFunction",params:[e,r,n],signal:s})}async getNormalizedMoveStruct({package:e,module:r,struct:n,signal:s}){return e&&Yt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveStruct",params:[e,r,n],signal:s})}async getOwnedObjects(e){if(!e.owner||!kr(ve(e.owner)))throw new Error("Invalid Sui address");const r=e.filter?{...e.filter}:void 0;return r&&"MoveModule"in r&&Yt(r.MoveModule.package)?r.MoveModule={module:r.MoveModule.module,package:(await this.core.mvr.resolvePackage({package:r.MoveModule.package})).package}:r&&"StructType"in r&&Et(r.StructType)&&(r.StructType=(await this.core.mvr.resolveType({type:r.StructType})).type),await this.transport.request({method:"suix_getOwnedObjects",params:[e.owner,{filter:r,options:e.options},e.cursor,e.limit],signal:e.signal})}async getObject(e){if(!e.id||!dc(tn(e.id)))throw new Error("Invalid Sui Object id");return await this.transport.request({method:"sui_getObject",params:[e.id,e.options],signal:e.signal})}async tryGetPastObject(e){return await this.transport.request({method:"sui_tryGetPastObject",params:[e.id,e.version,e.options],signal:e.signal})}async multiGetObjects(e){if(e.ids.forEach(n=>{if(!n||!dc(tn(n)))throw new Error(`Invalid Sui Object id ${n}`)}),e.ids.length!==new Set(e.ids).size)throw new Error(`Duplicate object ids in batch call ${e.ids}`);return await this.transport.request({method:"sui_multiGetObjects",params:[e.ids,e.options],signal:e.signal})}async queryTransactionBlocks({filter:e,options:r,cursor:n,limit:s,order:i,signal:a}){return e&&"MoveFunction"in e&&Yt(e.MoveFunction.package)&&(e={...e,MoveFunction:{package:(await this.core.mvr.resolvePackage({package:e.MoveFunction.package})).package}}),await this.transport.request({method:"suix_queryTransactionBlocks",params:[{filter:e,options:r},n,s,(i||"descending")==="descending"],signal:a})}async getTransactionBlock(e){if(!pm(e.digest))throw new Error("Invalid Transaction digest");return await this.transport.request({method:"sui_getTransactionBlock",params:[e.digest,e.options],signal:e.signal})}async multiGetTransactionBlocks(e){if(e.digests.forEach(n=>{if(!pm(n))throw new Error(`Invalid Transaction digest ${n}`)}),e.digests.length!==new Set(e.digests).size)throw new Error(`Duplicate digests in batch call ${e.digests}`);return await this.transport.request({method:"sui_multiGetTransactionBlocks",params:[e.digests,e.options],signal:e.signal})}async executeTransactionBlock({transactionBlock:e,signature:r,options:n,requestType:s,signal:i}){const a=await this.transport.request({method:"sui_executeTransactionBlock",params:[typeof e=="string"?e:St(e),Array.isArray(r)?r:[r],n],signal:i});if(s==="WaitForLocalExecution")try{await this.waitForTransaction({digest:a.digest})}catch{}return a}async signAndExecuteTransaction({transaction:e,signer:r,...n}){let s;e instanceof Uint8Array?s=e:(e.setSenderIfNotSet(r.toSuiAddress()),s=await e.build({client:this}));const{signature:i,bytes:a}=await r.signTransaction(s);return this.executeTransactionBlock({transactionBlock:a,signature:i,...n})}async getTotalTransactionBlocks({signal:e}={}){const r=await this.transport.request({method:"sui_getTotalTransactionBlocks",params:[],signal:e});return BigInt(r)}async getReferenceGasPrice({signal:e}={}){const r=await this.transport.request({method:"suix_getReferenceGasPrice",params:[],signal:e});return BigInt(r)}async getStakes(e){if(!e.owner||!kr(ve(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getStakes",params:[e.owner],signal:e.signal})}async getStakesByIds(e){return e.stakedSuiIds.forEach(r=>{if(!r||!dc(tn(r)))throw new Error(`Invalid Sui Stake id ${r}`)}),await this.transport.request({method:"suix_getStakesByIds",params:[e.stakedSuiIds],signal:e.signal})}async getLatestSuiSystemState({signal:e}={}){return await this.transport.request({method:"suix_getLatestSuiSystemState",params:[],signal:e})}async queryEvents({query:e,cursor:r,limit:n,order:s,signal:i}){return e&&"MoveEventType"in e&&Et(e.MoveEventType)&&(e={...e,MoveEventType:(await this.core.mvr.resolveType({type:e.MoveEventType})).type}),e&&"MoveEventModule"in e&&Yt(e.MoveEventModule.package)&&(e={...e,MoveEventModule:{module:e.MoveEventModule.module,package:(await this.core.mvr.resolvePackage({package:e.MoveEventModule.package})).package}}),"MoveModule"in e&&Yt(e.MoveModule.package)&&(e={...e,MoveModule:{module:e.MoveModule.module,package:(await this.core.mvr.resolvePackage({package:e.MoveModule.package})).package}}),await this.transport.request({method:"suix_queryEvents",params:[e,r,n,(s||"descending")==="descending"],signal:i})}async subscribeEvent(e){return this.transport.subscribe({method:"suix_subscribeEvent",unsubscribe:"suix_unsubscribeEvent",params:[e.filter],onMessage:e.onMessage,signal:e.signal})}async subscribeTransaction(e){return this.transport.subscribe({method:"suix_subscribeTransaction",unsubscribe:"suix_unsubscribeTransaction",params:[e.filter],onMessage:e.onMessage,signal:e.signal})}async devInspectTransactionBlock(e){var n,s;let r;if(m6(e.transactionBlock))e.transactionBlock.setSenderIfNotSet(e.sender),r=St(await e.transactionBlock.build({client:this,onlyTransactionKind:!0}));else if(typeof e.transactionBlock=="string")r=e.transactionBlock;else if(e.transactionBlock instanceof Uint8Array)r=St(e.transactionBlock);else throw new Error("Unknown transaction block format.");return(n=e.signal)==null||n.throwIfAborted(),await this.transport.request({method:"sui_devInspectTransactionBlock",params:[e.sender,r,(s=e.gasPrice)==null?void 0:s.toString(),e.epoch],signal:e.signal})}async dryRunTransactionBlock(e){return await this.transport.request({method:"sui_dryRunTransactionBlock",params:[typeof e.transactionBlock=="string"?e.transactionBlock:St(e.transactionBlock)]})}async getDynamicFields(e){if(!e.parentId||!dc(tn(e.parentId)))throw new Error("Invalid Sui Object id");return await this.transport.request({method:"suix_getDynamicFields",params:[e.parentId,e.cursor,e.limit],signal:e.signal})}async getDynamicFieldObject(e){return await this.transport.request({method:"suix_getDynamicFieldObject",params:[e.parentId,e.name],signal:e.signal})}async getLatestCheckpointSequenceNumber({signal:e}={}){const r=await this.transport.request({method:"sui_getLatestCheckpointSequenceNumber",params:[],signal:e});return String(r)}async getCheckpoint(e){return await this.transport.request({method:"sui_getCheckpoint",params:[e.id],signal:e.signal})}async getCheckpoints(e){return await this.transport.request({method:"sui_getCheckpoints",params:[e.cursor,e==null?void 0:e.limit,e.descendingOrder],signal:e.signal})}async getCommitteeInfo(e){return await this.transport.request({method:"suix_getCommitteeInfo",params:[e==null?void 0:e.epoch],signal:e==null?void 0:e.signal})}async getNetworkMetrics({signal:e}={}){return await this.transport.request({method:"suix_getNetworkMetrics",params:[],signal:e})}async getAddressMetrics({signal:e}={}){return await this.transport.request({method:"suix_getLatestAddressMetrics",params:[],signal:e})}async getEpochMetrics(e){return await this.transport.request({method:"suix_getEpochMetrics",params:[e==null?void 0:e.cursor,e==null?void 0:e.limit,e==null?void 0:e.descendingOrder],signal:e==null?void 0:e.signal})}async getAllEpochAddressMetrics(e){return await this.transport.request({method:"suix_getAllEpochAddressMetrics",params:[e==null?void 0:e.descendingOrder],signal:e==null?void 0:e.signal})}async getEpochs(e){return await this.transport.request({method:"suix_getEpochs",params:[e==null?void 0:e.cursor,e==null?void 0:e.limit,e==null?void 0:e.descendingOrder],signal:e==null?void 0:e.signal})}async getMoveCallMetrics({signal:e}={}){return await this.transport.request({method:"suix_getMoveCallMetrics",params:[],signal:e})}async getCurrentEpoch({signal:e}={}){return await this.transport.request({method:"suix_getCurrentEpoch",params:[],signal:e})}async getValidatorsApy({signal:e}={}){return await this.transport.request({method:"suix_getValidatorsApy",params:[],signal:e})}async getChainIdentifier({signal:e}={}){const r=await this.getCheckpoint({id:"0",signal:e}),n=lo(r.digest);return Xi(n.slice(0,4))}async resolveNameServiceAddress(e){return await this.transport.request({method:"suix_resolveNameServiceAddress",params:[e.name],signal:e.signal})}async resolveNameServiceNames({format:e="dot",...r}){const{nextCursor:n,hasNextPage:s,data:i}=await this.transport.request({method:"suix_resolveNameServiceNames",params:[r.address,r.cursor,r.limit],signal:r.signal});return{hasNextPage:s,nextCursor:n,data:i.map(a=>gP(a,e))}}async getProtocolConfig(e){return await this.transport.request({method:"sui_getProtocolConfig",params:[e==null?void 0:e.version],signal:e==null?void 0:e.signal})}async verifyZkLoginSignature(e){return await this.transport.request({method:"sui_verifyZkLoginSignature",params:[e.bytes,e.signature,e.intentScope,e.author],signal:e.signal})}async waitForTransaction({signal:e,timeout:r=60*1e3,pollInterval:n=2*1e3,...s}){const i=AbortSignal.timeout(r),a=new Promise((o,c)=>{i.addEventListener("abort",()=>c(i.reason))});for(a.catch(()=>{});!i.aborted;){e==null||e.throwIfAborted();try{return await this.getTransactionBlock(s)}catch{await Promise.race([new Promise(o=>setTimeout(o,n)),a])}}throw i.throwIfAborted(),new Error("Unexpected error while waiting for transaction block.")}}class g4{constructor(e,r,n,s){this.client=new Im({url:um(n)}),this.url=e instanceof m.Url?e:new m.Url(e),this.account=r,this.network=n,this.auth=s,this.relayer=new ui(this.auth,this.url)}get htlcActorAddress(){var e,r;return"accounts"in this.account?((r=(e=this.account.accounts)==null?void 0:e[0])==null?void 0:r.address)??"":this.account.toSuiAddress()}async initiate(e){var r,n,s;if(!e)return m.Err("Order is required");if(D.isSuiOrderResponse(e))return this.initiateWithCreateOrderResponse(e);try{const{source_swap:i}=e,a=BigInt(i.amount),o=i.asset,c=i.redeemer,u=i.secret_hash,l=await $i(i.asset,this.url,this.auth);if(!l.ok)return m.Err(l.error);const{tokenAddress:f}=l.val,p=new Zd;p.setSender(this.htlcActorAddress);const[d]=p.splitCoins(p.gas,[a]);p.moveCall({target:`${zf[this.network].packageId}::${zf[this.network].moduleName}::initiate`,typeArguments:[f],arguments:[p.object(o),p.pure.address(this.htlcActorAddress),p.pure.address(c),p.pure.vector("u8",Buffer.from(u,"hex")),p.pure.u64(a),p.pure.u256(i.timelock),p.pure.vector("u8",Buffer.from("")),d,p.object(dO)]});const b=await p.build({client:this.client}),g=await this.client.dryRunTransactionBlock({transactionBlock:b});if(g.effects.status.status==="failure")return m.Err(`${g.effects.status.error}`);let A;if("features"in this.account?A=await((r=this.account.features[O0.SuiSignAndExecuteTransaction])==null?void 0:r.signAndExecuteTransaction({transaction:p,account:this.account.accounts[0],chain:`sui:${this.network}`})):A=await this.client.signAndExecuteTransaction({signer:this.account,transaction:p,options:{showEffects:!0}}),!A)return m.Err("Failed to initiate");const S=await this.client.waitForTransaction({digest:A.digest,options:{showEffects:!0}});return((n=S.effects)==null?void 0:n.status.status)==="failure"?m.Err(`Failed to initiate: ${(s=S.effects)==null?void 0:s.status.error}`):m.Ok(S.digest)}catch(i){return m.Err(i)}}async initiateWithCreateOrderResponse(e){var o,c,u;const{ptb_bytes:r}=e,s=await new Im({url:um("testnet")}).getReferenceGasPrice(),i=1e7,a=Zd.fromKind(new Uint8Array(r));a.setSender(this.htlcActorAddress),a.setGasPrice(s),a.setGasBudget(i);try{let l;if("features"in this.account?l=await((o=this.account.features[O0.SuiSignAndExecuteTransaction])==null?void 0:o.signAndExecuteTransaction({transaction:a,account:this.account.accounts[0],chain:`sui:${this.network}`})):l=await this.client.signAndExecuteTransaction({signer:this.account,transaction:a,options:{showEffects:!0}}),!l)return m.Err("Failed to initiate");const f=await this.client.waitForTransaction({digest:l.digest,options:{showEffects:!0}});return((c=f.effects)==null?void 0:c.status.status)==="failure"?m.Err(`Failed to initiate: ${(u=f.effects)==null?void 0:u.status.error}`):m.Ok(f.digest)}catch(l){return m.Err(String(l))}}async redeem(e,r){const n=await this.relayer.redeem(e.order_id,r);return n.error?m.Err(n.error):n.val?m.Ok(n.val):m.Err("Redeem: No result found")}async refund(){return m.Err("Refund is taken care of by the relayer")}}function Pm(t){let e=t.startsWith("0x")?t.slice(2):t;return e=e.toLowerCase(),e.length>64&&(e=e.slice(e.length-64)),e.length<64&&(e=e.padStart(64,"0")),`0x${e}`}class w4{constructor(e,r,n,s){this.url=typeof e=="string"?new m.Url(e):e,this.auth=n,s instanceof B0.TronWeb?(this.wallet={tronweb:s},this.tronweb=s):(this.wallet={adapter:s},this.tronweb=new B0.TronWeb({fullHost:Nm[r]})),this.relayer=new ui(this.auth,this.url)}get htlcActorAddress(){var e,r,n;return(e=this.wallet.adapter)!=null&&e.address?this.wallet.adapter.address:this.wallet.tronweb?((r=this.wallet.tronweb.defaultAddress)==null?void 0:r.base58)||"":((n=this.tronweb.defaultAddress)==null?void 0:n.base58)||""}async initiate(e){if(D.isEvmOrderResponse(e))return this.initiateDirectContractCall(e);try{const{source_swap:r}=e,n=await $i(r.asset,this.url,this.auth);if(!n.ok)return m.Err(n.error);const{htlcAddress:s}=n.val;return await this.executeContractCall({contractAddress:s,method:"initiate(address,uint256,uint256,bytes32,bytes)",parameters:[{type:"address",value:r.redeemer},{type:"uint256",value:r.timelock},{type:"uint256",value:BigInt(r.amount)},{type:"bytes32",value:Pm(String(r.secret_hash))},{type:"bytes",value:"0x"}],options:{}})}catch(r){return m.Err(`Failed to initiate: ${String(r)}`)}}async initiateDirectContractCall(e){var f;if(!this.htlcActorAddress)return m.Err("No HTLC actor address found");if(e.approval_transaction){const p=await this.executeApprovalTransaction(e);if(p.error)return m.Err(p.error)}if(!e.initiate_transaction)return m.Err("No initiate transaction data available for direct contract call");if(!((f=e.typed_data)!=null&&f.message))return m.Err("No typed data message found in order response");const{to:r,value:n,gas_limit:s}=e.initiate_transaction,{redeemer:i,timelock:a,amount:o,secretHash:c,destinationData:u}=e.typed_data.message,l=await this.executeContractCall({contractAddress:r,method:"initiate(address,uint256,uint256,bytes32,bytes)",parameters:[{type:"address",value:i},{type:"uint256",value:a},{type:"uint256",value:o},{type:"bytes32",value:Pm(String(c))},{type:"bytes",value:u}],options:{feeLimit:parseInt(s),callValue:n?parseInt(n):0}});return!l.val||l.error?m.Err("Failed to initiate"+(l.error||"")):await this.waitForTransactionConfirmation(l.val)}async executeApprovalTransaction(e){if(console.log("No Allowance found, Executing Approval"),!this.htlcActorAddress)return m.Err("No HTLC actor address found");const r=e.approval_transaction;if(!r)return m.Ok("No approval transaction required");try{const n="0x"+r.data.slice(10),s=this.tronweb.utils.abi.decodeParams(["spender","amount"],["address","uint256"],n,!1);return await this.executeContractCall({contractAddress:r.to,method:"approve(address,uint256)",parameters:[{type:"address",value:s.spender},{type:"uint256",value:s.amount.toString()}],options:{feeLimit:Number(r.gas_limit),callValue:0}})}catch(n){return m.Err(`Approval transaction failed: ${String(n)}`)}}async executeContractCall({contractAddress:e,method:r,parameters:n,options:s}){try{const i=await this.tronweb.transactionBuilder.triggerSmartContract(e,r,s,n,this.htlcActorAddress);if(!(i!=null&&i.transaction))return m.Err("Failed to build transaction");const a=await this.signTransaction(i.transaction);if(a.error)return m.Err(a.error);const o=a.val;return o?await this.broadcastWithRetry(o):m.Err("Signing returned no transaction")}catch(i){return m.Err(`Failed to execute contract call: ${String(i)}`)}}async broadcastWithRetry(e){for(let n=0;n<5;n++)try{const s=await this.tronweb.trx.sendRawTransaction(e);if(s.result&&s.txid)return m.Ok(s.txid);const i=typeof s.code=="string"?parseInt(s.code):s.code;if(this.isRetryableError(i)&&n<4){await this.sleep(Math.min(1e3*Math.pow(2,n),8e3));continue}const a=s.message||`Error code: ${s.code}`;return m.Err(String(a))}catch(s){if(n<4){await this.sleep(Math.min(1e3*Math.pow(2,n),8e3));continue}return m.Err(String(s))}return m.Err("Max broadcast retries exceeded")}isRetryableError(e){if(e===void 0)return!0;const r=typeof e=="string"?parseInt(e):e;return r===8||r===9||r===10||r===11||r===4}sleep(e){return new Promise(r=>setTimeout(r,e))}async signTransaction(e){if(this.wallet.adapter)try{const r=await this.wallet.adapter.signTransaction(e);return m.Ok(r)}catch(r){return m.Err(`Adapter signing failed: ${String(r)}`)}if(this.wallet.tronweb)try{const r=await this.wallet.tronweb.trx.sign(e);return m.Ok(r)}catch(r){return m.Err(`TronWeb signing failed: ${String(r)}`)}return m.Err("No signing method available")}async waitForTransactionConfirmation(e,r=15,n=3e3){var s,i,a,o;for(let c=0;c<r;c++){try{const u=await this.tronweb.trx.getTransaction(e);if(!u){await this.sleep(n);continue}if(((i=(s=u.ret)==null?void 0:s[0])==null?void 0:i.contractRet)==="SUCCESS")return m.Ok(u.txID);if(((o=(a=u.ret)==null?void 0:a[0])==null?void 0:o.contractRet)==="FAILED")return m.Err("Transaction failed on-chain")}catch{console.log(`Checking tx ${c+1}/${r}...`)}await this.sleep(n)}return m.Err("Transaction confirmation timeout")}async redeem(e,r){const n=await this.relayer.redeem(e.order_id,r);return n.error?m.Err(n.error):m.Ok(n.val)}async refund(){return m.Err("Refund is taken care of by the relayer")}}const v4=25*60*60*1e3;class E6{constructor(e,r,n,s){this.url=typeof e=="string"?new m.Url(e):e,this.auth=n,this.wallet=s,this.client=new C0.Client(Um[r],{}),this.relayer=new ui(this.auth,this.url)}isXrplWallet(e){return typeof e=="object"&&e!==null&&"classicAddress"in e&&typeof e.classicAddress=="string"}isCrossmarkWallet(e){var r;return typeof e=="object"&&e!==null&&"sync"in e&&"async"in e&&typeof e.sync=="object"&&typeof((r=e.sync)==null?void 0:r.getAddress)=="function"}get htlcActorAddress(){return this.isXrplWallet(this.wallet)?this.wallet.classicAddress:this.isCrossmarkWallet(this.wallet)?this.wallet.sync.getAddress()??"":""}async initiate(e){try{return D.isXrplOrderResponse(e)?this.initiateFromOrderResponse(e):this.initiateFromOrder(e)}catch(r){return m.Err(`Failed to initiate: ${String(r)}`)}}async initiateFromOrderResponse(e){try{if(!this.htlcActorAddress)return m.Err("No HTLC actor address found");const n=e.escrow_create_tx,s={TransactionType:"EscrowCreate",Account:n.Account,Amount:n.Amount,Destination:n.Destination,Condition:n.Condition,CancelAfter:n.CancelAfter};return await this.submitTransaction(s)}catch(r){return m.Err(`Failed to initiate from order response: ${String(r)}`)}}async initiateFromOrder(e){try{const r=this.htlcActorAddress;if(!r)return m.Err("No HTLC actor address found");const{source_swap:n}=e,s=m.trim0x(n.secret_hash),i={Account:r,Amount:n.amount,Destination:n.redeemer,Condition:this.buildCondition(s),CancelAfter:C0.isoTimeToRippleTime(new Date(new Date(n.created_at).getTime()+v4)),TransactionType:"EscrowCreate"};return await this.submitTransaction(i)}catch(r){return m.Err(`Failed to initiate from order: ${String(r)}`)}}async redeem(e,r){const n=await this.relayer.redeem(e.order_id,r);return n.error?m.Err(n.error):m.Ok(n.val)}async refund(){return m.Err("Refund is taken care of by the relayer")}async submitTransaction(e){try{this.client.isConnected()||await this.client.connect();const r=this.htlcActorAddress;if(!r)return m.Err("No HTLC actor address found");const n=await this.client.autofill(e);n.Account=r;const s=await this.signPreparedTransaction(n),i=await this.client.submitAndWait(s),a=i.result.meta;return(a==null?void 0:a.TransactionResult)==="tesSUCCESS"?m.Ok(i.result.hash):m.Err(`Transaction failed: ${String((a==null?void 0:a.TransactionResult)??"Unknown error")}`)}catch(r){return m.Err(`Transaction submission failed: ${String(r)}`)}finally{this.client.isConnected()&&await this.client.disconnect()}}async signPreparedTransaction(e){if(this.isXrplWallet(this.wallet))return this.wallet.sign(e).tx_blob;if(this.isCrossmarkWallet(this.wallet))return this.wallet.sync.getAddress()||await this.wallet.async.signInAndWait(),(await this.wallet.async.signAndWait(e)).response.data.txBlob;throw new Error("Unsupported wallet type")}buildCondition(e){return"A0258020"+e.toUpperCase()+"810120"}}const E4=t=>{if(t)if(typeof t=="string"){const e=m.DigestKey.from(t);if(!e.ok)throw new Error(e.error);return e.val}else return t},$f=t=>typeof t=="string"?new m.ApiKey(t):t;class mo extends m.EventBroker{get isInitialized(){return!!this.digestKey}constructor(e,r){super(),this.digestKey=e,this.walletClient=r}static fromDigestKey(e){return new mo(m.trim0x(e))}static fromWalletClient(e){return new mo(void 0,e)}async initialize(){if(this.digestKey)return m.Ok("Already initialized");const e=await this.deriveDigestKeyFromWalletClient();return e.error?m.Err(e.error):(this.emit("initialized",!0),m.Ok("Initialized"))}async deriveDigestKeyFromWalletClient(){if(!this.walletClient)return m.Err("No walletClient found");if(!this.walletClient.account)return m.Err("No account found");try{const e=await this.walletClient.signTypedData({account:this.walletClient.account,types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"}],Data:[{name:"Message",type:"string"},{name:"Version",type:"string"},{name:"Nonce",type:"uint256"}]},domain:{name:"GARDEN FINANCE",version:"1"},primaryType:"Data",message:{Message:"Initialize your account",Version:"1.0.2",Nonce:1n}});return this.digestKey=m.trim0x(Aa(e)),this.emit("initialized",!0),m.Ok(this.digestKey)}catch(e){return m.Err("Failed to initialize: "+e)}}async getDigestKey(){if(!this.digestKey&&!this.walletClient)return m.Err("No private key or wallet client found");if(!this.digestKey&&this.walletClient){const e=await this.deriveDigestKeyFromWalletClient();if(e.error)return m.Err(e.error)}return this.digestKey?m.Ok(this.digestKey):m.Err("No private key found")}async generateSecret(e){const r=await this.signMessage(e);if(!r.ok)return m.Err(r.error);const n=Aa(m.with0x(r.val)),s=Aa(n);return m.Ok({secret:n,secretHash:s})}async signMessage(e){if(!this.digestKey){const u=await this.getDigestKey();if(!u.ok)return m.Err(u.error);this.digestKey=u.val}const r=pc.ECPairFactory(mr),n="Garden.fi"+e.toString(),s=Buffer.from(n,"utf8"),i=Aa(s),a=Buffer.from(m.trim0x(this.digestKey),"hex");if(a.length!==32)return m.Err("Invalid private key length. Expected 32 bytes.");const c=r.fromPrivateKey(a).sign(Buffer.from(m.trim0x(i),"hex"));return m.Ok(c.toString("hex"))}}class A4{constructor(e={}){const r={stdTTL:e.ttl?e.ttl/1e3:3600,checkperiod:600};this.cache=new I6(r)}makeKey(e,r){return`${e}:${r}`}set(e,r,n,s){const i=this.makeKey(e,r);s?this.cache.set(i,n,s/1e3):this.cache.set(i,n)}get(e,r){const n=this.makeKey(e,r);return this.cache.get(n)}remove(e,r){const n=this.makeKey(e,r);this.cache.del(n)}clear(e){if(e){const r=this.cache.keys().filter(n=>n.startsWith(`${e}:`));this.cache.del(r)}else this.cache.flushAll()}setBitcoinRedeem(e,r,n){this.set("bitcoinRedeem",e,r,n)}getBitcoinRedeem(e){return this.get("bitcoinRedeem",e)}setOrderExecution(e,r,n,s,i){const a=this.makeOrderKey(e,r),o={txHash:n,timeStamp:Date.now(),btcRedeemUTXO:s};this.set("orderExecutor",a,o,i)}getOrderExecution(e,r){const n=this.makeOrderKey(e,r);return this.get("orderExecutor",n)}removeOrderExecution(e,r){const n=this.makeOrderKey(e,r);this.remove("orderExecutor",n)}makeOrderKey(e,r){return`${r}_${e.order_id??e.created_at}`}setSacpCache(e,r,n){this.set("refundSacp",e,r,n)}getSacpCache(e){return this.get("refundSacp",e)}has(e,r){const n=this.makeKey(e,r);return this.cache.has(n)}peek(e,r){return this.get(e,r)}getRemainingTTL(e,r){const n=this.makeKey(e,r),s=this.cache.getTtl(n);if(s===void 0)return-1;const i=Date.now();return Math.max(0,s-i)}}var bo,go,wo,Ne,Mi,is;class S4{constructor(e,r,n,s,i,a){ks(this,bo);ks(this,go);ks(this,wo);ks(this,Ne);ks(this,Mi);ks(this,is);this.isBackgroundServiceRunning=!1,this.stopBackgroundExecution=null,this.htlcs=r,this.events=a,Ts(this,bo,e),Ts(this,go,n),Ts(this,wo,mo.fromDigestKey(e.digestKey)),Ts(this,Ne,new A4),Ts(this,Mi,s),Ts(this,is,i)}async getAddressesFromHTLCs(){var n,s,i,a,o,c,u;const e=new Set;return[(n=this.htlcs.evm)==null?void 0:n.htlcActorAddress,(s=this.htlcs.sui)==null?void 0:s.htlcActorAddress,(i=this.htlcs.solana)==null?void 0:i.htlcActorAddress,(a=this.htlcs.starknet)==null?void 0:a.htlcActorAddress,(o=this.htlcs.bitcoin)==null?void 0:o.htlcActorAddress,(c=this.htlcs.tron)==null?void 0:c.htlcActorAddress,(u=this.htlcs.xrpl)==null?void 0:u.htlcActorAddress].filter(l=>!!l&&l.length>0).forEach(l=>e.add(l.toLowerCase())),Array.from(e)}start(e=5e3,r){this.isBackgroundServiceRunning||this.stopBackgroundExecution||(this.isBackgroundServiceRunning=!0,(async()=>{try{if(r){this.stop();return}const n=await this.execute(e);n&&(this.stopBackgroundExecution=n)}catch(n){console.error("Error starting background executor:",n),this.isBackgroundServiceRunning=!1}})())}stop(){if(this.stopBackgroundExecution){try{this.stopBackgroundExecution()}catch{console.error("Error stopping background executor")}this.stopBackgroundExecution=null}this.isBackgroundServiceRunning=!1}async execute(e=5e3){const r=await this.getAddressesFromHTLCs();r.length===0&&r.push(Se(this,bo).userId.toLowerCase());let n=!1,s=null;const i=async()=>{if(!n){n=!0;try{const a=r.map(async c=>{try{const u=await Se(this,go).getOrders({from_owner:c,status:D.OrderLifecycle.pending,per_page:500});return u.ok?u.val.data:(this.events.emit("error",{},`Failed to fetch orders for address ${c}: ${u.error}`),[])}catch(u){return this.events.emit("error",{},`Failed to fetch orders for address ${c}: ${u}`),[]}}),o=await Promise.all(a);this.events.emit("onPendingOrdersChanged",o.flat()),await this.processOrderActions(o.flat())}finally{n=!1}}};return await i(),s=setInterval(i,e),()=>{s&&clearInterval(s)}}async processOrderActions(e){const r=new Set([D.OrderStatus.InitiateDetected,D.OrderStatus.AwaitingRefund,D.OrderStatus.Initiated,D.OrderStatus.RefundDetected,D.OrderStatus.Refunded,D.OrderStatus.Expired]),n=e.map(async s=>{try{D.isBitcoin(s.source_swap.chain)&&r.has(s.status)&&!D.isCompleted(s)&&await this.postRefundSACP(s),D.parseAction(s)===D.OrderAction.Redeem&&await this.handleRedeemAction(s)}catch(i){this.events.emit("error",s,`Error processing order ${s.order_id}: ${i}`)}});await Promise.all(n)}async handleRedeemAction(e){const r=await Se(this,wo).generateSecret(e.nonce);if(!r.ok){this.events.emit("error",e,r.error);return}const n=m.trim0x(r.val.secretHash),s=m.trim0x(e.source_swap.secret_hash);if(n!==s){this.events.emit("log",e.order_id,"skipping redeem: secret hash mismatch");return}const i=r.val.secret,a=D.getBlockchainType(e.destination_swap.chain),c={[D.BlockchainType.evm]:()=>this.evmRedeem(e,i),[D.BlockchainType.bitcoin]:()=>this.btcRedeem(e,i),[D.BlockchainType.starknet]:()=>this.starknetRedeem(e,i),[D.BlockchainType.solana]:()=>this.solRedeem(e,i),[D.BlockchainType.xrpl]:()=>this.xrplRedeem(e,i),[D.BlockchainType.sui]:()=>this.suiRedeem(e,i),[D.BlockchainType.tron]:()=>this.tronRedeem(e,i)}[a];c?await c():this.events.emit("error",e,`Unsupported chain: ${e.destination_swap.chain}`)}async evmRedeem(e,r){if(this.events.emit("log",e.order_id,"executing evm redeem"),Se(this,Ne).getOrderExecution(e,D.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.evm){this.events.emit("error",e,"EVM HTLC is required");return}const s=await this.htlcs.evm.redeem(e,r);if(!s.ok){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,s.val),this.events.emit("success",e,D.OrderAction.Redeem,s.val)}async starknetRedeem(e,r){if(this.events.emit("log",e.order_id,"executing starknet redeem"),Se(this,Ne).getOrderExecution(e,D.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.starknet){this.events.emit("error",e,"Starknet HTLC is required");return}const s=await this.htlcs.starknet.redeem(e,r);if(!s.ok){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,s.val),this.events.emit("success",e,D.OrderAction.Redeem,s.val))}async solRedeem(e,r){if(this.events.emit("log",e.order_id,"executing sol redeem"),Se(this,Ne).getOrderExecution(e,D.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.solana){this.events.emit("error",e,"Solana HTLC is required");return}const s=await this.htlcs.solana.redeem(e,r);if(s.error){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,s.val),this.events.emit("success",e,D.OrderAction.Redeem,s.val))}async suiRedeem(e,r){if(this.events.emit("log",e.order_id,"executing sui redeem"),Se(this,Ne).getOrderExecution(e,D.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.sui){this.events.emit("error",e,"Sui HTLC is required");return}const s=await this.htlcs.sui.redeem(e,r);if(s.error){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,s.val),this.events.emit("success",e,D.OrderAction.Redeem,s.val))}async tronRedeem(e,r){if(this.events.emit("log",e.order_id,"executing tron redeem"),Se(this,Ne).getOrderExecution(e,D.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.tron){this.events.emit("error",e,"Tron HTLC is required");return}const s=await this.htlcs.tron.redeem(e,r);if(s.error){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,s.val),this.events.emit("success",e,D.OrderAction.Redeem,s.val))}async xrplRedeem(e,r){if(this.events.emit("log",e.order_id,"executing xrpl redeem"),Se(this,Ne).getOrderExecution(e,D.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.xrpl){this.events.emit("error",e,"XRPL HTLC is required");return}const s=await this.htlcs.xrpl.redeem(e,r);if(s.error){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,s.val),this.events.emit("success",e,D.OrderAction.Redeem,s.val))}async btcRedeem(e,r){var o,c;const n=(o=this.htlcs.bitcoin)==null?void 0:o.getProvider();if(!n){this.events.emit("error",e,"Bitcoin provider not found");return}const s=Se(this,Ne).getBitcoinRedeem(e.order_id),i=(c=e.destination_swap.initiate_tx_hash.split(",").at(-1))==null?void 0:c.split(":").at(0);if(!i){this.events.emit("error",e,"Failed to get initiate_tx_hash");return}let a=!1;if(s)if(s.redeemedFromUTXO&&s.redeemedFromUTXO!==i)a=!0,this.events.emit("log",e.order_id,"rbf btc redeem");else if(s.redeemedAt&&Date.now()-s.redeemedAt>1e3*60*15)this.events.emit("log",e.order_id,"redeem not confirmed in last 15 minutes"),a=!0;else{this.events.emit("log",e.order_id,"btcRedeem: already redeemed");return}else if(e.destination_swap.redeem_tx_hash&&!Number(e.destination_swap.redeem_block_number))try{const u=await(await n).getTransaction(e.destination_swap.redeem_tx_hash);let l=!1;for(const f of u.vin)if(f.txid===i){l=!0;break}if(l){this.events.emit("log",e.order_id,"already a valid redeem");let f=0;try{const[p]=await(await n).getTransactionTimes([e.destination_swap.redeem_tx_hash]);p!==0&&(f=p)}catch{f=Date.now()}Se(this,Ne).setBitcoinRedeem(e.order_id,{redeemedFromUTXO:i,redeemedAt:f,redeemTxHash:e.destination_swap.redeem_tx_hash});return}a=!0}catch(u){if(u.message.includes("Transaction not found"))a=!0;else{this.events.emit("error",e,"Failed to get redeem tx: "+u);return}}this.events.emit("log",e.order_id,"executing btc redeem");try{if(!this.htlcs.bitcoin){this.events.emit("error",e,"Bitcoin HTLC is required");return}const u=await this.htlcs.bitcoin.getRedeemHex(e,m.trim0x(r),a?[i]:[]);if(!u.ok){this.events.emit("error",e,"Failed to get redeem hex");return}const l=await this.broadcastRedeemTx(u.val,e.order_id);if(!l.ok){this.events.emit("error",e,l.error||"Failed to broadcast redeem tx");return}a?(this.events.emit("log",e.order_id,"rbf: btc redeem success"),this.events.emit("rbf",e,l.val)):this.events.emit("success",e,D.OrderAction.Redeem,l.val),Se(this,Ne).setBitcoinRedeem(e.order_id,{redeemedFromUTXO:i,redeemedAt:Date.now(),redeemTxHash:l.val})}catch(u){this.events.emit("error",e,"Failed btc redeem: "+u)}}async postRefundSACP(e){if(e.source_swap.delegate)try{if(!this.htlcs.bitcoin){this.events.emit("error",e,"Bitcoin HTLC is required");return}const n=await Se(this,Mi).getAuthHeaders();if(n.error){this.events.emit("error",e,"Failed to get auth headers: "+n.error);return}const s=await m.Fetcher.post(new m.Url(Se(this,is).baseurl).endpoint("relayer/bitcoin/instant-refund-hash"),{body:JSON.stringify({order_id:e.order_id}),headers:{"Content-Type":"application/json",...n.val}});if(s.error||!s.result){this.events.emit("error",e,"Failed to get hash while posting instant refund SACP: "+s.error);return}const i=await this.htlcs.bitcoin.generateInstantRefundSACPWithHash(s.result),a=new m.Url(Se(this,is).baseurl).endpoint("relayer/bitcoin/instant-refund");(await m.Fetcher.post(a,{headers:{"Content-Type":"application/json",...n.val},body:JSON.stringify({order_id:e.order_id,signatures:i.val})})).ok&&Se(this,Ne).setSacpCache(e.order_id,{initTxHash:e.source_swap.initiate_tx_hash})}catch(n){this.events.emit("error",e,"Failed to generate and post SACP: "+n);return}}async broadcastRedeemTx(e,r){try{if(!Se(this,is))return m.Err("API not found");const n=new m.Url(Se(this,is).relayer).endpoint("/bitcoin/redeem "),s=await Se(this,Mi).getAuthHeaders(),a=await(await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...s.val},body:JSON.stringify({redeem_tx_bytes:e,order_id:r})})).json();return a.status==="Ok"&&a.result?m.Ok(a.result):m.Err(a.error)}catch(n){return m.Err("Failed to broadcast redeem tx: "+n)}}}bo=new WeakMap,go=new WeakMap,wo=new WeakMap,Ne=new WeakMap,Mi=new WeakMap,is=new WeakMap;class x4 extends m.EventBroker{emit(e,...r){super.emit(e,...r)}}class _0 extends D.Orderbook{constructor(e){const{api:r}=Vf(e.environment);if(!r)throw new Error("API Key not found");super(new m.Url(r.baseurl),$f(e.apiKey)),this._redeemServiceEnabled=!0,this.executeInterval=5e3,this._api=r,this._digestKey=E4(e.digestKey),this._auth=$f(e.apiKey),this._quote=e.quote??new Fb(this._api.baseurl,this._auth),this._htlcs=e.htlc??{},this._events=new x4,this._executor=this._digestKey?new S4(this._digestKey,this.htlcs,this,this._auth,this._api,this._events):void 0}static fromWallets(e){const r=$f(e.apiKey),{api:n,network:s}=Vf(e.environment);if(!n)throw new Error("API not found, invalid environment "+e.environment);const i=e.wallets?{evm:e.wallets.evm?new Rw(n.baseurl,e.wallets.evm,r):void 0,starknet:e.wallets.starknet?new $w(n.baseurl,e.wallets.starknet,s,r):void 0,solana:e.wallets.solana?new Qw(e.wallets.solana,new m.Url(n.baseurl),s,r,{programAddress:e.solanaProgramAddress}):void 0,sui:e.wallets.sui?new g4(n.baseurl,e.wallets.sui,s,r):void 0,bitcoin:e.wallets.bitcoin?new eE(e.wallets.bitcoin,s):void 0,tron:e.wallets.tron?new w4(n.baseurl,s,r,e.wallets.tron):void 0,xrpl:e.wallets.xrpl?new E6(n.baseurl,s,r,e.wallets.xrpl):void 0}:{};return new _0({htlc:i,...e})}get htlcs(){return{evm:this._htlcs.evm,starknet:this._htlcs.starknet,solana:this._htlcs.solana,sui:this._htlcs.sui,bitcoin:this._htlcs.bitcoin,tron:this._htlcs.tron,xrpl:this._htlcs.xrpl}}get quote(){return this._quote}get secretManager(){if(this._redeemServiceEnabled||!this._secretManager)throw new Error("Secret manager is not available");return this._secretManager}get digestKey(){return this._digestKey}get executor(){return this._executor}get redeemServiceEnabled(){return this._redeemServiceEnabled}async createSwap(e,r){const n=D.ChainAsset.from(e.fromAsset).blockchainType,s=await G6(n,this._htlcs);if(!s.ok)return m.Err(s.error);const i=await this.createOrder(e);if(!i.ok)return m.Err(i.error);const a=i.val;switch(r==null||r(Ta.orderCreated),r==null||r(Ta.orderInitiating),n){case D.BlockchainType.evm:if(!this._htlcs.evm||!D.isEvmOrderResponse(a))return m.Err("Order type does not match EVM blockchain type");{const o=await this._htlcs.evm.initiate(a);if(!o.ok)return m.Err(`EVM HTLC initiation failed: ${o.error}`)}break;case D.BlockchainType.solana:if(!this._htlcs.solana||!D.isSolanaOrderResponse(a))return m.Err("Order type does not match Solana blockchain type");{const o=await this._htlcs.solana.initiate(a);if(!o.ok)return m.Err(`Solana HTLC initiation failed: ${o.error}`)}break;case D.BlockchainType.starknet:if(!this._htlcs.starknet||!D.isStarknetOrderResponse(a))return m.Err("Order type does not match Starknet blockchain type");{const o=await this._htlcs.starknet.initiate(a);if(!o.ok)return m.Err(`Starknet HTLC initiation failed: ${o.error}`)}break;case D.BlockchainType.sui:if(!this._htlcs.sui||!D.isSuiOrderResponse(a))return m.Err("Order type does not match Sui blockchain type");{const o=await this._htlcs.sui.initiate(a);if(!o.ok)return m.Err(`Sui HTLC initiation failed: ${o.error}`)}break;case D.BlockchainType.tron:if(!this._htlcs.tron||!D.isEvmOrderResponse(a))return m.Err("Order type does not match Tron blockchain type");{const o=await this._htlcs.tron.initiate(a);if(!o.ok)return m.Err(`Tron HTLC initiation failed: ${o.error}`)}break;case D.BlockchainType.xrpl:if(!this._htlcs.xrpl||!D.isXrplOrderResponse(a))return m.Err("Order type does not match XRPL blockchain type");{const o=await this._htlcs.xrpl.initiate(a);if(!o.ok)return m.Err(`XRPL HTLC initiation failed: ${o.error}`)}break;case D.BlockchainType.bitcoin:return m.Ok(a);case D.BlockchainType.litecoin:return m.Ok(a);case D.BlockchainType.alpen_signet:return m.Ok(a);case D.BlockchainType.spark:return m.Ok(a);case D.BlockchainType.lightning:return m.Ok(a);default:return m.Err("Unsupported blockchain type for swap initiation")}return r==null||r(Ta.orderInitiated),m.Ok(a.order_id)}async createOrder(e){var T;if(m.hasKeys(e,["source","destination","nonce"]))return super.createOrder(e);const r=e,n=await this.validateAndFillParams(r);if(!n.ok)return m.Err(n.error??"Validation failed");const{sendAddress:s,receiveAddress:i,fromAsset:a,toAsset:o}=n.val,c=Date.now().toString();let u;if(!this.redeemServiceEnabled){const v=await this.secretManager.generateSecret(c);if(!v.ok)return m.Err(v.error);u=v.val.secretHash}const l=(T=r.addresses)==null?void 0:T.bitcoin,f=D.isBitcoin(D.ChainAsset.from(r.fromAsset).chain),p=D.isBitcoin(D.ChainAsset.from(r.toAsset).chain),d=!!u,b={source:{asset:a.toString(),owner:!r.sourceAddress&&f?l??s:s,delegate:d&&f?s:null,amount:r.sendAmount},destination:{asset:o.toString(),owner:!r.destinationAddress&&p?l??i:i,delegate:d&&p?i:null,amount:r.receiveAmount},nonce:Number(c),...!this.redeemServiceEnabled&&u?{secret_hash:m.trim0x(u)}:{},solver_id:r.solverId,...r.quoteId?{quote_id:r.quoteId}:{},affiliate_fees:r.affiliateFee,slippage:0},g=await super.createOrder(b);if(!g.ok)return m.Err(g.error);const A=D.ChainAsset.from(r.fromAsset).blockchainType,S=[D.BlockchainType.alpen_signet,D.BlockchainType.bitcoin,D.BlockchainType.litecoin,D.BlockchainType.spark].includes(A)?D.BlockchainType.bitcoin:[D.BlockchainType.tron].includes(A)?D.BlockchainType.evm:A;return g.val.type!==S&&g.val.type!==A?m.Err("Order response type does not match source blockchain type"):m.Ok(g.val)}async validateAndFillParams(e){var c;if(!e.fromAsset||!e.toAsset)return m.Err("Source and destination assets are required for swap");const r=D.ChainAsset.from(e.fromAsset),n=D.ChainAsset.from(e.toAsset);if(r.network!==n.network)return m.Err("Both assets should be on the same network (either mainnet or testnet)");const s=$0(e.sendAmount);if(!s.ok)return m.Err(s.error);const i=$0(e.receiveAmount);if(!i.ok)return m.Err(i.error);if(s<i)return m.Err("Send amount should be greater than receive amount");if(e.sourceAddress&&e.destinationAddress){const u=await this._getAddresses(r.blockchainType,{[r.blockchainType]:e.sourceAddress}),l=await this._getAddresses(n.blockchainType,{[n.blockchainType]:e.destinationAddress});return!u.ok||!l.ok?m.Err(u.error||l.error):m.Ok({sendAddress:u.val,receiveAddress:l.val,fromAsset:r,toAsset:n})}if((D.isBitcoin(D.ChainAsset.from(e.fromAsset).chain)||D.isBitcoin(D.ChainAsset.from(e.toAsset).chain))&&!((c=e.addresses)!=null&&c.bitcoin))return m.Err("Bitcoin address in addresses is required if source or destination chain is bitcoin, it is used as refund or redeem address.");const a=await this._getAddresses(r.blockchainType,e.addresses);if(!a.ok)return m.Err(a.error);const o=await this._getAddresses(n.blockchainType,e.addresses);return o.ok?m.Ok({sendAddress:a.val,receiveAddress:o.val,fromAsset:r,toAsset:n}):m.Err(o.error)}async _getAddresses(e,r){var n;if(this._redeemServiceEnabled&&r&&r[e])return m.Ok(r[e]);switch(e){case D.BlockchainType.evm:return this._htlcs.evm?m.Ok(this._htlcs.evm.htlcActorAddress):m.Err("Please provide evmHTLC when initializing garden or pass EVM address in SwapParams");case D.BlockchainType.bitcoin:{const s=(n=this._htlcs.bitcoin)==null?void 0:n.getPublicKey;return!s||!M6(s)?m.Err("Invalid btc public key or pass Bitcoin address in SwapParams"):m.Ok(De(s))}case D.BlockchainType.solana:return this._htlcs.solana?m.Ok(this._htlcs.solana.htlcActorAddress):m.Err("Please provide solanaHTLC when initializing garden or pass Solana address in SwapParams");case D.BlockchainType.starknet:return this._htlcs.starknet?m.Ok(this._htlcs.starknet.htlcActorAddress):m.Err("Please provide starknetHTLC when initializing garden or pass Starknet address in SwapParams");case D.BlockchainType.sui:return this._htlcs.sui?m.Ok(this._htlcs.sui.htlcActorAddress):m.Err("Please provide suiHTLC when initializing garden or pass Sui address in SwapParams");case D.BlockchainType.tron:return this._htlcs.tron?m.Ok(this._htlcs.tron.htlcActorAddress):m.Err("Please provide tronHTLC when initializing garden or pass Tron address in SwapParams");case D.BlockchainType.xrpl:return this._htlcs.xrpl?m.Ok(this._htlcs.xrpl.htlcActorAddress):m.Err("Please provide xrplHTLC when initializing garden or pass XRPL address in SwapParams");default:return m.Err("Unsupported chain")}}on(e,r){return this._events.on(e,r),this}off(e,r){return this._events.off(e,r),this}}class k4{constructor(e,r,n){this.callData=new Qe.CallData(Nw),this.account=e,this.starknetProvider=new Qe.RpcProvider({nodeUrl:r||(n?Fa[n].nodeUrl:Fa.mainnet.nodeUrl)})}get htlcActorAddress(){return this.account.address}async getHTLCContract(e,r=!1){const n=r?e.destination_swap.asset:e.source_swap.asset;return new Qe.Contract({abi:Mw,address:n,providerOrAccount:this.account})}async initiate(e){try{const n=await(await this.getHTLCContract(e)).token();if(!n)throw new Error("Token address retrieval failed");const s=Qe.num.toHex(n),i=Qe.cairo.uint256(BigInt(e.source_swap.amount));try{const u=await Uw(this.account,s,e.source_swap.asset,BigInt(e.source_swap.amount),this.starknetProvider);if(u.error)return m.Err(u.error)}catch(u){return m.Err(`Allowance check failed: ${u}`)}const a=e.source_swap.secret_hash;if(!a)return m.Err("Invalid order: secret_hash is undefined");const o=m.hexToU128Array(a),c=await this.account.execute({contractAddress:e.source_swap.asset,entrypoint:"initiate",calldata:[e.source_swap.redeemer,e.source_swap.timelock.toString(),i.low.toString(),i.high.toString(),...o.map(u=>u.toString())]});if(!c.transaction_hash)throw new Error("Failed to initiate HTLC transaction");return m.Ok(c.transaction_hash)}catch(r){return m.Err(`HTLC Initiation Error: ${r}`)}}async redeem(e,r){try{const n=await this.getHTLCContract(e,!0),s=e.source_swap.chain.includes("starknet")?e.source_swap.swap_id:e.destination_swap.swap_id,i=await this.account.execute({contractAddress:n.address,entrypoint:"redeem",calldata:Qe.CallData.compile({swap_id:s,secret:m.hexToU32Array(r)})});return i.transaction_hash?m.Ok(i.transaction_hash):m.Err("Failed to redeem HTLC transaction")}catch{return m.Err("HTLC Redeem Error")}}async refund(e){try{const r=e.source_swap.chain.includes("starknet")?e.source_swap.swap_id:e.destination_swap.swap_id,n=await this.getHTLCContract(e),s=await this.account.execute({contractAddress:n.address,entrypoint:"refund",calldata:{orderId:r}});return s.transaction_hash?m.Ok(s.transaction_hash):m.Err("Failed to refund HTLC transaction")}catch{return m.Err("HTLC Refund Error")}}}class T4{constructor(e){if(this.provider=e,!e)throw new Error("Provider is required");this.provider=e,this.program=new Ar.Program(Ud,e)}get htlcActorAddress(){if(!this.program.programId)throw new Error("No program found");return this.provider.publicKey.toBase58()}async initiate(e){if(!e)return m.Err("Order is required");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=os.from(e),a=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Ar.web3.PublicKey.findProgramAddressSync(a,this.program.programId)[0];const o=await this.program.methods.initiate(s,i,r,n).accounts({initiator:this.provider.publicKey}).transaction(),c=await this.provider.sendAndConfirm(o);return c?m.Ok(c):m.Err("Failed to initiate HTLC transaction")}catch(r){return m.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async redeem(e,r){if(!e)return m.Err("Order is required");if(!r)return m.Err("Secret is required");const{secretHash:n}=os.from(e),s=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Ar.web3.PublicKey.findProgramAddressSync(s,this.program.programId)[0];try{const{redeemer:i}=os.from(e);if(!this.swapAccount)return m.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const a=await this.program.methods.redeem(Zw(r)).accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey,redeemer:i}).transaction(),o=await this.provider.sendAndConfirm(a);return o?m.Ok(o):m.Err("Failed to redeem HTLC transaction")}catch(i){return m.Err(`Error redeeming swap: ${i instanceof Error?i.message:String(i)}`)}}async refund(e){if(!e)return m.Err("Order is required");const{secretHash:r}=os.from(e),n=[Buffer.from("swap_account"),Buffer.from(r)];this.swapAccount=Ar.web3.PublicKey.findProgramAddressSync(n,this.program.programId)[0];try{if(console.log("Initiating refund for ::",e.source_swap.swap_id),!this.swapAccount)return m.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const s=await this.program.methods.refund().accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey}).transaction(),i=await this.provider.sendAndConfirm(s);return i?m.Ok(i):m.Err("Failed to refund HTLC transaction")}catch(s){return m.Err(`Error refunding swap: ${s instanceof Error?s.message:String(s)}`)}}}const _4=t=>t.map(e=>e),I4=t=>{if(t===m.Network.TESTNET)return P4;if(t===m.Network.LOCALNET)return B4;if(t===m.Network.MAINNET)return O4;throw new Error("Invalid network")},P4=["https://mempool.space/testnet4/api"],O4=["https://mempool.space/api","https://blockstream.info/api"],B4=["http://localhost:30000"],Bs={INVALID_PK:"invalid private key",FEE_EXCEEDS_AMOUNT:(t,e)=>`fee exceeds amount: fee: ${t} > amount: ${e}`,SWAP_NOT_FOUND:"swap config not found, please set the swap config first",SCRIPT_NOT_FUNDED:"script not funded",SWAP_NOT_EXPIRED:t=>`swap not expired. Need ${t} more blocks`,MIN_AMOUNT:t=>`amount is too low. Minimum amount is ${t}`,INSUFFICIENT_FUNDS:(t,e)=>`insufficient funds, need ${e} but got ${t}`,AmtPlusFeeExceedsBalance:(t,e,r)=>`amount + fee exceeds balance. Need ${t+e} but got ${r}`},ka={INVALID_SECRET_HASH:"invalid secret hash",INVALID_PUBKEY_OR_SECRET:"invalid public key or secret",INVALID_PUBKEY:"invalid public key",ORDER_NOT_EXPIRED:"you cannot refund before your transaction expires"},Om=t=>t.sort((e,r)=>e.status.confirmed!=r.status.confirmed?e.status.confirmed?-1:1:r.value-e.value);class C4{constructor(e,r){this.cacheTimeout=2e3,this.utxosCache=new Map,this.APIs=r?_4([r]):I4(e),this.network=D6(e)}async getTxIndex(e,r){const n=this.APIs.map(i=>`${i}/tx/${e}`),{vout:s}=await m.Fetcher.getWithFallback(n);for(let i=0;i<s.length;i++)if(s[i].scriptpubkey_address===r)return i;throw new Error("failed to get tx index")}async broadcast(e){if(!/^[0-9a-fA-F]+$/.test(e))throw new Error("invalid tx hex");for(let r=0;r<5;r++)try{return m.Fetcher.postWithFallback(this.APIs.map(n=>`${n}/tx`),{body:e})}catch(n){if(r===4)throw n;await new Promise(s=>setTimeout(s,500))}throw new Error("failed to broadcast tx")}async getBalance(e){return(await this.getUTXOs(e)).reduce((r,n)=>r+n.value,0)}setTimeoutForCache(e){this.cacheTimeout=e}async getUTXOs(e,r){const n=this.utxosCache.get(e);if(n&&Date.now()-n.timestamp<this.cacheTimeout)return Bm(n.utxos,r);const s=await m.Fetcher.getWithFallback(this.APIs.map(i=>`${i}/address/${e}/utxo`),{signal:AbortSignal.timeout(5e3)});return this.utxosCache.set(e,{timestamp:Date.now(),utxos:s}),Bm(s,r)}async getTransactionHex(e){return m.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${e}/hex`))}async getTransaction(e){return m.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${e}`))}async getConfirmations(e){const r=await this.getTransaction(e);return!r.status.confirmed||!r.status.block_height?0:await this.getLatestTip()-r.status.block_height+1}async getFeeRates(){if(this.network===Cr.Regtest)return{fastestFee:8,halfHourFee:7,hourFee:6,economyFee:4,minimumFee:2};let e="";this.network===Cr.Testnet&&(e="testnet4/");const r=`https://mempool.space/${e}api/v1/fees/recommended`,n=`https://blockstream.info/${e}api/fee-estimates`,s=await m.Fetcher.getWithFallback([r,n],{signal:AbortSignal.timeout(5e3)});return"fastestFee"in s?s.fastestFee===1?{fastestFee:2,halfHourFee:2,hourFee:2,economyFee:2,minimumFee:2}:s:{fastestFee:s[1],halfHourFee:s[5],hourFee:s[10],economyFee:s[20],minimumFee:s[25]}}async getTransactions(e,r){const n=await m.Fetcher.getWithFallback(this.APIs.map(s=>`${s}/address/${e}/txs`));if(r===mc.ALL)return n;if(r===mc.IN)return n.filter(s=>s.vout.find(i=>i.scriptpubkey_address===e));if(r===mc.OUT)return n.filter(s=>s.vin.find(i=>i.prevout.scriptpubkey_address===e));throw new Error("failed to get transactions: invalid bitcoin tx type")}getNetwork(){return this.network}async getLatestTip(){return m.Fetcher.getWithFallback(this.APIs.map(e=>`${e}/blocks/tip/height`))}async suggestFee(e,r,n){const i=(await this.getUTXOs(e,r)).length,a=2,o=await this.getFeeRates();return Math.floor(o[C6[n]]*1.05)*(i*70+a*31+10)}async getTransactionTimes(e){const r=e.map(s=>`txId[]=${s}`).join("&");return(await m.Fetcher.getWithFallback(this.APIs.map(s=>`${s}/v1/transaction-times?${r}`))).map(s=>s*1e3)}}const Bm=(t,e)=>{if(Array.isArray(t)){if(e){const r=t.reduce((i,a)=>i+a.value,0);if(r<e)throw new Error(Bs.INSUFFICIENT_FUNDS(r,e));let n=BigInt(0);t.sort((i,a)=>a.value-i.value);const s=[];for(const i of t)if(n+=BigInt(i.value),s.push(i),n>=e)break;return Om(s)}return Om(t)}return[]},ga={p2wpkh:"p2wpkh","p2wpkh-p2sh":"p2wpkh-p2sh"},_c={ALL:me.Transaction.SIGHASH_ALL,NONE:me.Transaction.SIGHASH_NONE,SINGLE:me.Transaction.SIGHASH_SINGLE,ALL_ANYONECANPAY:me.Transaction.SIGHASH_ALL|me.Transaction.SIGHASH_ANYONECANPAY,NONE_ANYONECANPAY:me.Transaction.SIGHASH_NONE|me.Transaction.SIGHASH_ANYONECANPAY,SINGLE_ANYONECANPAY:me.Transaction.SIGHASH_SINGLE|me.Transaction.SIGHASH_ANYONECANPAY};class Gs{constructor(e,r){this._scriptType=e,this._sigHashType=r}get scriptType(){return this._scriptType}get sigHashType(){return this._sigHashType}toString(){return`${this._scriptType} ${this._sigHashType}`}static async fromString(e){const[r,n]=e.split(" "),s=await R0.mixed().oneOf(["segwitV0","segwitV1","p2shSignature"]).required().validate(r),i=await R0.mixed().oneOf(Object.values(_c)).required().validate(parseInt(n));return new Gs(s,i)}}const R4=(t,e,r=!1)=>{const n=a=>{try{a=me.address.fromBech32(a).data.toString("hex")}catch(o){if(qf(o))(o.message.includes("Mixed-case string")||o.message.includes("too short"))&&(a=me.address.fromBase58Check(a).hash.toString("hex"));else throw new Error(String(o))}return a},s=me.script.fromASM(`
86
+ ${String(n)}`);zd(e);for(let s=0;s<e.callbacks.length;s++){const i=n[s];i instanceof Error?e.callbacks[s].reject(i):e.callbacks[s].resolve(i)}}).catch(n=>{Bf(t,e,n)})}function Bf(t,e,r){zd(e);for(let n=0;n<e.keys.length;n++)t.clear(e.keys[n]),e.callbacks[n].reject(r)}function zd(t){if(t.cacheHits)for(let e=0;e<t.cacheHits.length;e++)t.cacheHits[e]()}function VI(t){if(!(!t||t.batch!==!1))return 1;const r=t&&t.maxBatchSize;if(r===void 0)return 1/0;if(typeof r!="number"||r<1)throw new TypeError(`maxBatchSize must be a positive number: ${r}`);return r}function GI(t){const e=t&&t.batchScheduleFn;if(e===void 0)return LI;if(typeof e!="function")throw new TypeError(`batchScheduleFn must be a function: ${e}`);return e}function qI(t){const e=t&&t.cacheKeyFn;if(e===void 0)return r=>r;if(typeof e!="function")throw new TypeError(`cacheKeyFn must be a function: ${e}`);return e}function WI(t){if(!(!t||t.cache!==!1))return null;const r=t&&t.cacheMap;if(r===void 0)return new Map;if(r!==null){const s=["get","set","delete","clear"].filter(i=>r&&typeof r[i]!="function");if(s.length!==0)throw new TypeError("Custom cacheMap missing methods: "+s.join(", "))}return r}function KI(t){return t&&t.name?t.name:null}function b2(t){return typeof t=="object"&&t!==null&&"length"in t&&typeof t.length=="number"&&(t.length===0||t.length>0&&Object.prototype.hasOwnProperty.call(t,t.length-1))}function Hc(t){let e=BigInt(t);const r=[];let n=0;if(e===0n)return[0];for(;e>0;)r[n]=Number(e&0x7fn),e>>=7n,e>0n&&(r[n]|=128),n+=1;return r}function XI(t){let e=0n,r=0n,n=0;for(;;){if(n>=t.length)throw new Error("ULEB decode error: buffer overflow");const s=t[n];if(n+=1,e+=BigInt(s&127)<<r,!(s&128))break;r+=7n}if(e>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("ULEB decode error: value exceeds MAX_SAFE_INTEGER");return{value:Number(e),length:n}}class YI{constructor(e){this.bytePosition=0,this.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength)}shift(e){return this.bytePosition+=e,this}read8(){const e=this.dataView.getUint8(this.bytePosition);return this.shift(1),e}read16(){const e=this.dataView.getUint16(this.bytePosition,!0);return this.shift(2),e}read32(){const e=this.dataView.getUint32(this.bytePosition,!0);return this.shift(4),e}read64(){const e=this.read32(),n=this.read32().toString(16)+e.toString(16).padStart(8,"0");return BigInt("0x"+n).toString(10)}read128(){const e=BigInt(this.read64()),n=BigInt(this.read64()).toString(16)+e.toString(16).padStart(16,"0");return BigInt("0x"+n).toString(10)}read256(){const e=BigInt(this.read128()),n=BigInt(this.read128()).toString(16)+e.toString(16).padStart(32,"0");return BigInt("0x"+n).toString(10)}readBytes(e){const r=this.bytePosition+this.dataView.byteOffset,n=new Uint8Array(this.dataView.buffer,r,e);return this.shift(e),n}readULEB(){const e=this.bytePosition+this.dataView.byteOffset,r=new Uint8Array(this.dataView.buffer,e),{value:n,length:s}=XI(r);return this.shift(s),n}readVec(e){const r=this.readULEB(),n=[];for(let s=0;s<r;s++)n.push(e(this,s,r));return n}}function JI(t,e){switch(e){case"base58":return Mu(t);case"base64":return St(t);case"hex":return Xi(t);default:throw new Error("Unsupported encoding, supported values are: base64, hex")}}function g2(t,e=["<",">"]){const[r,n]=e,s=[];let i="",a=0;for(let o=0;o<t.length;o++){const c=t[o];if(c===r&&a++,c===n&&a--,a===0&&c===","){s.push(i.trim()),i="";continue}i+=c}return s.push(i.trim()),s}class ZI{constructor({initialSize:e=1024,maxSize:r=1/0,allocateSize:n=1024}={}){this.bytePosition=0,this.size=e,this.maxSize=r,this.allocateSize=n,this.dataView=new DataView(new ArrayBuffer(e))}ensureSizeOrGrow(e){const r=this.bytePosition+e;if(r>this.size){const n=Math.min(this.maxSize,Math.max(this.size+r,this.size+this.allocateSize));if(r>n)throw new Error(`Attempting to serialize to BCS, but buffer does not have enough size. Allocated size: ${this.size}, Max size: ${this.maxSize}, Required size: ${r}`);this.size=n;const s=new ArrayBuffer(this.size);new Uint8Array(s).set(new Uint8Array(this.dataView.buffer)),this.dataView=new DataView(s)}}shift(e){return this.bytePosition+=e,this}write8(e){return this.ensureSizeOrGrow(1),this.dataView.setUint8(this.bytePosition,Number(e)),this.shift(1)}writeBytes(e){this.ensureSizeOrGrow(e.length);for(let r=0;r<e.length;r++)this.dataView.setUint8(this.bytePosition+r,e[r]);return this.shift(e.length)}write16(e){return this.ensureSizeOrGrow(2),this.dataView.setUint16(this.bytePosition,Number(e),!0),this.shift(2)}write32(e){return this.ensureSizeOrGrow(4),this.dataView.setUint32(this.bytePosition,Number(e),!0),this.shift(4)}write64(e){return Cf(BigInt(e),8).forEach(r=>this.write8(r)),this}write128(e){return Cf(BigInt(e),16).forEach(r=>this.write8(r)),this}write256(e){return Cf(BigInt(e),32).forEach(r=>this.write8(r)),this}writeULEB(e){return Hc(e).forEach(r=>this.write8(r)),this}writeVec(e,r){return this.writeULEB(e.length),Array.from(e).forEach((n,s)=>r(this,n,s,e.length)),this}*[Symbol.iterator](){for(let e=0;e<this.bytePosition;e++)yield this.dataView.getUint8(e);return this.toBytes()}toBytes(){return new Uint8Array(this.dataView.buffer.slice(0,this.bytePosition))}toString(e){return JI(this.toBytes(),e)}}function Cf(t,e){const r=new Uint8Array(e);let n=0;for(;t>0;)r[n]=Number(t%BigInt(256)),t=t/BigInt(256),n+=1;return r}var w2=t=>{throw TypeError(t)},v2=(t,e,r)=>e.has(t)||w2("Cannot "+r),xr=(t,e,r)=>(v2(t,e,"read from private field"),r?r.call(t):e.get(t)),Lc=(t,e,r)=>e.has(t)?w2("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Dc=(t,e,r,n)=>(v2(t,e,"write to private field"),e.set(t,r),r),Si,xa,xc,ts;const QI=class E2{constructor(e){Lc(this,Si),Lc(this,xa),this.name=e.name,this.read=e.read,this.serializedSize=e.serializedSize??(()=>null),Dc(this,Si,e.write),Dc(this,xa,e.serialize??((r,n)=>{const s=new ZI({initialSize:this.serializedSize(r)??void 0,...n});return xr(this,Si).call(this,r,s),s.toBytes()})),this.validate=e.validate??(()=>{})}write(e,r){this.validate(e),xr(this,Si).call(this,e,r)}serialize(e,r){return this.validate(e),new eP(this,xr(this,xa).call(this,e,r))}parse(e){const r=new YI(e);return this.read(r)}fromHex(e){return this.parse(y2(e))}fromBase58(e){return this.parse(lo(e))}fromBase64(e){return this.parse(tr(e))}transform({name:e,input:r,output:n,validate:s}){return new E2({name:e??this.name,read:i=>n?n(this.read(i)):this.read(i),write:(i,a)=>xr(this,Si).call(this,r?r(i):i,a),serializedSize:i=>this.serializedSize(r?r(i):i),serialize:(i,a)=>xr(this,xa).call(this,r?r(i):i,a),validate:i=>{s==null||s(i),this.validate(r?r(i):i)}})}};Si=new WeakMap;xa=new WeakMap;let cn=QI;const A2=Symbol.for("@mysten/serialized-bcs");function w0(t){return!!t&&typeof t=="object"&&t[A2]===!0}class eP{constructor(e,r){Lc(this,xc),Lc(this,ts),Dc(this,xc,e),Dc(this,ts,r)}get[A2](){return!0}toBytes(){return xr(this,ts)}toHex(){return Xi(xr(this,ts))}toBase64(){return St(xr(this,ts))}toBase58(){return Mu(xr(this,ts))}parse(){return xr(this,xc).parse(xr(this,ts))}}xc=new WeakMap;ts=new WeakMap;function zc({size:t,...e}){return new cn({...e,serializedSize:()=>t})}function Rf({readMethod:t,writeMethod:e,...r}){return zc({...r,read:n=>n[t](),write:(n,s)=>s[e](n),validate:n=>{var s;if(n<0||n>r.maxValue)throw new TypeError(`Invalid ${r.name} value: ${n}. Expected value in range 0-${r.maxValue}`);(s=r.validate)==null||s.call(r,n)}})}function Nf({readMethod:t,writeMethod:e,...r}){return zc({...r,read:n=>n[t](),write:(n,s)=>s[e](BigInt(n)),validate:n=>{var i;const s=BigInt(n);if(s<0||s>r.maxValue)throw new TypeError(`Invalid ${r.name} value: ${s}. Expected value in range 0-${r.maxValue}`);(i=r.validate)==null||i.call(r,s)}})}function tP({serialize:t,...e}){const r=new cn({...e,serialize:t,write:(n,s)=>{for(const i of r.serialize(n).toBytes())s.write8(i)}});return r}function rP({toBytes:t,fromBytes:e,...r}){return new cn({...r,read:n=>{const s=n.readULEB(),i=n.readBytes(s);return e(i)},write:(n,s)=>{const i=t(n);s.writeULEB(i.length);for(let a=0;a<i.length;a++)s.write8(i[a])},serialize:n=>{const s=t(n),i=Hc(s.length),a=new Uint8Array(i.length+s.length);return a.set(i,0),a.set(s,i.length),a},validate:n=>{var s;if(typeof n!="string")throw new TypeError(`Invalid ${r.name} value: ${n}. Expected string`);(s=r.validate)==null||s.call(r,n)}})}function nP(t){let e=null;function r(){return e||(e=t()),e}return new cn({name:"lazy",read:n=>r().read(n),serializedSize:n=>r().serializedSize(n),write:(n,s)=>r().write(n,s),serialize:(n,s)=>r().serialize(n,s).toBytes()})}class sP extends cn{constructor({name:e,fields:r,...n}){const s=Object.entries(r);super({name:e,serializedSize:i=>{let a=0;for(const[o,c]of s){const u=c.serializedSize(i[o]);if(u==null)return null;a+=u}return a},read:i=>{const a={};for(const[o,c]of s)a[o]=c.read(i);return a},write:(i,a)=>{for(const[o,c]of s)c.write(i[o],a)},...n,validate:i=>{var a;if((a=n==null?void 0:n.validate)==null||a.call(n,i),typeof i!="object"||i==null)throw new TypeError(`Expected object, found ${typeof i}`)}})}}class iP extends cn{constructor({fields:e,...r}){const n=Object.entries(e);super({read:s=>{const i=s.readULEB(),a=n[i];if(!a)throw new TypeError(`Unknown value ${i} for enum ${r.name}`);const[o,c]=a;return{[o]:(c==null?void 0:c.read(s))??!0,$kind:o}},write:(s,i)=>{const[a,o]=Object.entries(s).filter(([c])=>Object.hasOwn(e,c))[0];for(let c=0;c<n.length;c++){const[u,l]=n[c];if(u===a){i.writeULEB(c),l==null||l.write(o,i);return}}},...r,validate:s=>{var o;if((o=r==null?void 0:r.validate)==null||o.call(r,s),typeof s!="object"||s==null)throw new TypeError(`Expected object, found ${typeof s}`);const i=Object.keys(s).filter(c=>s[c]!==void 0&&Object.hasOwn(e,c));if(i.length!==1)throw new TypeError(`Expected object with one key, but found ${i.length} for type ${r.name}}`);const[a]=i;if(!Object.hasOwn(e,a))throw new TypeError(`Invalid enum variant ${a}`)}})}}class aP extends cn{constructor({fields:e,name:r,...n}){super({name:r??`(${e.map(s=>s.name).join(", ")})`,serializedSize:s=>{let i=0;for(let a=0;a<e.length;a++){const o=e[a].serializedSize(s[a]);if(o==null)return null;i+=o}return i},read:s=>{const i=[];for(const a of e)i.push(a.read(s));return i},write:(s,i)=>{for(let a=0;a<e.length;a++)e[a].write(s[a],i)},...n,validate:s=>{var i;if((i=n==null?void 0:n.validate)==null||i.call(n,s),!Array.isArray(s))throw new TypeError(`Expected array, found ${typeof s}`);if(s.length!==e.length)throw new TypeError(`Expected array of length ${e.length}, found ${s.length}`)}})}}function oP(t,e,r){return new cn({read:n=>{const s=new Array(t);for(let i=0;i<t;i++)s[i]=e.read(n);return s},write:(n,s)=>{for(const i of n)e.write(i,s)},...r,name:(r==null?void 0:r.name)??`${e.name}[${t}]`,validate:n=>{var s;if((s=r==null?void 0:r.validate)==null||s.call(r,n),!n||typeof n!="object"||!("length"in n))throw new TypeError(`Expected array, found ${typeof n}`);if(n.length!==t)throw new TypeError(`Expected array of length ${t}, found ${n.length}`)}})}function cP(t){return P.enum(`Option<${t.name}>`,{None:null,Some:t}).transform({input:e=>e==null?{None:!0}:{Some:e},output:e=>e.$kind==="Some"?e.Some:null})}function uP(t,e){return new cn({read:r=>{const n=r.readULEB(),s=new Array(n);for(let i=0;i<n;i++)s[i]=t.read(r);return s},write:(r,n)=>{n.writeULEB(r.length);for(const s of r)t.write(s,n)},...e,name:(e==null?void 0:e.name)??`vector<${t.name}>`,validate:r=>{var n;if((n=e==null?void 0:e.validate)==null||n.call(e,r),!r||typeof r!="object"||!("length"in r))throw new TypeError(`Expected array, found ${typeof r}`)}})}function lP(t,e){return P.vector(P.tuple([t,e])).transform({name:`Map<${t.name}, ${e.name}>`,input:r=>[...r.entries()],output:r=>{const n=new Map;for(const[s,i]of r)n.set(s,i);return n}})}const P={u8(t){return Rf({readMethod:"read8",writeMethod:"write8",size:1,maxValue:2**8-1,...t,name:(t==null?void 0:t.name)??"u8"})},u16(t){return Rf({readMethod:"read16",writeMethod:"write16",size:2,maxValue:2**16-1,...t,name:(t==null?void 0:t.name)??"u16"})},u32(t){return Rf({readMethod:"read32",writeMethod:"write32",size:4,maxValue:2**32-1,...t,name:(t==null?void 0:t.name)??"u32"})},u64(t){return Nf({readMethod:"read64",writeMethod:"write64",size:8,maxValue:2n**64n-1n,...t,name:(t==null?void 0:t.name)??"u64"})},u128(t){return Nf({readMethod:"read128",writeMethod:"write128",size:16,maxValue:2n**128n-1n,...t,name:(t==null?void 0:t.name)??"u128"})},u256(t){return Nf({readMethod:"read256",writeMethod:"write256",size:32,maxValue:2n**256n-1n,...t,name:(t==null?void 0:t.name)??"u256"})},bool(t){return zc({size:1,read:e=>e.read8()===1,write:(e,r)=>r.write8(e?1:0),...t,name:(t==null?void 0:t.name)??"bool",validate:e=>{var r;if((r=t==null?void 0:t.validate)==null||r.call(t,e),typeof e!="boolean")throw new TypeError(`Expected boolean, found ${typeof e}`)}})},uleb128(t){return tP({read:e=>e.readULEB(),serialize:e=>Uint8Array.from(Hc(e)),...t,name:(t==null?void 0:t.name)??"uleb128"})},bytes(t,e){return zc({size:t,read:r=>r.readBytes(t),write:(r,n)=>{n.writeBytes(new Uint8Array(r))},...e,name:(e==null?void 0:e.name)??`bytes[${t}]`,validate:r=>{var n;if((n=e==null?void 0:e.validate)==null||n.call(e,r),!r||typeof r!="object"||!("length"in r))throw new TypeError(`Expected array, found ${typeof r}`);if(r.length!==t)throw new TypeError(`Expected array of length ${t}, found ${r.length}`)}})},byteVector(t){return new cn({read:e=>{const r=e.readULEB();return e.readBytes(r)},write:(e,r)=>{const n=new Uint8Array(e);r.writeULEB(n.length),r.writeBytes(n)},...t,name:(t==null?void 0:t.name)??"vector<u8>",serializedSize:e=>{const r="length"in e?e.length:null;return r==null?null:Hc(r).length+r},validate:e=>{var r;if((r=t==null?void 0:t.validate)==null||r.call(t,e),!e||typeof e!="object"||!("length"in e))throw new TypeError(`Expected array, found ${typeof e}`)}})},string(t){return rP({toBytes:e=>new TextEncoder().encode(e),fromBytes:e=>new TextDecoder().decode(e),...t,name:(t==null?void 0:t.name)??"string"})},fixedArray:oP,option:cP,vector:uP,tuple(t,e){return new aP({fields:t,...e})},struct(t,e,r){return new sP({name:t,fields:e,...r})},enum(t,e,r){return new iP({name:t,fields:e,...r})},map:lP,lazy(t){return nP(t)}};var S2=t=>{throw TypeError(t)},x2=(t,e,r)=>e.has(t)||S2("Cannot "+r),vt=(t,e,r)=>(x2(t,e,"read from private field"),e.get(t)),hm=(t,e,r)=>e.has(t)?S2("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),pm=(t,e,r,n)=>(x2(t,e,"write to private field"),e.set(t,r),r),Bs,Ct;const fP=class k2{constructor({prefix:e,cache:r}={}){hm(this,Bs),hm(this,Ct),pm(this,Bs,e??[]),pm(this,Ct,r??new Map)}read(e,r){const n=[vt(this,Bs),...e].join(":");if(vt(this,Ct).has(n))return vt(this,Ct).get(n);const s=r();return vt(this,Ct).set(n,s),typeof s=="object"&&s!==null&&"then"in s?Promise.resolve(s).then(i=>(vt(this,Ct).set(n,i),i)).catch(i=>{throw vt(this,Ct).delete(n),i}):s}readSync(e,r){const n=[vt(this,Bs),...e].join(":");if(vt(this,Ct).has(n))return vt(this,Ct).get(n);const s=r();return vt(this,Ct).set(n,s),s}clear(e){const r=[...vt(this,Bs),...e??[]].join(":");if(!r){vt(this,Ct).clear();return}for(const n of vt(this,Ct).keys())n.startsWith(r)&&vt(this,Ct).delete(n)}scope(e){return new k2({prefix:[...vt(this,Bs),...Array.isArray(e)?e:[e]],cache:vt(this,Ct)})}};Bs=new WeakMap;Ct=new WeakMap;let dP=fP;class T2{constructor({network:e,base:r,cache:n=(r==null?void 0:r.cache)??new dP}){this.network=e,this.base=r??this,this.cache=n}$extend(...e){return Object.create(this,Object.fromEntries(e.map(r=>[r.name,{value:r.register(this)}])))}}let bn;function _2(t){return{lang:(t==null?void 0:t.lang)??(bn==null?void 0:bn.lang),message:t==null?void 0:t.message,abortEarly:(t==null?void 0:t.abortEarly)??(bn==null?void 0:bn.abortEarly),abortPipeEarly:(t==null?void 0:t.abortPipeEarly)??(bn==null?void 0:bn.abortPipeEarly)}}let Uf;function hP(t){return Uf==null?void 0:Uf.get(t)}let Ff;function pP(t){return Ff==null?void 0:Ff.get(t)}let Mf;function yP(t,e){var r;return(r=Mf==null?void 0:Mf.get(t))==null?void 0:r.get(e)}function I2(t){var r,n;const e=typeof t;return e==="string"?`"${t}"`:e==="number"||e==="bigint"||e==="boolean"?`${t}`:e==="object"||e==="function"?(t&&((n=(r=Object.getPrototypeOf(t))==null?void 0:r.constructor)==null?void 0:n.name))??"null":e}function qt(t,e,r,n,s){const i=s&&"input"in s?s.input:r.value,a=(s==null?void 0:s.expected)??t.expects??null,o=(s==null?void 0:s.received)??I2(i),c={kind:t.kind,type:t.type,input:i,expected:a,received:o,message:`Invalid ${e}: ${a?`Expected ${a} but r`:"R"}eceived ${o}`,requirement:t.requirement,path:s==null?void 0:s.path,issues:s==null?void 0:s.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},u=t.kind==="schema",l=(s==null?void 0:s.message)??t.message??yP(t.reference,c.lang)??(u?pP(c.lang):null)??n.message??hP(c.lang);l!==void 0&&(c.message=typeof l=="function"?l(c):l),u&&(r.typed=!1),r.issues?r.issues.push(c):r.issues=[c]}function Tt(t){return{version:1,vendor:"valibot",validate(e){return t["~run"]({value:e},_2())}}}function mP(t,e){return Object.hasOwn(t,e)&&e!=="__proto__"&&e!=="prototype"&&e!=="constructor"}function bP(t,e){const r=[...new Set(t)];return r.length>1?`(${r.join(` ${e} `)})`:r[0]??"never"}var gP=class extends Error{constructor(t){super(t[0].message),this.name="ValiError",this.issues=t}};function v0(t,e){return{kind:"validation",type:"check",reference:v0,async:!1,expects:null,requirement:t,message:e,"~run"(r,n){return r.typed&&!this.requirement(r.value)&&qt(this,"input",r,n),r}}}function Dt(t){return{kind:"validation",type:"integer",reference:Dt,async:!1,expects:null,requirement:Number.isInteger,message:t,"~run"(e,r){return e.typed&&!this.requirement(e.value)&&qt(this,"integer",e,r),e}}}function ju(t){return{kind:"transformation",type:"transform",reference:ju,async:!1,operation:t,"~run"(e){return e.value=this.operation(e.value),e}}}function wP(t,e,r){return typeof t.fallback=="function"?t.fallback(e,r):t.fallback}function Hu(t,e,r){return typeof t.default=="function"?t.default(e,r):t.default}function Vd(t,e){return!t["~run"]({value:e},{abortEarly:!0}).issues}function xe(t,e){return{kind:"schema",type:"array",reference:xe,expects:"Array",async:!1,item:t,message:e,get"~standard"(){return Tt(this)},"~run"(r,n){var i;const s=r.value;if(Array.isArray(s)){r.typed=!0,r.value=[];for(let a=0;a<s.length;a++){const o=s[a],c=this.item["~run"]({value:o},n);if(c.issues){const u={type:"array",origin:"value",input:s,key:a,value:o};for(const l of c.issues)l.path?l.path.unshift(u):l.path=[u],(i=r.issues)==null||i.push(l);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value.push(c.value)}}else qt(this,"type",r,n);return r}}}function P2(t){return{kind:"schema",type:"bigint",reference:P2,expects:"bigint",async:!1,message:t,get"~standard"(){return Tt(this)},"~run"(e,r){return typeof e.value=="bigint"?e.typed=!0:qt(this,"type",e,r),e}}}function ia(t){return{kind:"schema",type:"boolean",reference:ia,expects:"boolean",async:!1,message:t,get"~standard"(){return Tt(this)},"~run"(e,r){return typeof e.value=="boolean"?e.typed=!0:qt(this,"type",e,r),e}}}function Gd(t){return{kind:"schema",type:"lazy",reference:Gd,expects:"unknown",async:!1,getter:t,get"~standard"(){return Tt(this)},"~run"(e,r){return this.getter(e.value)["~run"](e,r)}}}function ot(t,e){return{kind:"schema",type:"literal",reference:ot,expects:I2(t),async:!1,literal:t,message:e,get"~standard"(){return Tt(this)},"~run"(r,n){return r.value===this.literal?r.typed=!0:qt(this,"type",r,n),r}}}function Ke(t,e){return{kind:"schema",type:"nullable",reference:Ke,expects:`(${t.expects} | null)`,async:!1,wrapped:t,default:e,get"~standard"(){return Tt(this)},"~run"(r,n){return r.value===null&&(this.default!==void 0&&(r.value=Hu(this,r,n)),r.value===null)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}function fo(t,e){return{kind:"schema",type:"nullish",reference:fo,expects:`(${t.expects} | null | undefined)`,async:!1,wrapped:t,default:e,get"~standard"(){return Tt(this)},"~run"(r,n){return(r.value===null||r.value===void 0)&&(this.default!==void 0&&(r.value=Hu(this,r,n)),r.value===null||r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}function zt(t){return{kind:"schema",type:"number",reference:zt,expects:"number",async:!1,message:t,get"~standard"(){return Tt(this)},"~run"(e,r){return typeof e.value=="number"&&!isNaN(e.value)?e.typed=!0:qt(this,"type",e,r),e}}}function de(t,e){return{kind:"schema",type:"object",reference:de,expects:"Object",async:!1,entries:t,message:e,get"~standard"(){return Tt(this)},"~run"(r,n){var i;const s=r.value;if(s&&typeof s=="object"){r.typed=!0,r.value={};for(const a in this.entries){const o=this.entries[a];if(a in s||(o.type==="exact_optional"||o.type==="optional"||o.type==="nullish")&&o.default!==void 0){const c=a in s?s[a]:Hu(o),u=o["~run"]({value:c},n);if(u.issues){const l={type:"object",origin:"value",input:s,key:a,value:c};for(const f of u.issues)f.path?f.path.unshift(l):f.path=[l],(i=r.issues)==null||i.push(f);if(r.issues||(r.issues=u.issues),n.abortEarly){r.typed=!1;break}}u.typed||(r.typed=!1),r.value[a]=u.value}else if(o.fallback!==void 0)r.value[a]=wP(o);else if(o.type!=="exact_optional"&&o.type!=="optional"&&o.type!=="nullish"&&(qt(this,"key",r,n,{input:void 0,expected:`"${a}"`,path:[{type:"object",origin:"key",input:s,key:a,value:s[a]}]}),n.abortEarly))break}}else qt(this,"type",r,n);return r}}}function er(t,e){return{kind:"schema",type:"optional",reference:er,expects:`(${t.expects} | undefined)`,async:!1,wrapped:t,default:e,get"~standard"(){return Tt(this)},"~run"(r,n){return r.value===void 0&&(this.default!==void 0&&(r.value=Hu(this,r,n)),r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}function ho(t,e,r){return{kind:"schema",type:"record",reference:ho,expects:"Object",async:!1,key:t,value:e,message:r,get"~standard"(){return Tt(this)},"~run"(n,s){var a,o;const i=n.value;if(i&&typeof i=="object"){n.typed=!0,n.value={};for(const c in i)if(mP(i,c)){const u=i[c],l=this.key["~run"]({value:c},s);if(l.issues){const p={type:"object",origin:"key",input:i,key:c,value:u};for(const d of l.issues)d.path=[p],(a=n.issues)==null||a.push(d);if(n.issues||(n.issues=l.issues),s.abortEarly){n.typed=!1;break}}const f=this.value["~run"]({value:u},s);if(f.issues){const p={type:"object",origin:"value",input:i,key:c,value:u};for(const d of f.issues)d.path?d.path.unshift(p):d.path=[p],(o=n.issues)==null||o.push(d);if(n.issues||(n.issues=f.issues),s.abortEarly){n.typed=!1;break}}(!l.typed||!f.typed)&&(n.typed=!1),l.typed&&(n.value[l.value]=f.value)}}else qt(this,"type",n,s);return n}}}function _e(t){return{kind:"schema",type:"string",reference:_e,expects:"string",async:!1,message:t,get"~standard"(){return Tt(this)},"~run"(e,r){return typeof e.value=="string"?e.typed=!0:qt(this,"type",e,r),e}}}function E0(t,e){return{kind:"schema",type:"tuple",reference:E0,expects:"Array",async:!1,items:t,message:e,get"~standard"(){return Tt(this)},"~run"(r,n){var i;const s=r.value;if(Array.isArray(s)){r.typed=!0,r.value=[];for(let a=0;a<this.items.length;a++){const o=s[a],c=this.items[a]["~run"]({value:o},n);if(c.issues){const u={type:"array",origin:"value",input:s,key:a,value:o};for(const l of c.issues)l.path?l.path.unshift(u):l.path=[u],(i=r.issues)==null||i.push(l);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value.push(c.value)}}else qt(this,"type",r,n);return r}}}function ym(t){let e;if(t)for(const r of t)e?e.push(...r.issues):e=r.issues;return e}function un(t,e){return{kind:"schema",type:"union",reference:un,expects:bP(t.map(r=>r.expects),"|"),async:!1,options:t,message:e,get"~standard"(){return Tt(this)},"~run"(r,n){let s,i,a;for(const o of this.options){const c=o["~run"]({value:r.value},n);if(c.typed)if(c.issues)i?i.push(c):i=[c];else{s=c;break}else a?a.push(c):a=[c]}if(s)return s;if(i){if(i.length===1)return i[0];qt(this,"type",r,n,{issues:ym(i)}),r.typed=!0}else{if((a==null?void 0:a.length)===1)return a[0];qt(this,"type",r,n,{issues:ym(a)})}return r}}}function zo(){return{kind:"schema",type:"unknown",reference:zo,expects:"unknown",async:!1,get"~standard"(){return Tt(this)},"~run"(t){return t.typed=!0,t}}}function Ve(t,e,r){const n=t["~run"]({value:e},_2(r));if(n.issues)throw new gP(n.issues);return n.value}function mt(...t){return{...t[0],pipe:t,get"~standard"(){return Tt(this)},"~run"(e,r){for(const n of t)if(n.kind!=="metadata"){if(e.issues&&(n.kind==="schema"||n.kind==="transformation")){e.typed=!1;break}(!e.issues||!r.abortEarly&&!r.abortPipeEarly)&&(e=n["~run"](e,r))}return e}}}const O2=/^(?!.*(^(?!@)|[-.@])($|[-.@]))(?:[a-z0-9-]{0,63}(?:\.[a-z0-9-]{0,63})*)?@[a-z0-9-]{0,63}$/i,B2=/^(?!.*(^|[-.])($|[-.]))(?:[a-z0-9-]{0,63}\.)+sui$/i,vP=235;function EP(t){return t.length>vP?!1:t.includes("@")?O2.test(t):B2.test(t)}function AP(t,e="at"){const r=t.toLowerCase();let n;if(r.includes("@")){if(!O2.test(r))throw new Error(`Invalid SuiNS name ${t}`);const[s,i]=r.split("@");n=[...s?s.split("."):[],i]}else{if(!B2.test(r))throw new Error(`Invalid SuiNS name ${t}`);n=r.split(".").slice(0,-1)}return e==="dot"?`${n.join(".")}.sui`:`${n.slice(0,-1).join(".")}@${n[n.length-1]}`}const SP=/^([a-z0-9]+(?:-[a-z0-9]+)*)$/,xP=/^\d+$/,kP=64,C2="/",Yt=t=>{const e=t.split(C2);if(e.length<2||e.length>3)return!1;const[r,n,s]=e;return s!==void 0&&!xP.test(s)||!EP(r)?!1:SP.test(n)&&n.length<kP},TP=t=>{const e=t.split(/::|<|>|,/);for(const r of e)if(r.includes(C2)&&!Yt(r))return!1;return!0},_P=32;function mm(t){try{return lo(t).length===_P}catch{return!1}}const Lu=32;function kr(t){return PP(t)&&OP(t)===Lu}function pc(t){return kr(t)}function IP(t){return t.includes("::")?ni(t):t}function ni(t){const[e,r]=t.split("::"),n=Yt(e),s=t.slice(e.length+r.length+4),i=s.includes("<")?s.slice(0,s.indexOf("<")):s,a=s.includes("<")?g2(s.slice(s.indexOf("<")+1,s.lastIndexOf(">"))).map(o=>IP(o.trim())):[];return{address:n?e:ve(e),module:r,name:i,typeParams:a}}function Vc(t){const{address:e,module:r,name:n,typeParams:s}=typeof t=="string"?ni(t):t,i=(s==null?void 0:s.length)>0?`<${s.map(a=>typeof a=="string"?a:Vc(a)).join(",")}>`:"";return`${e}::${r}::${n}${i}`}function ve(t,e=!1){let r=t.toLowerCase();return!e&&r.startsWith("0x")&&(r=r.slice(2)),`0x${r.padStart(Lu*2,"0")}`}function tn(t,e=!1){return ve(t,e)}function PP(t){return/^(0x|0X)?[a-fA-F0-9]+$/.test(t)&&t.length%2===0}function OP(t){return/^(0x|0X)/.test(t)?(t.length-2)/2:t.length/2}function fi(t){const e=Object.entries(t).map(([r,n])=>de({[r]:n}));return mt(un(e),ju(r=>({...r,$kind:Object.keys(r)[0]})))}const aa=mt(_e(),ju(t=>ve(t)),v0(kr)),rr=aa,si=_e(),Wt=mt(un([_e(),mt(zt(),Dt())]),v0(t=>{try{return BigInt(t),BigInt(t)>=0&&BigInt(t)<=18446744073709551615n}catch{return!1}},"Invalid u64")),ws=de({objectId:aa,version:Wt,digest:_e()}),Me=mt(un([de({GasCoin:ot(!0)}),de({Input:mt(zt(),Dt()),type:er(ot("pure"))}),de({Input:mt(zt(),Dt()),type:er(ot("object"))}),de({Result:mt(zt(),Dt())}),de({NestedResult:E0([mt(zt(),Dt()),mt(zt(),Dt())])})]),ju(t=>({...t,$kind:Object.keys(t)[0]}))),BP=de({budget:Ke(Wt),price:Ke(Wt),owner:Ke(aa),payment:Ke(xe(ws))}),qd=un([ot("address"),ot("bool"),ot("u8"),ot("u16"),ot("u32"),ot("u64"),ot("u128"),ot("u256"),de({vector:Gd(()=>qd)}),de({datatype:de({package:_e(),module:_e(),type:_e(),typeParameters:xe(Gd(()=>qd))})}),de({typeParameter:mt(zt(),Dt())})]),CP=de({ref:Ke(un([ot("&"),ot("&mut")])),body:qd}),RP=de({package:rr,module:_e(),function:_e(),typeArguments:xe(_e()),arguments:xe(Me),_argumentTypes:er(Ke(xe(CP)))}),NP=de({name:_e(),inputs:ho(_e(),un([Me,xe(Me)])),data:ho(_e(),zo())}),UP=fi({MoveCall:RP,TransferObjects:de({objects:xe(Me),address:Me}),SplitCoins:de({coin:Me,amounts:xe(Me)}),MergeCoins:de({destination:Me,sources:xe(Me)}),Publish:de({modules:xe(si),dependencies:xe(rr)}),MakeMoveVec:de({type:Ke(_e()),elements:xe(Me)}),Upgrade:de({modules:xe(si),dependencies:xe(rr),package:rr,ticket:Me}),$Intent:NP}),R2=fi({ImmOrOwnedObject:ws,SharedObject:de({objectId:rr,initialSharedVersion:Wt,mutable:ia()}),Receiving:ws}),FP=fi({Object:R2,Pure:de({bytes:si}),UnresolvedPure:de({value:zo()}),UnresolvedObject:de({objectId:rr,version:er(Ke(Wt)),digest:er(Ke(_e())),initialSharedVersion:er(Ke(Wt)),mutable:er(Ke(ia()))})}),bm=fi({Object:R2,Pure:de({bytes:si})}),N2=fi({None:ot(!0),Epoch:Wt}),kc=de({version:ot(2),sender:fo(aa),expiration:fo(N2),gasData:BP,inputs:xe(FP),commands:xe(UP)}),Os={MoveCall(t){const[e,r="",n=""]="target"in t?t.target.split("::"):[t.package,t.module,t.function];return{$kind:"MoveCall",MoveCall:{package:e,module:r,function:n,typeArguments:t.typeArguments??[],arguments:t.arguments??[]}}},TransferObjects(t,e){return{$kind:"TransferObjects",TransferObjects:{objects:t.map(r=>Ve(Me,r)),address:Ve(Me,e)}}},SplitCoins(t,e){return{$kind:"SplitCoins",SplitCoins:{coin:Ve(Me,t),amounts:e.map(r=>Ve(Me,r))}}},MergeCoins(t,e){return{$kind:"MergeCoins",MergeCoins:{destination:Ve(Me,t),sources:e.map(r=>Ve(Me,r))}}},Publish({modules:t,dependencies:e}){return{$kind:"Publish",Publish:{modules:t.map(r=>typeof r=="string"?r:St(new Uint8Array(r))),dependencies:e.map(r=>tn(r))}}},Upgrade({modules:t,dependencies:e,package:r,ticket:n}){return{$kind:"Upgrade",Upgrade:{modules:t.map(s=>typeof s=="string"?s:St(new Uint8Array(s))),dependencies:e.map(s=>tn(s)),package:r,ticket:Ve(Me,n)}}},MakeMoveVec({type:t,elements:e}){return{$kind:"MakeMoveVec",MakeMoveVec:{type:t??null,elements:e.map(r=>Ve(Me,r))}}},Intent({name:t,inputs:e={},data:r={}}){return{$kind:"$Intent",$Intent:{name:t,inputs:Object.fromEntries(Object.entries(e).map(([n,s])=>[n,Array.isArray(s)?s.map(i=>Ve(Me,i)):Ve(Me,s)])),data:r}}}},MP=/^vector<(.+)>$/,$P=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;class Tr{static parseFromStr(e,r=!1){if(e==="address")return{address:null};if(e==="bool")return{bool:null};if(e==="u8")return{u8:null};if(e==="u16")return{u16:null};if(e==="u32")return{u32:null};if(e==="u64")return{u64:null};if(e==="u128")return{u128:null};if(e==="u256")return{u256:null};if(e==="signer")return{signer:null};const n=e.match(MP);if(n)return{vector:Tr.parseFromStr(n[1],r)};const s=e.match($P);if(s)return{struct:{address:r?ve(s[1]):s[1],module:s[2],name:s[3],typeParams:s[5]===void 0?[]:Tr.parseStructTypeArgs(s[5],r)}};throw new Error(`Encountered unexpected token when parsing type args for ${e}`)}static parseStructTypeArgs(e,r=!1){return g2(e).map(n=>Tr.parseFromStr(n,r))}static tagToString(e){if("bool"in e)return"bool";if("u8"in e)return"u8";if("u16"in e)return"u16";if("u32"in e)return"u32";if("u64"in e)return"u64";if("u128"in e)return"u128";if("u256"in e)return"u256";if("address"in e)return"address";if("signer"in e)return"signer";if("vector"in e)return`vector<${Tr.tagToString(e.vector)}>`;if("struct"in e){const r=e.struct,n=r.typeParams.map(Tr.tagToString).join(", ");return`${r.address}::${r.module}::${r.name}${n?`<${n}>`:""}`}throw new Error("Invalid TypeTag")}}function jP(t){return P.u64({name:"unsafe_u64",...t}).transform({input:e=>e,output:e=>Number(e)})}function HP(t){return P.enum("Option",{None:null,Some:t})}const $e=P.bytes(Lu).transform({validate:t=>{const e=typeof t=="string"?t:Xi(t);if(!e||!kr(ve(e)))throw new Error(`Invalid Sui address ${e}`)},input:t=>typeof t=="string"?y2(ve(t)):t,output:t=>ve(Xi(t))}),Or=P.byteVector().transform({name:"ObjectDigest",input:t=>lo(t),output:t=>Mu(new Uint8Array(t)),validate:t=>{if(lo(t).length!==32)throw new Error("ObjectDigest must be 32 bytes")}}),pr=P.struct("SuiObjectRef",{objectId:$e,version:P.u64(),digest:Or}),U2=P.struct("SharedObjectRef",{objectId:$e,initialSharedVersion:P.u64(),mutable:P.bool()}),F2=P.enum("ObjectArg",{ImmOrOwnedObject:pr,SharedObject:U2,Receiving:pr}),Ms=P.enum("Owner",{AddressOwner:$e,ObjectOwner:$e,Shared:P.struct("Shared",{initialSharedVersion:P.u64()}),Immutable:null,ConsensusAddressOwner:P.struct("ConsensusAddressOwner",{owner:$e,startVersion:P.u64()})}),M2=P.enum("CallArg",{Pure:P.struct("Pure",{bytes:P.byteVector().transform({input:t=>typeof t=="string"?tr(t):t,output:t=>St(new Uint8Array(t))})}),Object:F2}),A0=P.enum("TypeTag",{bool:null,u8:null,u64:null,u128:null,address:null,signer:null,vector:P.lazy(()=>A0),struct:P.lazy(()=>z2),u16:null,u32:null,u256:null}),S0=A0.transform({input:t=>typeof t=="string"?Tr.parseFromStr(t,!0):t,output:t=>Tr.tagToString(t)}),Zr=P.enum("Argument",{GasCoin:null,Input:P.u16(),Result:P.u16(),NestedResult:P.tuple([P.u16(),P.u16()])}),$2=P.struct("ProgrammableMoveCall",{package:$e,module:P.string(),function:P.string(),typeArguments:P.vector(S0),arguments:P.vector(Zr)}),j2=P.enum("Command",{MoveCall:$2,TransferObjects:P.struct("TransferObjects",{objects:P.vector(Zr),address:Zr}),SplitCoins:P.struct("SplitCoins",{coin:Zr,amounts:P.vector(Zr)}),MergeCoins:P.struct("MergeCoins",{destination:Zr,sources:P.vector(Zr)}),Publish:P.struct("Publish",{modules:P.vector(P.byteVector().transform({input:t=>typeof t=="string"?tr(t):t,output:t=>St(new Uint8Array(t))})),dependencies:P.vector($e)}),MakeMoveVec:P.struct("MakeMoveVec",{type:HP(S0).transform({input:t=>t===null?{None:!0}:{Some:t},output:t=>t.Some??null}),elements:P.vector(Zr)}),Upgrade:P.struct("Upgrade",{modules:P.vector(P.byteVector().transform({input:t=>typeof t=="string"?tr(t):t,output:t=>St(new Uint8Array(t))})),dependencies:P.vector($e),package:$e,ticket:Zr})}),H2=P.struct("ProgrammableTransaction",{inputs:P.vector(M2),commands:P.vector(j2)}),L2=P.enum("TransactionKind",{ProgrammableTransaction:H2,ChangeEpoch:null,Genesis:null,ConsensusCommitPrologue:null}),D2=P.enum("TransactionExpiration",{None:null,Epoch:jP()}),z2=P.struct("StructTag",{address:$e,module:P.string(),name:P.string(),typeParams:P.vector(A0)}),V2=P.struct("GasData",{payment:P.vector(pr),owner:$e,price:P.u64(),budget:P.u64()}),G2=P.struct("TransactionDataV1",{kind:L2,sender:$e,gasData:V2,expiration:D2}),q2=P.enum("TransactionData",{V1:G2}),W2=P.enum("IntentScope",{TransactionData:null,TransactionEffects:null,CheckpointSummary:null,PersonalMessage:null}),K2=P.enum("IntentVersion",{V0:null}),X2=P.enum("AppId",{Sui:null}),Y2=P.struct("Intent",{scope:W2,version:K2,appId:X2});function J2(t){return P.struct(`IntentMessage<${t.name}>`,{intent:Y2,value:t})}const Z2=P.enum("CompressedSignature",{ED25519:P.bytes(64),Secp256k1:P.bytes(64),Secp256r1:P.bytes(64),ZkLogin:P.byteVector(),Passkey:P.byteVector()}),Q2=P.enum("PublicKey",{ED25519:P.bytes(32),Secp256k1:P.bytes(33),Secp256r1:P.bytes(33),ZkLogin:P.byteVector(),Passkey:P.bytes(33)}),e6=P.struct("MultiSigPkMap",{pubKey:Q2,weight:P.u8()}),t6=P.struct("MultiSigPublicKey",{pk_map:P.vector(e6),threshold:P.u16()}),LP=P.struct("MultiSig",{sigs:P.vector(Z2),bitmap:P.u16(),multisig_pk:t6}),DP=P.byteVector().transform({input:t=>typeof t=="string"?tr(t):t,output:t=>St(new Uint8Array(t))}),r6=P.struct("SenderSignedTransaction",{intentMessage:J2(q2),txSignatures:P.vector(DP)}),zP=P.vector(r6,{name:"SenderSignedData"}),VP=P.struct("PasskeyAuthenticator",{authenticatorData:P.byteVector(),clientDataJson:P.string(),userSignature:P.byteVector()}),GP=P.enum("PackageUpgradeError",{UnableToFetchPackage:P.struct("UnableToFetchPackage",{packageId:$e}),NotAPackage:P.struct("NotAPackage",{objectId:$e}),IncompatibleUpgrade:null,DigestDoesNotMatch:P.struct("DigestDoesNotMatch",{digest:P.byteVector()}),UnknownUpgradePolicy:P.struct("UnknownUpgradePolicy",{policy:P.u8()}),PackageIDDoesNotMatch:P.struct("PackageIDDoesNotMatch",{packageId:$e,ticketId:$e})}),qP=P.struct("ModuleId",{address:$e,name:P.string()}),gm=P.struct("MoveLocation",{module:qP,function:P.u16(),instruction:P.u16(),functionName:P.option(P.string())}),WP=P.enum("CommandArgumentError",{TypeMismatch:null,InvalidBCSBytes:null,InvalidUsageOfPureArg:null,InvalidArgumentToPrivateEntryFunction:null,IndexOutOfBounds:P.struct("IndexOutOfBounds",{idx:P.u16()}),SecondaryIndexOutOfBounds:P.struct("SecondaryIndexOutOfBounds",{resultIdx:P.u16(),secondaryIdx:P.u16()}),InvalidResultArity:P.struct("InvalidResultArity",{resultIdx:P.u16()}),InvalidGasCoinUsage:null,InvalidValueUsage:null,InvalidObjectByValue:null,InvalidObjectByMutRef:null,SharedObjectOperationNotAllowed:null}),KP=P.enum("TypeArgumentError",{TypeNotFound:null,ConstraintNotSatisfied:null}),XP=P.enum("ExecutionFailureStatus",{InsufficientGas:null,InvalidGasObject:null,InvariantViolation:null,FeatureNotYetSupported:null,MoveObjectTooBig:P.struct("MoveObjectTooBig",{objectSize:P.u64(),maxObjectSize:P.u64()}),MovePackageTooBig:P.struct("MovePackageTooBig",{objectSize:P.u64(),maxObjectSize:P.u64()}),CircularObjectOwnership:P.struct("CircularObjectOwnership",{object:$e}),InsufficientCoinBalance:null,CoinBalanceOverflow:null,PublishErrorNonZeroAddress:null,SuiMoveVerificationError:null,MovePrimitiveRuntimeError:P.option(gm),MoveAbort:P.tuple([gm,P.u64()]),VMVerificationOrDeserializationError:null,VMInvariantViolation:null,FunctionNotFound:null,ArityMismatch:null,TypeArityMismatch:null,NonEntryFunctionInvoked:null,CommandArgumentError:P.struct("CommandArgumentError",{argIdx:P.u16(),kind:WP}),TypeArgumentError:P.struct("TypeArgumentError",{argumentIdx:P.u16(),kind:KP}),UnusedValueWithoutDrop:P.struct("UnusedValueWithoutDrop",{resultIdx:P.u16(),secondaryIdx:P.u16()}),InvalidPublicFunctionReturnType:P.struct("InvalidPublicFunctionReturnType",{idx:P.u16()}),InvalidTransferObject:null,EffectsTooLarge:P.struct("EffectsTooLarge",{currentSize:P.u64(),maxSize:P.u64()}),PublishUpgradeMissingDependency:null,PublishUpgradeDependencyDowngrade:null,PackageUpgradeError:P.struct("PackageUpgradeError",{upgradeError:GP}),WrittenObjectsTooLarge:P.struct("WrittenObjectsTooLarge",{currentSize:P.u64(),maxSize:P.u64()}),CertificateDenied:null,SuiMoveVerificationTimedout:null,SharedObjectOperationNotAllowed:null,InputObjectDeleted:null,ExecutionCancelledDueToSharedObjectCongestion:P.struct("ExecutionCancelledDueToSharedObjectCongestion",{congestedObjects:P.vector($e)}),AddressDeniedForCoin:P.struct("AddressDeniedForCoin",{address:$e,coinType:P.string()}),CoinTypeGlobalPause:P.struct("CoinTypeGlobalPause",{coinType:P.string()}),ExecutionCancelledDueToRandomnessUnavailable:null}),n6=P.enum("ExecutionStatus",{Success:null,Failed:P.struct("ExecutionFailed",{error:XP,command:P.option(P.u64())})}),s6=P.struct("GasCostSummary",{computationCost:P.u64(),storageCost:P.u64(),storageRebate:P.u64(),nonRefundableStorageFee:P.u64()}),YP=P.struct("TransactionEffectsV1",{status:n6,executedEpoch:P.u64(),gasUsed:s6,modifiedAtVersions:P.vector(P.tuple([$e,P.u64()])),sharedObjects:P.vector(pr),transactionDigest:Or,created:P.vector(P.tuple([pr,Ms])),mutated:P.vector(P.tuple([pr,Ms])),unwrapped:P.vector(P.tuple([pr,Ms])),deleted:P.vector(pr),unwrappedThenDeleted:P.vector(pr),wrapped:P.vector(pr),gasObject:P.tuple([pr,Ms]),eventsDigest:P.option(Or),dependencies:P.vector(Or)}),x0=P.tuple([P.u64(),Or]),JP=P.enum("ObjectIn",{NotExist:null,Exist:P.tuple([x0,Ms])}),ZP=P.enum("ObjectOut",{NotExist:null,ObjectWrite:P.tuple([Or,Ms]),PackageWrite:x0}),QP=P.enum("IDOperation",{None:null,Created:null,Deleted:null}),eO=P.struct("EffectsObjectChange",{inputState:JP,outputState:ZP,idOperation:QP}),tO=P.enum("UnchangedSharedKind",{ReadOnlyRoot:x0,MutateDeleted:P.u64(),ReadDeleted:P.u64(),Cancelled:P.u64(),PerEpochConfig:null}),rO=P.struct("TransactionEffectsV2",{status:n6,executedEpoch:P.u64(),gasUsed:s6,transactionDigest:Or,gasObjectIndex:P.option(P.u32()),eventsDigest:P.option(Or),dependencies:P.vector(Or),lamportVersion:P.u64(),changedObjects:P.vector(P.tuple([$e,eO])),unchangedSharedObjects:P.vector(P.tuple([$e,tO])),auxDataDigest:P.option(Or)}),nO=P.enum("TransactionEffects",{V1:YP,V2:rO});function Ca(t){switch(t){case"u8":return P.u8();case"u16":return P.u16();case"u32":return P.u32();case"u64":return P.u64();case"u128":return P.u128();case"u256":return P.u256();case"bool":return P.bool();case"string":return P.string();case"id":case"address":return $e}const e=t.match(/^(vector|option)<(.+)>$/);if(e){const[r,n]=e.slice(1);return r==="vector"?P.vector(Ca(n)):P.option(Ca(n))}throw new Error(`Invalid Pure type name: ${t}`)}const pe={...P,U8:P.u8(),U16:P.u16(),U32:P.u32(),U64:P.u64(),U128:P.u128(),U256:P.u256(),ULEB128:P.uleb128(),Bool:P.bool(),String:P.string(),Address:$e,AppId:X2,Argument:Zr,CallArg:M2,Command:j2,CompressedSignature:Z2,GasData:V2,Intent:Y2,IntentMessage:J2,IntentScope:W2,IntentVersion:K2,MultiSig:LP,MultiSigPkMap:e6,MultiSigPublicKey:t6,ObjectArg:F2,ObjectDigest:Or,Owner:Ms,PasskeyAuthenticator:VP,ProgrammableMoveCall:$2,ProgrammableTransaction:H2,PublicKey:Q2,SenderSignedData:zP,SenderSignedTransaction:r6,SharedObjectRef:U2,StructTag:z2,SuiObjectRef:pr,TransactionData:q2,TransactionDataV1:G2,TransactionEffects:nO,TransactionExpiration:D2,TransactionKind:L2,TypeTag:S0},wm=de({digest:_e(),objectId:_e(),version:un([mt(zt(),Dt()),_e(),P2()])}),sO=fi({ImmOrOwned:wm,Shared:de({objectId:rr,initialSharedVersion:Wt,mutable:ia()}),Receiving:wm}),vm=fi({Object:sO,Pure:xe(mt(zt(),Dt()))});function Em(t){var r;const e=t.inputs.map((n,s)=>{if(n.Object)return{kind:"Input",index:s,value:{Object:n.Object.ImmOrOwnedObject?{ImmOrOwned:n.Object.ImmOrOwnedObject}:n.Object.Receiving?{Receiving:{digest:n.Object.Receiving.digest,version:n.Object.Receiving.version,objectId:n.Object.Receiving.objectId}}:{Shared:{mutable:n.Object.SharedObject.mutable,initialSharedVersion:n.Object.SharedObject.initialSharedVersion,objectId:n.Object.SharedObject.objectId}}},type:"object"};if(n.Pure)return{kind:"Input",index:s,value:{Pure:Array.from(tr(n.Pure.bytes))},type:"pure"};if(n.UnresolvedPure)return{kind:"Input",type:"pure",index:s,value:n.UnresolvedPure.value};if(n.UnresolvedObject)return{kind:"Input",type:"object",index:s,value:n.UnresolvedObject.objectId};throw new Error("Invalid input")});return{version:1,sender:t.sender??void 0,expiration:((r=t.expiration)==null?void 0:r.$kind)==="Epoch"?{Epoch:Number(t.expiration.Epoch)}:t.expiration?{None:!0}:null,gasConfig:{owner:t.gasData.owner??void 0,budget:t.gasData.budget??void 0,price:t.gasData.price??void 0,payment:t.gasData.payment??void 0},inputs:e,transactions:t.commands.map(n=>{if(n.MakeMoveVec)return{kind:"MakeMoveVec",type:n.MakeMoveVec.type===null?{None:!0}:{Some:Tr.parseFromStr(n.MakeMoveVec.type)},objects:n.MakeMoveVec.elements.map(s=>gn(s,e))};if(n.MergeCoins)return{kind:"MergeCoins",destination:gn(n.MergeCoins.destination,e),sources:n.MergeCoins.sources.map(s=>gn(s,e))};if(n.MoveCall)return{kind:"MoveCall",target:`${n.MoveCall.package}::${n.MoveCall.module}::${n.MoveCall.function}`,typeArguments:n.MoveCall.typeArguments,arguments:n.MoveCall.arguments.map(s=>gn(s,e))};if(n.Publish)return{kind:"Publish",modules:n.Publish.modules.map(s=>Array.from(tr(s))),dependencies:n.Publish.dependencies};if(n.SplitCoins)return{kind:"SplitCoins",coin:gn(n.SplitCoins.coin,e),amounts:n.SplitCoins.amounts.map(s=>gn(s,e))};if(n.TransferObjects)return{kind:"TransferObjects",objects:n.TransferObjects.objects.map(s=>gn(s,e)),address:gn(n.TransferObjects.address,e)};if(n.Upgrade)return{kind:"Upgrade",modules:n.Upgrade.modules.map(s=>Array.from(tr(s))),dependencies:n.Upgrade.dependencies,packageId:n.Upgrade.package,ticket:gn(n.Upgrade.ticket,e)};throw new Error(`Unknown transaction ${Object.keys(n)}`)})}}function gn(t,e){if(t.$kind==="GasCoin")return{kind:"GasCoin"};if(t.$kind==="Result")return{kind:"Result",index:t.Result};if(t.$kind==="NestedResult")return{kind:"NestedResult",index:t.NestedResult[0],resultIndex:t.NestedResult[1]};if(t.$kind==="Input")return e[t.Input];throw new Error(`Invalid argument ${Object.keys(t)}`)}function iO(t){var e,r,n;return Ve(kc,{version:2,sender:t.sender??null,expiration:t.expiration?"Epoch"in t.expiration?{Epoch:t.expiration.Epoch}:{None:!0}:null,gasData:{owner:t.gasConfig.owner??null,budget:((e=t.gasConfig.budget)==null?void 0:e.toString())??null,price:((r=t.gasConfig.price)==null?void 0:r.toString())??null,payment:((n=t.gasConfig.payment)==null?void 0:n.map(s=>({digest:s.digest,objectId:s.objectId,version:s.version.toString()})))??null},inputs:t.inputs.map(s=>{if(s.kind==="Input"){if(Vd(vm,s.value)){const i=Ve(vm,s.value);if(i.Object){if(i.Object.ImmOrOwned)return{Object:{ImmOrOwnedObject:{objectId:i.Object.ImmOrOwned.objectId,version:String(i.Object.ImmOrOwned.version),digest:i.Object.ImmOrOwned.digest}}};if(i.Object.Shared)return{Object:{SharedObject:{mutable:i.Object.Shared.mutable??null,initialSharedVersion:i.Object.Shared.initialSharedVersion,objectId:i.Object.Shared.objectId}}};if(i.Object.Receiving)return{Object:{Receiving:{digest:i.Object.Receiving.digest,version:String(i.Object.Receiving.version),objectId:i.Object.Receiving.objectId}}};throw new Error("Invalid object input")}return{Pure:{bytes:St(new Uint8Array(i.Pure))}}}return s.type==="object"?{UnresolvedObject:{objectId:s.value}}:{UnresolvedPure:{value:s.value}}}throw new Error("Invalid input")}),commands:t.transactions.map(s=>{switch(s.kind){case"MakeMoveVec":return{MakeMoveVec:{type:"Some"in s.type?Tr.tagToString(s.type.Some):null,elements:s.objects.map(i=>wn(i))}};case"MergeCoins":return{MergeCoins:{destination:wn(s.destination),sources:s.sources.map(i=>wn(i))}};case"MoveCall":{const[i,a,o]=s.target.split("::");return{MoveCall:{package:i,module:a,function:o,typeArguments:s.typeArguments,arguments:s.arguments.map(c=>wn(c))}}}case"Publish":return{Publish:{modules:s.modules.map(i=>St(Uint8Array.from(i))),dependencies:s.dependencies}};case"SplitCoins":return{SplitCoins:{coin:wn(s.coin),amounts:s.amounts.map(i=>wn(i))}};case"TransferObjects":return{TransferObjects:{objects:s.objects.map(i=>wn(i)),address:wn(s.address)}};case"Upgrade":return{Upgrade:{modules:s.modules.map(i=>St(Uint8Array.from(i))),dependencies:s.dependencies,package:s.packageId,ticket:wn(s.ticket)}}}throw new Error(`Unknown transaction ${Object.keys(s)}`)})})}function wn(t){switch(t.kind){case"GasCoin":return{GasCoin:!0};case"Result":return{Result:t.index};case"NestedResult":return{NestedResult:[t.index,t.resultIndex]};case"Input":return{Input:t.index}}}function Vo(t){return un(Object.entries(t).map(([e,r])=>de({[e]:r})))}const Er=Vo({GasCoin:ot(!0),Input:mt(zt(),Dt()),Result:mt(zt(),Dt()),NestedResult:E0([mt(zt(),Dt()),mt(zt(),Dt())])}),aO=de({budget:Ke(Wt),price:Ke(Wt),owner:Ke(aa),payment:Ke(xe(ws))}),oO=de({package:rr,module:_e(),function:_e(),typeArguments:xe(_e()),arguments:xe(Er)}),cO=de({name:_e(),inputs:ho(_e(),un([Er,xe(Er)])),data:ho(_e(),zo())}),uO=Vo({MoveCall:oO,TransferObjects:de({objects:xe(Er),address:Er}),SplitCoins:de({coin:Er,amounts:xe(Er)}),MergeCoins:de({destination:Er,sources:xe(Er)}),Publish:de({modules:xe(si),dependencies:xe(rr)}),MakeMoveVec:de({type:Ke(_e()),elements:xe(Er)}),Upgrade:de({modules:xe(si),dependencies:xe(rr),package:rr,ticket:Er}),$Intent:cO}),lO=Vo({ImmOrOwnedObject:ws,SharedObject:de({objectId:rr,initialSharedVersion:Wt,mutable:ia()}),Receiving:ws}),fO=Vo({Object:lO,Pure:de({bytes:si}),UnresolvedPure:de({value:zo()}),UnresolvedObject:de({objectId:rr,version:er(Ke(Wt)),digest:er(Ke(_e())),initialSharedVersion:er(Ke(Wt)),mutable:er(Ke(ia()))})}),dO=Vo({None:ot(!0),Epoch:Wt}),hO=de({version:ot(2),sender:fo(aa),expiration:fo(dO),gasData:aO,inputs:xe(fO),commands:xe(uO),digest:er(Ke(_e()))});function pO(t){return{$kind:"Pure",Pure:{bytes:t instanceof Uint8Array?St(t):t.toBase64()}}}const Br={Pure:pO,ObjectRef({objectId:t,digest:e,version:r}){return{$kind:"Object",Object:{$kind:"ImmOrOwnedObject",ImmOrOwnedObject:{digest:e,version:r,objectId:ve(t)}}}},SharedObjectRef({objectId:t,mutable:e,initialSharedVersion:r}){return{$kind:"Object",Object:{$kind:"SharedObject",SharedObject:{mutable:e,initialSharedVersion:r,objectId:ve(t)}}}},ReceivingRef({objectId:t,digest:e,version:r}){return{$kind:"Object",Object:{$kind:"Receiving",Receiving:{digest:e,version:r,objectId:ve(t)}}}}};BigInt(1e9);const yO="0x1",i6="0x2",mO=tn("0x6"),bO=`${i6}::sui::SUI`;tn("0x5");tn("0x8");const gO=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),it=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),te=new Uint32Array(32);function Jn(t,e,r,n,s,i){const a=s[i],o=s[i+1];let c=te[2*t],u=te[2*t+1],l=te[2*e],f=te[2*e+1],p=te[2*r],d=te[2*r+1],b=te[2*n],g=te[2*n+1],A=lg(c,l,a);u=fg(A,u,f,o),c=A|0,{Dh:g,Dl:b}={Dh:g^u,Dl:b^c},{Dh:g,Dl:b}={Dh:gA(g,b),Dl:wA(g)},{h:d,l:p}=ug(d,p,g,b),{Bh:f,Bl:l}={Bh:f^d,Bl:l^p},{Bh:f,Bl:l}={Bh:og(f,l,24),Bl:cg(f,l,24)},te[2*t]=c,te[2*t+1]=u,te[2*e]=l,te[2*e+1]=f,te[2*r]=p,te[2*r+1]=d,te[2*n]=b,te[2*n+1]=g}function Zn(t,e,r,n,s,i){const a=s[i],o=s[i+1];let c=te[2*t],u=te[2*t+1],l=te[2*e],f=te[2*e+1],p=te[2*r],d=te[2*r+1],b=te[2*n],g=te[2*n+1],A=lg(c,l,a);u=fg(A,u,f,o),c=A|0,{Dh:g,Dl:b}={Dh:g^u,Dl:b^c},{Dh:g,Dl:b}={Dh:og(g,b,16),Dl:cg(g,b,16)},{h:d,l:p}=ug(d,p,g,b),{Bh:f,Bl:l}={Bh:f^d,Bl:l^p},{Bh:f,Bl:l}={Bh:mA(f,l,63),Bl:bA(f,l,63)},te[2*t]=c,te[2*t+1]=u,te[2*e]=l,te[2*e+1]=f,te[2*r]=p,te[2*r+1]=d,te[2*n]=b,te[2*n+1]=g}function wO(t,e={},r,n,s){if(ps(r),t<0||t>r)throw new Error("outputLen bigger than keyLen");const{key:i,salt:a,personalization:o}=e;if(i!==void 0&&(i.length<1||i.length>r))throw new Error("key length must be undefined or 1.."+r);if(a!==void 0&&a.length!==n)throw new Error("salt must be undefined or "+n);if(o!==void 0&&o.length!==s)throw new Error("personalization must be undefined or "+s)}class vO extends cu{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,ps(e),ps(r),this.blockLen=e,this.outputLen=r,this.buffer=new Uint8Array(e),this.buffer32=ja(this.buffer)}update(e){ms(this),e=Pn(e),ys(e);const{blockLen:r,buffer:n,buffer32:s}=this,i=e.length,a=e.byteOffset,o=e.buffer;for(let c=0;c<i;){this.pos===r&&(rs(s),this.compress(s,0,!1),rs(s),this.pos=0);const u=Math.min(r-this.pos,i-c),l=a+c;if(u===r&&!(l%4)&&c+u<i){const f=new Uint32Array(o,l,Math.floor((i-c)/4));rs(f);for(let p=0;c+r<i;p+=s.length,c+=r)this.length+=r,this.compress(f,p,!1);rs(f);continue}n.set(e.subarray(c,c+u),this.pos),this.pos+=u,this.length+=u,c+=u}return this}digestInto(e){ms(this),bh(e,this);const{pos:r,buffer32:n}=this;this.finished=!0,Nn(this.buffer.subarray(r)),rs(n),this.compress(n,0,!0),rs(n);const s=ja(e);this.get().forEach((i,a)=>s[a]=En(i))}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){const{buffer:r,length:n,finished:s,destroyed:i,outputLen:a,pos:o}=this;return e||(e=new this.constructor({dkLen:a})),e.set(...this.get()),e.buffer.set(r),e.destroyed=i,e.finished=s,e.length=n,e.pos=o,e.outputLen=a,e}clone(){return this._cloneInto()}}class EO extends vO{constructor(e={}){const r=e.dkLen===void 0?64:e.dkLen;super(128,r),this.v0l=it[0]|0,this.v0h=it[1]|0,this.v1l=it[2]|0,this.v1h=it[3]|0,this.v2l=it[4]|0,this.v2h=it[5]|0,this.v3l=it[6]|0,this.v3h=it[7]|0,this.v4l=it[8]|0,this.v4h=it[9]|0,this.v5l=it[10]|0,this.v5h=it[11]|0,this.v6l=it[12]|0,this.v6h=it[13]|0,this.v7l=it[14]|0,this.v7h=it[15]|0,wO(r,e,64,16,16);let{key:n,personalization:s,salt:i}=e,a=0;if(n!==void 0&&(n=Pn(n),a=n.length),this.v0l^=this.outputLen|a<<8|65536|1<<24,i!==void 0){i=Pn(i);const o=ja(i);this.v4l^=En(o[0]),this.v4h^=En(o[1]),this.v5l^=En(o[2]),this.v5h^=En(o[3])}if(s!==void 0){s=Pn(s);const o=ja(s);this.v6l^=En(o[0]),this.v6h^=En(o[1]),this.v7l^=En(o[2]),this.v7h^=En(o[3])}if(n!==void 0){const o=new Uint8Array(this.blockLen);o.set(n),this.update(o)}}get(){let{v0l:e,v0h:r,v1l:n,v1h:s,v2l:i,v2h:a,v3l:o,v3h:c,v4l:u,v4h:l,v5l:f,v5h:p,v6l:d,v6h:b,v7l:g,v7h:A}=this;return[e,r,n,s,i,a,o,c,u,l,f,p,d,b,g,A]}set(e,r,n,s,i,a,o,c,u,l,f,p,d,b,g,A){this.v0l=e|0,this.v0h=r|0,this.v1l=n|0,this.v1h=s|0,this.v2l=i|0,this.v2h=a|0,this.v3l=o|0,this.v3h=c|0,this.v4l=u|0,this.v4h=l|0,this.v5l=f|0,this.v5h=p|0,this.v6l=d|0,this.v6h=b|0,this.v7l=g|0,this.v7h=A|0}compress(e,r,n){this.get().forEach((c,u)=>te[u]=c),te.set(it,16);let{h:s,l:i}=ag(BigInt(this.length));te[24]=it[8]^i,te[25]=it[9]^s,n&&(te[28]=~te[28],te[29]=~te[29]);let a=0;const o=gO;for(let c=0;c<12;c++)Jn(0,4,8,12,e,r+2*o[a++]),Zn(0,4,8,12,e,r+2*o[a++]),Jn(1,5,9,13,e,r+2*o[a++]),Zn(1,5,9,13,e,r+2*o[a++]),Jn(2,6,10,14,e,r+2*o[a++]),Zn(2,6,10,14,e,r+2*o[a++]),Jn(3,7,11,15,e,r+2*o[a++]),Zn(3,7,11,15,e,r+2*o[a++]),Jn(0,5,10,15,e,r+2*o[a++]),Zn(0,5,10,15,e,r+2*o[a++]),Jn(1,6,11,12,e,r+2*o[a++]),Zn(1,6,11,12,e,r+2*o[a++]),Jn(2,7,8,13,e,r+2*o[a++]),Zn(2,7,8,13,e,r+2*o[a++]),Jn(3,4,9,14,e,r+2*o[a++]),Zn(3,4,9,14,e,r+2*o[a++]);this.v0l^=te[0]^te[16],this.v0h^=te[1]^te[17],this.v1l^=te[2]^te[18],this.v1h^=te[3]^te[19],this.v2l^=te[4]^te[20],this.v2h^=te[5]^te[21],this.v3l^=te[6]^te[22],this.v3h^=te[7]^te[23],this.v4l^=te[8]^te[24],this.v4h^=te[9]^te[25],this.v5l^=te[10]^te[26],this.v5h^=te[11]^te[27],this.v6l^=te[12]^te[28],this.v6h^=te[13]^te[29],this.v7l^=te[14]^te[30],this.v7h^=te[15]^te[31],Nn(te)}destroy(){this.destroyed=!0,Nn(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const AO=PA(t=>new EO(t)),a6=AO;function SO(t,e,r){const n=pe.Address.serialize(t).toBytes(),s=pe.TypeTag.serialize(e).toBytes(),i=pe.u64().serialize(r.length).toBytes(),a=a6.create({dkLen:32});return a.update(new Uint8Array([240])),a.update(n),a.update(i),a.update(r),a.update(s),`0x${Xi(a.digest().slice(0,32))}`}const xO="object",kO="ID",TO="ascii",_O="String",IO="string",PO="String",OO="option",BO="Option";function CO(t){const e=typeof t.body=="object"&&"datatype"in t.body?t.body.datatype:null;return!!e&&ve(e.package)===ve("0x2")&&e.module==="tx_context"&&e.type==="TxContext"}function Wd(t){if(typeof t=="string")switch(t){case"address":return pe.Address;case"bool":return pe.Bool;case"u8":return pe.U8;case"u16":return pe.U16;case"u32":return pe.U32;case"u64":return pe.U64;case"u128":return pe.U128;case"u256":return pe.U256;default:throw new Error(`Unknown type signature ${t}`)}if("vector"in t){if(t.vector==="u8")return pe.byteVector().transform({input:r=>typeof r=="string"?new TextEncoder().encode(r):r,output:r=>r});const e=Wd(t.vector);return e?pe.vector(e):null}if("datatype"in t){const e=ve(t.datatype.package);if(e===ve(yO)){if(t.datatype.module===TO&&t.datatype.type===_O||t.datatype.module===IO&&t.datatype.type===PO)return pe.String;if(t.datatype.module===OO&&t.datatype.type===BO){const r=Wd(t.datatype.typeParameters[0]);return r?pe.vector(r):null}}if(e===ve(i6)&&t.datatype.module===xO&&t.datatype.type===kO)return pe.Address}return null}function RO(t){return typeof t=="object"&&"Reference"in t?{ref:"&",body:Ra(t.Reference)}:typeof t=="object"&&"MutableReference"in t?{ref:"&mut",body:Ra(t.MutableReference)}:{ref:null,body:Ra(t)}}function Ra(t){if(typeof t=="string")switch(t){case"Address":return"address";case"Bool":return"bool";case"U8":return"u8";case"U16":return"u16";case"U32":return"u32";case"U64":return"u64";case"U128":return"u128";case"U256":return"u256";default:throw new Error(`Unexpected type ${t}`)}if("Vector"in t)return{vector:Ra(t.Vector)};if("Struct"in t)return{datatype:{package:t.Struct.address,module:t.Struct.module,type:t.Struct.name,typeParameters:t.Struct.typeArguments.map(Ra)}};if("TypeParameter"in t)return{typeParameter:t.TypeParameter};throw new Error(`Unexpected type ${JSON.stringify(t)}`)}const NO=50,UO=1000n,FO=5e10;function o6(t){return async function(r,n,s){return await LO(r,t),await HO(r,t),n.onlyTransactionKind||(await MO(r,t),await $O(r,t),await jO(r,t)),await s()}}async function MO(t,e){t.gasConfig.price||(t.gasConfig.price=String(await e.getReferenceGasPrice()))}async function $O(t,e){if(t.gasConfig.budget)return;const r=await e.dryRunTransactionBlock({transactionBlock:t.build({overrides:{gasData:{budget:String(FO),payment:[]}}})});if(r.effects.status.status!=="success")throw new Error(`Dry run failed, could not automatically determine a budget: ${r.effects.status.error}`,{cause:r});const n=UO*BigInt(t.gasConfig.price||1n),s=BigInt(r.effects.gasUsed.computationCost)+n,i=s+BigInt(r.effects.gasUsed.storageCost)-BigInt(r.effects.gasUsed.storageRebate);t.gasConfig.budget=String(i>s?i:s)}async function jO(t,e){if(!t.gasConfig.payment){const n=(await e.getCoins({owner:t.gasConfig.owner||t.sender,coinType:bO})).data.filter(s=>!t.inputs.find(a=>{var o;return(o=a.Object)!=null&&o.ImmOrOwnedObject?s.coinObjectId===a.Object.ImmOrOwnedObject.objectId:!1})).map(s=>({objectId:s.coinObjectId,digest:s.digest,version:s.version}));if(!n.length)throw new Error("No valid gas coins found for the transaction.");t.gasConfig.payment=n.map(s=>Ve(ws,s))}}async function HO(t,e){const r=t.inputs.filter(l=>{var f;return l.UnresolvedObject&&!(l.UnresolvedObject.version||(f=l.UnresolvedObject)!=null&&f.initialSharedVersion)}),n=[...new Set(r.map(l=>tn(l.UnresolvedObject.objectId)))],s=n.length?$u(n,NO):[],i=(await Promise.all(s.map(l=>e.multiGetObjects({ids:l,options:{showOwner:!0}})))).flat(),a=new Map(n.map((l,f)=>[l,i[f]])),o=Array.from(a).filter(([l,f])=>f.error).map(([l,f])=>JSON.stringify(f.error));if(o.length)throw new Error(`The following input objects are invalid: ${o.join(", ")}`);const c=i.map(l=>{if(l.error||!l.data)throw new Error(`Failed to fetch object: ${l.error}`);const f=l.data.owner,p=f&&typeof f=="object"?"Shared"in f?f.Shared.initial_shared_version:"ConsensusAddressOwner"in f?f.ConsensusAddressOwner.start_version:null:null;return{objectId:l.data.objectId,digest:l.data.digest,version:l.data.version,initialSharedVersion:p}}),u=new Map(n.map((l,f)=>[l,c[f]]));for(const[l,f]of t.inputs.entries()){if(!f.UnresolvedObject)continue;let p;const d=ve(f.UnresolvedObject.objectId),b=u.get(d);f.UnresolvedObject.initialSharedVersion??(b==null?void 0:b.initialSharedVersion)?p=Br.SharedObjectRef({objectId:d,initialSharedVersion:f.UnresolvedObject.initialSharedVersion||(b==null?void 0:b.initialSharedVersion),mutable:f.UnresolvedObject.mutable||DO(t,l)}):zO(t,l)&&(p=Br.ReceivingRef({objectId:d,digest:f.UnresolvedObject.digest??(b==null?void 0:b.digest),version:f.UnresolvedObject.version??(b==null?void 0:b.version)})),t.inputs[t.inputs.indexOf(f)]=p??Br.ObjectRef({objectId:d,digest:f.UnresolvedObject.digest??(b==null?void 0:b.digest),version:f.UnresolvedObject.version??(b==null?void 0:b.version)})}}async function LO(t,e){const{inputs:r,commands:n}=t,s=[],i=new Set;n.forEach(o=>{if(o.MoveCall){if(o.MoveCall._argumentTypes)return;if(o.MoveCall.arguments.map(l=>l.$kind==="Input"?t.inputs[l.Input]:null).some(l=>(l==null?void 0:l.UnresolvedPure)||(l==null?void 0:l.UnresolvedObject)&&typeof(l==null?void 0:l.UnresolvedObject.mutable)!="boolean")){const l=`${o.MoveCall.package}::${o.MoveCall.module}::${o.MoveCall.function}`;i.add(l),s.push(o.MoveCall)}}});const a=new Map;i.size>0&&await Promise.all([...i].map(async o=>{const[c,u,l]=o.split("::"),f=await e.getNormalizedMoveFunction({package:c,module:u,function:l});a.set(o,f.parameters.map(p=>RO(p)))})),s.length&&await Promise.all(s.map(async o=>{const c=a.get(`${o.package}::${o.module}::${o.function}`);if(!c)return;const l=c.length>0&&CO(c.at(-1))?c.slice(0,c.length-1):c;o._argumentTypes=l})),n.forEach(o=>{if(!o.MoveCall)return;const c=o.MoveCall,u=`${c.package}::${c.module}::${c.function}`,l=c._argumentTypes;if(l){if(l.length!==o.MoveCall.arguments.length)throw new Error(`Incorrect number of arguments for ${u}`);l.forEach((f,p)=>{var T,v;const d=c.arguments[p];if(d.$kind!=="Input")return;const b=r[d.Input];if(!b.UnresolvedPure&&!b.UnresolvedObject)return;const g=((T=b.UnresolvedPure)==null?void 0:T.value)??((v=b.UnresolvedObject)==null?void 0:v.objectId),A=Wd(f.body);if(A){d.type="pure",r[r.indexOf(b)]=Br.Pure(A.serialize(g));return}if(typeof g!="string")throw new Error(`Expect the argument to be an object id string, got ${JSON.stringify(g,null,2)}`);d.type="object";const S=b.UnresolvedPure?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:g}}:b;r[d.Input]=S})}})}function DO(t,e){let r=!1;return t.getInputUses(e,(n,s)=>{if(s.MoveCall&&s.MoveCall._argumentTypes){const i=s.MoveCall.arguments.indexOf(n);r=s.MoveCall._argumentTypes[i].ref!=="&"||r}(s.$kind==="MakeMoveVec"||s.$kind==="MergeCoins"||s.$kind==="SplitCoins"||s.$kind==="TransferObjects")&&(r=!0)}),r}function zO(t,e){let r=!1;return t.getInputUses(e,(n,s)=>{if(s.MoveCall&&s.MoveCall._argumentTypes){const i=s.MoveCall.arguments.indexOf(n);r=VO(s.MoveCall._argumentTypes[i])||r}}),r}function VO(t){return typeof t.body!="object"||!("datatype"in t.body)?!1:t.body.datatype.package==="0x2"&&t.body.datatype.module==="transfer"&&t.body.datatype.type==="Receiving"}function c6(t,e){return!!(t.inputs.some(r=>r.UnresolvedObject||r.UnresolvedPure)||!e.onlyTransactionKind&&(!t.gasConfig.price||!t.gasConfig.budget||!t.gasConfig.payment))}async function GO(t,e,r){var i;if(WO(t),!c6(t,e))return await Am(t),r();const n=qO(e);return(((i=n.core)==null?void 0:i.resolveTransactionPlugin())??o6(n))(t,e,async()=>{await Am(t),await r()})}function Am(t){t.inputs.forEach((e,r)=>{if(e.$kind!=="Object"&&e.$kind!=="Pure")throw new Error(`Input at index ${r} has not been resolved. Expected a Pure or Object input, but found ${JSON.stringify(e)}`)})}function qO(t){if(!t.client)throw new Error("No sui client passed to Transaction#build, but transaction data was not sufficient to build offline.");return t.client}function WO(t){for(const e of t.commands)switch(e.$kind){case"SplitCoins":e.SplitCoins.amounts.forEach(r=>{Sm(r,pe.U64,t)});break;case"TransferObjects":Sm(e.TransferObjects.address,pe.Address,t);break}}function Sm(t,e,r){if(t.$kind!=="Input")return;const n=r.inputs[t.Input];n.$kind==="UnresolvedPure"&&(r.inputs[t.Input]=Br.Pure(e.serialize(n.UnresolvedPure.value)))}function KO(t){function e(r){return t(r)}return e.system=r=>{const n=r==null?void 0:r.mutable;return e(n!==void 0?Br.SharedObjectRef({objectId:"0x5",initialSharedVersion:1,mutable:n}):{$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x5",initialSharedVersion:1}})},e.clock=()=>e(Br.SharedObjectRef({objectId:"0x6",initialSharedVersion:1,mutable:!1})),e.random=()=>e({$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x8",mutable:!1}}),e.denyList=r=>e({$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x403",mutable:r==null?void 0:r.mutable}}),e.option=({type:r,value:n})=>s=>s.moveCall({typeArguments:[r],target:`0x1::option::${n===null?"none":"some"}`,arguments:n===null?[]:[s.object(n)]}),e}function XO(t){function e(r,n){if(typeof r=="string")return t(Ca(r).serialize(n));if(r instanceof Uint8Array||w0(r))return t(r);throw new Error("tx.pure must be called either a bcs type name, or a serialized bcs value")}return e.u8=r=>t(pe.U8.serialize(r)),e.u16=r=>t(pe.U16.serialize(r)),e.u32=r=>t(pe.U32.serialize(r)),e.u64=r=>t(pe.U64.serialize(r)),e.u128=r=>t(pe.U128.serialize(r)),e.u256=r=>t(pe.U256.serialize(r)),e.bool=r=>t(pe.Bool.serialize(r)),e.string=r=>t(pe.String.serialize(r)),e.address=r=>t(pe.Address.serialize(r)),e.id=e.address,e.vector=(r,n)=>t(pe.vector(Ca(r)).serialize(n)),e.option=(r,n)=>t(pe.option(Ca(r)).serialize(n)),e}function YO(t,e){const r=Array.from(`${t}::`).map(s=>s.charCodeAt(0)),n=new Uint8Array(r.length+e.length);return n.set(r),n.set(e,r.length),a6(n,{dkLen:32})}function Gc(t){if(typeof t=="string")return ve(t);if(t.Object)return t.Object.ImmOrOwnedObject?ve(t.Object.ImmOrOwnedObject.objectId):t.Object.Receiving?ve(t.Object.Receiving.objectId):ve(t.Object.SharedObject.objectId);if(t.UnresolvedObject)return ve(t.UnresolvedObject.objectId)}function JO(t,e,r){const n=s=>{switch(s.$kind){case"Input":{const i=e.get(s.Input);if(i===void 0)throw new Error(`Input ${s.Input} not found in input mapping`);return{...s,Input:i}}case"Result":{const i=r.get(s.Result);return i!==void 0?{...s,Result:i}:s}case"NestedResult":{const i=r.get(s.NestedResult[0]);return i!==void 0?{...s,NestedResult:[i,s.NestedResult[1]]}:s}default:return s}};switch(t.$kind){case"MoveCall":t.MoveCall.arguments=t.MoveCall.arguments.map(n);break;case"TransferObjects":t.TransferObjects.objects=t.TransferObjects.objects.map(n),t.TransferObjects.address=n(t.TransferObjects.address);break;case"SplitCoins":t.SplitCoins.coin=n(t.SplitCoins.coin),t.SplitCoins.amounts=t.SplitCoins.amounts.map(n);break;case"MergeCoins":t.MergeCoins.destination=n(t.MergeCoins.destination),t.MergeCoins.sources=t.MergeCoins.sources.map(n);break;case"MakeMoveVec":t.MakeMoveVec.elements=t.MakeMoveVec.elements.map(n);break;case"Upgrade":t.Upgrade.ticket=n(t.Upgrade.ticket);break;case"$Intent":{const s=t.$Intent.inputs;t.$Intent.inputs={};for(const[i,a]of Object.entries(s))t.$Intent.inputs[i]=Array.isArray(a)?a.map(n):n(a);break}}}function xm(t){return ve(t).replace("0x","")}class Lt{constructor(e){this.version=2,this.sender=(e==null?void 0:e.sender)??null,this.expiration=(e==null?void 0:e.expiration)??null,this.inputs=(e==null?void 0:e.inputs)??[],this.commands=(e==null?void 0:e.commands)??[],this.gasData=(e==null?void 0:e.gasData)??{budget:null,price:null,owner:null,payment:null}}static fromKindBytes(e){const n=pe.TransactionKind.parse(e).ProgrammableTransaction;if(!n)throw new Error("Unable to deserialize from bytes.");return Lt.restore({version:2,sender:null,expiration:null,gasData:{budget:null,owner:null,payment:null,price:null},inputs:n.inputs,commands:n.commands})}static fromBytes(e){const r=pe.TransactionData.parse(e),n=r==null?void 0:r.V1,s=n.kind.ProgrammableTransaction;if(!n||!s)throw new Error("Unable to deserialize from bytes.");return Lt.restore({version:2,sender:n.sender,expiration:n.expiration,gasData:n.gasData,inputs:s.inputs,commands:s.commands})}static restore(e){return e.version===2?new Lt(Ve(kc,e)):new Lt(Ve(kc,iO(e)))}static getDigestFromBytes(e){const r=YO("TransactionData",e);return Mu(r)}get gasConfig(){return this.gasData}set gasConfig(e){this.gasData=e}build({maxSizeBytes:e=1/0,overrides:r,onlyTransactionKind:n}={}){const s=this.inputs,i=this.commands,a={ProgrammableTransaction:{inputs:s,commands:i}};if(n)return pe.TransactionKind.serialize(a,{maxSize:e}).toBytes();const o=(r==null?void 0:r.expiration)??this.expiration,c=(r==null?void 0:r.sender)??this.sender,u={...this.gasData,...r==null?void 0:r.gasConfig,...r==null?void 0:r.gasData};if(!c)throw new Error("Missing transaction sender");if(!u.budget)throw new Error("Missing gas budget");if(!u.payment)throw new Error("Missing gas payment");if(!u.price)throw new Error("Missing gas price");const l={sender:xm(c),expiration:o||{None:!0},gasData:{payment:u.payment,owner:xm(this.gasData.owner??c),price:BigInt(u.price),budget:BigInt(u.budget)},kind:{ProgrammableTransaction:{inputs:s,commands:i}}};return pe.TransactionData.serialize({V1:l},{maxSize:e}).toBytes()}addInput(e,r){const n=this.inputs.length;return this.inputs.push(r),{Input:n,type:e,$kind:"Input"}}getInputUses(e,r){this.mapArguments((n,s)=>(n.$kind==="Input"&&n.Input===e&&r(n,s),n))}mapCommandArguments(e,r){const n=this.commands[e];switch(n.$kind){case"MoveCall":n.MoveCall.arguments=n.MoveCall.arguments.map(i=>r(i,n,e));break;case"TransferObjects":n.TransferObjects.objects=n.TransferObjects.objects.map(i=>r(i,n,e)),n.TransferObjects.address=r(n.TransferObjects.address,n,e);break;case"SplitCoins":n.SplitCoins.coin=r(n.SplitCoins.coin,n,e),n.SplitCoins.amounts=n.SplitCoins.amounts.map(i=>r(i,n,e));break;case"MergeCoins":n.MergeCoins.destination=r(n.MergeCoins.destination,n,e),n.MergeCoins.sources=n.MergeCoins.sources.map(i=>r(i,n,e));break;case"MakeMoveVec":n.MakeMoveVec.elements=n.MakeMoveVec.elements.map(i=>r(i,n,e));break;case"Upgrade":n.Upgrade.ticket=r(n.Upgrade.ticket,n,e);break;case"$Intent":const s=n.$Intent.inputs;n.$Intent.inputs={};for(const[i,a]of Object.entries(s))n.$Intent.inputs[i]=Array.isArray(a)?a.map(o=>r(o,n,e)):r(a,n,e);break;case"Publish":break;default:throw new Error(`Unexpected transaction kind: ${n.$kind}`)}}mapArguments(e){for(const r of this.commands.keys())this.mapCommandArguments(r,e)}replaceCommand(e,r,n=e){if(!Array.isArray(r)){this.commands[e]=r;return}const s=r.length-1;this.commands.splice(e,1,...structuredClone(r)),this.mapArguments((i,a,o)=>{if(o<e+r.length)return i;if(typeof n!="number"&&(i.$kind==="Result"&&i.Result===e||i.$kind==="NestedResult"&&i.NestedResult[0]===e)){if(!("NestedResult"in i)||i.NestedResult[1]===0)return Ve(Me,structuredClone(n));throw new Error(`Cannot replace command ${e} with a specific result type: NestedResult[${e}, ${i.NestedResult[1]}] references a nested element that cannot be mapped to the replacement result`)}switch(i.$kind){case"Result":i.Result===e&&typeof n=="number"&&(i.Result=n),i.Result>e&&(i.Result+=s);break;case"NestedResult":if(i.NestedResult[0]===e&&typeof n=="number")return{$kind:"NestedResult",NestedResult:[n,i.NestedResult[1]]};i.NestedResult[0]>e&&(i.NestedResult[0]+=s);break}return i})}replaceCommandWithTransaction(e,r,n){if(n.$kind!=="Result"&&n.$kind!=="NestedResult")throw new Error("Result must be of kind Result or NestedResult");this.insertTransaction(e,r),this.replaceCommand(e+r.commands.length,[],"Result"in n?{NestedResult:[n.Result+e,0]}:{NestedResult:[n.NestedResult[0]+e,n.NestedResult[1]]})}insertTransaction(e,r){var o,c;const n=new Map,s=new Map;for(let u=0;u<r.inputs.length;u++){const l=r.inputs[u],f=Gc(l);let p=-1;if(f!==void 0&&(p=this.inputs.findIndex(d=>Gc(d)===f),p!==-1&&((o=this.inputs[p].Object)!=null&&o.SharedObject)&&((c=l.Object)!=null&&c.SharedObject)&&(this.inputs[p].Object.SharedObject.mutable=this.inputs[p].Object.SharedObject.mutable||l.Object.SharedObject.mutable)),p!==-1)n.set(u,p);else{const d=this.inputs.length;this.inputs.push(l),n.set(u,d)}}for(let u=0;u<r.commands.length;u++)s.set(u,e+u);const i=[];for(let u=0;u<r.commands.length;u++){const l=structuredClone(r.commands[u]);JO(l,n,s),i.push(l)}this.commands.splice(e,0,...i);const a=i.length;a>0&&this.mapArguments((u,l,f)=>{if(f>=e&&f<e+i.length)return u;switch(u.$kind){case"Result":u.Result>=e&&(u.Result+=a);break;case"NestedResult":u.NestedResult[0]>=e&&(u.NestedResult[0]+=a);break}return u})}getDigest(){const e=this.build({onlyTransactionKind:!1});return Lt.getDigestFromBytes(e)}snapshot(){return Ve(kc,this)}shallowClone(){return new Lt({version:this.version,sender:this.sender,expiration:this.expiration,gasData:{...this.gasData},inputs:[...this.inputs],commands:[...this.commands]})}applyResolvedData(e){this.sender||(this.sender=e.sender??null),this.expiration||(this.expiration=e.expiration??null),this.gasData.budget||(this.gasData.budget=e.gasData.budget),this.gasData.owner||(this.gasData.owner=e.gasData.owner??null),this.gasData.payment||(this.gasData.payment=e.gasData.payment),this.gasData.price||(this.gasData.price=e.gasData.price);for(let r=0;r<this.inputs.length;r++){const n=this.inputs[r],s=e.inputs[r];switch(n.$kind){case"UnresolvedPure":if(s.$kind!=="Pure")throw new Error(`Expected input at index ${r} to resolve to a Pure argument, but got ${JSON.stringify(s)}`);this.inputs[r]=s;break;case"UnresolvedObject":if(s.$kind!=="Object")throw new Error(`Expected input at index ${r} to resolve to an Object argument, but got ${JSON.stringify(s)}`);if(s.Object.$kind==="ImmOrOwnedObject"||s.Object.$kind==="Receiving"){const i=n.UnresolvedObject,a=s.Object.ImmOrOwnedObject??s.Object.Receiving;if(ve(i.objectId)!==ve(a.objectId)||i.version!=null&&i.version!==a.version||i.digest!=null&&i.digest!==a.digest||i.mutable!=null||i.initialSharedVersion!=null)throw new Error(`Input at index ${r} did not match unresolved object. ${JSON.stringify(i)} is not compatible with ${JSON.stringify(a)}`)}else if(s.Object.$kind==="SharedObject"){const i=n.UnresolvedObject,a=s.Object.SharedObject;if(ve(i.objectId)!==ve(a.objectId)||i.initialSharedVersion!=null&&i.initialSharedVersion!==a.initialSharedVersion||i.mutable!=null&&i.mutable!==a.mutable||i.version!=null||i.digest!=null)throw new Error(`Input at index ${r} did not match unresolved object. ${JSON.stringify(i)} is not compatible with ${JSON.stringify(a)}`)}else throw new Error(`Input at index ${r} resolved to an unexpected Object kind: ${JSON.stringify(s.Object)}`);this.inputs[r]=s;break}}}}var u6=t=>{throw TypeError(t)},k0=(t,e,r)=>e.has(t)||u6("Cannot "+r),ct=(t,e,r)=>(k0(t,e,"read from private field"),r?r.call(t):e.get(t)),ma=(t,e,r)=>e.has(t)?u6("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),yc=(t,e,r,n)=>(k0(t,e,"write to private field"),e.set(t,r),r),Du=(t,e,r)=>(k0(t,e,"access private method"),r),po,Mn,yo,ns,en,Kd,Xd,l6,f6,T0;const ZO="/",QO={"Mvr-Source":`@mysten/sui@${r2}`};class e4{constructor({cache:e,url:r,pageSize:n=50,overrides:s}){ma(this,en),ma(this,po),ma(this,Mn),ma(this,yo),ma(this,ns),yc(this,po,e),yc(this,Mn,r),yc(this,yo,n),yc(this,ns,{packages:s==null?void 0:s.packages,types:s==null?void 0:s.types}),t4(ct(this,ns))}async resolvePackage({package:e}){return Et(e)?{package:await ct(this,en,Kd).load(e)}:{package:e}}async resolveType({type:e}){if(!Et(e))return{type:e};const r=[...Yd(e)],n=await ct(this,en,Xd).loadMany(r),s={};for(let i=0;i<r.length;i++){const a=n[i];if(a instanceof Error)throw a;s[r[i]]=a}return{type:Jd(e,s)}}async resolve({types:e=[],packages:r=[]}){var l,f,p;const n=new Set;for(const d of e??[])Yd(d,n);const s=[...n],[i,a]=await Promise.all([s.length>0?ct(this,en,Xd).loadMany(s):[],r.length>0?ct(this,en,Kd).loadMany(r):[]]),o={...(l=ct(this,ns))==null?void 0:l.types};for(const[d,b]of s.entries()){const g=i[d];if(g instanceof Error)throw g;o[b]=g}const c={};for(const d of e??[]){const b=Jd(d,o);c[d]={type:b}}const u={};for(const[d,b]of(r??[]).entries()){const g=((p=(f=ct(this,ns))==null?void 0:f.packages)==null?void 0:p[b])??a[d];if(g instanceof Error)throw g;u[b]={package:g}}return{types:c,packages:u}}}po=new WeakMap;Mn=new WeakMap;yo=new WeakMap;ns=new WeakMap;en=new WeakSet;Kd=function(){return ct(this,po).readSync(["#mvrPackageDataLoader",ct(this,Mn)??""],()=>{var r;const t=new m2(async n=>{if(!ct(this,Mn))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const s=await Du(this,en,l6).call(this,n);return n.map(i=>s[i]??new Error(`Failed to resolve package: ${i}`))}),e=(r=ct(this,ns))==null?void 0:r.packages;if(e)for(const[n,s]of Object.entries(e))t.prime(n,s);return t})};Xd=function(){return ct(this,po).readSync(["#mvrTypeDataLoader",ct(this,Mn)??""],()=>{var r;const t=new m2(async n=>{if(!ct(this,Mn))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const s=await Du(this,en,f6).call(this,n);return n.map(i=>s[i]??new Error(`Failed to resolve type: ${i}`))}),e=(r=ct(this,ns))==null?void 0:r.types;if(e)for(const[n,s]of Object.entries(e))t.prime(n,s);return t})};l6=async function(t){if(t.length===0)return{};const e=$u(t,ct(this,yo)),r={};return await Promise.all(e.map(async n=>{var i;const s=await Du(this,en,T0).call(this,"/v1/resolution/bulk",{names:n});if(s!=null&&s.resolution)for(const a of Object.keys(s==null?void 0:s.resolution)){const o=(i=s.resolution[a])==null?void 0:i.package_id;o&&(r[a]=o)}})),r};f6=async function(t){if(t.length===0)return{};const e=$u(t,ct(this,yo)),r={};return await Promise.all(e.map(async n=>{var i;const s=await Du(this,en,T0).call(this,"/v1/struct-definition/bulk",{types:n});if(s!=null&&s.resolution)for(const a of Object.keys(s==null?void 0:s.resolution)){const o=(i=s.resolution[a])==null?void 0:i.type_tag;o&&(r[a]=o)}})),r};T0=async function(t,e){if(!ct(this,Mn))throw new Error("MVR Api URL is not set for the current client");const r=await fetch(`${ct(this,Mn)}${t}`,{method:"POST",headers:{"Content-Type":"application/json",...QO},body:JSON.stringify(e)});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(`Failed to resolve types: ${n==null?void 0:n.message}`)}return r.json()};function t4(t){if(t!=null&&t.packages)for(const[e,r]of Object.entries(t.packages)){if(!Yt(e))throw new Error(`Invalid package name: ${e}`);if(!kr(ve(r)))throw new Error(`Invalid package ID: ${r}`)}if(t!=null&&t.types)for(const[e,r]of Object.entries(t.types)){if(ni(e).typeParams.length>0)throw new Error("Type overrides must be first-level only. If you want to supply generic types, just pass each type individually.");const n=ni(r);if(!kr(n.address))throw new Error(`Invalid type: ${r}`)}}function Yd(t,e=new Set){if(typeof t=="string"&&!Et(t))return e;const r=d6(t)?t:ni(t);Et(r.address)&&e.add(`${r.address}::${r.module}::${r.name}`);for(const n of r.typeParams)Yd(n,e);return e}function Jd(t,e){const r=d6(t)?t:ni(t),n=`${r.address}::${r.module}::${r.name}`,s=e[n];return Vc({...r,address:s?s.split("::")[0]:r.address,typeParams:r.typeParams.map(i=>Jd(i,e))})}function Et(t){return t.includes(ZO)||t.includes("@")||t.includes(".sui")}function d6(t){return typeof t=="object"&&"address"in t&&"module"in t&&"name"in t&&"typeParams"in t}function r4(t){const e=new Set,r=new Set;for(const n of t.commands)switch(n.$kind){case"MakeMoveVec":n.MakeMoveVec.type&&km([n.MakeMoveVec.type]).forEach(a=>{r.add(a)});break;case"MoveCall":const s=n.MoveCall,i=s.package.split("::")[0];if(Et(i)){if(!Yt(i))throw new Error(`Invalid package name: ${i}`);e.add(i)}km(s.typeArguments??[]).forEach(a=>{r.add(a)});break}return{packages:[...e],types:[...r]}}function n4(t,e){var r;for(const n of t.commands){if((r=n.MakeMoveVec)!=null&&r.type){if(!Et(n.MakeMoveVec.type))continue;if(!e.types[n.MakeMoveVec.type])throw new Error(`No resolution found for type: ${n.MakeMoveVec.type}`);n.MakeMoveVec.type=e.types[n.MakeMoveVec.type].type}const s=n.MoveCall;if(!s)continue;const i=s.package.split("::"),a=i[0];if(Et(a)&&!e.packages[a])throw new Error(`No address found for package: ${a}`);Et(a)&&(i[0]=e.packages[a].package,s.package=i.join("::"));const o=s.typeArguments;if(o){for(let c=0;c<o.length;c++)if(Et(o[c])){if(!e.types[o[c]])throw new Error(`No resolution found for type: ${o[c]}`);o[c]=e.types[o[c]].type}s.typeArguments=o}}}function km(t){const e=new Set;for(const r of t)if(Et(r)){if(!TP(r))throw new Error(`Invalid type with names: ${r}`);e.add(r)}return e}const s4=t=>async(e,r,n)=>{const s=r4(e);if(s.types.length===0&&s.packages.length===0)return n();const i=await i4(r).core.mvr.resolve({types:s.types,packages:s.packages});n4(e,i),await n()};function i4(t){if(!t.client)throw new Error("No sui client passed to Transaction#build, but transaction data was not sufficient to build offline.");return t.client}var h6=t=>{throw TypeError(t)},_0=(t,e,r)=>e.has(t)||h6("Cannot "+r),Z=(t,e,r)=>(_0(t,e,"read from private field"),r?r.call(t):e.get(t)),Kr=(t,e,r)=>e.has(t)?h6("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Oe=(t,e,r,n)=>(_0(t,e,"write to private field"),e.set(t,r),r),at=(t,e,r)=>(_0(t,e,"access private method"),r),$s,Gs,xn,nn,Zt,Qt,_r,ss,oe,Ye,p6,Tc,_c,Ic,qc,Zd,I0,y6,m6;function $f(t,e=1/0){const r={$kind:"Result",get Result(){return typeof t=="function"?t():t}},n=[],s=i=>n[i]??(n[i]={$kind:"NestedResult",get NestedResult(){return[typeof t=="function"?t():t,i]}});return new Proxy(r,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(i,a){if(a in i)return Reflect.get(i,a);if(a===Symbol.iterator)return function*(){let c=0;for(;c<e;)yield s(c),c++};if(typeof a=="symbol")return;const o=parseInt(a,10);if(!(Number.isNaN(o)||o<0))return s(o)}})}const b6=Symbol.for("@mysten/transaction");function g6(t){return!!t&&typeof t=="object"&&t[b6]===!0}const Tm={buildPlugins:new Map,serializationPlugins:new Map},jf=Symbol.for("@mysten/transaction/registry");function ba(){try{const t=globalThis;return t[jf]||(t[jf]=Tm),t[jf]}catch{return Tm}}const w6=class Qd{constructor(){Kr(this,Ye),Kr(this,$s),Kr(this,Gs),Kr(this,xn,new Map),Kr(this,nn,[]),Kr(this,Zt,[]),Kr(this,Qt,new Set),Kr(this,_r,new Set),Kr(this,ss,new Map),Kr(this,oe),this.object=KO(r=>{var i,a;if(typeof r=="function")return this.object(this.add(r));if(typeof r=="object"&&Vd(Me,r))return r;const n=Gc(r),s=Z(this,oe).inputs.find(o=>n===Gc(o));return(i=s==null?void 0:s.Object)!=null&&i.SharedObject&&typeof r=="object"&&((a=r.Object)!=null&&a.SharedObject)&&(s.Object.SharedObject.mutable=s.Object.SharedObject.mutable||r.Object.SharedObject.mutable),s?{$kind:"Input",Input:Z(this,oe).inputs.indexOf(s),type:"object"}:at(this,Ye,_c).call(this,"object",typeof r=="string"?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:ve(r)}}:r)});const e=ba();Oe(this,oe,new Lt),Oe(this,Gs,[...e.buildPlugins.values()]),Oe(this,$s,[...e.serializationPlugins.values()])}static fromKind(e){const r=new Qd;return Oe(r,oe,Lt.fromKindBytes(typeof e=="string"?tr(e):e)),Oe(r,nn,Z(r,oe).inputs.slice()),Oe(r,Zt,Z(r,oe).commands.slice()),Oe(r,Qt,new Set(Z(r,Zt).map((n,s)=>s))),r}static from(e){const r=new Qd;return g6(e)?Oe(r,oe,Lt.restore(e.getData())):typeof e!="string"||!e.startsWith("{")?Oe(r,oe,Lt.fromBytes(typeof e=="string"?tr(e):e)):Oe(r,oe,Lt.restore(JSON.parse(e))),Oe(r,nn,Z(r,oe).inputs.slice()),Oe(r,Zt,Z(r,oe).commands.slice()),Oe(r,Qt,new Set(Z(r,Zt).map((n,s)=>s))),r}static registerGlobalSerializationPlugin(e,r){ba().serializationPlugins.set(e,r??e)}static unregisterGlobalSerializationPlugin(e){ba().serializationPlugins.delete(e)}static registerGlobalBuildPlugin(e,r){ba().buildPlugins.set(e,r??e)}static unregisterGlobalBuildPlugin(e){ba().buildPlugins.delete(e)}addSerializationPlugin(e){Z(this,$s).push(e)}addBuildPlugin(e){Z(this,Gs).push(e)}addIntentResolver(e,r){if(Z(this,xn).has(e)&&Z(this,xn).get(e)!==r)throw new Error(`Intent resolver for ${e} already exists`);Z(this,xn).set(e,r)}setSender(e){Z(this,oe).sender=e}setSenderIfNotSet(e){Z(this,oe).sender||(Z(this,oe).sender=e)}setExpiration(e){Z(this,oe).expiration=e?Ve(N2,e):null}setGasPrice(e){Z(this,oe).gasConfig.price=String(e)}setGasBudget(e){Z(this,oe).gasConfig.budget=String(e)}setGasBudgetIfNotSet(e){Z(this,oe).gasData.budget==null&&(Z(this,oe).gasConfig.budget=String(e))}setGasOwner(e){Z(this,oe).gasConfig.owner=e}setGasPayment(e){Z(this,oe).gasConfig.payment=e.map(r=>Ve(ws,r))}get blockData(){return Em(Z(this,oe).snapshot())}getData(){return Z(this,oe).snapshot()}get[b6](){return!0}get pure(){return Object.defineProperty(this,"pure",{enumerable:!1,value:XO(e=>w0(e)?at(this,Ye,_c).call(this,"pure",{$kind:"Pure",Pure:{bytes:e.toBase64()}}):at(this,Ye,_c).call(this,"pure",Vd(bm,e)?Ve(bm,e):e instanceof Uint8Array?Br.Pure(e):{$kind:"UnresolvedPure",UnresolvedPure:{value:e}}))}),this.pure}get gas(){return{$kind:"GasCoin",GasCoin:!0}}objectRef(...e){return this.object(Br.ObjectRef(...e))}receivingRef(...e){return this.object(Br.ReceivingRef(...e))}sharedObjectRef(...e){return this.object(Br.SharedObjectRef(...e))}add(e){if(typeof e=="function"){if(Z(this,ss).has(e))return Z(this,ss).get(e);const r=at(this,Ye,p6).call(this),n=e(r);if(!(n&&typeof n=="object"&&"then"in n))return Oe(this,Qt,Z(r,Qt)),Z(this,ss).set(e,n),n;const s=at(this,Ye,Tc).call(this,{$kind:"$Intent",$Intent:{name:"AsyncTransactionThunk",inputs:{},data:{resultIndex:Z(this,oe).commands.length,result:null}}});Z(this,_r).add(Promise.resolve(n).then(a=>{s.$Intent.data.result=a}));const i=$f(()=>s.$Intent.data.resultIndex);return Z(this,ss).set(e,i),i}else at(this,Ye,Tc).call(this,e);return $f(Z(this,oe).commands.length-1)}splitCoins(e,r){const n=Os.SplitCoins(typeof e=="string"?this.object(e):at(this,Ye,qc).call(this,e),r.map(s=>typeof s=="number"||typeof s=="bigint"||typeof s=="string"?this.pure.u64(s):at(this,Ye,Ic).call(this,s)));return at(this,Ye,Tc).call(this,n),$f(Z(this,oe).commands.length-1,r.length)}mergeCoins(e,r){return this.add(Os.MergeCoins(this.object(e),r.map(n=>this.object(n))))}publish({modules:e,dependencies:r}){return this.add(Os.Publish({modules:e,dependencies:r}))}upgrade({modules:e,dependencies:r,package:n,ticket:s}){return this.add(Os.Upgrade({modules:e,dependencies:r,package:n,ticket:this.object(s)}))}moveCall({arguments:e,...r}){return this.add(Os.MoveCall({...r,arguments:e==null?void 0:e.map(n=>at(this,Ye,Ic).call(this,n))}))}transferObjects(e,r){return this.add(Os.TransferObjects(e.map(n=>this.object(n)),typeof r=="string"?this.pure.address(r):at(this,Ye,Ic).call(this,r)))}makeMoveVec({type:e,elements:r}){return this.add(Os.MakeMoveVec({type:e,elements:r.map(n=>this.object(n))}))}serialize(){return JSON.stringify(Em(Z(this,oe).snapshot()))}async toJSON(e={}){await this.prepareForSerialization(e);const r=this.isFullyResolved();return JSON.stringify(Ve(hO,r?{...Z(this,oe).snapshot(),digest:Z(this,oe).getDigest()}:Z(this,oe).snapshot()),(n,s)=>typeof s=="bigint"?s.toString():s,2)}async sign(e){const{signer:r,...n}=e,s=await this.build(n);return r.signTransaction(s)}isFullyResolved(){return!(!Z(this,oe).sender||Z(this,_r).size>0||Z(this,oe).commands.some(e=>e.$Intent)||c6(Z(this,oe),{}))}async build(e={}){return await this.prepareForSerialization(e),await at(this,Ye,Zd).call(this,e),Z(this,oe).build({onlyTransactionKind:e.onlyTransactionKind})}async getDigest(e={}){return await this.prepareForSerialization(e),await at(this,Ye,Zd).call(this,e),Z(this,oe).getDigest()}async prepareForSerialization(e){var s;await at(this,Ye,y6).call(this),at(this,Ye,m6).call(this);const r=new Set;for(const i of Z(this,oe).commands)i.$Intent&&r.add(i.$Intent.name);const n=[...Z(this,$s)];for(const i of r)if(!((s=e.supportedIntents)!=null&&s.includes(i))){if(!Z(this,xn).has(i))throw new Error(`Missing intent resolver for ${i}`);n.push(Z(this,xn).get(i))}n.push(s4()),await at(this,Ye,I0).call(this,n,e)}};$s=new WeakMap;Gs=new WeakMap;xn=new WeakMap;nn=new WeakMap;Zt=new WeakMap;Qt=new WeakMap;_r=new WeakMap;ss=new WeakMap;oe=new WeakMap;Ye=new WeakSet;p6=function(){const t=new w6;return Oe(t,oe,Z(this,oe)),Oe(t,$s,Z(this,$s)),Oe(t,Gs,Z(this,Gs)),Oe(t,xn,Z(this,xn)),Oe(t,_r,Z(this,_r)),Oe(t,Qt,new Set(Z(this,Qt))),Oe(t,ss,Z(this,ss)),Z(this,nn).push(Z(t,nn)),Z(this,Zt).push(Z(t,Zt)),t};Tc=function(t){const e=Z(this,oe).commands.length;return Z(this,Zt).push(t),Z(this,Qt).add(e),Z(this,oe).commands.push(t),Z(this,oe).mapCommandArguments(e,r=>{if(r.$kind==="Result"&&!Z(this,Qt).has(r.Result))throw new Error(`Result { Result: ${r.Result} } is not available to use in the current transaction`);if(r.$kind==="NestedResult"&&!Z(this,Qt).has(r.NestedResult[0]))throw new Error(`Result { NestedResult: [${r.NestedResult[0]}, ${r.NestedResult[1]}] } is not available to use in the current transaction`);if(r.$kind==="Input"&&r.Input>=Z(this,oe).inputs.length)throw new Error(`Input { Input: ${r.Input} } references an input that does not exist in the current transaction`);return r}),t};_c=function(t,e){return Z(this,nn).push(e),Z(this,oe).addInput(t,e)};Ic=function(t){return w0(t)?this.pure(t):at(this,Ye,qc).call(this,t)};qc=function(t){if(typeof t=="function"){const e=this.add(t);return typeof e=="function"?at(this,Ye,qc).call(this,e):Ve(Me,e)}return Ve(Me,t)};Zd=async function(t){if(!t.onlyTransactionKind&&!Z(this,oe).sender)throw new Error("Missing transaction sender");await at(this,Ye,I0).call(this,[...Z(this,Gs),GO],t)};I0=async function(t,e){try{const r=n=>{if(n>=t.length)return()=>{};const s=t[n];return async()=>{const i=r(n+1);let a=!1,o=!1;if(await s(Z(this,oe),e,async()=>{if(a)throw new Error(`next() was call multiple times in TransactionPlugin ${n}`);a=!0,await i(),o=!0}),!a)throw new Error(`next() was not called in TransactionPlugin ${n}`);if(!o)throw new Error(`next() was not awaited in TransactionPlugin ${n}`)}};await r(0)()}finally{Oe(this,nn,Z(this,oe).inputs.slice()),Oe(this,Zt,Z(this,oe).commands.slice()),Oe(this,Qt,new Set(Z(this,Zt).map((r,n)=>n)))}};y6=async function(){for(;Z(this,_r).size>0;){const t=Promise.all(Z(this,_r));Z(this,_r).clear(),Z(this,_r).add(t),await t,Z(this,_r).delete(t)}};m6=function(){var a;const t=Z(this,oe).commands,e=Z(this,oe).inputs,r=Z(this,Zt).flat(1/0),n=Z(this,nn).flat(1/0);if(r.length!==t.length)throw new Error("Unexpected number of commands found in transaction data");if(n.length!==e.length)throw new Error("Unexpected number of inputs found in transaction data");const s=r.filter(o=>{var c;return((c=o.$Intent)==null?void 0:c.name)!=="AsyncTransactionThunk"});Z(this,oe).commands=s,Z(this,oe).inputs=n,Oe(this,Zt,s),Oe(this,nn,n),Oe(this,Qt,new Set(s.map((o,c)=>c)));function i(o){var l;const c=t[o];if(((l=c.$Intent)==null?void 0:l.name)==="AsyncTransactionThunk"){const f=c.$Intent.data.result;if(f==null)throw new Error("AsyncTransactionThunk has not been resolved");return i(f.Result)}const u=s.indexOf(c);if(u===-1)throw new Error("Unable to find original index for command");return u}Z(this,oe).mapArguments(o=>{if(o.$kind==="Input"){const c=n.indexOf(e[o.Input]);if(c===-1)throw new Error("Input has not been resolved");return{...o,Input:c}}else if(o.$kind==="Result"){const c=i(o.Result);return{...o,Result:c}}else if(o.$kind==="NestedResult"){const c=i(o.NestedResult[0]);return{...o,NestedResult:[c,o.NestedResult[1]]}}return o});for(const[o,c]of t.entries())if(((a=c.$Intent)==null?void 0:a.name)==="AsyncTransactionThunk")try{c.$Intent.data.resultIndex=i(o)}catch{}};let eh=w6;const a4={mainnet:"https://mainnet.mvr.mystenlabs.com",testnet:"https://testnet.mvr.mystenlabs.com"};class o4 extends T2{constructor(e){var r,n,s;super(e),this.core=this,this.mvr=new e4({cache:this.cache.scope("core.mvr"),url:((r=e.mvr)==null?void 0:r.url)??a4[this.network],pageSize:(n=e.mvr)==null?void 0:n.pageSize,overrides:(s=e.mvr)==null?void 0:s.overrides})}async getObject(e){const{objectId:r}=e,{objects:[n]}=await this.getObjects({objectIds:[r],signal:e.signal});if(n instanceof Error)throw n;return{object:n}}async getDynamicField(e){const r=Tr.parseFromStr((await this.core.mvr.resolveType({type:e.name.type})).type),n=SO(e.parentId,r,e.name.bcs),{objects:[s]}=await this.getObjects({objectIds:[n],signal:e.signal});if(s instanceof Error)throw s;const i=ni(s.type),a=await s.content;return{dynamicField:{id:s.id,digest:s.digest,version:s.version,type:s.type,previousTransaction:s.previousTransaction,name:{type:typeof i.typeParams[0]=="string"?i.typeParams[0]:Vc(i.typeParams[0]),bcs:e.name.bcs},value:{type:typeof i.typeParams[1]=="string"?i.typeParams[1]:Vc(i.typeParams[1]),bcs:a.slice(Lu+e.name.bcs.length)}}}}async waitForTransaction({signal:e,timeout:r=60*1e3,...n}){const s=e?AbortSignal.any([AbortSignal.timeout(r),e]):AbortSignal.timeout(r),i=new Promise((a,o)=>{s.addEventListener("abort",()=>o(s.reason))});for(i.catch(()=>{});;){s.throwIfAborted();try{return await this.getTransaction({...n,signal:s})}catch{await Promise.race([new Promise(a=>setTimeout(a,2e3)),i])}}}}class c4 extends Error{}class is extends c4{constructor(e,r){super(r),this.code=e}static fromResponse(e,r){switch(e.code){case"notExists":return new is(e.code,`Object ${e.object_id} does not exist`);case"dynamicFieldNotFound":return new is(e.code,`Dynamic field not found for object ${e.parent_object_id}`);case"deleted":return new is(e.code,`Object ${e.object_id} has been deleted`);case"displayError":return new is(e.code,`Display error: ${e.error}`);case"unknown":default:return new is(e.code,`Unknown error while loading object${r?` ${r}`:""}`)}}}function u4(t){return{...Lt.fromBytes(t).snapshot(),bcs:t}}function l4(t){const e=pe.TransactionEffects.parse(t);switch(e.$kind){case"V1":return f4({effects:e.V1});case"V2":return d4({bytes:t,effects:e.V2});default:throw new Error(`Unknown transaction effects version: ${e.$kind}`)}}function f4(t){throw new Error("V1 effects are not supported yet")}function d4({bytes:t,effects:e}){const r=e.changedObjects.map(([n,s])=>{var i,a,o,c,u,l;return{id:n,inputState:s.inputState.$kind==="Exist"?"Exists":"DoesNotExist",inputVersion:((i=s.inputState.Exist)==null?void 0:i[0][0])??null,inputDigest:((a=s.inputState.Exist)==null?void 0:a[0][1])??null,inputOwner:((o=s.inputState.Exist)==null?void 0:o[1])??null,outputState:s.outputState.$kind==="NotExist"?"DoesNotExist":s.outputState.$kind,outputVersion:s.outputState.$kind==="PackageWrite"?(c=s.outputState.PackageWrite)==null?void 0:c[0]:s.outputState.ObjectWrite?e.lamportVersion:null,outputDigest:s.outputState.$kind==="PackageWrite"?(u=s.outputState.PackageWrite)==null?void 0:u[1]:((l=s.outputState.ObjectWrite)==null?void 0:l[0])??null,outputOwner:s.outputState.ObjectWrite?s.outputState.ObjectWrite[1]:null,idOperation:s.idOperation.$kind}});return{bcs:t,digest:e.transactionDigest,version:2,status:e.status.$kind==="Success"?{success:!0,error:null}:{success:!1,error:e.status.Failed.error.$kind},gasUsed:e.gasUsed,transactionDigest:e.transactionDigest,gasObject:e.gasObjectIndex===null?null:r[e.gasObjectIndex]??null,eventsDigest:e.eventsDigest,dependencies:e.dependencies,lamportVersion:e.lamportVersion,changedObjects:r,unchangedConsensusObjects:e.unchangedSharedObjects.map(([n,s])=>({kind:s.$kind==="MutateDeleted"?"MutateConsensusStreamEnded":s.$kind==="ReadDeleted"?"ReadConsensusStreamEnded":s.$kind,objectId:n,version:s.$kind==="ReadOnlyRoot"?s.ReadOnlyRoot[0]:s[s.$kind],digest:s.$kind==="ReadOnlyRoot"?s.ReadOnlyRoot[1]:null})),auxiliaryDataDigest:e.auxDataDigest}}var v6=t=>{throw TypeError(t)},E6=(t,e,r)=>e.has(t)||v6("Cannot "+r),jt=(t,e,r)=>(E6(t,e,"read from private field"),r?r.call(t):e.get(t)),h4=(t,e,r)=>e.has(t)?v6("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),p4=(t,e,r,n)=>(E6(t,e,"write to private field"),e.set(t,r),r),dt;class y4 extends o4{constructor({jsonRpcClient:e,mvr:r}){super({network:e.network,base:e,mvr:r}),h4(this,dt),p4(this,dt,e)}async getObjects(e){const r=$u(e.objectIds,50),n=[];for(const s of r){const i=await jt(this,dt).multiGetObjects({ids:s,options:{showOwner:!0,showType:!0,showBcs:!0,showPreviousTransaction:!0},signal:e.signal});for(const[a,o]of i.entries())o.error?n.push(is.fromResponse(o.error,s[a])):n.push(_m(o.data))}return{objects:n}}async getOwnedObjects(e){const r=await jt(this,dt).getOwnedObjects({owner:e.address,limit:e.limit,cursor:e.cursor,options:{showOwner:!0,showType:!0,showBcs:!0,showPreviousTransaction:!0},filter:e.type?{StructType:e.type}:null,signal:e.signal});return{objects:r.data.map(n=>{if(n.error)throw is.fromResponse(n.error);return _m(n.data)}),hasNextPage:r.hasNextPage,cursor:r.nextCursor??null}}async getCoins(e){const r=await jt(this,dt).getCoins({owner:e.address,coinType:e.coinType,limit:e.limit,cursor:e.cursor,signal:e.signal});return{objects:r.data.map(n=>({id:n.coinObjectId,version:n.version,digest:n.digest,balance:n.balance,type:`0x2::coin::Coin<${n.coinType}>`,content:Promise.resolve(g4.serialize({id:n.coinObjectId,balance:{value:n.balance}}).toBytes()),owner:{$kind:"ObjectOwner",ObjectOwner:e.address},previousTransaction:n.previousTransaction})),hasNextPage:r.hasNextPage,cursor:r.nextCursor??null}}async getBalance(e){const r=await jt(this,dt).getBalance({owner:e.address,coinType:e.coinType,signal:e.signal});return{balance:{coinType:r.coinType,balance:r.totalBalance}}}async getAllBalances(e){return{balances:(await jt(this,dt).getAllBalances({owner:e.address,signal:e.signal})).map(n=>({coinType:n.coinType,balance:n.totalBalance})),hasNextPage:!1,cursor:null}}async getTransaction(e){const r=await jt(this,dt).getTransactionBlock({digest:e.digest,options:{showRawInput:!0,showObjectChanges:!0,showRawEffects:!0,showEvents:!0,showEffects:!0,showBalanceChanges:!0},signal:e.signal});return{transaction:Im(r)}}async executeTransaction(e){const r=await jt(this,dt).executeTransactionBlock({transactionBlock:e.transaction,signature:e.signatures,options:{showRawEffects:!0,showEvents:!0,showObjectChanges:!0,showRawInput:!0,showEffects:!0,showBalanceChanges:!0},signal:e.signal});return{transaction:Im(r)}}async dryRunTransaction(e){const r=eh.from(e.transaction),n=await jt(this,dt).dryRunTransactionBlock({transactionBlock:e.transaction,signal:e.signal}),{effects:s,objectTypes:i}=m4({effects:n.effects,objectChanges:n.objectChanges});return{transaction:{digest:await r.getDigest(),epoch:null,effects:s,objectTypes:Promise.resolve(i),signatures:[],transaction:u4(e.transaction),balanceChanges:n.balanceChanges.map(a=>({coinType:a.coinType,address:A6(a.owner),amount:a.amount}))}}}async getReferenceGasPrice(e){const r=await jt(this,dt).getReferenceGasPrice({signal:e==null?void 0:e.signal});return{referenceGasPrice:String(r)}}async getDynamicFields(e){const r=await jt(this,dt).getDynamicFields({parentId:e.parentId,limit:e.limit,cursor:e.cursor});return{dynamicFields:r.data.map(n=>({id:n.objectId,type:n.objectType,name:{type:n.name.type,bcs:tr(n.bcsName)}})),hasNextPage:r.hasNextPage,cursor:r.nextCursor}}async verifyZkLoginSignature(e){const r=await jt(this,dt).verifyZkLoginSignature({bytes:e.bytes,signature:e.signature,intentScope:e.intentScope,author:e.author});return{success:r.success,errors:r.errors}}async defaultNameServiceName(e){return{data:{name:(await jt(this,dt).resolveNameServiceNames(e)).data[0]}}}resolveTransactionPlugin(){return o6(jt(this,dt))}async getMoveFunction(e){const r=await jt(this,dt).getNormalizedMoveFunction({package:(await this.mvr.resolvePackage({package:e.packageId})).package,module:e.moduleName,function:e.name});return{function:{packageId:ve(e.packageId),moduleName:e.moduleName,name:e.name,visibility:v4(r.visibility),isEntry:r.isEntry,typeParameters:r.typeParameters.map(n=>({isPhantom:!1,constraints:w4(n)})),parameters:r.parameters.map(n=>Pm(n)),returns:r.return.map(n=>Pm(n))}}}}dt=new WeakMap;function _m(t){var e;return{id:t.objectId,version:t.version,digest:t.digest,type:t.type,content:Promise.resolve(((e=t.bcs)==null?void 0:e.dataType)==="moveObject"?tr(t.bcs.bcsBytes):new Uint8Array),owner:xi(t.owner),previousTransaction:t.previousTransaction??null}}function xi(t){if(t==="Immutable")return{$kind:"Immutable",Immutable:!0};if("ConsensusAddressOwner"in t)return{$kind:"ConsensusAddressOwner",ConsensusAddressOwner:{owner:t.ConsensusAddressOwner.owner,startVersion:t.ConsensusAddressOwner.start_version}};if("AddressOwner"in t)return{$kind:"AddressOwner",AddressOwner:t.AddressOwner};if("ObjectOwner"in t)return{$kind:"ObjectOwner",ObjectOwner:t.ObjectOwner};if("Shared"in t)return{$kind:"Shared",Shared:{initialSharedVersion:t.Shared.initial_shared_version}};throw new Error(`Unknown owner type: ${JSON.stringify(t)}`)}function A6(t){if(t==="Immutable")return null;if("ConsensusAddressOwner"in t)return t.ConsensusAddressOwner.owner;if("AddressOwner"in t)return t.AddressOwner;if("ObjectOwner"in t)return t.ObjectOwner;if("Shared"in t)return null;throw new Error(`Unknown owner type: ${JSON.stringify(t)}`)}function Im(t){var i,a,o;const e=pe.SenderSignedData.parse(tr(t.rawTransaction))[0],r={};(i=t.objectChanges)==null||i.forEach(c=>{c.type!=="published"&&(r[c.objectId]=c.objectType)});const n=pe.TransactionData.serialize(e.intentMessage.value).toBytes(),s=Lt.restore({version:2,sender:e.intentMessage.value.V1.sender,expiration:e.intentMessage.value.V1.expiration,gasData:e.intentMessage.value.V1.gasData,inputs:e.intentMessage.value.V1.kind.ProgrammableTransaction.inputs,commands:e.intentMessage.value.V1.kind.ProgrammableTransaction.commands});return{digest:t.digest,epoch:((a=t.effects)==null?void 0:a.executedEpoch)??null,effects:l4(new Uint8Array(t.rawEffects)),objectTypes:Promise.resolve(r),transaction:{...s,bcs:n},signatures:e.txSignatures,balanceChanges:((o=t.balanceChanges)==null?void 0:o.map(c=>({coinType:c.coinType,address:A6(c.owner),amount:c.amount})))??[]}}function m4({bytes:t,effects:e,objectChanges:r}){var a;const n=[],s=[],i={};return r==null||r.forEach(o=>{var c,u,l,f;switch(o.type){case"published":n.push({id:o.packageId,inputState:"DoesNotExist",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"PackageWrite",outputVersion:o.version,outputDigest:o.digest,outputOwner:null,idOperation:"Created"});break;case"transferred":n.push({id:o.objectId,inputState:"Exists",inputVersion:o.version,inputDigest:o.digest,inputOwner:{$kind:"AddressOwner",AddressOwner:o.sender},outputState:"ObjectWrite",outputVersion:o.version,outputDigest:o.digest,outputOwner:xi(o.recipient),idOperation:"None"}),i[o.objectId]=o.objectType;break;case"mutated":n.push({id:o.objectId,inputState:"Exists",inputVersion:o.previousVersion,inputDigest:null,inputOwner:xi(o.owner),outputState:"ObjectWrite",outputVersion:o.version,outputDigest:o.digest,outputOwner:xi(o.owner),idOperation:"None"}),i[o.objectId]=o.objectType;break;case"deleted":n.push({id:o.objectId,inputState:"Exists",inputVersion:o.version,inputDigest:((u=(c=e.deleted)==null?void 0:c.find(p=>p.objectId===o.objectId))==null?void 0:u.digest)??null,inputOwner:null,outputState:"DoesNotExist",outputVersion:null,outputDigest:null,outputOwner:null,idOperation:"Deleted"}),i[o.objectId]=o.objectType;break;case"wrapped":n.push({id:o.objectId,inputState:"Exists",inputVersion:o.version,inputDigest:null,inputOwner:{$kind:"AddressOwner",AddressOwner:o.sender},outputState:"ObjectWrite",outputVersion:o.version,outputDigest:((f=(l=e.wrapped)==null?void 0:l.find(p=>p.objectId===o.objectId))==null?void 0:f.digest)??null,outputOwner:{$kind:"ObjectOwner",ObjectOwner:o.sender},idOperation:"None"}),i[o.objectId]=o.objectType;break;case"created":n.push({id:o.objectId,inputState:"DoesNotExist",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"ObjectWrite",outputVersion:o.version,outputDigest:o.digest,outputOwner:xi(o.owner),idOperation:"Created"}),i[o.objectId]=o.objectType;break}}),{objectTypes:i,effects:{bcs:t??null,digest:e.transactionDigest,version:2,status:e.status.status==="success"?{success:!0,error:null}:{success:!1,error:e.status.error},gasUsed:e.gasUsed,transactionDigest:e.transactionDigest,gasObject:{id:(a=e.gasObject)==null?void 0:a.reference.objectId,inputState:"Exists",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"ObjectWrite",outputVersion:e.gasObject.reference.version,outputDigest:e.gasObject.reference.digest,outputOwner:xi(e.gasObject.owner),idOperation:"None"},eventsDigest:e.eventsDigest??null,dependencies:e.dependencies??[],lamportVersion:e.gasObject.reference.version,changedObjects:n,unchangedConsensusObjects:s,auxiliaryDataDigest:null}}}const b4=pe.struct("Balance",{value:pe.u64()}),g4=pe.struct("Coin",{id:pe.Address,balance:b4});function Pm(t){if(typeof t!="string"){if("Reference"in t)return{reference:"immutable",body:Na(t.Reference)};if("MutableReference"in t)return{reference:"mutable",body:Na(t.MutableReference)}}return{reference:null,body:Na(t)}}function Na(t){switch(t){case"Address":return{$kind:"address"};case"Bool":return{$kind:"bool"};case"U8":return{$kind:"u8"};case"U16":return{$kind:"u16"};case"U32":return{$kind:"u32"};case"U64":return{$kind:"u64"};case"U128":return{$kind:"u128"};case"U256":return{$kind:"u256"}}if(typeof t=="string")throw new Error(`Unknown type: ${t}`);if("Vector"in t)return{$kind:"vector",vector:Na(t.Vector)};if("Struct"in t)return{$kind:"datatype",datatype:{typeName:`${ve(t.Struct.address)}::${t.Struct.module}::${t.Struct.name}`,typeParameters:t.Struct.typeArguments.map(e=>Na(e))}};if("TypeParameter"in t)return{$kind:"typeParameter",index:t.TypeParameter};throw new Error(`Unknown type: ${JSON.stringify(t)}`)}function w4(t){return t.abilities.map(e=>{switch(e){case"Copy":return"copy";case"Drop":return"drop";case"Store":return"store";case"Key":return"key";default:return"unknown"}})}function v4(t){switch(t){case"Public":return"public";case"Private":return"private";case"Friend":return"friend";default:return"unknown"}}const E4=Symbol.for("@mysten/SuiClient");class Om extends T2{constructor(e){super({network:e.network??"unknown"}),this.jsonRpc=this,this.transport=e.transport??new RI({url:e.url}),this.core=new y4({jsonRpcClient:this,mvr:e.mvr})}get[E4](){return!0}async getRpcApiVersion({signal:e}={}){return(await this.transport.request({method:"rpc.discover",params:[],signal:e})).info.version}async getCoins({coinType:e,owner:r,cursor:n,limit:s,signal:i}){if(!r||!kr(ve(r)))throw new Error("Invalid Sui address");return e&&Et(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getCoins",params:[r,e,n,s],signal:i})}async getAllCoins(e){if(!e.owner||!kr(ve(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getAllCoins",params:[e.owner,e.cursor,e.limit],signal:e.signal})}async getBalance({owner:e,coinType:r,signal:n}){if(!e||!kr(ve(e)))throw new Error("Invalid Sui address");return r&&Et(r)&&(r=(await this.core.mvr.resolveType({type:r})).type),await this.transport.request({method:"suix_getBalance",params:[e,r],signal:n})}async getAllBalances(e){if(!e.owner||!kr(ve(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getAllBalances",params:[e.owner],signal:e.signal})}async getCoinMetadata({coinType:e,signal:r}){return e&&Et(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getCoinMetadata",params:[e],signal:r})}async getTotalSupply({coinType:e,signal:r}){return e&&Et(e)&&(e=(await this.core.mvr.resolveType({type:e})).type),await this.transport.request({method:"suix_getTotalSupply",params:[e],signal:r})}async call(e,r,{signal:n}={}){return await this.transport.request({method:e,params:r,signal:n})}async getMoveFunctionArgTypes({package:e,module:r,function:n,signal:s}){return e&&Yt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getMoveFunctionArgTypes",params:[e,r,n],signal:s})}async getNormalizedMoveModulesByPackage({package:e,signal:r}){return e&&Yt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveModulesByPackage",params:[e],signal:r})}async getNormalizedMoveModule({package:e,module:r,signal:n}){return e&&Yt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveModule",params:[e,r],signal:n})}async getNormalizedMoveFunction({package:e,module:r,function:n,signal:s}){return e&&Yt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveFunction",params:[e,r,n],signal:s})}async getNormalizedMoveStruct({package:e,module:r,struct:n,signal:s}){return e&&Yt(e)&&(e=(await this.core.mvr.resolvePackage({package:e})).package),await this.transport.request({method:"sui_getNormalizedMoveStruct",params:[e,r,n],signal:s})}async getOwnedObjects(e){if(!e.owner||!kr(ve(e.owner)))throw new Error("Invalid Sui address");const r=e.filter?{...e.filter}:void 0;return r&&"MoveModule"in r&&Yt(r.MoveModule.package)?r.MoveModule={module:r.MoveModule.module,package:(await this.core.mvr.resolvePackage({package:r.MoveModule.package})).package}:r&&"StructType"in r&&Et(r.StructType)&&(r.StructType=(await this.core.mvr.resolveType({type:r.StructType})).type),await this.transport.request({method:"suix_getOwnedObjects",params:[e.owner,{filter:r,options:e.options},e.cursor,e.limit],signal:e.signal})}async getObject(e){if(!e.id||!pc(tn(e.id)))throw new Error("Invalid Sui Object id");return await this.transport.request({method:"sui_getObject",params:[e.id,e.options],signal:e.signal})}async tryGetPastObject(e){return await this.transport.request({method:"sui_tryGetPastObject",params:[e.id,e.version,e.options],signal:e.signal})}async multiGetObjects(e){if(e.ids.forEach(n=>{if(!n||!pc(tn(n)))throw new Error(`Invalid Sui Object id ${n}`)}),e.ids.length!==new Set(e.ids).size)throw new Error(`Duplicate object ids in batch call ${e.ids}`);return await this.transport.request({method:"sui_multiGetObjects",params:[e.ids,e.options],signal:e.signal})}async queryTransactionBlocks({filter:e,options:r,cursor:n,limit:s,order:i,signal:a}){return e&&"MoveFunction"in e&&Yt(e.MoveFunction.package)&&(e={...e,MoveFunction:{package:(await this.core.mvr.resolvePackage({package:e.MoveFunction.package})).package}}),await this.transport.request({method:"suix_queryTransactionBlocks",params:[{filter:e,options:r},n,s,(i||"descending")==="descending"],signal:a})}async getTransactionBlock(e){if(!mm(e.digest))throw new Error("Invalid Transaction digest");return await this.transport.request({method:"sui_getTransactionBlock",params:[e.digest,e.options],signal:e.signal})}async multiGetTransactionBlocks(e){if(e.digests.forEach(n=>{if(!mm(n))throw new Error(`Invalid Transaction digest ${n}`)}),e.digests.length!==new Set(e.digests).size)throw new Error(`Duplicate digests in batch call ${e.digests}`);return await this.transport.request({method:"sui_multiGetTransactionBlocks",params:[e.digests,e.options],signal:e.signal})}async executeTransactionBlock({transactionBlock:e,signature:r,options:n,requestType:s,signal:i}){const a=await this.transport.request({method:"sui_executeTransactionBlock",params:[typeof e=="string"?e:St(e),Array.isArray(r)?r:[r],n],signal:i});if(s==="WaitForLocalExecution")try{await this.waitForTransaction({digest:a.digest})}catch{}return a}async signAndExecuteTransaction({transaction:e,signer:r,...n}){let s;e instanceof Uint8Array?s=e:(e.setSenderIfNotSet(r.toSuiAddress()),s=await e.build({client:this}));const{signature:i,bytes:a}=await r.signTransaction(s);return this.executeTransactionBlock({transactionBlock:a,signature:i,...n})}async getTotalTransactionBlocks({signal:e}={}){const r=await this.transport.request({method:"sui_getTotalTransactionBlocks",params:[],signal:e});return BigInt(r)}async getReferenceGasPrice({signal:e}={}){const r=await this.transport.request({method:"suix_getReferenceGasPrice",params:[],signal:e});return BigInt(r)}async getStakes(e){if(!e.owner||!kr(ve(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getStakes",params:[e.owner],signal:e.signal})}async getStakesByIds(e){return e.stakedSuiIds.forEach(r=>{if(!r||!pc(tn(r)))throw new Error(`Invalid Sui Stake id ${r}`)}),await this.transport.request({method:"suix_getStakesByIds",params:[e.stakedSuiIds],signal:e.signal})}async getLatestSuiSystemState({signal:e}={}){return await this.transport.request({method:"suix_getLatestSuiSystemState",params:[],signal:e})}async queryEvents({query:e,cursor:r,limit:n,order:s,signal:i}){return e&&"MoveEventType"in e&&Et(e.MoveEventType)&&(e={...e,MoveEventType:(await this.core.mvr.resolveType({type:e.MoveEventType})).type}),e&&"MoveEventModule"in e&&Yt(e.MoveEventModule.package)&&(e={...e,MoveEventModule:{module:e.MoveEventModule.module,package:(await this.core.mvr.resolvePackage({package:e.MoveEventModule.package})).package}}),"MoveModule"in e&&Yt(e.MoveModule.package)&&(e={...e,MoveModule:{module:e.MoveModule.module,package:(await this.core.mvr.resolvePackage({package:e.MoveModule.package})).package}}),await this.transport.request({method:"suix_queryEvents",params:[e,r,n,(s||"descending")==="descending"],signal:i})}async subscribeEvent(e){return this.transport.subscribe({method:"suix_subscribeEvent",unsubscribe:"suix_unsubscribeEvent",params:[e.filter],onMessage:e.onMessage,signal:e.signal})}async subscribeTransaction(e){return this.transport.subscribe({method:"suix_subscribeTransaction",unsubscribe:"suix_unsubscribeTransaction",params:[e.filter],onMessage:e.onMessage,signal:e.signal})}async devInspectTransactionBlock(e){var n,s;let r;if(g6(e.transactionBlock))e.transactionBlock.setSenderIfNotSet(e.sender),r=St(await e.transactionBlock.build({client:this,onlyTransactionKind:!0}));else if(typeof e.transactionBlock=="string")r=e.transactionBlock;else if(e.transactionBlock instanceof Uint8Array)r=St(e.transactionBlock);else throw new Error("Unknown transaction block format.");return(n=e.signal)==null||n.throwIfAborted(),await this.transport.request({method:"sui_devInspectTransactionBlock",params:[e.sender,r,(s=e.gasPrice)==null?void 0:s.toString(),e.epoch],signal:e.signal})}async dryRunTransactionBlock(e){return await this.transport.request({method:"sui_dryRunTransactionBlock",params:[typeof e.transactionBlock=="string"?e.transactionBlock:St(e.transactionBlock)]})}async getDynamicFields(e){if(!e.parentId||!pc(tn(e.parentId)))throw new Error("Invalid Sui Object id");return await this.transport.request({method:"suix_getDynamicFields",params:[e.parentId,e.cursor,e.limit],signal:e.signal})}async getDynamicFieldObject(e){return await this.transport.request({method:"suix_getDynamicFieldObject",params:[e.parentId,e.name],signal:e.signal})}async getLatestCheckpointSequenceNumber({signal:e}={}){const r=await this.transport.request({method:"sui_getLatestCheckpointSequenceNumber",params:[],signal:e});return String(r)}async getCheckpoint(e){return await this.transport.request({method:"sui_getCheckpoint",params:[e.id],signal:e.signal})}async getCheckpoints(e){return await this.transport.request({method:"sui_getCheckpoints",params:[e.cursor,e==null?void 0:e.limit,e.descendingOrder],signal:e.signal})}async getCommitteeInfo(e){return await this.transport.request({method:"suix_getCommitteeInfo",params:[e==null?void 0:e.epoch],signal:e==null?void 0:e.signal})}async getNetworkMetrics({signal:e}={}){return await this.transport.request({method:"suix_getNetworkMetrics",params:[],signal:e})}async getAddressMetrics({signal:e}={}){return await this.transport.request({method:"suix_getLatestAddressMetrics",params:[],signal:e})}async getEpochMetrics(e){return await this.transport.request({method:"suix_getEpochMetrics",params:[e==null?void 0:e.cursor,e==null?void 0:e.limit,e==null?void 0:e.descendingOrder],signal:e==null?void 0:e.signal})}async getAllEpochAddressMetrics(e){return await this.transport.request({method:"suix_getAllEpochAddressMetrics",params:[e==null?void 0:e.descendingOrder],signal:e==null?void 0:e.signal})}async getEpochs(e){return await this.transport.request({method:"suix_getEpochs",params:[e==null?void 0:e.cursor,e==null?void 0:e.limit,e==null?void 0:e.descendingOrder],signal:e==null?void 0:e.signal})}async getMoveCallMetrics({signal:e}={}){return await this.transport.request({method:"suix_getMoveCallMetrics",params:[],signal:e})}async getCurrentEpoch({signal:e}={}){return await this.transport.request({method:"suix_getCurrentEpoch",params:[],signal:e})}async getValidatorsApy({signal:e}={}){return await this.transport.request({method:"suix_getValidatorsApy",params:[],signal:e})}async getChainIdentifier({signal:e}={}){const r=await this.getCheckpoint({id:"0",signal:e}),n=lo(r.digest);return Xi(n.slice(0,4))}async resolveNameServiceAddress(e){return await this.transport.request({method:"suix_resolveNameServiceAddress",params:[e.name],signal:e.signal})}async resolveNameServiceNames({format:e="dot",...r}){const{nextCursor:n,hasNextPage:s,data:i}=await this.transport.request({method:"suix_resolveNameServiceNames",params:[r.address,r.cursor,r.limit],signal:r.signal});return{hasNextPage:s,nextCursor:n,data:i.map(a=>AP(a,e))}}async getProtocolConfig(e){return await this.transport.request({method:"sui_getProtocolConfig",params:[e==null?void 0:e.version],signal:e==null?void 0:e.signal})}async verifyZkLoginSignature(e){return await this.transport.request({method:"sui_verifyZkLoginSignature",params:[e.bytes,e.signature,e.intentScope,e.author],signal:e.signal})}async waitForTransaction({signal:e,timeout:r=60*1e3,pollInterval:n=2*1e3,...s}){const i=AbortSignal.timeout(r),a=new Promise((o,c)=>{i.addEventListener("abort",()=>c(i.reason))});for(a.catch(()=>{});!i.aborted;){e==null||e.throwIfAborted();try{return await this.getTransactionBlock(s)}catch{await Promise.race([new Promise(o=>setTimeout(o,n)),a])}}throw i.throwIfAborted(),new Error("Unexpected error while waiting for transaction block.")}}class A4{constructor(e,r,n,s){this.client=new Om({url:fm(n)}),this.url=e instanceof m.Url?e:new m.Url(e),this.account=r,this.network=n,this.auth=s,this.relayer=new li(this.auth,this.url)}get htlcActorAddress(){var e,r;return"accounts"in this.account?((r=(e=this.account.accounts)==null?void 0:e[0])==null?void 0:r.address)??"":this.account.toSuiAddress()}async initiate(e){var r,n,s;if(!e)return m.Err("Order is required");if(D.isSuiOrderResponse(e))return this.initiateWithCreateOrderResponse(e);try{const{source_swap:i}=e,a=BigInt(i.amount),o=i.asset,c=i.redeemer,u=i.secret_hash,l=await ji(i.asset,this.url,this.auth);if(!l.ok)return m.Err(l.error);const{tokenAddress:f}=l.val,p=new eh;p.setSender(this.htlcActorAddress);const[d]=p.splitCoins(p.gas,[a]);p.moveCall({target:`${Gf[this.network].packageId}::${Gf[this.network].moduleName}::initiate`,typeArguments:[f],arguments:[p.object(o),p.pure.address(this.htlcActorAddress),p.pure.address(c),p.pure.vector("u8",Buffer.from(u,"hex")),p.pure.u64(a),p.pure.u256(i.timelock),p.pure.vector("u8",Buffer.from("")),d,p.object(mO)]});const b=await p.build({client:this.client}),g=await this.client.dryRunTransactionBlock({transactionBlock:b});if(g.effects.status.status==="failure")return m.Err(`${g.effects.status.error}`);let A;if("features"in this.account?A=await((r=this.account.features[C0.SuiSignAndExecuteTransaction])==null?void 0:r.signAndExecuteTransaction({transaction:p,account:this.account.accounts[0],chain:`sui:${this.network}`})):A=await this.client.signAndExecuteTransaction({signer:this.account,transaction:p,options:{showEffects:!0}}),!A)return m.Err("Failed to initiate");const S=await this.client.waitForTransaction({digest:A.digest,options:{showEffects:!0}});return((n=S.effects)==null?void 0:n.status.status)==="failure"?m.Err(`Failed to initiate: ${(s=S.effects)==null?void 0:s.status.error}`):m.Ok(S.digest)}catch(i){return m.Err(i)}}async initiateWithCreateOrderResponse(e){var o,c,u;const{ptb_bytes:r}=e,s=await new Om({url:fm("testnet")}).getReferenceGasPrice(),i=1e7,a=eh.fromKind(new Uint8Array(r));a.setSender(this.htlcActorAddress),a.setGasPrice(s),a.setGasBudget(i);try{let l;if("features"in this.account?l=await((o=this.account.features[C0.SuiSignAndExecuteTransaction])==null?void 0:o.signAndExecuteTransaction({transaction:a,account:this.account.accounts[0],chain:`sui:${this.network}`})):l=await this.client.signAndExecuteTransaction({signer:this.account,transaction:a,options:{showEffects:!0}}),!l)return m.Err("Failed to initiate");const f=await this.client.waitForTransaction({digest:l.digest,options:{showEffects:!0}});return((c=f.effects)==null?void 0:c.status.status)==="failure"?m.Err(`Failed to initiate: ${(u=f.effects)==null?void 0:u.status.error}`):m.Ok(f.digest)}catch(l){return m.Err(String(l))}}async redeem(e,r){const n=await this.relayer.redeem(e.order_id,r);return n.error?m.Err(n.error):n.val?m.Ok(n.val):m.Err("Redeem: No result found")}async refund(){return m.Err("Refund is taken care of by the relayer")}}function Bm(t){let e=t.startsWith("0x")?t.slice(2):t;return e=e.toLowerCase(),e.length>64&&(e=e.slice(e.length-64)),e.length<64&&(e=e.padStart(64,"0")),`0x${e}`}class S4{constructor(e,r,n,s){this.url=typeof e=="string"?new m.Url(e):e,this.auth=n,s instanceof R0.TronWeb?(this.wallet={tronweb:s},this.tronweb=s):(this.wallet={adapter:s},this.tronweb=new R0.TronWeb({fullHost:Fm[r]})),this.relayer=new li(this.auth,this.url)}get htlcActorAddress(){var e,r,n;return(e=this.wallet.adapter)!=null&&e.address?this.wallet.adapter.address:this.wallet.tronweb?((r=this.wallet.tronweb.defaultAddress)==null?void 0:r.base58)||"":((n=this.tronweb.defaultAddress)==null?void 0:n.base58)||""}async initiate(e){if(D.isEvmOrderResponse(e))return this.initiateDirectContractCall(e);try{const{source_swap:r}=e,n=await ji(r.asset,this.url,this.auth);if(!n.ok)return m.Err(n.error);const{htlcAddress:s}=n.val;return await this.executeContractCall({contractAddress:s,method:"initiate(address,uint256,uint256,bytes32,bytes)",parameters:[{type:"address",value:r.redeemer},{type:"uint256",value:r.timelock},{type:"uint256",value:BigInt(r.amount)},{type:"bytes32",value:Bm(String(r.secret_hash))},{type:"bytes",value:"0x"}],options:{}})}catch(r){return m.Err(`Failed to initiate: ${String(r)}`)}}async initiateDirectContractCall(e){var f;if(!this.htlcActorAddress)return m.Err("No HTLC actor address found");if(e.approval_transaction){const p=await this.executeApprovalTransaction(e);if(p.error)return m.Err(p.error)}if(!e.initiate_transaction)return m.Err("No initiate transaction data available for direct contract call");if(!((f=e.typed_data)!=null&&f.message))return m.Err("No typed data message found in order response");const{to:r,value:n,gas_limit:s}=e.initiate_transaction,{redeemer:i,timelock:a,amount:o,secretHash:c,destinationData:u}=e.typed_data.message,l=await this.executeContractCall({contractAddress:r,method:"initiate(address,uint256,uint256,bytes32,bytes)",parameters:[{type:"address",value:i},{type:"uint256",value:a},{type:"uint256",value:o},{type:"bytes32",value:Bm(String(c))},{type:"bytes",value:u}],options:{feeLimit:parseInt(s),callValue:n?parseInt(n):0}});return!l.val||l.error?m.Err("Failed to initiate"+(l.error||"")):await this.waitForTransactionConfirmation(l.val)}async executeApprovalTransaction(e){if(console.log("No Allowance found, Executing Approval"),!this.htlcActorAddress)return m.Err("No HTLC actor address found");const r=e.approval_transaction;if(!r)return m.Ok("No approval transaction required");try{const n="0x"+r.data.slice(10),s=this.tronweb.utils.abi.decodeParams(["spender","amount"],["address","uint256"],n,!1);return await this.executeContractCall({contractAddress:r.to,method:"approve(address,uint256)",parameters:[{type:"address",value:s.spender},{type:"uint256",value:s.amount.toString()}],options:{feeLimit:Number(r.gas_limit),callValue:0}})}catch(n){return m.Err(`Approval transaction failed: ${String(n)}`)}}async executeContractCall({contractAddress:e,method:r,parameters:n,options:s}){try{const i=await this.tronweb.transactionBuilder.triggerSmartContract(e,r,s,n,this.htlcActorAddress);if(!(i!=null&&i.transaction))return m.Err("Failed to build transaction");const a=await this.signTransaction(i.transaction);if(a.error)return m.Err(a.error);const o=a.val;return o?await this.broadcastWithRetry(o):m.Err("Signing returned no transaction")}catch(i){return m.Err(`Failed to execute contract call: ${String(i)}`)}}async broadcastWithRetry(e){for(let n=0;n<5;n++)try{const s=await this.tronweb.trx.sendRawTransaction(e);if(s.result&&s.txid)return m.Ok(s.txid);const i=typeof s.code=="string"?parseInt(s.code):s.code;if(this.isRetryableError(i)&&n<4){await this.sleep(Math.min(1e3*Math.pow(2,n),8e3));continue}const a=s.message||`Error code: ${s.code}`;return m.Err(String(a))}catch(s){if(n<4){await this.sleep(Math.min(1e3*Math.pow(2,n),8e3));continue}return m.Err(String(s))}return m.Err("Max broadcast retries exceeded")}isRetryableError(e){if(e===void 0)return!0;const r=typeof e=="string"?parseInt(e):e;return r===8||r===9||r===10||r===11||r===4}sleep(e){return new Promise(r=>setTimeout(r,e))}async signTransaction(e){if(this.wallet.adapter)try{const r=await this.wallet.adapter.signTransaction(e);return m.Ok(r)}catch(r){return m.Err(`Adapter signing failed: ${String(r)}`)}if(this.wallet.tronweb)try{const r=await this.wallet.tronweb.trx.sign(e);return m.Ok(r)}catch(r){return m.Err(`TronWeb signing failed: ${String(r)}`)}return m.Err("No signing method available")}async waitForTransactionConfirmation(e,r=15,n=3e3){var s,i,a,o;for(let c=0;c<r;c++){try{const u=await this.tronweb.trx.getTransaction(e);if(!u){await this.sleep(n);continue}if(((i=(s=u.ret)==null?void 0:s[0])==null?void 0:i.contractRet)==="SUCCESS")return m.Ok(u.txID);if(((o=(a=u.ret)==null?void 0:a[0])==null?void 0:o.contractRet)==="FAILED")return m.Err("Transaction failed on-chain")}catch{console.log(`Checking tx ${c+1}/${r}...`)}await this.sleep(n)}return m.Err("Transaction confirmation timeout")}async redeem(e,r){const n=await this.relayer.redeem(e.order_id,r);return n.error?m.Err(n.error):m.Ok(n.val)}async refund(){return m.Err("Refund is taken care of by the relayer")}}const x4=25*60*60*1e3;class S6{constructor(e,r,n,s){this.url=typeof e=="string"?new m.Url(e):e,this.auth=n,this.wallet=s,this.client=new N0.Client(Mm[r],{}),this.relayer=new li(this.auth,this.url)}isXrplWallet(e){return typeof e=="object"&&e!==null&&"classicAddress"in e&&typeof e.classicAddress=="string"}isCrossmarkWallet(e){var r;return typeof e=="object"&&e!==null&&"sync"in e&&"async"in e&&typeof e.sync=="object"&&typeof((r=e.sync)==null?void 0:r.getAddress)=="function"}get htlcActorAddress(){return this.isXrplWallet(this.wallet)?this.wallet.classicAddress:this.isCrossmarkWallet(this.wallet)?this.wallet.sync.getAddress()??"":""}async initiate(e){try{return D.isXrplOrderResponse(e)?this.initiateFromOrderResponse(e):this.initiateFromOrder(e)}catch(r){return m.Err(`Failed to initiate: ${String(r)}`)}}async initiateFromOrderResponse(e){try{if(!this.htlcActorAddress)return m.Err("No HTLC actor address found");const n=e.escrow_create_tx,s={TransactionType:"EscrowCreate",Account:n.Account,Amount:n.Amount,Destination:n.Destination,Condition:n.Condition,CancelAfter:n.CancelAfter};return await this.submitTransaction(s)}catch(r){return m.Err(`Failed to initiate from order response: ${String(r)}`)}}async initiateFromOrder(e){try{const r=this.htlcActorAddress;if(!r)return m.Err("No HTLC actor address found");const{source_swap:n}=e,s=m.trim0x(n.secret_hash),i={Account:r,Amount:n.amount,Destination:n.redeemer,Condition:this.buildCondition(s),CancelAfter:N0.isoTimeToRippleTime(new Date(new Date(n.created_at).getTime()+x4)),TransactionType:"EscrowCreate"};return await this.submitTransaction(i)}catch(r){return m.Err(`Failed to initiate from order: ${String(r)}`)}}async redeem(e,r){const n=await this.relayer.redeem(e.order_id,r);return n.error?m.Err(n.error):m.Ok(n.val)}async refund(){return m.Err("Refund is taken care of by the relayer")}async submitTransaction(e){try{this.client.isConnected()||await this.client.connect();const r=this.htlcActorAddress;if(!r)return m.Err("No HTLC actor address found");const n=await this.client.autofill(e);n.Account=r;const s=await this.signPreparedTransaction(n),i=await this.client.submitAndWait(s),a=i.result.meta;return(a==null?void 0:a.TransactionResult)==="tesSUCCESS"?m.Ok(i.result.hash):m.Err(`Transaction failed: ${String((a==null?void 0:a.TransactionResult)??"Unknown error")}`)}catch(r){return m.Err(`Transaction submission failed: ${String(r)}`)}finally{this.client.isConnected()&&await this.client.disconnect()}}async signPreparedTransaction(e){if(this.isXrplWallet(this.wallet))return this.wallet.sign(e).tx_blob;if(this.isCrossmarkWallet(this.wallet))return this.wallet.sync.getAddress()||await this.wallet.async.signInAndWait(),(await this.wallet.async.signAndWait(e)).response.data.txBlob;throw new Error("Unsupported wallet type")}buildCondition(e){return"A0258020"+e.toUpperCase()+"810120"}}const k4=t=>{if(t)if(typeof t=="string"){const e=m.DigestKey.from(t);if(!e.ok)throw new Error(e.error);return e.val}else return t},Hf=t=>typeof t=="string"?new m.ApiKey(t):t;class mo extends m.EventBroker{get isInitialized(){return!!this.digestKey}constructor(e,r){super(),this.digestKey=e,this.walletClient=r}static fromDigestKey(e){return new mo(m.trim0x(e))}static fromWalletClient(e){return new mo(void 0,e)}async initialize(){if(this.digestKey)return m.Ok("Already initialized");const e=await this.deriveDigestKeyFromWalletClient();return e.error?m.Err(e.error):(this.emit("initialized",!0),m.Ok("Initialized"))}async deriveDigestKeyFromWalletClient(){if(!this.walletClient)return m.Err("No walletClient found");if(!this.walletClient.account)return m.Err("No account found");try{const e=await this.walletClient.signTypedData({account:this.walletClient.account,types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"}],Data:[{name:"Message",type:"string"},{name:"Version",type:"string"},{name:"Nonce",type:"uint256"}]},domain:{name:"GARDEN FINANCE",version:"1"},primaryType:"Data",message:{Message:"Initialize your account",Version:"1.0.2",Nonce:1n}});return this.digestKey=m.trim0x(Aa(e)),this.emit("initialized",!0),m.Ok(this.digestKey)}catch(e){return m.Err("Failed to initialize: "+e)}}async getDigestKey(){if(!this.digestKey&&!this.walletClient)return m.Err("No private key or wallet client found");if(!this.digestKey&&this.walletClient){const e=await this.deriveDigestKeyFromWalletClient();if(e.error)return m.Err(e.error)}return this.digestKey?m.Ok(this.digestKey):m.Err("No private key found")}async generateSecret(e){const r=await this.signMessage(e);if(!r.ok)return m.Err(r.error);const n=Aa(m.with0x(r.val)),s=Aa(n);return m.Ok({secret:n,secretHash:s})}async signMessage(e){if(!this.digestKey){const u=await this.getDigestKey();if(!u.ok)return m.Err(u.error);this.digestKey=u.val}const r=mc.ECPairFactory(mr),n="Garden.fi"+e.toString(),s=Buffer.from(n,"utf8"),i=Aa(s),a=Buffer.from(m.trim0x(this.digestKey),"hex");if(a.length!==32)return m.Err("Invalid private key length. Expected 32 bytes.");const c=r.fromPrivateKey(a).sign(Buffer.from(m.trim0x(i),"hex"));return m.Ok(c.toString("hex"))}}class T4{constructor(e={}){const r={stdTTL:e.ttl?e.ttl/1e3:3600,checkperiod:600};this.cache=new O6(r)}makeKey(e,r){return`${e}:${r}`}set(e,r,n,s){const i=this.makeKey(e,r);s?this.cache.set(i,n,s/1e3):this.cache.set(i,n)}get(e,r){const n=this.makeKey(e,r);return this.cache.get(n)}remove(e,r){const n=this.makeKey(e,r);this.cache.del(n)}clear(e){if(e){const r=this.cache.keys().filter(n=>n.startsWith(`${e}:`));this.cache.del(r)}else this.cache.flushAll()}setBitcoinRedeem(e,r,n){this.set("bitcoinRedeem",e,r,n)}getBitcoinRedeem(e){return this.get("bitcoinRedeem",e)}setOrderExecution(e,r,n,s,i){const a=this.makeOrderKey(e,r),o={txHash:n,timeStamp:Date.now(),btcRedeemUTXO:s};this.set("orderExecutor",a,o,i)}getOrderExecution(e,r){const n=this.makeOrderKey(e,r);return this.get("orderExecutor",n)}removeOrderExecution(e,r){const n=this.makeOrderKey(e,r);this.remove("orderExecutor",n)}makeOrderKey(e,r){return`${r}_${e.order_id??e.created_at}`}setSacpCache(e,r,n){this.set("refundSacp",e,r,n)}getSacpCache(e){return this.get("refundSacp",e)}has(e,r){const n=this.makeKey(e,r);return this.cache.has(n)}peek(e,r){return this.get(e,r)}getRemainingTTL(e,r){const n=this.makeKey(e,r),s=this.cache.getTtl(n);if(s===void 0)return-1;const i=Date.now();return Math.max(0,s-i)}}var bo,go,wo,Ne,$i,as;class _4{constructor(e,r,n,s,i,a){Ts(this,bo);Ts(this,go);Ts(this,wo);Ts(this,Ne);Ts(this,$i);Ts(this,as);this.isBackgroundServiceRunning=!1,this.stopBackgroundExecution=null,this.htlcs=r,this.events=a,_s(this,bo,e),_s(this,go,n),_s(this,wo,mo.fromDigestKey(e.digestKey)),_s(this,Ne,new T4),_s(this,$i,s),_s(this,as,i)}async getAddressesFromHTLCs(){var n,s,i,a,o,c,u;const e=new Set;return[(n=this.htlcs.evm)==null?void 0:n.htlcActorAddress,(s=this.htlcs.sui)==null?void 0:s.htlcActorAddress,(i=this.htlcs.solana)==null?void 0:i.htlcActorAddress,(a=this.htlcs.starknet)==null?void 0:a.htlcActorAddress,(o=this.htlcs.bitcoin)==null?void 0:o.htlcActorAddress,(c=this.htlcs.tron)==null?void 0:c.htlcActorAddress,(u=this.htlcs.xrpl)==null?void 0:u.htlcActorAddress].filter(l=>!!l&&l.length>0).forEach(l=>e.add(l.toLowerCase())),Array.from(e)}start(e=5e3,r){this.isBackgroundServiceRunning||this.stopBackgroundExecution||(this.isBackgroundServiceRunning=!0,(async()=>{try{if(r){this.stop();return}const n=await this.execute(e);n&&(this.stopBackgroundExecution=n)}catch(n){console.error("Error starting background executor:",n),this.isBackgroundServiceRunning=!1}})())}stop(){if(this.stopBackgroundExecution){try{this.stopBackgroundExecution()}catch{console.error("Error stopping background executor")}this.stopBackgroundExecution=null}this.isBackgroundServiceRunning=!1}async execute(e=5e3){const r=await this.getAddressesFromHTLCs();r.length===0&&r.push(Se(this,bo).userId.toLowerCase());let n=!1,s=null;const i=async()=>{if(!n){n=!0;try{const a=r.map(async c=>{try{const u=await Se(this,go).getOrders({from_owner:c,status:D.OrderLifecycle.pending,per_page:500});return u.ok?u.val.data:(this.events.emit("error",{},`Failed to fetch orders for address ${c}: ${u.error}`),[])}catch(u){return this.events.emit("error",{},`Failed to fetch orders for address ${c}: ${u}`),[]}}),o=await Promise.all(a);this.events.emit("onPendingOrdersChanged",o.flat()),await this.processOrderActions(o.flat())}finally{n=!1}}};return await i(),s=setInterval(i,e),()=>{s&&clearInterval(s)}}async processOrderActions(e){const r=new Set([D.OrderStatus.InitiateDetected,D.OrderStatus.AwaitingRefund,D.OrderStatus.Initiated,D.OrderStatus.RefundDetected,D.OrderStatus.Refunded,D.OrderStatus.Expired]),n=e.map(async s=>{try{D.isBitcoin(s.source_swap.chain)&&r.has(s.status)&&!D.isCompleted(s)&&await this.postRefundSACP(s),D.parseAction(s)===D.OrderAction.Redeem&&await this.handleRedeemAction(s)}catch(i){this.events.emit("error",s,`Error processing order ${s.order_id}: ${i}`)}});await Promise.all(n)}async handleRedeemAction(e){const r=await Se(this,wo).generateSecret(e.nonce);if(!r.ok){this.events.emit("error",e,r.error);return}const n=m.trim0x(r.val.secretHash),s=m.trim0x(e.source_swap.secret_hash);if(n!==s){this.events.emit("log",e.order_id,"skipping redeem: secret hash mismatch");return}const i=r.val.secret,a=D.getBlockchainType(e.destination_swap.chain),c={[D.BlockchainType.evm]:()=>this.evmRedeem(e,i),[D.BlockchainType.bitcoin]:()=>this.btcRedeem(e,i),[D.BlockchainType.starknet]:()=>this.starknetRedeem(e,i),[D.BlockchainType.solana]:()=>this.solRedeem(e,i),[D.BlockchainType.xrpl]:()=>this.xrplRedeem(e,i),[D.BlockchainType.sui]:()=>this.suiRedeem(e,i),[D.BlockchainType.tron]:()=>this.tronRedeem(e,i)}[a];c?await c():this.events.emit("error",e,`Unsupported chain: ${e.destination_swap.chain}`)}async evmRedeem(e,r){if(this.events.emit("log",e.order_id,"executing evm redeem"),Se(this,Ne).getOrderExecution(e,D.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.evm){this.events.emit("error",e,"EVM HTLC is required");return}const s=await this.htlcs.evm.redeem(e,r);if(!s.ok){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,s.val),this.events.emit("success",e,D.OrderAction.Redeem,s.val)}async starknetRedeem(e,r){if(this.events.emit("log",e.order_id,"executing starknet redeem"),Se(this,Ne).getOrderExecution(e,D.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.starknet){this.events.emit("error",e,"Starknet HTLC is required");return}const s=await this.htlcs.starknet.redeem(e,r);if(!s.ok){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,s.val),this.events.emit("success",e,D.OrderAction.Redeem,s.val))}async solRedeem(e,r){if(this.events.emit("log",e.order_id,"executing sol redeem"),Se(this,Ne).getOrderExecution(e,D.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.solana){this.events.emit("error",e,"Solana HTLC is required");return}const s=await this.htlcs.solana.redeem(e,r);if(s.error){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,s.val),this.events.emit("success",e,D.OrderAction.Redeem,s.val))}async suiRedeem(e,r){if(this.events.emit("log",e.order_id,"executing sui redeem"),Se(this,Ne).getOrderExecution(e,D.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.sui){this.events.emit("error",e,"Sui HTLC is required");return}const s=await this.htlcs.sui.redeem(e,r);if(s.error){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,s.val),this.events.emit("success",e,D.OrderAction.Redeem,s.val))}async tronRedeem(e,r){if(this.events.emit("log",e.order_id,"executing tron redeem"),Se(this,Ne).getOrderExecution(e,D.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.tron){this.events.emit("error",e,"Tron HTLC is required");return}const s=await this.htlcs.tron.redeem(e,r);if(s.error){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,s.val),this.events.emit("success",e,D.OrderAction.Redeem,s.val))}async xrplRedeem(e,r){if(this.events.emit("log",e.order_id,"executing xrpl redeem"),Se(this,Ne).getOrderExecution(e,D.OrderAction.Redeem)){this.events.emit("log",e.order_id,"already redeemed");return}if(!this.htlcs.xrpl){this.events.emit("error",e,"XRPL HTLC is required");return}const s=await this.htlcs.xrpl.redeem(e,r);if(s.error){this.events.emit("error",e,s.error),s.error.includes("Order already redeemed")&&Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,e.destination_swap.redeem_tx_hash);return}s.val&&(Se(this,Ne).setOrderExecution(e,D.OrderAction.Redeem,s.val),this.events.emit("success",e,D.OrderAction.Redeem,s.val))}async btcRedeem(e,r){var o,c;const n=(o=this.htlcs.bitcoin)==null?void 0:o.getProvider();if(!n){this.events.emit("error",e,"Bitcoin provider not found");return}const s=Se(this,Ne).getBitcoinRedeem(e.order_id),i=(c=e.destination_swap.initiate_tx_hash.split(",").at(-1))==null?void 0:c.split(":").at(0);if(!i){this.events.emit("error",e,"Failed to get initiate_tx_hash");return}let a=!1;if(s)if(s.redeemedFromUTXO&&s.redeemedFromUTXO!==i)a=!0,this.events.emit("log",e.order_id,"rbf btc redeem");else if(s.redeemedAt&&Date.now()-s.redeemedAt>1e3*60*15)this.events.emit("log",e.order_id,"redeem not confirmed in last 15 minutes"),a=!0;else{this.events.emit("log",e.order_id,"btcRedeem: already redeemed");return}else if(e.destination_swap.redeem_tx_hash&&!Number(e.destination_swap.redeem_block_number))try{const u=await(await n).getTransaction(e.destination_swap.redeem_tx_hash);let l=!1;for(const f of u.vin)if(f.txid===i){l=!0;break}if(l){this.events.emit("log",e.order_id,"already a valid redeem");let f=0;try{const[p]=await(await n).getTransactionTimes([e.destination_swap.redeem_tx_hash]);p!==0&&(f=p)}catch{f=Date.now()}Se(this,Ne).setBitcoinRedeem(e.order_id,{redeemedFromUTXO:i,redeemedAt:f,redeemTxHash:e.destination_swap.redeem_tx_hash});return}a=!0}catch(u){if(u.message.includes("Transaction not found"))a=!0;else{this.events.emit("error",e,"Failed to get redeem tx: "+u);return}}this.events.emit("log",e.order_id,"executing btc redeem");try{if(!this.htlcs.bitcoin){this.events.emit("error",e,"Bitcoin HTLC is required");return}const u=await this.htlcs.bitcoin.getRedeemHex(e,m.trim0x(r),a?[i]:[]);if(!u.ok){this.events.emit("error",e,"Failed to get redeem hex");return}const l=await this.broadcastRedeemTx(u.val,e.order_id);if(!l.ok){this.events.emit("error",e,l.error||"Failed to broadcast redeem tx");return}a?(this.events.emit("log",e.order_id,"rbf: btc redeem success"),this.events.emit("rbf",e,l.val)):this.events.emit("success",e,D.OrderAction.Redeem,l.val),Se(this,Ne).setBitcoinRedeem(e.order_id,{redeemedFromUTXO:i,redeemedAt:Date.now(),redeemTxHash:l.val})}catch(u){this.events.emit("error",e,"Failed btc redeem: "+u)}}async postRefundSACP(e){if(e.source_swap.delegate)try{if(!this.htlcs.bitcoin){this.events.emit("error",e,"Bitcoin HTLC is required");return}const n=await Se(this,$i).getAuthHeaders();if(n.error){this.events.emit("error",e,"Failed to get auth headers: "+n.error);return}const s=await m.Fetcher.post(new m.Url(Se(this,as).baseurl).endpoint("relayer/bitcoin/instant-refund-hash"),{body:JSON.stringify({order_id:e.order_id}),headers:{"Content-Type":"application/json",...n.val}});if(s.error||!s.result){this.events.emit("error",e,"Failed to get hash while posting instant refund SACP: "+s.error);return}const i=await this.htlcs.bitcoin.generateInstantRefundSACPWithHash(s.result),a=new m.Url(Se(this,as).baseurl).endpoint("relayer/bitcoin/instant-refund");(await m.Fetcher.post(a,{headers:{"Content-Type":"application/json",...n.val},body:JSON.stringify({order_id:e.order_id,signatures:i.val})})).ok&&Se(this,Ne).setSacpCache(e.order_id,{initTxHash:e.source_swap.initiate_tx_hash})}catch(n){this.events.emit("error",e,"Failed to generate and post SACP: "+n);return}}async broadcastRedeemTx(e,r){try{if(!Se(this,as))return m.Err("API not found");const n=new m.Url(Se(this,as).relayer).endpoint("/bitcoin/redeem "),s=await Se(this,$i).getAuthHeaders(),a=await(await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...s.val},body:JSON.stringify({redeem_tx_bytes:e,order_id:r})})).json();return a.status==="Ok"&&a.result?m.Ok(a.result):m.Err(a.error)}catch(n){return m.Err("Failed to broadcast redeem tx: "+n)}}}bo=new WeakMap,go=new WeakMap,wo=new WeakMap,Ne=new WeakMap,$i=new WeakMap,as=new WeakMap;class I4 extends m.EventBroker{emit(e,...r){super.emit(e,...r)}}class P0 extends D.Orderbook{constructor(e){const{api:r}=qf(e.environment);if(!r)throw new Error("API Key not found");super(new m.Url(r.baseurl),Hf(e.apiKey)),this._redeemServiceEnabled=!0,this.executeInterval=5e3,this._api=r,this._digestKey=k4(e.digestKey),this._auth=Hf(e.apiKey),this._quote=e.quote??new $b(this._api.baseurl,this._auth),this._htlcs=e.htlc??{},this._events=new I4,this._executor=this._digestKey?new _4(this._digestKey,this.htlcs,this,this._auth,this._api,this._events):void 0}static fromWallets(e){const r=Hf(e.apiKey),{api:n,network:s}=qf(e.environment);if(!n)throw new Error("API not found, invalid environment "+e.environment);const i=e.wallets?{evm:e.wallets.evm?new Uw(n.baseurl,e.wallets.evm,r):void 0,starknet:e.wallets.starknet?new Hw(n.baseurl,e.wallets.starknet,s,r):void 0,solana:e.wallets.solana?new t2(e.wallets.solana,new m.Url(n.baseurl),s,r,{programAddress:e.solanaProgramAddress}):void 0,sui:e.wallets.sui?new A4(n.baseurl,e.wallets.sui,s,r):void 0,bitcoin:e.wallets.bitcoin?new rE(e.wallets.bitcoin,s):void 0,tron:e.wallets.tron?new S4(n.baseurl,s,r,e.wallets.tron):void 0,xrpl:e.wallets.xrpl?new S6(n.baseurl,s,r,e.wallets.xrpl):void 0}:{};return new P0({htlc:i,...e})}get htlcs(){return{evm:this._htlcs.evm,starknet:this._htlcs.starknet,solana:this._htlcs.solana,sui:this._htlcs.sui,bitcoin:this._htlcs.bitcoin,tron:this._htlcs.tron,xrpl:this._htlcs.xrpl}}get quote(){return this._quote}get secretManager(){if(this._redeemServiceEnabled||!this._secretManager)throw new Error("Secret manager is not available");return this._secretManager}get digestKey(){return this._digestKey}get executor(){return this._executor}get redeemServiceEnabled(){return this._redeemServiceEnabled}async createSwap(e,r){const n=D.ChainAsset.from(e.fromAsset).blockchainType,s=await W6(n,this._htlcs);if(!s.ok)return m.Err(s.error);const i=await this.createOrder(e);if(!i.ok)return m.Err(i.error);const a=i.val;switch(r==null||r(Ta.orderCreated),r==null||r(Ta.orderInitiating),n){case D.BlockchainType.evm:if(!this._htlcs.evm||!D.isEvmOrderResponse(a))return m.Err("Order type does not match EVM blockchain type");{const o=await this._htlcs.evm.initiate(a);if(!o.ok)return m.Err(`EVM HTLC initiation failed: ${o.error}`)}break;case D.BlockchainType.solana:if(!this._htlcs.solana||!D.isSolanaOrderResponse(a))return m.Err("Order type does not match Solana blockchain type");{const o=await this._htlcs.solana.initiate(a);if(!o.ok)return m.Err(`Solana HTLC initiation failed: ${o.error}`)}break;case D.BlockchainType.starknet:if(!this._htlcs.starknet||!D.isStarknetOrderResponse(a))return m.Err("Order type does not match Starknet blockchain type");{const o=await this._htlcs.starknet.initiate(a);if(!o.ok)return m.Err(`Starknet HTLC initiation failed: ${o.error}`)}break;case D.BlockchainType.sui:if(!this._htlcs.sui||!D.isSuiOrderResponse(a))return m.Err("Order type does not match Sui blockchain type");{const o=await this._htlcs.sui.initiate(a);if(!o.ok)return m.Err(`Sui HTLC initiation failed: ${o.error}`)}break;case D.BlockchainType.tron:if(!this._htlcs.tron||!D.isEvmOrderResponse(a))return m.Err("Order type does not match Tron blockchain type");{const o=await this._htlcs.tron.initiate(a);if(!o.ok)return m.Err(`Tron HTLC initiation failed: ${o.error}`)}break;case D.BlockchainType.xrpl:if(!this._htlcs.xrpl||!D.isXrplOrderResponse(a))return m.Err("Order type does not match XRPL blockchain type");{const o=await this._htlcs.xrpl.initiate(a);if(!o.ok)return m.Err(`XRPL HTLC initiation failed: ${o.error}`)}break;case D.BlockchainType.bitcoin:return m.Ok(a);case D.BlockchainType.litecoin:return m.Ok(a);case D.BlockchainType.alpen_signet:return m.Ok(a);case D.BlockchainType.spark:return m.Ok(a);case D.BlockchainType.lightning:return m.Ok(a);default:return m.Err("Unsupported blockchain type for swap initiation")}return r==null||r(Ta.orderInitiated),m.Ok(a.order_id)}async createOrder(e){var T;if(m.hasKeys(e,["source","destination","nonce"]))return super.createOrder(e);const r=e,n=await this.validateAndFillParams(r);if(!n.ok)return m.Err(n.error??"Validation failed");const{sendAddress:s,receiveAddress:i,fromAsset:a,toAsset:o}=n.val,c=Date.now().toString();let u;if(!this.redeemServiceEnabled){const v=await this.secretManager.generateSecret(c);if(!v.ok)return m.Err(v.error);u=v.val.secretHash}const l=(T=r.addresses)==null?void 0:T.bitcoin,f=D.isBitcoin(D.ChainAsset.from(r.fromAsset).chain),p=D.isBitcoin(D.ChainAsset.from(r.toAsset).chain),d=!!u,b={source:{asset:a.toString(),owner:!r.sourceAddress&&f?l??s:s,delegate:d&&f?s:null,amount:r.sendAmount},destination:{asset:o.toString(),owner:!r.destinationAddress&&p?l??i:i,delegate:d&&p?i:null,amount:r.receiveAmount},nonce:Number(c),...!this.redeemServiceEnabled&&u?{secret_hash:m.trim0x(u)}:{},solver_id:r.solverId,...r.quoteId?{quote_id:r.quoteId}:{},affiliate_fees:r.affiliateFee,slippage:0},g=await super.createOrder(b);if(!g.ok)return m.Err(g.error);const A=D.ChainAsset.from(r.fromAsset).blockchainType,S=[D.BlockchainType.alpen_signet,D.BlockchainType.bitcoin,D.BlockchainType.litecoin,D.BlockchainType.spark].includes(A)?D.BlockchainType.bitcoin:[D.BlockchainType.tron].includes(A)?D.BlockchainType.evm:A;return g.val.type!==S&&g.val.type!==A?m.Err("Order response type does not match source blockchain type"):m.Ok(g.val)}async validateAndFillParams(e){var c;if(!e.fromAsset||!e.toAsset)return m.Err("Source and destination assets are required for swap");const r=D.ChainAsset.from(e.fromAsset),n=D.ChainAsset.from(e.toAsset);if(r.network!==n.network)return m.Err("Both assets should be on the same network (either mainnet or testnet)");const s=H0(e.sendAmount);if(!s.ok)return m.Err(s.error);const i=H0(e.receiveAmount);if(!i.ok)return m.Err(i.error);if(s<i)return m.Err("Send amount should be greater than receive amount");if(e.sourceAddress&&e.destinationAddress){const u=await this._getAddresses(r.blockchainType,{[r.blockchainType]:e.sourceAddress}),l=await this._getAddresses(n.blockchainType,{[n.blockchainType]:e.destinationAddress});return!u.ok||!l.ok?m.Err(u.error||l.error):m.Ok({sendAddress:u.val,receiveAddress:l.val,fromAsset:r,toAsset:n})}if((D.isBitcoin(D.ChainAsset.from(e.fromAsset).chain)||D.isBitcoin(D.ChainAsset.from(e.toAsset).chain))&&!((c=e.addresses)!=null&&c.bitcoin))return m.Err("Bitcoin address in addresses is required if source or destination chain is bitcoin, it is used as refund or redeem address.");const a=await this._getAddresses(r.blockchainType,e.addresses);if(!a.ok)return m.Err(a.error);const o=await this._getAddresses(n.blockchainType,e.addresses);return o.ok?m.Ok({sendAddress:a.val,receiveAddress:o.val,fromAsset:r,toAsset:n}):m.Err(o.error)}async _getAddresses(e,r){var n;if(this._redeemServiceEnabled&&r&&r[e])return m.Ok(r[e]);switch(e){case D.BlockchainType.evm:return this._htlcs.evm?m.Ok(this._htlcs.evm.htlcActorAddress):m.Err("Please provide evmHTLC when initializing garden or pass EVM address in SwapParams");case D.BlockchainType.bitcoin:{const s=(n=this._htlcs.bitcoin)==null?void 0:n.getPublicKey;return!s||!j6(s)?m.Err("Invalid btc public key or pass Bitcoin address in SwapParams"):m.Ok(De(s))}case D.BlockchainType.solana:return this._htlcs.solana?m.Ok(this._htlcs.solana.htlcActorAddress):m.Err("Please provide solanaHTLC when initializing garden or pass Solana address in SwapParams");case D.BlockchainType.starknet:return this._htlcs.starknet?m.Ok(this._htlcs.starknet.htlcActorAddress):m.Err("Please provide starknetHTLC when initializing garden or pass Starknet address in SwapParams");case D.BlockchainType.sui:return this._htlcs.sui?m.Ok(this._htlcs.sui.htlcActorAddress):m.Err("Please provide suiHTLC when initializing garden or pass Sui address in SwapParams");case D.BlockchainType.tron:return this._htlcs.tron?m.Ok(this._htlcs.tron.htlcActorAddress):m.Err("Please provide tronHTLC when initializing garden or pass Tron address in SwapParams");case D.BlockchainType.xrpl:return this._htlcs.xrpl?m.Ok(this._htlcs.xrpl.htlcActorAddress):m.Err("Please provide xrplHTLC when initializing garden or pass XRPL address in SwapParams");default:return m.Err("Unsupported chain")}}on(e,r){return this._events.on(e,r),this}off(e,r){return this._events.off(e,r),this}}class P4{constructor(e,r,n){this.callData=new Qe.CallData(Fw),this.account=e,this.starknetProvider=new Qe.RpcProvider({nodeUrl:r||(n?Fa[n].nodeUrl:Fa.mainnet.nodeUrl)})}get htlcActorAddress(){return this.account.address}async getHTLCContract(e,r=!1){const n=r?e.destination_swap.asset:e.source_swap.asset;return new Qe.Contract({abi:jw,address:n,providerOrAccount:this.account})}async initiate(e){try{const n=await(await this.getHTLCContract(e)).token();if(!n)throw new Error("Token address retrieval failed");const s=Qe.num.toHex(n),i=Qe.cairo.uint256(BigInt(e.source_swap.amount));try{const u=await Mw(this.account,s,e.source_swap.asset,BigInt(e.source_swap.amount),this.starknetProvider);if(u.error)return m.Err(u.error)}catch(u){return m.Err(`Allowance check failed: ${u}`)}const a=e.source_swap.secret_hash;if(!a)return m.Err("Invalid order: secret_hash is undefined");const o=m.hexToU128Array(a),c=await this.account.execute({contractAddress:e.source_swap.asset,entrypoint:"initiate",calldata:[e.source_swap.redeemer,e.source_swap.timelock.toString(),i.low.toString(),i.high.toString(),...o.map(u=>u.toString())]});if(!c.transaction_hash)throw new Error("Failed to initiate HTLC transaction");return m.Ok(c.transaction_hash)}catch(r){return m.Err(`HTLC Initiation Error: ${r}`)}}async redeem(e,r){try{const n=await this.getHTLCContract(e,!0),s=e.source_swap.chain.includes("starknet")?e.source_swap.swap_id:e.destination_swap.swap_id,i=await this.account.execute({contractAddress:n.address,entrypoint:"redeem",calldata:Qe.CallData.compile({swap_id:s,secret:m.hexToU32Array(r)})});return i.transaction_hash?m.Ok(i.transaction_hash):m.Err("Failed to redeem HTLC transaction")}catch{return m.Err("HTLC Redeem Error")}}async refund(e){try{const r=e.source_swap.chain.includes("starknet")?e.source_swap.swap_id:e.destination_swap.swap_id,n=await this.getHTLCContract(e),s=await this.account.execute({contractAddress:n.address,entrypoint:"refund",calldata:{orderId:r}});return s.transaction_hash?m.Ok(s.transaction_hash):m.Err("Failed to refund HTLC transaction")}catch{return m.Err("HTLC Refund Error")}}}class O4{constructor(e){if(this.provider=e,!e)throw new Error("Provider is required");this.provider=e,this.program=new Ar.Program(Md,e)}get htlcActorAddress(){if(!this.program.programId)throw new Error("No program found");return this.provider.publicKey.toBase58()}async initiate(e){if(!e)return m.Err("Order is required");try{const{redeemer:r,secretHash:n,amount:s,expiresIn:i}=cs.from(e),a=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Ar.web3.PublicKey.findProgramAddressSync(a,this.program.programId)[0];const o=await this.program.methods.initiate(s,i,r,n).accounts({initiator:this.provider.publicKey}).transaction(),c=await this.provider.sendAndConfirm(o);return c?m.Ok(c):m.Err("Failed to initiate HTLC transaction")}catch(r){return m.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async redeem(e,r){if(!e)return m.Err("Order is required");if(!r)return m.Err("Secret is required");const{secretHash:n}=cs.from(e),s=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Ar.web3.PublicKey.findProgramAddressSync(s,this.program.programId)[0];try{const{redeemer:i}=cs.from(e);if(!this.swapAccount)return m.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const a=await this.program.methods.redeem(e2(r)).accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey,redeemer:i}).transaction(),o=await this.provider.sendAndConfirm(a);return o?m.Ok(o):m.Err("Failed to redeem HTLC transaction")}catch(i){return m.Err(`Error redeeming swap: ${i instanceof Error?i.message:String(i)}`)}}async refund(e){if(!e)return m.Err("Order is required");const{secretHash:r}=cs.from(e),n=[Buffer.from("swap_account"),Buffer.from(r)];this.swapAccount=Ar.web3.PublicKey.findProgramAddressSync(n,this.program.programId)[0];try{if(console.log("Initiating refund for ::",e.source_swap.swap_id),!this.swapAccount)return m.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const s=await this.program.methods.refund().accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey}).transaction(),i=await this.provider.sendAndConfirm(s);return i?m.Ok(i):m.Err("Failed to refund HTLC transaction")}catch(s){return m.Err(`Error refunding swap: ${s instanceof Error?s.message:String(s)}`)}}}const B4=t=>t.map(e=>e),C4=t=>{if(t===m.Network.TESTNET)return R4;if(t===m.Network.LOCALNET)return U4;if(t===m.Network.MAINNET)return N4;throw new Error("Invalid network")},R4=["https://mempool.space/testnet4/api"],N4=["https://mempool.space/api","https://blockstream.info/api"],U4=["http://localhost:30000"],Cs={INVALID_PK:"invalid private key",FEE_EXCEEDS_AMOUNT:(t,e)=>`fee exceeds amount: fee: ${t} > amount: ${e}`,SWAP_NOT_FOUND:"swap config not found, please set the swap config first",SCRIPT_NOT_FUNDED:"script not funded",SWAP_NOT_EXPIRED:t=>`swap not expired. Need ${t} more blocks`,MIN_AMOUNT:t=>`amount is too low. Minimum amount is ${t}`,INSUFFICIENT_FUNDS:(t,e)=>`insufficient funds, need ${e} but got ${t}`,AmtPlusFeeExceedsBalance:(t,e,r)=>`amount + fee exceeds balance. Need ${t+e} but got ${r}`},ka={INVALID_SECRET_HASH:"invalid secret hash",INVALID_PUBKEY_OR_SECRET:"invalid public key or secret",INVALID_PUBKEY:"invalid public key",ORDER_NOT_EXPIRED:"you cannot refund before your transaction expires"},Cm=t=>t.sort((e,r)=>e.status.confirmed!=r.status.confirmed?e.status.confirmed?-1:1:r.value-e.value);class F4{constructor(e,r){this.cacheTimeout=2e3,this.utxosCache=new Map,this.APIs=r?B4([r]):C4(e),this.network=V6(e)}async getTxIndex(e,r){const n=this.APIs.map(i=>`${i}/tx/${e}`),{vout:s}=await m.Fetcher.getWithFallback(n);for(let i=0;i<s.length;i++)if(s[i].scriptpubkey_address===r)return i;throw new Error("failed to get tx index")}async broadcast(e){if(!/^[0-9a-fA-F]+$/.test(e))throw new Error("invalid tx hex");for(let r=0;r<5;r++)try{return m.Fetcher.postWithFallback(this.APIs.map(n=>`${n}/tx`),{body:e})}catch(n){if(r===4)throw n;await new Promise(s=>setTimeout(s,500))}throw new Error("failed to broadcast tx")}async getBalance(e){return(await this.getUTXOs(e)).reduce((r,n)=>r+n.value,0)}setTimeoutForCache(e){this.cacheTimeout=e}async getUTXOs(e,r){const n=this.utxosCache.get(e);if(n&&Date.now()-n.timestamp<this.cacheTimeout)return Rm(n.utxos,r);const s=await m.Fetcher.getWithFallback(this.APIs.map(i=>`${i}/address/${e}/utxo`),{signal:AbortSignal.timeout(5e3)});return this.utxosCache.set(e,{timestamp:Date.now(),utxos:s}),Rm(s,r)}async getTransactionHex(e){return m.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${e}/hex`))}async getTransaction(e){return m.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${e}`))}async getConfirmations(e){const r=await this.getTransaction(e);return!r.status.confirmed||!r.status.block_height?0:await this.getLatestTip()-r.status.block_height+1}async getFeeRates(){if(this.network===Cr.Regtest)return{fastestFee:8,halfHourFee:7,hourFee:6,economyFee:4,minimumFee:2};let e="";this.network===Cr.Testnet&&(e="testnet4/");const r=`https://mempool.space/${e}api/v1/fees/recommended`,n=`https://blockstream.info/${e}api/fee-estimates`,s=await m.Fetcher.getWithFallback([r,n],{signal:AbortSignal.timeout(5e3)});return"fastestFee"in s?s.fastestFee===1?{fastestFee:2,halfHourFee:2,hourFee:2,economyFee:2,minimumFee:2}:s:{fastestFee:s[1],halfHourFee:s[5],hourFee:s[10],economyFee:s[20],minimumFee:s[25]}}async getTransactions(e,r){const n=await m.Fetcher.getWithFallback(this.APIs.map(s=>`${s}/address/${e}/txs`));if(r===gc.ALL)return n;if(r===gc.IN)return n.filter(s=>s.vout.find(i=>i.scriptpubkey_address===e));if(r===gc.OUT)return n.filter(s=>s.vin.find(i=>i.prevout.scriptpubkey_address===e));throw new Error("failed to get transactions: invalid bitcoin tx type")}getNetwork(){return this.network}async getLatestTip(){return m.Fetcher.getWithFallback(this.APIs.map(e=>`${e}/blocks/tip/height`))}async suggestFee(e,r,n){const i=(await this.getUTXOs(e,r)).length,a=2,o=await this.getFeeRates();return Math.floor(o[N6[n]]*1.05)*(i*70+a*31+10)}async getTransactionTimes(e){const r=e.map(s=>`txId[]=${s}`).join("&");return(await m.Fetcher.getWithFallback(this.APIs.map(s=>`${s}/v1/transaction-times?${r}`))).map(s=>s*1e3)}}const Rm=(t,e)=>{if(Array.isArray(t)){if(e){const r=t.reduce((i,a)=>i+a.value,0);if(r<e)throw new Error(Cs.INSUFFICIENT_FUNDS(r,e));let n=BigInt(0);t.sort((i,a)=>a.value-i.value);const s=[];for(const i of t)if(n+=BigInt(i.value),s.push(i),n>=e)break;return Cm(s)}return Cm(t)}return[]},ga={p2wpkh:"p2wpkh","p2wpkh-p2sh":"p2wpkh-p2sh"},Pc={ALL:me.Transaction.SIGHASH_ALL,NONE:me.Transaction.SIGHASH_NONE,SINGLE:me.Transaction.SIGHASH_SINGLE,ALL_ANYONECANPAY:me.Transaction.SIGHASH_ALL|me.Transaction.SIGHASH_ANYONECANPAY,NONE_ANYONECANPAY:me.Transaction.SIGHASH_NONE|me.Transaction.SIGHASH_ANYONECANPAY,SINGLE_ANYONECANPAY:me.Transaction.SIGHASH_SINGLE|me.Transaction.SIGHASH_ANYONECANPAY};class qs{constructor(e,r){this._scriptType=e,this._sigHashType=r}get scriptType(){return this._scriptType}get sigHashType(){return this._sigHashType}toString(){return`${this._scriptType} ${this._sigHashType}`}static async fromString(e){const[r,n]=e.split(" "),s=await U0.mixed().oneOf(["segwitV0","segwitV1","p2shSignature"]).required().validate(r),i=await U0.mixed().oneOf(Object.values(Pc)).required().validate(parseInt(n));return new qs(s,i)}}const M4=(t,e,r=!1)=>{const n=a=>{try{a=me.address.fromBech32(a).data.toString("hex")}catch(o){if(Kf(o))(o.message.includes("Mixed-case string")||o.message.includes("too short"))&&(a=me.address.fromBase58Check(a).hash.toString("hex"));else throw new Error(String(o))}return a},s=me.script.fromASM(`
87
87
  OP_IF
88
88
  OP_SHA256
89
89
  ${t.secretHash}
@@ -101,4 +101,4 @@ ${String(n)}`);Ld(e);for(let s=0;s<e.callbacks.length;s++){const i=n[s];i instan
101
101
  OP_ENDIF
102
102
  OP_EQUALVERIFY
103
103
  OP_CHECKSIG
104
- `.trim().replace(/\s+/g," ")),i=me.payments[r?"p2sh":"p2wsh"]({redeem:{output:s},network:e});if(!i.address)throw new Error("Could not build address");return{script:s,address:i.address}},Ua={P2SH:"p2sh",P2WSH:"p2wsh",P2TR:"p2tr"};var A6=(t=>(t[t.Bitcoin=0]="Bitcoin",t[t.EVM=1]="EVM",t))(A6||{});class N4{addSignatureSegwitV0(e=_c.ALL){return new Gs("segwitV0",e)}addSignatureP2sh(e=_c.ALL){return new Gs("p2shSignature",e)}addSignatureSegwitV1(e=_c.ALL){return new Gs("segwitV1",e)}chain(){return A6.Bitcoin}async addAllInputs(e,r,n,s){const i=(s==null?void 0:s.utxos)||await n.getUTXOs(r);for(const a of i){const o=await n.getTxIndex(a.txid,r);e.addInput(Gf(a.txid),o,s==null?void 0:s.nSequence)}return e}async suggestFee(e,r){const n=await this.getAddress();return(await this.getProvider()).suggestFee(n,e,r)}async toOutputScript(e){return me.address.toOutputScript(e,await this.getNetwork())}totalValueFromUTXOs(e){return e.reduce((r,n)=>r+n.value,0)}async scriptToAddress(e){const r=me.payments.p2wsh({redeem:{output:e},network:await this.getNetwork()});if(!r.address)throw new Error("Could not generate p2wsh address");return r.address}async newSwap(e){if(e.secretHash=m.trim0x(e.secretHash),e.secretHash.length!==64)throw new Error(ka.INVALID_SECRET_HASH);const{script:r,address:n}=R4(e,await this.getNetwork());return new U4(this,{...e,redeemScript:r,scriptAddress:n})}getScriptType(e,r){try{if(me.address.fromBase58Check(e).version===r.scriptHash)return Ua.P2SH}catch{const s=me.address.fromBech32(e);if(s.prefix!==r.bech32)throw new Error("Invalid address");if(s.version===0){if(s.data.length===32)return Ua.P2WSH}else if(s.version===1&&s.data.length===32)return Ua.P2TR}throw new Error("Unsupported script type")}}class U4{constructor(e,r){if(r.secretHash=m.trim0x(r.secretHash),r.secretHash.length!==64)throw new Error(ka.INVALID_SECRET_HASH);this.wallet=e,this.swap=r}id(){return this.swap.scriptAddress}async init(){return this.wallet.send(this.swap.scriptAddress,+this.swap.amount.toString())}async redeem(e,r){e=m.trim0x(e);const n=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),Buffer.from(e,"hex"),me.script.number.encode(1),this.swap.redeemScript],s=me.payments.p2wsh({redeem:{output:this.swap.redeemScript},network:await this.wallet.getNetwork()}).address;if(!s)throw new Error("Could not generate p2wsh address for redeem script");try{return await this.wallet.spend(this.swap.redeemScript,s,{witness:n,toAddress:r})}catch(i){throw qf(i)?i.message.includes("OP_EQUALVERIFY")?new Error(ka.INVALID_PUBKEY_OR_SECRET):new Error(i.message):new Error(String(i))}}async refund(e){const r=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),me.script.number.encode(0),this.swap.redeemScript];try{const n=me.payments.p2wsh({redeem:{output:this.swap.redeemScript},network:await this.wallet.getNetwork()}).address;if(!n)throw new Error("Could not generate p2wsh address for refund script");return await this.wallet.spend(this.swap.redeemScript,n,{toAddress:e,witness:r,nSequence:this.swap.expiryBlocks})}catch(n){throw qf(n)?n.message.includes("OP_EQUALVERIFY")?new Error(ka.INVALID_PUBKEY):n.message.includes("BIP")?new Error(ka.ORDER_NOT_EXPIRED):new Error(n.message):new Error(String(n))}}}const jf=(t,e,r,n)=>`m/${t}'/${e===Cr.Mainnet?0:1}'/${r}'/0/${n??0}`,S6={bip44:(t,e,r)=>jf("44",t,r??0,e),bip49:(t,e,r)=>jf("49",t,r??0,e),bip84:(t,e,r)=>jf("84",t,r??0,e)};function Hf(t){if(t===Cr.Mainnet)return me.networks.bitcoin;if(t===Cr.Testnet)return me.networks.testnet;if(t===Cr.Regtest)return me.networks.regtest;throw new Error("Invalid network")}function F4(t,e,r){if(!N0.validateMnemonic(t))throw new Error("Invalid mnemonic");const n=(r==null?void 0:r.path)??S6.bip44(e,(r==null?void 0:r.index)??0),s=P6.BIP32Factory(mr).fromSeed(N0.mnemonicToSeedSync(t));return M4(s,n)}const M4=(t,e)=>{const r=t.derivePath(e).privateKey;if(!r)throw new Error("Unable to derive private key from mnemonic");return r.toString("hex")};me.initEccLib(mr);class _i extends N4{constructor({privateKey:e,provider:r,pkPath:n,pkType:s}){const i=pc.ECPairFactory(mr),a=Hf(r.getNetwork()),o=Buffer.from(e,"hex");if(o.length===0)throw new Error("invalid private key");super(),this.minAmt=1e3,this.path=n||"",this.pkType=s,this.signer=i.fromPrivateKey(o,{network:a}),this.provider=r,this.network=a}static fromMnemonic(e,r,n){const s=S6.bip84(r.getNetwork(),n==null?void 0:n.index),i=F4(e,r.getNetwork(),{path:s});return new _i({privateKey:i,provider:r,pkType:ga.p2wpkh,pkPath:s})}static fromPrivateKey(e,r,n){return new _i({privateKey:e,provider:r,pkType:(n==null?void 0:n.pkType)??ga.p2wpkh,pkPath:(n==null?void 0:n.pkPath)??"unknown"})}static createRandom(e){const r=pc.ECPairFactory(mr),n=Hf(e.getNetwork()),s=r.makeRandom({network:n});if(!s.privateKey)throw new Error("Failed to create random key");return new _i({privateKey:s.privateKey.toString("hex"),provider:e,pkType:ga.p2wpkh,pkPath:"unknown"})}static fromWIF(e,r,n){const s=pc.ECPairFactory(mr),i=Hf(r.getNetwork()),a=s.fromWIF(e,i);if(!a.privateKey)throw new Error("Invalid WIF");return _i.fromPrivateKey(a.privateKey.toString("hex"),r,n)}walletConfig(){return{network:this.provider.getNetwork(),path:this.path,addressType:this.pkType}}async spend(e,r,{toAddress:n,fee:s,nSequence:i,unlockScript:a,witness:o}){var p;const c=this.getScriptType(r,this.network),u=await this.provider.getBalance(r);if(u===0)throw new Error(Bs.SCRIPT_NOT_FUNDED);let l=new me.Transaction;if(l.version=2,s??(s=await this.provider.suggestFee(r,u,Ii.FAST)),s>u)throw new Error(Bs.FEE_EXCEEDS_AMOUNT(s,u));const f=await this.provider.getUTXOs(r);l=await this.addAllInputs(l,r,this.provider,{nSequence:i,utxos:f}),l.addOutput(await this.toOutputScript(n??await this.getAddress()),u-s);for(let d=0;d<l.ins.length;d++)if(c===Ua.P2SH){if(!a)throw new Error("Unlock script is required for p2sh");const b=[];for(const A of a)if(A instanceof Gs){const S=A.sigHashType,T=l.hashForSignature(d,e,S);b.push(me.script.signature.encode(Buffer.from(await this.sign(T.toString("hex")),"hex"),S))}else b.push(A);const g=(p=me.payments.p2sh({redeem:{input:me.script.compile(b),output:e},network:this.network}).redeem)==null?void 0:p.input;l.setInputScript(d,g)}else if(c===Ua.P2WSH){if(!o)throw new Error("Witness is required for p2wsh");const b=[];for(const g of o)if(g instanceof Gs){const A=g.sigHashType,S=l.hashForWitnessV0(d,e,f[d].value,A);b.push(me.script.signature.encode(Buffer.from(await this.sign(S.toString("hex")),"hex"),A))}else b.push(g);l.setWitness(d,b)}else throw new Error("Invalid script type "+c);return this.provider.broadcast(l.toHex())}async getAddress(){if(this.pkType===ga["p2wpkh-p2sh"]){const{address:r}=me.payments.p2sh({redeem:me.payments.p2wpkh({pubkey:this.signer.publicKey,network:this.network}),network:this.network});if(!r)throw new Error("failed to get the p2wpkh-p2sh address");return r}const{address:e}=me.payments[this.pkType]({pubkey:this.signer.publicKey,network:this.network});if(!e)throw new Error("failed to get the p2wpkh address");return e}getProvider(){return Promise.resolve(this.provider)}async getBalance(){return this.provider.getBalance(await this.getAddress())}getPublicKey(){return this.signer.publicKey.toString("hex")}getNetwork(){return Promise.resolve(this.network)}static async generateUnsignedPSBT(e,r,n,s,i,a){if(a||(a=await e.suggestFee(n,i,Ii.FAST)),a>i)throw new Error(Bs.FEE_EXCEEDS_AMOUNT(a,i));const o=await e.getUTXOs(n,i+a),c=o.reduce((f,p)=>f+p.value,0);if(c<i+a)throw new Error(Bs.INSUFFICIENT_FUNDS(c,i+a));const u=new me.Psbt({network:r});for(const f of o){const p=await e.getTransactionHex(f.txid);u.addInput({hash:Gf(f.txid),index:f.vout,nonWitnessUtxo:Buffer.from(p,"hex")})}const l=c-i-a;return u.addOutput({address:s,value:i}),l>546&&u.addOutput({address:n,value:l}),{txHex:u.toHex(),utxoCount:o.length}}async _send(e,r,n){var u;if(n||(n=await this.provider.suggestFee(await this.getAddress(),r,Ii.FAST)),n>r)throw new Error(Bs.FEE_EXCEEDS_AMOUNT(n,r));if(r<this.minAmt)throw new Error(Bs.MIN_AMOUNT(this.minAmt));const s=await this.getAddress(),i=await this.provider.getUTXOs(s,r+n),a=i.reduce((l,f)=>l+f.value,0),o=new me.Psbt({network:this.network});for(const l of i){const f=await this.provider.getTransactionHex(l.txid),p=await this.provider.getTransaction(l.txid);let d;this.pkType===ga["p2wpkh-p2sh"]&&(d={witnessUtxo:{script:Buffer.from(p.vout[l.vout].scriptpubkey,"hex"),value:l.value},redeemScript:(u=me.payments.p2sh({redeem:me.payments.p2wpkh({pubkey:this.signer.publicKey,network:this.network}),network:this.network}).redeem)==null?void 0:u.output}),o.addInput({hash:Gf(l.txid),index:l.vout,nonWitnessUtxo:Buffer.from(f,"hex"),...d})}const c=a-r-n;return o.addOutput({address:e,value:r}),c>0&&o.addOutput({address:s,value:c}),o.signAllInputs(this.signer).finalizeAllInputs(),o.extractTransaction().toHex()}async send(e,r,n){const s=await this._send(e,r,n);return this.provider.broadcast(s)}async sign(e){return e=e.startsWith("0x")?e.slice(2):e,this.signer.sign(Buffer.from(e,"hex")).toString("hex")}async signSchnorr(e){return this.signer.signSchnorr(e)}}exports.API=yc;exports.BaseError=G;exports.BitcoinNetwork=Cr;exports.BitcoinProvider=C4;exports.BitcoinWallet=_i;exports.DEFAULT_AFFILIATE_ASSET=B6;exports.EvmRelay=Rw;exports.Garden=_0;exports.HttpRequestError=Ci;exports.OrderCreationStatus=Ta;exports.Quote=Fb;exports.STARKNET_CONFIG=Fa;exports.SUI_CONFIG=zf;exports.SecretManager=mo;exports.SolanaHTLC=T4;exports.SolanaRelay=Qw;exports.SolanaRelayerAddress=Rm;exports.StarknetHTLC=k4;exports.StarknetRelay=$w;exports.TRON_CONFIG=Nm;exports.XRPL_CONFIG=Um;exports.XrplRelay=E6;exports.alpenTestnet=Ow;exports.arcTestnet=Tw;exports.botanixMainnet=Pw;exports.call=Fo;exports.checkAllowance=Pa;exports.checkAllowanceAndApprove=Uw;exports.concat=sr;exports.decodeErrorResult=Tg;exports.encodeAbiParameters=vs;exports.evmToViemChainMap=_u;exports.getChainNameFromChainId=Cw;exports.getUrl=uu;exports.hyperevm=Rd;exports.hyperliquidTestnet=Cd;exports.isAddressEqual=ta;exports.isAllowanceSufficient=Fw;exports.isHex=Nr;exports.localBatchGatewayRequest=O1;exports.localBatchGatewayUrl=$o;exports.megaethMainnet=Bw;exports.resolveApiConfig=Vf;exports.solanaProgramAddress=Df;exports.stringify=et;exports.switchOrAddNetwork=Nd;exports.toXOnly=De;exports.validateBTCAddress=$6;exports.validateLTCAddress=H6;exports.validateLightningAddress=L6;exports.validateSparkAddress=j6;
104
+ `.trim().replace(/\s+/g," ")),i=me.payments[r?"p2sh":"p2wsh"]({redeem:{output:s},network:e});if(!i.address)throw new Error("Could not build address");return{script:s,address:i.address}},Ua={P2SH:"p2sh",P2WSH:"p2wsh",P2TR:"p2tr"};var x6=(t=>(t[t.Bitcoin=0]="Bitcoin",t[t.EVM=1]="EVM",t))(x6||{});class $4{addSignatureSegwitV0(e=Pc.ALL){return new qs("segwitV0",e)}addSignatureP2sh(e=Pc.ALL){return new qs("p2shSignature",e)}addSignatureSegwitV1(e=Pc.ALL){return new qs("segwitV1",e)}chain(){return x6.Bitcoin}async addAllInputs(e,r,n,s){const i=(s==null?void 0:s.utxos)||await n.getUTXOs(r);for(const a of i){const o=await n.getTxIndex(a.txid,r);e.addInput(Wf(a.txid),o,s==null?void 0:s.nSequence)}return e}async suggestFee(e,r){const n=await this.getAddress();return(await this.getProvider()).suggestFee(n,e,r)}async toOutputScript(e){return me.address.toOutputScript(e,await this.getNetwork())}totalValueFromUTXOs(e){return e.reduce((r,n)=>r+n.value,0)}async scriptToAddress(e){const r=me.payments.p2wsh({redeem:{output:e},network:await this.getNetwork()});if(!r.address)throw new Error("Could not generate p2wsh address");return r.address}async newSwap(e){if(e.secretHash=m.trim0x(e.secretHash),e.secretHash.length!==64)throw new Error(ka.INVALID_SECRET_HASH);const{script:r,address:n}=M4(e,await this.getNetwork());return new j4(this,{...e,redeemScript:r,scriptAddress:n})}getScriptType(e,r){try{if(me.address.fromBase58Check(e).version===r.scriptHash)return Ua.P2SH}catch{const s=me.address.fromBech32(e);if(s.prefix!==r.bech32)throw new Error("Invalid address");if(s.version===0){if(s.data.length===32)return Ua.P2WSH}else if(s.version===1&&s.data.length===32)return Ua.P2TR}throw new Error("Unsupported script type")}}class j4{constructor(e,r){if(r.secretHash=m.trim0x(r.secretHash),r.secretHash.length!==64)throw new Error(ka.INVALID_SECRET_HASH);this.wallet=e,this.swap=r}id(){return this.swap.scriptAddress}async init(){return this.wallet.send(this.swap.scriptAddress,+this.swap.amount.toString())}async redeem(e,r){e=m.trim0x(e);const n=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),Buffer.from(e,"hex"),me.script.number.encode(1),this.swap.redeemScript],s=me.payments.p2wsh({redeem:{output:this.swap.redeemScript},network:await this.wallet.getNetwork()}).address;if(!s)throw new Error("Could not generate p2wsh address for redeem script");try{return await this.wallet.spend(this.swap.redeemScript,s,{witness:n,toAddress:r})}catch(i){throw Kf(i)?i.message.includes("OP_EQUALVERIFY")?new Error(ka.INVALID_PUBKEY_OR_SECRET):new Error(i.message):new Error(String(i))}}async refund(e){const r=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),me.script.number.encode(0),this.swap.redeemScript];try{const n=me.payments.p2wsh({redeem:{output:this.swap.redeemScript},network:await this.wallet.getNetwork()}).address;if(!n)throw new Error("Could not generate p2wsh address for refund script");return await this.wallet.spend(this.swap.redeemScript,n,{toAddress:e,witness:r,nSequence:this.swap.expiryBlocks})}catch(n){throw Kf(n)?n.message.includes("OP_EQUALVERIFY")?new Error(ka.INVALID_PUBKEY):n.message.includes("BIP")?new Error(ka.ORDER_NOT_EXPIRED):new Error(n.message):new Error(String(n))}}}const Lf=(t,e,r,n)=>`m/${t}'/${e===Cr.Mainnet?0:1}'/${r}'/0/${n??0}`,k6={bip44:(t,e,r)=>Lf("44",t,r??0,e),bip49:(t,e,r)=>Lf("49",t,r??0,e),bip84:(t,e,r)=>Lf("84",t,r??0,e)};function Df(t){if(t===Cr.Mainnet)return me.networks.bitcoin;if(t===Cr.Testnet)return me.networks.testnet;if(t===Cr.Regtest)return me.networks.regtest;throw new Error("Invalid network")}function H4(t,e,r){if(!F0.validateMnemonic(t))throw new Error("Invalid mnemonic");const n=(r==null?void 0:r.path)??k6.bip44(e,(r==null?void 0:r.index)??0),s=B6.BIP32Factory(mr).fromSeed(F0.mnemonicToSeedSync(t));return L4(s,n)}const L4=(t,e)=>{const r=t.derivePath(e).privateKey;if(!r)throw new Error("Unable to derive private key from mnemonic");return r.toString("hex")};me.initEccLib(mr);class Ii extends $4{constructor({privateKey:e,provider:r,pkPath:n,pkType:s}){const i=mc.ECPairFactory(mr),a=Df(r.getNetwork()),o=Buffer.from(e,"hex");if(o.length===0)throw new Error("invalid private key");super(),this.minAmt=1e3,this.path=n||"",this.pkType=s,this.signer=i.fromPrivateKey(o,{network:a}),this.provider=r,this.network=a}static fromMnemonic(e,r,n){const s=k6.bip84(r.getNetwork(),n==null?void 0:n.index),i=H4(e,r.getNetwork(),{path:s});return new Ii({privateKey:i,provider:r,pkType:ga.p2wpkh,pkPath:s})}static fromPrivateKey(e,r,n){return new Ii({privateKey:e,provider:r,pkType:(n==null?void 0:n.pkType)??ga.p2wpkh,pkPath:(n==null?void 0:n.pkPath)??"unknown"})}static createRandom(e){const r=mc.ECPairFactory(mr),n=Df(e.getNetwork()),s=r.makeRandom({network:n});if(!s.privateKey)throw new Error("Failed to create random key");return new Ii({privateKey:s.privateKey.toString("hex"),provider:e,pkType:ga.p2wpkh,pkPath:"unknown"})}static fromWIF(e,r,n){const s=mc.ECPairFactory(mr),i=Df(r.getNetwork()),a=s.fromWIF(e,i);if(!a.privateKey)throw new Error("Invalid WIF");return Ii.fromPrivateKey(a.privateKey.toString("hex"),r,n)}walletConfig(){return{network:this.provider.getNetwork(),path:this.path,addressType:this.pkType}}async spend(e,r,{toAddress:n,fee:s,nSequence:i,unlockScript:a,witness:o}){var p;const c=this.getScriptType(r,this.network),u=await this.provider.getBalance(r);if(u===0)throw new Error(Cs.SCRIPT_NOT_FUNDED);let l=new me.Transaction;if(l.version=2,s??(s=await this.provider.suggestFee(r,u,Pi.FAST)),s>u)throw new Error(Cs.FEE_EXCEEDS_AMOUNT(s,u));const f=await this.provider.getUTXOs(r);l=await this.addAllInputs(l,r,this.provider,{nSequence:i,utxos:f}),l.addOutput(await this.toOutputScript(n??await this.getAddress()),u-s);for(let d=0;d<l.ins.length;d++)if(c===Ua.P2SH){if(!a)throw new Error("Unlock script is required for p2sh");const b=[];for(const A of a)if(A instanceof qs){const S=A.sigHashType,T=l.hashForSignature(d,e,S);b.push(me.script.signature.encode(Buffer.from(await this.sign(T.toString("hex")),"hex"),S))}else b.push(A);const g=(p=me.payments.p2sh({redeem:{input:me.script.compile(b),output:e},network:this.network}).redeem)==null?void 0:p.input;l.setInputScript(d,g)}else if(c===Ua.P2WSH){if(!o)throw new Error("Witness is required for p2wsh");const b=[];for(const g of o)if(g instanceof qs){const A=g.sigHashType,S=l.hashForWitnessV0(d,e,f[d].value,A);b.push(me.script.signature.encode(Buffer.from(await this.sign(S.toString("hex")),"hex"),A))}else b.push(g);l.setWitness(d,b)}else throw new Error("Invalid script type "+c);return this.provider.broadcast(l.toHex())}async getAddress(){if(this.pkType===ga["p2wpkh-p2sh"]){const{address:r}=me.payments.p2sh({redeem:me.payments.p2wpkh({pubkey:this.signer.publicKey,network:this.network}),network:this.network});if(!r)throw new Error("failed to get the p2wpkh-p2sh address");return r}const{address:e}=me.payments[this.pkType]({pubkey:this.signer.publicKey,network:this.network});if(!e)throw new Error("failed to get the p2wpkh address");return e}getProvider(){return Promise.resolve(this.provider)}async getBalance(){return this.provider.getBalance(await this.getAddress())}getPublicKey(){return this.signer.publicKey.toString("hex")}getNetwork(){return Promise.resolve(this.network)}static async generateUnsignedPSBT(e,r,n,s,i,a){if(a||(a=await e.suggestFee(n,i,Pi.FAST)),a>i)throw new Error(Cs.FEE_EXCEEDS_AMOUNT(a,i));const o=await e.getUTXOs(n,i+a),c=o.reduce((f,p)=>f+p.value,0);if(c<i+a)throw new Error(Cs.INSUFFICIENT_FUNDS(c,i+a));const u=new me.Psbt({network:r});for(const f of o){const p=await e.getTransactionHex(f.txid);u.addInput({hash:Wf(f.txid),index:f.vout,nonWitnessUtxo:Buffer.from(p,"hex")})}const l=c-i-a;return u.addOutput({address:s,value:i}),l>546&&u.addOutput({address:n,value:l}),{txHex:u.toHex(),utxoCount:o.length}}async _send(e,r,n){var u;if(n||(n=await this.provider.suggestFee(await this.getAddress(),r,Pi.FAST)),n>r)throw new Error(Cs.FEE_EXCEEDS_AMOUNT(n,r));if(r<this.minAmt)throw new Error(Cs.MIN_AMOUNT(this.minAmt));const s=await this.getAddress(),i=await this.provider.getUTXOs(s,r+n),a=i.reduce((l,f)=>l+f.value,0),o=new me.Psbt({network:this.network});for(const l of i){const f=await this.provider.getTransactionHex(l.txid),p=await this.provider.getTransaction(l.txid);let d;this.pkType===ga["p2wpkh-p2sh"]&&(d={witnessUtxo:{script:Buffer.from(p.vout[l.vout].scriptpubkey,"hex"),value:l.value},redeemScript:(u=me.payments.p2sh({redeem:me.payments.p2wpkh({pubkey:this.signer.publicKey,network:this.network}),network:this.network}).redeem)==null?void 0:u.output}),o.addInput({hash:Wf(l.txid),index:l.vout,nonWitnessUtxo:Buffer.from(f,"hex"),...d})}const c=a-r-n;return o.addOutput({address:e,value:r}),c>0&&o.addOutput({address:s,value:c}),o.signAllInputs(this.signer).finalizeAllInputs(),o.extractTransaction().toHex()}async send(e,r,n){const s=await this._send(e,r,n);return this.provider.broadcast(s)}async sign(e){return e=e.startsWith("0x")?e.slice(2):e,this.signer.sign(Buffer.from(e,"hex")).toString("hex")}async signSchnorr(e){return this.signer.signSchnorr(e)}}exports.API=bc;exports.BaseError=G;exports.BitcoinNetwork=Cr;exports.BitcoinProvider=F4;exports.BitcoinWallet=Ii;exports.DEFAULT_AFFILIATE_ASSET=R6;exports.EvmRelay=Uw;exports.Garden=P0;exports.HttpRequestError=Ri;exports.OrderCreationStatus=Ta;exports.Quote=$b;exports.STARKNET_CONFIG=Fa;exports.SUI_CONFIG=Gf;exports.SecretManager=mo;exports.SolanaHTLC=O4;exports.SolanaRelay=t2;exports.SolanaRelayerAddress=Um;exports.StarknetHTLC=P4;exports.StarknetRelay=Hw;exports.TRON_CONFIG=Fm;exports.XRPL_CONFIG=Mm;exports.XrplRelay=S6;exports.alpenTestnet=Cw;exports.arcTestnet=Iw;exports.botanixMainnet=Bw;exports.call=Fo;exports.checkAllowance=Pa;exports.checkAllowanceAndApprove=Mw;exports.concat=sr;exports.decodeErrorResult=Ig;exports.encodeAbiParameters=Es;exports.evmToViemChainMap=Pu;exports.getChainNameFromChainId=Nw;exports.getUrl=fu;exports.hyperevm=Ud;exports.hyperliquidTestnet=Nd;exports.isAddressEqual=ta;exports.isAllowanceSufficient=$w;exports.isHex=Nr;exports.localBatchGatewayRequest=C1;exports.localBatchGatewayUrl=$o;exports.megaethMainnet=Rw;exports.resolveApiConfig=qf;exports.solanaProgramAddress=Vf;exports.stringify=et;exports.switchOrAddNetwork=Fd;exports.toXOnly=De;exports.validateBTCAddress=H6;exports.validateLTCAddress=D6;exports.validateLightningAddress=z6;exports.validateSparkAddress=L6;