@gardenfi/core 3.1.3-beta.2 → 3.1.3-beta.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ccip-fFmTEKgV.js → ccip-Cok4USeJ.js} +1 -1
- package/dist/{ccip-CoK_g_s0.cjs → ccip-DkEfWv-9.cjs} +1 -1
- package/dist/index-BVbFl7I1.cjs +105 -0
- package/dist/{index-BgO5SheZ.js → index-Dpu0liry.js} +14962 -13156
- package/dist/index.cjs +1 -1
- package/dist/index.js +26 -23
- package/dist/src/index.d.ts +2 -2
- package/dist/src/lib/bitcoin/API.d.ts +1 -0
- package/dist/src/lib/evm/abi/coreWriter.d.ts +24 -0
- package/dist/src/lib/evm/relay/coreWrite.d.ts +9 -0
- package/dist/src/lib/evm/relay/evmRelay.d.ts +2 -2
- package/dist/src/lib/garden/garden.types.d.ts +5 -0
- package/dist/src/lib/quote/quote.types.d.ts +4 -0
- package/dist/src/lib/switchOrAddNetwork.d.ts +4 -1
- package/dist/src/lib/utils.d.ts +2 -0
- package/package.json +5 -3
- package/dist/index-CJMkaKG-.cjs +0 -104
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"use strict";var Pp=e=>{throw TypeError(e)};var Op=(e,t,r)=>t.has(e)||Pp("Cannot "+r);var ke=(e,t,r)=>(Op(e,t,"read from private field"),r?r.call(e):t.get(e)),$i=(e,t,r)=>t.has(e)?Pp("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Mi=(e,t,r,n)=>(Op(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);const D=require("@gardenfi/orderbook"),m=require("@gardenfi/utils"),be=require("bitcoinjs-lib"),X5=require("tiny-secp256k1"),jb=require("varuint-bitcoin"),mc=require("bitcore-lib-ltc"),vi=require("bech32"),_d=require("bignumber.js"),J5=require("@buildonspark/spark-sdk"),st=require("starknet"),Or=require("@coral-xyz/anchor"),Y5=require("@solana/spl-token"),Bp=require("@mysten/wallet-standard"),Cp=require("tronweb"),Rp=require("xrpl"),zc=require("ecpair"),Z5=require("node-cache"),Np=require("yup"),Up=require("bip39"),Q5=require("bip32");function Au(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const Ie=Au(be),xr=Au(X5),Fp=Au(jb),ev=Au(Y5),Vc={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"}},ro={[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:""}},Hb={[m.Network.MAINNET]:"9cBuPNiHXiMNg3Fin8xLCGJQBTXjYQTFtyaFQv2uiM1H",[m.Network.TESTNET]:"ANUVKxeqaec3bf4DVPqLTnG1PT3Fng56wPcE7LXAb46Q",[m.Network.LOCALNET]:"AKnL4NNf3DGWZJS6cPknBuEGnVsV4A4m5tgebLHaRSZ9"},Pd={mainnet:{native:"2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",spl:"gdnvdMCHJgnidtU7SL8RkRshHPvDJU1pdfZEpoLvqdU"},staging:{native:"6eksgdCnSjUaGQWZ6iYvauv1qzvYPF33RTGTM1ZuyENx",spl:"2WXpY8havGjfRxme9LUxtjFHTh1EfU3ur4v6wiK4KdNC"}},Od={[m.Network.TESTNET]:{packageId:"0x99865b03dd1bc03d0a6a805c454ea257c464f7abcccae9cd4b621b91e7ca04de",moduleName:"AtomicSwap"},[m.Network.MAINNET]:{packageId:"0xbfb5728aab0dd117747ef4574af6d3540ea6093109c22856e3ae201dfd58c0fc",moduleName:"AtomicSwap"},[m.Network.LOCALNET]:{packageId:"",moduleName:""}},Lb={[m.Network.MAINNET]:"https://api.trongrid.io",[m.Network.TESTNET]:"https://api.shasta.trongrid.io",[m.Network.LOCALNET]:""},Db={[m.Network.MAINNET]:"wss://s.altnet.rippletest.net:51233",[m.Network.TESTNET]:"wss://s.altnet.rippletest.net:51233",[m.Network.LOCALNET]:""},tv={asset:D.ChainAsset.from(D.Assets.base.cBBTC)};var Ga=(e=>(e.orderCreated="orderCreated",e.orderInitiating="orderInitiating",e.orderInitiated="orderInitiated",e))(Ga||{}),Ls=(e=>(e.SLOW="SLOW",e.MEDIUM="MEDIUM",e.FAST="FAST",e))(Ls||{}),Hr=(e=>(e.Mainnet="Mainnet",e.Testnet="Testnet",e.Regtest="Regtest",e))(Hr||{}),Gc=(e=>(e.ALL="ALL",e.IN="IN",e.OUT="OUT",e))(Gc||{});const rv={SLOW:"economyFee",MEDIUM:"hourFee",FAST:"fastestFee"};function Bd(e){const t=typeof e=="string"?e:e.network,r=t===m.Network.MAINNET?Vc.mainnet:t===m.Network.TESTNET?Vc.testnet:Vc.localnet;return{api:typeof e=="string"?r:{...r,...e},network:t}}function nv(e){return typeof e=="string"&&(e=Buffer.from(e,"hex")),e.length===32?e:e.subarray(1,33)}function $p(e,t){if(!e)throw new Error(t)}function iv(e){return Buffer.concat([Uint8Array.from([192]),sv(e)])}function sv(e){const t=Fp.encodingLength(e.length),r=Buffer.allocUnsafe(t);return Fp.encode(e.length,r),Buffer.concat([r,e])}function av(e,t){if(e.compare(t)>0){const r=e;e=t,t=r}return[e,t]}const Ve=e=>e.length===64?e:e.slice(2),ov=e=>{if(!e)return!1;try{const t=Buffer.from(e,"hex");return xr.isPoint(t)}catch{return!1}};function cv(e,t){if(!e)return!1;const r=t===m.Environment.MAINNET?Ie.networks.bitcoin:t===m.Environment.TESTNET?Ie.networks.testnet:Ie.networks.regtest;if(!r)return!1;Ie.initEccLib(xr);try{return Ie.address.toOutputScript(e,r),!0}catch{return!1}}function uv(e,t){if(!e)return!1;const r=t===m.Environment.MAINNET?"MAINNET":"REGTEST";try{return J5.decodeSparkAddress(e,r),!0}catch{return!1}}function fv(e,t){if(!e)return!1;let r;if(t===m.Environment.MAINNET?r=mc.Networks.livenet:(m.Environment.TESTNET,r=mc.Networks.testnet),!r)return!1;try{return mc.Address.fromString(e,r),!0}catch{const n=e.toLowerCase(),s=t===m.Environment.MAINNET?"ltc":"tltc";if(!n.startsWith(s+"1"))return!1;const a=[vi.bech32.decode,vi.bech32m.decode];for(const o of a)try{const c=o(n);if(c.prefix!==s)continue;const u=c.words;if(u.length===0)continue;const f=u[0],l=u.slice(1);if(f<0||f>16)continue;const h=vi.bech32.fromWords(l);if(h.length!==20&&h.length!==32)continue;return!0}catch{continue}return!1}}function lv(e,t){if(!e)return!1;const r=e.trim();if(r.includes("@")){const s=r.split("@");if(s.length!==2)return!1;const[a,o]=s;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 vi.bech32.decode(n,2e3),!0}catch{return!1}const i=t===m.Environment.MAINNET;return i&&n.startsWith("lnbc")||!i&&(n.startsWith("lntb")||n.startsWith("lnbcrt"))?r.length>50:!1}function Aa(e,t){const r=[];for(let n=0;n<t;n++)r.push(e);return r}const dv=e=>{switch(e){case m.Network.MAINNET:return Hr.Mainnet;case m.Network.TESTNET:return Hr.Testnet;case m.Network.LOCALNET:return Hr.Regtest;default:throw new Error(`Invalid bitcoin network ${e}`)}},hv=e=>{switch(e){case m.Network.MAINNET:return Ie.networks.bitcoin;case m.Network.TESTNET:return Ie.networks.testnet;case m.Network.LOCALNET:return Ie.networks.regtest;default:throw new Error(`Invalid bitcoin network ${e}`)}},pv=e=>{const t=e.toLowerCase().replace("0x","");return/^[0-9a-f]+$/.test(t)},Mp=e=>{if(typeof e=="object"&&"r"in e&&"s"in e)return m.Ok([e.r.toString(),e.s.toString()]);if(Array.isArray(e)){const t=e.map(r=>typeof r=="string"&&r.startsWith("0x")&&pv(r)?BigInt(r).toString():r);return m.Ok(t.join(","))}return m.Err("Invalid signature format")};function Cd(e){return Buffer.from(e,"hex").reverse()}function Rd(e){return typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"}const bc=async(e,t)=>{const r=Date.now(),n=3e4,i=2e3;for(;Date.now()-r<n;){const s=await e.getLatestBlockhash(),a=await e.confirmTransaction({signature:t,blockhash:s.blockhash,lastValidBlockHeight:s.lastValidBlockHeight},"confirmed");if(a.value&&a.value.err==null)return console.log("Tx Confirmed ✅",t),!0;console.log("Tx not confirmed yet. Retrying in 2 seconds..."),await new Promise(o=>setTimeout(o,i))}return!1},Ys=async(e,t,r)=>{var u,f;const n=await r.getAuthHeaders();if(!n.ok)return m.Err(n.error);const i=await m.Fetcher.get(t+"/v2/assets",{headers:{...n.val}});if(i.error)return m.Err("Failed to fetch asset info: "+i.error);const a=(i.result||[]).find(l=>l.id===e);if(!a)return m.Err(`Asset info not found for asset id: ${e}`);const o=((u=a.htlc)==null?void 0:u.address)||"",c=((f=a.token)==null?void 0:f.address)||"";return m.Ok({htlcAddress:o,tokenAddress:c})},jp=e=>{if(e==null||e.includes("."))return m.Err("Invalid amount ",e);const t=new _d.BigNumber(e);return!t.isInteger()||t.isNaN()||t.lt(0)||t.isLessThanOrEqualTo(0)?m.Err("Invalid amount ",e):m.Ok(t)},yv=async(e,t)=>{const r={[D.BlockchainType.evm]:{htlc:t.evm,name:"EVM"},[D.BlockchainType.solana]:{htlc:t.solana,name:"Solana"},[D.BlockchainType.starknet]:{htlc:t.starknet,name:"Starknet"},[D.BlockchainType.sui]:{htlc:t.sui,name:"Sui"},[D.BlockchainType.bitcoin]:{htlc:t.bitcoin,name:"Bitcoin"},[D.BlockchainType.tron]:{htlc:t.tron,name:"Tron"},[D.BlockchainType.litecoin]:{htlc:t.litecoin,name:"Litecoin"},[D.BlockchainType.alpen_signet]:{htlc:t.alpen_signet,name:"Alpen Signet"},[D.BlockchainType.xrpl]:{htlc:t.xrpl,name:"XRPL"},[D.BlockchainType.spark]:{htlc:t.spark,name:"Spark"},[D.BlockchainType.lightning]:{htlc:t.lightning,name:"Lightning"}};if(e===D.BlockchainType.bitcoin||e===D.BlockchainType.litecoin||e===D.BlockchainType.alpen_signet||e===D.BlockchainType.spark||e===D.BlockchainType.lightning)return m.Ok(void 0);const n=r[e];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: ${e}`)},mv=["0x90c06174","0xee1b963b"],bv=e=>{if(!e)return"";if(typeof e=="string")return e;if(e instanceof Error)return[e.message,e.shortMessage,e.reason,e.signature,e.stack].filter(Boolean).join(" | ");if(typeof e=="object"){const t=e.message;if(typeof t=="string")return t;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)},Vh=e=>{const t=bv(e).toLowerCase();return mv.some(r=>t.includes(r.toLowerCase()))},gv=e=>e.toLowerCase().includes("not supported for initiations"),zb=async({attempt:e,wallet:t,maxAttempts:r=1,baseDelayMs:n=1e3})=>{var i;for(let s=0;s<r;s++){const a=await e();if(a.error&&gv(a.error))break;if(a.ok){const o=await m.waitForTransactionReceipt(t,a.val);if(!o.ok){if(s<r-1){await m.sleep(n*2**s);continue}break}if(((i=o.val)==null?void 0:i.status)==="success")return a.val}s<r-1&&await m.sleep(n*2**s)}return null},wv=Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),vv=Buffer.from("483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8","hex"),Ev=Buffer.concat([wv,vv]),xv=Buffer.from("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0","hex"),Hp={failedToCreateInternalPubkey:"failed to create internal pubkey"};function Lp(){const e=be.crypto.sha256(Buffer.from("GardenHTLC","utf-8")),t=xr.pointMultiply(Buffer.concat([Buffer.from("04","hex"),Ev]),e);if(!t)throw new Error(Hp.failedToCreateInternalPubkey);const r=xr.pointAdd(xv,t);if(!r)throw new Error(Hp.failedToCreateInternalPubkey);return nv(Buffer.from(r))}var dn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Ge={},Rt={},bs={},Su={};Su.byteLength=kv;Su.toByteArray=Iv;Su.fromByteArray=Ov;var cn=[],gr=[],Av=typeof Uint8Array<"u"?Uint8Array:Array,Pf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var ks=0,Sv=Pf.length;ks<Sv;++ks)cn[ks]=Pf[ks],gr[Pf.charCodeAt(ks)]=ks;gr[45]=62;gr[95]=63;function Vb(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var n=r===t?0:4-r%4;return[r,n]}function kv(e){var t=Vb(e),r=t[0],n=t[1];return(r+n)*3/4-n}function Tv(e,t,r){return(t+r)*3/4-r}function Iv(e){var t,r=Vb(e),n=r[0],i=r[1],s=new Av(Tv(e,n,i)),a=0,o=i>0?n-4:n,c;for(c=0;c<o;c+=4)t=gr[e.charCodeAt(c)]<<18|gr[e.charCodeAt(c+1)]<<12|gr[e.charCodeAt(c+2)]<<6|gr[e.charCodeAt(c+3)],s[a++]=t>>16&255,s[a++]=t>>8&255,s[a++]=t&255;return i===2&&(t=gr[e.charCodeAt(c)]<<2|gr[e.charCodeAt(c+1)]>>4,s[a++]=t&255),i===1&&(t=gr[e.charCodeAt(c)]<<10|gr[e.charCodeAt(c+1)]<<4|gr[e.charCodeAt(c+2)]>>2,s[a++]=t>>8&255,s[a++]=t&255),s}function _v(e){return cn[e>>18&63]+cn[e>>12&63]+cn[e>>6&63]+cn[e&63]}function Pv(e,t,r){for(var n,i=[],s=t;s<r;s+=3)n=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(e[s+2]&255),i.push(_v(n));return i.join("")}function Ov(e){for(var t,r=e.length,n=r%3,i=[],s=16383,a=0,o=r-n;a<o;a+=s)i.push(Pv(e,a,a+s>o?o:a+s));return n===1?(t=e[r-1],i.push(cn[t>>2]+cn[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],i.push(cn[t>>10]+cn[t>>4&63]+cn[t<<2&63]+"=")),i.join("")}var Gh={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */Gh.read=function(e,t,r,n,i){var s,a,o=i*8-n-1,c=(1<<o)-1,u=c>>1,f=-7,l=r?i-1:0,h=r?-1:1,d=e[t+l];for(l+=h,s=d&(1<<-f)-1,d>>=-f,f+=o;f>0;s=s*256+e[t+l],l+=h,f-=8);for(a=s&(1<<-f)-1,s>>=-f,f+=n;f>0;a=a*256+e[t+l],l+=h,f-=8);if(s===0)s=1-u;else{if(s===c)return a?NaN:(d?-1:1)*(1/0);a=a+Math.pow(2,n),s=s-u}return(d?-1:1)*a*Math.pow(2,s-n)};Gh.write=function(e,t,r,n,i,s){var a,o,c,u=s*8-i-1,f=(1<<u)-1,l=f>>1,h=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:s-1,b=n?1:-1,g=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,a=f):(a=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-a))<1&&(a--,c*=2),a+l>=1?t+=h/c:t+=h*Math.pow(2,1-l),t*c>=2&&(a++,c/=2),a+l>=f?(o=0,a=f):a+l>=1?(o=(t*c-1)*Math.pow(2,i),a=a+l):(o=t*Math.pow(2,l-1)*Math.pow(2,i),a=0));i>=8;e[r+d]=o&255,d+=b,o/=256,i-=8);for(a=a<<i|o,u+=i;u>0;e[r+d]=a&255,d+=b,a/=256,u-=8);e[r+d-b]|=g*128};/*!
|
|
2
|
+
* The buffer module from node.js, for the browser.
|
|
3
|
+
*
|
|
4
|
+
* @author Feross Aboukhadijeh <https://feross.org>
|
|
5
|
+
* @license MIT
|
|
6
|
+
*/(function(e){const t=Su,r=Gh,n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=o,e.SlowBuffer=k,e.INSPECT_MAX_BYTES=50;const i=2147483647;e.kMaxLength=i,o.TYPED_ARRAY_SUPPORT=s(),!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 s(){try{const E=new Uint8Array(1),p={foo:function(){return 42}};return Object.setPrototypeOf(p,Uint8Array.prototype),Object.setPrototypeOf(E,p),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>i)throw new RangeError('The value "'+E+'" is invalid for option "size"');const p=new Uint8Array(E);return Object.setPrototypeOf(p,o.prototype),p}function o(E,p,y){if(typeof E=="number"){if(typeof p=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return l(E)}return c(E,p,y)}o.poolSize=8192;function c(E,p,y){if(typeof E=="string")return h(E,p);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(Ft(E,ArrayBuffer)||E&&Ft(E.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Ft(E,SharedArrayBuffer)||E&&Ft(E.buffer,SharedArrayBuffer)))return g(E,p,y);if(typeof E=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const T=E.valueOf&&E.valueOf();if(T!=null&&T!==E)return o.from(T,p,y);const N=x(E);if(N)return N;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof E[Symbol.toPrimitive]=="function")return o.from(E[Symbol.toPrimitive]("string"),p,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,p,y){return c(E,p,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 f(E,p,y){return u(E),E<=0?a(E):p!==void 0?typeof y=="string"?a(E).fill(p,y):a(E).fill(p):a(E)}o.alloc=function(E,p,y){return f(E,p,y)};function l(E){return u(E),a(E<0?0:A(E)|0)}o.allocUnsafe=function(E){return l(E)},o.allocUnsafeSlow=function(E){return l(E)};function h(E,p){if((typeof p!="string"||p==="")&&(p="utf8"),!o.isEncoding(p))throw new TypeError("Unknown encoding: "+p);const y=w(E,p)|0;let T=a(y);const N=T.write(E,p);return N!==y&&(T=T.slice(0,N)),T}function d(E){const p=E.length<0?0:A(E.length)|0,y=a(p);for(let T=0;T<p;T+=1)y[T]=E[T]&255;return y}function b(E){if(Ft(E,Uint8Array)){const p=new Uint8Array(E);return g(p.buffer,p.byteOffset,p.byteLength)}return d(E)}function g(E,p,y){if(p<0||E.byteLength<p)throw new RangeError('"offset" is outside of buffer bounds');if(E.byteLength<p+(y||0))throw new RangeError('"length" is outside of buffer bounds');let T;return p===void 0&&y===void 0?T=new Uint8Array(E):y===void 0?T=new Uint8Array(E,p):T=new Uint8Array(E,p,y),Object.setPrototypeOf(T,o.prototype),T}function x(E){if(o.isBuffer(E)){const p=A(E.length)|0,y=a(p);return y.length===0||E.copy(y,0,0,p),y}if(E.length!==void 0)return typeof E.length!="number"||Wn(E.length)?a(0):d(E);if(E.type==="Buffer"&&Array.isArray(E.data))return d(E.data)}function A(E){if(E>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return E|0}function k(E){return+E!=E&&(E=0),o.alloc(+E)}o.isBuffer=function(p){return p!=null&&p._isBuffer===!0&&p!==o.prototype},o.compare=function(p,y){if(Ft(p,Uint8Array)&&(p=o.from(p,p.offset,p.byteLength)),Ft(y,Uint8Array)&&(y=o.from(y,y.offset,y.byteLength)),!o.isBuffer(p)||!o.isBuffer(y))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(p===y)return 0;let T=p.length,N=y.length;for(let j=0,W=Math.min(T,N);j<W;++j)if(p[j]!==y[j]){T=p[j],N=y[j];break}return T<N?-1:N<T?1:0},o.isEncoding=function(p){switch(String(p).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(p,y){if(!Array.isArray(p))throw new TypeError('"list" argument must be an Array of Buffers');if(p.length===0)return o.alloc(0);let T;if(y===void 0)for(y=0,T=0;T<p.length;++T)y+=p[T].length;const N=o.allocUnsafe(y);let j=0;for(T=0;T<p.length;++T){let W=p[T];if(Ft(W,Uint8Array))j+W.length>N.length?(o.isBuffer(W)||(W=o.from(W)),W.copy(N,j)):Uint8Array.prototype.set.call(N,W,j);else if(o.isBuffer(W))W.copy(N,j);else throw new TypeError('"list" argument must be an Array of Buffers');j+=W.length}return N};function w(E,p){if(o.isBuffer(E))return E.length;if(ArrayBuffer.isView(E)||Ft(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,T=arguments.length>2&&arguments[2]===!0;if(!T&&y===0)return 0;let N=!1;for(;;)switch(p){case"ascii":case"latin1":case"binary":return y;case"utf8":case"utf-8":return Kr(E).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return y*2;case"hex":return y>>>1;case"base64":return Xr(E).length;default:if(N)return T?-1:Kr(E).length;p=(""+p).toLowerCase(),N=!0}}o.byteLength=w;function v(E,p,y){let T=!1;if((p===void 0||p<0)&&(p=0),p>this.length||((y===void 0||y>this.length)&&(y=this.length),y<=0)||(y>>>=0,p>>>=0,y<=p))return"";for(E||(E="utf8");;)switch(E){case"hex":return O(this,p,y);case"utf8":case"utf-8":return Q(this,p,y);case"ascii":return ee(this,p,y);case"latin1":case"binary":return q(this,p,y);case"base64":return z(this,p,y);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,p,y);default:if(T)throw new TypeError("Unknown encoding: "+E);E=(E+"").toLowerCase(),T=!0}}o.prototype._isBuffer=!0;function S(E,p,y){const T=E[p];E[p]=E[y],E[y]=T}o.prototype.swap16=function(){const p=this.length;if(p%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let y=0;y<p;y+=2)S(this,y,y+1);return this},o.prototype.swap32=function(){const p=this.length;if(p%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let y=0;y<p;y+=4)S(this,y,y+3),S(this,y+1,y+2);return this},o.prototype.swap64=function(){const p=this.length;if(p%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let y=0;y<p;y+=8)S(this,y,y+7),S(this,y+1,y+6),S(this,y+2,y+5),S(this,y+3,y+4);return this},o.prototype.toString=function(){const p=this.length;return p===0?"":arguments.length===0?Q(this,0,p):v.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(p){if(!o.isBuffer(p))throw new TypeError("Argument must be a Buffer");return this===p?!0:o.compare(this,p)===0},o.prototype.inspect=function(){let p="";const y=e.INSPECT_MAX_BYTES;return p=this.toString("hex",0,y).replace(/(.{2})/g,"$1 ").trim(),this.length>y&&(p+=" ... "),"<Buffer "+p+">"},n&&(o.prototype[n]=o.prototype.inspect),o.prototype.compare=function(p,y,T,N,j){if(Ft(p,Uint8Array)&&(p=o.from(p,p.offset,p.byteLength)),!o.isBuffer(p))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof p);if(y===void 0&&(y=0),T===void 0&&(T=p?p.length:0),N===void 0&&(N=0),j===void 0&&(j=this.length),y<0||T>p.length||N<0||j>this.length)throw new RangeError("out of range index");if(N>=j&&y>=T)return 0;if(N>=j)return-1;if(y>=T)return 1;if(y>>>=0,T>>>=0,N>>>=0,j>>>=0,this===p)return 0;let W=j-N,ve=T-y;const Ke=Math.min(W,ve),De=this.slice(N,j),Xe=p.slice(y,T);for(let Oe=0;Oe<Ke;++Oe)if(De[Oe]!==Xe[Oe]){W=De[Oe],ve=Xe[Oe];break}return W<ve?-1:ve<W?1:0};function I(E,p,y,T,N){if(E.length===0)return-1;if(typeof y=="string"?(T=y,y=0):y>2147483647?y=2147483647:y<-2147483648&&(y=-2147483648),y=+y,Wn(y)&&(y=N?0:E.length-1),y<0&&(y=E.length+y),y>=E.length){if(N)return-1;y=E.length-1}else if(y<0)if(N)y=0;else return-1;if(typeof p=="string"&&(p=o.from(p,T)),o.isBuffer(p))return p.length===0?-1:_(E,p,y,T,N);if(typeof p=="number")return p=p&255,typeof Uint8Array.prototype.indexOf=="function"?N?Uint8Array.prototype.indexOf.call(E,p,y):Uint8Array.prototype.lastIndexOf.call(E,p,y):_(E,[p],y,T,N);throw new TypeError("val must be string, number or Buffer")}function _(E,p,y,T,N){let j=1,W=E.length,ve=p.length;if(T!==void 0&&(T=String(T).toLowerCase(),T==="ucs2"||T==="ucs-2"||T==="utf16le"||T==="utf-16le")){if(E.length<2||p.length<2)return-1;j=2,W/=2,ve/=2,y/=2}function Ke(Xe,Oe){return j===1?Xe[Oe]:Xe.readUInt16BE(Oe*j)}let De;if(N){let Xe=-1;for(De=y;De<W;De++)if(Ke(E,De)===Ke(p,Xe===-1?0:De-Xe)){if(Xe===-1&&(Xe=De),De-Xe+1===ve)return Xe*j}else Xe!==-1&&(De-=De-Xe),Xe=-1}else for(y+ve>W&&(y=W-ve),De=y;De>=0;De--){let Xe=!0;for(let Oe=0;Oe<ve;Oe++)if(Ke(E,De+Oe)!==Ke(p,Oe)){Xe=!1;break}if(Xe)return De}return-1}o.prototype.includes=function(p,y,T){return this.indexOf(p,y,T)!==-1},o.prototype.indexOf=function(p,y,T){return I(this,p,y,T,!0)},o.prototype.lastIndexOf=function(p,y,T){return I(this,p,y,T,!1)};function R(E,p,y,T){y=Number(y)||0;const N=E.length-y;T?(T=Number(T),T>N&&(T=N)):T=N;const j=p.length;T>j/2&&(T=j/2);let W;for(W=0;W<T;++W){const ve=parseInt(p.substr(W*2,2),16);if(Wn(ve))return W;E[y+W]=ve}return W}function B(E,p,y,T){return Ut(Kr(p,E.length-y),E,y,T)}function M(E,p,y,T){return Ut(Fi(p),E,y,T)}function F(E,p,y,T){return Ut(Xr(p),E,y,T)}function H(E,p,y,T){return Ut(X(p,E.length-y),E,y,T)}o.prototype.write=function(p,y,T,N){if(y===void 0)N="utf8",T=this.length,y=0;else if(T===void 0&&typeof y=="string")N=y,T=this.length,y=0;else if(isFinite(y))y=y>>>0,isFinite(T)?(T=T>>>0,N===void 0&&(N="utf8")):(N=T,T=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const j=this.length-y;if((T===void 0||T>j)&&(T=j),p.length>0&&(T<0||y<0)||y>this.length)throw new RangeError("Attempt to write outside buffer bounds");N||(N="utf8");let W=!1;for(;;)switch(N){case"hex":return R(this,p,y,T);case"utf8":case"utf-8":return B(this,p,y,T);case"ascii":case"latin1":case"binary":return M(this,p,y,T);case"base64":return F(this,p,y,T);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return H(this,p,y,T);default:if(W)throw new TypeError("Unknown encoding: "+N);N=(""+N).toLowerCase(),W=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function z(E,p,y){return p===0&&y===E.length?t.fromByteArray(E):t.fromByteArray(E.slice(p,y))}function Q(E,p,y){y=Math.min(E.length,y);const T=[];let N=p;for(;N<y;){const j=E[N];let W=null,ve=j>239?4:j>223?3:j>191?2:1;if(N+ve<=y){let Ke,De,Xe,Oe;switch(ve){case 1:j<128&&(W=j);break;case 2:Ke=E[N+1],(Ke&192)===128&&(Oe=(j&31)<<6|Ke&63,Oe>127&&(W=Oe));break;case 3:Ke=E[N+1],De=E[N+2],(Ke&192)===128&&(De&192)===128&&(Oe=(j&15)<<12|(Ke&63)<<6|De&63,Oe>2047&&(Oe<55296||Oe>57343)&&(W=Oe));break;case 4:Ke=E[N+1],De=E[N+2],Xe=E[N+3],(Ke&192)===128&&(De&192)===128&&(Xe&192)===128&&(Oe=(j&15)<<18|(Ke&63)<<12|(De&63)<<6|Xe&63,Oe>65535&&Oe<1114112&&(W=Oe))}}W===null?(W=65533,ve=1):W>65535&&(W-=65536,T.push(W>>>10&1023|55296),W=56320|W&1023),T.push(W),N+=ve}return K(T)}const U=4096;function K(E){const p=E.length;if(p<=U)return String.fromCharCode.apply(String,E);let y="",T=0;for(;T<p;)y+=String.fromCharCode.apply(String,E.slice(T,T+=U));return y}function ee(E,p,y){let T="";y=Math.min(E.length,y);for(let N=p;N<y;++N)T+=String.fromCharCode(E[N]&127);return T}function q(E,p,y){let T="";y=Math.min(E.length,y);for(let N=p;N<y;++N)T+=String.fromCharCode(E[N]);return T}function O(E,p,y){const T=E.length;(!p||p<0)&&(p=0),(!y||y<0||y>T)&&(y=T);let N="";for(let j=p;j<y;++j)N+=Ss[E[j]];return N}function L(E,p,y){const T=E.slice(p,y);let N="";for(let j=0;j<T.length-1;j+=2)N+=String.fromCharCode(T[j]+T[j+1]*256);return N}o.prototype.slice=function(p,y){const T=this.length;p=~~p,y=y===void 0?T:~~y,p<0?(p+=T,p<0&&(p=0)):p>T&&(p=T),y<0?(y+=T,y<0&&(y=0)):y>T&&(y=T),y<p&&(y=p);const N=this.subarray(p,y);return Object.setPrototypeOf(N,o.prototype),N};function Y(E,p,y){if(E%1!==0||E<0)throw new RangeError("offset is not uint");if(E+p>y)throw new RangeError("Trying to access beyond buffer length")}o.prototype.readUintLE=o.prototype.readUIntLE=function(p,y,T){p=p>>>0,y=y>>>0,T||Y(p,y,this.length);let N=this[p],j=1,W=0;for(;++W<y&&(j*=256);)N+=this[p+W]*j;return N},o.prototype.readUintBE=o.prototype.readUIntBE=function(p,y,T){p=p>>>0,y=y>>>0,T||Y(p,y,this.length);let N=this[p+--y],j=1;for(;y>0&&(j*=256);)N+=this[p+--y]*j;return N},o.prototype.readUint8=o.prototype.readUInt8=function(p,y){return p=p>>>0,y||Y(p,1,this.length),this[p]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(p,y){return p=p>>>0,y||Y(p,2,this.length),this[p]|this[p+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(p,y){return p=p>>>0,y||Y(p,2,this.length),this[p]<<8|this[p+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(p,y){return p=p>>>0,y||Y(p,4,this.length),(this[p]|this[p+1]<<8|this[p+2]<<16)+this[p+3]*16777216},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(p,y){return p=p>>>0,y||Y(p,4,this.length),this[p]*16777216+(this[p+1]<<16|this[p+2]<<8|this[p+3])},o.prototype.readBigUInt64LE=Kn(function(p){p=p>>>0,Ae(p,"offset");const y=this[p],T=this[p+7];(y===void 0||T===void 0)&&_e(p,this.length-8);const N=y+this[++p]*2**8+this[++p]*2**16+this[++p]*2**24,j=this[++p]+this[++p]*2**8+this[++p]*2**16+T*2**24;return BigInt(N)+(BigInt(j)<<BigInt(32))}),o.prototype.readBigUInt64BE=Kn(function(p){p=p>>>0,Ae(p,"offset");const y=this[p],T=this[p+7];(y===void 0||T===void 0)&&_e(p,this.length-8);const N=y*2**24+this[++p]*2**16+this[++p]*2**8+this[++p],j=this[++p]*2**24+this[++p]*2**16+this[++p]*2**8+T;return(BigInt(N)<<BigInt(32))+BigInt(j)}),o.prototype.readIntLE=function(p,y,T){p=p>>>0,y=y>>>0,T||Y(p,y,this.length);let N=this[p],j=1,W=0;for(;++W<y&&(j*=256);)N+=this[p+W]*j;return j*=128,N>=j&&(N-=Math.pow(2,8*y)),N},o.prototype.readIntBE=function(p,y,T){p=p>>>0,y=y>>>0,T||Y(p,y,this.length);let N=y,j=1,W=this[p+--N];for(;N>0&&(j*=256);)W+=this[p+--N]*j;return j*=128,W>=j&&(W-=Math.pow(2,8*y)),W},o.prototype.readInt8=function(p,y){return p=p>>>0,y||Y(p,1,this.length),this[p]&128?(255-this[p]+1)*-1:this[p]},o.prototype.readInt16LE=function(p,y){p=p>>>0,y||Y(p,2,this.length);const T=this[p]|this[p+1]<<8;return T&32768?T|4294901760:T},o.prototype.readInt16BE=function(p,y){p=p>>>0,y||Y(p,2,this.length);const T=this[p+1]|this[p]<<8;return T&32768?T|4294901760:T},o.prototype.readInt32LE=function(p,y){return p=p>>>0,y||Y(p,4,this.length),this[p]|this[p+1]<<8|this[p+2]<<16|this[p+3]<<24},o.prototype.readInt32BE=function(p,y){return p=p>>>0,y||Y(p,4,this.length),this[p]<<24|this[p+1]<<16|this[p+2]<<8|this[p+3]},o.prototype.readBigInt64LE=Kn(function(p){p=p>>>0,Ae(p,"offset");const y=this[p],T=this[p+7];(y===void 0||T===void 0)&&_e(p,this.length-8);const N=this[p+4]+this[p+5]*2**8+this[p+6]*2**16+(T<<24);return(BigInt(N)<<BigInt(32))+BigInt(y+this[++p]*2**8+this[++p]*2**16+this[++p]*2**24)}),o.prototype.readBigInt64BE=Kn(function(p){p=p>>>0,Ae(p,"offset");const y=this[p],T=this[p+7];(y===void 0||T===void 0)&&_e(p,this.length-8);const N=(y<<24)+this[++p]*2**16+this[++p]*2**8+this[++p];return(BigInt(N)<<BigInt(32))+BigInt(this[++p]*2**24+this[++p]*2**16+this[++p]*2**8+T)}),o.prototype.readFloatLE=function(p,y){return p=p>>>0,y||Y(p,4,this.length),r.read(this,p,!0,23,4)},o.prototype.readFloatBE=function(p,y){return p=p>>>0,y||Y(p,4,this.length),r.read(this,p,!1,23,4)},o.prototype.readDoubleLE=function(p,y){return p=p>>>0,y||Y(p,8,this.length),r.read(this,p,!0,52,8)},o.prototype.readDoubleBE=function(p,y){return p=p>>>0,y||Y(p,8,this.length),r.read(this,p,!1,52,8)};function C(E,p,y,T,N,j){if(!o.isBuffer(E))throw new TypeError('"buffer" argument must be a Buffer instance');if(p>N||p<j)throw new RangeError('"value" argument is out of bounds');if(y+T>E.length)throw new RangeError("Index out of range")}o.prototype.writeUintLE=o.prototype.writeUIntLE=function(p,y,T,N){if(p=+p,y=y>>>0,T=T>>>0,!N){const ve=Math.pow(2,8*T)-1;C(this,p,y,T,ve,0)}let j=1,W=0;for(this[y]=p&255;++W<T&&(j*=256);)this[y+W]=p/j&255;return y+T},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(p,y,T,N){if(p=+p,y=y>>>0,T=T>>>0,!N){const ve=Math.pow(2,8*T)-1;C(this,p,y,T,ve,0)}let j=T-1,W=1;for(this[y+j]=p&255;--j>=0&&(W*=256);)this[y+j]=p/W&255;return y+T},o.prototype.writeUint8=o.prototype.writeUInt8=function(p,y,T){return p=+p,y=y>>>0,T||C(this,p,y,1,255,0),this[y]=p&255,y+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(p,y,T){return p=+p,y=y>>>0,T||C(this,p,y,2,65535,0),this[y]=p&255,this[y+1]=p>>>8,y+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(p,y,T){return p=+p,y=y>>>0,T||C(this,p,y,2,65535,0),this[y]=p>>>8,this[y+1]=p&255,y+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(p,y,T){return p=+p,y=y>>>0,T||C(this,p,y,4,4294967295,0),this[y+3]=p>>>24,this[y+2]=p>>>16,this[y+1]=p>>>8,this[y]=p&255,y+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(p,y,T){return p=+p,y=y>>>0,T||C(this,p,y,4,4294967295,0),this[y]=p>>>24,this[y+1]=p>>>16,this[y+2]=p>>>8,this[y+3]=p&255,y+4};function $(E,p,y,T,N){we(p,T,N,E,y,7);let j=Number(p&BigInt(4294967295));E[y++]=j,j=j>>8,E[y++]=j,j=j>>8,E[y++]=j,j=j>>8,E[y++]=j;let W=Number(p>>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 V(E,p,y,T,N){we(p,T,N,E,y,7);let j=Number(p&BigInt(4294967295));E[y+7]=j,j=j>>8,E[y+6]=j,j=j>>8,E[y+5]=j,j=j>>8,E[y+4]=j;let W=Number(p>>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=Kn(function(p,y=0){return $(this,p,y,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=Kn(function(p,y=0){return V(this,p,y,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(p,y,T,N){if(p=+p,y=y>>>0,!N){const Ke=Math.pow(2,8*T-1);C(this,p,y,T,Ke-1,-Ke)}let j=0,W=1,ve=0;for(this[y]=p&255;++j<T&&(W*=256);)p<0&&ve===0&&this[y+j-1]!==0&&(ve=1),this[y+j]=(p/W>>0)-ve&255;return y+T},o.prototype.writeIntBE=function(p,y,T,N){if(p=+p,y=y>>>0,!N){const Ke=Math.pow(2,8*T-1);C(this,p,y,T,Ke-1,-Ke)}let j=T-1,W=1,ve=0;for(this[y+j]=p&255;--j>=0&&(W*=256);)p<0&&ve===0&&this[y+j+1]!==0&&(ve=1),this[y+j]=(p/W>>0)-ve&255;return y+T},o.prototype.writeInt8=function(p,y,T){return p=+p,y=y>>>0,T||C(this,p,y,1,127,-128),p<0&&(p=255+p+1),this[y]=p&255,y+1},o.prototype.writeInt16LE=function(p,y,T){return p=+p,y=y>>>0,T||C(this,p,y,2,32767,-32768),this[y]=p&255,this[y+1]=p>>>8,y+2},o.prototype.writeInt16BE=function(p,y,T){return p=+p,y=y>>>0,T||C(this,p,y,2,32767,-32768),this[y]=p>>>8,this[y+1]=p&255,y+2},o.prototype.writeInt32LE=function(p,y,T){return p=+p,y=y>>>0,T||C(this,p,y,4,2147483647,-2147483648),this[y]=p&255,this[y+1]=p>>>8,this[y+2]=p>>>16,this[y+3]=p>>>24,y+4},o.prototype.writeInt32BE=function(p,y,T){return p=+p,y=y>>>0,T||C(this,p,y,4,2147483647,-2147483648),p<0&&(p=4294967295+p+1),this[y]=p>>>24,this[y+1]=p>>>16,this[y+2]=p>>>8,this[y+3]=p&255,y+4},o.prototype.writeBigInt64LE=Kn(function(p,y=0){return $(this,p,y,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=Kn(function(p,y=0){return V(this,p,y,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ie(E,p,y,T,N,j){if(y+T>E.length)throw new RangeError("Index out of range");if(y<0)throw new RangeError("Index out of range")}function ce(E,p,y,T,N){return p=+p,y=y>>>0,N||ie(E,p,y,4),r.write(E,p,y,T,23,4),y+4}o.prototype.writeFloatLE=function(p,y,T){return ce(this,p,y,!0,T)},o.prototype.writeFloatBE=function(p,y,T){return ce(this,p,y,!1,T)};function de(E,p,y,T,N){return p=+p,y=y>>>0,N||ie(E,p,y,8),r.write(E,p,y,T,52,8),y+8}o.prototype.writeDoubleLE=function(p,y,T){return de(this,p,y,!0,T)},o.prototype.writeDoubleBE=function(p,y,T){return de(this,p,y,!1,T)},o.prototype.copy=function(p,y,T,N){if(!o.isBuffer(p))throw new TypeError("argument should be a Buffer");if(T||(T=0),!N&&N!==0&&(N=this.length),y>=p.length&&(y=p.length),y||(y=0),N>0&&N<T&&(N=T),N===T||p.length===0||this.length===0)return 0;if(y<0)throw new RangeError("targetStart out of bounds");if(T<0||T>=this.length)throw new RangeError("Index out of range");if(N<0)throw new RangeError("sourceEnd out of bounds");N>this.length&&(N=this.length),p.length-y<N-T&&(N=p.length-y+T);const j=N-T;return this===p&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(y,T,N):Uint8Array.prototype.set.call(p,this.subarray(T,N),y),j},o.prototype.fill=function(p,y,T,N){if(typeof p=="string"){if(typeof y=="string"?(N=y,y=0,T=this.length):typeof T=="string"&&(N=T,T=this.length),N!==void 0&&typeof N!="string")throw new TypeError("encoding must be a string");if(typeof N=="string"&&!o.isEncoding(N))throw new TypeError("Unknown encoding: "+N);if(p.length===1){const W=p.charCodeAt(0);(N==="utf8"&&W<128||N==="latin1")&&(p=W)}}else typeof p=="number"?p=p&255:typeof p=="boolean"&&(p=Number(p));if(y<0||this.length<y||this.length<T)throw new RangeError("Out of range index");if(T<=y)return this;y=y>>>0,T=T===void 0?this.length:T>>>0,p||(p=0);let j;if(typeof p=="number")for(j=y;j<T;++j)this[j]=p;else{const W=o.isBuffer(p)?p:o.from(p,N),ve=W.length;if(ve===0)throw new TypeError('The value "'+p+'" is invalid for argument "value"');for(j=0;j<T-y;++j)this[j+y]=W[j%ve]}return this};const le={};function oe(E,p,y){le[E]=class extends y{constructor(){super(),Object.defineProperty(this,"message",{value:p.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${E}]`,this.stack,delete this.name}get code(){return E}set code(N){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:N,writable:!0})}toString(){return`${this.name} [${E}]: ${this.message}`}}}oe("ERR_BUFFER_OUT_OF_BOUNDS",function(E){return E?`${E} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),oe("ERR_INVALID_ARG_TYPE",function(E,p){return`The "${E}" argument must be of type number. Received type ${typeof p}`},TypeError),oe("ERR_OUT_OF_RANGE",function(E,p,y){let T=`The value of "${E}" is out of range.`,N=y;return Number.isInteger(y)&&Math.abs(y)>2**32?N=ae(String(y)):typeof y=="bigint"&&(N=String(y),(y>BigInt(2)**BigInt(32)||y<-(BigInt(2)**BigInt(32)))&&(N=ae(N)),N+="n"),T+=` It must be ${p}. Received ${N}`,T},RangeError);function ae(E){let p="",y=E.length;const T=E[0]==="-"?1:0;for(;y>=T+4;y-=3)p=`_${E.slice(y-3,y)}${p}`;return`${E.slice(0,y)}${p}`}function ge(E,p,y){Ae(p,"offset"),(E[p]===void 0||E[p+y]===void 0)&&_e(p,E.length-(y+1))}function we(E,p,y,T,N,j){if(E>y||E<p){const W=typeof p=="bigint"?"n":"";let ve;throw p===0||p===BigInt(0)?ve=`>= 0${W} and < 2${W} ** ${(j+1)*8}${W}`:ve=`>= -(2${W} ** ${(j+1)*8-1}${W}) and < 2 ** ${(j+1)*8-1}${W}`,new le.ERR_OUT_OF_RANGE("value",ve,E)}ge(T,N,j)}function Ae(E,p){if(typeof E!="number")throw new le.ERR_INVALID_ARG_TYPE(p,"number",E)}function _e(E,p,y){throw Math.floor(E)!==E?(Ae(E,y),new le.ERR_OUT_OF_RANGE("offset","an integer",E)):p<0?new le.ERR_BUFFER_OUT_OF_BOUNDS:new le.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${p}`,E)}const ct=/[^+/0-9A-Za-z-_]/g;function Ne(E){if(E=E.split("=")[0],E=E.trim().replace(ct,""),E.length<2)return"";for(;E.length%4!==0;)E=E+"=";return E}function Kr(E,p){p=p||1/0;let y;const T=E.length;let N=null;const j=[];for(let W=0;W<T;++W){if(y=E.charCodeAt(W),y>55295&&y<57344){if(!N){if(y>56319){(p-=3)>-1&&j.push(239,191,189);continue}else if(W+1===T){(p-=3)>-1&&j.push(239,191,189);continue}N=y;continue}if(y<56320){(p-=3)>-1&&j.push(239,191,189),N=y;continue}y=(N-55296<<10|y-56320)+65536}else N&&(p-=3)>-1&&j.push(239,191,189);if(N=null,y<128){if((p-=1)<0)break;j.push(y)}else if(y<2048){if((p-=2)<0)break;j.push(y>>6|192,y&63|128)}else if(y<65536){if((p-=3)<0)break;j.push(y>>12|224,y>>6&63|128,y&63|128)}else if(y<1114112){if((p-=4)<0)break;j.push(y>>18|240,y>>12&63|128,y>>6&63|128,y&63|128)}else throw new Error("Invalid code point")}return j}function Fi(E){const p=[];for(let y=0;y<E.length;++y)p.push(E.charCodeAt(y)&255);return p}function X(E,p){let y,T,N;const j=[];for(let W=0;W<E.length&&!((p-=2)<0);++W)y=E.charCodeAt(W),T=y>>8,N=y%256,j.push(N),j.push(T);return j}function Xr(E){return t.toByteArray(Ne(E))}function Ut(E,p,y,T){let N;for(N=0;N<T&&!(N+y>=p.length||N>=E.length);++N)p[N+y]=E[N];return N}function Ft(E,p){return E instanceof p||E!=null&&E.constructor!=null&&E.constructor.name!=null&&E.constructor.name===p.name}function Wn(E){return E!==E}const Ss=function(){const E="0123456789abcdef",p=new Array(256);for(let y=0;y<16;++y){const T=y*16;for(let N=0;N<16;++N)p[T+N]=E[y]+E[N]}return p}();function Kn(E){return typeof BigInt>"u"?K5:E}function K5(){throw new Error("BigInt not supported")}})(bs);var no={Array:function(e){return e!=null&&e.constructor===Array},Boolean:function(e){return typeof e=="boolean"},Function:function(e){return typeof e=="function"},Nil:function(e){return e==null},Number:function(e){return typeof e=="number"},Object:function(e){return typeof e=="object"},String:function(e){return typeof e=="string"},"":function(){return!0}};no.Null=no.Nil;for(var Dp in no)no[Dp].toJSON=(function(e){return e}).bind(null,Dp);var qh=no,Yi=qh;function Gb(e){return e.name||e.toString().match(/function (.*?)\s*\(/)[1]}function Wh(e){return Yi.Nil(e)?"":Gb(e.constructor)}function Bv(e){return Yi.Function(e)?"":Yi.String(e)?JSON.stringify(e):e&&Yi.Object(e)?"":e}function Kh(e,t){Error.captureStackTrace&&Error.captureStackTrace(e,t)}function iu(e){return Yi.Function(e)?e.toJSON?e.toJSON():Gb(e):Yi.Array(e)?"Array":e&&Yi.Object(e)?"Object":e!==void 0?e:""}function qb(e,t,r){var n=Bv(t);return"Expected "+iu(e)+", got"+(r!==""?" "+r:"")+(n!==""?" "+n:"")}function Hn(e,t,r){r=r||Wh(t),this.message=qb(e,t,r),Kh(this,Hn),this.__type=e,this.__value=t,this.__valueTypeName=r}Hn.prototype=Object.create(Error.prototype);Hn.prototype.constructor=Hn;function Cv(e,t,r,n,i){var s='" of type ';return t==="key"&&(s='" with key type '),qb('property "'+iu(r)+s+iu(e),n,i)}function Ds(e,t,r,n,i){e?(i=i||Wh(n),this.message=Cv(e,r,t,n,i)):this.message='Unexpected property "'+t+'"',Kh(this,Hn),this.__label=r,this.__property=t,this.__type=e,this.__value=n,this.__valueTypeName=i}Ds.prototype=Object.create(Error.prototype);Ds.prototype.constructor=Hn;function Rv(e,t){return new Hn(e,{},t)}function Nv(e,t,r){return e instanceof Ds?(t=t+"."+e.__property,e=new Ds(e.__type,t,e.__label,e.__value,e.__valueTypeName)):e instanceof Hn&&(e=new Ds(e.__type,t,r,e.__value,e.__valueTypeName)),Kh(e),e}var Wb={TfTypeError:Hn,TfPropertyTypeError:Ds,tfCustomError:Rv,tfSubError:Nv,tfJSON:iu,getValueTypeName:Wh},Of,zp;function Uv(){if(zp)return Of;zp=1;var e=qh,t=Wb;function r(I){return Buffer.isBuffer(I)}function n(I){return typeof I=="string"&&/^([0-9a-f]{2})+$/i.test(I)}function i(I,_){var R=I.toJSON();function B(M){if(!I(M))return!1;if(M.length===_)return!0;throw t.tfCustomError(R+"(Length: "+_+")",R+"(Length: "+M.length+")")}return B.toJSON=function(){return R},B}var s=i.bind(null,e.Array),a=i.bind(null,r),o=i.bind(null,n),c=i.bind(null,e.String);function u(I,_,R){R=R||e.Number;function B(M,F){return R(M,F)&&M>I&&M<_}return B.toJSON=function(){return`${R.toJSON()} between [${I}, ${_}]`},B}var f=Math.pow(2,53)-1;function l(I){return typeof I=="number"&&isFinite(I)}function h(I){return I<<24>>24===I}function d(I){return I<<16>>16===I}function b(I){return(I|0)===I}function g(I){return typeof I=="number"&&I>=-f&&I<=f&&Math.floor(I)===I}function x(I){return(I&255)===I}function A(I){return(I&65535)===I}function k(I){return I>>>0===I}function w(I){return typeof I=="number"&&I>=0&&I<=f&&Math.floor(I)===I}var v={ArrayN:s,Buffer:r,BufferN:a,Finite:l,Hex:n,HexN:o,Int8:h,Int16:d,Int32:b,Int53:g,Range:u,StringN:c,UInt8:x,UInt16:A,UInt32:k,UInt53:w};for(var S in v)v[S].toJSON=(function(I){return I}).bind(null,S);return Of=v,Of}var Do=Wb,wt=qh,gn=Do.tfJSON,Kb=Do.TfTypeError,Xb=Do.TfPropertyTypeError,Sa=Do.tfSubError,Fv=Do.getValueTypeName,Rn={arrayOf:function(t,r){t=an(t),r=r||{};function n(i,s){return!wt.Array(i)||wt.Nil(i)||r.minLength!==void 0&&i.length<r.minLength||r.maxLength!==void 0&&i.length>r.maxLength||r.length!==void 0&&i.length!==r.length?!1:i.every(function(a,o){try{return Lt(t,a,s)}catch(c){throw Sa(c,o)}})}return n.toJSON=function(){var i="["+gn(t)+"]";return r.length!==void 0?i+="{"+r.length+"}":(r.minLength!==void 0||r.maxLength!==void 0)&&(i+="{"+(r.minLength===void 0?0:r.minLength)+","+(r.maxLength===void 0?1/0:r.maxLength)+"}"),i},n},maybe:function e(t){t=an(t);function r(n,i){return wt.Nil(n)||t(n,i,e)}return r.toJSON=function(){return"?"+gn(t)},r},map:function(t,r){t=an(t),r&&(r=an(r));function n(i,s){if(!wt.Object(i)||wt.Nil(i))return!1;for(var a in i){try{r&&Lt(r,a,s)}catch(c){throw Sa(c,a,"key")}try{var o=i[a];Lt(t,o,s)}catch(c){throw Sa(c,a)}}return!0}return r?n.toJSON=function(){return"{"+gn(r)+": "+gn(t)+"}"}:n.toJSON=function(){return"{"+gn(t)+"}"},n},object:function(t){var r={};for(var n in t)r[n]=an(t[n]);function i(s,a){if(!wt.Object(s)||wt.Nil(s))return!1;var o;try{for(o in r){var c=r[o],u=s[o];Lt(c,u,a)}}catch(f){throw Sa(f,o)}if(a){for(o in s)if(!r[o])throw new Xb(void 0,o)}return!0}return i.toJSON=function(){return gn(r)},i},anyOf:function(){var t=[].slice.call(arguments).map(an);function r(n,i){return t.some(function(s){try{return Lt(s,n,i)}catch{return!1}})}return r.toJSON=function(){return t.map(gn).join("|")},r},allOf:function(){var t=[].slice.call(arguments).map(an);function r(n,i){return t.every(function(s){try{return Lt(s,n,i)}catch{return!1}})}return r.toJSON=function(){return t.map(gn).join(" & ")},r},quacksLike:function(t){function r(n){return t===Fv(n)}return r.toJSON=function(){return t},r},tuple:function(){var t=[].slice.call(arguments).map(an);function r(n,i){return wt.Nil(n)||wt.Nil(n.length)||i&&n.length!==t.length?!1:t.every(function(s,a){try{return Lt(s,n[a],i)}catch(o){throw Sa(o,a)}})}return r.toJSON=function(){return"("+t.map(gn).join(", ")+")"},r},value:function(t){function r(n){return n===t}return r.toJSON=function(){return t},r}};Rn.oneOf=Rn.anyOf;function an(e){if(wt.String(e))return e[0]==="?"?Rn.maybe(e.slice(1)):wt[e]||Rn.quacksLike(e);if(e&&wt.Object(e)){if(wt.Array(e)){if(e.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return Rn.arrayOf(e[0])}return Rn.object(e)}else if(wt.Function(e))return e;return Rn.value(e)}function Lt(e,t,r,n){if(wt.Function(e)){if(e(t,r))return!0;throw new Kb(n||e,t)}return Lt(an(e),t,r)}for(var Ei in wt)Lt[Ei]=wt[Ei];for(Ei in Rn)Lt[Ei]=Rn[Ei];var Vp=Uv();for(Ei in Vp)Lt[Ei]=Vp[Ei];Lt.compile=an;Lt.TfTypeError=Kb;Lt.TfPropertyTypeError=Xb;var $v=Lt;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.oneOf=e.Null=e.BufferN=e.Function=e.UInt32=e.UInt8=e.tuple=e.maybe=e.Hex=e.Buffer=e.String=e.Boolean=e.Array=e.Number=e.Hash256bit=e.Hash160bit=e.Buffer256bit=e.isTaptree=e.isTapleaf=e.TAPLEAF_VERSION_MASK=e.Satoshi=e.isPoint=e.stacksEqual=e.typeforce=void 0;const t=bs;e.typeforce=$v;const r=t.Buffer.alloc(32,0),n=t.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function i(f,l){return f.length!==l.length?!1:f.every((h,d)=>h.equals(l[d]))}e.stacksEqual=i;function s(f){if(!t.Buffer.isBuffer(f)||f.length<33)return!1;const l=f[0],h=f.slice(1,33);if(h.compare(r)===0||h.compare(n)>=0)return!1;if((l===2||l===3)&&f.length===33)return!0;const d=f.slice(33);return d.compare(r)===0||d.compare(n)>=0?!1:l===4&&f.length===65}e.isPoint=s;const a=21*1e14;function o(f){return e.typeforce.UInt53(f)&&f<=a}e.Satoshi=o,e.TAPLEAF_VERSION_MASK=254;function c(f){return!f||!("output"in f)||!t.Buffer.isBuffer(f.output)?!1:f.version!==void 0?(f.version&e.TAPLEAF_VERSION_MASK)===f.version:!0}e.isTapleaf=c;function u(f){return(0,e.Array)(f)?f.length!==2?!1:f.every(l=>u(l)):c(f)}e.isTaptree=u,e.Buffer256bit=e.typeforce.BufferN(32),e.Hash160bit=e.typeforce.BufferN(20),e.Hash256bit=e.typeforce.BufferN(32),e.Number=e.typeforce.Number,e.Array=e.typeforce.Array,e.Boolean=e.typeforce.Boolean,e.String=e.typeforce.String,e.Buffer=e.typeforce.Buffer,e.Hex=e.typeforce.Hex,e.maybe=e.typeforce.maybe,e.tuple=e.typeforce.tuple,e.UInt8=e.typeforce.UInt8,e.UInt32=e.typeforce.UInt32,e.Function=e.typeforce.Function,e.BufferN=e.typeforce.BufferN,e.Null=e.typeforce.Null,e.oneOf=e.typeforce.oneOf})(Rt);var zo={},vt={};Object.defineProperty(vt,"__esModule",{value:!0});vt.BufferReader=vt.BufferWriter=vt.cloneBuffer=vt.reverseBuffer=vt.writeUInt64LE=vt.readUInt64LE=vt.varuint=void 0;const Zi=Rt,{typeforce:Jb}=Zi,io=jb;vt.varuint=io;function Yb(e,t){if(typeof e!="number")throw new Error("cannot write a non-number as a number");if(e<0)throw new Error("specified a negative value for writing an unsigned value");if(e>t)throw new Error("RangeError: value out of range");if(Math.floor(e)!==e)throw new Error("value has a fractional component")}function Zb(e,t){const r=e.readUInt32LE(t);let n=e.readUInt32LE(t+4);return n*=4294967296,Yb(n+r,9007199254740991),n+r}vt.readUInt64LE=Zb;function Qb(e,t,r){return Yb(t,9007199254740991),e.writeInt32LE(t&-1,r),e.writeUInt32LE(Math.floor(t/4294967296),r+4),r+8}vt.writeUInt64LE=Qb;function Mv(e){if(e.length<1)return e;let t=e.length-1,r=0;for(let n=0;n<e.length/2;n++)r=e[n],e[n]=e[t],e[t]=r,t--;return e}vt.reverseBuffer=Mv;function jv(e){const t=Buffer.allocUnsafe(e.length);return e.copy(t),t}vt.cloneBuffer=jv;class Xh{static withCapacity(t){return new Xh(Buffer.alloc(t))}constructor(t,r=0){this.buffer=t,this.offset=r,Jb(Zi.tuple(Zi.Buffer,Zi.UInt32),[t,r])}writeUInt8(t){this.offset=this.buffer.writeUInt8(t,this.offset)}writeInt32(t){this.offset=this.buffer.writeInt32LE(t,this.offset)}writeUInt32(t){this.offset=this.buffer.writeUInt32LE(t,this.offset)}writeUInt64(t){this.offset=Qb(this.buffer,t,this.offset)}writeVarInt(t){io.encode(t,this.buffer,this.offset),this.offset+=io.encode.bytes}writeSlice(t){if(this.buffer.length<this.offset+t.length)throw new Error("Cannot write slice out of bounds");this.offset+=t.copy(this.buffer,this.offset)}writeVarSlice(t){this.writeVarInt(t.length),this.writeSlice(t)}writeVector(t){this.writeVarInt(t.length),t.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}`)}}vt.BufferWriter=Xh;class Hv{constructor(t,r=0){this.buffer=t,this.offset=r,Jb(Zi.tuple(Zi.Buffer,Zi.UInt32),[t,r])}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=Zb(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const t=io.decode(this.buffer,this.offset);return this.offset+=io.decode.bytes,t}readSlice(t){if(this.buffer.length<this.offset+t)throw new Error("Cannot read slice out of bounds");const r=this.buffer.slice(this.offset,this.offset+t);return this.offset+=t,r}readVarSlice(){return this.readSlice(this.readVarInt())}readVector(){const t=this.readVarInt(),r=[];for(let n=0;n<t;n++)r.push(this.readVarSlice());return r}}vt.BufferReader=Hv;var Bi={},Zs={},Dt={},Ot={},ku={},Tu={};Object.defineProperty(Tu,"__esModule",{value:!0});Tu.crypto=void 0;Tu.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;(function(e){/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */Object.defineProperty(e,"__esModule",{value:!0}),e.wrapXOFConstructorWithOpts=e.wrapConstructorWithOpts=e.wrapConstructor=e.Hash=e.nextTick=e.swap32IfBE=e.byteSwapIfBE=e.swap8IfBE=e.isLE=void 0,e.isBytes=r,e.anumber=n,e.abytes=i,e.ahash=s,e.aexists=a,e.aoutput=o,e.u8=c,e.u32=u,e.clean=f,e.createView=l,e.rotr=h,e.rotl=d,e.byteSwap=b,e.byteSwap32=g,e.bytesToHex=k,e.hexToBytes=S,e.asyncLoop=_,e.utf8ToBytes=R,e.bytesToUtf8=B,e.toBytes=M,e.kdfInputToBytes=F,e.concatBytes=H,e.checkOpts=z,e.createHasher=U,e.createOptHasher=K,e.createXOFer=ee,e.randomBytes=q;const t=Tu;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 i(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 s(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){i(O);const Y=L.outputLen;if(O.length<Y)throw new Error("digestInto() expects output buffer of length at least "+Y)}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 f(...O){for(let L=0;L<O.length;L++)O[L].fill(0)}function l(O){return new DataView(O.buffer,O.byteOffset,O.byteLength)}function h(O,L){return O<<32-L|O>>>L}function d(O,L){return O<<L|O>>>32-L>>>0}e.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}e.swap8IfBE=e.isLE?O=>O:O=>b(O),e.byteSwapIfBE=e.swap8IfBE;function g(O){for(let L=0;L<O.length;L++)O[L]=b(O[L]);return O}e.swap32IfBE=e.isLE?O=>O:g;const x=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",A=Array.from({length:256},(O,L)=>L.toString(16).padStart(2,"0"));function k(O){if(i(O),x)return O.toHex();let L="";for(let Y=0;Y<O.length;Y++)L+=A[O[Y]];return L}const w={_0:48,_9:57,A:65,F:70,a:97,f:102};function v(O){if(O>=w._0&&O<=w._9)return O-w._0;if(O>=w.A&&O<=w.F)return O-(w.A-10);if(O>=w.a&&O<=w.f)return O-(w.a-10)}function S(O){if(typeof O!="string")throw new Error("hex string expected, got "+typeof O);if(x)return Uint8Array.fromHex(O);const L=O.length,Y=L/2;if(L%2)throw new Error("hex string expected, got unpadded hex of length "+L);const C=new Uint8Array(Y);for(let $=0,V=0;$<Y;$++,V+=2){const ie=v(O.charCodeAt(V)),ce=v(O.charCodeAt(V+1));if(ie===void 0||ce===void 0){const de=O[V]+O[V+1];throw new Error('hex string expected, got non-hex character "'+de+'" at index '+V)}C[$]=ie*16+ce}return C}const I=async()=>{};e.nextTick=I;async function _(O,L,Y){let C=Date.now();for(let $=0;$<O;$++){Y($);const V=Date.now()-C;V>=0&&V<L||(await(0,e.nextTick)(),C+=V)}}function R(O){if(typeof O!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(O))}function B(O){return new TextDecoder().decode(O)}function M(O){return typeof O=="string"&&(O=R(O)),i(O),O}function F(O){return typeof O=="string"&&(O=R(O)),i(O),O}function H(...O){let L=0;for(let C=0;C<O.length;C++){const $=O[C];i($),L+=$.length}const Y=new Uint8Array(L);for(let C=0,$=0;C<O.length;C++){const V=O[C];Y.set(V,$),$+=V.length}return Y}function z(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{}e.Hash=Q;function U(O){const L=C=>O().update(M(C)).digest(),Y=O();return L.outputLen=Y.outputLen,L.blockLen=Y.blockLen,L.create=()=>O(),L}function K(O){const L=(C,$)=>O($).update(M(C)).digest(),Y=O({});return L.outputLen=Y.outputLen,L.blockLen=Y.blockLen,L.create=C=>O(C),L}function ee(O){const L=(C,$)=>O($).update(M(C)).digest(),Y=O({});return L.outputLen=Y.outputLen,L.blockLen=Y.blockLen,L.create=C=>O(C),L}e.wrapConstructor=U,e.wrapConstructorWithOpts=K,e.wrapXOFConstructorWithOpts=ee;function q(O=32){if(t.crypto&&typeof t.crypto.getRandomValues=="function")return t.crypto.getRandomValues(new Uint8Array(O));if(t.crypto&&typeof t.crypto.randomBytes=="function")return Uint8Array.from(t.crypto.randomBytes(O));throw new Error("crypto.getRandomValues must be defined")}})(ku);Object.defineProperty(Ot,"__esModule",{value:!0});Ot.SHA512_IV=Ot.SHA384_IV=Ot.SHA224_IV=Ot.SHA256_IV=Ot.HashMD=void 0;Ot.setBigUint64=eg;Ot.Chi=Lv;Ot.Maj=Dv;const Jr=ku;function eg(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const i=BigInt(32),s=BigInt(4294967295),a=Number(r>>i&s),o=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,a,n),e.setUint32(t+u,o,n)}function Lv(e,t,r){return e&t^~e&r}function Dv(e,t,r){return e&t^e&r^t&r}let zv=class extends Jr.Hash{constructor(t,r,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(t),this.view=(0,Jr.createView)(this.buffer)}update(t){(0,Jr.aexists)(this),t=(0,Jr.toBytes)(t),(0,Jr.abytes)(t);const{view:r,buffer:n,blockLen:i}=this,s=t.length;for(let a=0;a<s;){const o=Math.min(i-this.pos,s-a);if(o===i){const c=(0,Jr.createView)(t);for(;i<=s-a;a+=i)this.process(c,a);continue}n.set(t.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){(0,Jr.aexists)(this),(0,Jr.aoutput)(t,this),this.finished=!0;const{buffer:r,view:n,blockLen:i,isLE:s}=this;let{pos:a}=this;r[a++]=128,(0,Jr.clean)(this.buffer.subarray(a)),this.padOffset>i-a&&(this.process(n,0),a=0);for(let l=a;l<i;l++)r[l]=0;eg(n,i-8,BigInt(this.length*8),s),this.process(n,0);const o=(0,Jr.createView)(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)o.setUint32(4*l,f[l],s)}digest(){const{buffer:t,outputLen:r}=this;this.digestInto(t);const n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:r,buffer:n,length:i,finished:s,destroyed:a,pos:o}=this;return t.destroyed=a,t.finished=s,t.length=i,t.pos=o,i%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}};Ot.HashMD=zv;Ot.SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);Ot.SHA224_IV=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);Ot.SHA384_IV=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]);Ot.SHA512_IV=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);Object.defineProperty(Dt,"__esModule",{value:!0});Dt.ripemd160=Dt.RIPEMD160=Dt.md5=Dt.MD5=Dt.sha1=Dt.SHA1=void 0;const Qi=Ot,Et=ku,Ps=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Xn=new Uint32Array(80);class tg extends Qi.HashMD{constructor(){super(64,20,8,!1),this.A=Ps[0]|0,this.B=Ps[1]|0,this.C=Ps[2]|0,this.D=Ps[3]|0,this.E=Ps[4]|0}get(){const{A:t,B:r,C:n,D:i,E:s}=this;return[t,r,n,i,s]}set(t,r,n,i,s){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0}process(t,r){for(let c=0;c<16;c++,r+=4)Xn[c]=t.getUint32(r,!1);for(let c=16;c<80;c++)Xn[c]=(0,Et.rotl)(Xn[c-3]^Xn[c-8]^Xn[c-14]^Xn[c-16],1);let{A:n,B:i,C:s,D:a,E:o}=this;for(let c=0;c<80;c++){let u,f;c<20?(u=(0,Qi.Chi)(i,s,a),f=1518500249):c<40?(u=i^s^a,f=1859775393):c<60?(u=(0,Qi.Maj)(i,s,a),f=2400959708):(u=i^s^a,f=3395469782);const l=(0,Et.rotl)(n,5)+u+o+f+Xn[c]|0;o=a,a=s,s=(0,Et.rotl)(i,30),i=n,n=l}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,a=a+this.D|0,o=o+this.E|0,this.set(n,i,s,a,o)}roundClean(){(0,Et.clean)(Xn)}destroy(){this.set(0,0,0,0,0),(0,Et.clean)(this.buffer)}}Dt.SHA1=tg;Dt.sha1=(0,Et.createHasher)(()=>new tg);const Vv=Math.pow(2,32),Gv=Array.from({length:64},(e,t)=>Math.floor(Vv*Math.abs(Math.sin(t+1)))),gc=Ps.slice(0,4),Bf=new Uint32Array(16);class rg extends Qi.HashMD{constructor(){super(64,16,8,!0),this.A=gc[0]|0,this.B=gc[1]|0,this.C=gc[2]|0,this.D=gc[3]|0}get(){const{A:t,B:r,C:n,D:i}=this;return[t,r,n,i]}set(t,r,n,i){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0}process(t,r){for(let o=0;o<16;o++,r+=4)Bf[o]=t.getUint32(r,!0);let{A:n,B:i,C:s,D:a}=this;for(let o=0;o<64;o++){let c,u,f;o<16?(c=(0,Qi.Chi)(i,s,a),u=o,f=[7,12,17,22]):o<32?(c=(0,Qi.Chi)(a,i,s),u=(5*o+1)%16,f=[5,9,14,20]):o<48?(c=i^s^a,u=(3*o+5)%16,f=[4,11,16,23]):(c=s^(i|~a),u=7*o%16,f=[6,10,15,21]),c=c+n+Gv[o]+Bf[u],n=a,a=s,s=i,i=i+(0,Et.rotl)(c,f[o%4])}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,a=a+this.D|0,this.set(n,i,s,a)}roundClean(){(0,Et.clean)(Bf)}destroy(){this.set(0,0,0,0),(0,Et.clean)(this.buffer)}}Dt.MD5=rg;Dt.md5=(0,Et.createHasher)(()=>new rg);const qv=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),ng=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),Wv=ng.map(e=>(9*e+5)%16),ig=(()=>{const r=[[ng],[Wv]];for(let n=0;n<4;n++)for(let i of r)i.push(i[n].map(s=>qv[s]));return r})(),sg=ig[0],ag=ig[1],og=[[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(e=>Uint8Array.from(e)),Kv=sg.map((e,t)=>e.map(r=>og[t][r])),Xv=ag.map((e,t)=>e.map(r=>og[t][r])),Jv=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Yv=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function Gp(e,t,r,n){return e===0?t^r^n:e===1?t&r|~t&n:e===2?(t|~r)^n:e===3?t&n|r&~n:t^(r|~n)}const wc=new Uint32Array(16);class cg extends Qi.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:t,h1:r,h2:n,h3:i,h4:s}=this;return[t,r,n,i,s]}set(t,r,n,i,s){this.h0=t|0,this.h1=r|0,this.h2=n|0,this.h3=i|0,this.h4=s|0}process(t,r){for(let d=0;d<16;d++,r+=4)wc[d]=t.getUint32(r,!0);let n=this.h0|0,i=n,s=this.h1|0,a=s,o=this.h2|0,c=o,u=this.h3|0,f=u,l=this.h4|0,h=l;for(let d=0;d<5;d++){const b=4-d,g=Jv[d],x=Yv[d],A=sg[d],k=ag[d],w=Kv[d],v=Xv[d];for(let S=0;S<16;S++){const I=(0,Et.rotl)(n+Gp(d,s,o,u)+wc[A[S]]+g,w[S])+l|0;n=l,l=u,u=(0,Et.rotl)(o,10)|0,o=s,s=I}for(let S=0;S<16;S++){const I=(0,Et.rotl)(i+Gp(b,a,c,f)+wc[k[S]]+x,v[S])+h|0;i=h,h=f,f=(0,Et.rotl)(c,10)|0,c=a,a=I}}this.set(this.h1+o+f|0,this.h2+u+h|0,this.h3+l+i|0,this.h4+n+a|0,this.h0+s+c|0)}roundClean(){(0,Et.clean)(wc)}destroy(){this.destroyed=!0,(0,Et.clean)(this.buffer),this.set(0,0,0,0,0)}}Dt.RIPEMD160=cg;Dt.ripemd160=(0,Et.createHasher)(()=>new cg);Object.defineProperty(Zs,"__esModule",{value:!0});Zs.ripemd160=Zs.RIPEMD160=void 0;const ug=Dt;Zs.RIPEMD160=ug.RIPEMD160;Zs.ripemd160=ug.ripemd160;var Qs={};Object.defineProperty(Qs,"__esModule",{value:!0});Qs.sha1=Qs.SHA1=void 0;const fg=Dt;Qs.SHA1=fg.SHA1;Qs.sha1=fg.sha1;var Fr={},$e={},pe={};Object.defineProperty(pe,"__esModule",{value:!0});pe.toBig=pe.shrSL=pe.shrSH=pe.rotrSL=pe.rotrSH=pe.rotrBL=pe.rotrBH=pe.rotr32L=pe.rotr32H=pe.rotlSL=pe.rotlSH=pe.rotlBL=pe.rotlBH=pe.add5L=pe.add5H=pe.add4L=pe.add4H=pe.add3L=pe.add3H=void 0;pe.add=kg;pe.fromBig=Jh;pe.split=lg;const vc=BigInt(2**32-1),Nd=BigInt(32);function Jh(e,t=!1){return t?{h:Number(e&vc),l:Number(e>>Nd&vc)}:{h:Number(e>>Nd&vc)|0,l:Number(e&vc)|0}}function lg(e,t=!1){const r=e.length;let n=new Uint32Array(r),i=new Uint32Array(r);for(let s=0;s<r;s++){const{h:a,l:o}=Jh(e[s],t);[n[s],i[s]]=[a,o]}return[n,i]}const dg=(e,t)=>BigInt(e>>>0)<<Nd|BigInt(t>>>0);pe.toBig=dg;const hg=(e,t,r)=>e>>>r;pe.shrSH=hg;const pg=(e,t,r)=>e<<32-r|t>>>r;pe.shrSL=pg;const yg=(e,t,r)=>e>>>r|t<<32-r;pe.rotrSH=yg;const mg=(e,t,r)=>e<<32-r|t>>>r;pe.rotrSL=mg;const bg=(e,t,r)=>e<<64-r|t>>>r-32;pe.rotrBH=bg;const gg=(e,t,r)=>e>>>r-32|t<<64-r;pe.rotrBL=gg;const wg=(e,t)=>t;pe.rotr32H=wg;const vg=(e,t)=>e;pe.rotr32L=vg;const Eg=(e,t,r)=>e<<r|t>>>32-r;pe.rotlSH=Eg;const xg=(e,t,r)=>t<<r|e>>>32-r;pe.rotlSL=xg;const Ag=(e,t,r)=>t<<r-32|e>>>64-r;pe.rotlBH=Ag;const Sg=(e,t,r)=>e<<r-32|t>>>64-r;pe.rotlBL=Sg;function kg(e,t,r,n){const i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}const Tg=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0);pe.add3L=Tg;const Ig=(e,t,r,n)=>t+r+n+(e/2**32|0)|0;pe.add3H=Ig;const _g=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0);pe.add4L=_g;const Pg=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0;pe.add4H=Pg;const Og=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0);pe.add5L=Og;const Bg=(e,t,r,n,i,s)=>t+r+n+i+s+(e/2**32|0)|0;pe.add5H=Bg;const Zv={fromBig:Jh,split:lg,toBig:dg,shrSH:hg,shrSL:pg,rotrSH:yg,rotrSL:mg,rotrBH:bg,rotrBL:gg,rotr32H:wg,rotr32L:vg,rotlSH:Eg,rotlSL:xg,rotlBH:Ag,rotlBL:Sg,add:kg,add3L:Tg,add3H:Ig,add4L:_g,add4H:Pg,add5H:Bg,add5L:Og};pe.default=Zv;Object.defineProperty($e,"__esModule",{value:!0});$e.sha512_224=$e.sha512_256=$e.sha384=$e.sha512=$e.sha224=$e.sha256=$e.SHA512_256=$e.SHA512_224=$e.SHA384=$e.SHA512=$e.SHA224=$e.SHA256=void 0;const fe=Ot,me=pe,it=ku,Qv=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]),Jn=new Uint32Array(64);let Yh=class extends fe.HashMD{constructor(t=32){super(64,t,8,!1),this.A=fe.SHA256_IV[0]|0,this.B=fe.SHA256_IV[1]|0,this.C=fe.SHA256_IV[2]|0,this.D=fe.SHA256_IV[3]|0,this.E=fe.SHA256_IV[4]|0,this.F=fe.SHA256_IV[5]|0,this.G=fe.SHA256_IV[6]|0,this.H=fe.SHA256_IV[7]|0}get(){const{A:t,B:r,C:n,D:i,E:s,F:a,G:o,H:c}=this;return[t,r,n,i,s,a,o,c]}set(t,r,n,i,s,a,o,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=a|0,this.G=o|0,this.H=c|0}process(t,r){for(let l=0;l<16;l++,r+=4)Jn[l]=t.getUint32(r,!1);for(let l=16;l<64;l++){const h=Jn[l-15],d=Jn[l-2],b=(0,it.rotr)(h,7)^(0,it.rotr)(h,18)^h>>>3,g=(0,it.rotr)(d,17)^(0,it.rotr)(d,19)^d>>>10;Jn[l]=g+Jn[l-7]+b+Jn[l-16]|0}let{A:n,B:i,C:s,D:a,E:o,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){const h=(0,it.rotr)(o,6)^(0,it.rotr)(o,11)^(0,it.rotr)(o,25),d=f+h+(0,fe.Chi)(o,c,u)+Qv[l]+Jn[l]|0,g=((0,it.rotr)(n,2)^(0,it.rotr)(n,13)^(0,it.rotr)(n,22))+(0,fe.Maj)(n,i,s)|0;f=u,u=c,c=o,o=a+d|0,a=s,s=i,i=n,n=d+g|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,a=a+this.D|0,o=o+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(n,i,s,a,o,c,u,f)}roundClean(){(0,it.clean)(Jn)}destroy(){this.set(0,0,0,0,0,0,0,0),(0,it.clean)(this.buffer)}};$e.SHA256=Yh;class Cg extends Yh{constructor(){super(28),this.A=fe.SHA224_IV[0]|0,this.B=fe.SHA224_IV[1]|0,this.C=fe.SHA224_IV[2]|0,this.D=fe.SHA224_IV[3]|0,this.E=fe.SHA224_IV[4]|0,this.F=fe.SHA224_IV[5]|0,this.G=fe.SHA224_IV[6]|0,this.H=fe.SHA224_IV[7]|0}}$e.SHA224=Cg;const Rg=me.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(e=>BigInt(e))),eE=Rg[0],tE=Rg[1],Yn=new Uint32Array(80),Zn=new Uint32Array(80);let Vo=class extends fe.HashMD{constructor(t=64){super(128,t,16,!1),this.Ah=fe.SHA512_IV[0]|0,this.Al=fe.SHA512_IV[1]|0,this.Bh=fe.SHA512_IV[2]|0,this.Bl=fe.SHA512_IV[3]|0,this.Ch=fe.SHA512_IV[4]|0,this.Cl=fe.SHA512_IV[5]|0,this.Dh=fe.SHA512_IV[6]|0,this.Dl=fe.SHA512_IV[7]|0,this.Eh=fe.SHA512_IV[8]|0,this.El=fe.SHA512_IV[9]|0,this.Fh=fe.SHA512_IV[10]|0,this.Fl=fe.SHA512_IV[11]|0,this.Gh=fe.SHA512_IV[12]|0,this.Gl=fe.SHA512_IV[13]|0,this.Hh=fe.SHA512_IV[14]|0,this.Hl=fe.SHA512_IV[15]|0}get(){const{Ah:t,Al:r,Bh:n,Bl:i,Ch:s,Cl:a,Dh:o,Dl:c,Eh:u,El:f,Fh:l,Fl:h,Gh:d,Gl:b,Hh:g,Hl:x}=this;return[t,r,n,i,s,a,o,c,u,f,l,h,d,b,g,x]}set(t,r,n,i,s,a,o,c,u,f,l,h,d,b,g,x){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=i|0,this.Ch=s|0,this.Cl=a|0,this.Dh=o|0,this.Dl=c|0,this.Eh=u|0,this.El=f|0,this.Fh=l|0,this.Fl=h|0,this.Gh=d|0,this.Gl=b|0,this.Hh=g|0,this.Hl=x|0}process(t,r){for(let w=0;w<16;w++,r+=4)Yn[w]=t.getUint32(r),Zn[w]=t.getUint32(r+=4);for(let w=16;w<80;w++){const v=Yn[w-15]|0,S=Zn[w-15]|0,I=me.rotrSH(v,S,1)^me.rotrSH(v,S,8)^me.shrSH(v,S,7),_=me.rotrSL(v,S,1)^me.rotrSL(v,S,8)^me.shrSL(v,S,7),R=Yn[w-2]|0,B=Zn[w-2]|0,M=me.rotrSH(R,B,19)^me.rotrBH(R,B,61)^me.shrSH(R,B,6),F=me.rotrSL(R,B,19)^me.rotrBL(R,B,61)^me.shrSL(R,B,6),H=me.add4L(_,F,Zn[w-7],Zn[w-16]),z=me.add4H(H,I,M,Yn[w-7],Yn[w-16]);Yn[w]=z|0,Zn[w]=H|0}let{Ah:n,Al:i,Bh:s,Bl:a,Ch:o,Cl:c,Dh:u,Dl:f,Eh:l,El:h,Fh:d,Fl:b,Gh:g,Gl:x,Hh:A,Hl:k}=this;for(let w=0;w<80;w++){const v=me.rotrSH(l,h,14)^me.rotrSH(l,h,18)^me.rotrBH(l,h,41),S=me.rotrSL(l,h,14)^me.rotrSL(l,h,18)^me.rotrBL(l,h,41),I=l&d^~l&g,_=h&b^~h&x,R=me.add5L(k,S,_,tE[w],Zn[w]),B=me.add5H(R,A,v,I,eE[w],Yn[w]),M=R|0,F=me.rotrSH(n,i,28)^me.rotrBH(n,i,34)^me.rotrBH(n,i,39),H=me.rotrSL(n,i,28)^me.rotrBL(n,i,34)^me.rotrBL(n,i,39),z=n&s^n&o^s&o,Q=i&a^i&c^a&c;A=g|0,k=x|0,g=d|0,x=b|0,d=l|0,b=h|0,{h:l,l:h}=me.add(u|0,f|0,B|0,M|0),u=o|0,f=c|0,o=s|0,c=a|0,s=n|0,a=i|0;const U=me.add3L(M,H,Q);n=me.add3H(U,B,F,z),i=U|0}({h:n,l:i}=me.add(this.Ah|0,this.Al|0,n|0,i|0)),{h:s,l:a}=me.add(this.Bh|0,this.Bl|0,s|0,a|0),{h:o,l:c}=me.add(this.Ch|0,this.Cl|0,o|0,c|0),{h:u,l:f}=me.add(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:h}=me.add(this.Eh|0,this.El|0,l|0,h|0),{h:d,l:b}=me.add(this.Fh|0,this.Fl|0,d|0,b|0),{h:g,l:x}=me.add(this.Gh|0,this.Gl|0,g|0,x|0),{h:A,l:k}=me.add(this.Hh|0,this.Hl|0,A|0,k|0),this.set(n,i,s,a,o,c,u,f,l,h,d,b,g,x,A,k)}roundClean(){(0,it.clean)(Yn,Zn)}destroy(){(0,it.clean)(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};$e.SHA512=Vo;let Ng=class extends Vo{constructor(){super(48),this.Ah=fe.SHA384_IV[0]|0,this.Al=fe.SHA384_IV[1]|0,this.Bh=fe.SHA384_IV[2]|0,this.Bl=fe.SHA384_IV[3]|0,this.Ch=fe.SHA384_IV[4]|0,this.Cl=fe.SHA384_IV[5]|0,this.Dh=fe.SHA384_IV[6]|0,this.Dl=fe.SHA384_IV[7]|0,this.Eh=fe.SHA384_IV[8]|0,this.El=fe.SHA384_IV[9]|0,this.Fh=fe.SHA384_IV[10]|0,this.Fl=fe.SHA384_IV[11]|0,this.Gh=fe.SHA384_IV[12]|0,this.Gl=fe.SHA384_IV[13]|0,this.Hh=fe.SHA384_IV[14]|0,this.Hl=fe.SHA384_IV[15]|0}};$e.SHA384=Ng;const St=Uint32Array.from([2352822216,424955298,1944164710,2312950998,502970286,855612546,1738396948,1479516111,258812777,2077511080,2011393907,79989058,1067287976,1780299464,286451373,2446758561]),kt=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class Ug extends Vo{constructor(){super(28),this.Ah=St[0]|0,this.Al=St[1]|0,this.Bh=St[2]|0,this.Bl=St[3]|0,this.Ch=St[4]|0,this.Cl=St[5]|0,this.Dh=St[6]|0,this.Dl=St[7]|0,this.Eh=St[8]|0,this.El=St[9]|0,this.Fh=St[10]|0,this.Fl=St[11]|0,this.Gh=St[12]|0,this.Gl=St[13]|0,this.Hh=St[14]|0,this.Hl=St[15]|0}}$e.SHA512_224=Ug;class Fg extends Vo{constructor(){super(32),this.Ah=kt[0]|0,this.Al=kt[1]|0,this.Bh=kt[2]|0,this.Bl=kt[3]|0,this.Ch=kt[4]|0,this.Cl=kt[5]|0,this.Dh=kt[6]|0,this.Dl=kt[7]|0,this.Eh=kt[8]|0,this.El=kt[9]|0,this.Fh=kt[10]|0,this.Fl=kt[11]|0,this.Gh=kt[12]|0,this.Gl=kt[13]|0,this.Hh=kt[14]|0,this.Hl=kt[15]|0}}$e.SHA512_256=Fg;$e.sha256=(0,it.createHasher)(()=>new Yh);$e.sha224=(0,it.createHasher)(()=>new Cg);$e.sha512=(0,it.createHasher)(()=>new Vo);$e.sha384=(0,it.createHasher)(()=>new Ng);$e.sha512_256=(0,it.createHasher)(()=>new Fg);$e.sha512_224=(0,it.createHasher)(()=>new Ug);Object.defineProperty(Fr,"__esModule",{value:!0});Fr.sha224=Fr.SHA224=Fr.sha256=Fr.SHA256=void 0;const Iu=$e;Fr.SHA256=Iu.SHA256;Fr.sha256=Iu.sha256;Fr.SHA224=Iu.SHA224;Fr.sha224=Iu.sha224;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.taggedHash=e.TAGGED_HASH_PREFIXES=e.TAGS=e.hash256=e.hash160=e.sha256=e.sha1=e.ripemd160=void 0;const t=Zs,r=Qs,n=Fr;function i(f){return Buffer.from((0,t.ripemd160)(Uint8Array.from(f)))}e.ripemd160=i;function s(f){return Buffer.from((0,r.sha1)(Uint8Array.from(f)))}e.sha1=s;function a(f){return Buffer.from((0,n.sha256)(Uint8Array.from(f)))}e.sha256=a;function o(f){return Buffer.from((0,t.ripemd160)((0,n.sha256)(Uint8Array.from(f))))}e.hash160=o;function c(f){return Buffer.from((0,n.sha256)((0,n.sha256)(Uint8Array.from(f))))}e.hash256=c,e.TAGS=["BIP0340/challenge","BIP0340/aux","BIP0340/nonce","TapLeaf","TapBranch","TapSighash","TapTweak","KeyAgg list","KeyAgg coefficient"],e.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(f,l){return a(Buffer.concat([e.TAGGED_HASH_PREFIXES[f],l]))}e.taggedHash=u})(Bi);var Cf={},Fn={};Object.defineProperty(Fn,"__esModule",{value:!0});Fn.encode=Fn.decode=Fn.check=void 0;function rE(e){if(e.length<8||e.length>72||e[0]!==48||e[1]!==e.length-2||e[2]!==2)return!1;const t=e[3];if(t===0||5+t>=e.length||e[4+t]!==2)return!1;const r=e[5+t];return!(r===0||6+t+r!==e.length||e[4]&128||t>1&&e[4]===0&&!(e[5]&128)||e[t+6]&128||r>1&&e[t+6]===0&&!(e[t+7]&128))}Fn.check=rE;function nE(e){if(e.length<8)throw new Error("DER sequence length is too short");if(e.length>72)throw new Error("DER sequence length is too long");if(e[0]!==48)throw new Error("Expected DER sequence");if(e[1]!==e.length-2)throw new Error("DER sequence length is invalid");if(e[2]!==2)throw new Error("Expected DER integer");const t=e[3];if(t===0)throw new Error("R length is zero");if(5+t>=e.length)throw new Error("R length is too long");if(e[4+t]!==2)throw new Error("Expected DER integer (2)");const r=e[5+t];if(r===0)throw new Error("S length is zero");if(6+t+r!==e.length)throw new Error("S length is invalid");if(e[4]&128)throw new Error("R value is negative");if(t>1&&e[4]===0&&!(e[5]&128))throw new Error("R value excessively padded");if(e[t+6]&128)throw new Error("S value is negative");if(r>1&&e[t+6]===0&&!(e[t+7]&128))throw new Error("S value excessively padded");return{r:e.slice(4,4+t),s:e.slice(6+t)}}Fn.decode=nE;function iE(e,t){const r=e.length,n=t.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(e[0]&128)throw new Error("R value is negative");if(t[0]&128)throw new Error("S value is negative");if(r>1&&e[0]===0&&!(e[1]&128))throw new Error("R value excessively padded");if(n>1&&t[0]===0&&!(t[1]&128))throw new Error("S value excessively padded");const i=Buffer.allocUnsafe(6+r+n);return i[0]=48,i[1]=i.length-2,i[2]=2,i[3]=e.length,e.copy(i,4),i[4+r]=2,i[5+r]=t.length,t.copy(i,6+r),i}Fn.encode=iE;var ss={};Object.defineProperty(ss,"__esModule",{value:!0});ss.REVERSE_OPS=ss.OPS=void 0;const Ud={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};ss.OPS=Ud;const $g={};ss.REVERSE_OPS=$g;for(const e of Object.keys(Ud)){const t=Ud[e];$g[t]=e}var xi={};Object.defineProperty(xi,"__esModule",{value:!0});xi.decode=xi.encode=xi.encodingLength=void 0;const gi=ss;function Mg(e){return e<gi.OPS.OP_PUSHDATA1?1:e<=255?2:e<=65535?3:5}xi.encodingLength=Mg;function sE(e,t,r){const n=Mg(t);return n===1?e.writeUInt8(t,r):n===2?(e.writeUInt8(gi.OPS.OP_PUSHDATA1,r),e.writeUInt8(t,r+1)):n===3?(e.writeUInt8(gi.OPS.OP_PUSHDATA2,r),e.writeUInt16LE(t,r+1)):(e.writeUInt8(gi.OPS.OP_PUSHDATA4,r),e.writeUInt32LE(t,r+1)),n}xi.encode=sE;function aE(e,t){const r=e.readUInt8(t);let n,i;if(r<gi.OPS.OP_PUSHDATA1)n=r,i=1;else if(r===gi.OPS.OP_PUSHDATA1){if(t+2>e.length)return null;n=e.readUInt8(t+1),i=2}else if(r===gi.OPS.OP_PUSHDATA2){if(t+3>e.length)return null;n=e.readUInt16LE(t+1),i=3}else{if(t+5>e.length)return null;if(r!==gi.OPS.OP_PUSHDATA4)throw new Error("Unexpected opcode");n=e.readUInt32LE(t+1),i=5}return{opcode:r,number:n,size:i}}xi.decode=aE;var ea={};Object.defineProperty(ea,"__esModule",{value:!0});ea.encode=ea.decode=void 0;function oE(e,t,r){t=t||4,r=r===void 0?!0:r;const n=e.length;if(n===0)return 0;if(n>t)throw new TypeError("Script number overflow");if(r&&!(e[n-1]&127)&&(n<=1||!(e[n-2]&128)))throw new Error("Non-minimally encoded script number");if(n===5){const s=e.readUInt32LE(0),a=e.readUInt8(4);return a&128?-((a&-129)*4294967296+s):a*4294967296+s}let i=0;for(let s=0;s<n;++s)i|=e[s]<<8*s;return e[n-1]&128?-(i&~(128<<8*(n-1))):i}ea.decode=oE;function cE(e){return e>2147483647?5:e>8388607?4:e>32767?3:e>127?2:e>0?1:0}function uE(e){let t=Math.abs(e);const r=cE(t),n=Buffer.allocUnsafe(r),i=e<0;for(let s=0;s<r;++s)n.writeUInt8(t&255,s),t>>=8;return n[r-1]&128?n.writeUInt8(i?128:0,r-1):i&&(n[r-1]|=128),n}ea.encode=uE;var ji={},qp;function fE(){if(qp)return ji;qp=1,Object.defineProperty(ji,"__esModule",{value:!0}),ji.encode=ji.decode=void 0;const e=Fn,t=dr(),r=Rt,{typeforce:n}=r,i=Buffer.alloc(1,0);function s(u){let f=0;for(;u[f]===0;)++f;return f===u.length?i:(u=u.slice(f),u[0]&128?Buffer.concat([i,u],1+u.length):u)}function a(u){u[0]===0&&(u=u.slice(1));const f=Buffer.alloc(32,0),l=Math.max(0,32-u.length);return u.copy(f,l),f}function o(u){const f=u.readUInt8(u.length-1);if(!(0,t.isDefinedHashType)(f))throw new Error("Invalid hashType "+f);const l=e.decode(u.slice(0,-1)),h=a(l.r),d=a(l.s);return{signature:Buffer.concat([h,d],64),hashType:f}}ji.decode=o;function c(u,f){if(n({signature:r.BufferN(64),hashType:r.UInt8},{signature:u,hashType:f}),!(0,t.isDefinedHashType)(f))throw new Error("Invalid hashType "+f);const l=Buffer.allocUnsafe(1);l.writeUInt8(f,0);const h=s(u.slice(0,32)),d=s(u.slice(32,64));return Buffer.concat([e.encode(h,d),l])}return ji.encode=c,ji}var Wp;function dr(){return Wp||(Wp=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.signature=e.number=e.isCanonicalScriptSignature=e.isDefinedHashType=e.isCanonicalPubKey=e.toStack=e.fromASM=e.toASM=e.decompile=e.compile=e.countNonPushOnlyOPs=e.isPushOnly=e.OPS=void 0;const t=Fn,r=ss;Object.defineProperty(e,"OPS",{enumerable:!0,get:function(){return r.OPS}});const n=xi,i=ea,s=fE(),a=Rt,{typeforce:o}=a,c=r.OPS.OP_RESERVED;function u(B){return a.Number(B)&&(B===r.OPS.OP_0||B>=r.OPS.OP_1&&B<=r.OPS.OP_16||B===r.OPS.OP_1NEGATE)}function f(B){return a.Buffer(B)||u(B)}function l(B){return a.Array(B)&&B.every(f)}e.isPushOnly=l;function h(B){return B.length-B.filter(f).length}e.countNonPushOnlyOPs=h;function d(B){if(B.length===0)return r.OPS.OP_0;if(B.length===1){if(B[0]>=1&&B[0]<=16)return c+B[0];if(B[0]===129)return r.OPS.OP_1NEGATE}}function b(B){return Buffer.isBuffer(B)}function g(B){return a.Array(B)}function x(B){return Buffer.isBuffer(B)}function A(B){if(b(B))return B;o(a.Array,B);const M=B.reduce((z,Q)=>x(Q)?Q.length===1&&d(Q)!==void 0?z+1:z+n.encodingLength(Q.length)+Q.length:z+1,0),F=Buffer.allocUnsafe(M);let H=0;if(B.forEach(z=>{if(x(z)){const Q=d(z);if(Q!==void 0){F.writeUInt8(Q,H),H+=1;return}H+=n.encode(F,z.length,H),z.copy(F,H),H+=z.length}else F.writeUInt8(z,H),H+=1}),H!==F.length)throw new Error("Could not decode chunks");return F}e.compile=A;function k(B){if(g(B))return B;o(a.Buffer,B);const M=[];let F=0;for(;F<B.length;){const H=B[F];if(H>r.OPS.OP_0&&H<=r.OPS.OP_PUSHDATA4){const z=n.decode(B,F);if(z===null||(F+=z.size,F+z.number>B.length))return null;const Q=B.slice(F,F+z.number);F+=z.number;const U=d(Q);U!==void 0?M.push(U):M.push(Q)}else M.push(H),F+=1}return M}e.decompile=k;function w(B){if(b(B)&&(B=k(B)),!B)throw new Error("Could not convert invalid chunks to ASM");return B.map(M=>{if(x(M)){const F=d(M);if(F===void 0)return M.toString("hex");M=F}return r.REVERSE_OPS[M]}).join(" ")}e.toASM=w;function v(B){return o(a.String,B),A(B.split(" ").map(M=>r.OPS[M]!==void 0?r.OPS[M]:(o(a.Hex,M),Buffer.from(M,"hex"))))}e.fromASM=v;function S(B){return B=k(B),o(l,B),B.map(M=>x(M)?M:M===r.OPS.OP_0?Buffer.allocUnsafe(0):i.encode(M-c))}e.toStack=S;function I(B){return a.isPoint(B)}e.isCanonicalPubKey=I;function _(B){const M=B&-129;return M>0&&M<4}e.isDefinedHashType=_;function R(B){return!Buffer.isBuffer(B)||!_(B[B.length-1])?!1:t.check(B.slice(0,-1))}e.isCanonicalScriptSignature=R,e.number=i,e.signature=s}(Cf)),Cf}Object.defineProperty(zo,"__esModule",{value:!0});zo.Transaction=void 0;const nt=vt,$t=Bi,Kp=dr(),lE=dr(),Se=Rt,{typeforce:Yr}=Se;function nn(e){const t=e.length;return nt.varuint.encodingLength(t)+t}function dE(e){const t=e.length;return nt.varuint.encodingLength(t)+e.reduce((r,n)=>r+nn(n),0)}const ci=Buffer.allocUnsafe(0),Rf=[],Nf=Buffer.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),Xp=Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),hE=Buffer.from("ffffffffffffffff","hex"),pE={script:ci,valueBuffer:hE};function yE(e){return e.value!==void 0}let Gr=class Be{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(t,r){const n=new nt.BufferReader(t),i=new Be;i.version=n.readInt32();const s=n.readUInt8(),a=n.readUInt8();let o=!1;s===Be.ADVANCED_TRANSACTION_MARKER&&a===Be.ADVANCED_TRANSACTION_FLAG?o=!0:n.offset-=2;const c=n.readVarInt();for(let f=0;f<c;++f)i.ins.push({hash:n.readSlice(32),index:n.readUInt32(),script:n.readVarSlice(),sequence:n.readUInt32(),witness:Rf});const u=n.readVarInt();for(let f=0;f<u;++f)i.outs.push({value:n.readUInt64(),script:n.readVarSlice()});if(o){for(let f=0;f<c;++f)i.ins[f].witness=n.readVector();if(!i.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(i.locktime=n.readUInt32(),r)return i;if(n.offset!==t.length)throw new Error("Transaction has unexpected data");return i}static fromHex(t){return Be.fromBuffer(Buffer.from(t,"hex"),!1)}static isCoinbaseHash(t){Yr(Se.Hash256bit,t);for(let r=0;r<32;++r)if(t[r]!==0)return!1;return!0}isCoinbase(){return this.ins.length===1&&Be.isCoinbaseHash(this.ins[0].hash)}addInput(t,r,n,i){return Yr(Se.tuple(Se.Hash256bit,Se.UInt32,Se.maybe(Se.UInt32),Se.maybe(Se.Buffer)),arguments),Se.Null(n)&&(n=Be.DEFAULT_SEQUENCE),this.ins.push({hash:t,index:r,script:i||ci,sequence:n,witness:Rf})-1}addOutput(t,r){return Yr(Se.tuple(Se.Buffer,Se.Satoshi),arguments),this.outs.push({script:t,value:r})-1}hasWitnesses(){return this.ins.some(t=>t.witness.length!==0)}stripWitnesses(){this.ins.forEach(t=>{t.witness=Rf})}weight(){const t=this.byteLength(!1),r=this.byteLength(!0);return t*3+r}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(t=!0){const r=t&&this.hasWitnesses();return(r?10:8)+nt.varuint.encodingLength(this.ins.length)+nt.varuint.encodingLength(this.outs.length)+this.ins.reduce((n,i)=>n+40+nn(i.script),0)+this.outs.reduce((n,i)=>n+8+nn(i.script),0)+(r?this.ins.reduce((n,i)=>n+dE(i.witness),0):0)}clone(){const t=new Be;return t.version=this.version,t.locktime=this.locktime,t.ins=this.ins.map(r=>({hash:r.hash,index:r.index,script:r.script,sequence:r.sequence,witness:r.witness})),t.outs=this.outs.map(r=>({script:r.script,value:r.value})),t}hashForSignature(t,r,n){if(Yr(Se.tuple(Se.UInt32,Se.Buffer,Se.Number),arguments),t>=this.ins.length)return Xp;const i=Kp.compile(Kp.decompile(r).filter(o=>o!==lE.OPS.OP_CODESEPARATOR)),s=this.clone();if((n&31)===Be.SIGHASH_NONE)s.outs=[],s.ins.forEach((o,c)=>{c!==t&&(o.sequence=0)});else if((n&31)===Be.SIGHASH_SINGLE){if(t>=this.outs.length)return Xp;s.outs.length=t+1;for(let o=0;o<t;o++)s.outs[o]=pE;s.ins.forEach((o,c)=>{c!==t&&(o.sequence=0)})}n&Be.SIGHASH_ANYONECANPAY?(s.ins=[s.ins[t]],s.ins[0].script=i):(s.ins.forEach(o=>{o.script=ci}),s.ins[t].script=i);const a=Buffer.allocUnsafe(s.byteLength(!1)+4);return a.writeInt32LE(n,a.length-4),s.__toBuffer(a,0,!1),$t.hash256(a)}hashForWitnessV1(t,r,n,i,s,a){if(Yr(Se.tuple(Se.UInt32,Yr.arrayOf(Se.Buffer),Yr.arrayOf(Se.Satoshi),Se.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=i===Be.SIGHASH_DEFAULT?Be.SIGHASH_ALL:i&Be.SIGHASH_OUTPUT_MASK,u=(i&Be.SIGHASH_INPUT_MASK)===Be.SIGHASH_ANYONECANPAY,f=o===Be.SIGHASH_NONE,l=o===Be.SIGHASH_SINGLE;let h=ci,d=ci,b=ci,g=ci,x=ci;if(!u){let v=nt.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(S=>{v.writeSlice(S.hash),v.writeUInt32(S.index)}),h=$t.sha256(v.end()),v=nt.BufferWriter.withCapacity(8*this.ins.length),n.forEach(S=>v.writeUInt64(S)),d=$t.sha256(v.end()),v=nt.BufferWriter.withCapacity(r.map(nn).reduce((S,I)=>S+I)),r.forEach(S=>v.writeVarSlice(S)),b=$t.sha256(v.end()),v=nt.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(S=>v.writeUInt32(S.sequence)),g=$t.sha256(v.end())}if(f||l){if(l&&t<this.outs.length){const v=this.outs[t],S=nt.BufferWriter.withCapacity(8+nn(v.script));S.writeUInt64(v.value),S.writeVarSlice(v.script),x=$t.sha256(S.end())}}else{const v=this.outs.map(I=>8+nn(I.script)).reduce((I,_)=>I+_),S=nt.BufferWriter.withCapacity(v);this.outs.forEach(I=>{S.writeUInt64(I.value),S.writeVarSlice(I.script)}),x=$t.sha256(S.end())}const A=(s?2:0)+(a?1:0),k=174-(u?49:0)-(f?32:0)+(a?32:0)+(s?37:0),w=nt.BufferWriter.withCapacity(k);if(w.writeUInt8(i),w.writeInt32(this.version),w.writeUInt32(this.locktime),w.writeSlice(h),w.writeSlice(d),w.writeSlice(b),w.writeSlice(g),f||l||w.writeSlice(x),w.writeUInt8(A),u){const v=this.ins[t];w.writeSlice(v.hash),w.writeUInt32(v.index),w.writeUInt64(n[t]),w.writeVarSlice(r[t]),w.writeUInt32(v.sequence)}else w.writeUInt32(t);if(a){const v=nt.BufferWriter.withCapacity(nn(a));v.writeVarSlice(a),w.writeSlice($t.sha256(v.end()))}return l&&w.writeSlice(x),s&&(w.writeSlice(s),w.writeUInt8(0),w.writeUInt32(4294967295)),$t.taggedHash("TapSighash",Buffer.concat([Buffer.from([0]),w.end()]))}hashForWitnessV0(t,r,n,i){Yr(Se.tuple(Se.UInt32,Se.Buffer,Se.Satoshi,Se.UInt32),arguments);let s=Buffer.from([]),a,o=Nf,c=Nf,u=Nf;if(i&Be.SIGHASH_ANYONECANPAY||(s=Buffer.allocUnsafe(36*this.ins.length),a=new nt.BufferWriter(s,0),this.ins.forEach(l=>{a.writeSlice(l.hash),a.writeUInt32(l.index)}),c=$t.hash256(s)),!(i&Be.SIGHASH_ANYONECANPAY)&&(i&31)!==Be.SIGHASH_SINGLE&&(i&31)!==Be.SIGHASH_NONE&&(s=Buffer.allocUnsafe(4*this.ins.length),a=new nt.BufferWriter(s,0),this.ins.forEach(l=>{a.writeUInt32(l.sequence)}),u=$t.hash256(s)),(i&31)!==Be.SIGHASH_SINGLE&&(i&31)!==Be.SIGHASH_NONE){const l=this.outs.reduce((h,d)=>h+8+nn(d.script),0);s=Buffer.allocUnsafe(l),a=new nt.BufferWriter(s,0),this.outs.forEach(h=>{a.writeUInt64(h.value),a.writeVarSlice(h.script)}),o=$t.hash256(s)}else if((i&31)===Be.SIGHASH_SINGLE&&t<this.outs.length){const l=this.outs[t];s=Buffer.allocUnsafe(8+nn(l.script)),a=new nt.BufferWriter(s,0),a.writeUInt64(l.value),a.writeVarSlice(l.script),o=$t.hash256(s)}s=Buffer.allocUnsafe(156+nn(r)),a=new nt.BufferWriter(s,0);const f=this.ins[t];return a.writeInt32(this.version),a.writeSlice(c),a.writeSlice(u),a.writeSlice(f.hash),a.writeUInt32(f.index),a.writeVarSlice(r),a.writeUInt64(n),a.writeUInt32(f.sequence),a.writeSlice(o),a.writeUInt32(this.locktime),a.writeUInt32(i),$t.hash256(s)}getHash(t){return t&&this.isCoinbase()?Buffer.alloc(32,0):$t.hash256(this.__toBuffer(void 0,void 0,t))}getId(){return(0,nt.reverseBuffer)(this.getHash(!1)).toString("hex")}toBuffer(t,r){return this.__toBuffer(t,r,!0)}toHex(){return this.toBuffer(void 0,void 0).toString("hex")}setInputScript(t,r){Yr(Se.tuple(Se.Number,Se.Buffer),arguments),this.ins[t].script=r}setWitness(t,r){Yr(Se.tuple(Se.Number,[Se.Buffer]),arguments),this.ins[t].witness=r}__toBuffer(t,r,n=!1){t||(t=Buffer.allocUnsafe(this.byteLength(n)));const i=new nt.BufferWriter(t,r||0);i.writeInt32(this.version);const s=n&&this.hasWitnesses();return s&&(i.writeUInt8(Be.ADVANCED_TRANSACTION_MARKER),i.writeUInt8(Be.ADVANCED_TRANSACTION_FLAG)),i.writeVarInt(this.ins.length),this.ins.forEach(a=>{i.writeSlice(a.hash),i.writeUInt32(a.index),i.writeVarSlice(a.script),i.writeUInt32(a.sequence)}),i.writeVarInt(this.outs.length),this.outs.forEach(a=>{yE(a)?i.writeUInt64(a.value):i.writeSlice(a.valueBuffer),i.writeVarSlice(a.script)}),s&&this.ins.forEach(a=>{i.writeVector(a.witness)}),i.writeUInt32(this.locktime),r!==void 0?t.slice(r,i.offset):t}};zo.Transaction=Gr;Gr.DEFAULT_SEQUENCE=4294967295;Gr.SIGHASH_DEFAULT=0;Gr.SIGHASH_ALL=1;Gr.SIGHASH_NONE=2;Gr.SIGHASH_SINGLE=3;Gr.SIGHASH_ANYONECANPAY=128;Gr.SIGHASH_OUTPUT_MASK=3;Gr.SIGHASH_INPUT_MASK=128;Gr.ADVANCED_TRANSACTION_MARKER=0;Gr.ADVANCED_TRANSACTION_FLAG=1;var Re={},Go={};Object.defineProperty(Go,"__esModule",{value:!0});const mE=9007199254740991;function Zh(e){if(e<0||e>mE||e%1!==0)throw new RangeError("value out of range")}function Ua(e,t,r){if(Zh(e),t||(t=Buffer.allocUnsafe(jg(e))),!Buffer.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");return r||(r=0),e<253?(t.writeUInt8(e,r),Object.assign(Ua,{bytes:1})):e<=65535?(t.writeUInt8(253,r),t.writeUInt16LE(e,r+1),Object.assign(Ua,{bytes:3})):e<=4294967295?(t.writeUInt8(254,r),t.writeUInt32LE(e,r+1),Object.assign(Ua,{bytes:5})):(t.writeUInt8(255,r),t.writeUInt32LE(e>>>0,r+1),t.writeUInt32LE(e/4294967296|0,r+5),Object.assign(Ua,{bytes:9})),t}Go.encode=Ua;function Fa(e,t){if(!Buffer.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");t||(t=0);const r=e.readUInt8(t);if(r<253)return Object.assign(Fa,{bytes:1}),r;if(r===253)return Object.assign(Fa,{bytes:3}),e.readUInt16LE(t+1);if(r===254)return Object.assign(Fa,{bytes:5}),e.readUInt32LE(t+1);{Object.assign(Fa,{bytes:9});const n=e.readUInt32LE(t+1),s=e.readUInt32LE(t+5)*4294967296+n;return Zh(s),s}}Go.decode=Fa;function jg(e){return Zh(e),e<253?1:e<=65535?3:e<=4294967295?5:9}Go.encodingLength=jg;var Uf={},_u={},Ct={};Object.defineProperty(Ct,"__esModule",{value:!0});Ct.testnet=Ct.regtest=Ct.bitcoin=void 0;Ct.bitcoin={messagePrefix:`Bitcoin Signed Message:
|
|
7
|
+
`,bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128};Ct.regtest={messagePrefix:`Bitcoin Signed Message:
|
|
8
|
+
`,bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};Ct.testnet={messagePrefix:`Bitcoin Signed Message:
|
|
9
|
+
`,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var fr={};Object.defineProperty(fr,"__esModule",{value:!0});fr.value=fr.prop=void 0;function bE(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){const n=r.call(this);return this[t]=n,n},set(n){Object.defineProperty(this,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}})}fr.prop=bE;function gE(e){let t;return()=>(t!==void 0||(t=e()),t)}fr.value=gE;Object.defineProperty(_u,"__esModule",{value:!0});_u.p2data=void 0;const wE=Ct,qc=dr(),Zr=Rt,Jp=fr,Yp=qc.OPS;function vE(e,t){if(!e.data&&!e.output)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Zr.typeforce)({network:Zr.typeforce.maybe(Zr.typeforce.Object),output:Zr.typeforce.maybe(Zr.typeforce.Buffer),data:Zr.typeforce.maybe(Zr.typeforce.arrayOf(Zr.typeforce.Buffer))},e);const n={name:"embed",network:e.network||wE.bitcoin};if(Jp.prop(n,"output",()=>{if(e.data)return qc.compile([Yp.OP_RETURN].concat(e.data))}),Jp.prop(n,"data",()=>{if(e.output)return qc.decompile(e.output).slice(1)}),t.validate&&e.output){const i=qc.decompile(e.output);if(i[0]!==Yp.OP_RETURN)throw new TypeError("Output is invalid");if(!i.slice(1).every(Zr.typeforce.Buffer))throw new TypeError("Output is invalid");if(e.data&&!(0,Zr.stacksEqual)(e.data,n.data))throw new TypeError("Data mismatch")}return Object.assign(n,e)}_u.p2data=vE;var Pu={};Object.defineProperty(Pu,"__esModule",{value:!0});Pu.p2ms=void 0;const EE=Ct,Os=dr(),Qe=Rt,Qn=fr,Bs=Os.OPS,Ec=Bs.OP_RESERVED;function xE(e,t){if(!e.input&&!e.output&&!(e.pubkeys&&e.m!==void 0)&&!e.signatures)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{});function r(c){return Os.isCanonicalScriptSignature(c)||(t.allowIncomplete&&c===Bs.OP_0)!==void 0}(0,Qe.typeforce)({network:Qe.typeforce.maybe(Qe.typeforce.Object),m:Qe.typeforce.maybe(Qe.typeforce.Number),n:Qe.typeforce.maybe(Qe.typeforce.Number),output:Qe.typeforce.maybe(Qe.typeforce.Buffer),pubkeys:Qe.typeforce.maybe(Qe.typeforce.arrayOf(Qe.isPoint)),signatures:Qe.typeforce.maybe(Qe.typeforce.arrayOf(r)),input:Qe.typeforce.maybe(Qe.typeforce.Buffer)},e);const i={network:e.network||EE.bitcoin};let s=[],a=!1;function o(c){a||(a=!0,s=Os.decompile(c),i.m=s[0]-Ec,i.n=s[s.length-2]-Ec,i.pubkeys=s.slice(1,-2))}if(Qn.prop(i,"output",()=>{if(e.m&&i.n&&e.pubkeys)return Os.compile([].concat(Ec+e.m,e.pubkeys,Ec+i.n,Bs.OP_CHECKMULTISIG))}),Qn.prop(i,"m",()=>{if(i.output)return o(i.output),i.m}),Qn.prop(i,"n",()=>{if(i.pubkeys)return i.pubkeys.length}),Qn.prop(i,"pubkeys",()=>{if(e.output)return o(e.output),i.pubkeys}),Qn.prop(i,"signatures",()=>{if(e.input)return Os.decompile(e.input).slice(1)}),Qn.prop(i,"input",()=>{if(e.signatures)return Os.compile([Bs.OP_0].concat(e.signatures))}),Qn.prop(i,"witness",()=>{if(i.input)return[]}),Qn.prop(i,"name",()=>{if(!(!i.m||!i.n))return`p2ms(${i.m} of ${i.n})`}),t.validate){if(e.output){if(o(e.output),!Qe.typeforce.Number(s[0]))throw new TypeError("Output is invalid");if(!Qe.typeforce.Number(s[s.length-2]))throw new TypeError("Output is invalid");if(s[s.length-1]!==Bs.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(i.m<=0||i.n>16||i.m>i.n||i.n!==s.length-3)throw new TypeError("Output is invalid");if(!i.pubkeys.every(c=>(0,Qe.isPoint)(c)))throw new TypeError("Output is invalid");if(e.m!==void 0&&e.m!==i.m)throw new TypeError("m mismatch");if(e.n!==void 0&&e.n!==i.n)throw new TypeError("n mismatch");if(e.pubkeys&&!(0,Qe.stacksEqual)(e.pubkeys,i.pubkeys))throw new TypeError("Pubkeys mismatch")}if(e.pubkeys){if(e.n!==void 0&&e.n!==e.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(i.n=e.pubkeys.length,i.n<i.m)throw new TypeError("Pubkey count cannot be less than m")}if(e.signatures){if(e.signatures.length<i.m)throw new TypeError("Not enough signatures provided");if(e.signatures.length>i.m)throw new TypeError("Too many signatures provided")}if(e.input){if(e.input[0]!==Bs.OP_0)throw new TypeError("Input is invalid");if(i.signatures.length===0||!i.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(e.signatures&&!(0,Qe.stacksEqual)(e.signatures,i.signatures))throw new TypeError("Signature mismatch");if(e.m!==void 0&&e.m!==e.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(i,e)}Pu.p2ms=xE;var Ou={};Object.defineProperty(Ou,"__esModule",{value:!0});Ou.p2pk=void 0;const AE=Ct,Cs=dr(),Tr=Rt,Ts=fr,Zp=Cs.OPS;function SE(e,t){if(!e.input&&!e.output&&!e.pubkey&&!e.input&&!e.signature)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Tr.typeforce)({network:Tr.typeforce.maybe(Tr.typeforce.Object),output:Tr.typeforce.maybe(Tr.typeforce.Buffer),pubkey:Tr.typeforce.maybe(Tr.isPoint),signature:Tr.typeforce.maybe(Cs.isCanonicalScriptSignature),input:Tr.typeforce.maybe(Tr.typeforce.Buffer)},e);const r=Ts.value(()=>Cs.decompile(e.input)),i={name:"p2pk",network:e.network||AE.bitcoin};if(Ts.prop(i,"output",()=>{if(e.pubkey)return Cs.compile([e.pubkey,Zp.OP_CHECKSIG])}),Ts.prop(i,"pubkey",()=>{if(e.output)return e.output.slice(1,-1)}),Ts.prop(i,"signature",()=>{if(e.input)return r()[0]}),Ts.prop(i,"input",()=>{if(e.signature)return Cs.compile([e.signature])}),Ts.prop(i,"witness",()=>{if(i.input)return[]}),t.validate){if(e.output){if(e.output[e.output.length-1]!==Zp.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!(0,Tr.isPoint)(i.pubkey))throw new TypeError("Output pubkey is invalid");if(e.pubkey&&!e.pubkey.equals(i.pubkey))throw new TypeError("Pubkey mismatch")}if(e.signature&&e.input&&!e.input.equals(i.input))throw new TypeError("Signature mismatch");if(e.input){if(r().length!==1)throw new TypeError("Input is invalid");if(!Cs.isCanonicalScriptSignature(i.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(i,e)}Ou.p2pk=SE;var Bu={};function kE(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var n=0;n<e.length;n++){var i=e.charAt(n),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=n}var a=e.length,o=e.charAt(0),c=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(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,x=0,A=d.length;x!==A&&d[x]===0;)x++,b++;for(var k=(A-x)*u+1>>>0,w=new Uint8Array(k);x!==A;){for(var v=d[x],S=0,I=k-1;(v!==0||S<g)&&I!==-1;I--,S++)v+=256*w[I]>>>0,w[I]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,x++}for(var _=k-g;_!==k&&w[_]===0;)_++;for(var R=o.repeat(b);_<k;++_)R+=e.charAt(w[_]);return R}function l(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;for(var b=0,g=0,x=0;d[b]===o;)g++,b++;for(var A=(d.length-b)*c+1>>>0,k=new Uint8Array(A);d[b];){var w=d.charCodeAt(b);if(w>255)return;var v=t[w];if(v===255)return;for(var S=0,I=A-1;(v!==0||S<x)&&I!==-1;I--,S++)v+=a*k[I]>>>0,k[I]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");x=S,b++}for(var _=A-x;_!==A&&k[_]===0;)_++;for(var R=new Uint8Array(g+(A-_)),B=g;_!==A;)R[B++]=k[_++];return R}function h(d){var b=l(d);if(b)return b;throw new Error("Non-base"+a+" character")}return{encode:f,decodeUnsafe:l,decode:h}}var TE=kE;const IE=TE,_E="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";var PE=IE(_E),Ff=PE,OE=function(e){function t(s){var a=Uint8Array.from(s),o=e(a),c=a.length+4,u=new Uint8Array(c);return u.set(a,0),u.set(o.subarray(0,4),a.length),Ff.encode(u,c)}function r(s){var a=s.slice(0,-4),o=s.slice(-4),c=e(a);if(!(o[0]^c[0]|o[1]^c[1]|o[2]^c[2]|o[3]^c[3]))return a}function n(s){var a=Ff.decodeUnsafe(s);if(a)return r(a)}function i(s){var a=Ff.decode(s),o=r(a);if(!o)throw new Error("Invalid checksum");return o}return{encode:t,decode:i,decodeUnsafe:n}},{sha256:Qp}=Fr,BE=OE;function CE(e){return Qp(Qp(e))}var Qh=BE(CE);Object.defineProperty(Bu,"__esModule",{value:!0});Bu.p2pkh=void 0;const $f=Bi,RE=Ct,Rs=dr(),Mt=Rt,wn=fr,ey=Qh,ei=Rs.OPS;function NE(e,t){if(!e.address&&!e.hash&&!e.output&&!e.pubkey&&!e.input)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Mt.typeforce)({network:Mt.typeforce.maybe(Mt.typeforce.Object),address:Mt.typeforce.maybe(Mt.typeforce.String),hash:Mt.typeforce.maybe(Mt.typeforce.BufferN(20)),output:Mt.typeforce.maybe(Mt.typeforce.BufferN(25)),pubkey:Mt.typeforce.maybe(Mt.isPoint),signature:Mt.typeforce.maybe(Rs.isCanonicalScriptSignature),input:Mt.typeforce.maybe(Mt.typeforce.Buffer)},e);const r=wn.value(()=>{const a=Buffer.from(ey.decode(e.address)),o=a.readUInt8(0),c=a.slice(1);return{version:o,hash:c}}),n=wn.value(()=>Rs.decompile(e.input)),i=e.network||RE.bitcoin,s={name:"p2pkh",network:i};if(wn.prop(s,"address",()=>{if(!s.hash)return;const a=Buffer.allocUnsafe(21);return a.writeUInt8(i.pubKeyHash,0),s.hash.copy(a,1),ey.encode(a)}),wn.prop(s,"hash",()=>{if(e.output)return e.output.slice(3,23);if(e.address)return r().hash;if(e.pubkey||s.pubkey)return $f.hash160(e.pubkey||s.pubkey)}),wn.prop(s,"output",()=>{if(s.hash)return Rs.compile([ei.OP_DUP,ei.OP_HASH160,s.hash,ei.OP_EQUALVERIFY,ei.OP_CHECKSIG])}),wn.prop(s,"pubkey",()=>{if(e.input)return n()[1]}),wn.prop(s,"signature",()=>{if(e.input)return n()[0]}),wn.prop(s,"input",()=>{if(e.pubkey&&e.signature)return Rs.compile([e.signature,e.pubkey])}),wn.prop(s,"witness",()=>{if(s.input)return[]}),t.validate){let a=Buffer.from([]);if(e.address){if(r().version!==i.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(r().hash.length!==20)throw new TypeError("Invalid address");a=r().hash}if(e.hash){if(a.length>0&&!a.equals(e.hash))throw new TypeError("Hash mismatch");a=e.hash}if(e.output){if(e.output.length!==25||e.output[0]!==ei.OP_DUP||e.output[1]!==ei.OP_HASH160||e.output[2]!==20||e.output[23]!==ei.OP_EQUALVERIFY||e.output[24]!==ei.OP_CHECKSIG)throw new TypeError("Output is invalid");const o=e.output.slice(3,23);if(a.length>0&&!a.equals(o))throw new TypeError("Hash mismatch");a=o}if(e.pubkey){const o=$f.hash160(e.pubkey);if(a.length>0&&!a.equals(o))throw new TypeError("Hash mismatch");a=o}if(e.input){const o=n();if(o.length!==2)throw new TypeError("Input is invalid");if(!Rs.isCanonicalScriptSignature(o[0]))throw new TypeError("Input has invalid signature");if(!(0,Mt.isPoint)(o[1]))throw new TypeError("Input has invalid pubkey");if(e.signature&&!e.signature.equals(o[0]))throw new TypeError("Signature mismatch");if(e.pubkey&&!e.pubkey.equals(o[1]))throw new TypeError("Pubkey mismatch");const c=$f.hash160(o[1]);if(a.length>0&&!a.equals(c))throw new TypeError("Hash mismatch")}}return Object.assign(s,e)}Bu.p2pkh=NE;var Cu={};Object.defineProperty(Cu,"__esModule",{value:!0});Cu.p2sh=void 0;const ty=Bi,UE=Ct,sn=dr(),je=Rt,Qr=fr,ry=Qh,ka=sn.OPS;function FE(e,t){if(!e.address&&!e.hash&&!e.output&&!e.redeem&&!e.input)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,je.typeforce)({network:je.typeforce.maybe(je.typeforce.Object),address:je.typeforce.maybe(je.typeforce.String),hash:je.typeforce.maybe(je.typeforce.BufferN(20)),output:je.typeforce.maybe(je.typeforce.BufferN(23)),redeem:je.typeforce.maybe({network:je.typeforce.maybe(je.typeforce.Object),output:je.typeforce.maybe(je.typeforce.Buffer),input:je.typeforce.maybe(je.typeforce.Buffer),witness:je.typeforce.maybe(je.typeforce.arrayOf(je.typeforce.Buffer))}),input:je.typeforce.maybe(je.typeforce.Buffer),witness:je.typeforce.maybe(je.typeforce.arrayOf(je.typeforce.Buffer))},e);let r=e.network;r||(r=e.redeem&&e.redeem.network||UE.bitcoin);const n={network:r},i=Qr.value(()=>{const o=Buffer.from(ry.decode(e.address)),c=o.readUInt8(0),u=o.slice(1);return{version:c,hash:u}}),s=Qr.value(()=>sn.decompile(e.input)),a=Qr.value(()=>{const o=s(),c=o[o.length-1];return{network:r,output:c===ka.OP_FALSE?Buffer.from([]):c,input:sn.compile(o.slice(0,-1)),witness:e.witness||[]}});if(Qr.prop(n,"address",()=>{if(!n.hash)return;const o=Buffer.allocUnsafe(21);return o.writeUInt8(n.network.scriptHash,0),n.hash.copy(o,1),ry.encode(o)}),Qr.prop(n,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return i().hash;if(n.redeem&&n.redeem.output)return ty.hash160(n.redeem.output)}),Qr.prop(n,"output",()=>{if(n.hash)return sn.compile([ka.OP_HASH160,n.hash,ka.OP_EQUAL])}),Qr.prop(n,"redeem",()=>{if(e.input)return a()}),Qr.prop(n,"input",()=>{if(!(!e.redeem||!e.redeem.input||!e.redeem.output))return sn.compile([].concat(sn.decompile(e.redeem.input),e.redeem.output))}),Qr.prop(n,"witness",()=>{if(n.redeem&&n.redeem.witness)return n.redeem.witness;if(n.input)return[]}),Qr.prop(n,"name",()=>{const o=["p2sh"];return n.redeem!==void 0&&n.redeem.name!==void 0&&o.push(n.redeem.name),o.join("-")}),t.validate){let o=Buffer.from([]);if(e.address){if(i().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(i().hash.length!==20)throw new TypeError("Invalid address");o=i().hash}if(e.hash){if(o.length>0&&!o.equals(e.hash))throw new TypeError("Hash mismatch");o=e.hash}if(e.output){if(e.output.length!==23||e.output[0]!==ka.OP_HASH160||e.output[1]!==20||e.output[22]!==ka.OP_EQUAL)throw new TypeError("Output is invalid");const u=e.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 f=sn.decompile(u.output);if(!f||f.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(sn.countNonPushOnlyOPs(f)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const l=ty.hash160(u.output);if(o.length>0&&!o.equals(l))throw new TypeError("Hash mismatch");o=l}if(u.input){const f=u.input.length>0,l=u.witness&&u.witness.length>0;if(!f&&!l)throw new TypeError("Empty input");if(f&&l)throw new TypeError("Input and witness provided");if(f){const h=sn.decompile(u.input);if(!sn.isPushOnly(h))throw new TypeError("Non push-only scriptSig")}}};if(e.input){const u=s();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(e.redeem){if(e.redeem.network&&e.redeem.network!==r)throw new TypeError("Network mismatch");if(e.input){const u=a();if(e.redeem.output&&!e.redeem.output.equals(u.output))throw new TypeError("Redeem.output mismatch");if(e.redeem.input&&!e.redeem.input.equals(u.input))throw new TypeError("Redeem.input mismatch")}c(e.redeem)}if(e.witness&&e.redeem&&e.redeem.witness&&!(0,je.stacksEqual)(e.redeem.witness,e.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,e)}Cu.p2sh=FE;var Ru={};Object.defineProperty(Ru,"__esModule",{value:!0});Ru.p2wpkh=void 0;const Mf=Bi,$E=Ct,Wc=dr(),ut=Rt,ti=fr,xc=vi,ny=Wc.OPS,ME=Buffer.alloc(0);function jE(e,t){if(!e.address&&!e.hash&&!e.output&&!e.pubkey&&!e.witness)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,ut.typeforce)({address:ut.typeforce.maybe(ut.typeforce.String),hash:ut.typeforce.maybe(ut.typeforce.BufferN(20)),input:ut.typeforce.maybe(ut.typeforce.BufferN(0)),network:ut.typeforce.maybe(ut.typeforce.Object),output:ut.typeforce.maybe(ut.typeforce.BufferN(22)),pubkey:ut.typeforce.maybe(ut.isPoint),signature:ut.typeforce.maybe(Wc.isCanonicalScriptSignature),witness:ut.typeforce.maybe(ut.typeforce.arrayOf(ut.typeforce.Buffer))},e);const r=ti.value(()=>{const s=xc.bech32.decode(e.address),a=s.words.shift(),o=xc.bech32.fromWords(s.words);return{version:a,prefix:s.prefix,data:Buffer.from(o)}}),n=e.network||$E.bitcoin,i={name:"p2wpkh",network:n};if(ti.prop(i,"address",()=>{if(!i.hash)return;const s=xc.bech32.toWords(i.hash);return s.unshift(0),xc.bech32.encode(n.bech32,s)}),ti.prop(i,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return r().data;if(e.pubkey||i.pubkey)return Mf.hash160(e.pubkey||i.pubkey)}),ti.prop(i,"output",()=>{if(i.hash)return Wc.compile([ny.OP_0,i.hash])}),ti.prop(i,"pubkey",()=>{if(e.pubkey)return e.pubkey;if(e.witness)return e.witness[1]}),ti.prop(i,"signature",()=>{if(e.witness)return e.witness[0]}),ti.prop(i,"input",()=>{if(i.witness)return ME}),ti.prop(i,"witness",()=>{if(e.pubkey&&e.signature)return[e.signature,e.pubkey]}),t.validate){let s=Buffer.from([]);if(e.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");s=r().data}if(e.hash){if(s.length>0&&!s.equals(e.hash))throw new TypeError("Hash mismatch");s=e.hash}if(e.output){if(e.output.length!==22||e.output[0]!==ny.OP_0||e.output[1]!==20)throw new TypeError("Output is invalid");if(s.length>0&&!s.equals(e.output.slice(2)))throw new TypeError("Hash mismatch");s=e.output.slice(2)}if(e.pubkey){const a=Mf.hash160(e.pubkey);if(s.length>0&&!s.equals(a))throw new TypeError("Hash mismatch");if(s=a,!(0,ut.isPoint)(e.pubkey)||e.pubkey.length!==33)throw new TypeError("Invalid pubkey for p2wpkh")}if(e.witness){if(e.witness.length!==2)throw new TypeError("Witness is invalid");if(!Wc.isCanonicalScriptSignature(e.witness[0]))throw new TypeError("Witness has invalid signature");if(!(0,ut.isPoint)(e.witness[1])||e.witness[1].length!==33)throw new TypeError("Witness has invalid pubkey");if(e.signature&&!e.signature.equals(e.witness[0]))throw new TypeError("Signature mismatch");if(e.pubkey&&!e.pubkey.equals(e.witness[1]))throw new TypeError("Pubkey mismatch");const a=Mf.hash160(e.witness[1]);if(s.length>0&&!s.equals(a))throw new TypeError("Hash mismatch")}}return Object.assign(i,e)}Ru.p2wpkh=jE;var Nu={};Object.defineProperty(Nu,"__esModule",{value:!0});Nu.p2wsh=void 0;const iy=Bi,HE=Ct,_n=dr(),Ue=Rt,vn=fr,Ac=vi,sy=_n.OPS,jf=Buffer.alloc(0);function Sc(e){return!!(Buffer.isBuffer(e)&&e.length===65&&e[0]===4&&(0,Ue.isPoint)(e))}function LE(e,t){if(!e.address&&!e.hash&&!e.output&&!e.redeem&&!e.witness)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Ue.typeforce)({network:Ue.typeforce.maybe(Ue.typeforce.Object),address:Ue.typeforce.maybe(Ue.typeforce.String),hash:Ue.typeforce.maybe(Ue.typeforce.BufferN(32)),output:Ue.typeforce.maybe(Ue.typeforce.BufferN(34)),redeem:Ue.typeforce.maybe({input:Ue.typeforce.maybe(Ue.typeforce.Buffer),network:Ue.typeforce.maybe(Ue.typeforce.Object),output:Ue.typeforce.maybe(Ue.typeforce.Buffer),witness:Ue.typeforce.maybe(Ue.typeforce.arrayOf(Ue.typeforce.Buffer))}),input:Ue.typeforce.maybe(Ue.typeforce.BufferN(0)),witness:Ue.typeforce.maybe(Ue.typeforce.arrayOf(Ue.typeforce.Buffer))},e);const r=vn.value(()=>{const a=Ac.bech32.decode(e.address),o=a.words.shift(),c=Ac.bech32.fromWords(a.words);return{version:o,prefix:a.prefix,data:Buffer.from(c)}}),n=vn.value(()=>_n.decompile(e.redeem.input));let i=e.network;i||(i=e.redeem&&e.redeem.network||HE.bitcoin);const s={network:i};if(vn.prop(s,"address",()=>{if(!s.hash)return;const a=Ac.bech32.toWords(s.hash);return a.unshift(0),Ac.bech32.encode(i.bech32,a)}),vn.prop(s,"hash",()=>{if(e.output)return e.output.slice(2);if(e.address)return r().data;if(s.redeem&&s.redeem.output)return iy.sha256(s.redeem.output)}),vn.prop(s,"output",()=>{if(s.hash)return _n.compile([sy.OP_0,s.hash])}),vn.prop(s,"redeem",()=>{if(e.witness)return{output:e.witness[e.witness.length-1],input:jf,witness:e.witness.slice(0,-1)}}),vn.prop(s,"input",()=>{if(s.witness)return jf}),vn.prop(s,"witness",()=>{if(e.redeem&&e.redeem.input&&e.redeem.input.length>0&&e.redeem.output&&e.redeem.output.length>0){const a=_n.toStack(n());return s.redeem=Object.assign({witness:a},e.redeem),s.redeem.input=jf,[].concat(a,e.redeem.output)}if(e.redeem&&e.redeem.output&&e.redeem.witness)return[].concat(e.redeem.witness,e.redeem.output)}),vn.prop(s,"name",()=>{const a=["p2wsh"];return s.redeem!==void 0&&s.redeem.name!==void 0&&a.push(s.redeem.name),a.join("-")}),t.validate){let a=Buffer.from([]);if(e.address){if(r().prefix!==i.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(e.hash){if(a.length>0&&!a.equals(e.hash))throw new TypeError("Hash mismatch");a=e.hash}if(e.output){if(e.output.length!==34||e.output[0]!==sy.OP_0||e.output[1]!==32)throw new TypeError("Output is invalid");const o=e.output.slice(2);if(a.length>0&&!a.equals(o))throw new TypeError("Hash mismatch");a=o}if(e.redeem){if(e.redeem.network&&e.redeem.network!==i)throw new TypeError("Network mismatch");if(e.redeem.input&&e.redeem.input.length>0&&e.redeem.witness&&e.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(e.redeem.output){const o=_n.decompile(e.redeem.output);if(!o||o.length<1)throw new TypeError("Redeem.output is invalid");if(e.redeem.output.byteLength>3600)throw new TypeError("Redeem.output unspendable if larger than 3600 bytes");if(_n.countNonPushOnlyOPs(o)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const c=iy.sha256(e.redeem.output);if(a.length>0&&!a.equals(c))throw new TypeError("Hash mismatch");a=c}if(e.redeem.input&&!_n.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(e.witness&&e.redeem.witness&&!(0,Ue.stacksEqual)(e.witness,e.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(e.redeem.input&&n().some(Sc)||e.redeem.output&&(_n.decompile(e.redeem.output)||[]).some(Sc))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(e.witness&&e.witness.length>0){const o=e.witness[e.witness.length-1];if(e.redeem&&e.redeem.output&&!e.redeem.output.equals(o))throw new TypeError("Witness and redeem.output mismatch");if(e.witness.some(Sc)||(_n.decompile(o)||[]).some(Sc))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(s,e)}Nu.p2wsh=LE;var Ta={},as={};Object.defineProperty(as,"__esModule",{value:!0});as.getEccLib=as.initEccLib=void 0;const qa={};function DE(e,t){e?e!==qa.eccLib&&(t!=null&&t.DANGER_DO_NOT_VERIFY_ECCLIB||VE(e),qa.eccLib=e):qa.eccLib=e}as.initEccLib=DE;function zE(){if(!qa.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return qa.eccLib}as.getEccLib=zE;const En=e=>Buffer.from(e,"hex");function VE(e){yr(typeof e.isXOnlyPoint=="function"),yr(e.isXOnlyPoint(En("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),yr(e.isXOnlyPoint(En("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),yr(e.isXOnlyPoint(En("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),yr(e.isXOnlyPoint(En("0000000000000000000000000000000000000000000000000000000000000001"))),yr(!e.isXOnlyPoint(En("0000000000000000000000000000000000000000000000000000000000000000"))),yr(!e.isXOnlyPoint(En("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),yr(typeof e.xOnlyPointAddTweak=="function"),GE.forEach(t=>{const r=e.xOnlyPointAddTweak(En(t.pubkey),En(t.tweak));t.result===null?yr(r===null):(yr(r!==null),yr(r.parity===t.parity),yr(Buffer.from(r.xOnlyPubkey).equals(En(t.result))))})}function yr(e){if(!e)throw new Error("ecc library invalid")}const GE=[{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 e0={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.tweakKey=e.tapTweakHash=e.tapleafHash=e.findScriptPath=e.toHashTree=e.rootHashFromPath=e.MAX_TAPTREE_DEPTH=e.LEAF_VERSION_TAPSCRIPT=void 0;const t=bs,r=as,n=Bi,i=vt,s=Rt;e.LEAF_VERSION_TAPSCRIPT=192,e.MAX_TAPTREE_DEPTH=128;const a=g=>"left"in g&&"right"in g;function o(g,x){if(g.length<33)throw new TypeError(`The control-block length is too small. Got ${g.length}, expected min 33.`);const A=(g.length-33)/32;let k=x;for(let w=0;w<A;w++){const v=g.slice(33+32*w,65+32*w);k.compare(v)<0?k=d(k,v):k=d(v,k)}return k}e.rootHashFromPath=o;function c(g){if((0,s.isTapleaf)(g))return{hash:f(g)};const x=[c(g[0]),c(g[1])];x.sort((w,v)=>w.hash.compare(v.hash));const[A,k]=x;return{hash:d(A.hash,k.hash),left:A,right:k}}e.toHashTree=c;function u(g,x){if(a(g)){const A=u(g.left,x);if(A!==void 0)return[...A,g.right.hash];const k=u(g.right,x);if(k!==void 0)return[...k,g.left.hash]}else if(g.hash.equals(x))return[]}e.findScriptPath=u;function f(g){const x=g.version||e.LEAF_VERSION_TAPSCRIPT;return n.taggedHash("TapLeaf",t.Buffer.concat([t.Buffer.from([x]),b(g.output)]))}e.tapleafHash=f;function l(g,x){return n.taggedHash("TapTweak",t.Buffer.concat(x?[g,x]:[g]))}e.tapTweakHash=l;function h(g,x){if(!t.Buffer.isBuffer(g)||g.length!==32||x&&x.length!==32)return null;const A=l(g,x),k=(0,r.getEccLib)().xOnlyPointAddTweak(g,A);return!k||k.xOnlyPubkey===null?null:{parity:k.parity,x:t.Buffer.from(k.xOnlyPubkey)}}e.tweakKey=h;function d(g,x){return n.taggedHash("TapBranch",t.Buffer.concat([g,x]))}function b(g){const x=i.varuint.encodingLength(g.length),A=t.Buffer.allocUnsafe(x);return i.varuint.encode(g.length,A),t.Buffer.concat([A,g])}})(e0);var jt={},ay;function qE(){if(ay)return jt;ay=1,Object.defineProperty(jt,"__esModule",{value:!0}),jt.toOutputScript=jt.fromOutputScript=jt.toBech32=jt.toBase58Check=jt.fromBech32=jt.fromBase58Check=void 0;const e=Ct,t=t0(),r=dr(),n=Rt,i=vi,s=Qh,a=40,o=2,c=16,u=2,f=80,l="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 h(w,v){const S=w.slice(2);if(S.length<o||S.length>a)throw new TypeError("Invalid program length for segwit address");const I=w[0]-f;if(I<u||I>c)throw new TypeError("Invalid version for segwit address");if(w[1]!==S.length)throw new TypeError("Invalid script for segwit address");return console.warn(l),x(S,I,v.bech32)}function d(w){const v=Buffer.from(s.decode(w));if(v.length<21)throw new TypeError(w+" is too short");if(v.length>21)throw new TypeError(w+" is too long");const S=v.readUInt8(0),I=v.slice(1);return{version:S,hash:I}}jt.fromBase58Check=d;function b(w){let v,S;try{v=i.bech32.decode(w)}catch{}if(v){if(S=v.words[0],S!==0)throw new TypeError(w+" uses wrong encoding")}else if(v=i.bech32m.decode(w),S=v.words[0],S===0)throw new TypeError(w+" uses wrong encoding");const I=i.bech32.fromWords(v.words.slice(1));return{version:S,prefix:v.prefix,data:Buffer.from(I)}}jt.fromBech32=b;function g(w,v){(0,n.typeforce)((0,n.tuple)(n.Hash160bit,n.UInt8),arguments);const S=Buffer.allocUnsafe(21);return S.writeUInt8(v,0),w.copy(S,1),s.encode(S)}jt.toBase58Check=g;function x(w,v,S){const I=i.bech32.toWords(w);return I.unshift(v),v===0?i.bech32.encode(S,I):i.bech32m.encode(S,I)}jt.toBech32=x;function A(w,v){v=v||e.bitcoin;try{return t.p2pkh({output:w,network:v}).address}catch{}try{return t.p2sh({output:w,network:v}).address}catch{}try{return t.p2wpkh({output:w,network:v}).address}catch{}try{return t.p2wsh({output:w,network:v}).address}catch{}try{return t.p2tr({output:w,network:v}).address}catch{}try{return h(w,v)}catch{}throw new Error(r.toASM(w)+" has no matching Address")}jt.fromOutputScript=A;function k(w,v){v=v||e.bitcoin;let S,I;try{S=d(w)}catch{}if(S){if(S.version===v.pubKeyHash)return t.p2pkh({hash:S.hash}).output;if(S.version===v.scriptHash)return t.p2sh({hash:S.hash}).output}else{try{I=b(w)}catch{}if(I){if(I.prefix!==v.bech32)throw new Error(w+" has an invalid prefix");if(I.version===0){if(I.data.length===20)return t.p2wpkh({hash:I.data}).output;if(I.data.length===32)return t.p2wsh({hash:I.data}).output}else if(I.version===1){if(I.data.length===32)return t.p2tr({pubkey:I.data}).output}else if(I.version>=u&&I.version<=c&&I.data.length>=o&&I.data.length<=a)return console.warn(l),r.compile([I.version+f,I.data])}}throw new Error(w+" has no matching Script")}return jt.toOutputScript=k,jt}var oy;function WE(){if(oy)return Ta;oy=1,Object.defineProperty(Ta,"__esModule",{value:!0}),Ta.p2tr=void 0;const e=bs,t=Ct,r=dr(),n=Rt,i=as,s=e0,a=fr,o=vi,c=qE(),u=r.OPS,f=1,l=80;function h(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)),x=a.value(()=>{if(!(!d.witness||!d.witness.length))return d.witness.length>=2&&d.witness[d.witness.length-1][0]===l?d.witness.slice(0,-1):d.witness.slice()}),A=a.value(()=>{if(d.scriptTree)return(0,s.toHashTree)(d.scriptTree);if(d.hash)return{hash:d.hash}}),k=d.network||t.bitcoin,w={name:"p2tr",network:k};if(a.prop(w,"address",()=>{if(!w.pubkey)return;const v=o.bech32m.toWords(w.pubkey);return v.unshift(f),o.bech32m.encode(k.bech32,v)}),a.prop(w,"hash",()=>{const v=A();if(v)return v.hash;const S=x();if(S&&S.length>1){const I=S[S.length-1],_=I[0]&n.TAPLEAF_VERSION_MASK,R=S[S.length-2],B=(0,s.tapleafHash)({output:R,version:_});return(0,s.rootHashFromPath)(I,B)}return null}),a.prop(w,"output",()=>{if(w.pubkey)return r.compile([u.OP_1,w.pubkey])}),a.prop(w,"redeemVersion",()=>d.redeemVersion?d.redeemVersion:d.redeem&&d.redeem.redeemVersion!==void 0&&d.redeem.redeemVersion!==null?d.redeem.redeemVersion:s.LEAF_VERSION_TAPSCRIPT),a.prop(w,"redeem",()=>{const v=x();if(!(!v||v.length<2))return{output:v[v.length-2],witness:v.slice(0,-2),redeemVersion:v[v.length-1][0]&n.TAPLEAF_VERSION_MASK}}),a.prop(w,"pubkey",()=>{if(d.pubkey)return d.pubkey;if(d.output)return d.output.slice(2);if(d.address)return g().data;if(w.internalPubkey){const v=(0,s.tweakKey)(w.internalPubkey,w.hash);if(v)return v.x}}),a.prop(w,"internalPubkey",()=>{if(d.internalPubkey)return d.internalPubkey;const v=x();if(v&&v.length>1)return v[v.length-1].slice(1,33)}),a.prop(w,"signature",()=>{if(d.signature)return d.signature;const v=x();if(!(!v||v.length!==1))return v[0]}),a.prop(w,"witness",()=>{if(d.witness)return d.witness;const v=A();if(v&&d.redeem&&d.redeem.output&&d.internalPubkey){const S=(0,s.tapleafHash)({output:d.redeem.output,version:w.redeemVersion}),I=(0,s.findScriptPath)(v,S);if(!I)return;const _=(0,s.tweakKey)(d.internalPubkey,v.hash);if(!_)return;const R=e.Buffer.concat([e.Buffer.from([w.redeemVersion|_.parity]),d.internalPubkey].concat(I));return[d.redeem.output,R]}if(d.signature)return[d.signature]}),b.validate){let v=e.Buffer.from([]);if(d.address){if(k&&k.bech32!==g().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(g().version!==f)throw new TypeError("Invalid address version");if(g().data.length!==32)throw new TypeError("Invalid address data");v=g().data}if(d.pubkey){if(v.length>0&&!v.equals(d.pubkey))throw new TypeError("Pubkey mismatch");v=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(v.length>0&&!v.equals(d.output.slice(2)))throw new TypeError("Pubkey mismatch");v=d.output.slice(2)}if(d.internalPubkey){const _=(0,s.tweakKey)(d.internalPubkey,w.hash);if(v.length>0&&!v.equals(_.x))throw new TypeError("Pubkey mismatch");v=_.x}if(v&&v.length&&!(0,i.getEccLib)().isXOnlyPoint(v))throw new TypeError("Invalid pubkey for p2tr");const S=A();if(d.hash&&S&&!d.hash.equals(S.hash))throw new TypeError("Hash mismatch");if(d.redeem&&d.redeem.output&&S){const _=(0,s.tapleafHash)({output:d.redeem.output,version:w.redeemVersion});if(!(0,s.findScriptPath)(S,_))throw new TypeError("Redeem script not in tree")}const I=x();if(d.redeem&&w.redeem){if(d.redeem.redeemVersion&&d.redeem.redeemVersion!==w.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(w.redeem.output&&!d.redeem.output.equals(w.redeem.output))throw new TypeError("Redeem.output and witness mismatch")}if(d.redeem.witness&&w.redeem.witness&&!(0,n.stacksEqual)(d.redeem.witness,w.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(I&&I.length)if(I.length===1){if(d.signature&&!d.signature.equals(I[0]))throw new TypeError("Signature mismatch")}else{const _=I[I.length-1];if(_.length<33)throw new TypeError(`The control-block length is too small. Got ${_.length}, expected min 33.`);if((_.length-33)%32!==0)throw new TypeError(`The control-block length of ${_.length} is incorrect!`);const R=(_.length-33)/32;if(R>128)throw new TypeError(`The script path is too long. Got ${R}, expected max 128.`);const B=_.slice(1,33);if(d.internalPubkey&&!d.internalPubkey.equals(B))throw new TypeError("Internal pubkey mismatch");if(!(0,i.getEccLib)().isXOnlyPoint(B))throw new TypeError("Invalid internalPubkey for p2tr witness");const M=_[0]&n.TAPLEAF_VERSION_MASK,F=I[I.length-2],H=(0,s.tapleafHash)({output:F,version:M}),z=(0,s.rootHashFromPath)(_,H),Q=(0,s.tweakKey)(B,z);if(!Q)throw new TypeError("Invalid outputKey for p2tr witness");if(v.length&&!v.equals(Q.x))throw new TypeError("Pubkey mismatch for p2tr witness");if(Q.parity!==(_[0]&1))throw new Error("Incorrect parity")}}return Object.assign(w,d)}return Ta.p2tr=h,Ta}var cy;function t0(){return cy||(cy=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.p2tr=e.p2wsh=e.p2wpkh=e.p2sh=e.p2pkh=e.p2pk=e.p2ms=e.embed=void 0;const t=_u;Object.defineProperty(e,"embed",{enumerable:!0,get:function(){return t.p2data}});const r=Pu;Object.defineProperty(e,"p2ms",{enumerable:!0,get:function(){return r.p2ms}});const n=Ou;Object.defineProperty(e,"p2pk",{enumerable:!0,get:function(){return n.p2pk}});const i=Bu;Object.defineProperty(e,"p2pkh",{enumerable:!0,get:function(){return i.p2pkh}});const s=Cu;Object.defineProperty(e,"p2sh",{enumerable:!0,get:function(){return s.p2sh}});const a=Ru;Object.defineProperty(e,"p2wpkh",{enumerable:!0,get:function(){return a.p2wpkh}});const o=Nu;Object.defineProperty(e,"p2wsh",{enumerable:!0,get:function(){return o.p2wsh}});const c=WE();Object.defineProperty(e,"p2tr",{enumerable:!0,get:function(){return c.p2tr}})}(Uf)),Uf}Object.defineProperty(Re,"__esModule",{value:!0});Re.signatureBlocksAction=Re.checkInputForSig=Re.pubkeyInScript=Re.pubkeyPositionInScript=Re.witnessStackToScriptWitness=Re.isP2TR=Re.isP2SHScript=Re.isP2WSHScript=Re.isP2WPKH=Re.isP2PKH=Re.isP2PK=Re.isP2MS=void 0;const uy=Go,Wa=dr(),kc=zo,KE=Bi,gs=t0();function ws(e){return t=>{try{return e({output:t}),!0}catch{return!1}}}Re.isP2MS=ws(gs.p2ms);Re.isP2PK=ws(gs.p2pk);Re.isP2PKH=ws(gs.p2pkh);Re.isP2WPKH=ws(gs.p2wpkh);Re.isP2WSHScript=ws(gs.p2wsh);Re.isP2SHScript=ws(gs.p2sh);Re.isP2TR=ws(gs.p2tr);function XE(e){let t=Buffer.allocUnsafe(0);function r(a){t=Buffer.concat([t,Buffer.from(a)])}function n(a){const o=t.length,c=uy.encodingLength(a);t=Buffer.concat([t,Buffer.allocUnsafe(c)]),uy.encode(a,t,o)}function i(a){n(a.length),r(a)}function s(a){n(a.length),a.forEach(i)}return s(e),t}Re.witnessStackToScriptWitness=XE;function Hg(e,t){const r=(0,KE.hash160)(e),n=e.slice(1,33),i=Wa.decompile(t);if(i===null)throw new Error("Unknown script error");return i.findIndex(s=>typeof s=="number"?!1:s.equals(e)||s.equals(r)||s.equals(n))}Re.pubkeyPositionInScript=Hg;function JE(e,t){return Hg(e,t)!==-1}Re.pubkeyInScript=JE;function YE(e,t){return ZE(e).some(n=>Lg(n,Wa.signature.decode,t))}Re.checkInputForSig=YE;function Lg(e,t,r){const{hashType:n}=t(e),i=[];switch(n&kc.Transaction.SIGHASH_ANYONECANPAY&&i.push("addInput"),n&31){case kc.Transaction.SIGHASH_ALL:break;case kc.Transaction.SIGHASH_SINGLE:case kc.Transaction.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence");break}return i.indexOf(r)===-1}Re.signatureBlocksAction=Lg;function ZE(e){let t=[];if((e.partialSig||[]).length===0){if(!e.finalScriptSig&&!e.finalScriptWitness)return[];t=QE(e)}else t=e.partialSig;return t.map(r=>r.signature)}function QE(e){const t=e.finalScriptSig?Wa.decompile(e.finalScriptSig)||[]:[],r=e.finalScriptWitness?Wa.decompile(e.finalScriptWitness)||[]:[];return t.concat(r).filter(n=>Buffer.isBuffer(n)&&Wa.isCanonicalScriptSignature(n)).map(n=>({signature:n}))}Object.defineProperty(Ge,"__esModule",{value:!0});Ge.checkTaprootInputForSigs=Ge.tapTreeFromList=Ge.tapTreeToList=Ge.tweakInternalPubKey=Ge.checkTaprootOutputFields=Ge.checkTaprootInputFields=Ge.isTaprootOutput=Ge.isTaprootInput=$a=Ge.serializeTaprootSignature=Ge.tapScriptFinalizer=Ge.toXOnly=void 0;const r0=Rt,ex=zo,Uu=Re,Si=e0,tx=t0(),rx=Re,nx=e=>e.length===32?e:e.slice(1,33);Ge.toXOnly=nx;function ix(e,t,r){const n=xx(t,e,r);try{const s=vx(t,n).concat(n.script).concat(n.controlBlock);return{finalScriptWitness:(0,Uu.witnessStackToScriptWitness)(s)}}catch(i){throw new Error(`Can not finalize taproot input #${e}: ${i}`)}}Ge.tapScriptFinalizer=ix;function sx(e,t){const r=t?Buffer.from([t]):Buffer.from([]);return Buffer.concat([e,r])}var $a=Ge.serializeTaprootSignature=sx;function Kc(e){return e&&!!(e.tapInternalKey||e.tapMerkleRoot||e.tapLeafScript&&e.tapLeafScript.length||e.tapBip32Derivation&&e.tapBip32Derivation.length||e.witnessUtxo&&(0,Uu.isP2TR)(e.witnessUtxo.script))}Ge.isTaprootInput=Kc;function Xc(e,t){return e&&!!(e.tapInternalKey||e.tapTree||e.tapBip32Derivation&&e.tapBip32Derivation.length||t&&(0,Uu.isP2TR)(t))}Ge.isTaprootOutput=Xc;function ax(e,t,r){bx(e,t,r),wx(e,t,r)}Ge.checkTaprootInputFields=ax;function ox(e,t,r){gx(e,t,r),cx(e,t)}Ge.checkTaprootOutputFields=ox;function cx(e,t){if(!t.tapTree&&!t.tapInternalKey)return;const r=t.tapInternalKey||e.tapInternalKey,n=t.tapTree||e.tapTree;if(r){const{script:i}=e,s=ux(r,n);if(i&&!i.equals(s))throw new Error("Error adding output. Script or address missmatch.")}}function ux(e,t){const r=t&&Dg(t.leaves),{output:n}=(0,tx.p2tr)({internalPubkey:e,scriptTree:r});return n}function fx(e,t){const r=t.tapInternalKey,n=r&&(0,Si.tweakKey)(r,t.tapMerkleRoot);if(!n)throw new Error(`Cannot tweak tap internal key for input #${e}. Public key: ${r&&r.toString("hex")}`);return n.x}Ge.tweakInternalPubKey=fx;function lx(e){if(!(0,r0.isTaptree)(e))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return Fd(e)}Ge.tapTreeToList=lx;function Dg(e=[]){return e.length===1&&e[0].depth===0?{output:e[0].script,version:e[0].leafVersion}:mx(e)}Ge.tapTreeFromList=Dg;function dx(e,t){return px(e).some(n=>(0,rx.signatureBlocksAction)(n,hx,t))}Ge.checkTaprootInputForSigs=dx;function hx(e){return{signature:e.slice(0,64),hashType:e.slice(64)[0]||ex.Transaction.SIGHASH_DEFAULT}}function px(e){const t=[];if(e.tapKeySig&&t.push(e.tapKeySig),e.tapScriptSig&&t.push(...e.tapScriptSig.map(r=>r.signature)),!t.length){const r=yx(e.finalScriptWitness);r&&t.push(r)}return t}function yx(e){if(!e)return;const t=e.slice(2);if(t.length===64||t.length===65)return t}function Fd(e,t=[],r=0){if(r>Si.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return e?(0,r0.isTapleaf)(e)?(t.push({depth:r,leafVersion:e.version||Si.LEAF_VERSION_TAPSCRIPT,script:e.output}),t):(e[0]&&Fd(e[0],t,r+1),e[1]&&Fd(e[1],t,r+1),t):[]}function mx(e){let t;for(const r of e)if(t=$d(r,t),!t)throw new Error("No room left to insert tapleaf in tree");return t}function $d(e,t,r=0){if(r>Si.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");if(e.depth===r)return t?void 0:{output:e.script,version:e.leafVersion};if((0,r0.isTapleaf)(t))return;const n=$d(e,t&&t[0],r+1);if(n)return[n,t&&t[1]];const i=$d(e,t&&t[1],r+1);if(i)return[t&&t[0],i]}function bx(e,t,r){const n=Kc(e)&&zs(t),i=zs(e)&&Kc(t),s=e===t&&Kc(t)&&zs(t);if(n||i||s)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function gx(e,t,r){const n=Xc(e)&&zs(t),i=zs(e)&&Xc(t),s=e===t&&Xc(t)&&zs(t);if(n||i||s)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function wx(e,t,r){if(t.tapMerkleRoot){const n=(t.tapLeafScript||[]).every(s=>Hf(s,t.tapMerkleRoot)),i=(e.tapLeafScript||[]).every(s=>Hf(s,t.tapMerkleRoot));if(!n||!i)throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}else if(e.tapMerkleRoot&&!(t.tapLeafScript||[]).every(i=>Hf(i,e.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}function Hf(e,t){if(!t)return!0;const r=(0,Si.tapleafHash)({output:e.script,version:e.leafVersion});return(0,Si.rootHashFromPath)(e.controlBlock,r).equals(t)}function vx(e,t){const r=(0,Si.tapleafHash)({output:t.script,version:t.leafVersion});return(e.tapScriptSig||[]).filter(n=>n.leafHash.equals(r)).map(n=>Ex(t.script,n)).sort((n,i)=>i.positionInScript-n.positionInScript).map(n=>n.signature)}function Ex(e,t){return Object.assign({positionInScript:(0,Uu.pubkeyPositionInScript)(t.pubkey,e)},t)}function xx(e,t,r){if(!e.tapScriptSig||!e.tapScriptSig.length)throw new Error(`Can not finalize taproot input #${t}. No tapleaf script signature provided.`);const n=(e.tapLeafScript||[]).sort((i,s)=>i.controlBlock.length-s.controlBlock.length).find(i=>Ax(i,e.tapScriptSig,r));if(!n)throw new Error(`Can not finalize taproot input #${t}. Signature for tapleaf script not found.`);return n}function Ax(e,t,r){const n=(0,Si.tapleafHash)({output:e.script,version:e.leafVersion});return(!r||r.equals(n))&&t.find(s=>s.leafHash.equals(n))!==void 0}function zs(e){return e&&!!(e.redeemScript||e.witnessScript||e.bip32Derivation&&e.bip32Derivation.length)}const mr={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:e=>"counterparty signature not found for utxo "+e,invalidCounterpartySigForUTXO:e=>"invalid counterparty signature for utxo "+e,htlcNotExpired:e=>`HTLC not expired, need more ${e} blocks`,controlBlockGenerationFailed:"failed to generate control block",invalidLeaf:"invalid leaf"},Tc=192;Ie.initEccLib(xr);let Sx=class{constructor(t,r){this.signer=t,this.internalPubkey=Lp(),this.network=hv(r)}address(t,r){const n=this.generateLeaves(t,r),{address:i}=Ie.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:n});if(!i)throw new Error(mr.htlcAddressGenerationFailed);return i}async _buildRawTx(t,r,n,i,s){const a=new Ie.Transaction;a.version=2;const o=this.address(t,n||"redeem"),c=await this.getProvider();let u=[];if(s&&s.length>0)for(const h of s){const d=await c.getTransaction(h);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 f=u.reduce((h,d)=>h+d.value,0);if(f===0)throw new Error(`${o} ${mr.notFunded}`);for(let h=0;h<u.length;h++)a.addInput(Buffer.from(u[h].txid,"hex").reverse(),u[h].vout);if(i!=null&&i.vSize){const h=await c.getFeeRates(),d=Math.ceil(h.hourFee*i.vSize),b=f-d;return a.addOutput(Ie.address.toOutputScript(r,this.network),b),{tx:a,usedUtxos:u}}const l=(i==null?void 0:i.fee)??await c.suggestFee(o,f,Ls.MEDIUM);return a.addOutput(Ie.address.toOutputScript(r,this.network),f-l),{tx:a,usedUtxos:u,fee:l,balance:f}}getOutputScript(t,r){return Ie.address.toOutputScript(this.address(t,r||"redeem"),this.network)}async initiate(t,r){const n=await this.getProvider(),i=await this.signer.getAddress();let s,a;D.isOrder(t)?(s=t.source_swap.swap_id,a=Number(t.source_swap.amount)):(s=t.to,a=Number(t.amount)),r===void 0&&(r=await n.suggestFee(i,a,Ls.MEDIUM));const o=await this.signer.send(s,a,r);return m.Ok(o)}async generateRedeemSACP(t,r,n){const{tx:i,usedUtxos:s}=await this._buildRawTx(t,t.destination_swap.delegate,"redeem",{fee:n}),a=this.getOutputScript(t,"redeem"),o=Ie.Transaction.SIGHASH_SINGLE|Ie.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(1,t),u=s.map(l=>l.value),f=Aa(a,s.length);for(let l=0;l<i.ins.length;l++){const h=i.hashForWitnessV1(l,f,u,o,c),d=await this.signer.signSchnorr(h);i.setWitness(l,[$a(d,o),Buffer.from(r,"hex"),this.redeemLeaf(m.trim0x(t.destination_swap.secret_hash),Ve(t.destination_swap.delegate)),await this.generateControlBlockFor(1,t)])}return i.toHex()}async generateInstantRefundSACP(t){const r=this.getOutputScript(t,"instantRefund"),{tx:n,usedUtxos:i,fee:s}=await this._buildRawTx(t,t.destination_swap.delegate,"instantRefund",{fee:0});n.outs=[];const a=Math.max(...i.map(l=>l.value));i.forEach(({value:l})=>{n.addOutput(r,l-(l===a?s??0:0))});const o=Ie.Transaction.SIGHASH_SINGLE|Ie.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(2,t),u=i.map(l=>l.value),f=Aa(r,i.length);for(let l=0;l<n.ins.length;l++){const h=n.hashForWitnessV1(l,f,u,o,c),d=await this.signer.signSchnorr(h);n.setWitness(l,[$a(d,o),$a(d,o),this.instantRefundLeaf(Ve(t.source_swap.initiator),Ve(t.destination_swap.delegate)),await this.generateControlBlockFor(2,t)])}return n.toHex()}async generateInstantRefundSACPWithHash(t){const r=[],n=Ie.Transaction.SIGHASH_SINGLE|Ie.Transaction.SIGHASH_ANYONECANPAY;for(let i=0;i<t.length;i++){const s=Buffer.from(t[i],"hex"),a=await this.signer.signSchnorr(s);r.push($a(a,n).toString("hex"))}return m.Ok(r)}async instantRefund(t,r,n){$p(r.length>0,mr.noCounterpartySigs);const{tx:i,usedUtxos:s}=await this._buildRawTx(t,await this.signer.getAddress(),"instantRefund",{fee:n});for(const h of s)if(!r.find(d=>d.utxo===h.txid))throw new Error(mr.counterPartySigNotFound(h.txid));const a=this.getOutputScript(t,"instantRefund"),o=Ie.Transaction.SIGHASH_DEFAULT,c=this.leafHash(2,t),u=s.map(h=>h.value),f=Aa(a,s.length);for(let h=0;h<i.ins.length;h++){const d=i.hashForWitnessV1(h,f,u,o,c);if(!xr.verifySchnorr(d,Buffer.from(Ve(t.destination_swap.delegate),"hex"),Buffer.from(r[h].sig,"hex")))throw new Error(mr.invalidCounterpartySigForUTXO(r[h].utxo));const b=await this.signer.signSchnorr(d),g=Buffer.from(i.ins[h].hash).reverse().toString("hex"),x=r.find(A=>A.utxo===g);if(!x)throw new Error(mr.counterPartySigNotFound(g));i.setWitness(h,[Buffer.from(x.sig,"hex"),b,this.instantRefundLeaf(Ve(t.source_swap.initiator),Ve(t.destination_swap.delegate)),await this.generateControlBlockFor(2,t)])}return await(await this.getProvider()).broadcast(i.toHex())}async redeem(t,r,n){const i=await this.getRedeemHex(t,r,n);if(!i.ok)return m.Err(i.error);const a=await(await this.getProvider()).broadcast(i.val);return m.Ok(a)}async getRedeemHex(t,r,n){$p(Ie.crypto.sha256(Buffer.from(r,"hex")).toString("hex")===m.trim0x(t.destination_swap.secret_hash),mr.secretMismatch);const a=(D.isBitcoin(t.source_swap.chain)?t.source_swap.redeemer:t.destination_swap.redeemer)??await this.signer.getAddress(),{tx:o,usedUtxos:c}=await this._buildRawTx(t,a,"redeem",{fee:0},n),u=this.leafHash(1,t),f=c.map(b=>b.value),l=Aa(this.getOutputScript(t,"redeem"),c.length),h=Ie.Transaction.SIGHASH_DEFAULT;for(let b=0;b<o.ins.length;b++){const g=o.hashForWitnessV1(b,l,f,h,u),x=await this.signer.signSchnorr(g);o.setWitness(b,[x,Buffer.from(r,"hex"),this.redeemLeaf(m.trim0x(t.destination_swap.secret_hash),Ve(t.destination_swap.delegate)),await this.generateControlBlockFor(1,t)])}const{tx:d}=await this._buildRawTx(t,a,"redeem",{vSize:o.virtualSize()},n);for(let b=0;b<d.ins.length;b++){const g=d.hashForWitnessV1(b,l,f,h,u),x=await this.signer.signSchnorr(g);d.setWitness(b,[x,Buffer.from(r,"hex"),this.redeemLeaf(m.trim0x(t.destination_swap.secret_hash),Ve(t.destination_swap.delegate)),await this.generateControlBlockFor(1,t)])}return m.Ok(d.toHex())}async refund(t,r){const{tx:n,usedUtxos:i}=await this._buildRawTx(t,t.source_swap.delegate??await this.signer.getAddress(),"refund",{fee:r}),[s,a]=await this.canRefund(t,i);if(!s)throw new Error(mr.htlcNotExpired(a));const o=this.leafHash(0,t),c=i.map(d=>d.value),u=Aa(this.getOutputScript(t,"refund"),i.length),f=Ie.Transaction.SIGHASH_DEFAULT;for(let d=0;d<n.ins.length;d++){n.ins[d].sequence=t.source_swap.timelock;const b=n.hashForWitnessV1(d,u,c,f,o),g=await this.signer.signSchnorr(b);n.setWitness(d,[g,this.refundLeaf(t.source_swap.timelock,Ve(t.source_swap.initiator)),await this.generateControlBlockFor(0,t)])}const h=await(await this.getProvider()).broadcast(n.toHex());return m.Ok(h)}async canRefund(t,r){const i=await(await this.getProvider()).getLatestTip();for(const s of r){let a=0;if(s.status.confirmed&&s.status.block_height+t.source_swap.timelock>i?a=s.status.block_height+t.source_swap.timelock-i+1:s.status.confirmed||(a=t.source_swap.timelock+1),a>0)return[!1,a]}return[!0,0]}async generateControlBlockFor(t,r){let n,i;switch(t){case 1:n=this.redeemLeaf(m.trim0x(r.destination_swap.secret_hash),Ve(r.destination_swap.delegate)),i=this.generateLeaves(r,"redeem");break;case 0:n=this.refundLeaf(r.source_swap.timelock,Ve(r.source_swap.initiator)),i=this.generateLeaves(r,"refund");break;case 2:n=this.instantRefundLeaf(Ve(r.source_swap.initiator),Ve(r.destination_swap.delegate)),i=this.generateLeaves(r,"instantRefund");break;default:throw new Error(mr.controlBlockGenerationFailed)}const s=await this.signer.getNetwork(),a=Ie.payments.p2tr({internalPubkey:Lp(),network:s,scriptTree:i,redeem:{output:n,redeemVersion:Tc}});if(!a.witness)throw new Error(mr.controlBlockGenerationFailed);return a.witness[a.witness.length-1]}leafHash(t,r){let n;switch(t){case 1:n=this.redeemLeaf(m.trim0x(r.destination_swap.secret_hash),Ve(r.destination_swap.delegate));break;case 0:n=this.refundLeaf(r.source_swap.timelock,Ve(r.source_swap.initiator));break;case 2:n=this.instantRefundLeaf(Ve(r.source_swap.initiator),Ve(r.destination_swap.redeemer));break;default:throw new Error(mr.invalidLeaf)}return Ie.crypto.taggedHash("TapLeaf",iv(n))}refundLeaf(t,r){return Ie.script.fromASM(`
|
|
10
|
+
${Ie.script.number.encode(t).toString("hex")}
|
|
11
|
+
OP_CHECKSEQUENCEVERIFY
|
|
12
|
+
OP_DROP
|
|
13
|
+
${r}
|
|
14
|
+
OP_CHECKSIG
|
|
15
|
+
`.trim().replace(/\s+/g," "))}redeemLeaf(t,r){return Ie.script.fromASM(`
|
|
16
|
+
OP_SHA256
|
|
17
|
+
${t}
|
|
18
|
+
OP_EQUALVERIFY
|
|
19
|
+
${r}
|
|
20
|
+
OP_CHECKSIG
|
|
21
|
+
`.trim().replace(/\s+/g," "))}instantRefundLeaf(t,r){return Ie.script.fromASM(`
|
|
22
|
+
${t}
|
|
23
|
+
OP_CHECKSIG
|
|
24
|
+
${r}
|
|
25
|
+
OP_CHECKSIGADD
|
|
26
|
+
OP_2
|
|
27
|
+
OP_NUMEQUAL
|
|
28
|
+
`.trim().replace(/\s+/g," "))}generateLeaves(t,r){let n,i,s;switch(r){case"redeem":n=t.destination_swap,i=n.delegate,s=n.delegate;break;case"refund":n=t.source_swap,i=n.delegate,s=n.delegate;break;case"instantRefund":n=t.source_swap,i=n.redeemer,s=n.redeemer;break;default:throw new Error("Invalid leaf generation type")}return[{version:Tc,output:this.redeemLeaf(n.secret_hash,Ve(i))},[{version:Tc,output:this.refundLeaf(n.timelock,Ve(n.initiator))},{version:Tc,output:this.instantRefundLeaf(Ve(n.initiator),Ve(s))}]]}generateMerkleProofFor(t,r){const n=this.leafHash(1,r),i=this.leafHash(2,r),s=this.leafHash(0,r);switch(t){case 1:{const a=av(s,i);return[Ie.crypto.taggedHash("TapBranch",Buffer.concat(a))]}case 0:return[i,n];case 2:return[s,n];default:throw new Error(mr.invalidLeaf)}}getProvider(){return this.signer.getProvider()}get getPublicKey(){return this.signer.getPublicKey()}get htlcActorAddress(){return this.signer.getPublicKey()}};class zg{constructor(t,r){this.quoteUrl=new m.Url(t),this.auth=r}async getQuoteFromAssets({fromAsset:t,toAsset:r,amount:n,isExactOut:i=!1,options:s}){const a=D.ChainAsset.from(t),o=D.ChainAsset.from(r);return this.getQuote(a,o,n,i,s)}async getQuote(t,r,n,i=!1,s){try{const a=await this.auth.getAuthHeaders();if(a.error)return m.Err(a.error);const o={from:D.ChainAsset.from(t).toString(),to:D.ChainAsset.from(r).toString(),...i?{to_amount:n.toString()}:{from_amount:n.toString()},...(s==null?void 0:s.affiliateFee)!==void 0&&{affiliate_fee:s.affiliateFee.toString()},...(s==null?void 0:s.indicative)!==void 0&&{indicative:s.indicative.toString()}},c=this.quoteUrl.endpoint("/v2/quote").addSearchParams(o),u=await m.Fetcher.get(c,{retryCount:0,...s==null?void 0:s.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 kx="1.2.3";let tr=class Md extends Error{constructor(t,r={}){var a;const n=r.cause instanceof Md?r.cause.details:(a=r.cause)!=null&&a.message?r.cause.message:r.details,i=r.cause instanceof Md&&r.cause.docsPath||r.docsPath,s=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: https://abitype.dev${i}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${kx}`].join(`
|
|
29
|
+
`);super(s),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=i,this.metaMessages=r.metaMessages,this.shortMessage=t}};function Gn(e,t){const r=e.exec(t);return r==null?void 0:r.groups}const Vg=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Gg=/^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)?$/,qg=/^\(.+?\).*?$/,fy=/^tuple(?<array>(\[(\d*)\])*)$/;function jd(e){let t=e.type;if(fy.test(e.type)&&"components"in e){t="(";const r=e.components.length;for(let i=0;i<r;i++){const s=e.components[i];t+=jd(s),i<r-1&&(t+=", ")}const n=Gn(fy,e.type);return t+=`)${(n==null?void 0:n.array)||""}`,jd({...e,type:t})}return"indexed"in e&&e.indexed&&(t=`${t} indexed`),e.name?`${t} ${e.name}`:t}function Ns(e){let t="";const r=e.length;for(let n=0;n<r;n++){const i=e[n];t+=jd(i),n!==r-1&&(t+=", ")}return t}function su(e){var t;return e.type==="function"?`function ${e.name}(${Ns(e.inputs)})${e.stateMutability&&e.stateMutability!=="nonpayable"?` ${e.stateMutability}`:""}${(t=e.outputs)!=null&&t.length?` returns (${Ns(e.outputs)})`:""}`:e.type==="event"?`event ${e.name}(${Ns(e.inputs)})`:e.type==="error"?`error ${e.name}(${Ns(e.inputs)})`:e.type==="constructor"?`constructor(${Ns(e.inputs)})${e.stateMutability==="payable"?" payable":""}`:e.type==="fallback"?`fallback() external${e.stateMutability==="payable"?" payable":""}`:"receive() external payable"}const Wg=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function Tx(e){return Wg.test(e)}function Ix(e){return Gn(Wg,e)}const Kg=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function _x(e){return Kg.test(e)}function Px(e){return Gn(Kg,e)}const Xg=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function Ox(e){return Xg.test(e)}function Bx(e){return Gn(Xg,e)}const Jg=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function Fu(e){return Jg.test(e)}function Cx(e){return Gn(Jg,e)}const Yg=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function Rx(e){return Yg.test(e)}function Nx(e){return Gn(Yg,e)}const Zg=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function Ux(e){return Zg.test(e)}function Fx(e){return Gn(Zg,e)}const $x=/^receive\(\) external payable$/;function Mx(e){return $x.test(e)}const ly=new Set(["memory","indexed","storage","calldata"]),jx=new Set(["indexed"]),Hd=new Set(["calldata","memory","storage"]);class Hx extends tr{constructor({signature:t}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}}class Lx extends tr{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" 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 Dx extends tr{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}}class zx extends tr{constructor({params:t}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"})}}class Vx extends tr{constructor({param:t}){super("Invalid ABI parameter.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}}class Gx extends tr{constructor({param:t,name:r}){super("Invalid ABI parameter.",{details:t,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 qx extends tr{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}}class Wx extends tr{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,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 Kx extends tr{constructor({abiParameter:t}){super("Invalid ABI parameter.",{details:JSON.stringify(t,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}}class ca extends tr{constructor({signature:t,type:r}){super(`Invalid ${r} signature.`,{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}}class Xx extends tr{constructor({signature:t}){super("Unknown signature.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}}class Jx extends tr{constructor({signature:t}){super("Invalid struct signature.",{details:t,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}}class Yx extends tr{constructor({type:t}){super("Circular reference detected.",{metaMessages:[`Struct "${t}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}}class Zx extends tr{constructor({current:t,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${t.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 Qx(e,t,r){let n="";if(r)for(const i of Object.entries(r)){if(!i)continue;let s="";for(const a of i[1])s+=`[${a.type}${a.name?`:${a.name}`:""}]`;n+=`(${i[0]}{${s}})`}return t?`${t}:${e}${n}`:`${e}${n}`}const Lf=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 Ld(e,t={}){if(Ox(e))return e8(e,t);if(_x(e))return t8(e,t);if(Tx(e))return r8(e,t);if(Rx(e))return n8(e,t);if(Ux(e))return i8(e);if(Mx(e))return{type:"receive",stateMutability:"payable"};throw new Xx({signature:e})}function e8(e,t={}){const r=Bx(e);if(!r)throw new ca({signature:e,type:"function"});const n=ir(r.parameters),i=[],s=n.length;for(let o=0;o<s;o++)i.push(Ln(n[o],{modifiers:Hd,structs:t,type:"function"}));const a=[];if(r.returns){const o=ir(r.returns),c=o.length;for(let u=0;u<c;u++)a.push(Ln(o[u],{modifiers:Hd,structs:t,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:i,outputs:a}}function t8(e,t={}){const r=Px(e);if(!r)throw new ca({signature:e,type:"event"});const n=ir(r.parameters),i=[],s=n.length;for(let a=0;a<s;a++)i.push(Ln(n[a],{modifiers:jx,structs:t,type:"event"}));return{name:r.name,type:"event",inputs:i}}function r8(e,t={}){const r=Ix(e);if(!r)throw new ca({signature:e,type:"error"});const n=ir(r.parameters),i=[],s=n.length;for(let a=0;a<s;a++)i.push(Ln(n[a],{structs:t,type:"error"}));return{name:r.name,type:"error",inputs:i}}function n8(e,t={}){const r=Nx(e);if(!r)throw new ca({signature:e,type:"constructor"});const n=ir(r.parameters),i=[],s=n.length;for(let a=0;a<s;a++)i.push(Ln(n[a],{structs:t,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:i}}function i8(e){const t=Fx(e);if(!t)throw new ca({signature:e,type:"fallback"});return{type:"fallback",stateMutability:t.stateMutability??"nonpayable"}}const s8=/^(?<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$_]*))?$/,a8=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,o8=/^u?int$/;function Ln(e,t){var l,h;const r=Qx(e,t==null?void 0:t.type,t==null?void 0:t.structs);if(Lf.has(r))return Lf.get(r);const n=qg.test(e),i=Gn(n?a8:s8,e);if(!i)throw new Vx({param:e});if(i.name&&u8(i.name))throw new Gx({param:e,name:i.name});const s=i.name?{name:i.name}:{},a=i.modifier==="indexed"?{indexed:!0}:{},o=(t==null?void 0:t.structs)??{};let c,u={};if(n){c="tuple";const d=ir(i.type),b=[],g=d.length;for(let x=0;x<g;x++)b.push(Ln(d[x],{structs:o}));u={components:b}}else if(i.type in o)c="tuple",u={components:o[i.type]};else if(o8.test(i.type))c=`${i.type}256`;else if(i.type==="address payable")c="address";else if(c=i.type,(t==null?void 0:t.type)!=="struct"&&!Qg(c))throw new Dx({type:c});if(i.modifier){if(!((h=(l=t==null?void 0:t.modifiers)==null?void 0:l.has)!=null&&h.call(l,i.modifier)))throw new qx({param:e,type:t==null?void 0:t.type,modifier:i.modifier});if(Hd.has(i.modifier)&&!f8(c,!!i.array))throw new Wx({param:e,type:t==null?void 0:t.type,modifier:i.modifier})}const f={type:`${c}${i.array??""}`,...s,...a,...u};return Lf.set(r,f),f}function ir(e,t=[],r="",n=0){const i=e.trim().length;for(let s=0;s<i;s++){const a=e[s],o=e.slice(s+1);switch(a){case",":return n===0?ir(o,[...t,r.trim()]):ir(o,t,`${r}${a}`,n);case"(":return ir(o,t,`${r}${a}`,n+1);case")":return ir(o,t,`${r}${a}`,n-1);default:return ir(o,t,`${r}${a}`,n)}}if(r==="")return t;if(n!==0)throw new Zx({current:r,depth:n});return t.push(r.trim()),t}function Qg(e){return e==="address"||e==="bool"||e==="function"||e==="string"||Vg.test(e)||Gg.test(e)}const c8=/^(?: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 u8(e){return e==="address"||e==="bool"||e==="function"||e==="string"||e==="tuple"||Vg.test(e)||Gg.test(e)||c8.test(e)}function f8(e,t){return t||e==="bytes"||e==="string"||e==="tuple"}function n0(e){const t={},r=e.length;for(let a=0;a<r;a++){const o=e[a];if(!Fu(o))continue;const c=Cx(o);if(!c)throw new ca({signature:o,type:"struct"});const u=c.properties.split(";"),f=[],l=u.length;for(let h=0;h<l;h++){const b=u[h].trim();if(!b)continue;const g=Ln(b,{type:"struct"});f.push(g)}if(!f.length)throw new Jx({signature:o});t[c.name]=f}const n={},i=Object.entries(t),s=i.length;for(let a=0;a<s;a++){const[o,c]=i[a];n[o]=e1(c,t)}return n}const l8=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function e1(e=[],t={},r=new Set){const n=[],i=e.length;for(let s=0;s<i;s++){const a=e[s];if(qg.test(a.type))n.push(a);else{const c=Gn(l8,a.type);if(!(c!=null&&c.type))throw new Kx({abiParameter:a});const{array:u,type:f}=c;if(f in t){if(r.has(f))throw new Yx({type:f});n.push({...a,type:`tuple${u??""}`,components:e1(t[f],t,new Set([...r,f]))})}else if(Qg(f))n.push(a);else throw new Lx({type:f})}}return n}function t1(e){const t=n0(e),r=[],n=e.length;for(let i=0;i<n;i++){const s=e[i];Fu(s)||r.push(Ld(s,t))}return r}function dy(e){let t;if(typeof e=="string")t=Ld(e);else{const r=n0(e),n=e.length;for(let i=0;i<n;i++){const s=e[i];if(!Fu(s)){t=Ld(s,r);break}}}if(!t)throw new Hx({signature:e});return t}function hy(e){const t=[];if(typeof e=="string"){const r=ir(e),n=r.length;for(let i=0;i<n;i++)t.push(Ln(r[i],{modifiers:ly}))}else{const r=n0(e),n=e.length;for(let i=0;i<n;i++){const s=e[i];if(Fu(s))continue;const a=ir(s),o=a.length;for(let c=0;c<o;c++)t.push(Ln(a[c],{modifiers:ly,structs:r}))}}if(t.length===0)throw new zx({params:e});return t}function re(e,t,r){const n=e[t.name];if(typeof n=="function")return n;const i=e[r];return typeof i=="function"?i:s=>t(e,s)}function Lr(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new k8(e.type);return`${e.name}(${$u(e.inputs,{includeName:t})})`}function $u(e,{includeName:t=!1}={}){return e?e.map(r=>d8(r,{includeName:t})).join(t?", ":","):""}function d8(e,{includeName:t}){return e.type.startsWith("tuple")?`(${$u(e.components,{includeName:t})})${e.type.slice(5)}`:e.type+(t&&e.name?` ${e.name}`:"")}function Dr(e,{strict:t=!0}={}){return!e||typeof e!="string"?!1:t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}function We(e){return Dr(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}const r1="2.44.4";let Ia={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${r1}`},G=class Dd extends Error{constructor(t,r={}){var o;const n=(()=>{var c;return r.cause instanceof Dd?r.cause.details:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),i=r.cause instanceof Dd&&r.cause.docsPath||r.docsPath,s=(o=Ia.getDocsUrl)==null?void 0:o.call(Ia,{...r,docsPath:i}),a=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...n?[`Details: ${n}`]:[],...Ia.version?[`Version: ${Ia.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=i,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=t,this.version=r1}walk(t){return n1(this,t)}};function n1(e,t){return t!=null&&t(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause!==void 0?n1(e.cause,t):t?null:e}class h8 extends G{constructor({docsPath:t}){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:t,name:"AbiConstructorNotFoundError"})}}class py extends G{constructor({docsPath:t}){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:t,name:"AbiConstructorParamsNotFoundError"})}}class i1 extends G{constructor({data:t,params:r,size:n}){super([`Data size of ${n} bytes is too small for given parameters.`].join(`
|
|
33
|
+
`),{metaMessages:[`Params: (${$u(r,{includeName:!0})})`,`Data: ${t} (${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=t,this.params=r,this.size=n}}class qo extends G{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError"})}}class p8 extends G{constructor({expectedLength:t,givenLength:r,type:n}){super([`ABI encoding array length mismatch for type ${n}.`,`Expected length: ${t}`,`Given length: ${r}`].join(`
|
|
34
|
+
`),{name:"AbiEncodingArrayLengthMismatchError"})}}class y8 extends G{constructor({expectedSize:t,value:r}){super(`Size of bytes "${r}" (bytes${We(r)}) does not match expected size (bytes${t}).`,{name:"AbiEncodingBytesSizeMismatchError"})}}class m8 extends G{constructor({expectedLength:t,givenLength:r}){super(["ABI encoding params/values length mismatch.",`Expected length (params): ${t}`,`Given length (values): ${r}`].join(`
|
|
35
|
+
`),{name:"AbiEncodingLengthMismatchError"})}}class b8 extends G{constructor(t,{docsPath:r}){super([`Arguments (\`args\`) were provided to "${t}", but "${t}" 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 yy extends G{constructor(t,{docsPath:r}={}){super([`Error ${t?`"${t}" `:""}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 s1 extends G{constructor(t,{docsPath:r}){super([`Encoded error signature "${t}" 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=${t}.`].join(`
|
|
38
|
+
`),{docsPath:r,name:"AbiErrorSignatureNotFoundError"}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.signature=t}}class g8 extends G{constructor({docsPath:t}){super("Cannot extract event signature from empty topics.",{docsPath:t,name:"AbiEventSignatureEmptyTopicsError"})}}class w8 extends G{constructor(t,{docsPath:r}){super([`Encoded event signature "${t}" 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=${t}.`].join(`
|
|
39
|
+
`),{docsPath:r,name:"AbiEventSignatureNotFoundError"})}}class my extends G{constructor(t,{docsPath:r}={}){super([`Event ${t?`"${t}" `:""}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 ta extends G{constructor(t,{docsPath:r}={}){super([`Function ${t?`"${t}" `:""}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 a1 extends G{constructor(t,{docsPath:r}){super([`Function "${t}" 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 v8 extends G{constructor(t,{docsPath:r}){super([`Encoded function signature "${t}" 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=${t}.`].join(`
|
|
43
|
+
`),{docsPath:r,name:"AbiFunctionSignatureNotFoundError"})}}class E8 extends G{constructor(t,r){super("Found ambiguous types in overloaded ABI items.",{metaMessages:[`\`${t.type}\` in \`${Lr(t.abiItem)}\`, and`,`\`${r.type}\` in \`${Lr(r.abiItem)}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."],name:"AbiItemAmbiguityError"})}}let x8=class extends G{constructor({expectedSize:t,givenSize:r}){super(`Expected bytes${t}, got bytes${r}.`,{name:"BytesSizeMismatchError"})}};class au extends G{constructor({abiItem:t,data:r,params:n,size:i}){super([`Data size of ${i} bytes is too small for non-indexed event parameters.`].join(`
|
|
44
|
+
`),{metaMessages:[`Params: (${$u(n,{includeName:!0})})`,`Data: ${r} (${i} 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=t,this.data=r,this.params=n,this.size=i}}class i0 extends G{constructor({abiItem:t,param:r}){super([`Expected a topic for indexed event parameter${r.name?` "${r.name}"`:""} on event "${Lr(t,{includeName:!0})}".`].join(`
|
|
45
|
+
`),{name:"DecodeLogTopicsMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=t}}class A8 extends G{constructor(t,{docsPath:r}){super([`Type "${t}" is not a valid encoding type.`,"Please provide a valid ABI type."].join(`
|
|
46
|
+
`),{docsPath:r,name:"InvalidAbiEncodingType"})}}class S8 extends G{constructor(t,{docsPath:r}){super([`Type "${t}" is not a valid decoding type.`,"Please provide a valid ABI type."].join(`
|
|
47
|
+
`),{docsPath:r,name:"InvalidAbiDecodingType"})}}let o1=class extends G{constructor(t){super([`Value "${t}" is not a valid array.`].join(`
|
|
48
|
+
`),{name:"InvalidArrayError"})}};class k8 extends G{constructor(t){super([`"${t}" is not a valid definition type.`,'Valid types: "function", "event", "error"'].join(`
|
|
49
|
+
`),{name:"InvalidDefinitionTypeError"})}}class T8 extends G{constructor(t){super(`Filter type "${t}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}let c1=class extends G{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${t}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}},u1=class extends G{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${t}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}};class by extends G{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} is expected to be ${r} ${n} long, but is ${t} ${n} long.`,{name:"InvalidBytesLengthError"})}}function ua(e,{dir:t,size:r=32}={}){return typeof e=="string"?Ai(e,{dir:t,size:r}):I8(e,{dir:t,size:r})}function Ai(e,{dir:t,size:r=32}={}){if(r===null)return e;const n=e.replace("0x","");if(n.length>r*2)throw new u1({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[t==="right"?"padEnd":"padStart"](r*2,"0")}`}function I8(e,{dir:t,size:r=32}={}){if(r===null)return e;if(e.length>r)throw new u1({size:e.length,targetSize:r,type:"bytes"});const n=new Uint8Array(r);for(let i=0;i<r;i++){const s=t==="right";n[s?i:r-i-1]=e[s?i:e.length-i-1]}return n}let s0=class extends G{constructor({max:t,min:r,signed:n,size:i,value:s}){super(`Number "${s}" is not in safe ${i?`${i*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${t?`(${r} to ${t})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}},_8=class extends G{constructor(t){super(`Bytes value "${t}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}};class P8 extends G{constructor(t){super(`Hex value "${t}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`,{name:"InvalidHexBooleanError"})}}let O8=class extends G{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${t} bytes.`,{name:"SizeOverflowError"})}};function Ar(e,{dir:t="left"}={}){let r=typeof e=="string"?e.replace("0x",""):e,n=0;for(let i=0;i<r.length-1&&r[t==="left"?i:r.length-i-1].toString()==="0";i++)n++;return r=t==="left"?r.slice(n):r.slice(0,r.length-n),typeof e=="string"?(r.length===1&&t==="right"&&(r=`${r}0`),`0x${r.length%2===1?`0${r}`:r}`):r}function qr(e,{size:t}){if(We(e)>t)throw new O8({givenSize:We(e),maxSize:t})}function mt(e,t={}){const{signed:r}=t;t.size&&qr(e,{size:t.size});const n=BigInt(e);if(!r)return n;const i=(e.length-2)/2,s=(1n<<BigInt(i)*8n-1n)-1n;return n<=s?n:n-BigInt(`0x${"f".padStart(i*2,"f")}`)-1n}function B8(e,t={}){let r=e;if(t.size&&(qr(r,{size:t.size}),r=Ar(r)),Ar(r)==="0x00")return!1;if(Ar(r)==="0x01")return!0;throw new P8(r)}function Sr(e,t={}){const r=mt(e,t),n=Number(r);if(!Number.isSafeInteger(n))throw new s0({max:`${Number.MAX_SAFE_INTEGER}`,min:`${Number.MIN_SAFE_INTEGER}`,signed:t.signed,size:t.size,value:`${r}n`});return n}const C8=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function zt(e,t={}){return typeof e=="number"||typeof e=="bigint"?J(e,t):typeof e=="string"?ra(e,t):typeof e=="boolean"?f1(e,t):ot(e,t)}function f1(e,t={}){const r=`0x${Number(e)}`;return typeof t.size=="number"?(qr(r,{size:t.size}),ua(r,{size:t.size})):r}function ot(e,t={}){let r="";for(let i=0;i<e.length;i++)r+=C8[e[i]];const n=`0x${r}`;return typeof t.size=="number"?(qr(n,{size:t.size}),ua(n,{dir:"right",size:t.size})):n}function J(e,t={}){const{signed:r,size:n}=t,i=BigInt(e);let s;n?r?s=(1n<<BigInt(n)*8n-1n)-1n:s=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const a=typeof s=="bigint"&&r?-s-1n:0;if(s&&i>s||i<a){const c=typeof e=="bigint"?"n":"";throw new s0({max:s?`${s}${c}`:void 0,min:`${a}${c}`,signed:r,size:n,value:`${e}${c}`})}const o=`0x${(r&&i<0?(1n<<BigInt(n*8))+BigInt(i):i).toString(16)}`;return n?ua(o,{size:n}):o}const R8=new TextEncoder;function ra(e,t={}){const r=R8.encode(e);return ot(r,t)}const N8=new TextEncoder;function fa(e,t={}){return typeof e=="number"||typeof e=="bigint"?F8(e,t):typeof e=="boolean"?U8(e,t):Dr(e)?hn(e,t):es(e,t)}function U8(e,t={}){const r=new Uint8Array(1);return r[0]=Number(e),typeof t.size=="number"?(qr(r,{size:t.size}),ua(r,{size:t.size})):r}const xn={zero:48,nine:57,A:65,F:70,a:97,f:102};function gy(e){if(e>=xn.zero&&e<=xn.nine)return e-xn.zero;if(e>=xn.A&&e<=xn.F)return e-(xn.A-10);if(e>=xn.a&&e<=xn.f)return e-(xn.a-10)}function hn(e,t={}){let r=e;t.size&&(qr(r,{size:t.size}),r=ua(r,{dir:"right",size:t.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);const i=n.length/2,s=new Uint8Array(i);for(let a=0,o=0;a<i;a++){const c=gy(n.charCodeAt(o++)),u=gy(n.charCodeAt(o++));if(c===void 0||u===void 0)throw new G(`Invalid byte sequence ("${n[o-2]}${n[o-1]}" in "${n}").`);s[a]=c*16+u}return s}function F8(e,t){const r=J(e,t);return hn(r)}function es(e,t={}){const r=N8.encode(e);return typeof t.size=="number"?(qr(r,{size:t.size}),ua(r,{dir:"right",size:t.size})):r}const Ic=BigInt(2**32-1),wy=BigInt(32);function l1(e,t=!1){return t?{h:Number(e&Ic),l:Number(e>>wy&Ic)}:{h:Number(e>>wy&Ic)|0,l:Number(e&Ic)|0}}function d1(e,t=!1){const r=e.length;let n=new Uint32Array(r),i=new Uint32Array(r);for(let s=0;s<r;s++){const{h:a,l:o}=l1(e[s],t);[n[s],i[s]]=[a,o]}return[n,i]}const vy=(e,t,r)=>e>>>r,Ey=(e,t,r)=>e<<32-r|t>>>r,li=(e,t,r)=>e>>>r|t<<32-r,di=(e,t,r)=>e<<32-r|t>>>r,Ma=(e,t,r)=>e<<64-r|t>>>r-32,ja=(e,t,r)=>e>>>r-32|t<<64-r,$8=(e,t)=>t,M8=(e,t)=>e,j8=(e,t,r)=>e<<r|t>>>32-r,H8=(e,t,r)=>t<<r|e>>>32-r,L8=(e,t,r)=>t<<r-32|e>>>64-r,D8=(e,t,r)=>e<<r-32|t>>>64-r;function Ir(e,t,r,n){const i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}const a0=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),o0=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,z8=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),V8=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,G8=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),q8=(e,t,r,n,i,s)=>t+r+n+i+s+(e/2**32|0)|0,Is=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function W8(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function ki(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Ti(e,...t){if(!W8(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function K8(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ki(e.outputLen),ki(e.blockLen)}function Ii(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function c0(e,t){Ti(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function so(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function zr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Df(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function en(e,t){return e<<32-t|e>>>t}const h1=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function p1(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const Pn=h1?e=>e:e=>p1(e);function X8(e){for(let t=0;t<e.length;t++)e[t]=p1(e[t]);return e}const hi=h1?e=>e:X8;function J8(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function $n(e){return typeof e=="string"&&(e=J8(e)),Ti(e),e}function Y8(...e){let t=0;for(let n=0;n<e.length;n++){const i=e[n];Ti(i),t+=i.length}const r=new Uint8Array(t);for(let n=0,i=0;n<e.length;n++){const s=e[n];r.set(s,i),i+=s.length}return r}class Mu{}function ju(e){const t=n=>e().update($n(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Z8(e){const t=(n,i)=>e(i).update($n(n)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}function Q8(e=32){if(Is&&typeof Is.getRandomValues=="function")return Is.getRandomValues(new Uint8Array(e));if(Is&&typeof Is.randomBytes=="function")return Uint8Array.from(Is.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}const eA=BigInt(0),_a=BigInt(1),tA=BigInt(2),rA=BigInt(7),nA=BigInt(256),iA=BigInt(113),y1=[],m1=[],b1=[];for(let e=0,t=_a,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],y1.push(2*(5*n+r)),m1.push((e+1)*(e+2)/2%64);let i=eA;for(let s=0;s<7;s++)t=(t<<_a^(t>>rA)*iA)%nA,t&tA&&(i^=_a<<(_a<<BigInt(s))-_a);b1.push(i)}const g1=d1(b1,!0),sA=g1[0],aA=g1[1],xy=(e,t,r)=>r>32?L8(e,t,r):j8(e,t,r),Ay=(e,t,r)=>r>32?D8(e,t,r):H8(e,t,r);function oA(e,t=24){const r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let a=0;a<10;a++)r[a]=e[a]^e[a+10]^e[a+20]^e[a+30]^e[a+40];for(let a=0;a<10;a+=2){const o=(a+8)%10,c=(a+2)%10,u=r[c],f=r[c+1],l=xy(u,f,1)^r[o],h=Ay(u,f,1)^r[o+1];for(let d=0;d<50;d+=10)e[a+d]^=l,e[a+d+1]^=h}let i=e[2],s=e[3];for(let a=0;a<24;a++){const o=m1[a],c=xy(i,s,o),u=Ay(i,s,o),f=y1[a];i=e[f],s=e[f+1],e[f]=c,e[f+1]=u}for(let a=0;a<50;a+=10){for(let o=0;o<10;o++)r[o]=e[a+o];for(let o=0;o<10;o++)e[a+o]^=~r[(o+2)%10]&r[(o+4)%10]}e[0]^=sA[n],e[1]^=aA[n]}zr(r)}class u0 extends Mu{constructor(t,r,n,i=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=s,ki(n),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=so(this.state)}clone(){return this._cloneInto()}keccak(){hi(this.state32),oA(this.state32,this.rounds),hi(this.state32),this.posOut=0,this.pos=0}update(t){Ii(this),t=$n(t),Ti(t);const{blockLen:r,state:n}=this,i=t.length;for(let s=0;s<i;){const a=Math.min(r-this.pos,i-s);for(let o=0;o<a;o++)n[this.pos++]^=t[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:r,pos:n,blockLen:i}=this;t[n]^=r,r&128&&n===i-1&&this.keccak(),t[i-1]^=128,this.keccak()}writeInto(t){Ii(this,!1),Ti(t),this.finish();const r=this.state,{blockLen:n}=this;for(let i=0,s=t.length;i<s;){this.posOut>=n&&this.keccak();const a=Math.min(n-this.posOut,s-i);t.set(r.subarray(this.posOut,this.posOut+a),i),this.posOut+=a,i+=a}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return ki(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(c0(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,zr(this.state)}_cloneInto(t){const{blockLen:r,suffix:n,outputLen:i,rounds:s,enableXOF:a}=this;return t||(t=new u0(r,n,i,a,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=n,t.outputLen=i,t.enableXOF=a,t.destroyed=this.destroyed,t}}const cA=(e,t,r)=>ju(()=>new u0(t,e,r)),w1=cA(1,136,256/8);function At(e,t){const r=t||"hex",n=w1(Dr(e,{strict:!1})?fa(e):e);return r==="bytes"?n:zt(n)}const uA=e=>At(fa(e));function fA(e){return uA(e)}function lA(e){let t=!0,r="",n=0,i="",s=!1;for(let a=0;a<e.length;a++){const o=e[a];if(["(",")",","].includes(o)&&(t=!0),o==="("&&n++,o===")"&&n--,!!t){if(n===0){if(o===" "&&["event","function",""].includes(i))i="";else if(i+=o,o===")"){s=!0;break}continue}if(o===" "){e[a-1]!==","&&r!==","&&r!==",("&&(r="",t=!1);continue}i+=o,r+=o}}if(!s)throw new G("Unable to normalize signature.");return i}const dA=e=>{const t=typeof e=="string"?e:su(e);return lA(t)};function v1(e){return fA(dA(e))}const Hu=v1;let Gt=class extends G{constructor({address:t}){super(`Address "${t}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}},la=class extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){const r=super.get(t);return super.has(t)&&r!==void 0&&(this.delete(t),super.set(t,r)),r}set(t,r){if(super.set(t,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}};const zf=new la(8192);function Wo(e,t){if(zf.has(`${e}.${t}`))return zf.get(`${e}.${t}`);const r=e.substring(2).toLowerCase(),n=At(es(r),"bytes"),i=r.split("");for(let a=0;a<40;a+=2)n[a>>1]>>4>=8&&i[a]&&(i[a]=i[a].toUpperCase()),(n[a>>1]&15)>=8&&i[a+1]&&(i[a+1]=i[a+1].toUpperCase());const s=`0x${i.join("")}`;return zf.set(`${e}.${t}`,s),s}function f0(e,t){if(!pt(e,{strict:!1}))throw new Gt({address:e});return Wo(e,t)}const hA=/^0x[a-fA-F0-9]{40}$/,Vf=new la(8192);function pt(e,t){const{strict:r=!0}=t??{},n=`${e}.${r}`;if(Vf.has(n))return Vf.get(n);const i=hA.test(e)?e.toLowerCase()===e?!0:r?Wo(e)===e:!0:!1;return Vf.set(n,i),i}function lr(e){return typeof e[0]=="string"?Wr(e):pA(e)}function pA(e){let t=0;for(const i of e)t+=i.length;const r=new Uint8Array(t);let n=0;for(const i of e)r.set(i,n),n+=i.length;return r}function Wr(e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function os(e,t,r,{strict:n}={}){return Dr(e,{strict:!1})?zd(e,t,r,{strict:n}):A1(e,t,r,{strict:n})}function E1(e,t){if(typeof t=="number"&&t>0&&t>We(e)-1)throw new c1({offset:t,position:"start",size:We(e)})}function x1(e,t,r){if(typeof t=="number"&&typeof r=="number"&&We(e)!==r-t)throw new c1({offset:r,position:"end",size:We(e)})}function A1(e,t,r,{strict:n}={}){E1(e,t);const i=e.slice(t,r);return n&&x1(i,t,r),i}function zd(e,t,r,{strict:n}={}){E1(e,t);const i=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;return n&&x1(i,t,r),i}const yA=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,S1=/^(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 Ci(e,t){if(e.length!==t.length)throw new m8({expectedLength:e.length,givenLength:t.length});const r=mA({params:e,values:t}),n=d0(r);return n.length===0?"0x":n}function mA({params:e,values:t}){const r=[];for(let n=0;n<e.length;n++)r.push(l0({param:e[n],value:t[n]}));return r}function l0({param:e,value:t}){const r=h0(e.type);if(r){const[n,i]=r;return gA(t,{length:n,param:{...e,type:i}})}if(e.type==="tuple")return AA(t,{param:e});if(e.type==="address")return bA(t);if(e.type==="bool")return vA(t);if(e.type.startsWith("uint")||e.type.startsWith("int")){const n=e.type.startsWith("int"),[,,i="256"]=S1.exec(e.type)??[];return EA(t,{signed:n,size:Number(i)})}if(e.type.startsWith("bytes"))return wA(t,{param:e});if(e.type==="string")return xA(t);throw new A8(e.type,{docsPath:"/docs/contract/encodeAbiParameters"})}function d0(e){let t=0;for(let s=0;s<e.length;s++){const{dynamic:a,encoded:o}=e[s];a?t+=32:t+=We(o)}const r=[],n=[];let i=0;for(let s=0;s<e.length;s++){const{dynamic:a,encoded:o}=e[s];a?(r.push(J(t+i,{size:32})),n.push(o),i+=We(o)):r.push(o)}return lr([...r,...n])}function bA(e){if(!pt(e))throw new Gt({address:e});return{dynamic:!1,encoded:Ai(e.toLowerCase())}}function gA(e,{length:t,param:r}){const n=t===null;if(!Array.isArray(e))throw new o1(e);if(!n&&e.length!==t)throw new p8({expectedLength:t,givenLength:e.length,type:`${r.type}[${t}]`});let i=!1;const s=[];for(let a=0;a<e.length;a++){const o=l0({param:r,value:e[a]});o.dynamic&&(i=!0),s.push(o)}if(n||i){const a=d0(s);if(n){const o=J(s.length,{size:32});return{dynamic:!0,encoded:s.length>0?lr([o,a]):o}}if(i)return{dynamic:!0,encoded:a}}return{dynamic:!1,encoded:lr(s.map(({encoded:a})=>a))}}function wA(e,{param:t}){const[,r]=t.type.split("bytes"),n=We(e);if(!r){let i=e;return n%32!==0&&(i=Ai(i,{dir:"right",size:Math.ceil((e.length-2)/2/32)*32})),{dynamic:!0,encoded:lr([Ai(J(n,{size:32})),i])}}if(n!==Number.parseInt(r,10))throw new y8({expectedSize:Number.parseInt(r,10),value:e});return{dynamic:!1,encoded:Ai(e,{dir:"right"})}}function vA(e){if(typeof e!="boolean")throw new G(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Ai(f1(e))}}function EA(e,{signed:t,size:r=256}){if(typeof r=="number"){const n=2n**(BigInt(r)-(t?1n:0n))-1n,i=t?-n-1n:0n;if(e>n||e<i)throw new s0({max:n.toString(),min:i.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:J(e,{size:32,signed:t})}}function xA(e){const t=ra(e),r=Math.ceil(We(t)/32),n=[];for(let i=0;i<r;i++)n.push(Ai(os(t,i*32,(i+1)*32),{dir:"right"}));return{dynamic:!0,encoded:lr([Ai(J(We(t),{size:32})),...n])}}function AA(e,{param:t}){let r=!1;const n=[];for(let i=0;i<t.components.length;i++){const s=t.components[i],a=Array.isArray(e)?i:s.name,o=l0({param:s,value:e[a]});n.push(o),o.dynamic&&(r=!0)}return{dynamic:r,encoded:r?d0(n):lr(n.map(({encoded:i})=>i))}}function h0(e){const t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}const Ko=e=>os(v1(e),0,4);function vs(e){const{abi:t,args:r=[],name:n}=e,i=Dr(n,{strict:!1}),s=t.filter(o=>i?o.type==="function"?Ko(o)===n:o.type==="event"?Hu(o)===n:!1:"name"in o&&o.name===n);if(s.length===0)return;if(s.length===1)return s[0];let a;for(const o of s){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,f)=>{const l="inputs"in o&&o.inputs[f];return l?Vd(u,l):!1})){if(a&&"inputs"in a&&a.inputs){const u=k1(o.inputs,a.inputs,r);if(u)throw new E8({abiItem:o,type:u[0]},{abiItem:a,type:u[1]})}a=o}}return a||s[0]}function Vd(e,t){const r=typeof e,n=t.type;switch(n){case"address":return pt(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in t?Object.values(t.components).every((i,s)=>r==="object"&&Vd(Object.values(e)[s],i)):/^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"||e instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(e)&&e.every(i=>Vd(i,{...t,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function k1(e,t,r){for(const n in e){const i=e[n],s=t[n];if(i.type==="tuple"&&s.type==="tuple"&&"components"in i&&"components"in s)return k1(i.components,s.components,r[n]);const a=[i.type,s.type];if(a.includes("address")&&a.includes("bytes20")?!0:a.includes("address")&&a.includes("string")?pt(r[n],{strict:!1}):a.includes("address")&&a.includes("bytes")?pt(r[n],{strict:!1}):!1)return a}}const Sy="/docs/contract/encodeEventTopics";function Xo(e){var c;const{abi:t,eventName:r,args:n}=e;let i=t[0];if(r){const u=vs({abi:t,name:r});if(!u)throw new my(r,{docsPath:Sy});i=u}if(i.type!=="event")throw new my(void 0,{docsPath:Sy});const s=Lr(i),a=Hu(s);let o=[];if(n&&"inputs"in i){const u=(c=i.inputs)==null?void 0:c.filter(l=>"indexed"in l&&l.indexed),f=Array.isArray(n)?n:Object.values(n).length>0?(u==null?void 0:u.map(l=>n[l.name]))??[]:[];f.length>0&&(o=(u==null?void 0:u.map((l,h)=>Array.isArray(f[h])?f[h].map((d,b)=>ky({param:l,value:f[h][b]})):typeof f[h]<"u"&&f[h]!==null?ky({param:l,value:f[h]}):null))??[])}return[a,...o]}function ky({param:e,value:t}){if(e.type==="string"||e.type==="bytes")return At(fa(t));if(e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))throw new T8(e.type);return Ci([e],[t])}function Lu(e,{method:t}){var n,i;const r={};return e.transport.type==="fallback"&&((i=(n=e.transport).onResponse)==null||i.call(n,({method:s,response:a,status:o,transport:c})=>{o==="success"&&t===s&&(r[a]=c.request)})),s=>r[s]||e.request}async function p0(e,t){const{address:r,abi:n,args:i,eventName:s,fromBlock:a,strict:o,toBlock:c}=t,u=Lu(e,{method:"eth_newFilter"}),f=s?Xo({abi:n,args:i,eventName:s}):void 0,l=await e.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof a=="bigint"?J(a):a,toBlock:typeof c=="bigint"?J(c):c,topics:f}]});return{abi:n,args:i,eventName:s,id:l,request:u(l),strict:!!o,type:"event"}}function Me(e){return typeof e=="string"?{address:e,type:"json-rpc"}:e}const Ty="/docs/contract/encodeFunctionData";function SA(e){const{abi:t,args:r,functionName:n}=e;let i=t[0];if(n){const s=vs({abi:t,args:r,name:n});if(!s)throw new ta(n,{docsPath:Ty});i=s}if(i.type!=="function")throw new ta(void 0,{docsPath:Ty});return{abi:[i],functionName:Ko(Lr(i))}}function hr(e){const{args:t}=e,{abi:r,functionName:n}=(()=>{var o;return e.abi.length===1&&((o=e.functionName)!=null&&o.startsWith("0x"))?e:SA(e)})(),i=r[0],s=n,a="inputs"in i&&i.inputs?Ci(i.inputs,t??[]):void 0;return Wr([s,a??"0x"])}const kA={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."},T1={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},TA={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"};let Iy=class extends G{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`,{name:"NegativeOffsetError"})}},I1=class extends G{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`,{name:"PositionOutOfBoundsError"})}},IA=class extends G{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`,{name:"RecursiveReadLimitExceededError"})}};const _A={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 IA({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new I1({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new Iy({offset:e});const t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new Iy({offset:e});const t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){const r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){const t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){const t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){const t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();const r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();const e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();const e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();const e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();const e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){const t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};function y0(e,{recursiveReadLimit:t=8192}={}){const r=Object.create(_A);return r.bytes=e,r.dataView=new DataView(e.buffer??e,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}function PA(e,t={}){typeof t.size<"u"&&qr(e,{size:t.size});const r=ot(e,t);return mt(r,t)}function OA(e,t={}){let r=e;if(typeof t.size<"u"&&(qr(r,{size:t.size}),r=Ar(r)),r.length>1||r[0]>1)throw new _8(r);return!!r[0]}function Mn(e,t={}){typeof t.size<"u"&&qr(e,{size:t.size});const r=ot(e,t);return Sr(r,t)}function BA(e,t={}){let r=e;return typeof t.size<"u"&&(qr(r,{size:t.size}),r=Ar(r,{dir:"right"})),new TextDecoder().decode(r)}function Jo(e,t){const r=typeof t=="string"?hn(t):t,n=y0(r);if(We(r)===0&&e.length>0)throw new qo;if(We(t)&&We(t)<32)throw new i1({data:typeof t=="string"?t:ot(t),params:e,size:We(t)});let i=0;const s=[];for(let a=0;a<e.length;++a){const o=e[a];n.setPosition(i);const[c,u]=Vs(n,o,{staticPosition:0});i+=u,s.push(c)}return s}function Vs(e,t,{staticPosition:r}){const n=h0(t.type);if(n){const[i,s]=n;return RA(e,{...t,type:s},{length:i,staticPosition:r})}if(t.type==="tuple")return $A(e,t,{staticPosition:r});if(t.type==="address")return CA(e);if(t.type==="bool")return NA(e);if(t.type.startsWith("bytes"))return UA(e,t,{staticPosition:r});if(t.type.startsWith("uint")||t.type.startsWith("int"))return FA(e,t);if(t.type==="string")return MA(e,{staticPosition:r});throw new S8(t.type,{docsPath:"/docs/contract/decodeAbiParameters"})}const _y=32,Gd=32;function CA(e){const t=e.readBytes(32);return[Wo(ot(A1(t,-20))),32]}function RA(e,t,{length:r,staticPosition:n}){if(!r){const a=Mn(e.readBytes(Gd)),o=n+a,c=o+_y;e.setPosition(o);const u=Mn(e.readBytes(_y)),f=ao(t);let l=0;const h=[];for(let d=0;d<u;++d){e.setPosition(c+(f?d*32:l));const[b,g]=Vs(e,t,{staticPosition:c});l+=g,h.push(b)}return e.setPosition(n+32),[h,32]}if(ao(t)){const a=Mn(e.readBytes(Gd)),o=n+a,c=[];for(let u=0;u<r;++u){e.setPosition(o+u*32);const[f]=Vs(e,t,{staticPosition:o});c.push(f)}return e.setPosition(n+32),[c,32]}let i=0;const s=[];for(let a=0;a<r;++a){const[o,c]=Vs(e,t,{staticPosition:n+i});i+=c,s.push(o)}return[s,i]}function NA(e){return[OA(e.readBytes(32),{size:32}),32]}function UA(e,t,{staticPosition:r}){const[n,i]=t.type.split("bytes");if(!i){const a=Mn(e.readBytes(32));e.setPosition(r+a);const o=Mn(e.readBytes(32));if(o===0)return e.setPosition(r+32),["0x",32];const c=e.readBytes(o);return e.setPosition(r+32),[ot(c),32]}return[ot(e.readBytes(Number.parseInt(i,10),32)),32]}function FA(e,t){const r=t.type.startsWith("int"),n=Number.parseInt(t.type.split("int")[1]||"256",10),i=e.readBytes(32);return[n>48?PA(i,{signed:r}):Mn(i,{signed:r}),32]}function $A(e,t,{staticPosition:r}){const n=t.components.length===0||t.components.some(({name:a})=>!a),i=n?[]:{};let s=0;if(ao(t)){const a=Mn(e.readBytes(Gd)),o=r+a;for(let c=0;c<t.components.length;++c){const u=t.components[c];e.setPosition(o+s);const[f,l]=Vs(e,u,{staticPosition:o});s+=l,i[n?c:u==null?void 0:u.name]=f}return e.setPosition(r+32),[i,32]}for(let a=0;a<t.components.length;++a){const o=t.components[a],[c,u]=Vs(e,o,{staticPosition:r});i[n?a:o==null?void 0:o.name]=c,s+=u}return[i,s]}function MA(e,{staticPosition:t}){const r=Mn(e.readBytes(32)),n=t+r;e.setPosition(n);const i=Mn(e.readBytes(32));if(i===0)return e.setPosition(t+32),["",32];const s=e.readBytes(i,32),a=BA(Ar(s));return e.setPosition(t+32),[a,32]}function ao(e){var n;const{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return(n=e.components)==null?void 0:n.some(ao);const r=h0(e.type);return!!(r&&ao({...e,type:r[1]}))}function _1(e){const{abi:t,data:r}=e,n=os(r,0,4);if(n==="0x")throw new qo;const s=[...t||[],T1,TA].find(a=>a.type==="error"&&n===Ko(Lr(a)));if(!s)throw new s1(n,{docsPath:"/docs/contract/decodeErrorResult"});return{abiItem:s,args:"inputs"in s&&s.inputs&&s.inputs.length>0?Jo(s.inputs,os(r,4)):void 0,errorName:s.name}}const at=(e,t,r)=>JSON.stringify(e,(n,i)=>typeof i=="bigint"?i.toString():i,r);function P1({abiItem:e,args:t,includeFunctionName:r=!0,includeName:n=!1}){if("name"in e&&"inputs"in e&&e.inputs)return`${r?e.name:""}(${e.inputs.map((i,s)=>`${n&&i.name?`${i.name}: `:""}${typeof t[s]=="object"?at(t[s]):t[s]}`).join(", ")})`}const jA={gwei:9,wei:18},HA={ether:-9,wei:9};function O1(e,t){let r=e.toString();const n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(t,"0");let[i,s]=[r.slice(0,r.length-t),r.slice(r.length-t)];return s=s.replace(/(0+)$/,""),`${n?"-":""}${i||"0"}${s?`.${s}`:""}`}function m0(e,t="wei"){return O1(e,jA[t])}function Zt(e,t="wei"){return O1(e,HA[t])}class LA extends G{constructor({address:t}){super(`State for account "${t}" is set multiple times.`,{name:"AccountStateConflictError"})}}class DA extends G{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}function Py(e){return e.reduce((t,{slot:r,value:n})=>`${t} ${r}: ${n}
|
|
50
|
+
`,"")}function zA(e){return e.reduce((t,{address:r,...n})=>{let i=`${t} ${r}:
|
|
51
|
+
`;return n.nonce&&(i+=` nonce: ${n.nonce}
|
|
52
|
+
`),n.balance&&(i+=` balance: ${n.balance}
|
|
53
|
+
`),n.code&&(i+=` code: ${n.code}
|
|
54
|
+
`),n.state&&(i+=` state:
|
|
55
|
+
`,i+=Py(n.state)),n.stateDiff&&(i+=` stateDiff:
|
|
56
|
+
`,i+=Py(n.stateDiff)),i},` State Override:
|
|
57
|
+
`).slice(0,-1)}function Yo(e){const t=Object.entries(e).map(([n,i])=>i===void 0||i===!1?null:[n,i]).filter(Boolean),r=t.reduce((n,[i])=>Math.max(n,i.length),0);return t.map(([n,i])=>` ${`${n}:`.padEnd(r+1)} ${i}`).join(`
|
|
58
|
+
`)}class VA extends G{constructor({v:t}){super(`Invalid \`v\` value "${t}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}}class GA extends G{constructor({transaction:t}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",Yo(t),"}","","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"})}}let qA=class extends G{constructor({storageKey:t}){super(`Size for storage key "${t}" is invalid. Expected 32 bytes. Got ${Math.floor((t.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}};class WA extends G{constructor(t,{account:r,docsPath:n,chain:i,data:s,gas:a,gasPrice:o,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:f,to:l,value:h}){var b;const d=Yo({chain:i&&`${i==null?void 0:i.name} (id: ${i==null?void 0:i.id})`,from:r==null?void 0:r.address,to:l,value:typeof h<"u"&&`${m0(h)} ${((b=i==null?void 0:i.nativeCurrency)==null?void 0:b.symbol)||"ETH"}`,data:s,gas:a,gasPrice:typeof o<"u"&&`${Zt(o)} gwei`,maxFeePerGas:typeof c<"u"&&`${Zt(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${Zt(u)} gwei`,nonce:f});super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Request Arguments:",d].filter(Boolean),name:"TransactionExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}}class B1 extends G{constructor({blockHash:t,blockNumber:r,blockTag:n,hash:i,index:s}){let a="Transaction";n&&s!==void 0&&(a=`Transaction at block time "${n}" at index "${s}"`),t&&s!==void 0&&(a=`Transaction at block hash "${t}" at index "${s}"`),r&&s!==void 0&&(a=`Transaction at block number "${r}" at index "${s}"`),i&&(a=`Transaction with hash "${i}"`),super(`${a} could not be found.`,{name:"TransactionNotFoundError"})}}class C1 extends G{constructor({hash:t}){super(`Transaction receipt with hash "${t}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}}class R1 extends G{constructor({receipt:t}){super(`Transaction with hash "${t.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=t}}class KA extends G{constructor({hash:t}){super(`Timed out while waiting for transaction with hash "${t}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}const XA=e=>e,Du=e=>e;class N1 extends G{constructor(t,{account:r,docsPath:n,chain:i,data:s,gas:a,gasPrice:o,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:f,to:l,value:h,stateOverride:d}){var x;const b=r?Me(r):void 0;let g=Yo({from:b==null?void 0:b.address,to:l,value:typeof h<"u"&&`${m0(h)} ${((x=i==null?void 0:i.nativeCurrency)==null?void 0:x.symbol)||"ETH"}`,data:s,gas:a,gasPrice:typeof o<"u"&&`${Zt(o)} gwei`,maxFeePerGas:typeof c<"u"&&`${Zt(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${Zt(u)} gwei`,nonce:f});d&&(g+=`
|
|
59
|
+
${zA(d)}`),super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Raw Call Arguments:",g].filter(Boolean),name:"CallExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}}class U1 extends G{constructor(t,{abi:r,args:n,contractAddress:i,docsPath:s,functionName:a,sender:o}){const c=vs({abi:r,args:n,name:a}),u=c?P1({abiItem:c,args:n,includeFunctionName:!1,includeName:!1}):void 0,f=c?Lr(c,{includeName:!0}):void 0,l=Yo({address:i&&XA(i),function:f,args:u&&u!=="()"&&`${[...Array((a==null?void 0:a.length)??0).keys()].map(()=>" ").join("")}${u}`,sender:o});super(t.shortMessage||`An unknown error occurred while executing the contract function "${a}".`,{cause:t,docsPath:s,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],l&&"Contract Call:",l].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=t,this.contractAddress=i,this.functionName=a,this.sender=o}}class qd extends G{constructor({abi:t,data:r,functionName:n,message:i}){let s,a,o,c;if(r&&r!=="0x")try{a=_1({abi:t,data:r});const{abiItem:f,errorName:l,args:h}=a;if(l==="Error")c=h[0];else if(l==="Panic"){const[d]=h;c=kA[d]}else{const d=f?Lr(f,{includeName:!0}):void 0,b=f&&h?P1({abiItem:f,args:h,includeFunctionName:!1,includeName:!1}):void 0;o=[d?`Error: ${d}`:"",b&&b!=="()"?` ${[...Array((l==null?void 0:l.length)??0).keys()].map(()=>" ").join("")}${b}`:""]}}catch(f){s=f}else i&&(c=i);let u;s instanceof s1&&(u=s.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:s,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 JA extends G{constructor({functionName:t}){super(`The contract function "${t}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${t}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError"})}}class YA extends G{constructor({factory:t}){super(`Deployment for counterfactual contract call failed${t?` for factory "${t}".`:""}`,{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 zu extends G{constructor({data:t,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=t}}class Gs extends G{constructor({body:t,cause:r,details:n,headers:i,status:s,url:a}){super("HTTP request failed.",{cause:r,details:n,metaMessages:[s&&`Status: ${s}`,`URL: ${Du(a)}`,t&&`Request body: ${at(t)}`].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=t,this.headers=i,this.status=s,this.url=a}}class b0 extends G{constructor({body:t,error:r,url:n}){super("RPC Request failed.",{cause:r,details:r.message,metaMessages:[`URL: ${Du(n)}`,`Request body: ${at(t)}`],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 Oy extends G{constructor({body:t,url:r}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${Du(r)}`,`Request body: ${at(t)}`],name:"TimeoutError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=r}}const ZA=-1;class rr extends G{constructor(t,{code:r,docsPath:n,metaMessages:i,name:s,shortMessage:a}){super(a,{cause:t,docsPath:n,metaMessages:i||(t==null?void 0:t.metaMessages),name:s||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=s||t.name,this.code=t instanceof b0?t.code:r??ZA}}class pr extends rr{constructor(t,r){super(t,r),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=r.data}}class oo extends rr{constructor(t){super(t,{code:oo.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(oo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class co extends rr{constructor(t){super(t,{code:co.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(co,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class uo extends rr{constructor(t,{method:r}={}){super(t,{code:uo.code,name:"MethodNotFoundRpcError",shortMessage:`The method${r?` "${r}"`:""} does not exist / is not available.`})}}Object.defineProperty(uo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class fo extends rr{constructor(t){super(t,{code:fo.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
|
|
61
|
+
`)})}}Object.defineProperty(fo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class cs extends rr{constructor(t){super(t,{code:cs.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(cs,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class _i extends rr{constructor(t){super(t,{code:_i.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
|
|
62
|
+
`)})}}Object.defineProperty(_i,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class lo extends rr{constructor(t){super(t,{code:lo.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(lo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class ho extends rr{constructor(t){super(t,{code:ho.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(ho,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class po extends rr{constructor(t){super(t,{code:po.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(po,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class Vi extends rr{constructor(t,{method:r}={}){super(t,{code:Vi.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${r?` "${r}"`:""} is not supported.`})}}Object.defineProperty(Vi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class na extends rr{constructor(t){super(t,{code:na.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(na,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class yo extends rr{constructor(t){super(t,{code:yo.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(yo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class qs extends pr{constructor(t){super(t,{code:qs.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(qs,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class mo extends pr{constructor(t){super(t,{code:mo.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(mo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class bo extends pr{constructor(t,{method:r}={}){super(t,{code:bo.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${r?` " ${r}"`:""}.`})}}Object.defineProperty(bo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class go extends pr{constructor(t){super(t,{code:go.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(go,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class wo extends pr{constructor(t){super(t,{code:wo.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(wo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class vo extends pr{constructor(t){super(t,{code:vo.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(vo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class ia extends pr{constructor(t){super(t,{code:ia.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(ia,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class Eo extends pr{constructor(t){super(t,{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 xo extends pr{constructor(t){super(t,{code:xo.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(xo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class Ao extends pr{constructor(t){super(t,{code:Ao.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(Ao,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class So extends pr{constructor(t){super(t,{code:So.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(So,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class ko extends pr{constructor(t){super(t,{code:ko.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(ko,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class sa extends pr{constructor(t){super(t,{code:sa.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(sa,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class QA extends rr{constructor(t){super(t,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}const e3=3;function us(e,{abi:t,address:r,args:n,docsPath:i,functionName:s,sender:a}){const o=e instanceof zu?e:e instanceof G?e.walk(b=>"data"in b)||e.walk():{},{code:c,data:u,details:f,message:l,shortMessage:h}=o,d=e instanceof qo?new JA({functionName:s}):[e3,cs.code].includes(c)&&(u||f||l||h)||c===_i.code&&f==="execution reverted"&&u?new qd({abi:t,data:typeof u=="object"?u.data:u,functionName:s,message:o instanceof b0?f:h??l}):e;return new U1(d,{abi:t,args:n,contractAddress:r,docsPath:i,functionName:s,sender:a})}function t3(e){const t=At(`0x${e.substring(4)}`).substring(26);return Wo(`0x${t}`)}async function r3({hash:e,signature:t}){const r=Dr(e)?e:zt(e),{secp256k1:n}=await Promise.resolve().then(()=>QT);return`0x${(()=>{if(typeof t=="object"&&"r"in t&&"s"in t){const{r:u,s:f,v:l,yParity:h}=t,d=Number(h??l),b=By(d);return new n.Signature(mt(u),mt(f)).addRecoveryBit(b)}const a=Dr(t)?t:zt(t);if(We(a)!==65)throw new Error("invalid signature length");const o=Sr(`0x${a.slice(130)}`),c=By(o);return n.Signature.fromCompact(a.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function By(e){if(e===0||e===1)return e;if(e===27)return 0;if(e===28)return 1;throw new Error("Invalid yParityOrV value")}async function F1({hash:e,signature:t}){return t3(await r3({hash:e,signature:t}))}function Pi(e,t="hex"){const r=$1(e),n=y0(new Uint8Array(r.length));return r.encode(n),t==="hex"?ot(n.bytes):n.bytes}function $1(e){return Array.isArray(e)?n3(e.map(t=>$1(t))):i3(e)}function n3(e){const t=e.reduce((i,s)=>i+s.length,0),r=M1(t);return{length:t<=55?1+t:1+r+t,encode(i){t<=55?i.pushByte(192+t):(i.pushByte(247+r),r===1?i.pushUint8(t):r===2?i.pushUint16(t):r===3?i.pushUint24(t):i.pushUint32(t));for(const{encode:s}of e)s(i)}}}function i3(e){const t=typeof e=="string"?hn(e):e,r=M1(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length,encode(i){t.length===1&&t[0]<128?i.pushBytes(t):t.length<=55?(i.pushByte(128+t.length),i.pushBytes(t)):(i.pushByte(183+r),r===1?i.pushUint8(t.length):r===2?i.pushUint16(t.length):r===3?i.pushUint24(t.length):i.pushUint32(t.length),i.pushBytes(t))}}}function M1(e){if(e<2**8)return 1;if(e<2**16)return 2;if(e<2**24)return 3;if(e<2**32)return 4;throw new G("Length is too large.")}function s3(e){const{chainId:t,nonce:r,to:n}=e,i=e.contractAddress??e.address,s=At(Wr(["0x05",Pi([t?J(t):"0x",i,r?J(r):"0x"])]));return n==="bytes"?hn(s):s}async function Vu(e){const{authorization:t,signature:r}=e;return F1({hash:s3(t),signature:r??t})}class a3 extends G{constructor(t,{account:r,docsPath:n,chain:i,data:s,gas:a,gasPrice:o,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:f,to:l,value:h}){var b;const d=Yo({from:r==null?void 0:r.address,to:l,value:typeof h<"u"&&`${m0(h)} ${((b=i==null?void 0:i.nativeCurrency)==null?void 0:b.symbol)||"ETH"}`,data:s,gas:a,gasPrice:typeof o<"u"&&`${Zt(o)} gwei`,maxFeePerGas:typeof c<"u"&&`${Zt(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${Zt(u)} gwei`,nonce:f});super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Estimate Gas Arguments:",d].filter(Boolean),name:"EstimateGasExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}}class $s extends G{constructor({cause:t,message:r}={}){var i;const n=(i=r==null?void 0:r.replace("execution reverted: ",""))==null?void 0:i.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:t,name:"ExecutionRevertedError"})}}Object.defineProperty($s,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty($s,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});let fs=class extends G{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${Zt(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:t,name:"FeeCapTooHighError"})}};Object.defineProperty(fs,"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 Wd extends G{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${Zt(r)}`:""} gwei) cannot be lower than the block base fee.`,{cause:t,name:"FeeCapTooLowError"})}}Object.defineProperty(Wd,"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 Kd extends G{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}is higher than the next one expected.`,{cause:t,name:"NonceTooHighError"})}}Object.defineProperty(Kd,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class Xd extends G{constructor({cause:t,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:t,name:"NonceTooLowError"})}}Object.defineProperty(Xd,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class Jd extends G{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}exceeds the maximum allowed nonce.`,{cause:t,name:"NonceMaxValueError"})}}Object.defineProperty(Jd,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});class Yd extends G{constructor({cause:t}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
|
|
64
|
+
`),{cause:t,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(Yd,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class Zd extends G{constructor({cause:t,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:t,name:"IntrinsicGasTooHighError"})}}Object.defineProperty(Zd,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class Qd extends G{constructor({cause:t,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction is too low.`,{cause:t,name:"IntrinsicGasTooLowError"})}}Object.defineProperty(Qd,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class eh extends G{constructor({cause:t}){super("The transaction type is not supported for this chain.",{cause:t,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(eh,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});let To=class extends G{constructor({cause:t,maxPriorityFeePerGas:r,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${r?` = ${Zt(r)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${Zt(n)} gwei`:""}).`].join(`
|
|
65
|
+
`),{cause:t,name:"TipAboveFeeCapError"})}};Object.defineProperty(To,"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 Zo extends G{constructor({cause:t}){super(`An error occurred while executing: ${t==null?void 0:t.shortMessage}`,{cause:t,name:"UnknownNodeError"})}}function Gu(e,t){const r=(e.details||"").toLowerCase(),n=e instanceof G?e.walk(i=>(i==null?void 0:i.code)===$s.code):e;return n instanceof G?new $s({cause:e,message:n.details}):$s.nodeMessage.test(r)?new $s({cause:e,message:e.details}):fs.nodeMessage.test(r)?new fs({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas}):Wd.nodeMessage.test(r)?new Wd({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas}):Kd.nodeMessage.test(r)?new Kd({cause:e,nonce:t==null?void 0:t.nonce}):Xd.nodeMessage.test(r)?new Xd({cause:e,nonce:t==null?void 0:t.nonce}):Jd.nodeMessage.test(r)?new Jd({cause:e,nonce:t==null?void 0:t.nonce}):Yd.nodeMessage.test(r)?new Yd({cause:e}):Zd.nodeMessage.test(r)?new Zd({cause:e,gas:t==null?void 0:t.gas}):Qd.nodeMessage.test(r)?new Qd({cause:e,gas:t==null?void 0:t.gas}):eh.nodeMessage.test(r)?new eh({cause:e}):To.nodeMessage.test(r)?new To({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas,maxPriorityFeePerGas:t==null?void 0:t.maxPriorityFeePerGas}):new Zo({cause:e})}function o3(e,{docsPath:t,...r}){const n=(()=>{const i=Gu(e,r);return i instanceof Zo?e:i})();return new a3(n,{docsPath:t,...r})}function da(e,{format:t}){if(!t)return{};const r={};function n(s){const a=Object.keys(s);for(const o of a)o in e&&(r[o]=e[o]),s[o]&&typeof s[o]=="object"&&!Array.isArray(s[o])&&n(s[o])}const i=t(e||{});return n(i),r}function qu(e,t){return({exclude:r,format:n})=>({exclude:r,format:(i,s)=>{const a=t(i,s);if(r)for(const o of r)delete a[o];return{...a,...n(i,s)}},type:e})}const c3={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function yn(e,t){const r={};return typeof e.authorizationList<"u"&&(r.authorizationList=f3(e.authorizationList)),typeof e.accessList<"u"&&(r.accessList=e.accessList),typeof e.blobVersionedHashes<"u"&&(r.blobVersionedHashes=e.blobVersionedHashes),typeof e.blobs<"u"&&(typeof e.blobs[0]!="string"?r.blobs=e.blobs.map(n=>ot(n)):r.blobs=e.blobs),typeof e.data<"u"&&(r.data=e.data),e.account&&(r.from=e.account.address),typeof e.from<"u"&&(r.from=e.from),typeof e.gas<"u"&&(r.gas=J(e.gas)),typeof e.gasPrice<"u"&&(r.gasPrice=J(e.gasPrice)),typeof e.maxFeePerBlobGas<"u"&&(r.maxFeePerBlobGas=J(e.maxFeePerBlobGas)),typeof e.maxFeePerGas<"u"&&(r.maxFeePerGas=J(e.maxFeePerGas)),typeof e.maxPriorityFeePerGas<"u"&&(r.maxPriorityFeePerGas=J(e.maxPriorityFeePerGas)),typeof e.nonce<"u"&&(r.nonce=J(e.nonce)),typeof e.to<"u"&&(r.to=e.to),typeof e.type<"u"&&(r.type=c3[e.type]),typeof e.value<"u"&&(r.value=J(e.value)),r}const u3=qu("transactionRequest",yn);function f3(e){return e.map(t=>({address:t.address,r:t.r?J(BigInt(t.r)):t.r,s:t.s?J(BigInt(t.s)):t.s,chainId:J(t.chainId),nonce:J(t.nonce),...typeof t.yParity<"u"?{yParity:J(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:J(t.v)}:{}}))}function Cy(e){if(!(!e||e.length===0))return e.reduce((t,{slot:r,value:n})=>{if(r.length!==66)throw new by({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new by({size:n.length,targetSize:66,type:"hex"});return t[r]=n,t},{})}function l3(e){const{balance:t,nonce:r,state:n,stateDiff:i,code:s}=e,a={};if(s!==void 0&&(a.code=s),t!==void 0&&(a.balance=J(t)),r!==void 0&&(a.nonce=J(r)),n!==void 0&&(a.state=Cy(n)),i!==void 0){if(a.state)throw new DA;a.stateDiff=Cy(i)}return a}function g0(e){if(!e)return;const t={};for(const{address:r,...n}of e){if(!pt(r,{strict:!1}))throw new Gt({address:r});if(t[r])throw new LA({address:r});t[r]=l3(n)}return t}const Wu=2n**256n-1n;function qn(e){const{account:t,maxFeePerGas:r,maxPriorityFeePerGas:n,to:i}=e,s=t?Me(t):void 0;if(s&&!pt(s.address))throw new Gt({address:s.address});if(i&&!pt(i))throw new Gt({address:i});if(r&&r>Wu)throw new fs({maxFeePerGas:r});if(n&&r&&n>r)throw new To({maxFeePerGas:r,maxPriorityFeePerGas:n})}class j1 extends G{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class w0 extends G{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class d3 extends G{constructor({maxPriorityFeePerGas:t}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${Zt(t)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class H1 extends G{constructor({blockHash:t,blockNumber:r}){let n="Block";t&&(n=`Block at hash "${t}"`),r&&(n=`Block at number "${r}"`),super(`${n} could not be found.`,{name:"BlockNotFoundError"})}}const L1={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function ha(e,t){const r={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,chainId:e.chainId?Sr(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?Sr(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?L1[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};return e.authorizationList&&(r.authorizationList=h3(e.authorizationList)),r.yParity=(()=>{if(e.yParity)return Number(e.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 D1=qu("transaction",ha);function h3(e){return e.map(t=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}function v0(e,t){const r=(e.transactions??[]).map(n=>typeof n=="string"?n:ha(n));return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:r,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}const p3=qu("block",v0);async function $r(e,{blockHash:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",includeTransactions:i}={}){var u,f,l;const s=i??!1,a=r!==void 0?J(r):void 0;let o=null;if(t?o=await e.request({method:"eth_getBlockByHash",params:[t,s]},{dedupe:!0}):o=await e.request({method:"eth_getBlockByNumber",params:[a||n,s]},{dedupe:!!a}),!o)throw new H1({blockHash:t,blockNumber:r});return(((l=(f=(u=e.chain)==null?void 0:u.formatters)==null?void 0:f.block)==null?void 0:l.format)||v0)(o,"getBlock")}async function E0(e){const t=await e.request({method:"eth_gasPrice"});return BigInt(t)}async function y3(e,t){return z1(e,t)}async function z1(e,t){var s,a;const{block:r,chain:n=e.chain,request:i}=t||{};try{const o=((s=n==null?void 0:n.fees)==null?void 0:s.maxPriorityFeePerGas)??((a=n==null?void 0:n.fees)==null?void 0:a.defaultPriorityFee);if(typeof o=="function"){const u=r||await re(e,$r,"getBlock")({}),f=await o({block:u,client:e,request:i});if(f===null)throw new Error;return f}if(typeof o<"u")return o;const c=await e.request({method:"eth_maxPriorityFeePerGas"});return mt(c)}catch{const[o,c]=await Promise.all([r?Promise.resolve(r):re(e,$r,"getBlock")({}),re(e,E0,"getGasPrice")({})]);if(typeof o.baseFeePerGas!="bigint")throw new w0;const u=c-o.baseFeePerGas;return u<0n?0n:u}}async function m3(e,t){return th(e,t)}async function th(e,t){var h,d;const{block:r,chain:n=e.chain,request:i,type:s="eip1559"}=t||{},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:e,request:i}):((g=n==null?void 0:n.fees)==null?void 0:g.baseFeeMultiplier)??1.2})();if(a<1)throw new j1;const c=10**(((h=a.toString().split(".")[1])==null?void 0:h.length)??0),u=b=>b*BigInt(Math.ceil(a*c))/BigInt(c),f=r||await re(e,$r,"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:e,multiply:u,request:i,type:s});if(b!==null)return b}if(s==="eip1559"){if(typeof f.baseFeePerGas!="bigint")throw new w0;const b=typeof(i==null?void 0:i.maxPriorityFeePerGas)=="bigint"?i.maxPriorityFeePerGas:await z1(e,{block:f,chain:n,request:i}),g=u(f.baseFeePerGas);return{maxFeePerGas:(i==null?void 0:i.maxFeePerGas)??g+b,maxPriorityFeePerGas:b}}return{gasPrice:(i==null?void 0:i.gasPrice)??u(await re(e,E0,"getGasPrice")({}))}}async function x0(e,{address:t,blockTag:r="latest",blockNumber:n}){const i=await e.request({method:"eth_getTransactionCount",params:[t,typeof n=="bigint"?J(n):r]},{dedupe:!!n});return Sr(i)}function A0(e){const{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(s=>hn(s)):e.blobs,i=[];for(const s of n)i.push(Uint8Array.from(t.blobToKzgCommitment(s)));return r==="bytes"?i:i.map(s=>ot(s))}function S0(e){const{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(a=>hn(a)):e.blobs,i=typeof e.commitments[0]=="string"?e.commitments.map(a=>hn(a)):e.commitments,s=[];for(let a=0;a<n.length;a++){const o=n[a],c=i[a];s.push(Uint8Array.from(t.computeBlobKzgProof(o,c)))}return r==="bytes"?s:s.map(a=>ot(a))}function b3(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const i=BigInt(32),s=BigInt(4294967295),a=Number(r>>i&s),o=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,a,n),e.setUint32(t+u,o,n)}function g3(e,t,r){return e&t^~e&r}function w3(e,t,r){return e&t^e&r^t&r}class V1 extends Mu{constructor(t,r,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(t),this.view=Df(this.buffer)}update(t){Ii(this),t=$n(t),Ti(t);const{view:r,buffer:n,blockLen:i}=this,s=t.length;for(let a=0;a<s;){const o=Math.min(i-this.pos,s-a);if(o===i){const c=Df(t);for(;i<=s-a;a+=i)this.process(c,a);continue}n.set(t.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Ii(this),c0(t,this),this.finished=!0;const{buffer:r,view:n,blockLen:i,isLE:s}=this;let{pos:a}=this;r[a++]=128,zr(this.buffer.subarray(a)),this.padOffset>i-a&&(this.process(n,0),a=0);for(let l=a;l<i;l++)r[l]=0;b3(n,i-8,BigInt(this.length*8),s),this.process(n,0);const o=Df(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)o.setUint32(4*l,f[l],s)}digest(){const{buffer:t,outputLen:r}=this;this.digestInto(t);const n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:r,buffer:n,length:i,finished:s,destroyed:a,pos:o}=this;return t.destroyed=a,t.finished=s,t.length=i,t.pos=o,i%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}}const ri=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Tt=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),It=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),v3=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]),ni=new Uint32Array(64);class E3 extends V1{constructor(t=32){super(64,t,8,!1),this.A=ri[0]|0,this.B=ri[1]|0,this.C=ri[2]|0,this.D=ri[3]|0,this.E=ri[4]|0,this.F=ri[5]|0,this.G=ri[6]|0,this.H=ri[7]|0}get(){const{A:t,B:r,C:n,D:i,E:s,F:a,G:o,H:c}=this;return[t,r,n,i,s,a,o,c]}set(t,r,n,i,s,a,o,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=a|0,this.G=o|0,this.H=c|0}process(t,r){for(let l=0;l<16;l++,r+=4)ni[l]=t.getUint32(r,!1);for(let l=16;l<64;l++){const h=ni[l-15],d=ni[l-2],b=en(h,7)^en(h,18)^h>>>3,g=en(d,17)^en(d,19)^d>>>10;ni[l]=g+ni[l-7]+b+ni[l-16]|0}let{A:n,B:i,C:s,D:a,E:o,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){const h=en(o,6)^en(o,11)^en(o,25),d=f+h+g3(o,c,u)+v3[l]+ni[l]|0,g=(en(n,2)^en(n,13)^en(n,22))+w3(n,i,s)|0;f=u,u=c,c=o,o=a+d|0,a=s,s=i,i=n,n=d+g|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,a=a+this.D|0,o=o+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(n,i,s,a,o,c,u,f)}roundClean(){zr(ni)}destroy(){this.set(0,0,0,0,0,0,0,0),zr(this.buffer)}}const G1=d1(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),x3=G1[0],A3=G1[1],ii=new Uint32Array(80),si=new Uint32Array(80);class q1 extends V1{constructor(t=64){super(128,t,16,!1),this.Ah=It[0]|0,this.Al=It[1]|0,this.Bh=It[2]|0,this.Bl=It[3]|0,this.Ch=It[4]|0,this.Cl=It[5]|0,this.Dh=It[6]|0,this.Dl=It[7]|0,this.Eh=It[8]|0,this.El=It[9]|0,this.Fh=It[10]|0,this.Fl=It[11]|0,this.Gh=It[12]|0,this.Gl=It[13]|0,this.Hh=It[14]|0,this.Hl=It[15]|0}get(){const{Ah:t,Al:r,Bh:n,Bl:i,Ch:s,Cl:a,Dh:o,Dl:c,Eh:u,El:f,Fh:l,Fl:h,Gh:d,Gl:b,Hh:g,Hl:x}=this;return[t,r,n,i,s,a,o,c,u,f,l,h,d,b,g,x]}set(t,r,n,i,s,a,o,c,u,f,l,h,d,b,g,x){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=i|0,this.Ch=s|0,this.Cl=a|0,this.Dh=o|0,this.Dl=c|0,this.Eh=u|0,this.El=f|0,this.Fh=l|0,this.Fl=h|0,this.Gh=d|0,this.Gl=b|0,this.Hh=g|0,this.Hl=x|0}process(t,r){for(let w=0;w<16;w++,r+=4)ii[w]=t.getUint32(r),si[w]=t.getUint32(r+=4);for(let w=16;w<80;w++){const v=ii[w-15]|0,S=si[w-15]|0,I=li(v,S,1)^li(v,S,8)^vy(v,S,7),_=di(v,S,1)^di(v,S,8)^Ey(v,S,7),R=ii[w-2]|0,B=si[w-2]|0,M=li(R,B,19)^Ma(R,B,61)^vy(R,B,6),F=di(R,B,19)^ja(R,B,61)^Ey(R,B,6),H=z8(_,F,si[w-7],si[w-16]),z=V8(H,I,M,ii[w-7],ii[w-16]);ii[w]=z|0,si[w]=H|0}let{Ah:n,Al:i,Bh:s,Bl:a,Ch:o,Cl:c,Dh:u,Dl:f,Eh:l,El:h,Fh:d,Fl:b,Gh:g,Gl:x,Hh:A,Hl:k}=this;for(let w=0;w<80;w++){const v=li(l,h,14)^li(l,h,18)^Ma(l,h,41),S=di(l,h,14)^di(l,h,18)^ja(l,h,41),I=l&d^~l&g,_=h&b^~h&x,R=G8(k,S,_,A3[w],si[w]),B=q8(R,A,v,I,x3[w],ii[w]),M=R|0,F=li(n,i,28)^Ma(n,i,34)^Ma(n,i,39),H=di(n,i,28)^ja(n,i,34)^ja(n,i,39),z=n&s^n&o^s&o,Q=i&a^i&c^a&c;A=g|0,k=x|0,g=d|0,x=b|0,d=l|0,b=h|0,{h:l,l:h}=Ir(u|0,f|0,B|0,M|0),u=o|0,f=c|0,o=s|0,c=a|0,s=n|0,a=i|0;const U=a0(M,H,Q);n=o0(U,B,F,z),i=U|0}({h:n,l:i}=Ir(this.Ah|0,this.Al|0,n|0,i|0)),{h:s,l:a}=Ir(this.Bh|0,this.Bl|0,s|0,a|0),{h:o,l:c}=Ir(this.Ch|0,this.Cl|0,o|0,c|0),{h:u,l:f}=Ir(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:h}=Ir(this.Eh|0,this.El|0,l|0,h|0),{h:d,l:b}=Ir(this.Fh|0,this.Fl|0,d|0,b|0),{h:g,l:x}=Ir(this.Gh|0,this.Gl|0,g|0,x|0),{h:A,l:k}=Ir(this.Hh|0,this.Hl|0,A|0,k|0),this.set(n,i,s,a,o,c,u,f,l,h,d,b,g,x,A,k)}roundClean(){zr(ii,si)}destroy(){zr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class S3 extends q1{constructor(){super(48),this.Ah=Tt[0]|0,this.Al=Tt[1]|0,this.Bh=Tt[2]|0,this.Bl=Tt[3]|0,this.Ch=Tt[4]|0,this.Cl=Tt[5]|0,this.Dh=Tt[6]|0,this.Dl=Tt[7]|0,this.Eh=Tt[8]|0,this.El=Tt[9]|0,this.Fh=Tt[10]|0,this.Fl=Tt[11]|0,this.Gh=Tt[12]|0,this.Gl=Tt[13]|0,this.Hh=Tt[14]|0,this.Hl=Tt[15]|0}}const k0=ju(()=>new E3),k3=ju(()=>new q1),T3=ju(()=>new S3),W1=k0;function Ha(e,t){const r=t||"hex",n=W1(Dr(e,{strict:!1})?fa(e):e);return r==="bytes"?n:zt(n)}function I3(e){const{commitment:t,version:r=1}=e,n=e.to??(typeof t=="string"?"hex":"bytes"),i=Ha(t,"bytes");return i.set([r],0),n==="bytes"?i:ot(i)}function K1(e){const{commitments:t,version:r}=e,n=e.to??(typeof t[0]=="string"?"hex":"bytes"),i=[];for(const s of t)i.push(I3({commitment:s,to:n,version:r}));return i}const Ry=6,X1=32,T0=4096,J1=X1*T0,Ny=J1*Ry-1-1*T0*Ry,Y1=1;class _3 extends G{constructor({maxSize:t,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${t} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}}class Z1 extends G{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class P3 extends G{constructor({hash:t,size:r}){super(`Versioned hash "${t}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}}class O3 extends G{constructor({hash:t,version:r}){super(`Versioned hash "${t}" version is invalid.`,{metaMessages:[`Expected: ${Y1}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}function B3(e){const t=e.to??(typeof e.data=="string"?"hex":"bytes"),r=typeof e.data=="string"?hn(e.data):e.data,n=We(r);if(!n)throw new Z1;if(n>Ny)throw new _3({maxSize:Ny,size:n});const i=[];let s=!0,a=0;for(;s;){const o=y0(new Uint8Array(J1));let c=0;for(;c<T0;){const u=r.slice(a,a+(X1-1));if(o.pushByte(0),o.pushBytes(u),u.length<31){o.pushByte(128),s=!1;break}c++,a+=31}i.push(o)}return t==="bytes"?i.map(o=>o.bytes):i.map(o=>ot(o.bytes))}function Q1(e){const{data:t,kzg:r,to:n}=e,i=e.blobs??B3({data:t,to:n}),s=e.commitments??A0({blobs:i,kzg:r,to:n}),a=e.proofs??S0({blobs:i,commitments:s,kzg:r,to:n}),o=[];for(let c=0;c<i.length;c++)o.push({blob:i[c],commitment:s[c],proof:a[c]});return o}function I0(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u")return typeof e.accessList<"u"?"eip2930":"legacy";throw new GA({transaction:e})}function Ku(e,{docsPath:t,...r}){const n=(()=>{const i=Gu(e,r);return i instanceof Zo?e:i})();return new WA(n,{docsPath:t,...r})}async function Ri(e){const t=await e.request({method:"eth_chainId"},{dedupe:!0});return Sr(t)}async function _0(e,t){var R,B,M,F,H;const{account:r=e.account,accessList:n,authorizationList:i,chain:s=e.chain,blobVersionedHashes:a,blobs:o,data:c,gas:u,gasPrice:f,maxFeePerBlobGas:l,maxFeePerGas:h,maxPriorityFeePerGas:d,nonce:b,nonceManager:g,to:x,type:A,value:k,...w}=t,v=await(async()=>{if(!r||!g||typeof b<"u")return b;const z=Me(r),Q=s?s.id:await re(e,Ri,"getChainId")({});return await g.consume({address:z.address,chainId:Q,client:e})})();qn(t);const S=(B=(R=s==null?void 0:s.formatters)==null?void 0:R.transactionRequest)==null?void 0:B.format,_=(S||yn)({...da(w,{format:S}),account:r?Me(r):void 0,accessList:n,authorizationList:i,blobs:o,blobVersionedHashes:a,data:c,gas:u,gasPrice:f,maxFeePerBlobGas:l,maxFeePerGas:h,maxPriorityFeePerGas:d,nonce:v,to:x,type:A,value:k},"fillTransaction");try{const z=await e.request({method:"eth_fillTransaction",params:[_]}),U=(((F=(M=s==null?void 0:s.formatters)==null?void 0:M.transaction)==null?void 0:F.format)||ha)(z.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=t.gas??U.gas),U.gasPrice&&(U.gasPrice=t.gasPrice??U.gasPrice),U.maxFeePerBlobGas&&(U.maxFeePerBlobGas=t.maxFeePerBlobGas??U.maxFeePerBlobGas),U.maxFeePerGas&&(U.maxFeePerGas=t.maxFeePerGas??U.maxFeePerGas),U.maxPriorityFeePerGas&&(U.maxPriorityFeePerGas=t.maxPriorityFeePerGas??U.maxPriorityFeePerGas),U.nonce&&(U.nonce=t.nonce??U.nonce);const K=await(async()=>{var L,Y;if(typeof((L=s==null?void 0:s.fees)==null?void 0:L.baseFeeMultiplier)=="function"){const C=await re(e,$r,"getBlock")({});return s.fees.baseFeeMultiplier({block:C,client:e,request:t})}return((Y=s==null?void 0:s.fees)==null?void 0:Y.baseFeeMultiplier)??1.2})();if(K<1)throw new j1;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&&!t.maxFeePerGas&&(U.maxFeePerGas=O(U.maxFeePerGas)),U.gasPrice&&!t.gasPrice&&(U.gasPrice=O(U.gasPrice)),{raw:z.raw,transaction:{from:_.from,...U}}}catch(z){throw Ku(z,{...t,chain:e.chain})}}const P0=["blobVersionedHashes","chainId","fees","gas","nonce","type"],Uy=new Map,Gf=new la(128);async function Qo(e,t){var v,S,I;let r=t;r.account??(r.account=e.account),r.parameters??(r.parameters=P0);const{account:n,chain:i=e.chain,nonceManager:s,parameters:a}=r,o=(()=>{if(typeof(i==null?void 0:i.prepareTransactionRequest)=="function")return{fn:i.prepareTransactionRequest,runAt:["beforeFillTransaction"]};if(Array.isArray(i==null?void 0:i.prepareTransactionRequest))return{fn:i.prepareTransactionRequest[0],runAt:i.prepareTransactionRequest[1].runAt}})();let c;async function u(){return c||(typeof r.chainId<"u"?r.chainId:i?i.id:(c=await re(e,Ri,"getChainId")({}),c))}const f=n&&Me(n);let l=r.nonce;if(a.includes("nonce")&&typeof l>"u"&&f&&s){const _=await u();l=await s.consume({address:f.address,chainId:_,client:e})}o!=null&&o.fn&&((v=o.runAt)!=null&&v.includes("beforeFillTransaction"))&&(r=await o.fn({...r,chain:i},{phase:"beforeFillTransaction"}),l??(l=r.nonce));const d=((a.includes("blobVersionedHashes")||a.includes("sidecars"))&&r.kzg&&r.blobs||Gf.get(e.uid)===!1||!["fees","gas"].some(R=>a.includes(R))?!1:!!(a.includes("chainId")&&typeof r.chainId!="number"||a.includes("nonce")&&typeof l!="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(e,_0,"fillTransaction")({...r,nonce:l}).then(_=>{const{chainId:R,from:B,gas:M,gasPrice:F,nonce:H,maxFeePerBlobGas:z,maxFeePerGas:Q,maxPriorityFeePerGas:U,type:K,...ee}=_.transaction;return Gf.set(e.uid,!0),{...r,...B?{from:B}:{},...K?{type:K}:{},...typeof R<"u"?{chainId:R}:{},...typeof M<"u"?{gas:M}:{},...typeof F<"u"?{gasPrice:F}:{},...typeof H<"u"?{nonce:H}:{},...typeof z<"u"?{maxFeePerBlobGas:z}:{},...typeof Q<"u"?{maxFeePerGas:Q}:{},...typeof U<"u"?{maxPriorityFeePerGas:U}:{},..."nonceKey"in ee&&typeof ee.nonceKey<"u"?{nonceKey:ee.nonceKey}:{}}}).catch(_=>{var M;const R=_;return R.name!=="TransactionExecutionError"||((M=R.walk)==null?void 0:M.call(R,F=>{const H=F;return H.name==="MethodNotFoundRpcError"||H.name==="MethodNotSupportedRpcError"}))&&Gf.set(e.uid,!1),r}):r;l??(l=d.nonce),r={...d,...f?{from:f==null?void 0:f.address}:{},...l?{nonce:l}:{}};const{blobs:b,gas:g,kzg:x,type:A}=r;o!=null&&o.fn&&((S=o.runAt)!=null&&S.includes("beforeFillParameters"))&&(r=await o.fn({...r,chain:i},{phase:"beforeFillParameters"}));let k;async function w(){return k||(k=await re(e,$r,"getBlock")({blockTag:"latest"}),k)}if(a.includes("nonce")&&typeof l>"u"&&f&&!s&&(r.nonce=await re(e,x0,"getTransactionCount")({address:f.address,blockTag:"pending"})),(a.includes("blobVersionedHashes")||a.includes("sidecars"))&&b&&x){const _=A0({blobs:b,kzg:x});if(a.includes("blobVersionedHashes")){const R=K1({commitments:_,to:"hex"});r.blobVersionedHashes=R}if(a.includes("sidecars")){const R=S0({blobs:b,commitments:_,kzg:x}),B=Q1({blobs:b,commitments:_,proofs:R,to:"hex"});r.sidecars=B}}if(a.includes("chainId")&&(r.chainId=await u()),(a.includes("fees")||a.includes("type"))&&typeof A>"u")try{r.type=I0(r)}catch{let _=Uy.get(e.uid);if(typeof _>"u"){const R=await w();_=typeof(R==null?void 0:R.baseFeePerGas)=="bigint",Uy.set(e.uid,_)}r.type=_?"eip1559":"legacy"}if(a.includes("fees"))if(r.type!=="legacy"&&r.type!=="eip2930"){if(typeof r.maxFeePerGas>"u"||typeof r.maxPriorityFeePerGas>"u"){const _=await w(),{maxFeePerGas:R,maxPriorityFeePerGas:B}=await th(e,{block:_,chain:i,request:r});if(typeof r.maxPriorityFeePerGas>"u"&&r.maxFeePerGas&&r.maxFeePerGas<B)throw new d3({maxPriorityFeePerGas:B});r.maxPriorityFeePerGas=B,r.maxFeePerGas=R}}else{if(typeof r.maxFeePerGas<"u"||typeof r.maxPriorityFeePerGas<"u")throw new w0;if(typeof r.gasPrice>"u"){const _=await w(),{gasPrice:R}=await th(e,{block:_,chain:i,request:r,type:"legacy"});r.gasPrice=R}}return a.includes("gas")&&typeof g>"u"&&(r.gas=await re(e,O0,"estimateGas")({...r,account:f,prepare:(f==null?void 0:f.type)==="local"?[]:["blobVersionedHashes"]})),o!=null&&o.fn&&((I=o.runAt)!=null&&I.includes("afterFillParameters"))&&(r=await o.fn({...r,chain:i},{phase:"afterFillParameters"})),qn(r),delete r.parameters,r}async function O0(e,t){var a,o,c;const{account:r=e.account,prepare:n=!0}=t,i=r?Me(r):void 0,s=(()=>{if(Array.isArray(n))return n;if((i==null?void 0:i.type)!=="local")return["blobVersionedHashes"]})();try{const u=await(async()=>{if(t.to)return t.to;if(t.authorizationList&&t.authorizationList.length>0)return await Vu({authorization:t.authorizationList[0]}).catch(()=>{throw new G("`to` is required. Could not infer from `authorizationList`")})})(),{accessList:f,authorizationList:l,blobs:h,blobVersionedHashes:d,blockNumber:b,blockTag:g,data:x,gas:A,gasPrice:k,maxFeePerBlobGas:w,maxFeePerGas:v,maxPriorityFeePerGas:S,nonce:I,value:_,stateOverride:R,...B}=n?await Qo(e,{...t,parameters:s,to:u}):t;if(A&&t.gas!==A)return A;const F=(typeof b=="bigint"?J(b):void 0)||g,H=g0(R);qn(t);const z=(c=(o=(a=e.chain)==null?void 0:a.formatters)==null?void 0:o.transactionRequest)==null?void 0:c.format,U=(z||yn)({...da(B,{format:z}),account:i,accessList:f,authorizationList:l,blobs:h,blobVersionedHashes:d,data:x,gasPrice:k,maxFeePerBlobGas:w,maxFeePerGas:v,maxPriorityFeePerGas:S,nonce:I,to:u,value:_},"estimateGas");return BigInt(await e.request({method:"eth_estimateGas",params:H?[U,F??e.experimental_blockTag??"latest",H]:F?[U,F]:[U]}))}catch(u){throw o3(u,{...t,account:i,chain:e.chain})}}async function ew(e,t){const{abi:r,address:n,args:i,functionName:s,dataSuffix:a,...o}=t,c=hr({abi:r,args:i,functionName:s});try{return await re(e,O0,"estimateGas")({data:`${c}${a?a.replace("0x",""):""}`,to:n,...o})}catch(u){const f=o.account?Me(o.account):void 0;throw us(u,{abi:r,address:n,args:i,docsPath:"/docs/contract/estimateContractGas",functionName:s,sender:f==null?void 0:f.address})}}function pa(e,t){if(!pt(e,{strict:!1}))throw new Gt({address:e});if(!pt(t,{strict:!1}))throw new Gt({address:t});return e.toLowerCase()===t.toLowerCase()}const Fy="/docs/contract/decodeEventLog";function ou(e){const{abi:t,data:r,strict:n,topics:i}=e,s=n??!0,[a,...o]=i;if(!a)throw new g8({docsPath:Fy});const c=t.find(A=>A.type==="event"&&a===Hu(Lr(A)));if(!(c&&"name"in c)||c.type!=="event")throw new w8(a,{docsPath:Fy});const{name:u,inputs:f}=c,l=f==null?void 0:f.some(A=>!("name"in A&&A.name)),h=l?[]:{},d=f.map((A,k)=>[A,k]).filter(([A])=>"indexed"in A&&A.indexed),b=[];for(let A=0;A<d.length;A++){const[k,w]=d[A],v=o[A];if(!v){if(s)throw new i0({abiItem:c,param:k});b.push([k,w]);continue}h[l?w:k.name||w]=C3({param:k,value:v})}const g=f.filter(A=>!("indexed"in A&&A.indexed)),x=s?g:[...b.map(([A])=>A),...g];if(x.length>0){if(r&&r!=="0x")try{const A=Jo(x,r);if(A){let k=0;if(!s)for(const[w,v]of b)h[l?v:w.name||v]=A[k++];if(l)for(let w=0;w<f.length;w++)h[w]===void 0&&k<A.length&&(h[w]=A[k++]);else for(let w=0;w<g.length;w++)h[g[w].name]=A[k++]}}catch(A){if(s)throw A instanceof i1||A instanceof I1?new au({abiItem:c,data:r,params:x,size:We(r)}):A}else if(s)throw new au({abiItem:c,data:"0x",params:x,size:0})}return{eventName:u,args:Object.values(h).length>0?h:void 0}}function C3({param:e,value:t}){return e.type==="string"||e.type==="bytes"||e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/)?t:(Jo([e],t)||[])[0]}function B0(e){const{abi:t,args:r,logs:n,strict:i=!0}=e,s=(()=>{if(e.eventName)return Array.isArray(e.eventName)?e.eventName:[e.eventName]})();return n.map(a=>{var f;const o=t.filter(l=>l.type==="event"&&a.topics[0]===Hu(l));if(o.length===0)return null;let c,u;for(const l of o)try{c=ou({...a,abi:[l],strict:!0}),u=l;break}catch{}if(!c&&!i){u=o[0];try{c=ou({...a,abi:[u],strict:!1})}catch{const l=(f=u.inputs)==null?void 0:f.some(h=>!("name"in h&&h.name));return{...a,args:l?[]:{},eventName:u.name}}}return!c||!u||s&&!s.includes(c.eventName)||!R3({args:c.args,inputs:u.inputs,matchArgs:r})?null:{...c,...a}}).filter(Boolean)}function R3(e){const{args:t,inputs:r,matchArgs:n}=e;if(!n)return!0;if(!t)return!1;function i(s,a,o){try{return s.type==="address"?pa(a,o):s.type==="string"||s.type==="bytes"?At(fa(a))===o:a===o}catch{return!1}}return Array.isArray(t)&&Array.isArray(n)?n.every((s,a)=>{if(s==null)return!0;const o=r[a];return o?(Array.isArray(s)?s:[s]).some(u=>i(o,u,t[a])):!1}):typeof t=="object"&&!Array.isArray(t)&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).every(([s,a])=>{if(a==null)return!0;const o=r.find(u=>u.name===s);return o?(Array.isArray(a)?a:[a]).some(u=>i(o,u,t[s])):!1}):!1}function Dn(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,blockTimestamp:e.blockTimestamp?BigInt(e.blockTimestamp):e.blockTimestamp===null?null:void 0,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}async function C0(e,{address:t,blockHash:r,fromBlock:n,toBlock:i,event:s,events:a,args:o,strict:c}={}){const u=c??!1,f=a??(s?[s]:void 0);let l=[];f&&(l=[f.flatMap(g=>Xo({abi:[g],eventName:g.name,args:a?void 0:o}))],s&&(l=l[0]));let h;r?h=await e.request({method:"eth_getLogs",params:[{address:t,topics:l,blockHash:r}]}):h=await e.request({method:"eth_getLogs",params:[{address:t,topics:l,fromBlock:typeof n=="bigint"?J(n):n,toBlock:typeof i=="bigint"?J(i):i}]});const d=h.map(b=>Dn(b));return f?B0({abi:f,args:o,logs:d,strict:u}):d}async function R0(e,t){const{abi:r,address:n,args:i,blockHash:s,eventName:a,fromBlock:o,toBlock:c,strict:u}=t,f=a?vs({abi:r,name:a}):void 0,l=f?void 0:r.filter(h=>h.type==="event");return re(e,C0,"getLogs")({address:n,args:i,blockHash:s,event:f,events:l,fromBlock:o,toBlock:c,strict:u})}const qf="/docs/contract/decodeFunctionResult";function Es(e){const{abi:t,args:r,functionName:n,data:i}=e;let s=t[0];if(n){const o=vs({abi:t,args:r,name:n});if(!o)throw new ta(n,{docsPath:qf});s=o}if(s.type!=="function")throw new ta(void 0,{docsPath:qf});if(!s.outputs)throw new a1(s.name,{docsPath:qf});const a=Jo(s.outputs,i);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 N0=BigInt(0),rh=BigInt(1);function ec(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function U0(e){if(!ec(e))throw new Error("Uint8Array expected")}function Io(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function _c(e){const t=e.toString(16);return t.length&1?"0"+t:t}function tw(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?N0:BigInt("0x"+e)}const rw=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",N3=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function _o(e){if(U0(e),rw)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=N3[e[r]];return t}const An={_0:48,_9:57,A:65,F:70,a:97,f:102};function $y(e){if(e>=An._0&&e<=An._9)return e-An._0;if(e>=An.A&&e<=An.F)return e-(An.A-10);if(e>=An.a&&e<=An.f)return e-(An.a-10)}function cu(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(rw)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let i=0,s=0;i<r;i++,s+=2){const a=$y(e.charCodeAt(s)),o=$y(e.charCodeAt(s+1));if(a===void 0||o===void 0){const c=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[i]=a*16+o}return n}function ts(e){return tw(_o(e))}function nw(e){return U0(e),tw(_o(Uint8Array.from(e).reverse()))}function tc(e,t){return cu(e.toString(16).padStart(t*2,"0"))}function iw(e,t){return tc(e,t).reverse()}function wr(e,t,r){let n;if(typeof t=="string")try{n=cu(t)}catch(s){throw new Error(e+" must be hex string or Uint8Array, cause: "+s)}else if(ec(t))n=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");const i=n.length;if(typeof r=="number"&&i!==r)throw new Error(e+" of length "+r+" expected, got "+i);return n}function uu(...e){let t=0;for(let n=0;n<e.length;n++){const i=e[n];U0(i),t+=i.length}const r=new Uint8Array(t);for(let n=0,i=0;n<e.length;n++){const s=e[n];r.set(s,i),i+=s.length}return r}const Wf=e=>typeof e=="bigint"&&N0<=e;function F0(e,t,r){return Wf(e)&&Wf(t)&&Wf(r)&&t<=e&&e<r}function Ws(e,t,r,n){if(!F0(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function U3(e){let t;for(t=0;e>N0;e>>=rh,t+=1);return t}const Xu=e=>(rh<<BigInt(e))-rh,Kf=e=>new Uint8Array(e),My=e=>Uint8Array.from(e);function F3(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=Kf(e),i=Kf(e),s=0;const a=()=>{n.fill(1),i.fill(0),s=0},o=(...l)=>r(i,n,...l),c=(l=Kf(0))=>{i=o(My([0]),l),n=o(),l.length!==0&&(i=o(My([1]),l),n=o())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const h=[];for(;l<t;){n=o();const d=n.slice();h.push(d),l+=n.length}return uu(...h)};return(l,h)=>{a(),c(l);let d;for(;!(d=h(u()));)c();return a(),d}}const $3={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||ec(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function Ju(e,t,r={}){const n=(i,s,a)=>{const o=$3[s];if(typeof o!="function")throw new Error("invalid validator function");const c=e[i];if(!(a&&c===void 0)&&!o(c,e))throw new Error("param "+String(i)+" is invalid. Expected "+s+", got "+c)};for(const[i,s]of Object.entries(t))n(i,s,!1);for(const[i,s]of Object.entries(r))n(i,s,!0);return e}function jy(e){const t=new WeakMap;return(r,...n)=>{const i=t.get(r);if(i!==void 0)return i;const s=e(r,...n);return t.set(r,s),s}}const M3="0.1.1";function j3(){return M3}class se extends Error{static setStaticOptions(t){se.prototype.docsOrigin=t.docsOrigin,se.prototype.showVersion=t.showVersion,se.prototype.version=t.version}constructor(t,r={}){const n=(()=>{var f;if(r.cause instanceof se){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:(f=r.cause)!=null&&f.message?r.cause.message:r.details})(),i=r.cause instanceof se&&r.cause.docsPath||r.docsPath,s=r.docsOrigin??se.prototype.docsOrigin,a=`${s}${i??""}`,o=!!(r.version??se.prototype.showVersion),c=r.version??se.prototype.version,u=[t||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||i||o?["",n?`Details: ${n}`:void 0,i?`See: ${a}`:void 0,o?`Version: ${c}`:void 0]:[]].filter(f=>typeof f=="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=s,this.docsPath=i,this.shortMessage=t,this.showVersion=o,this.version=c}walk(t){return sw(this,t)}}Object.defineProperty(se,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:"https://oxlib.sh",showVersion:!1,version:`ox@${j3()}`}});se.setStaticOptions(se.defaultStaticOptions);function sw(e,t){return t!=null&&t(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?sw(e.cause,t):t?null:e}function ya(e,t){if(Ms(e)>t)throw new iS({givenSize:Ms(e),maxSize:t})}const Sn={zero:48,nine:57,A:65,F:70,a:97,f:102};function Hy(e){if(e>=Sn.zero&&e<=Sn.nine)return e-Sn.zero;if(e>=Sn.A&&e<=Sn.F)return e-(Sn.A-10);if(e>=Sn.a&&e<=Sn.f)return e-(Sn.a-10)}function H3(e,t={}){const{dir:r,size:n=32}=t;if(n===0)return e;if(e.length>n)throw new sS({size:e.length,targetSize:n,type:"Bytes"});const i=new Uint8Array(n);for(let s=0;s<n;s++){const a=r==="right";i[a?s:n-s-1]=e[a?s:e.length-s-1]}return i}function aw(e,t={}){const{dir:r="left"}=t;let n=e,i=0;for(let s=0;s<n.length-1&&n[r==="left"?s:n.length-s-1].toString()==="0";s++)i++;return n=r==="left"?n.slice(i):n.slice(0,n.length-i),n}function Yu(e,t){if(rt(e)>t)throw new fS({givenSize:rt(e),maxSize:t})}function L3(e,t){if(typeof t=="number"&&t>0&&t>rt(e)-1)throw new yw({offset:t,position:"start",size:rt(e)})}function D3(e,t,r){if(typeof t=="number"&&typeof r=="number"&&rt(e)!==r-t)throw new yw({offset:r,position:"end",size:rt(e)})}function ow(e,t={}){const{dir:r,size:n=32}=t;if(n===0)return e;const i=e.replace("0x","");if(i.length>n*2)throw new lS({size:Math.ceil(i.length/2),targetSize:n,type:"Hex"});return`0x${i[r==="right"?"padEnd":"padStart"](n*2,"0")}`}function z3(e,t={}){const{dir:r="left"}=t;let n=e.replace("0x",""),i=0;for(let s=0;s<n.length-1&&n[r==="left"?s:n.length-s-1].toString()==="0";s++)i++;return n=r==="left"?n.slice(i):n.slice(0,n.length-i),n==="0"?"0x":r==="right"&&n.length%2===1?`0x${n}0`:`0x${n}`}const V3="#__bigint";function rc(e,t,r){return JSON.stringify(e,(n,i)=>typeof i=="bigint"?i.toString()+V3:i,r)}const G3=new TextDecoder,q3=new TextEncoder;function W3(e){if(!(e instanceof Uint8Array)){if(!e)throw new Pc(e);if(typeof e!="object")throw new Pc(e);if(!("BYTES_PER_ELEMENT"in e))throw new Pc(e);if(e.BYTES_PER_ELEMENT!==1||e.constructor.name!=="Uint8Array")throw new Pc(e)}}function K3(...e){let t=0;for(const n of e)t+=n.length;const r=new Uint8Array(t);for(let n=0,i=0;n<e.length;n++){const s=e[n];r.set(s,i),i+=s.length}return r}function $0(e){return e instanceof Uint8Array?e:typeof e=="string"?Ni(e):X3(e)}function X3(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function Ni(e,t={}){const{size:r}=t;let n=e;r&&(Yu(e,r),n=ds(e,r));let i=n.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,a=new Uint8Array(s);for(let o=0,c=0;o<s;o++){const u=Hy(i.charCodeAt(c++)),f=Hy(i.charCodeAt(c++));if(u===void 0||f===void 0)throw new se(`Invalid byte sequence ("${i[c-2]}${i[c-1]}" in "${i}").`);a[o]=u<<4|f}return a}function cw(e,t={}){const{size:r}=t,n=q3.encode(e);return typeof r=="number"?(ya(n,r),J3(n,r)):n}function J3(e,t){return H3(e,{dir:"right",size:t})}function Y3(e){return crypto.getRandomValues(new Uint8Array(e))}function Ms(e){return e.length}function Z3(e,t,r,n={}){const{strict:i}=n;return e.slice(t,r)}function Q3(e,t={}){const{size:r}=t;typeof r<"u"&&ya(e,r);const n=bt(e,t);return tt(n,t)}function eS(e,t={}){const{size:r}=t;let n=e;if(typeof r<"u"&&(ya(n,r),n=uw(n)),n.length>1||n[0]>1)throw new nS(n);return!!n[0]}function jn(e,t={}){const{size:r}=t;typeof r<"u"&&ya(e,r);const n=bt(e,t);return Po(n,t)}function tS(e,t={}){const{size:r}=t;let n=e;return typeof r<"u"&&(ya(n,r),n=fw(n)),G3.decode(n)}function uw(e){return aw(e,{dir:"left"})}function fw(e){return aw(e,{dir:"right"})}function rS(e){try{return W3(e),!0}catch{return!1}}class nS extends se{constructor(t){super(`Bytes value \`${t}\` 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"})}}class Pc extends se{constructor(t){super(`Value \`${typeof t=="object"?rc(t):t}\` of type \`${typeof t}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}}let iS=class extends se{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}},sS=class extends se{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}};const aS=new TextEncoder,oS=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function cS(e,t={}){const{strict:r=!1}=t;if(!e)throw new Ly(e);if(typeof e!="string")throw new Ly(e);if(r&&!/^0x[0-9a-fA-F]*$/.test(e))throw new Dy(e);if(!e.startsWith("0x"))throw new Dy(e)}function Je(...e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function Zu(e){return e instanceof Uint8Array?bt(e):Array.isArray(e)?bt(new Uint8Array(e)):e}function lw(e,t={}){const r=`0x${Number(e)}`;return typeof t.size=="number"?(Yu(r,t.size),ls(r,t.size)):r}function bt(e,t={}){let r="";for(let i=0;i<e.length;i++)r+=oS[e[i]];const n=`0x${r}`;return typeof t.size=="number"?(Yu(n,t.size),ds(n,t.size)):n}function te(e,t={}){const{signed:r,size:n}=t,i=BigInt(e);let s;n?r?s=(1n<<BigInt(n)*8n-1n)-1n:s=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const a=typeof s=="bigint"&&r?-s-1n:0;if(s&&i>s||i<a){const u=typeof e=="bigint"?"n":"";throw new pw({max:s?`${s}${u}`:void 0,min:`${a}${u}`,signed:r,size:n,value:`${e}${u}`})}const c=`0x${(r&&i<0?BigInt.asUintN(n*8,BigInt(i)):i).toString(16)}`;return n?ls(c,n):c}function nc(e,t={}){return bt(aS.encode(e),t)}function ls(e,t){return ow(e,{dir:"left",size:t})}function ds(e,t){return ow(e,{dir:"right",size:t})}function dw(e){return bt(Y3(e))}function Ee(e,t,r,n={}){const{strict:i}=n;L3(e,t);const s=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;return i&&D3(s,t,r),s}function rt(e){return Math.ceil((e.length-2)/2)}function nh(e){return z3(e,{dir:"left"})}function tt(e,t={}){const{signed:r}=t;t.size&&Yu(e,t.size);const n=BigInt(e);if(!r)return n;const i=(e.length-2)/2,s=(1n<<BigInt(i)*8n)-1n,a=s>>1n;return n<=a?n:n-s-1n}function Po(e,t={}){const{signed:r,size:n}=t;return Number(!r&&!n?e:tt(e,t))}function hw(e,t={}){const{size:r}=t;let n=Ni(e);return r&&(ya(n,r),n=fw(n)),new TextDecoder().decode(n)}function _r(e,t={}){const{strict:r=!1}=t;try{return cS(e,{strict:r}),!0}catch{return!1}}class pw extends se{constructor({max:t,min:r,signed:n,size:i,value:s}){super(`Number \`${s}\` is not in safe${i?` ${i*8}-bit`:""}${n?" signed":" unsigned"} integer range ${t?`(\`${r}\` to \`${t}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class Ly extends se{constructor(t){super(`Value \`${typeof t=="object"?rc(t):t}\` of type \`${typeof t}\` 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 Dy extends se{constructor(t){super(`Value \`${t}\` 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 uS extends se{constructor(t){super(`Hex value \`"${t}"\` is an odd length (${t.length-2} nibbles).`,{metaMessages:["It must be an even length."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidLengthError"})}}class fS extends se{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class yw extends se{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${t}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}class lS extends se{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}function dS(e){return{address:e.address,amount:te(e.amount),index:te(e.index),validatorIndex:te(e.validatorIndex)}}function mw(e){return{...typeof e.baseFeePerGas=="bigint"&&{baseFeePerGas:te(e.baseFeePerGas)},...typeof e.blobBaseFee=="bigint"&&{blobBaseFee:te(e.blobBaseFee)},...typeof e.feeRecipient=="string"&&{feeRecipient:e.feeRecipient},...typeof e.gasLimit=="bigint"&&{gasLimit:te(e.gasLimit)},...typeof e.number=="bigint"&&{number:te(e.number)},...typeof e.prevRandao=="bigint"&&{prevRandao:te(e.prevRandao)},...typeof e.time=="bigint"&&{time:te(e.time)},...e.withdrawals&&{withdrawals:e.withdrawals.map(dS)}}}const fu=[{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"}],ih=[{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"}]}],bw=[{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"}],gw=[...bw,{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"}]}],hS=[...bw,{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"}]}],zy=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],Vy=[{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"}]}],ww=[{name:"isValidSignature",type:"function",stateMutability:"view",inputs:[{name:"hash",type:"bytes32"},{name:"signature",type:"bytes"}],outputs:[{name:"",type:"bytes4"}]}],Gy=[{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"}],pS="0x82ad56cb",vw="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",yS="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",mS="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",M0="0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033";class sh extends G{constructor({blockNumber:t,chain:r,contract:n}){super(`Chain "${r.name}" does not support contract "${n.name}".`,{metaMessages:["This could be due to any of the following:",...t&&n.blockCreated&&n.blockCreated>t?[`- The contract "${n.name}" was not deployed until block ${n.blockCreated} (current block ${t}).`]:[`- The chain does not have the contract "${n.name}" configured.`]],name:"ChainDoesNotSupportContract"})}}class bS extends G{constructor({chain:t,currentChainId:r}){super(`The current chain of the wallet (id: ${r}) does not match the target chain for the transaction (id: ${t.id} – ${t.name}).`,{metaMessages:[`Current Chain ID: ${r}`,`Expected Chain ID: ${t.id} – ${t.name}`],name:"ChainMismatchError"})}}class gS 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 Ew extends G{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}let Qu=class extends G{constructor({chainId:t}){super(typeof t=="number"?`Chain ID "${t}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}};const Xf="/docs/contract/encodeDeployData";function ef(e){const{abi:t,args:r,bytecode:n}=e;if(!r||r.length===0)return n;const i=t.find(a=>"type"in a&&a.type==="constructor");if(!i)throw new h8({docsPath:Xf});if(!("inputs"in i))throw new py({docsPath:Xf});if(!i.inputs||i.inputs.length===0)throw new py({docsPath:Xf});const s=Ci(i.inputs,r);return Wr([n,s])}function ma({blockNumber:e,chain:t,contract:r}){var i;const n=(i=t==null?void 0:t.contracts)==null?void 0:i[r];if(!n)throw new sh({chain:t,contract:{name:r}});if(e&&n.blockCreated&&n.blockCreated>e)throw new sh({blockNumber:e,chain:t,contract:{name:r,blockCreated:n.blockCreated}});return n.address}function xw(e,{docsPath:t,...r}){const n=(()=>{const i=Gu(e,r);return i instanceof Zo?e:i})();return new N1(n,{docsPath:t,...r})}function j0(){let e=()=>{},t=()=>{};return{promise:new Promise((n,i)=>{e=n,t=i}),resolve:e,reject:t}}const Jf=new Map;function Aw({fn:e,id:t,shouldSplitBatch:r,wait:n=0,sort:i}){const s=async()=>{const f=c();a();const l=f.map(({args:h})=>h);l.length!==0&&e(l).then(h=>{i&&Array.isArray(h)&&h.sort(i);for(let d=0;d<f.length;d++){const{resolve:b}=f[d];b==null||b([h[d],h])}}).catch(h=>{for(let d=0;d<f.length;d++){const{reject:b}=f[d];b==null||b(h)}})},a=()=>Jf.delete(t),o=()=>c().map(({args:f})=>f),c=()=>Jf.get(t)||[],u=f=>Jf.set(t,[...c(),f]);return{flush:a,async schedule(f){const{promise:l,resolve:h,reject:d}=j0();return(r==null?void 0:r([...o(),f]))&&s(),c().length>0?(u({args:f,resolve:h,reject:d}),l):(u({args:f,resolve:h,reject:d}),setTimeout(s,n),l)}}}async function ic(e,t){var z,Q,U,K;const{account:r=e.account,authorizationList:n,batch:i=!!((z=e.batch)!=null&&z.multicall),blockNumber:s,blockTag:a=e.experimental_blockTag??"latest",accessList:o,blobs:c,blockOverrides:u,code:f,data:l,factory:h,factoryData:d,gas:b,gasPrice:g,maxFeePerBlobGas:x,maxFeePerGas:A,maxPriorityFeePerGas:k,nonce:w,to:v,value:S,stateOverride:I,..._}=t,R=r?Me(r):void 0;if(f&&(h||d))throw new G("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(f&&v)throw new G("Cannot provide both `code` & `to` as parameters.");const B=f&&l,M=h&&d&&v&&l,F=B||M,H=B?Sw({code:f,data:l}):M?ES({data:l,factory:h,factoryData:d,to:v}):l;try{qn(t);const q=(typeof s=="bigint"?J(s):void 0)||a,O=u?mw(u):void 0,L=g0(I),Y=(K=(U=(Q=e.chain)==null?void 0:Q.formatters)==null?void 0:U.transactionRequest)==null?void 0:K.format,$=(Y||yn)({...da(_,{format:Y}),accessList:o,account:R,authorizationList:n,blobs:c,data:H,gas:b,gasPrice:g,maxFeePerBlobGas:x,maxFeePerGas:A,maxPriorityFeePerGas:k,nonce:w,to:F?void 0:v,value:S},"call");if(i&&wS({request:$})&&!L&&!O)try{return await vS(e,{...$,blockNumber:s,blockTag:a})}catch(ce){if(!(ce instanceof Ew)&&!(ce instanceof sh))throw ce}const V=(()=>{const ce=[$,q];return L&&O?[...ce,L,O]:L?[...ce,L]:O?[...ce,{},O]:ce})(),ie=await e.request({method:"eth_call",params:V});return ie==="0x"?{data:void 0}:{data:ie}}catch(ee){const q=xS(ee),{offchainLookup:O,offchainLookupSignature:L}=await Promise.resolve().then(()=>require("./ccip-DkEfWv-9.cjs"));if(e.ccipRead!==!1&&(q==null?void 0:q.slice(0,10))===L&&v)return{data:await O(e,{data:q,to:v})};throw F&&(q==null?void 0:q.slice(0,10))==="0x101bb98d"?new YA({factory:h}):xw(ee,{...t,account:R,chain:e.chain})}}function wS({request:e}){const{data:t,to:r,...n}=e;return!(!t||t.startsWith(pS)||!r||Object.values(n).filter(i=>typeof i<"u").length>0)}async function vS(e,t){var g;const{batchSize:r=1024,deployless:n=!1,wait:i=0}=typeof((g=e.batch)==null?void 0:g.multicall)=="object"?e.batch.multicall:{},{blockNumber:s,blockTag:a=e.experimental_blockTag??"latest",data:o,to:c}=t,u=(()=>{if(n)return null;if(t.multicallAddress)return t.multicallAddress;if(e.chain)return ma({blockNumber:s,chain:e.chain,contract:"multicall3"});throw new Ew})(),l=(typeof s=="bigint"?J(s):void 0)||a,{schedule:h}=Aw({id:`${e.uid}.${l}`,wait:i,shouldSplitBatch(x){return x.reduce((k,{data:w})=>k+(w.length-2),0)>r*2},fn:async x=>{const A=x.map(v=>({allowFailure:!0,callData:v.data,target:v.to})),k=hr({abi:fu,args:[A],functionName:"aggregate3"}),w=await e.request({method:"eth_call",params:[{...u===null?{data:Sw({code:M0,data:k})}:{to:u,data:k}},l]});return Es({abi:fu,args:[A],functionName:"aggregate3",data:w||"0x"})}}),[{returnData:d,success:b}]=await h({data:o,to:c});if(!b)throw new zu({data:d});return d==="0x"?{data:void 0}:{data:d}}function Sw(e){const{code:t,data:r}=e;return ef({abi:t1(["constructor(bytes, bytes)"]),bytecode:vw,args:[t,r]})}function ES(e){const{data:t,factory:r,factoryData:n,to:i}=e;return ef({abi:t1(["constructor(address, bytes, address, bytes)"]),bytecode:yS,args:[i,t,r,n]})}function xS(e){var r;if(!(e instanceof G))return;const t=e.walk();return typeof(t==null?void 0:t.data)=="object"?(r=t.data)==null?void 0:r.data:t.data}async function kr(e,t){const{abi:r,address:n,args:i,functionName:s,...a}=t,o=hr({abi:r,args:i,functionName:s});try{const{data:c}=await re(e,ic,"call")({...a,data:o,to:n});return Es({abi:r,args:i,functionName:s,data:c||"0x"})}catch(c){throw us(c,{abi:r,address:n,args:i,docsPath:"/docs/contract/readContract",functionName:s})}}async function kw(e,t){const{abi:r,address:n,args:i,dataSuffix:s,functionName:a,...o}=t,c=o.account?Me(o.account):e.account,u=hr({abi:r,args:i,functionName:a});try{const{data:f}=await re(e,ic,"call")({batch:!1,data:`${u}${s?s.replace("0x",""):""}`,to:n,...o,account:c}),l=Es({abi:r,args:i,functionName:a,data:f||"0x"}),h=r.filter(d=>"name"in d&&d.name===t.functionName);return{result:l,request:{abi:h,address:n,args:i,dataSuffix:s,functionName:a,...o,account:c}}}catch(f){throw us(f,{abi:r,address:n,args:i,docsPath:"/docs/contract/simulateContract",functionName:a,sender:c==null?void 0:c.address})}}const Yf=new Map,qy=new Map;let AS=0;function zn(e,t,r){const n=++AS,i=()=>Yf.get(e)||[],s=()=>{const f=i();Yf.set(e,f.filter(l=>l.id!==n))},a=()=>{const f=i();if(!f.some(h=>h.id===n))return;const l=qy.get(e);if(f.length===1&&l){const h=l();h instanceof Promise&&h.catch(()=>{})}s()},o=i();if(Yf.set(e,[...o,{id:n,fns:t}]),o&&o.length>0)return a;const c={};for(const f in t)c[f]=(...l)=>{var d,b;const h=i();if(h.length!==0)for(const g of h)(b=(d=g.fns)[f])==null||b.call(d,...l)};const u=r(c);return typeof u=="function"&&qy.set(e,u),a}async function ah(e){return new Promise(t=>setTimeout(t,e))}function ba(e,{emitOnBegin:t,initialWaitTime:r,interval:n}){let i=!0;const s=()=>i=!1;return(async()=>{let o;t&&(o=await e({unpoll:s}));const c=await(r==null?void 0:r(o))??n;await ah(c);const u=async()=>{i&&(await e({unpoll:s}),await ah(n),u())};u()})(),s}const SS=new Map,kS=new Map;function TS(e){const t=(i,s)=>({clear:()=>s.delete(i),get:()=>s.get(i),set:a=>s.set(i,a)}),r=t(e,SS),n=t(e,kS);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function IS(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){const n=TS(t),i=n.response.get();if(i&&r>0&&Date.now()-i.created.getTime()<r)return i.data;let s=n.promise.get();s||(s=e(),n.promise.set(s));try{const a=await s;return n.response.set({created:new Date,data:a}),a}finally{n.promise.clear()}}const _S=e=>`blockNumber.${e}`;async function sc(e,{cacheTime:t=e.cacheTime}={}){const r=await IS(()=>e.request({method:"eth_blockNumber"}),{cacheKey:_S(e.uid),cacheTime:t});return BigInt(r)}async function tf(e,{filter:t}){const r="strict"in t&&t.strict,n=await t.request({method:"eth_getFilterChanges",params:[t.id]});if(typeof n[0]=="string")return n;const i=n.map(s=>Dn(s));return!("abi"in t)||!t.abi?i:B0({abi:t.abi,logs:i,strict:r})}async function rf(e,{filter:t}){return t.request({method:"eth_uninstallFilter",params:[t.id]})}function Tw(e,t){const{abi:r,address:n,args:i,batch:s=!0,eventName:a,fromBlock:o,onError:c,onLogs:u,poll:f,pollingInterval:l=e.pollingInterval,strict:h}=t;return(typeof f<"u"?f:typeof o=="bigint"?!0:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")))?(()=>{const x=h??!1,A=at(["watchContractEvent",n,i,s,e.uid,a,l,x,o]);return zn(A,{onLogs:u,onError:c},k=>{let w;o!==void 0&&(w=o-1n);let v,S=!1;const I=ba(async()=>{var _;if(!S){try{v=await re(e,p0,"createContractEventFilter")({abi:r,address:n,args:i,eventName:a,strict:x,fromBlock:o})}catch{}S=!0;return}try{let R;if(v)R=await re(e,tf,"getFilterChanges")({filter:v});else{const B=await re(e,sc,"getBlockNumber")({});w&&w<B?R=await re(e,R0,"getContractEvents")({abi:r,address:n,args:i,eventName:a,fromBlock:w+1n,toBlock:B,strict:x}):R=[],w=B}if(R.length===0)return;if(s)k.onLogs(R);else for(const B of R)k.onLogs([B])}catch(R){v&&R instanceof _i&&(S=!1),(_=k.onError)==null||_.call(k,R)}},{emitOnBegin:!0,interval:l});return async()=>{v&&await re(e,rf,"uninstallFilter")({filter:v}),I()}})})():(()=>{const x=h??!1,A=at(["watchContractEvent",n,i,s,e.uid,a,l,x]);let k=!0,w=()=>k=!1;return zn(A,{onLogs:u,onError:c},v=>((async()=>{try{const S=(()=>{if(e.transport.type==="fallback"){const R=e.transport.transports.find(B=>B.config.type==="webSocket"||B.config.type==="ipc");return R?R.value:e.transport}return e.transport})(),I=a?Xo({abi:r,eventName:a,args:i}):[],{unsubscribe:_}=await S.subscribe({params:["logs",{address:n,topics:I}],onData(R){var M;if(!k)return;const B=R.result;try{const{eventName:F,args:H}=ou({abi:r,data:B.data,topics:B.topics,strict:h}),z=Dn(B,{args:H,eventName:F});v.onLogs([z])}catch(F){let H,z;if(F instanceof au||F instanceof i0){if(h)return;H=F.abiItem.name,z=(M=F.abiItem.inputs)==null?void 0:M.some(U=>!("name"in U&&U.name))}const Q=Dn(B,{args:z?[]:{},eventName:H});v.onLogs([Q])}},onError(R){var B;(B=v.onError)==null||B.call(v,R)}});w=_,k||w()}catch(S){c==null||c(S)}})(),()=>w()))})()}class Ui extends G{constructor({docsPath:t}={}){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:t,docsSlug:"account",name:"AccountNotFoundError"})}}class rs extends G{constructor({docsPath:t,metaMessages:r,type:n}){super(`Account type "${n}" is not supported.`,{docsPath:t,metaMessages:r,name:"AccountTypeNotSupportedError"})}}function H0({chain:e,currentChainId:t}){if(!e)throw new gS;if(t!==e.id)throw new bS({chain:e,currentChainId:t})}async function L0(e,{serializedTransaction:t}){return e.request({method:"eth_sendRawTransaction",params:[t]},{retryCount:0})}const Zf=new la(128);async function nf(e,t){var w,v,S,I;const{account:r=e.account,assertChainId:n=!0,chain:i=e.chain,accessList:s,authorizationList:a,blobs:o,data:c,gas:u,gasPrice:f,maxFeePerBlobGas:l,maxFeePerGas:h,maxPriorityFeePerGas:d,nonce:b,type:g,value:x,...A}=t;if(typeof r>"u")throw new Ui({docsPath:"/docs/actions/wallet/sendTransaction"});const k=r?Me(r):null;try{qn(t);const _=await(async()=>{if(t.to)return t.to;if(t.to!==null&&a&&a.length>0)return await Vu({authorization:a[0]}).catch(()=>{throw new G("`to` is required. Could not infer from `authorizationList`.")})})();if((k==null?void 0:k.type)==="json-rpc"||k===null){let R;i!==null&&(R=await re(e,Ri,"getChainId")({}),n&&H0({currentChainId:R,chain:i}));const B=(S=(v=(w=e.chain)==null?void 0:w.formatters)==null?void 0:v.transactionRequest)==null?void 0:S.format,F=(B||yn)({...da(A,{format:B}),accessList:s,account:k,authorizationList:a,blobs:o,chainId:R,data:c,gas:u,gasPrice:f,maxFeePerBlobGas:l,maxFeePerGas:h,maxPriorityFeePerGas:d,nonce:b,to:_,type:g,value:x},"sendTransaction"),H=Zf.get(e.uid),z=H?"wallet_sendTransaction":"eth_sendTransaction";try{return await e.request({method:z,params:[F]},{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 e.request({method:"wallet_sendTransaction",params:[F]},{retryCount:0}).then(K=>(Zf.set(e.uid,!0),K)).catch(K=>{const ee=K;throw ee.name==="MethodNotFoundRpcError"||ee.name==="MethodNotSupportedRpcError"?(Zf.set(e.uid,!1),U):ee});throw U}}if((k==null?void 0:k.type)==="local"){const R=await re(e,Qo,"prepareTransactionRequest")({account:k,accessList:s,authorizationList:a,blobs:o,chain:i,data:c,gas:u,gasPrice:f,maxFeePerBlobGas:l,maxFeePerGas:h,maxPriorityFeePerGas:d,nonce:b,nonceManager:k.nonceManager,parameters:[...P0,"sidecars"],type:g,value:x,...A,to:_}),B=(I=i==null?void 0:i.serializers)==null?void 0:I.transaction,M=await k.signTransaction(R,{serializer:B});return await re(e,L0,"sendRawTransaction")({serializedTransaction:M})}throw(k==null?void 0:k.type)==="smart"?new rs({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new rs({docsPath:"/docs/actions/wallet/sendTransaction",type:k==null?void 0:k.type})}catch(_){throw _ instanceof rs?_:Ku(_,{...t,account:k,chain:t.chain||void 0})}}async function aa(e,t){return aa.internal(e,nf,"sendTransaction",t)}(function(e){async function t(r,n,i,s){const{abi:a,account:o=r.account,address:c,args:u,dataSuffix:f,functionName:l,...h}=s;if(typeof o>"u")throw new Ui({docsPath:"/docs/contract/writeContract"});const d=o?Me(o):null,b=hr({abi:a,args:u,functionName:l});try{return await re(r,n,i)({data:`${b}${f?f.replace("0x",""):""}`,to:c,account:d,...h})}catch(g){throw us(g,{abi:a,address:c,args:u,docsPath:"/docs/contract/writeContract",functionName:l,sender:d==null?void 0:d.address})}}e.internal=t})(aa||(aa={}));function D0({abi:e,address:t,client:r}){const n=r,[i,s]=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=i!=null,o=s!=null,c={};let u=!1,f=!1,l=!1;for(const h of e)if(h.type==="function"?h.stateMutability==="view"||h.stateMutability==="pure"?u=!0:f=!0:h.type==="event"&&(l=!0),u&&f&&l)break;return a&&(u&&(c.read=new Proxy({},{get(h,d){return(...b)=>{const{args:g,options:x}=Oc(b);return re(i,kr,"readContract")({abi:e,address:t,functionName:d,args:g,...x})}}})),f&&(c.simulate=new Proxy({},{get(h,d){return(...b)=>{const{args:g,options:x}=Oc(b);return re(i,kw,"simulateContract")({abi:e,address:t,functionName:d,args:g,...x})}}})),l&&(c.createEventFilter=new Proxy({},{get(h,d){return(...b)=>{const g=e.find(k=>k.type==="event"&&k.name===d),{args:x,options:A}=Qf(b,g);return re(i,p0,"createContractEventFilter")({abi:e,address:t,eventName:d,args:x,...A})}}}),c.getEvents=new Proxy({},{get(h,d){return(...b)=>{const g=e.find(k=>k.type==="event"&&k.name===d),{args:x,options:A}=Qf(b,g);return re(i,R0,"getContractEvents")({abi:e,address:t,eventName:d,args:x,...A})}}}),c.watchEvent=new Proxy({},{get(h,d){return(...b)=>{const g=e.find(k=>k.type==="event"&&k.name===d),{args:x,options:A}=Qf(b,g);return re(i,Tw,"watchContractEvent")({abi:e,address:t,eventName:d,args:x,...A})}}}))),o&&f&&(c.write=new Proxy({},{get(h,d){return(...b)=>{const{args:g,options:x}=Oc(b);return re(s,aa,"writeContract")({abi:e,address:t,functionName:d,args:g,...x})}}})),(a||o)&&f&&(c.estimateGas=new Proxy({},{get(h,d){return(...b)=>{const{args:g,options:x}=Oc(b);return re(i??s,ew,"estimateContractGas")({abi:e,address:t,functionName:d,args:g,...x,account:x.account??s.account})}}})),c.address=t,c.abi=e,c}function Oc(e){const t=e.length&&Array.isArray(e[0]),r=t?e[0]:[],n=(t?e[1]:e[0])??{};return{args:r,options:n}}function Qf(e,t){let r=!1;Array.isArray(e[0])?r=!0:e.length===1?r=t.inputs.some(s=>s.indexed):e.length===2&&(r=!0);const n=r?e[0]:void 0,i=(r?e[1]:e[0])??{};return{args:n,options:i}}class PS extends G{constructor(t){super(`Call bundle failed with status: ${t.statusCode}`,{name:"BundleFailedError"}),Object.defineProperty(this,"result",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.result=t}}function lu(e,{delay:t=100,retryCount:r=2,shouldRetry:n=()=>!0}={}){return new Promise((i,s)=>{const a=async({count:o=0}={})=>{const c=async({error:u})=>{const f=typeof t=="function"?t({count:o,error:u}):t;f&&await ah(f),a({count:o+1})};try{const u=await e();i(u)}catch(u){if(o<r&&await n({count:o,error:u}))return c({error:u});s(u)}};a()})}const Iw={"0x0":"reverted","0x1":"success"};function sf(e,t){const r={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map(n=>Dn(n)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Sr(e.transactionIndex):null,status:e.status?Iw[e.status]:null,type:e.type?L1[e.type]||e.type:null};return e.blobGasPrice&&(r.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(r.blobGasUsed=BigInt(e.blobGasUsed)),r}const _w=qu("transactionReceipt",sf),Pw="0x5792579257925792579257925792579257925792579257925792579257925792",Ow=J(0,{size:32});async function Bw(e,t){const{account:r=e.account,capabilities:n,chain:i=e.chain,experimental_fallback:s,experimental_fallbackDelay:a=32,forceAtomic:o=!1,id:c,version:u="2.0.0"}=t,f=r?Me(r):null,l=t.calls.map(h=>{const d=h,b=d.abi?hr({abi:d.abi,functionName:d.functionName,args:d.args}):d.data;return{data:d.dataSuffix&&b?lr([b,d.dataSuffix]):b,to:d.to,value:d.value?J(d.value):void 0}});try{const h=await e.request({method:"wallet_sendCalls",params:[{atomicRequired:o,calls:l,capabilities:n,chainId:J(i.id),from:f==null?void 0:f.address,id:c,version:u}]},{retryCount:0});return typeof h=="string"?{id:h}:h}catch(h){const d=h;if(s&&(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(k=>!k.optional)){const k="non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";throw new ia(new G(k,{details:k}))}if(o&&l.length>1){const A="`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";throw new sa(new G(A,{details:A}))}const b=[];for(const A of l){const k=nf(e,{account:f,chain:i,data:A.data,to:A.to,value:A.value?mt(A.value):void 0});b.push(k),a>0&&await new Promise(w=>setTimeout(w,a))}const g=await Promise.allSettled(b);if(g.every(A=>A.status==="rejected"))throw g[0].reason;const x=g.map(A=>A.status==="fulfilled"?A.value:Ow);return{id:lr([...x,J(i.id,{size:32}),Pw])}}throw Ku(h,{...t,account:f,chain:t.chain})}}async function Cw(e,t){async function r(f){if(f.endsWith(Pw.slice(2))){const h=Ar(zd(f,-64,-32)),d=zd(f,0,-64).slice(2).match(/.{1,64}/g),b=await Promise.all(d.map(x=>Ow.slice(2)!==x?e.request({method:"eth_getTransactionReceipt",params:[`0x${x}`]},{dedupe:!0}):void 0)),g=b.some(x=>x===null)?100:b.every(x=>(x==null?void 0:x.status)==="0x1")?200:b.every(x=>(x==null?void 0:x.status)==="0x0")?500:600;return{atomic:!1,chainId:Sr(h),receipts:b.filter(Boolean),status:g,version:"2.0.0"}}return e.request({method:"wallet_getCallsStatus",params:[f]})}const{atomic:n=!1,chainId:i,receipts:s,version:a="2.0.0",...o}=await r(t.id),[c,u]=(()=>{const f=o.status;return f>=100&&f<200?["pending",f]:f>=200&&f<300?["success",f]:f>=300&&f<700?["failure",f]:f==="CONFIRMED"?["success",200]:f==="PENDING"?["pending",100]:[void 0,f]})();return{...o,atomic:n,chainId:i?Sr(i):void 0,receipts:(s==null?void 0:s.map(f=>({...f,blockNumber:mt(f.blockNumber),gasUsed:mt(f.gasUsed),status:Iw[f.status]})))??[],statusCode:u,status:c,version:a}}async function Rw(e,t){const{id:r,pollingInterval:n=e.pollingInterval,status:i=({statusCode:g})=>g===200||g>=300,retryCount:s=4,retryDelay:a=({count:g})=>~~(1<<g)*200,timeout:o=6e4,throwOnFailure:c=!1}=t,u=at(["waitForCallsStatus",e.uid,r]),{promise:f,resolve:l,reject:h}=j0();let d;const b=zn(u,{resolve:l,reject:h},g=>{const x=ba(async()=>{const A=k=>{clearTimeout(d),x(),k(),b()};try{const k=await lu(async()=>{const w=await re(e,Cw,"getCallsStatus")({id:r});if(c&&w.status==="failure")throw new PS(w);return w},{retryCount:s,delay:a});if(!i(k))return;A(()=>g.resolve(k))}catch(k){A(()=>g.reject(k))}},{interval:n,emitOnBegin:!0});return x});return d=o?setTimeout(()=>{b(),clearTimeout(d),h(new OS({id:r}))},o):void 0,await f}class OS extends G{constructor({id:t}){super(`Timed out while waiting for call bundle with id "${t}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}const oh=256;let Bc=oh,Cc;function Nw(e=11){if(!Cc||Bc+e>oh*2){Cc="",Bc=0;for(let t=0;t<oh;t++)Cc+=(256+Math.random()*256|0).toString(16).substring(1)}return Cc.substring(Bc,Bc+++e)}function Uw(e){const{batch:t,chain:r,ccipRead:n,key:i="base",name:s="Base Client",type:a="base"}=e,o=e.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),f=e.pollingInterval??u,l=e.cacheTime??f,h=e.account?Me(e.account):void 0,{config:d,request:b,value:g}=e.transport({account:h,chain:r,pollingInterval:f}),x={...d,...g},A={account:h,batch:t,cacheTime:l,ccipRead:n,chain:r,key:i,name:s,pollingInterval:f,request:b,transport:x,type:a,uid:Nw(),...o?{experimental_blockTag:o}:{}};function k(w){return v=>{const S=v(w);for(const _ in A)delete S[_];const I={...w,...S};return Object.assign(I,{extend:k(I)})}}return Object.assign(A,{extend:k(A)})}function z0(e){var r,n,i,s,a,o;if(!(e instanceof G))return!1;const t=e.walk(c=>c instanceof qd);return t instanceof qd?((r=t.data)==null?void 0:r.errorName)==="HttpError"||((n=t.data)==null?void 0:n.errorName)==="ResolverError"||((i=t.data)==null?void 0:i.errorName)==="ResolverNotContract"||((s=t.data)==null?void 0:s.errorName)==="ResolverNotFound"||((a=t.data)==null?void 0:a.errorName)==="ReverseAddressMismatch"||((o=t.data)==null?void 0:o.errorName)==="UnsupportedResolverProfile":!1}function BS(e){const{abi:t,data:r}=e,n=os(r,0,4),i=t.find(s=>s.type==="function"&&n===Ko(Lr(s)));if(!i)throw new v8(n,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:i.name,args:"inputs"in i&&i.inputs&&i.inputs.length>0?Jo(i.inputs,os(r,4)):void 0}}const el="/docs/contract/encodeErrorResult";function Wy(e){const{abi:t,errorName:r,args:n}=e;let i=t[0];if(r){const c=vs({abi:t,args:n,name:r});if(!c)throw new yy(r,{docsPath:el});i=c}if(i.type!=="error")throw new yy(void 0,{docsPath:el});const s=Lr(i),a=Ko(s);let o="0x";if(n&&n.length>0){if(!i.inputs)throw new b8(i.name,{docsPath:el});o=Ci(i.inputs,n)}return Wr([a,o])}const tl="/docs/contract/encodeFunctionResult";function CS(e){const{abi:t,functionName:r,result:n}=e;let i=t[0];if(r){const a=vs({abi:t,name:r});if(!a)throw new ta(r,{docsPath:tl});i=a}if(i.type!=="function")throw new ta(void 0,{docsPath:tl});if(!i.outputs)throw new a1(i.name,{docsPath:tl});const s=(()=>{if(i.outputs.length===0)return[];if(i.outputs.length===1)return[n];if(Array.isArray(n))return n;throw new o1(n)})();return Ci(i.outputs,s)}const ac="x-batch-gateway:true";async function Fw(e){const{data:t,ccipRequest:r}=e,{args:[n]}=BS({abi:ih,data:t}),i=[],s=[];return await Promise.all(n.map(async(a,o)=>{try{s[o]=a.urls.includes(ac)?await Fw({data:a.data,ccipRequest:r}):await r(a),i[o]=!1}catch(c){i[o]=!0,s[o]=RS(c)}})),CS({abi:ih,functionName:"query",result:[i,s]})}function RS(e){return e.name==="HttpRequestError"&&e.status?Wy({abi:ih,errorName:"HttpError",args:[e.status,e.shortMessage]}):Wy({abi:[T1],errorName:"Error",args:["shortMessage"in e?e.shortMessage:e.message]})}function $w(e){if(e.length!==66||e.indexOf("[")!==0||e.indexOf("]")!==65)return null;const t=`0x${e.slice(1,65)}`;return Dr(t)?t:null}function ch(e){let t=new Uint8Array(32).fill(0);if(!e)return ot(t);const r=e.split(".");for(let n=r.length-1;n>=0;n-=1){const i=$w(r[n]),s=i?fa(i):At(es(r[n]),"bytes");t=At(lr([t,s]),"bytes")}return ot(t)}function NS(e){return`[${e.slice(2)}]`}function US(e){const t=new Uint8Array(32).fill(0);return e?$w(e)||At(es(e)):ot(t)}function V0(e){const t=e.replace(/^\.|\.$/gm,"");if(t.length===0)return new Uint8Array(1);const r=new Uint8Array(es(t).byteLength+2);let n=0;const i=t.split(".");for(let s=0;s<i.length;s++){let a=es(i[s]);a.byteLength>255&&(a=es(NS(US(i[s])))),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 FS(e,t){const{blockNumber:r,blockTag:n,coinType:i,name:s,gatewayUrls:a,strict:o}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return ma({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),f=c==null?void 0:c.ensTlds;if(f&&!f.some(h=>s.endsWith(h)))return null;const l=i!=null?[ch(s),BigInt(i)]:[ch(s)];try{const h=hr({abi:Vy,functionName:"addr",args:l}),d={address:u,abi:gw,functionName:"resolveWithGateways",args:[zt(V0(s)),h,a??[ac]],blockNumber:r,blockTag:n},g=await re(e,kr,"readContract")(d);if(g[0]==="0x")return null;const x=Es({abi:Vy,args:l,functionName:"addr",data:g[0]});return x==="0x"||Ar(x)==="0x00"?null:x}catch(h){if(o)throw h;if(z0(h))return null;throw h}}class $S extends G{constructor({data:t}){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(t)}`],name:"EnsAvatarInvalidMetadataError"})}}class Pa extends G{constructor({reason:t}){super(`ENS NFT avatar URI is invalid. ${t}`,{name:"EnsAvatarInvalidNftUriError"})}}class G0 extends G{constructor({uri:t}){super(`Unable to resolve ENS avatar URI "${t}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class MS extends G{constructor({namespace:t}){super(`ENS NFT avatar namespace "${t}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}const jS=/(?<protocol>https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,HS=/^(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>\/.*)?$/,LS=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,DS=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function zS(e){try{const t=await fetch(e,{method:"HEAD"});if(t.status===200){const r=t.headers.get("content-type");return r==null?void 0:r.startsWith("image/")}return!1}catch(t){return typeof t=="object"&&typeof t.response<"u"||!Object.hasOwn(globalThis,"Image")?!1:new Promise(r=>{const n=new Image;n.onload=()=>{r(!0)},n.onerror=()=>{r(!1)},n.src=e})}}function Ky(e,t){return e?e.endsWith("/")?e.slice(0,-1):e:t}function Mw({uri:e,gatewayUrls:t}){const r=LS.test(e);if(r)return{uri:e,isOnChain:!0,isEncoded:r};const n=Ky(t==null?void 0:t.ipfs,"https://ipfs.io"),i=Ky(t==null?void 0:t.arweave,"https://arweave.net"),s=e.match(jS),{protocol:a,subpath:o,target:c,subtarget:u=""}=(s==null?void 0:s.groups)||{},f=a==="ipns:/"||o==="ipns/",l=a==="ipfs:/"||o==="ipfs/"||HS.test(e);if(e.startsWith("http")&&!f&&!l){let d=e;return t!=null&&t.arweave&&(d=e.replace(/https:\/\/arweave.net/g,t==null?void 0:t.arweave)),{uri:d,isOnChain:!1,isEncoded:!1}}if((f||l)&&c)return{uri:`${n}/${f?"ipns":"ipfs"}/${c}${u}`,isOnChain:!1,isEncoded:!1};if(a==="ar:/"&&c)return{uri:`${i}/${c}${u||""}`,isOnChain:!1,isEncoded:!1};let h=e.replace(DS,"");if(h.startsWith("<svg")&&(h=`data:image/svg+xml;base64,${btoa(h)}`),h.startsWith("data:")||h.startsWith("{"))return{uri:h,isOnChain:!0,isEncoded:!1};throw new G0({uri:e})}function jw(e){if(typeof e!="object"||!("image"in e)&&!("image_url"in e)&&!("image_data"in e))throw new $S({data:e});return e.image||e.image_url||e.image_data}async function VS({gatewayUrls:e,uri:t}){try{const r=await fetch(t).then(i=>i.json());return await q0({gatewayUrls:e,uri:jw(r)})}catch{throw new G0({uri:t})}}async function q0({gatewayUrls:e,uri:t}){const{uri:r,isOnChain:n}=Mw({uri:t,gatewayUrls:e});if(n||await zS(r))return r;throw new G0({uri:t})}function GS(e){let t=e;t.startsWith("did:nft:")&&(t=t.replace("did:nft:","").replace(/_/g,"/"));const[r,n,i]=t.split("/"),[s,a]=r.split(":"),[o,c]=n.split(":");if(!s||s.toLowerCase()!=="eip155")throw new Pa({reason:"Only EIP-155 supported"});if(!a)throw new Pa({reason:"Chain ID not found"});if(!c)throw new Pa({reason:"Contract address not found"});if(!i)throw new Pa({reason:"Token ID not found"});if(!o)throw new Pa({reason:"ERC namespace not found"});return{chainID:Number.parseInt(a,10),namespace:o.toLowerCase(),contractAddress:c,tokenID:i}}async function qS(e,{nft:t}){if(t.namespace==="erc721")return kr(e,{address:t.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(t.tokenID)]});if(t.namespace==="erc1155")return kr(e,{address:t.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(t.tokenID)]});throw new MS({namespace:t.namespace})}async function WS(e,{gatewayUrls:t,record:r}){return/eip155:/i.test(r)?KS(e,{gatewayUrls:t,record:r}):q0({uri:r,gatewayUrls:t})}async function KS(e,{gatewayUrls:t,record:r}){const n=GS(r),i=await qS(e,{nft:n}),{uri:s,isOnChain:a,isEncoded:o}=Mw({uri:i,gatewayUrls:t});if(a&&(s.includes("data:application/json;base64,")||s.startsWith("{"))){const u=o?atob(s.replace("data:application/json;base64,","")):s,f=JSON.parse(u);return q0({uri:jw(f),gatewayUrls:t})}let c=n.tokenID;return n.namespace==="erc1155"&&(c=c.replace("0x","").padStart(64,"0")),VS({gatewayUrls:t,uri:s.replace(/(?:0x)?{id}/,c)})}async function Hw(e,t){const{blockNumber:r,blockTag:n,key:i,name:s,gatewayUrls:a,strict:o}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return ma({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),f=c==null?void 0:c.ensTlds;if(f&&!f.some(l=>s.endsWith(l)))return null;try{const l={address:u,abi:gw,args:[zt(V0(s)),hr({abi:zy,functionName:"text",args:[ch(s),i]}),a??[ac]],functionName:"resolveWithGateways",blockNumber:r,blockTag:n},d=await re(e,kr,"readContract")(l);if(d[0]==="0x")return null;const b=Es({abi:zy,functionName:"text",data:d[0]});return b===""?null:b}catch(l){if(o)throw l;if(z0(l))return null;throw l}}async function XS(e,{blockNumber:t,blockTag:r,assetGatewayUrls:n,name:i,gatewayUrls:s,strict:a,universalResolverAddress:o}){const c=await re(e,Hw,"getEnsText")({blockNumber:t,blockTag:r,key:"avatar",name:i,universalResolverAddress:o,gatewayUrls:s,strict:a});if(!c)return null;try{return await WS(e,{record:c,gatewayUrls:n})}catch{return null}}async function JS(e,t){const{address:r,blockNumber:n,blockTag:i,coinType:s=60n,gatewayUrls:a,strict:o}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return ma({blockNumber:n,chain:c,contract:"ensUniversalResolver"})})();try{const f={address:u,abi:hS,args:[r,s,a??[ac]],functionName:"reverseWithGateways",blockNumber:n,blockTag:i},l=re(e,kr,"readContract"),[h]=await l(f);return h||null}catch(f){if(o)throw f;if(z0(f))return null;throw f}}async function YS(e,t){const{blockNumber:r,blockTag:n,name:i}=t,{chain:s}=e,a=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!s)throw new Error("client chain not configured. universalResolverAddress is required.");return ma({blockNumber:r,chain:s,contract:"ensUniversalResolver"})})(),o=s==null?void 0:s.ensTlds;if(o&&!o.some(u=>i.endsWith(u)))throw new Error(`${i} is not a valid ENS TLD (${o==null?void 0:o.join(", ")}) for chain "${s.name}" (id: ${s.id}).`);const[c]=await re(e,kr,"readContract")({address:a,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[zt(V0(i))],blockNumber:r,blockTag:n});return c}async function Lw(e,t){var x,A,k;const{account:r=e.account,blockNumber:n,blockTag:i="latest",blobs:s,data:a,gas:o,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:f,maxPriorityFeePerGas:l,to:h,value:d,...b}=t,g=r?Me(r):void 0;try{qn(t);const v=(typeof n=="bigint"?J(n):void 0)||i,S=(k=(A=(x=e.chain)==null?void 0:x.formatters)==null?void 0:A.transactionRequest)==null?void 0:k.format,_=(S||yn)({...da(b,{format:S}),account:g,blobs:s,data:a,gas:o,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:f,maxPriorityFeePerGas:l,to:h,value:d},"createAccessList"),R=await e.request({method:"eth_createAccessList",params:[_,v]});return{accessList:R.accessList,gasUsed:BigInt(R.gasUsed)}}catch(w){throw xw(w,{...t,account:g,chain:e.chain})}}async function ZS(e){const t=Lu(e,{method:"eth_newBlockFilter"}),r=await e.request({method:"eth_newBlockFilter"});return{id:r,request:t(r),type:"block"}}async function Dw(e,{address:t,args:r,event:n,events:i,fromBlock:s,strict:a,toBlock:o}={}){const c=i??(n?[n]:void 0),u=Lu(e,{method:"eth_newFilter"});let f=[];c&&(f=[c.flatMap(d=>Xo({abi:[d],eventName:d.name,args:r}))],n&&(f=f[0]));const l=await e.request({method:"eth_newFilter",params:[{address:t,fromBlock:typeof s=="bigint"?J(s):s,toBlock:typeof o=="bigint"?J(o):o,...f.length?{topics:f}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:s,id:l,request:u(l),strict:!!a,toBlock:o,type:"event"}}async function zw(e){const t=Lu(e,{method:"eth_newPendingTransactionFilter"}),r=await e.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:t(r),type:"transaction"}}async function QS(e,{address:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest"}){const i=typeof r=="bigint"?J(r):void 0,s=await e.request({method:"eth_getBalance",params:[t,i||n]});return BigInt(s)}async function ek(e){const t=await e.request({method:"eth_blobBaseFee"});return BigInt(t)}async function tk(e,{blockHash:t,blockNumber:r,blockTag:n="latest"}={}){const i=r!==void 0?J(r):void 0;let s;return t?s=await e.request({method:"eth_getBlockTransactionCountByHash",params:[t]},{dedupe:!0}):s=await e.request({method:"eth_getBlockTransactionCountByNumber",params:[i||n]},{dedupe:!!i}),Sr(s)}async function du(e,{address:t,blockNumber:r,blockTag:n="latest"}){const i=r!==void 0?J(r):void 0,s=await e.request({method:"eth_getCode",params:[t,i||n]},{dedupe:!!i});if(s!=="0x")return s}class rk extends G{constructor({address:t}){super(`No EIP-712 domain found on contract "${t}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${t}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}async function nk(e,t){const{address:r,factory:n,factoryData:i}=t;try{const[s,a,o,c,u,f,l]=await re(e,kr,"readContract")({abi:ik,address:r,functionName:"eip712Domain",factory:n,factoryData:i});return{domain:{name:a,version:o,chainId:Number(c),verifyingContract:u,salt:f},extensions:l,fields:s}}catch(s){const a=s;throw a.name==="ContractFunctionExecutionError"&&a.cause.name==="ContractFunctionZeroDataError"?new rk({address:r}):a}}const ik=[{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 sk(e){var t;return{baseFeePerGas:e.baseFeePerGas.map(r=>BigInt(r)),gasUsedRatio:e.gasUsedRatio,oldestBlock:BigInt(e.oldestBlock),reward:(t=e.reward)==null?void 0:t.map(r=>r.map(n=>BigInt(n)))}}async function ak(e,{blockCount:t,blockNumber:r,blockTag:n="latest",rewardPercentiles:i}){const s=typeof r=="bigint"?J(r):void 0,a=await e.request({method:"eth_feeHistory",params:[J(t),s||n,i]},{dedupe:!!s});return sk(a)}async function ok(e,{filter:t}){const r=t.strict??!1,i=(await t.request({method:"eth_getFilterLogs",params:[t.id]})).map(s=>Dn(s));return t.abi?B0({abi:t.abi,logs:i,strict:r}):i}function ck(e){const{authorizationList:t}=e;if(t)for(const r of t){const{chainId:n}=r,i=r.address;if(!pt(i))throw new Gt({address:i});if(n<0)throw new Qu({chainId:n})}W0(e)}function uk(e){const{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new Z1;for(const r of t){const n=We(r),i=Sr(os(r,0,1));if(n!==32)throw new P3({hash:r,size:n});if(i!==Y1)throw new O3({hash:r,version:i})}}W0(e)}function W0(e){const{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:i}=e;if(t<=0)throw new Qu({chainId:t});if(i&&!pt(i))throw new Gt({address:i});if(n&&n>Wu)throw new fs({maxFeePerGas:n});if(r&&n&&r>n)throw new To({maxFeePerGas:n,maxPriorityFeePerGas:r})}function fk(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:s}=e;if(t<=0)throw new Qu({chainId:t});if(s&&!pt(s))throw new Gt({address:s});if(r||i)throw new G("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>Wu)throw new fs({maxFeePerGas:n})}function lk(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:s}=e;if(s&&!pt(s))throw new Gt({address:s});if(typeof t<"u"&&t<=0)throw new Qu({chainId:t});if(r||i)throw new G("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>Wu)throw new fs({maxFeePerGas:n})}function af(e){if(!e||e.length===0)return[];const t=[];for(let r=0;r<e.length;r++){const{address:n,storageKeys:i}=e[r];for(let s=0;s<i.length;s++)if(i[s].length-2!==64)throw new qA({storageKey:i[s]});if(!pt(n,{strict:!1}))throw new Gt({address:n});t.push([n,i])}return t}function uh(e,t){const r=I0(e);return r==="eip1559"?pk(e,t):r==="eip2930"?yk(e,t):r==="eip4844"?hk(e,t):r==="eip7702"?dk(e,t):mk(e,t)}function dk(e,t){const{authorizationList:r,chainId:n,gas:i,nonce:s,to:a,value:o,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:f,data:l}=e;ck(e);const h=af(f),d=bk(r);return Wr(["0x04",Pi([J(n),s?J(s):"0x",u?J(u):"0x",c?J(c):"0x",i?J(i):"0x",a??"0x",o?J(o):"0x",l??"0x",h,d,...oc(e,t)])])}function hk(e,t){const{chainId:r,gas:n,nonce:i,to:s,value:a,maxFeePerBlobGas:o,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:f,data:l}=e;uk(e);let h=e.blobVersionedHashes,d=e.sidecars;if(e.blobs&&(typeof h>"u"||typeof d>"u")){const w=typeof e.blobs[0]=="string"?e.blobs:e.blobs.map(I=>ot(I)),v=e.kzg,S=A0({blobs:w,kzg:v});if(typeof h>"u"&&(h=K1({commitments:S})),typeof d>"u"){const I=S0({blobs:w,commitments:S,kzg:v});d=Q1({blobs:w,commitments:S,proofs:I})}}const b=af(f),g=[J(r),i?J(i):"0x",u?J(u):"0x",c?J(c):"0x",n?J(n):"0x",s??"0x",a?J(a):"0x",l??"0x",b,o?J(o):"0x",h??[],...oc(e,t)],x=[],A=[],k=[];if(d)for(let w=0;w<d.length;w++){const{blob:v,commitment:S,proof:I}=d[w];x.push(v),A.push(S),k.push(I)}return Wr(["0x03",Pi(d?[g,x,A,k]:g)])}function pk(e,t){const{chainId:r,gas:n,nonce:i,to:s,value:a,maxFeePerGas:o,maxPriorityFeePerGas:c,accessList:u,data:f}=e;W0(e);const l=af(u),h=[J(r),i?J(i):"0x",c?J(c):"0x",o?J(o):"0x",n?J(n):"0x",s??"0x",a?J(a):"0x",f??"0x",l,...oc(e,t)];return Wr(["0x02",Pi(h)])}function yk(e,t){const{chainId:r,gas:n,data:i,nonce:s,to:a,value:o,accessList:c,gasPrice:u}=e;fk(e);const f=af(c),l=[J(r),s?J(s):"0x",u?J(u):"0x",n?J(n):"0x",a??"0x",o?J(o):"0x",i??"0x",f,...oc(e,t)];return Wr(["0x01",Pi(l)])}function mk(e,t){const{chainId:r=0,gas:n,data:i,nonce:s,to:a,value:o,gasPrice:c}=e;lk(e);let u=[s?J(s):"0x",c?J(c):"0x",n?J(n):"0x",a??"0x",o?J(o):"0x",i??"0x"];if(t){const f=(()=>{if(t.v>=35n)return(t.v-35n)/2n>0?t.v:27n+(t.v===35n?0n:1n);if(r>0)return BigInt(r*2)+BigInt(35n+t.v-27n);const d=27n+(t.v===27n?0n:1n);if(t.v!==d)throw new VA({v:t.v});return d})(),l=Ar(t.r),h=Ar(t.s);u=[...u,J(f),l==="0x00"?"0x":l,h==="0x00"?"0x":h]}else r>0&&(u=[...u,J(r),"0x","0x"]);return Pi(u)}function oc(e,t){const r=t??e,{v:n,yParity:i}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof i>"u")return[];const s=Ar(r.r),a=Ar(r.s);return[typeof i=="number"?i?J(1):"0x":n===0n?"0x":n===1n?J(1):n===27n?"0x":J(1),s==="0x00"?"0x":s,a==="0x00"?"0x":a]}function bk(e){if(!e||e.length===0)return[];const t=[];for(const r of e){const{chainId:n,nonce:i,...s}=r,a=r.address;t.push([n?zt(n):"0x",a,i?zt(i):"0x",...oc({},s)])}return t}async function gk({address:e,authorization:t,signature:r}){return pa(f0(e),await Vu({authorization:t,signature:r}))}const Rc=new la(8192);function wk(e,{enabled:t=!0,id:r}){if(!t||!r)return e();if(Rc.get(r))return Rc.get(r);const n=e().finally(()=>Rc.delete(r));return Rc.set(r,n),n}function vk(e,t={}){return async(r,n={})=>{var l;const{dedupe:i=!1,methods:s,retryDelay:a=150,retryCount:o=3,uid:c}={...t,...n},{method:u}=r;if((l=s==null?void 0:s.exclude)!=null&&l.includes(u))throw new Vi(new Error("method not supported"),{method:u});if(s!=null&&s.include&&!s.include.includes(u))throw new Vi(new Error("method not supported"),{method:u});const f=i?ra(`${c}.${at(r)}`):void 0;return wk(()=>lu(async()=>{try{return await e(r)}catch(h){const d=h;switch(d.code){case oo.code:throw new oo(d);case co.code:throw new co(d);case uo.code:throw new uo(d,{method:r.method});case fo.code:throw new fo(d);case cs.code:throw new cs(d);case _i.code:throw new _i(d);case lo.code:throw new lo(d);case ho.code:throw new ho(d);case po.code:throw new po(d);case Vi.code:throw new Vi(d,{method:r.method});case na.code:throw new na(d);case yo.code:throw new yo(d);case qs.code:throw new qs(d);case mo.code:throw new mo(d);case bo.code:throw new bo(d);case go.code:throw new go(d);case wo.code:throw new wo(d);case vo.code:throw new vo(d);case ia.code:throw new ia(d);case Eo.code:throw new Eo(d);case xo.code:throw new xo(d);case Ao.code:throw new Ao(d);case So.code:throw new So(d);case ko.code:throw new ko(d);case sa.code:throw new sa(d);case 5e3:throw new qs(d);default:throw h instanceof G?h:new QA(d)}}},{delay:({count:h,error:d})=>{var b;if(d&&d instanceof Gs){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<<h)*a},retryCount:o,shouldRetry:({error:h})=>Ek(h)}),{enabled:i,id:f})}}function Ek(e){return"code"in e&&typeof e.code=="number"?e.code===-1||e.code===na.code||e.code===cs.code:e instanceof Gs&&e.status?e.status===403||e.status===408||e.status===413||e.status===429||e.status===500||e.status===502||e.status===503||e.status===504:!0}function Ze(e){const t={formatters:void 0,fees:void 0,serializers:void 0,...e};function r(n){return i=>{const s=typeof i=="function"?i(n):i,a={...n,...s};return Object.assign(a,{extend:r(a)})}}return Object.assign(t,{extend:r(t)})}function xk(){return{}}function Ak(e,{errorInstance:t=new Error("timed out"),timeout:r,signal:n}){return new Promise((i,s)=>{(async()=>{let a;try{const o=new AbortController;r>0&&(a=setTimeout(()=>{n&&o.abort()},r)),i(await e({signal:(o==null?void 0:o.signal)||null}))}catch(o){(o==null?void 0:o.name)==="AbortError"&&s(t),s(o)}finally{clearTimeout(a)}})()})}function Sk(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const Xy=Sk();function kk(e,t={}){const{url:r,headers:n}=Tk(e);return{async request(i){var b;const{body:s,fetchFn:a=t.fetchFn??fetch,onRequest:o=t.onRequest,onResponse:c=t.onResponse,timeout:u=t.timeout??1e4}=i,f={...t.fetchOptions??{},...i.fetchOptions??{}},{headers:l,method:h,signal:d}=f;try{const g=await Ak(async({signal:A})=>{const k={...f,body:Array.isArray(s)?at(s.map(I=>({jsonrpc:"2.0",id:I.id??Xy.take(),...I}))):at({jsonrpc:"2.0",id:s.id??Xy.take(),...s}),headers:{...n,"Content-Type":"application/json",...l},method:h||"POST",signal:d||(u>0?A:null)},w=new Request(r,k),v=await(o==null?void 0:o(w,k))??{...k,url:r};return await a(v.url??r,v)},{errorInstance:new Oy({body:s,url:r}),timeout:u,signal:!0});c&&await c(g);let x;if((b=g.headers.get("Content-Type"))!=null&&b.startsWith("application/json"))x=await g.json();else{x=await g.text();try{x=JSON.parse(x||"{}")}catch(A){if(g.ok)throw A;x={error:x}}}if(!g.ok)throw new Gs({body:s,details:at(x.error)||g.statusText,headers:g.headers,status:g.status,url:r});return x}catch(g){throw g instanceof Gs||g instanceof Oy?g:new Gs({body:s,cause:g,url:r})}}}}function Tk(e){try{const t=new URL(e),r=(()=>{if(t.username){const n=`${decodeURIComponent(t.username)}:${decodeURIComponent(t.password)}`;return t.username="",t.password="",{url:t.toString(),headers:{Authorization:`Basic ${btoa(n)}`}}}})();return{url:t.toString(),...r}}catch{return{url:e}}}const Ik=`Ethereum Signed Message:
|
|
69
|
+
`;function _k(e){const t=typeof e=="string"?ra(e):typeof e.raw=="string"?e.raw:ot(e.raw),r=ra(`${Ik}${We(t)}`);return lr([r,t])}function Vw(e,t){return At(_k(e),t)}class Pk extends G{constructor({domain:t}){super(`Invalid domain "${at(t)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class Ok extends G{constructor({primaryType:t,types:r}){super(`Invalid primary type \`${t}\` 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 Bk extends G{constructor({type:t}){super(`Struct type "${t}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function Ck(e){const{domain:t,message:r,primaryType:n,types:i}=e,s=(c,u)=>{const f={...u};for(const l of c){const{name:h,type:d}=l;d==="address"&&(f[h]=f[h].toLowerCase())}return f},a=i.EIP712Domain?t?s(i.EIP712Domain,t):{}:{},o=(()=>{if(n!=="EIP712Domain")return s(i[n],r)})();return at({domain:a,message:o,primaryType:n,types:i})}function Gw(e){const{domain:t,message:r,primaryType:n,types:i}=e,s=(a,o)=>{for(const c of a){const{name:u,type:f}=c,l=o[u],h=f.match(S1);if(h&&(typeof l=="number"||typeof l=="bigint")){const[g,x,A]=h;J(l,{signed:x==="int",size:Number.parseInt(A,10)/8})}if(f==="address"&&typeof l=="string"&&!pt(l))throw new Gt({address:l});const d=f.match(yA);if(d){const[g,x]=d;if(x&&We(l)!==Number.parseInt(x,10))throw new x8({expectedSize:Number.parseInt(x,10),givenSize:We(l)})}const b=i[f];b&&(Rk(f),s(b,l))}};if(i.EIP712Domain&&t){if(typeof t!="object")throw new Pk({domain:t});s(i.EIP712Domain,t)}if(n!=="EIP712Domain")if(i[n])s(i[n],r);else throw new Ok({primaryType:n,types:i})}function qw({domain:e}){return[typeof(e==null?void 0:e.name)=="string"&&{name:"name",type:"string"},(e==null?void 0:e.version)&&{name:"version",type:"string"},(typeof(e==null?void 0:e.chainId)=="number"||typeof(e==null?void 0:e.chainId)=="bigint")&&{name:"chainId",type:"uint256"},(e==null?void 0:e.verifyingContract)&&{name:"verifyingContract",type:"address"},(e==null?void 0:e.salt)&&{name:"salt",type:"bytes32"}].filter(Boolean)}function Rk(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new Bk({type:e})}function Nk(e){const{domain:t={},message:r,primaryType:n}=e,i={EIP712Domain:qw({domain:t}),...e.types};Gw({domain:t,message:r,primaryType:n,types:i});const s=["0x1901"];return t&&s.push(Uk({domain:t,types:i})),n!=="EIP712Domain"&&s.push(Ww({data:r,primaryType:n,types:i})),At(lr(s))}function Uk({domain:e,types:t}){return Ww({data:e,primaryType:"EIP712Domain",types:t})}function Ww({data:e,primaryType:t,types:r}){const n=Kw({data:e,primaryType:t,types:r});return At(n)}function Kw({data:e,primaryType:t,types:r}){const n=[{type:"bytes32"}],i=[Fk({primaryType:t,types:r})];for(const s of r[t]){const[a,o]=Jw({types:r,name:s.name,type:s.type,value:e[s.name]});n.push(a),i.push(o)}return Ci(n,i)}function Fk({primaryType:e,types:t}){const r=zt($k({primaryType:e,types:t}));return At(r)}function $k({primaryType:e,types:t}){let r="";const n=Xw({primaryType:e,types:t});n.delete(e);const i=[e,...Array.from(n).sort()];for(const s of i)r+=`${s}(${t[s].map(({name:a,type:o})=>`${o} ${a}`).join(",")})`;return r}function Xw({primaryType:e,types:t},r=new Set){const n=e.match(/^\w*/u),i=n==null?void 0:n[0];if(r.has(i)||t[i]===void 0)return r;r.add(i);for(const s of t[i])Xw({primaryType:s.type,types:t},r);return r}function Jw({types:e,name:t,type:r,value:n}){if(e[r]!==void 0)return[{type:"bytes32"},At(Kw({data:n,primaryType:r,types:e}))];if(r==="bytes")return[{type:"bytes32"},At(n)];if(r==="string")return[{type:"bytes32"},At(zt(n))];if(r.lastIndexOf("]")===r.length-1){const i=r.slice(0,r.lastIndexOf("[")),s=n.map(a=>Jw({name:t,type:i,types:e,value:a}));return[{type:"bytes32"},At(Ci(s.map(([a])=>a),s.map(([,a])=>a)))]}return[{type:r},n]}class Mk extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){const r=super.get(t);return super.has(t)&&r!==void 0&&(this.delete(t),super.set(t,r)),r}set(t,r){if(super.set(t,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const jk={checksum:new Mk(8192)},rl=jk.checksum;function cc(e,t={}){const{as:r=typeof e=="string"?"Hex":"Bytes"}=t,n=w1($0(e));return r==="Bytes"?n:bt(n)}function Hk(e,t={}){const{as:r=typeof e=="string"?"Hex":"Bytes"}=t,n=W1($0(e));return r==="Bytes"?n:bt(n)}function Lk(e){return _r(e)&&rt(e)===32}function Yw(e,t={}){const{compressed:r}=t,{prefix:n,x:i,y:s}=e;if(r===!1||typeof i=="bigint"&&typeof s=="bigint"){if(n!==4)throw new Jy({prefix:n,cause:new Wk});return}if(r===!0||typeof i=="bigint"&&typeof s>"u"){if(n!==3&&n!==2)throw new Jy({prefix:n,cause:new qk});return}throw new Gk({publicKey:e})}function Dk(e){const t=(()=>{if(_r(e))return Zw(e);if(rS(e))return zk(e);const{prefix:r,x:n,y:i}=e;return typeof n=="bigint"&&typeof i=="bigint"?{prefix:r??4,x:n,y:i}:{prefix:r,x:n}})();return Yw(t),t}function zk(e){return Zw(bt(e))}function Zw(e){if(e.length!==132&&e.length!==130&&e.length!==68)throw new Kk({publicKey:e});if(e.length===130){const n=BigInt(Ee(e,0,32)),i=BigInt(Ee(e,32,64));return{prefix:4,x:n,y:i}}if(e.length===132){const n=Number(Ee(e,0,1)),i=BigInt(Ee(e,1,33)),s=BigInt(Ee(e,33,65));return{prefix:n,x:i,y:s}}const t=Number(Ee(e,0,1)),r=BigInt(Ee(e,1,33));return{prefix:t,x:r}}function Vk(e,t={}){return Ni(K0(e,t))}function K0(e,t={}){Yw(e);const{prefix:r,x:n,y:i}=e,{includePrefix:s=!0}=t;return Je(s?te(r,{size:1}):"0x",te(n,{size:32}),typeof i=="bigint"?te(i,{size:32}):"0x")}class Gk extends se{constructor({publicKey:t}){super(`Value \`${rc(t)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}}class Jy extends se{constructor({prefix:t,cause:r}){super(`Prefix "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class qk extends se{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}}class Wk extends se{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}let Kk=class extends se{constructor({publicKey:t}){super(`Value \`${t}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${rt(Zu(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}};const Xk=/^0x[a-fA-F0-9]{40}$/;function Vr(e,t={}){const{strict:r=!0}=t;if(!Xk.test(e))throw new Yy({address:e,cause:new Yk});if(r){if(e.toLowerCase()===e)return;if(X0(e)!==e)throw new Yy({address:e,cause:new Zk})}}function X0(e){if(rl.has(e))return rl.get(e);Vr(e,{strict:!1});const t=e.substring(2).toLowerCase(),r=cc(cw(t),{as:"Bytes"}),n=t.split("");for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&n[s]&&(n[s]=n[s].toUpperCase()),(r[s>>1]&15)>=8&&n[s+1]&&(n[s+1]=n[s+1].toUpperCase());const i=`0x${n.join("")}`;return rl.set(e,i),i}function Jk(e,t={}){const{checksum:r=!1}=t;return Vr(e),r?X0(e):e}function Jc(e,t={}){const r=cc(`0x${K0(e).slice(4)}`).substring(26);return Jk(`0x${r}`,t)}function fh(e,t){return Vr(e,{strict:!1}),Vr(t,{strict:!1}),e.toLowerCase()===t.toLowerCase()}function hu(e,t={}){const{strict:r=!0}=t??{};try{return Vr(e,{strict:r}),!0}catch{return!1}}class Yy extends se{constructor({address:t,cause:r}){super(`Address "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class Yk extends se{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 Zk extends se{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}const Qk=/^(.*)\[([0-9]*)\]$/,eT=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Qw=/^(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)?$/,Zy=2n**256n-1n;function Ks(e,t,r){const{checksumAddress:n,staticPosition:i}=r,s=Z0(t.type);if(s){const[a,o]=s;return rT(e,{...t,type:o},{checksumAddress:n,length:a,staticPosition:i})}if(t.type==="tuple")return aT(e,t,{checksumAddress:n,staticPosition:i});if(t.type==="address")return tT(e,{checksum:n});if(t.type==="bool")return nT(e);if(t.type.startsWith("bytes"))return iT(e,t,{staticPosition:i});if(t.type.startsWith("uint")||t.type.startsWith("int"))return sT(e,t);if(t.type==="string")return oT(e,{staticPosition:i});throw new tp(t.type)}const Qy=32,lh=32;function tT(e,t={}){const{checksum:r=!1}=t,n=e.readBytes(32);return[(s=>r?X0(s):s)(bt(Z3(n,-20))),32]}function rT(e,t,r){const{checksumAddress:n,length:i,staticPosition:s}=r;if(!i){const c=jn(e.readBytes(lh)),u=s+c,f=u+Qy;e.setPosition(u);const l=jn(e.readBytes(Qy)),h=Oo(t);let d=0;const b=[];for(let g=0;g<l;++g){e.setPosition(f+(h?g*32:d));const[x,A]=Ks(e,t,{checksumAddress:n,staticPosition:f});d+=A,b.push(x)}return e.setPosition(s+32),[b,32]}if(Oo(t)){const c=jn(e.readBytes(lh)),u=s+c,f=[];for(let l=0;l<i;++l){e.setPosition(u+l*32);const[h]=Ks(e,t,{checksumAddress:n,staticPosition:u});f.push(h)}return e.setPosition(s+32),[f,32]}let a=0;const o=[];for(let c=0;c<i;++c){const[u,f]=Ks(e,t,{checksumAddress:n,staticPosition:s+a});a+=f,o.push(u)}return[o,a]}function nT(e){return[eS(e.readBytes(32),{size:32}),32]}function iT(e,t,{staticPosition:r}){const[n,i]=t.type.split("bytes");if(!i){const a=jn(e.readBytes(32));e.setPosition(r+a);const o=jn(e.readBytes(32));if(o===0)return e.setPosition(r+32),["0x",32];const c=e.readBytes(o);return e.setPosition(r+32),[bt(c),32]}return[bt(e.readBytes(Number.parseInt(i,10),32)),32]}function sT(e,t){const r=t.type.startsWith("int"),n=Number.parseInt(t.type.split("int")[1]||"256",10),i=e.readBytes(32);return[n>48?Q3(i,{signed:r}):jn(i,{signed:r}),32]}function aT(e,t,r){const{checksumAddress:n,staticPosition:i}=r,s=t.components.length===0||t.components.some(({name:c})=>!c),a=s?[]:{};let o=0;if(Oo(t)){const c=jn(e.readBytes(lh)),u=i+c;for(let f=0;f<t.components.length;++f){const l=t.components[f];e.setPosition(u+o);const[h,d]=Ks(e,l,{checksumAddress:n,staticPosition:u});o+=d,a[s?f:l==null?void 0:l.name]=h}return e.setPosition(i+32),[a,32]}for(let c=0;c<t.components.length;++c){const u=t.components[c],[f,l]=Ks(e,u,{checksumAddress:n,staticPosition:i});a[s?c:u==null?void 0:u.name]=f,o+=l}return[a,o]}function oT(e,{staticPosition:t}){const r=jn(e.readBytes(32)),n=t+r;e.setPosition(n);const i=jn(e.readBytes(32));if(i===0)return e.setPosition(t+32),["",32];const s=e.readBytes(i,32),a=tS(uw(s));return e.setPosition(t+32),[a,32]}function cT({checksumAddress:e,parameters:t,values:r}){const n=[];for(let i=0;i<t.length;i++)n.push(J0({checksumAddress:e,parameter:t[i],value:r[i]}));return n}function J0({checksumAddress:e=!1,parameter:t,value:r}){const n=t,i=Z0(n.type);if(i){const[s,a]=i;return fT(r,{checksumAddress:e,length:s,parameter:{...n,type:a}})}if(n.type==="tuple")return yT(r,{checksumAddress:e,parameter:n});if(n.type==="address")return uT(r,{checksum:e});if(n.type==="bool")return dT(r);if(n.type.startsWith("uint")||n.type.startsWith("int")){const s=n.type.startsWith("int"),[,,a="256"]=Qw.exec(n.type)??[];return hT(r,{signed:s,size:Number(a)})}if(n.type.startsWith("bytes"))return lT(r,{type:n.type});if(n.type==="string")return pT(r);throw new tp(n.type)}function Y0(e){let t=0;for(let s=0;s<e.length;s++){const{dynamic:a,encoded:o}=e[s];a?t+=32:t+=rt(o)}const r=[],n=[];let i=0;for(let s=0;s<e.length;s++){const{dynamic:a,encoded:o}=e[s];a?(r.push(te(t+i,{size:32})),n.push(o),i+=rt(o)):r.push(o)}return Je(...r,...n)}function uT(e,t){const{checksum:r=!1}=t;return Vr(e,{strict:r}),{dynamic:!1,encoded:ls(e.toLowerCase())}}function fT(e,t){const{checksumAddress:r,length:n,parameter:i}=t,s=n===null;if(!Array.isArray(e))throw new AT(e);if(!s&&e.length!==n)throw new xT({expectedLength:n,givenLength:e.length,type:`${i.type}[${n}]`});let a=!1;const o=[];for(let c=0;c<e.length;c++){const u=J0({checksumAddress:r,parameter:i,value:e[c]});u.dynamic&&(a=!0),o.push(u)}if(s||a){const c=Y0(o);if(s){const u=te(o.length,{size:32});return{dynamic:!0,encoded:o.length>0?Je(u,c):u}}if(a)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:Je(...o.map(({encoded:c})=>c))}}function lT(e,{type:t}){const[,r]=t.split("bytes"),n=rt(e);if(!r){let i=e;return n%32!==0&&(i=ds(i,Math.ceil((e.length-2)/2/32)*32)),{dynamic:!0,encoded:Je(ls(te(n,{size:32})),i)}}if(n!==Number.parseInt(r,10))throw new t2({expectedSize:Number.parseInt(r,10),value:e});return{dynamic:!1,encoded:ds(e)}}function dT(e){if(typeof e!="boolean")throw new se(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:ls(lw(e))}}function hT(e,{signed:t,size:r}){if(typeof r=="number"){const n=2n**(BigInt(r)-(t?1n:0n))-1n,i=t?-n-1n:0n;if(e>n||e<i)throw new pw({max:n.toString(),min:i.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:te(e,{size:32,signed:t})}}function pT(e){const t=nc(e),r=Math.ceil(rt(t)/32),n=[];for(let i=0;i<r;i++)n.push(ds(Ee(t,i*32,(i+1)*32)));return{dynamic:!0,encoded:Je(ds(te(rt(t),{size:32})),...n)}}function yT(e,t){const{checksumAddress:r,parameter:n}=t;let i=!1;const s=[];for(let a=0;a<n.components.length;a++){const o=n.components[a],c=Array.isArray(e)?a:o.name,u=J0({checksumAddress:r,parameter:o,value:e[c]});s.push(u),u.dynamic&&(i=!0)}return{dynamic:i,encoded:i?Y0(s):Je(...s.map(({encoded:a})=>a))}}function Z0(e){const t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function Oo(e){var n;const{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return(n=e.components)==null?void 0:n.some(Oo);const r=Z0(e.type);return!!(r&&Oo({...e,type:r[1]}))}const mT={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 gT({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new bT({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new em({offset:e});const t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new em({offset:e});const t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){const r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){const t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){const t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){const t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();const r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();const e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();const e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();const e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();const e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){const t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};function Q0(e,{recursiveReadLimit:t=8192}={}){const r=Object.create(mT);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}class em extends se{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}}class bT extends se{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"})}}class gT extends se{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"})}}function wT(e,t,r={}){const{as:n="Array",checksumAddress:i=!1}=r,s=typeof t=="string"?Ni(t):t,a=Q0(s);if(Ms(s)===0&&e.length>0)throw new ET;if(Ms(s)&&Ms(s)<32)throw new vT({data:typeof t=="string"?t:bt(t),parameters:e,size:Ms(s)});let o=0;const c=n==="Array"?[]:{};for(let u=0;u<e.length;++u){const f=e[u];a.setPosition(o);const[l,h]=Ks(a,f,{checksumAddress:i,staticPosition:0});o+=h,n==="Array"?c.push(l):c[f.name??u]=l}return c}function ep(e,t,r){const{checksumAddress:n=!1}={};if(e.length!==t.length)throw new r2({expectedLength:e.length,givenLength:t.length});const i=cT({checksumAddress:n,parameters:e,values:t}),s=Y0(i);return s.length===0?"0x":s}function dh(e,t){if(e.length!==t.length)throw new r2({expectedLength:e.length,givenLength:t.length});const r=[];for(let n=0;n<e.length;n++){const i=e[n],s=t[n];r.push(dh.encode(i,s))}return Je(...r)}(function(e){function t(r,n,i=!1){if(r==="address"){const c=n;return Vr(c),ls(c.toLowerCase(),i?32:0)}if(r==="string")return nc(n);if(r==="bytes")return n;if(r==="bool")return ls(lw(n),i?32:1);const s=r.match(Qw);if(s){const[c,u,f="256"]=s,l=Number.parseInt(f,10)/8;return te(n,{size:i?32:l,signed:u==="int"})}const a=r.match(eT);if(a){const[c,u]=a;if(Number.parseInt(u,10)!==(n.length-2)/2)throw new t2({expectedSize:Number.parseInt(u,10),value:n});return ds(n,i?32:0)}const o=r.match(Qk);if(o&&Array.isArray(n)){const[c,u]=o,f=[];for(let l=0;l<n.length;l++)f.push(t(u,n[l],!0));return f.length===0?"0x":Je(...f)}throw new tp(r)}e.encode=t})(dh||(dh={}));function e2(e){return Array.isArray(e)&&typeof e[0]=="string"||typeof e=="string"?hy(e):e}class vT extends se{constructor({data:t,parameters:r,size:n}){super(`Data size of ${n} bytes is too small for given parameters.`,{metaMessages:[`Params: (${Ns(r)})`,`Data: ${t} (${n} bytes)`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"})}}class ET extends se{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.'),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ZeroDataError"})}}class xT extends se{constructor({expectedLength:t,givenLength:r,type:n}){super(`Array length mismatch for type \`${n}\`. Expected: \`${t}\`. Given: \`${r}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}}class t2 extends se{constructor({expectedSize:t,value:r}){super(`Size of bytes "${r}" (bytes${rt(r)}) does not match expected size (bytes${t}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class r2 extends se{constructor({expectedLength:t,givenLength:r}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${t}`,`Given length (values): ${r}`].join(`
|
|
70
|
+
`)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class AT extends se{constructor(t){super(`Value \`${t}\` is not a valid array.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}}class tp extends se{constructor(t){super(`Type \`${t}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}function ST(e){return kT(e,"Hex")}function kT(e,t){const r=t,n=(()=>{if(typeof e=="string"){if(e.length>3&&e.length%2!==0)throw new uS(e);return Ni(e)}return e})(),i=Q0(n,{recursiveReadLimit:Number.POSITIVE_INFINITY});return n2(i,r)}function n2(e,t="Hex"){if(e.bytes.length===0)return t==="Hex"?bt(e.bytes):e.bytes;const r=e.readByte();if(r<128&&e.decrementPosition(1),r<192){const i=tm(e,r,128),s=e.readBytes(i);return t==="Hex"?bt(s):s}const n=tm(e,r,192);return TT(e,n,t)}function tm(e,t,r){if(r===128&&t<128)return 1;if(t<=r+55)return t-r;if(t===r+55+1)return e.readUint8();if(t===r+55+2)return e.readUint16();if(t===r+55+3)return e.readUint24();if(t===r+55+4)return e.readUint32();throw new se("Invalid RLP prefix")}function TT(e,t,r){const n=e.position,i=[];for(;e.position-n<t;)i.push(n2(e,r));return i}function IT(e,t){const{as:r}=t,n=i2(e),i=Q0(new Uint8Array(n.length));return n.encode(i),r==="Hex"?bt(i.bytes):i.bytes}function _T(e,t={}){const{as:r="Hex"}=t;return IT(e,{as:r})}function i2(e){return Array.isArray(e)?PT(e.map(t=>i2(t))):OT(e)}function PT(e){const t=e.reduce((i,s)=>i+s.length,0),r=s2(t);return{length:t<=55?1+t:1+r+t,encode(i){t<=55?i.pushByte(192+t):(i.pushByte(247+r),r===1?i.pushUint8(t):r===2?i.pushUint16(t):r===3?i.pushUint24(t):i.pushUint32(t));for(const{encode:s}of e)s(i)}}}function OT(e){const t=typeof e=="string"?Ni(e):e,r=s2(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length,encode(i){t.length===1&&t[0]<128?i.pushBytes(t):t.length<=55?(i.pushByte(128+t.length),i.pushBytes(t)):(i.pushByte(183+r),r===1?i.pushUint8(t.length):r===2?i.pushUint16(t.length):r===3?i.pushUint24(t.length):i.pushUint32(t.length),i.pushBytes(t))}}}function s2(e){if(e<=255)return 1;if(e<=65535)return 2;if(e<=16777215)return 3;if(e<=4294967295)return 4;throw new se("Length is too large.")}class a2 extends Mu{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,K8(t);const n=$n(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(n.length>i?t.create().update(n).digest():n);for(let a=0;a<s.length;a++)s[a]^=54;this.iHash.update(s),this.oHash=t.create();for(let a=0;a<s.length;a++)s[a]^=106;this.oHash.update(s),zr(s)}update(t){return Ii(this),this.iHash.update(t),this}digestInto(t){Ii(this),Ti(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:n,finished:i,destroyed:s,blockLen:a,outputLen:o}=this;return t=t,t.finished=i,t.destroyed=s,t.blockLen=a,t.outputLen=o,t.oHash=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const o2=(e,t,r)=>new a2(e,t).update(r).digest();o2.create=(e,t)=>new a2(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Yt=BigInt(0),Vt=BigInt(1),Gi=BigInt(2),BT=BigInt(3),c2=BigInt(4),u2=BigInt(5),f2=BigInt(8);function Wt(e,t){const r=e%t;return r>=Yt?r:t+r}function br(e,t,r){let n=e;for(;t-- >Yt;)n*=n,n%=r;return n}function hh(e,t){if(e===Yt)throw new Error("invert: expected non-zero number");if(t<=Yt)throw new Error("invert: expected positive modulus, got "+t);let r=Wt(e,t),n=t,i=Yt,s=Vt;for(;r!==Yt;){const o=n/r,c=n%r,u=i-s*o;n=r,r=c,i=s,s=u}if(n!==Vt)throw new Error("invert: does not exist");return Wt(i,t)}function l2(e,t){const r=(e.ORDER+Vt)/c2,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function CT(e,t){const r=(e.ORDER-u2)/f2,n=e.mul(t,Gi),i=e.pow(n,r),s=e.mul(t,i),a=e.mul(e.mul(s,Gi),i),o=e.mul(s,e.sub(a,e.ONE));if(!e.eql(e.sqr(o),t))throw new Error("Cannot find square root");return o}function RT(e){if(e<BigInt(3))throw new Error("sqrt is not defined for small field");let t=e-Vt,r=0;for(;t%Gi===Yt;)t/=Gi,r++;let n=Gi;const i=ga(e);for(;rm(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return l2;let s=i.pow(n,t);const a=(t+Vt)/Gi;return function(c,u){if(c.is0(u))return u;if(rm(c,u)!==1)throw new Error("Cannot find square root");let f=r,l=c.mul(c.ONE,s),h=c.pow(u,t),d=c.pow(u,a);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let b=1,g=c.sqr(h);for(;!c.eql(g,c.ONE);)if(b++,g=c.sqr(g),b===f)throw new Error("Cannot find square root");const x=Vt<<BigInt(f-b-1),A=c.pow(l,x);f=b,l=c.sqr(A),h=c.mul(h,l),d=c.mul(d,A)}return d}}function NT(e){return e%c2===BT?l2:e%f2===u2?CT:RT(e)}const UT=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function FT(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=UT.reduce((n,i)=>(n[i]="function",n),t);return Ju(e,r)}function $T(e,t,r){if(r<Yt)throw new Error("invalid exponent, negatives unsupported");if(r===Yt)return e.ONE;if(r===Vt)return t;let n=e.ONE,i=t;for(;r>Yt;)r&Vt&&(n=e.mul(n,i)),i=e.sqr(i),r>>=Vt;return n}function d2(e,t,r=!1){const n=new Array(t.length).fill(r?e.ZERO:void 0),i=t.reduce((a,o,c)=>e.is0(o)?a:(n[c]=a,e.mul(a,o)),e.ONE),s=e.inv(i);return t.reduceRight((a,o,c)=>e.is0(o)?a:(n[c]=e.mul(a,n[c]),e.mul(a,o)),s),n}function rm(e,t){const r=(e.ORDER-Vt)/Gi,n=e.pow(t,r),i=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),a=e.eql(n,e.neg(e.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function h2(e,t){t!==void 0&&ki(t);const r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function ga(e,t,r=!1,n={}){if(e<=Yt)throw new Error("invalid field: expected ORDER > 0, got "+e);const{nBitLength:i,nByteLength:s}=h2(e,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let a;const o=Object.freeze({ORDER:e,isLE:r,BITS:i,BYTES:s,MASK:Xu(i),ZERO:Yt,ONE:Vt,create:c=>Wt(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Yt<=c&&c<e},is0:c=>c===Yt,isOdd:c=>(c&Vt)===Vt,neg:c=>Wt(-c,e),eql:(c,u)=>c===u,sqr:c=>Wt(c*c,e),add:(c,u)=>Wt(c+u,e),sub:(c,u)=>Wt(c-u,e),mul:(c,u)=>Wt(c*u,e),pow:(c,u)=>$T(o,c,u),div:(c,u)=>Wt(c*hh(u,e),e),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>hh(c,e),sqrt:n.sqrt||(c=>(a||(a=NT(e)),a(o,c))),toBytes:c=>r?iw(c,s):tc(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?nw(c):ts(c)},invertBatch:c=>d2(o,c),cmov:(c,u,f)=>f?u:c});return Object.freeze(o)}function p2(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function y2(e){const t=p2(e);return t+Math.ceil(t/2)}function MT(e,t,r=!1){const n=e.length,i=p2(t),s=y2(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const a=r?nw(e):ts(e),o=Wt(a,t-Vt)+Vt;return r?iw(o,i):tc(o,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const nm=BigInt(0),ph=BigInt(1);function nl(e,t){const r=t.negate();return e?r:t}function m2(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function il(e,t){m2(e,t);const r=Math.ceil(t/e)+1,n=2**(e-1),i=2**e,s=Xu(e),a=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:i,shiftBy:a}}function im(e,t,r){const{windowSize:n,mask:i,maxNumber:s,shiftBy:a}=r;let o=Number(e&i),c=e>>a;o>n&&(o-=s,c+=ph);const u=t*n,f=u+Math.abs(o)-1,l=o===0,h=o<0,d=t%2!==0;return{nextN:c,offset:f,isZero:l,isNeg:h,isNegF:d,offsetF:u}}function jT(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function HT(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}const sl=new WeakMap,b2=new WeakMap;function al(e){return b2.get(e)||1}function LT(e,t){return{constTimeNegate:nl,hasPrecomputes(r){return al(r)!==1},unsafeLadder(r,n,i=e.ZERO){let s=r;for(;n>nm;)n&ph&&(i=i.add(s)),s=s.double(),n>>=ph;return i},precomputeWindow(r,n){const{windows:i,windowSize:s}=il(n,t),a=[];let o=r,c=o;for(let u=0;u<i;u++){c=o,a.push(c);for(let f=1;f<s;f++)c=c.add(o),a.push(c);o=c.double()}return a},wNAF(r,n,i){let s=e.ZERO,a=e.BASE;const o=il(r,t);for(let c=0;c<o.windows;c++){const{nextN:u,offset:f,isZero:l,isNeg:h,isNegF:d,offsetF:b}=im(i,c,o);i=u,l?a=a.add(nl(d,n[b])):s=s.add(nl(h,n[f]))}return{p:s,f:a}},wNAFUnsafe(r,n,i,s=e.ZERO){const a=il(r,t);for(let o=0;o<a.windows&&i!==nm;o++){const{nextN:c,offset:u,isZero:f,isNeg:l}=im(i,o,a);if(i=c,!f){const h=n[u];s=s.add(l?h.negate():h)}}return s},getPrecomputes(r,n,i){let s=sl.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&sl.set(n,i(s))),s},wNAFCached(r,n,i){const s=al(r);return this.wNAF(s,this.getPrecomputes(s,r,i),n)},wNAFCachedUnsafe(r,n,i,s){const a=al(r);return a===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(a,this.getPrecomputes(a,r,i),n,s)},setWindowSize(r,n){m2(n,t),b2.set(r,n),sl.delete(r)}}}function DT(e,t,r,n){jT(r,e),HT(n,t);const i=r.length,s=n.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const a=e.ZERO,o=U3(BigInt(i));let c=1;o>12?c=o-3:o>4?c=o-2:o>0&&(c=2);const u=Xu(c),f=new Array(Number(u)+1).fill(a),l=Math.floor((t.BITS-1)/c)*c;let h=a;for(let d=l;d>=0;d-=c){f.fill(a);for(let g=0;g<s;g++){const x=n[g],A=Number(x>>BigInt(d)&u);f[A]=f[A].add(r[g])}let b=a;for(let g=f.length-1,x=a;g>0;g--)x=x.add(f[g]),b=b.add(x);if(h=h.add(b),d!==0)for(let g=0;g<c;g++)h=h.double()}return h}function g2(e){return FT(e.Fp),Ju(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...h2(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function sm(e){e.lowS!==void 0&&Io("lowS",e.lowS),e.prehash!==void 0&&Io("prehash",e.prehash)}function zT(e){const t=g2(e);Ju(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:r,Fp:n,a:i}=t;if(r){if(!n.eql(i,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({...t})}class VT extends Error{constructor(t=""){super(t)}}const On={Err:VT,_tlv:{encode:(e,t)=>{const{Err:r}=On;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");const n=t.length/2,i=_c(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?_c(i.length/2|128):"";return _c(e)+s+i+t},decode(e,t){const{Err:r}=On;let n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");const i=t[n++],s=!!(i&128);let a=0;if(!s)a=i;else{const c=i&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=t.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 f of u)a=a<<8|f;if(n+=c,a<128)throw new r("tlv.decode(long): not minimal encoding")}const o=t.subarray(n,n+a);if(o.length!==a)throw new r("tlv.decode: wrong value length");return{v:o,l:t.subarray(n+a)}}},_int:{encode(e){const{Err:t}=On;if(e<Nn)throw new t("integer: negative integers are not allowed");let r=_c(e);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){const{Err:t}=On;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return ts(e)}},toSig(e){const{Err:t,_int:r,_tlv:n}=On,i=wr("signature",e),{v:s,l:a}=n.decode(48,i);if(a.length)throw new t("invalid signature: left bytes after parsing");const{v:o,l:c}=n.decode(2,s),{v:u,l:f}=n.decode(2,c);if(f.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(o),s:r.decode(u)}},hexFromSig(e){const{_tlv:t,_int:r}=On,n=t.encode(2,r.encode(e.r)),i=t.encode(2,r.encode(e.s)),s=n+i;return t.encode(48,s)}};function ol(e,t){return _o(tc(e,t))}const Nn=BigInt(0),yt=BigInt(1);BigInt(2);const cl=BigInt(3),GT=BigInt(4);function qT(e){const t=zT(e),{Fp:r}=t,n=ga(t.n,t.nBitLength),i=t.toBytes||((w,v,S)=>{const I=v.toAffine();return uu(Uint8Array.from([4]),r.toBytes(I.x),r.toBytes(I.y))}),s=t.fromBytes||(w=>{const v=w.subarray(1),S=r.fromBytes(v.subarray(0,r.BYTES)),I=r.fromBytes(v.subarray(r.BYTES,2*r.BYTES));return{x:S,y:I}});function a(w){const{a:v,b:S}=t,I=r.sqr(w),_=r.mul(I,w);return r.add(r.add(_,r.mul(w,v)),S)}function o(w,v){const S=r.sqr(v),I=a(w);return r.eql(S,I)}if(!o(t.Gx,t.Gy))throw new Error("bad curve params: generator point");const c=r.mul(r.pow(t.a,cl),GT),u=r.mul(r.sqr(t.b),BigInt(27));if(r.is0(r.add(c,u)))throw new Error("bad curve params: a or b");function f(w){return F0(w,yt,t.n)}function l(w){const{allowedPrivateKeyLengths:v,nByteLength:S,wrapPrivateKey:I,n:_}=t;if(v&&typeof w!="bigint"){if(ec(w)&&(w=_o(w)),typeof w!="string"||!v.includes(w.length))throw new Error("invalid private key");w=w.padStart(S*2,"0")}let R;try{R=typeof w=="bigint"?w:ts(wr("private key",w,S))}catch{throw new Error("invalid private key, expected hex or "+S+" bytes, got "+typeof w)}return I&&(R=Wt(R,_)),Ws("private key",R,yt,_),R}function h(w){if(!(w instanceof g))throw new Error("ProjectivePoint expected")}const d=jy((w,v)=>{const{px:S,py:I,pz:_}=w;if(r.eql(_,r.ONE))return{x:S,y:I};const R=w.is0();v==null&&(v=R?r.ONE:r.inv(_));const B=r.mul(S,v),M=r.mul(I,v),F=r.mul(_,v);if(R)return{x:r.ZERO,y:r.ZERO};if(!r.eql(F,r.ONE))throw new Error("invZ was invalid");return{x:B,y:M}}),b=jy(w=>{if(w.is0()){if(t.allowInfinityPoint&&!r.is0(w.py))return;throw new Error("bad point: ZERO")}const{x:v,y:S}=w.toAffine();if(!r.isValid(v)||!r.isValid(S))throw new Error("bad point: x or y not FE");if(!o(v,S))throw new Error("bad point: equation left != right");if(!w.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class g{constructor(v,S,I){if(v==null||!r.isValid(v))throw new Error("x required");if(S==null||!r.isValid(S)||r.is0(S))throw new Error("y required");if(I==null||!r.isValid(I))throw new Error("z required");this.px=v,this.py=S,this.pz=I,Object.freeze(this)}static fromAffine(v){const{x:S,y:I}=v||{};if(!v||!r.isValid(S)||!r.isValid(I))throw new Error("invalid affine point");if(v instanceof g)throw new Error("projective point not allowed");const _=R=>r.eql(R,r.ZERO);return _(S)&&_(I)?g.ZERO:new g(S,I,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(v){const S=d2(r,v.map(I=>I.pz));return v.map((I,_)=>I.toAffine(S[_])).map(g.fromAffine)}static fromHex(v){const S=g.fromAffine(s(wr("pointHex",v)));return S.assertValidity(),S}static fromPrivateKey(v){return g.BASE.multiply(l(v))}static msm(v,S){return DT(g,n,v,S)}_setWindowSize(v){k.setWindowSize(this,v)}assertValidity(){b(this)}hasEvenY(){const{y:v}=this.toAffine();if(r.isOdd)return!r.isOdd(v);throw new Error("Field doesn't support isOdd")}equals(v){h(v);const{px:S,py:I,pz:_}=this,{px:R,py:B,pz:M}=v,F=r.eql(r.mul(S,M),r.mul(R,_)),H=r.eql(r.mul(I,M),r.mul(B,_));return F&&H}negate(){return new g(this.px,r.neg(this.py),this.pz)}double(){const{a:v,b:S}=t,I=r.mul(S,cl),{px:_,py:R,pz:B}=this;let M=r.ZERO,F=r.ZERO,H=r.ZERO,z=r.mul(_,_),Q=r.mul(R,R),U=r.mul(B,B),K=r.mul(_,R);return K=r.add(K,K),H=r.mul(_,B),H=r.add(H,H),M=r.mul(v,H),F=r.mul(I,U),F=r.add(M,F),M=r.sub(Q,F),F=r.add(Q,F),F=r.mul(M,F),M=r.mul(K,M),H=r.mul(I,H),U=r.mul(v,U),K=r.sub(z,U),K=r.mul(v,K),K=r.add(K,H),H=r.add(z,z),z=r.add(H,z),z=r.add(z,U),z=r.mul(z,K),F=r.add(F,z),U=r.mul(R,B),U=r.add(U,U),z=r.mul(U,K),M=r.sub(M,z),H=r.mul(U,Q),H=r.add(H,H),H=r.add(H,H),new g(M,F,H)}add(v){h(v);const{px:S,py:I,pz:_}=this,{px:R,py:B,pz:M}=v;let F=r.ZERO,H=r.ZERO,z=r.ZERO;const Q=t.a,U=r.mul(t.b,cl);let K=r.mul(S,R),ee=r.mul(I,B),q=r.mul(_,M),O=r.add(S,I),L=r.add(R,B);O=r.mul(O,L),L=r.add(K,ee),O=r.sub(O,L),L=r.add(S,_);let Y=r.add(R,M);return L=r.mul(L,Y),Y=r.add(K,q),L=r.sub(L,Y),Y=r.add(I,_),F=r.add(B,M),Y=r.mul(Y,F),F=r.add(ee,q),Y=r.sub(Y,F),z=r.mul(Q,L),F=r.mul(U,q),z=r.add(F,z),F=r.sub(ee,z),z=r.add(ee,z),H=r.mul(F,z),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(Y,L),F=r.mul(O,F),F=r.sub(F,K),K=r.mul(O,ee),z=r.mul(Y,z),z=r.add(z,K),new g(F,H,z)}subtract(v){return this.add(v.negate())}is0(){return this.equals(g.ZERO)}wNAF(v){return k.wNAFCached(this,v,g.normalizeZ)}multiplyUnsafe(v){const{endo:S,n:I}=t;Ws("scalar",v,Nn,I);const _=g.ZERO;if(v===Nn)return _;if(this.is0()||v===yt)return this;if(!S||k.hasPrecomputes(this))return k.wNAFCachedUnsafe(this,v,g.normalizeZ);let{k1neg:R,k1:B,k2neg:M,k2:F}=S.splitScalar(v),H=_,z=_,Q=this;for(;B>Nn||F>Nn;)B&yt&&(H=H.add(Q)),F&yt&&(z=z.add(Q)),Q=Q.double(),B>>=yt,F>>=yt;return R&&(H=H.negate()),M&&(z=z.negate()),z=new g(r.mul(z.px,S.beta),z.py,z.pz),H.add(z)}multiply(v){const{endo:S,n:I}=t;Ws("scalar",v,yt,I);let _,R;if(S){const{k1neg:B,k1:M,k2neg:F,k2:H}=S.splitScalar(v);let{p:z,f:Q}=this.wNAF(M),{p:U,f:K}=this.wNAF(H);z=k.constTimeNegate(B,z),U=k.constTimeNegate(F,U),U=new g(r.mul(U.px,S.beta),U.py,U.pz),_=z.add(U),R=Q.add(K)}else{const{p:B,f:M}=this.wNAF(v);_=B,R=M}return g.normalizeZ([_,R])[0]}multiplyAndAddUnsafe(v,S,I){const _=g.BASE,R=(M,F)=>F===Nn||F===yt||!M.equals(_)?M.multiplyUnsafe(F):M.multiply(F),B=R(this,S).add(R(v,I));return B.is0()?void 0:B}toAffine(v){return d(this,v)}isTorsionFree(){const{h:v,isTorsionFree:S}=t;if(v===yt)return!0;if(S)return S(g,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:v,clearCofactor:S}=t;return v===yt?this:S?S(g,this):this.multiplyUnsafe(t.h)}toRawBytes(v=!0){return Io("isCompressed",v),this.assertValidity(),i(g,this,v)}toHex(v=!0){return Io("isCompressed",v),_o(this.toRawBytes(v))}}g.BASE=new g(t.Gx,t.Gy,r.ONE),g.ZERO=new g(r.ZERO,r.ONE,r.ZERO);const{endo:x,nBitLength:A}=t,k=LT(g,x?Math.ceil(A/2):A);return{CURVE:t,ProjectivePoint:g,normPrivateKeyToScalar:l,weierstrassEquation:a,isWithinCurveOrder:f}}function WT(e){const t=g2(e);return Ju(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function KT(e){const t=WT(e),{Fp:r,n,nByteLength:i,nBitLength:s}=t,a=r.BYTES+1,o=2*r.BYTES+1;function c(U){return Wt(U,n)}function u(U){return hh(U,n)}const{ProjectivePoint:f,normPrivateKeyToScalar:l,weierstrassEquation:h,isWithinCurveOrder:d}=qT({...t,toBytes(U,K,ee){const q=K.toAffine(),O=r.toBytes(q.x),L=uu;return Io("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=ts(q);if(!F0(O,yt,r.ORDER))throw new Error("Point is not on curve");const L=h(O);let Y;try{Y=r.sqrt(L)}catch(V){const ie=V instanceof Error?": "+V.message:"";throw new Error("Point is not on curve"+ie)}const C=(Y&yt)===yt;return(ee&1)===1!==C&&(Y=r.neg(Y)),{x:O,y:Y}}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>>yt;return U>K}function g(U){return b(U)?c(-U):U}const x=(U,K,ee)=>ts(U.slice(K,ee));class A{constructor(K,ee,q){Ws("r",K,yt,n),Ws("s",ee,yt,n),this.r=K,this.s=ee,q!=null&&(this.recovery=q),Object.freeze(this)}static fromCompact(K){const ee=i;return K=wr("compactSignature",K,ee*2),new A(x(K,0,ee),x(K,ee,2*ee))}static fromDER(K){const{r:ee,s:q}=On.toSig(wr("DER",K));return new A(ee,q)}assertValidity(){}addRecoveryBit(K){return new A(this.r,this.s,K)}recoverPublicKey(K){const{r:ee,s:q,recovery:O}=this,L=_(wr("msgHash",K));if(O==null||![0,1,2,3].includes(O))throw new Error("recovery id invalid");const Y=O===2||O===3?ee+t.n:ee;if(Y>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const C=O&1?"03":"02",$=f.fromHex(C+ol(Y,r.BYTES)),V=u(Y),ie=c(-L*V),ce=c(q*V),de=f.BASE.multiplyAndAddUnsafe($,ie,ce);if(!de)throw new Error("point at infinify");return de.assertValidity(),de}hasHighS(){return b(this.s)}normalizeS(){return this.hasHighS()?new A(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return cu(this.toDERHex())}toDERHex(){return On.hexFromSig(this)}toCompactRawBytes(){return cu(this.toCompactHex())}toCompactHex(){const K=i;return ol(this.r,K)+ol(this.s,K)}}const k={isValidPrivateKey(U){try{return l(U),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const U=y2(t.n);return MT(t.randomBytes(U),t.n)},precompute(U=8,K=f.BASE){return K._setWindowSize(U),K.multiply(BigInt(3)),K}};function w(U,K=!0){return f.fromPrivateKey(U).toRawBytes(K)}function v(U){if(typeof U=="bigint")return!1;if(U instanceof f)return!0;const ee=wr("key",U).length,q=r.BYTES,O=q+1,L=2*q+1;if(!(t.allowedPrivateKeyLengths||i===O))return ee===O||ee===L}function S(U,K,ee=!0){if(v(U)===!0)throw new Error("first arg must be private key");if(v(K)===!1)throw new Error("second arg must be public key");return f.fromHex(K).multiply(l(U)).toRawBytes(ee)}const I=t.bits2int||function(U){if(U.length>8192)throw new Error("input is too large");const K=ts(U),ee=U.length*8-s;return ee>0?K>>BigInt(ee):K},_=t.bits2int_modN||function(U){return c(I(U))},R=Xu(s);function B(U){return Ws("num < 2^"+s,U,Nn,R),tc(U,i)}function M(U,K,ee=F){if(["recovered","canonical"].some(oe=>oe in ee))throw new Error("sign() legacy options not supported");const{hash:q,randomBytes:O}=t;let{lowS:L,prehash:Y,extraEntropy:C}=ee;L==null&&(L=!0),U=wr("msgHash",U),sm(ee),Y&&(U=wr("prehashed msgHash",q(U)));const $=_(U),V=l(K),ie=[B(V),B($)];if(C!=null&&C!==!1){const oe=C===!0?O(r.BYTES):C;ie.push(wr("extraEntropy",oe))}const ce=uu(...ie),de=$;function le(oe){const ae=I(oe);if(!d(ae))return;const ge=u(ae),we=f.BASE.multiply(ae).toAffine(),Ae=c(we.x);if(Ae===Nn)return;const _e=c(ge*c(de+Ae*V));if(_e===Nn)return;let ct=(we.x===Ae?0:2)|Number(we.y&yt),Ne=_e;return L&&b(_e)&&(Ne=g(_e),ct^=1),new A(Ae,Ne,ct)}return{seed:ce,k2sig:le}}const F={lowS:t.lowS,prehash:!1},H={lowS:t.lowS,prehash:!1};function z(U,K,ee=F){const{seed:q,k2sig:O}=M(U,K,ee),L=t;return F3(L.hash.outputLen,L.nByteLength,L.hmac)(q,O)}f.BASE._setWindowSize(8);function Q(U,K,ee,q=H){var ct;const O=U;K=wr("msgHash",K),ee=wr("publicKey",ee);const{lowS:L,prehash:Y,format:C}=q;if(sm(q),"strict"in q)throw new Error("options.strict was renamed to lowS");if(C!==void 0&&C!=="compact"&&C!=="der")throw new Error("format must be compact or der");const $=typeof O=="string"||ec(O),V=!$&&!C&&typeof O=="object"&&O!==null&&typeof O.r=="bigint"&&typeof O.s=="bigint";if(!$&&!V)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let ie,ce;try{if(V&&(ie=new A(O.r,O.s)),$){try{C!=="compact"&&(ie=A.fromDER(O))}catch(Ne){if(!(Ne instanceof On.Err))throw Ne}!ie&&C!=="der"&&(ie=A.fromCompact(O))}ce=f.fromHex(ee)}catch{return!1}if(!ie||L&&ie.hasHighS())return!1;Y&&(K=t.hash(K));const{r:de,s:le}=ie,oe=_(K),ae=u(le),ge=c(oe*ae),we=c(de*ae),Ae=(ct=f.BASE.multiplyAndAddUnsafe(ce,ge,we))==null?void 0:ct.toAffine();return Ae?c(Ae.x)===de:!1}return{CURVE:t,getPublicKey:w,getSharedSecret:S,sign:z,verify:Q,ProjectivePoint:f,Signature:A,utils:k}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function XT(e){return{hash:e,hmac:(t,...r)=>o2(e,t,Y8(...r)),randomBytes:Q8}}function of(e,t){const r=n=>KT({...e,...XT(n)});return{...r(t),create:r}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const w2=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),am=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),JT=BigInt(0),YT=BigInt(1),yh=BigInt(2),om=(e,t)=>(e+t/yh)/t;function ZT(e){const t=w2,r=BigInt(3),n=BigInt(6),i=BigInt(11),s=BigInt(22),a=BigInt(23),o=BigInt(44),c=BigInt(88),u=e*e*e%t,f=u*u*e%t,l=br(f,r,t)*f%t,h=br(l,r,t)*f%t,d=br(h,yh,t)*u%t,b=br(d,i,t)*d%t,g=br(b,s,t)*b%t,x=br(g,o,t)*g%t,A=br(x,c,t)*x%t,k=br(A,o,t)*g%t,w=br(k,r,t)*f%t,v=br(w,a,t)*b%t,S=br(v,n,t)*u%t,I=br(S,yh,t);if(!mh.eql(mh.sqr(I),e))throw new Error("Cannot find square root");return I}const mh=ga(w2,void 0,void 0,{sqrt:ZT}),cf=of({a:JT,b:BigInt(7),Fp:mh,n:am,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=am,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-YT*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,a=BigInt("0x100000000000000000000000000000000"),o=om(s*e,t),c=om(-n*e,t);let u=Wt(e-o*r-c*i,t),f=Wt(-o*n-c*s,t);const l=u>a,h=f>a;if(l&&(u=t-u),h&&(f=t-f),u>a||f>a)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:l,k1:u,k2neg:h,k2:f}}}},k0),QT=Object.freeze(Object.defineProperty({__proto__:null,secp256k1:cf},Symbol.toStringTag,{value:"Module"}));function uf(e,t={}){const{recovered:r}=t;if(typeof e.r>"u")throw new ul({signature:e});if(typeof e.s>"u")throw new ul({signature:e});if(r&&typeof e.yParity>"u")throw new ul({signature:e});if(e.r<0n||e.r>Zy)throw new aI({value:e.r});if(e.s<0n||e.s>Zy)throw new oI({value:e.s});if(typeof e.yParity=="number"&&e.yParity!==0&&e.yParity!==1)throw new lf({value:e.yParity})}function eI(e){return rp(bt(e))}function rp(e){if(e.length!==130&&e.length!==132)throw new sI({signature:e});const t=BigInt(Ee(e,0,32)),r=BigInt(Ee(e,32,64)),n=(()=>{const i=+`0x${e.slice(130)}`;if(!Number.isNaN(i))try{return ip(i)}catch{throw new lf({value:i})}})();return typeof n>"u"?{r:t,s:r}:{r:t,s:r,yParity:n}}function v2(e){if(!(typeof e.r>"u")&&!(typeof e.s>"u"))return ff(e)}function ff(e){const t=typeof e=="string"?rp(e):e instanceof Uint8Array?eI(e):typeof e.r=="string"?np(e):e.v?tI(e):{r:e.r,s:e.s,...typeof e.yParity<"u"?{yParity:e.yParity}:{}};return uf(t),t}function tI(e){return{r:e.r,s:e.s,yParity:ip(e.v)}}function np(e){const t=(()=>{const r=e.v?Number(e.v):void 0;let n=e.yParity?Number(e.yParity):void 0;if(typeof r=="number"&&typeof n!="number"&&(n=ip(r)),typeof n!="number")throw new lf({value:e.yParity});return n})();return{r:BigInt(e.r),s:BigInt(e.s),yParity:t}}function rI(e){const[t,r,n]=e;return ff({r:r==="0x"?0n:BigInt(r),s:n==="0x"?0n:BigInt(n),yParity:t==="0x"?0:Number(t)})}function nI(e){uf(e);const t=e.r,r=e.s;return Je(te(t,{size:32}),te(r,{size:32}),typeof e.yParity=="number"?te(sp(e.yParity),{size:1}):"0x")}function E2(e){const{r:t,s:r,yParity:n}=e;return{r:te(t,{size:32}),s:te(r,{size:32}),yParity:n===0?"0x0":"0x1"}}function iI(e){const{r:t,s:r,yParity:n}=e;return[n?"0x01":"0x",t===0n?"0x":nh(te(t)),r===0n?"0x":nh(te(r))]}function ip(e){if(e===0||e===27)return 0;if(e===1||e===28)return 1;if(e>=35)return e%2===0?1:0;throw new cI({value:e})}function sp(e){if(e===0)return 27;if(e===1)return 28;throw new lf({value:e})}class sI extends se{constructor({signature:t}){super(`Value \`${t}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${rt(Zu(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class ul extends se{constructor({signature:t}){super(`Signature \`${rc(t)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}}class aI extends se{constructor({value:t}){super(`Value \`${t}\` 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 oI extends se{constructor({value:t}){super(`Value \`${t}\` 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 lf extends se{constructor({value:t}){super(`Value \`${t}\` 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 cI extends se{constructor({value:t}){super(`Value \`${t}\` 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 uI(e,t={}){return typeof e.chainId=="string"?x2(e):{...e,...t.signature}}function x2(e){const{address:t,chainId:r,nonce:n}=e,i=v2(e);return{address:t,chainId:Number(r),nonce:BigInt(n),...i}}function fI(e){return e.map(x2)}function lI(e){const{address:t,chainId:r,nonce:n,...i}=e;return{address:t,chainId:te(r),nonce:te(n),...E2(i)}}function dI(e){return e.map(lI)}function A2(e){return Jc(hI(e))}function hI(e){const{payload:t,signature:r}=e,{r:n,s:i,yParity:s}=r,o=new cf.Signature(BigInt(n),BigInt(i)).addRecoveryBit(s).recoverPublicKey(Zu(t).substring(2));return Dk(o)}function pI(e){const{address:t,hash:r,payload:n,publicKey:i,signature:s}=e;return t?fh(t,A2({payload:n,signature:s})):cf.verify(s,$0(n),Vk(i),...r?[{prehash:!0,lowS:!0}]:[])}const yI="0x8010801080108010801080108010801080108010801080108010801080108010",mI=e2("(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data");function S2(e){if(typeof e=="string"){if(Ee(e,-32)!==yI)throw new wI(e)}else uf(e.authorization)}function bI(e){S2(e);const t=Po(Ee(e,-64,-32)),r=Ee(e,-t-64,-64),n=Ee(e,0,-t-64),[i,s,a]=wT(mI,r);return{authorization:uI({address:i.delegation,chainId:Number(i.chainId),nonce:i.nonce,yParity:i.yParity,r:i.r,s:i.s}),signature:n,...a&&a!=="0x"?{data:a,to:s}:{}}}function gI(e){try{return S2(e),!0}catch{return!1}}let wI=class extends se{constructor(t){super(`Value \`${t}\` is an invalid ERC-8010 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc8010.InvalidWrappedSignatureError"})}};function vI(e){return e.map(t=>({...t,value:BigInt(t.value)}))}function EI(e){return{...e,balance:e.balance?BigInt(e.balance):void 0,nonce:e.nonce?Sr(e.nonce):void 0,storageProof:e.storageProof?vI(e.storageProof):void 0}}async function xI(e,{address:t,blockNumber:r,blockTag:n,storageKeys:i}){const s=n??"latest",a=r!==void 0?J(r):void 0,o=await e.request({method:"eth_getProof",params:[t,i,a||s]});return EI(o)}async function AI(e,{address:t,blockNumber:r,blockTag:n="latest",slot:i}){const s=r!==void 0?J(r):void 0;return await e.request({method:"eth_getStorageAt",params:[t,i,s||n]})}async function ap(e,{blockHash:t,blockNumber:r,blockTag:n,hash:i,index:s,sender:a,nonce:o}){var h,d,b;const c=n||"latest",u=r!==void 0?J(r):void 0;let f=null;if(i?f=await e.request({method:"eth_getTransactionByHash",params:[i]},{dedupe:!0}):t?f=await e.request({method:"eth_getTransactionByBlockHashAndIndex",params:[t,J(s)]},{dedupe:!0}):typeof s=="number"?f=await e.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[u||c,J(s)]},{dedupe:!!u}):a&&typeof o=="number"&&(f=await e.request({method:"eth_getTransactionBySenderAndNonce",params:[a,J(o)]},{dedupe:!0})),!f)throw new B1({blockHash:t,blockNumber:r,blockTag:c,hash:i,index:s});return(((b=(d=(h=e.chain)==null?void 0:h.formatters)==null?void 0:d.transaction)==null?void 0:b.format)||ha)(f,"getTransaction")}async function SI(e,{hash:t,transactionReceipt:r}){const[n,i]=await Promise.all([re(e,sc,"getBlockNumber")({}),t?re(e,ap,"getTransaction")({hash:t}):void 0]),s=(r==null?void 0:r.blockNumber)||(i==null?void 0:i.blockNumber);return s?n-s+1n:0n}async function Yc(e,{hash:t}){var i,s,a;const r=await e.request({method:"eth_getTransactionReceipt",params:[t]},{dedupe:!0});if(!r)throw new C1({hash:t});return(((a=(s=(i=e.chain)==null?void 0:i.formatters)==null?void 0:s.transactionReceipt)==null?void 0:a.format)||sf)(r,"getTransactionReceipt")}async function kI(e,t){var k;const{account:r,authorizationList:n,allowFailure:i=!0,blockNumber:s,blockOverrides:a,blockTag:o,stateOverride:c}=t,u=t.contracts,{batchSize:f=t.batchSize??1024,deployless:l=t.deployless??!1}=typeof((k=e.batch)==null?void 0:k.multicall)=="object"?e.batch.multicall:{},h=(()=>{if(t.multicallAddress)return t.multicallAddress;if(l)return null;if(e.chain)return ma({blockNumber:s,chain:e.chain,contract:"multicall3"});throw new Error("client chain not configured. multicallAddress is required.")})(),d=[[]];let b=0,g=0;for(let w=0;w<u.length;w++){const{abi:v,address:S,args:I,functionName:_}=u[w];try{const R=hr({abi:v,args:I,functionName:_});g+=(R.length-2)/2,f>0&&g>f&&d[b].length>0&&(b++,g=(R.length-2)/2,d[b]=[]),d[b]=[...d[b],{allowFailure:!0,callData:R,target:S}]}catch(R){const B=us(R,{abi:v,address:S,args:I,docsPath:"/docs/contract/multicall",functionName:_,sender:r});if(!i)throw B;d[b]=[...d[b],{allowFailure:!0,callData:"0x",target:S}]}}const x=await Promise.allSettled(d.map(w=>re(e,kr,"readContract")({...h===null?{code:M0}:{address:h},abi:fu,account:r,args:[w],authorizationList:n,blockNumber:s,blockOverrides:a,blockTag:o,functionName:"aggregate3",stateOverride:c}))),A=[];for(let w=0;w<x.length;w++){const v=x[w];if(v.status==="rejected"){if(!i)throw v.reason;for(let I=0;I<d[w].length;I++)A.push({status:"failure",error:v.reason,result:void 0});continue}const S=v.value;for(let I=0;I<S.length;I++){const{returnData:_,success:R}=S[I],{callData:B}=d[w][I],{abi:M,address:F,functionName:H,args:z}=u[A.length];try{if(B==="0x")throw new qo;if(!R)throw new zu({data:_});const Q=Es({abi:M,args:z,data:_,functionName:H});A.push(i?{result:Q,status:"success"}:Q)}catch(Q){const U=us(Q,{abi:M,address:F,args:z,docsPath:"/docs/contract/multicall",functionName:H});if(!i)throw U;A.push({error:U,result:void 0,status:"failure"})}}}if(A.length!==u.length)throw new G("multicall results mismatch");return A}async function bh(e,t){const{blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",blocks:i,returnFullTransactions:s,traceTransfers:a,validation:o}=t;try{const c=[];for(const h of i){const d=h.blockOverrides?mw(h.blockOverrides):void 0,b=h.calls.map(x=>{const A=x,k=A.account?Me(A.account):void 0,w=A.abi?hr(A):A.data,v={...A,account:k,data:A.dataSuffix?lr([w||"0x",A.dataSuffix]):w,from:A.from??(k==null?void 0:k.address)};return qn(v),yn(v)}),g=h.stateOverrides?g0(h.stateOverrides):void 0;c.push({blockOverrides:d,calls:b,stateOverrides:g})}const f=(typeof r=="bigint"?J(r):void 0)||n;return(await e.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:s,traceTransfers:a,validation:o},f]})).map((h,d)=>({...v0(h),calls:h.calls.map((b,g)=>{var M,F;const{abi:x,args:A,functionName:k,to:w}=i[d].calls[g],v=((M=b.error)==null?void 0:M.data)??b.returnData,S=BigInt(b.gasUsed),I=(F=b.logs)==null?void 0:F.map(H=>Dn(H)),_=b.status==="0x1"?"success":"failure",R=x&&_==="success"&&v!=="0x"?Es({abi:x,data:v,functionName:k}):null,B=(()=>{var z;if(_==="success")return;let H;if(((z=b.error)==null?void 0:z.data)==="0x"?H=new qo:b.error&&(H=new zu(b.error)),!!H)return us(H,{abi:x??[],address:w??"0x",args:A,functionName:k??"<unknown>"})})();return{data:v,gasUsed:S,logs:I,status:_,..._==="success"?{result:R}:{error:B}}})}))}catch(c){const u=c,f=Gu(u,{});throw f instanceof Zo?u:f}}function gh(e){let t=!0,r="",n=0,i="",s=!1;for(let a=0;a<e.length;a++){const o=e[a];if(["(",")",","].includes(o)&&(t=!0),o==="("&&n++,o===")"&&n--,!!t){if(n===0){if(o===" "&&["event","function","error",""].includes(i))i="";else if(i+=o,o===")"){s=!0;break}continue}if(o===" "){e[a-1]!==","&&r!==","&&r!==",("&&(r="",t=!1);continue}i+=o,r+=o}}if(!s)throw new se("Unable to normalize signature.");return i}function wh(e,t){const r=typeof e,n=t.type;switch(n){case"address":return hu(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in t?Object.values(t.components).every((i,s)=>wh(Object.values(e)[s],i)):/^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"||e instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(e)&&e.every(i=>wh(i,{...t,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function k2(e,t,r){for(const n in e){const i=e[n],s=t[n];if(i.type==="tuple"&&s.type==="tuple"&&"components"in i&&"components"in s)return k2(i.components,s.components,r[n]);const a=[i.type,s.type];if(a.includes("address")&&a.includes("bytes20")?!0:a.includes("address")&&a.includes("string")?hu(r[n],{strict:!1}):a.includes("address")&&a.includes("bytes")?hu(r[n],{strict:!1}):!1)return a}}function T2(e,t={}){const{prepare:r=!0}=t,n=Array.isArray(e)||typeof e=="string"?dy(e):e;return{...n,...r?{hash:js(n)}:{}}}function df(e,t,r){const{args:n=[],prepare:i=!0}=r??{},s=_r(t,{strict:!1}),a=e.filter(u=>s?u.type==="function"||u.type==="error"?I2(u)===Ee(t,0,4):u.type==="event"?js(u)===t:!1:"name"in u&&u.name===t);if(a.length===0)throw new pu({name:t});if(a.length===1)return{...a[0],...i?{hash:js(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,...i?{hash:js(u)}:{}};continue}if(!u.inputs||u.inputs.length===0||u.inputs.length!==n.length)continue;if(n.every((l,h)=>{const d="inputs"in u&&u.inputs[h];return d?wh(l,d):!1})){if(o&&"inputs"in o&&o.inputs){const l=k2(u.inputs,o.inputs,n);if(l)throw new II({abiItem:u,type:l[0]},{abiItem:o,type:l[1]})}o=u}}const c=(()=>{if(o)return o;const[u,...f]=a;return{...u,overloads:f}})();if(!c)throw new pu({name:t});return{...c,...i?{hash:js(c)}:{}}}function I2(...e){const t=(()=>{if(Array.isArray(e[0])){const[r,n]=e;return df(r,n)}return e[0]})();return Ee(js(t),0,4)}function TI(...e){const t=(()=>{if(Array.isArray(e[0])){const[n,i]=e;return df(n,i)}return e[0]})(),r=typeof t=="string"?t:su(t);return gh(r)}function js(...e){const t=(()=>{if(Array.isArray(e[0])){const[r,n]=e;return df(r,n)}return e[0]})();return typeof t!="string"&&"hash"in t&&t.hash?t.hash:cc(nc(TI(t)))}class II extends se{constructor(t,r){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${t.type}\` in \`${gh(su(t.abiItem))}\`, and`,`\`${r.type}\` in \`${gh(su(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 pu extends se{constructor({name:t,data:r,type:n="item"}){const i=t?` with name "${t}"`:r?` with data "${r}"`:"";super(`ABI ${n}${i} not found.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}function _I(...e){var s;const[t,r]=(()=>{if(Array.isArray(e[0])){const[a,o]=e;return[OI(a),o]}return e})(),{bytecode:n,args:i}=r;return Je(n,(s=t.inputs)!=null&&s.length&&(i!=null&&i.length)?ep(t.inputs,i):"0x")}function PI(e){return T2(e)}function OI(e){const t=e.find(r=>r.type==="constructor");if(!t)throw new pu({name:"constructor"});return t}function BI(...e){const[t,r=[]]=(()=>{if(Array.isArray(e[0])){const[u,f,l]=e;return[cm(u,f,{args:l}),l]}const[o,c]=e;return[o,c]})(),{overloads:n}=t,i=n?cm([t,...n],t.name,{args:r}):t,s=CI(i),a=r.length>0?ep(i.inputs,r):void 0;return a?Je(s,a):s}function _s(e,t={}){return T2(e,t)}function cm(e,t,r){const n=df(e,t,r);if(n.type!=="function")throw new pu({name:t,type:"function"});return n}function CI(e){return I2(e)}const RI="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",tn="0x0000000000000000000000000000000000000000",NI="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033";async function UI(e,t){const{blockNumber:r,blockTag:n,calls:i,stateOverrides:s,traceAssetChanges:a,traceTransfers:o,validation:c}=t,u=t.account?Me(t.account):void 0;if(a&&!u)throw new G("`account` is required when `traceAssetChanges` is true");const f=u?_I(PI("constructor(bytes, bytes)"),{bytecode:vw,args:[NI,BI(_s("function getBalance(address)"),[u.address])]}):void 0,l=a?await Promise.all(t.calls.map(async q=>{if(!q.data&&!q.abi)return;const{accessList:O}=await Lw(e,{account:u.address,...q,data:q.abi?hr(q):q.data});return O.map(({address:L,storageKeys:Y})=>Y.length>0?L:null)})).then(q=>q.flat().filter(Boolean)):[],h=await bh(e,{blockNumber:r,blockTag:n,blocks:[...a?[{calls:[{data:f}],stateOverrides:s},{calls:l.map((q,O)=>({abi:[_s("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[u.address],to:q,from:tn,nonce:O})),stateOverrides:[{address:tn,nonce:0}]}]:[],{calls:[...i,{}].map(q=>({...q,from:u==null?void 0:u.address})),stateOverrides:s},...a?[{calls:[{data:f}]},{calls:l.map((q,O)=>({abi:[_s("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[u.address],to:q,from:tn,nonce:O})),stateOverrides:[{address:tn,nonce:0}]},{calls:l.map((q,O)=>({to:q,abi:[_s("function decimals() returns (uint256)")],functionName:"decimals",from:tn,nonce:O})),stateOverrides:[{address:tn,nonce:0}]},{calls:l.map((q,O)=>({to:q,abi:[_s("function tokenURI(uint256) returns (string)")],functionName:"tokenURI",args:[0n],from:tn,nonce:O})),stateOverrides:[{address:tn,nonce:0}]},{calls:l.map((q,O)=>({to:q,abi:[_s("function symbol() returns (string)")],functionName:"symbol",from:tn,nonce:O})),stateOverrides:[{address:tn,nonce:0}]}]:[]],traceTransfers:o,validation:c}),d=a?h[2]:h[0],[b,g,,x,A,k,w,v]=a?h:[],{calls:S,...I}=d,_=S.slice(0,-1)??[],R=(b==null?void 0:b.calls)??[],B=(g==null?void 0:g.calls)??[],M=[...R,...B].map(q=>q.status==="success"?mt(q.data):null),F=(x==null?void 0:x.calls)??[],H=(A==null?void 0:A.calls)??[],z=[...F,...H].map(q=>q.status==="success"?mt(q.data):null),Q=((k==null?void 0:k.calls)??[]).map(q=>q.status==="success"?q.result:null),U=((v==null?void 0:v.calls)??[]).map(q=>q.status==="success"?q.result:null),K=((w==null?void 0:w.calls)??[]).map(q=>q.status==="success"?q.result:null),ee=[];for(const[q,O]of z.entries()){const L=M[q];if(typeof O!="bigint"||typeof L!="bigint")continue;const Y=Q[q-1],C=U[q-1],$=K[q-1],V=q===0?{address:RI,decimals:18,symbol:"ETH"}:{address:l[q-1],decimals:$||Y?Number(Y??1):void 0,symbol:C??void 0};ee.some(ie=>ie.token.address===V.address)||ee.push({token:V,value:{pre:L,post:O,diff:O-L}})}return{assetChanges:ee,block:I,results:_}}const _2="0x6492649264926492649264926492649264926492649264926492649264926492";function FI(e){if(Ee(e,-32)!==_2)throw new jI(e)}function $I(e){const{data:t,signature:r,to:n}=e;return Je(ep(e2("address, bytes, bytes"),[n,t,r]),_2)}function MI(e){try{return FI(e),!0}catch{return!1}}class jI extends se{constructor(t){super(`Value \`${t}\` is an invalid ERC-6492 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc6492.InvalidWrappedSignatureError"})}}function HI({r:e,s:t,to:r="hex",v:n,yParity:i}){const s=(()=>{if(i===0||i===1)return i;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 cf.Signature(mt(e),mt(t)).toCompactHex()}${s===0?"1b":"1c"}`;return r==="hex"?a:hn(a)}async function uc(e,t){var c,u,f,l;const{address:r,chain:n=e.chain,hash:i,erc6492VerifierAddress:s=t.universalSignatureVerifierAddress??((u=(c=n==null?void 0:n.contracts)==null?void 0:c.erc6492Verifier)==null?void 0:u.address),multicallAddress:a=t.multicallAddress??((l=(f=n==null?void 0:n.contracts)==null?void 0:f.multicall3)==null?void 0:l.address)}=t;if(n!=null&&n.verifyHash)return await n.verifyHash(e,t);const o=(()=>{const h=t.signature;return Dr(h)?h:typeof h=="object"&&"r"in h&&"s"in h?HI(h):ot(h)})();try{return gI(o)?await LI(e,{...t,multicallAddress:a,signature:o}):await DI(e,{...t,verifierAddress:s,signature:o})}catch(h){try{if(pa(f0(r),await F1({hash:i,signature:o})))return!0}catch{}if(h instanceof hs)return!1;throw h}}async function LI(e,t){var x;const{address:r,blockNumber:n,blockTag:i,hash:s,multicallAddress:a}=t,{authorization:o,data:c,signature:u,to:f}=bI(t.signature);if(await du(e,{address:r,blockNumber:n,blockTag:i})===Wr(["0xef0100",o.address]))return await zI(e,{address:r,blockNumber:n,blockTag:i,hash:s,signature:u});const h={address:o.address,chainId:Number(o.chainId),nonce:Number(o.nonce),r:J(o.r,{size:32}),s:J(o.s,{size:32}),yParity:o.yParity};if(!await gk({address:r,authorization:h}))throw new hs;const b=await re(e,kr,"readContract")({...a?{address:a}:{code:M0},authorizationList:[h],abi:fu,blockNumber:n,blockTag:"pending",functionName:"aggregate3",args:[[...c?[{allowFailure:!0,target:f??r,callData:c}]:[],{allowFailure:!0,target:r,callData:hr({abi:ww,functionName:"isValidSignature",args:[s,u]})}]]}),g=(x=b[b.length-1])==null?void 0:x.returnData;if(g!=null&&g.startsWith("0x1626ba7e"))return!0;throw new hs}async function DI(e,t){const{address:r,factory:n,factoryData:i,hash:s,signature:a,verifierAddress:o,...c}=t,u=await(async()=>!n&&!i||MI(a)?a:$I({data:i,signature:a,to:n}))(),f=o?{to:o,data:hr({abi:Gy,functionName:"isValidSig",args:[r,s,u]}),...c}:{data:ef({abi:Gy,args:[r,s,u],bytecode:mS}),...c},{data:l}=await re(e,ic,"call")(f).catch(h=>{throw h instanceof N1?new hs:h});if(B8(l??"0x0"))return!0;throw new hs}async function zI(e,t){const{address:r,blockNumber:n,blockTag:i,hash:s,signature:a}=t;if((await re(e,kr,"readContract")({address:r,abi:ww,args:[s,a],blockNumber:n,blockTag:i,functionName:"isValidSignature"}).catch(c=>{throw c instanceof U1?new hs:c})).startsWith("0x1626ba7e"))return!0;throw new hs}let hs=class extends Error{};async function VI(e,{address:t,message:r,factory:n,factoryData:i,signature:s,...a}){const o=Vw(r);return re(e,uc,"verifyHash")({address:t,factory:n,factoryData:i,hash:o,signature:s,...a})}async function GI(e,t){const{address:r,factory:n,factoryData:i,signature:s,message:a,primaryType:o,types:c,domain:u,...f}=t,l=Nk({message:a,primaryType:o,types:c,domain:u});return re(e,uc,"verifyHash")({address:r,factory:n,factoryData:i,hash:l,signature:s,...f})}function P2(e,{emitOnBegin:t=!1,emitMissed:r=!1,onBlockNumber:n,onError:i,poll:s,pollingInterval:a=e.pollingInterval}){const o=typeof s<"u"?s:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"));let c;return o?(()=>{const l=at(["watchBlockNumber",e.uid,t,r,a]);return zn(l,{onBlockNumber:n,onError:i},h=>ba(async()=>{var d;try{const b=await re(e,sc,"getBlockNumber")({cacheTime:0});if(c!==void 0){if(b===c)return;if(b-c>1&&r)for(let g=c+1n;g<b;g++)h.onBlockNumber(g,c),c=g}(c===void 0||b>c)&&(h.onBlockNumber(b,c),c=b)}catch(b){(d=h.onError)==null||d.call(h,b)}},{emitOnBegin:t,interval:a}))})():(()=>{const l=at(["watchBlockNumber",e.uid,t,r]);return zn(l,{onBlockNumber:n,onError:i},h=>{let d=!0,b=()=>d=!1;return(async()=>{try{const g=(()=>{if(e.transport.type==="fallback"){const A=e.transport.transports.find(k=>k.config.type==="webSocket"||k.config.type==="ipc");return A?A.value:e.transport}return e.transport})(),{unsubscribe:x}=await g.subscribe({params:["newHeads"],onData(A){var w;if(!d)return;const k=mt((w=A.result)==null?void 0:w.number);h.onBlockNumber(k,c),c=k},onError(A){var k;(k=h.onError)==null||k.call(h,A)}});b=x,d||b()}catch(g){i==null||i(g)}})(),()=>b()})})()}async function O2(e,t){const{checkReplacement:r=!0,confirmations:n=1,hash:i,onReplaced:s,retryCount:a=6,retryDelay:o=({count:S})=>~~(1<<S)*200,timeout:c=18e4}=t,u=at(["waitForTransactionReceipt",e.uid,i]),f=(()=>{var S;return t.pollingInterval?t.pollingInterval:(S=e.chain)!=null&&S.experimental_preconfirmationTime?e.chain.experimental_preconfirmationTime:e.pollingInterval})();let l,h,d,b=!1,g,x;const{promise:A,resolve:k,reject:w}=j0(),v=c?setTimeout(()=>{x==null||x(),g==null||g(),w(new KA({hash:i}))},c):void 0;return g=zn(u,{onReplaced:s,resolve:k,reject:w},async S=>{if(d=await re(e,Yc,"getTransactionReceipt")({hash:i}).catch(()=>{}),d&&n<=1){clearTimeout(v),S.resolve(d),g==null||g();return}x=re(e,P2,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:f,async onBlockNumber(I){const _=B=>{clearTimeout(v),x==null||x(),B(),g==null||g()};let R=I;if(!b)try{if(d){if(n>1&&(!d.blockNumber||R-d.blockNumber+1n<n))return;_(()=>S.resolve(d));return}if(r&&!l&&(b=!0,await lu(async()=>{l=await re(e,ap,"getTransaction")({hash:i}),l.blockNumber&&(R=l.blockNumber)},{delay:o,retryCount:a}),b=!1),d=await re(e,Yc,"getTransactionReceipt")({hash:i}),n>1&&(!d.blockNumber||R-d.blockNumber+1n<n))return;_(()=>S.resolve(d))}catch(B){if(B instanceof B1||B instanceof C1){if(!l){b=!1;return}try{h=l,b=!0;const M=await lu(()=>re(e,$r,"getBlock")({blockNumber:R,includeTransactions:!0}),{delay:o,retryCount:a,shouldRetry:({error:z})=>z instanceof H1});b=!1;const F=M.transactions.find(({from:z,nonce:Q})=>z===h.from&&Q===h.nonce);if(!F||(d=await re(e,Yc,"getTransactionReceipt")({hash:F.hash}),n>1&&(!d.blockNumber||R-d.blockNumber+1n<n)))return;let H="replaced";F.to===h.to&&F.value===h.value&&F.input===h.input?H="repriced":F.from===F.to&&F.value===0n&&(H="cancelled"),_(()=>{var z;(z=S.onReplaced)==null||z.call(S,{reason:H,replacedTransaction:h,transaction:F,transactionReceipt:d}),S.resolve(d)})}catch(M){_(()=>S.reject(M))}}else _(()=>S.reject(B))}}})}),A}function qI(e,{blockTag:t=e.experimental_blockTag??"latest",emitMissed:r=!1,emitOnBegin:n=!1,onBlock:i,onError:s,includeTransactions:a,poll:o,pollingInterval:c=e.pollingInterval}){const u=typeof o<"u"?o:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")),f=a??!1;let l;return u?(()=>{const b=at(["watchBlocks",e.uid,t,r,n,f,c]);return zn(b,{onBlock:i,onError:s},g=>ba(async()=>{var x;try{const A=await re(e,$r,"getBlock")({blockTag:t,includeTransactions:f});if(A.number!==null&&(l==null?void 0:l.number)!=null){if(A.number===l.number)return;if(A.number-l.number>1&&r)for(let k=(l==null?void 0:l.number)+1n;k<A.number;k++){const w=await re(e,$r,"getBlock")({blockNumber:k,includeTransactions:f});g.onBlock(w,l),l=w}}((l==null?void 0:l.number)==null||t==="pending"&&(A==null?void 0:A.number)==null||A.number!==null&&A.number>l.number)&&(g.onBlock(A,l),l=A)}catch(A){(x=g.onError)==null||x.call(g,A)}},{emitOnBegin:n,interval:c}))})():(()=>{let b=!0,g=!0,x=()=>b=!1;return(async()=>{try{n&&re(e,$r,"getBlock")({blockTag:t,includeTransactions:f}).then(w=>{b&&g&&(i(w,void 0),g=!1)}).catch(s);const A=(()=>{if(e.transport.type==="fallback"){const w=e.transport.transports.find(v=>v.config.type==="webSocket"||v.config.type==="ipc");return w?w.value:e.transport}return e.transport})(),{unsubscribe:k}=await A.subscribe({params:["newHeads"],async onData(w){var S;if(!b)return;const v=await re(e,$r,"getBlock")({blockNumber:(S=w.result)==null?void 0:S.number,includeTransactions:f}).catch(()=>{});b&&(i(v,l),g=!1,l=v)},onError(w){s==null||s(w)}});x=k,b||x()}catch(A){s==null||s(A)}})(),()=>x()})()}function WI(e,{address:t,args:r,batch:n=!0,event:i,events:s,fromBlock:a,onError:o,onLogs:c,poll:u,pollingInterval:f=e.pollingInterval,strict:l}){const h=typeof u<"u"?u:typeof a=="bigint"?!0:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")),d=l??!1;return h?(()=>{const x=at(["watchEvent",t,r,n,e.uid,i,f,a]);return zn(x,{onLogs:c,onError:o},A=>{let k;a!==void 0&&(k=a-1n);let w,v=!1;const S=ba(async()=>{var I;if(!v){try{w=await re(e,Dw,"createEventFilter")({address:t,args:r,event:i,events:s,strict:d,fromBlock:a})}catch{}v=!0;return}try{let _;if(w)_=await re(e,tf,"getFilterChanges")({filter:w});else{const R=await re(e,sc,"getBlockNumber")({});k&&k!==R?_=await re(e,C0,"getLogs")({address:t,args:r,event:i,events:s,fromBlock:k+1n,toBlock:R}):_=[],k=R}if(_.length===0)return;if(n)A.onLogs(_);else for(const R of _)A.onLogs([R])}catch(_){w&&_ instanceof _i&&(v=!1),(I=A.onError)==null||I.call(A,_)}},{emitOnBegin:!0,interval:f});return async()=>{w&&await re(e,rf,"uninstallFilter")({filter:w}),S()}})})():(()=>{let x=!0,A=()=>x=!1;return(async()=>{try{const k=(()=>{if(e.transport.type==="fallback"){const I=e.transport.transports.find(_=>_.config.type==="webSocket"||_.config.type==="ipc");return I?I.value:e.transport}return e.transport})(),w=s??(i?[i]:void 0);let v=[];w&&(v=[w.flatMap(_=>Xo({abi:[_],eventName:_.name,args:r}))],i&&(v=v[0]));const{unsubscribe:S}=await k.subscribe({params:["logs",{address:t,topics:v}],onData(I){var R;if(!x)return;const _=I.result;try{const{eventName:B,args:M}=ou({abi:w??[],data:_.data,topics:_.topics,strict:d}),F=Dn(_,{args:M,eventName:B});c([F])}catch(B){let M,F;if(B instanceof au||B instanceof i0){if(l)return;M=B.abiItem.name,F=(R=B.abiItem.inputs)==null?void 0:R.some(z=>!("name"in z&&z.name))}const H=Dn(_,{args:F?[]:{},eventName:M});c([H])}},onError(I){o==null||o(I)}});A=S,x||A()}catch(k){o==null||o(k)}})(),()=>A()})()}function KI(e,{batch:t=!0,onError:r,onTransactions:n,poll:i,pollingInterval:s=e.pollingInterval}){return(typeof i<"u"?i:e.transport.type!=="webSocket"&&e.transport.type!=="ipc")?(()=>{const u=at(["watchPendingTransactions",e.uid,t,s]);return zn(u,{onTransactions:n,onError:r},f=>{let l;const h=ba(async()=>{var d;try{if(!l)try{l=await re(e,zw,"createPendingTransactionFilter")({});return}catch(g){throw h(),g}const b=await re(e,tf,"getFilterChanges")({filter:l});if(b.length===0)return;if(t)f.onTransactions(b);else for(const g of b)f.onTransactions([g])}catch(b){(d=f.onError)==null||d.call(f,b)}},{emitOnBegin:!0,interval:s});return async()=>{l&&await re(e,rf,"uninstallFilter")({filter:l}),h()}})})():(()=>{let u=!0,f=()=>u=!1;return(async()=>{try{const{unsubscribe:l}=await e.transport.subscribe({params:["newPendingTransactions"],onData(h){if(!u)return;const d=h.result;n([d])},onError(h){r==null||r(h)}});f=l,u||f()}catch(l){r==null||r(l)}})(),()=>f()})()}function XI(e){var l,h,d;const{scheme:t,statement:r,...n}=((l=e.match(JI))==null?void 0:l.groups)??{},{chainId:i,expirationTime:s,issuedAt:a,notBefore:o,requestId:c,...u}=((h=e.match(YI))==null?void 0:h.groups)??{},f=(d=e.split("Resources:")[1])==null?void 0:d.split(`
|
|
71
|
+
- `).slice(1);return{...n,...u,...i?{chainId:Number(i)}:{},...s?{expirationTime:new Date(s)}:{},...a?{issuedAt:new Date(a)}:{},...o?{notBefore:new Date(o)}:{},...c?{requestId:c}:{},...f?{resources:f}:{},...t?{scheme:t}:{},...r?{statement:r}:{}}}const JI=/^(?:(?<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)?/,YI=/(?: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 ZI(e){const{address:t,domain:r,message:n,nonce:i,scheme:s,time:a=new Date}=e;if(r&&n.domain!==r||i&&n.nonce!==i||s&&n.scheme!==s||n.expirationTime&&a>=n.expirationTime||n.notBefore&&a<n.notBefore)return!1;try{if(!n.address||!pt(n.address,{strict:!1})||t&&!pa(n.address,t))return!1}catch{return!1}return!0}async function QI(e,t){const{address:r,domain:n,message:i,nonce:s,scheme:a,signature:o,time:c=new Date,...u}=t,f=XI(i);if(!f.address||!ZI({address:r,domain:n,message:f,nonce:s,scheme:a,time:c}))return!1;const h=Vw(i);return uc(e,{address:f.address,hash:h,signature:o,...u})}async function op(e,{serializedTransaction:t,throwOnReceiptRevert:r,timeout:n}){var o,c,u;const i=await e.request({method:"eth_sendRawTransactionSync",params:n?[t,J(n)]:[t]},{retryCount:0}),a=(((u=(c=(o=e.chain)==null?void 0:o.formatters)==null?void 0:c.transactionReceipt)==null?void 0:u.format)||sf)(i);if(a.status==="reverted"&&r)throw new R1({receipt:a});return a}function e_(e){return{call:t=>ic(e,t),createAccessList:t=>Lw(e,t),createBlockFilter:()=>ZS(e),createContractEventFilter:t=>p0(e,t),createEventFilter:t=>Dw(e,t),createPendingTransactionFilter:()=>zw(e),estimateContractGas:t=>ew(e,t),estimateGas:t=>O0(e,t),getBalance:t=>QS(e,t),getBlobBaseFee:()=>ek(e),getBlock:t=>$r(e,t),getBlockNumber:t=>sc(e,t),getBlockTransactionCount:t=>tk(e,t),getBytecode:t=>du(e,t),getChainId:()=>Ri(e),getCode:t=>du(e,t),getContractEvents:t=>R0(e,t),getEip712Domain:t=>nk(e,t),getEnsAddress:t=>FS(e,t),getEnsAvatar:t=>XS(e,t),getEnsName:t=>JS(e,t),getEnsResolver:t=>YS(e,t),getEnsText:t=>Hw(e,t),getFeeHistory:t=>ak(e,t),estimateFeesPerGas:t=>m3(e,t),getFilterChanges:t=>tf(e,t),getFilterLogs:t=>ok(e,t),getGasPrice:()=>E0(e),getLogs:t=>C0(e,t),getProof:t=>xI(e,t),estimateMaxPriorityFeePerGas:t=>y3(e,t),fillTransaction:t=>_0(e,t),getStorageAt:t=>AI(e,t),getTransaction:t=>ap(e,t),getTransactionConfirmations:t=>SI(e,t),getTransactionCount:t=>x0(e,t),getTransactionReceipt:t=>Yc(e,t),multicall:t=>kI(e,t),prepareTransactionRequest:t=>Qo(e,t),readContract:t=>kr(e,t),sendRawTransaction:t=>L0(e,t),sendRawTransactionSync:t=>op(e,t),simulate:t=>bh(e,t),simulateBlocks:t=>bh(e,t),simulateCalls:t=>UI(e,t),simulateContract:t=>kw(e,t),verifyHash:t=>uc(e,t),verifyMessage:t=>VI(e,t),verifySiweMessage:t=>QI(e,t),verifyTypedData:t=>GI(e,t),uninstallFilter:t=>rf(e,t),waitForTransactionReceipt:t=>O2(e,t),watchBlocks:t=>qI(e,t),watchBlockNumber:t=>P2(e,t),watchContractEvent:t=>Tw(e,t),watchEvent:t=>WI(e,t),watchPendingTransactions:t=>KI(e,t)}}function t_(e){const{key:t="public",name:r="Public Client"}=e;return Uw({...e,key:t,name:r,type:"publicClient"}).extend(e_)}async function r_(e,{chain:t}){const{id:r,name:n,nativeCurrency:i,rpcUrls:s,blockExplorers:a}=t;await e.request({method:"wallet_addEthereumChain",params:[{chainId:J(r),chainName:n,nativeCurrency:i,rpcUrls:s.default.http,blockExplorerUrls:a?Object.values(a).map(({url:o})=>o):void 0}]},{dedupe:!0,retryCount:0})}function n_(e,t){const{abi:r,args:n,bytecode:i,...s}=t,a=ef({abi:r,args:n,bytecode:i});return nf(e,{...s,...s.authorizationList?{to:null}:{},data:a})}async function i_(e){var r;return((r=e.account)==null?void 0:r.type)==="local"?[e.account.address]:(await e.request({method:"eth_accounts"},{dedupe:!0})).map(n=>Wo(n))}async function s_(e,t={}){const{account:r=e.account,chainId:n}=t,i=r?Me(r):void 0,s=n?[i==null?void 0:i.address,[J(n)]]:[i==null?void 0:i.address],a=await e.request({method:"wallet_getCapabilities",params:s}),o={};for(const[c,u]of Object.entries(a)){o[Number(c)]={};for(let[f,l]of Object.entries(u))f==="addSubAccount"&&(f="unstable_addSubAccount"),o[Number(c)][f]=l}return typeof n=="number"?o[n]:o}async function a_(e){return await e.request({method:"wallet_getPermissions"},{dedupe:!0})}async function B2(e,t){var c;const{account:r=e.account,chainId:n,nonce:i}=t;if(!r)throw new Ui({docsPath:"/docs/eip7702/prepareAuthorization"});const s=Me(r),a=(()=>{if(t.executor)return t.executor==="self"?t.executor:Me(t.executor)})(),o={address:t.contractAddress??t.address,chainId:n,nonce:i};return typeof o.chainId>"u"&&(o.chainId=((c=e.chain)==null?void 0:c.id)??await re(e,Ri,"getChainId")({})),typeof o.nonce>"u"&&(o.nonce=await re(e,x0,"getTransactionCount")({address:s.address,blockTag:"pending"}),(a==="self"||a!=null&&a.address&&pa(a.address,s.address))&&(o.nonce+=1)),o}async function o_(e){return(await e.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(r=>f0(r))}async function c_(e,t){return e.request({method:"wallet_requestPermissions",params:[t]},{retryCount:0})}async function u_(e,t){const{chain:r=e.chain}=t,n=t.timeout??Math.max(((r==null?void 0:r.blockTime)??0)*3,5e3),i=await Bw(e,t);return await Rw(e,{...t,id:i.id,timeout:n})}const fl=new la(128);async function C2(e,t){var I,_,R,B;const{account:r=e.account,assertChainId:n=!0,chain:i=e.chain,accessList:s,authorizationList:a,blobs:o,data:c,gas:u,gasPrice:f,maxFeePerBlobGas:l,maxFeePerGas:h,maxPriorityFeePerGas:d,nonce:b,pollingInterval:g,throwOnReceiptRevert:x,type:A,value:k,...w}=t,v=t.timeout??Math.max(((i==null?void 0:i.blockTime)??0)*3,5e3);if(typeof r>"u")throw new Ui({docsPath:"/docs/actions/wallet/sendTransactionSync"});const S=r?Me(r):null;try{qn(t);const M=await(async()=>{if(t.to)return t.to;if(t.to!==null&&a&&a.length>0)return await Vu({authorization:a[0]}).catch(()=>{throw new G("`to` is required. Could not infer from `authorizationList`.")})})();if((S==null?void 0:S.type)==="json-rpc"||S===null){let F;i!==null&&(F=await re(e,Ri,"getChainId")({}),n&&H0({currentChainId:F,chain:i}));const H=(R=(_=(I=e.chain)==null?void 0:I.formatters)==null?void 0:_.transactionRequest)==null?void 0:R.format,Q=(H||yn)({...da(w,{format:H}),accessList:s,account:S,authorizationList:a,blobs:o,chainId:F,data:c,gas:u,gasPrice:f,maxFeePerBlobGas:l,maxFeePerGas:h,maxPriorityFeePerGas:d,nonce:b,to:M,type:A,value:k},"sendTransaction"),U=fl.get(e.uid),K=U?"wallet_sendTransaction":"eth_sendTransaction",ee=await(async()=>{try{return await e.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 e.request({method:"wallet_sendTransaction",params:[Q]},{retryCount:0}).then(Y=>(fl.set(e.uid,!0),Y)).catch(Y=>{const C=Y;throw C.name==="MethodNotFoundRpcError"||C.name==="MethodNotSupportedRpcError"?(fl.set(e.uid,!1),L):C});throw L}})(),q=await re(e,O2,"waitForTransactionReceipt")({checkReplacement:!1,hash:ee,pollingInterval:g,timeout:v});if(x&&q.status==="reverted")throw new R1({receipt:q});return q}if((S==null?void 0:S.type)==="local"){const F=await re(e,Qo,"prepareTransactionRequest")({account:S,accessList:s,authorizationList:a,blobs:o,chain:i,data:c,gas:u,gasPrice:f,maxFeePerBlobGas:l,maxFeePerGas:h,maxPriorityFeePerGas:d,nonce:b,nonceManager:S.nonceManager,parameters:[...P0,"sidecars"],type:A,value:k,...w,to:M}),H=(B=i==null?void 0:i.serializers)==null?void 0:B.transaction,z=await S.signTransaction(F,{serializer:H});return await re(e,op,"sendRawTransactionSync")({serializedTransaction:z,throwOnReceiptRevert:x,timeout:t.timeout})}throw(S==null?void 0:S.type)==="smart"?new rs({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new rs({docsPath:"/docs/actions/wallet/sendTransactionSync",type:S==null?void 0:S.type})}catch(M){throw M instanceof rs?M:Ku(M,{...t,account:S,chain:t.chain||void 0})}}async function f_(e,t){const{id:r}=t;await e.request({method:"wallet_showCallsStatus",params:[r]})}async function l_(e,t){const{account:r=e.account}=t;if(!r)throw new Ui({docsPath:"/docs/eip7702/signAuthorization"});const n=Me(r);if(!n.signAuthorization)throw new rs({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});const i=await B2(e,t);return n.signAuthorization(i)}async function d_(e,{account:t=e.account,message:r}){if(!t)throw new Ui({docsPath:"/docs/actions/wallet/signMessage"});const n=Me(t);if(n.signMessage)return n.signMessage({message:r});const i=typeof r=="string"?ra(r):r.raw instanceof Uint8Array?zt(r.raw):r.raw;return e.request({method:"personal_sign",params:[i,n.address]},{retryCount:0})}async function h_(e,t){var u,f,l,h;const{account:r=e.account,chain:n=e.chain,...i}=t;if(!r)throw new Ui({docsPath:"/docs/actions/wallet/signTransaction"});const s=Me(r);qn({account:s,...t});const a=await re(e,Ri,"getChainId")({});n!==null&&H0({currentChainId:a,chain:n});const o=(n==null?void 0:n.formatters)||((u=e.chain)==null?void 0:u.formatters),c=((f=o==null?void 0:o.transactionRequest)==null?void 0:f.format)||yn;return s.signTransaction?s.signTransaction({...i,chainId:a},{serializer:(h=(l=e.chain)==null?void 0:l.serializers)==null?void 0:h.transaction}):await e.request({method:"eth_signTransaction",params:[{...c({...i,account:s},"signTransaction"),chainId:J(a),from:s.address}]},{retryCount:0})}async function p_(e,t){const{account:r=e.account,domain:n,message:i,primaryType:s}=t;if(!r)throw new Ui({docsPath:"/docs/actions/wallet/signTypedData"});const a=Me(r),o={EIP712Domain:qw({domain:n}),...t.types};if(Gw({domain:n,message:i,primaryType:s,types:o}),a.signTypedData)return a.signTypedData({domain:n,message:i,primaryType:s,types:o});const c=Ck({domain:n,message:i,primaryType:s,types:o});return e.request({method:"eth_signTypedData_v4",params:[a.address,c]},{retryCount:0})}async function y_(e,{id:t}){await e.request({method:"wallet_switchEthereumChain",params:[{chainId:J(t)}]},{retryCount:0})}async function m_(e,t){return await e.request({method:"wallet_watchAsset",params:t},{retryCount:0})}async function b_(e,t){return aa.internal(e,C2,"sendTransactionSync",t)}function g_(e){return{addChain:t=>r_(e,t),deployContract:t=>n_(e,t),fillTransaction:t=>_0(e,t),getAddresses:()=>i_(e),getCallsStatus:t=>Cw(e,t),getCapabilities:t=>s_(e,t),getChainId:()=>Ri(e),getPermissions:()=>a_(e),prepareAuthorization:t=>B2(e,t),prepareTransactionRequest:t=>Qo(e,t),requestAddresses:()=>o_(e),requestPermissions:t=>c_(e,t),sendCalls:t=>Bw(e,t),sendCallsSync:t=>u_(e,t),sendRawTransaction:t=>L0(e,t),sendRawTransactionSync:t=>op(e,t),sendTransaction:t=>nf(e,t),sendTransactionSync:t=>C2(e,t),showCallsStatus:t=>f_(e,t),signAuthorization:t=>l_(e,t),signMessage:t=>d_(e,t),signTransaction:t=>h_(e,t),signTypedData:t=>p_(e,t),switchChain:t=>y_(e,t),waitForCallsStatus:t=>Rw(e,t),watchAsset:t=>m_(e,t),writeContract:t=>aa(e,t),writeContractSync:t=>b_(e,t)}}function ll(e){const{key:t="wallet",name:r="Wallet Client",transport:n}=e;return Uw({...e,key:t,name:r,transport:n,type:"walletClient"}).extend(g_)}function R2({key:e,methods:t,name:r,request:n,retryCount:i=3,retryDelay:s=150,timeout:a,type:o},c){const u=Nw();return{config:{key:e,methods:t,name:r,request:n,retryCount:i,retryDelay:s,timeout:a,type:o},request:vk(n,{methods:t,retryCount:i,retryDelay:s,uid:u}),value:c}}function um(e,t={}){const{key:r="custom",methods:n,name:i="Custom Provider",retryDelay:s}=t;return({retryCount:a})=>R2({key:r,methods:n,name:i,request:e.request.bind(e),retryCount:t.retryCount??a,retryDelay:s,type:"custom"})}class w_ 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 N2(e,t={}){const{batch:r,fetchFn:n,fetchOptions:i,key:s="http",methods:a,name:o="HTTP JSON-RPC",onFetchRequest:c,onFetchResponse:u,retryDelay:f,raw:l}=t;return({chain:h,retryCount:d,timeout:b})=>{const{batchSize:g=1e3,wait:x=0}=typeof r=="object"?r:{},A=t.retryCount??d,k=b??t.timeout??1e4,w=h==null?void 0:h.rpcUrls.default.http[0];if(!w)throw new w_;const v=kk(w,{fetchFn:n,fetchOptions:i,onRequest:c,onResponse:u,timeout:k});return R2({key:s,methods:a,name:o,async request({method:S,params:I}){const _={method:S,params:I},{schedule:R}=Aw({id:w,wait:x,shouldSplitBatch(H){return H.length>g},fn:H=>v.request({body:H}),sort:(H,z)=>H.id-z.id}),B=async H=>r?R(H):[await v.request({body:H})],[{error:M,result:F}]=await B(_);if(l)return{error:M,result:F};if(M)throw new b0({body:_,error:M,url:w});return F},retryCount:A,retryDelay:f,timeout:k,type:"http"},{fetchOptions:i,url:w})}}const U2=[{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"}],v_=[{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 xs{constructor(t,r){this.auth=t,this.url=r instanceof m.Url?r:new m.Url(r)}async initiate(t,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return m.Err(n.error);const i=await m.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(t).addSearchParams({action:"initiate"}),{body:JSON.stringify({signature:r}),headers:{...n.val,"Content-Type":"application/json"}});return i.error||!i.result?m.Err(i.error||"Initiate failed"):m.Ok(i.result)}catch(n){return m.Err(String(n))}}async redeem(t,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return m.Err(n.error);const i=await m.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(t).addSearchParams({action:"redeem"}),{body:JSON.stringify({secret:m.trim0x(r)}),headers:{...n.val,"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return i.error?m.Err(i.error):i.result?m.Ok(i.result):m.Err("Redeem: No result found")}catch(n){return m.Err(String(n))}}}const E_=async(e,t)=>{if(!e.account)return m.Err("No account found");try{const n=await D0({address:m.with0x(t.htlc),abi:v_,client:e}).write.initiate([m.with0x(t.redeemer),t.timelock,t.amount,m.with0x(t.secretHash)],{account:e.account,chain:e.chain,value:t.amount}),i=await m.waitForTransactionReceipt(e,n);return i.ok?!i.val||i.val.status!=="success"?m.Err("Native initiate transaction failed"):m.Ok(n):m.Err(i.error)}catch(r){return Vh(r)?m.Ok("already initiated"):m.Err("Failed to initiate on native HTLC",String(r))}},x_=async(e,t,r,n)=>{if(!e.account)return m.Err("No account found");try{const i=D0({address:m.with0x(n.htlc),abi:U2,client:e}),s=await m.checkAllowanceAndApprove(Number(n.amount),n.token,n.htlc,e);if(!s.ok)return m.Err(s.error);const a=await i.read.eip712Domain(),o=await e.signTypedData({account:e.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 xs(r,t),u=await zb({wallet:e,attempt:()=>c.initiate(n.orderId,o)});if(u)return m.Ok(u);const f=await i.write.initiate([m.with0x(n.redeemer),n.timelock,n.amount,m.with0x(n.secretHash)],{account:e.account,chain:e.chain}),l=await m.waitForTransactionReceipt(e,f);return l.ok?!l.val||l.val.status!=="success"?m.Err("Failed to initiate (fallback)"):m.Ok(f):m.Err(l.error)}catch(i){return Vh(i)?m.Ok("already initiated"):m.Err("Failed to initiate on ERC20 HTLC",String(i))}},A_=async(e,t)=>{if(!e.account)return m.Err("No account found");try{const r=await e.sendTransaction({account:e.account,to:m.with0x(t.to),value:BigInt(t.value),data:m.with0x(t.data),gas:BigInt(t.gas_limit),chain:e.chain}),n=await m.waitForTransactionReceipt(e,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))}},S_={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}},k_={block:p3({format(e){var r;return{transactions:(r=e.transactions)==null?void 0:r.map(n=>{if(typeof n=="string")return n;const i=ha(n);return i.typeHex==="0x7e"&&(i.isSystemTx=n.isSystemTx,i.mint=n.mint?mt(n.mint):void 0,i.sourceHash=n.sourceHash,i.type="deposit"),i}),stateRoot:e.stateRoot}}}),transaction:D1({format(e){const t={};return e.type==="0x7e"&&(t.isSystemTx=e.isSystemTx,t.mint=e.mint?mt(e.mint):void 0,t.sourceHash=e.sourceHash,t.type="deposit"),t}}),transactionReceipt:_w({format(e){return{l1GasPrice:e.l1GasPrice?mt(e.l1GasPrice):null,l1GasUsed:e.l1GasUsed?mt(e.l1GasUsed):null,l1Fee:e.l1Fee?mt(e.l1Fee):null,l1FeeScalar:e.l1FeeScalar?Number(e.l1FeeScalar):null}}})};function T_(e,t){return P_(e)?__(e):uh(e,t)}const I_={transaction:T_};function __(e){O_(e);const{sourceHash:t,data:r,from:n,gas:i,isSystemTx:s,mint:a,to:o,value:c}=e,u=[t,n,o??"0x",a?zt(a):"0x",c?zt(c):"0x",i?zt(i):"0x",s?"0x1":"0x",r??"0x"];return Wr(["0x7e",Pi(u)])}function P_(e){return e.type==="deposit"||typeof e.sourceHash<"u"}function O_(e){const{from:t,to:r}=e;if(t&&!pt(t))throw new Gt({address:t});if(r&&!pt(r))throw new Gt({address:r})}const pn={blockTime:2e3,contracts:S_,formatters:k_,serializers:I_},B_=Ze({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}}}),C_=Ze({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}),F2=Ze({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}),Oa=1,$2=Ze({...pn,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:{...pn.contracts,disputeGameFactory:{[Oa]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[Oa]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[Oa]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[Oa]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:Oa});({...$2});const Ba=11155111,M2=Ze({...pn,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:{...pn.contracts,disputeGameFactory:{[Ba]:{address:"0xd6E6dBf4F7EA0ac412fD8b65ED297e64BB7a06E1"}},l2OutputOracle:{[Ba]:{address:"0x84457ca9D0163FbC4bbfe4Dfbb20ba46e48DF254"}},portal:{[Ba]:{address:"0x49f53e41452c74589e85ca1677426ba426459e85",blockCreated:4446677}},l1StandardBridge:{[Ba]:{address:"0xfd0Bf71F60660E2f608ed56e1659C450eB113120",blockCreated:4446677}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:1059647}},testnet:!0,sourceId:Ba});({...M2});const R_=Ze({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}),N_=Ze({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}),U_=Ze({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}}}),F_=Ze({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}),$_=Ze({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}),M_=Ze({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}),j_=1,H_=Ze({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:j_}),Nc=1,L_=Ze({...pn,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},...pn.contracts,disputeGameFactory:{[Nc]:{address:"0x10d7b35078d3baabb96dd45a9143b94be65b12cd"}},portal:{[Nc]:{address:"0x5d66c1782664115999c47c9fa5cd031f495d3e4f"}},l1StandardBridge:{[Nc]:{address:"0x88ff1e5b602916615391f55854588efcbb7663f0"}}},testnet:!1,sourceId:Nc}),Uc=11155111,D_=Ze({...pn,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:{...pn.contracts,multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:0},disputeGameFactory:{[Uc]:{address:"0x860e626c700af381133d9f4af31412a2d1db3d5d"}},portal:{[Uc]:{address:"0x5c1d29c6c9c8b0800692acc95d700bcb4966a1d7"}},l1StandardBridge:{[Uc]:{address:"0x33f60714bbd74d62b66d79213c348614de51901c"}}},testnet:!0,sourceId:Uc}),z_=Ze({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}}}),V_=Ze({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}),G_=Ze({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});/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const j2=ga(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),q_=j2.create(BigInt("-3")),W_=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),K_=of({a:q_,b:W_,Fp:j2,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},k0),H2=ga(BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff")),X_=H2.create(BigInt("-3")),J_=BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef");of({a:X_,b:J_,Fp:H2,n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"),h:BigInt(1),lowS:!1},T3);const L2=ga(BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")),Y_=L2.create(BigInt("-3")),Z_=BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00");of({a:Y_,b:Z_,Fp:L2,n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650"),h:BigInt(1),lowS:!1,allowedPrivateKeyLengths:[130,131,132]},k3);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Q_=K_;function D2(e){const{hash:t,payload:r,publicKey:n,signature:i}=e;return Q_.verify(i,r instanceof Uint8Array?r:Ni(r),K0(n).substring(2),...t?[{prehash:!0,lowS:!0}]:[])}const eP=new TextEncoder;Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[t,e.charCodeAt(0)]);const Fc={...Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[e.charCodeAt(0),t])),61:0,45:62,95:63};function tP(e){const t=e.replace(/=+$/,""),r=t.length,n=new Uint8Array(r+3);eP.encodeInto(t+"===",n);for(let s=0,a=0;s<t.length;s+=4,a+=3){const o=(Fc[n[s]]<<18)+(Fc[n[s+1]]<<12)+(Fc[n[s+2]]<<6)+Fc[n[s+3]];n[a]=o>>16,n[a+1]=o>>8&255,n[a+2]=o&255}const i=(r>>2)*3+(r%4&&r%4-1);return new Uint8Array(n.buffer,0,i)}Uint8Array.from([105,171,180,181,160,222,75,198,42,42,32,31,141,37,186,233]);function rP(e){const{challenge:t,hash:r=!0,metadata:n,publicKey:i,signature:s}=e,{authenticatorData:a,challengeIndex:o,clientDataJSON:c,typeIndex:u,userVerificationRequired:f}=n,l=Ni(a);if(l.length<37)return!1;const h=l[32];if((h&1)!==1||f&&(h&4)!==4||(h&8)!==8&&(h&16)===16)return!1;if(u!==void 0){const k='"type":"webauthn.get"';if(k!==c.slice(Number(u),k.length+1))return!1}const d=o!==void 0?c.slice(Number(o)).match(/^"challenge":"(.*?)"/):c.match(/"challenge":"(.*?)"/);if(!d)return!1;const[b,g]=d;if(bt(tP(g))!==t)return!1;const x=Hk(cw(c),{as:"Bytes"}),A=K3(l,x);return D2({hash:r,payload:A,publicKey:i,signature:s})}const vh="0x01",Eh="0x02",z2="0x03",qi="0x7777777777777777777777777777777777777777777777777777777777777777";function wa(e){const t=e.endsWith(qi.slice(2))?Ee(e,0,-rt(qi)):e;if(rt(t)===65){const a=rp(t);return uf(a),{signature:a,type:"secp256k1"}}const n=Ee(t,0,1),i=Ee(t,1),s=rt(i);if(n===vh){if(s!==129)throw new La({reason:`Invalid P256 signature envelope size: expected 129 bytes, got ${s} bytes`,serialized:t});return{publicKey:{prefix:4,x:tt(Ee(i,64,96)),y:tt(Ee(i,96,128))},prehash:Po(Ee(i,128,129))!==0,signature:{r:tt(Ee(i,0,32)),s:tt(Ee(i,32,64))},type:"p256"}}if(n===Eh){if(s<128)throw new La({reason:`Invalid WebAuthn signature envelope size: expected at least 128 bytes, got ${s} bytes`,serialized:t});const a=s-128,o=Ee(i,0,a);let c,u;for(let f=37;f<a;f++){const l=hw(Ee(o,f));if(l.startsWith("{")&&l.endsWith("}"))try{JSON.parse(l),c=Ee(o,0,f),u=l;break}catch{}}if(!c||!u)throw new La({reason:"Unable to parse WebAuthn metadata: could not extract valid authenticatorData and clientDataJSON",serialized:t});return{publicKey:{prefix:4,x:tt(Ee(i,a+64,a+96)),y:tt(Ee(i,a+96,a+128))},metadata:{authenticatorData:c,clientDataJSON:u},signature:{r:tt(Ee(i,a,a+32)),s:tt(Ee(i,a+32,a+64))},type:"webAuthn"}}if(n===z2){const a=Ee(i,0,20),o=wa(Ee(i,20));return{userAddress:a,inner:o,type:"keychain"}}throw new La({reason:`Unknown signature type identifier: ${n}. Expected ${vh} (P256) or ${Eh} (WebAuthn)`,serialized:t})}function fc(e){if(typeof e=="string")return wa(e);if(typeof e=="object"&&e!==null&&"r"in e&&"s"in e&&"yParity"in e)return{signature:e,type:"secp256k1"};const t=cp(e);return{...e,...t==="p256"?{prehash:e.prehash}:{},type:t}}function hf(e){if(e.type==="secp256k1")return{signature:np(e),type:"secp256k1"};if(e.type==="p256")return{prehash:e.preHash,publicKey:{prefix:4,x:tt(e.pubKeyX),y:tt(e.pubKeyY)},signature:{r:tt(e.r),s:tt(e.s)},type:"p256"};if(e.type==="webAuthn"){const t=e.webauthnData,r=rt(t);let n,i;for(let s=37;s<r;s++){const a=hw(Ee(t,s));if(a.startsWith("{")&&a.endsWith("}"))try{JSON.parse(a),n=Ee(t,0,s),i=a;break}catch{}}if(!n||!i)throw new La({reason:"Unable to parse WebAuthn metadata: could not extract valid authenticatorData and clientDataJSON",serialized:t});return{metadata:{authenticatorData:n,clientDataJSON:i},publicKey:{prefix:4,x:tt(e.pubKeyX),y:tt(e.pubKeyY)},signature:{r:tt(e.r),s:tt(e.s)},type:"webAuthn"}}if(e.type==="keychain"||"userAddress"in e&&"signature"in e)return{type:"keychain",userAddress:e.userAddress,inner:hf(e.signature)};throw new Bo({envelope:e})}function cp(e){if(typeof e!="object"||e===null)throw new Bo({envelope:e});if("type"in e&&e.type)return e.type;if("signature"in e&&!("publicKey"in e)&&typeof e.signature=="object"&&e.signature!==null&&"r"in e.signature&&"s"in e.signature&&"yParity"in e.signature||"r"in e&&"s"in e&&"yParity"in e)return"secp256k1";if("signature"in e&&"prehash"in e&&"publicKey"in e&&typeof e.prehash=="boolean")return"p256";if("signature"in e&&"metadata"in e&&"publicKey"in e)return"webAuthn";if("userAddress"in e&&"inner"in e)return"keychain";throw new Bo({envelope:e})}function pf(e,t={}){const r=cp(e);if(r==="secp256k1")return Je(nI(e.signature),t.magic?qi:"0x");if(r==="p256"){const n=e;return Je(vh,te(n.signature.r,{size:32}),te(n.signature.s,{size:32}),te(n.publicKey.x,{size:32}),te(n.publicKey.y,{size:32}),te(n.prehash?1:0,{size:1}),t.magic?qi:"0x")}if(r==="webAuthn"){const n=e,i=Je(n.metadata.authenticatorData,nc(n.metadata.clientDataJSON));return Je(Eh,i,te(n.signature.r,{size:32}),te(n.signature.s,{size:32}),te(n.publicKey.x,{size:32}),te(n.publicKey.y,{size:32}),t.magic?qi:"0x")}if(r==="keychain"){const n=e;return Je(z2,n.userAddress,pf(n.inner),t.magic?qi:"0x")}throw new Bo({envelope:e})}function up(e){const t=cp(e);if(t==="secp256k1")return{...E2(e.signature),type:"secp256k1"};if(t==="p256"){const r=e;return{preHash:r.prehash,pubKeyX:te(r.publicKey.x,{size:32}),pubKeyY:te(r.publicKey.y,{size:32}),r:te(r.signature.r,{size:32}),s:te(r.signature.s,{size:32}),type:"p256"}}if(t==="webAuthn"){const r=e,n=Je(r.metadata.authenticatorData,nc(r.metadata.clientDataJSON));return{pubKeyX:te(r.publicKey.x,{size:32}),pubKeyY:te(r.publicKey.y,{size:32}),r:te(r.signature.r,{size:32}),s:te(r.signature.s,{size:32}),type:"webAuthn",webauthnData:n}}if(t==="keychain"){const r=e;return{type:"keychain",userAddress:r.userAddress,signature:up(r.inner)}}throw new Bo({envelope:e})}function nP(e,t){const{payload:r}=t,n=(()=>{if(t.address)return t.address;if(t.publicKey)return Jc(t.publicKey)})();if(!n)return!1;const i=fc(e);if(i.type==="secp256k1")return n?pI({address:n,payload:r,signature:i.signature}):!1;if(i.type==="p256"){const s=Jc(i.publicKey);return fh(s,n)?D2({hash:i.prehash,publicKey:i.publicKey,payload:r,signature:i.signature}):!1}if(i.type==="webAuthn"){const s=Jc(i.publicKey);return fh(s,n)?rP({challenge:Zu(r),metadata:i.metadata,publicKey:i.publicKey,signature:i.signature}):!1}throw new iP(`Unable to verify signature envelope of type "${i.type}".`)}class Bo extends se{constructor({envelope:t}){super(`Unable to coerce value (\`${rc(t)}\`) to a valid signature envelope.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureEnvelope.CoercionError"})}}let La=class extends se{constructor({reason:t,serialized:r}){super(`Unable to deserialize signature envelope: ${t}`,{metaMessages:[`Serialized: ${r}`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureEnvelope.InvalidSerializedError"})}};class iP extends se{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureEnvelope.VerificationError"})}}function sP(e,t={}){return typeof e.chainId=="string"?V2(e):t.signature?{...e,signature:t.signature}:e}function V2(e){const{address:t,chainId:r,nonce:n}=e,i=hf(e.signature);return{address:t,chainId:Number(r),nonce:BigInt(n),signature:i}}function aP(e){return e.map(t=>V2(t))}function oP(e){const[t,r,n,i]=e,s={address:r,chainId:t==="0x"?0:Number(t),nonce:n==="0x"?0n:BigInt(n)};return i&&(s.signature=wa(i)),sP(s)}function cP(e){const t=[];for(const r of e)t.push(oP(r));return t}function uP(e){const{address:t,chainId:r,nonce:n,signature:i}=e;return{address:t,chainId:te(r),nonce:te(n),signature:up(i)}}function fP(e){return e.map(t=>uP(t))}function lP(e){const{address:t,chainId:r,nonce:n}=e,i=e.signature?pf(e.signature):void 0;return[r?te(r):"0x",t,n?te(n):"0x",...i?[i]:[]]}function dP(e){if(!e||e.length===0)return[];const t=[];for(const r of e)t.push(lP(r));return t}function hP(e,t={}){return typeof e.expiry=="string"?G2(e):t.signature?{...e,signature:fc(t.signature)}:e}function G2(e){const{chainId:t="0x0",keyId:r,expiry:n=0,limits:i,keyType:s}=e,a=hf(e.signature);return{address:r,chainId:t==="0x"?0n:tt(t),expiry:Number(n),limits:i==null?void 0:i.map(o=>({token:o.token,limit:BigInt(o.limit)})),signature:a,type:s}}function pP(e){const[t,r]=e,[n,i,s,a,o]=t,c=(()=>{switch(i){case"0x":case"0x00":return"secp256k1";case"0x01":return"p256";case"0x02":return"webAuthn";default:throw new Error(`Invalid key type: ${i}`)}})(),u={address:s,expiry:typeof a<"u"?Po(a):void 0,type:c,...n!=="0x"?{chainId:tt(n)}:{},...typeof a<"u"?{expiry:Po(a)}:{},...typeof o<"u"?{limits:o.map(([f,l])=>({token:f,limit:BigInt(l)}))}:{}};return r&&(u.signature=wa(r)),hP(u)}function yP(e){const{address:t,chainId:r=0n,expiry:n,limits:i,type:s,signature:a}=e;return{chainId:r===0n?"0x":te(r),expiry:typeof n=="number"?te(n):null,limits:i==null?void 0:i.map(({token:o,limit:c})=>({token:o,limit:te(c)})),keyId:t,signature:up(a),keyType:s}}function mP(e){const{address:t,chainId:r=0n,expiry:n,limits:i}=e,s=e.signature?pf(e.signature):void 0,a=(()=>{switch(e.type){case"secp256k1":return"0x";case"p256":return"0x01";case"webAuthn":return"0x02";default:throw new Error(`Invalid key type: ${e.type}`)}})();return[[r===0n?"0x":te(r),a,t,typeof n=="number"?te(n):void 0,(i==null?void 0:i.map(c=>[c.token,te(c.limit)]))??void 0].filter(Boolean),...s?[s]:[]]}const bP="0x20c0";function q2(e){if(typeof e=="string")return Vr(e),e;const t=te(e,{size:18});return Je(bP,t)}const W2={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"},K2={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function gP(e,t={}){if(!e)return null;const r=v2(e),n={...e,...r};return n.blockNumber=e.blockNumber?BigInt(e.blockNumber):null,n.data=e.input,n.gas=BigInt(e.gas??0n),n.nonce=BigInt(e.nonce??0n),n.transactionIndex=e.transactionIndex?Number(e.transactionIndex):null,n.value=BigInt(e.value??0n),e.authorizationList&&(n.authorizationList=fI(e.authorizationList)),e.chainId&&(n.chainId=Number(e.chainId)),e.gasPrice&&(n.gasPrice=BigInt(e.gasPrice)),e.maxFeePerBlobGas&&(n.maxFeePerBlobGas=BigInt(e.maxFeePerBlobGas)),e.maxFeePerGas&&(n.maxFeePerGas=BigInt(e.maxFeePerGas)),e.maxPriorityFeePerGas&&(n.maxPriorityFeePerGas=BigInt(e.maxPriorityFeePerGas)),e.type&&(n.type=K2[e.type]??e.type),r&&(n.v=sp(r.yParity)),n}const X2={...W2,tempo:"0x76"},wP={...K2,"0x76":"tempo"};function vP(e,t={}){if(!e)return null;const r=gP(e);return r.type=wP[e.type],e.aaAuthorizationList&&(r.authorizationList=aP(e.aaAuthorizationList),delete r.aaAuthorizationList),e.calls&&(r.calls=e.calls.map(n=>({to:n.to,value:n.value&&n.value!=="0x"?BigInt(n.value):void 0,data:n.input||n.data||"0x"}))),e.feeToken&&(r.feeToken=e.feeToken),e.nonceKey&&(r.nonceKey=BigInt(e.nonceKey)),e.signature&&(r.signature=hf(e.signature)),e.validAfter&&(r.validAfter=Number(e.validAfter)),e.validBefore&&(r.validBefore=Number(e.validBefore)),e.keyAuthorization&&(r.keyAuthorization=G2(e.keyAuthorization)),e.feePayerSignature&&(r.feePayerSignature=np(e.feePayerSignature),r.feePayerSignature.v=sp(r.feePayerSignature.yParity)),r}function EP(e){const t={};return typeof e.accessList<"u"&&(t.accessList=e.accessList),typeof e.authorizationList<"u"&&(t.authorizationList=dI(e.authorizationList)),typeof e.blobVersionedHashes<"u"&&(t.blobVersionedHashes=e.blobVersionedHashes),typeof e.blobs<"u"&&(t.blobs=e.blobs),typeof e.chainId<"u"&&(t.chainId=te(e.chainId)),typeof e.data<"u"?(t.data=e.data,t.input=e.data):typeof e.input<"u"&&(t.data=e.input,t.input=e.input),typeof e.from<"u"&&(t.from=e.from),typeof e.gas<"u"&&(t.gas=te(e.gas)),typeof e.gasPrice<"u"&&(t.gasPrice=te(e.gasPrice)),typeof e.maxFeePerBlobGas<"u"&&(t.maxFeePerBlobGas=te(e.maxFeePerBlobGas)),typeof e.maxFeePerGas<"u"&&(t.maxFeePerGas=te(e.maxFeePerGas)),typeof e.maxPriorityFeePerGas<"u"&&(t.maxPriorityFeePerGas=te(e.maxPriorityFeePerGas)),typeof e.maxPriorityFeePerGas<"u"&&(t.maxPriorityFeePerGas=te(e.maxPriorityFeePerGas)),typeof e.nonce<"u"&&(t.nonce=te(e.nonce)),typeof e.to<"u"&&(t.to=e.to),typeof e.type<"u"&&(t.type=W2[e.type]||e.type),typeof e.value<"u"&&(t.value=te(e.value)),t}function xP(e){const t=EP({...e,authorizationList:void 0});e.authorizationList&&(t.authorizationList=fP(e.authorizationList)),e.calls&&(t.calls=e.calls.map(n=>({to:n.to,value:n.value?te(n.value):"0x",data:n.data??"0x"}))),typeof e.feeToken<"u"&&(t.feeToken=q2(e.feeToken)),e.keyAuthorization&&(t.keyAuthorization=yP(e.keyAuthorization)),typeof e.validBefore<"u"&&(t.validBefore=te(e.validBefore)),typeof e.validAfter<"u"&&(t.validAfter=te(e.validAfter));const r=(()=>{if(e.nonceKey==="random")return dw(6);if(typeof e.nonceKey=="bigint")return te(e.nonceKey)})();return r&&(t.nonceKey=r),(typeof e.calls<"u"||typeof e.feeToken<"u"||typeof e.keyAuthorization<"u"||typeof e.nonceKey<"u"||typeof e.validBefore<"u"||typeof e.validAfter<"u"||e.type==="tempo")&&(t.type=X2.tempo,delete t.data,delete t.input,delete t.to,delete t.value),t}function AP(e){const t=[];for(let r=0;r<e.length;r++){const[n,i]=e[r];n&&Vr(n,{strict:!1}),t.push({address:n,storageKeys:i.map(s=>Lk(s)?s:nh(s))})}return t}function SP(e){if(!e||e.length===0)return[];const t=[];for(const{address:r,storageKeys:n}of e){for(let i=0;i<n.length;i++)if(rt(n[i])!==32)throw new kP({storageKey:n[i]});r&&Vr(r,{strict:!1}),t.push([r,n])}return t}class kP extends se{constructor({storageKey:t}){super(`Size for storage key "${t}" is invalid. Expected 32 bytes. Got ${rt(t)} bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AccessList.InvalidStorageKeySizeError"})}}const fm={wei:0,gwei:9,szabo:12,finney:15,ether:18};function TP(e,t=0){let r=e.toString();const n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(t,"0");let[i,s]=[r.slice(0,r.length-t),r.slice(r.length-t)];return s=s.replace(/(0+)$/,""),`${n?"-":""}${i||"0"}${s?`.${s}`:""}`}function xh(e,t="wei"){return TP(e,fm.gwei-fm[t])}class IP extends se{constructor({feeCap:t}={}){super(`The fee cap (\`maxFeePerGas\`/\`maxPriorityFeePerGas\`${t?` = ${xh(t)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TransactionEnvelope.FeeCapTooHighError"})}}class _P extends se{constructor({chainId:t}){super(typeof t<"u"?`Chain ID "${t}" is invalid.`:"Chain ID is invalid."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TransactionEnvelope.InvalidChainIdError"})}}class PP extends se{constructor({attributes:t,serialized:r,type:n}){const i=Object.entries(t).map(([s,a])=>typeof a>"u"?s:void 0).filter(Boolean);super(`Invalid serialized transaction of type "${n}" was provided.`,{metaMessages:[`Serialized Transaction: "${r}"`,i.length>0?`Missing Attributes: ${i.join(", ")}`:""].filter(Boolean)}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TransactionEnvelope.InvalidSerializedError"})}}class OP extends se{constructor({maxPriorityFeePerGas:t,maxFeePerGas:r}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${t?` = ${xh(t)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${r?` = ${xh(r)} gwei`:""}).`].join(`
|
|
72
|
+
`)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TransactionEnvelope.TipAboveFeeCapError"})}}const BP="0x78",CP="0x76",lm="tempo";function fp(e){const{calls:t,chainId:r,maxFeePerGas:n,maxPriorityFeePerGas:i,validBefore:s,validAfter:a}=e;if(!t||t.length===0)throw new MP;if(typeof s=="number"&&typeof a=="number"&&s<=a)throw new jP({validBefore:s,validAfter:a});if(t)for(const o of t)o.to&&Vr(o.to,{strict:!1});if(r<=0)throw new _P({chainId:r});if(n&&BigInt(n)>2n**256n-1n)throw new IP({feeCap:n});if(i&&n&&i>n)throw new OP({maxFeePerGas:n,maxPriorityFeePerGas:i})}function RP(e){const t=ST(Ee(e,1)),[r,n,i,s,a,o,c,u,f,l,h,d,b,g,x]=t,A=Array.isArray(g)?g:void 0,k=A?x:g;if(!(t.length===13||t.length===14||t.length===15))throw new PP({attributes:{authorizationList:b,chainId:r,maxPriorityFeePerGas:n,maxFeePerGas:i,gas:s,calls:a,accessList:o,keyAuthorization:A,nonceKey:c,nonce:u,validBefore:f,validAfter:l,feeToken:h,feePayerSignatureOrSender:d,...t.length>12?{signature:k}:{}},serialized:e,type:lm});let w={chainId:Number(r),type:lm};if(_r(s)&&s!=="0x"&&(w.gas=BigInt(s)),_r(u)&&(w.nonce=u==="0x"?0n:BigInt(u)),_r(i)&&i!=="0x"&&(w.maxFeePerGas=BigInt(i)),_r(n)&&n!=="0x"&&(w.maxPriorityFeePerGas=BigInt(n)),_r(c)&&(w.nonceKey=c==="0x"?0n:BigInt(c)),_r(f)&&f!=="0x"&&(w.validBefore=Number(f)),_r(l)&&l!=="0x"&&(w.validAfter=Number(l)),_r(h)&&h!=="0x"&&(w.feeToken=h),a&&a!=="0x"){const S=a;w.calls=S.map(I=>{const[_,R,B]=I,M={};return _&&_!=="0x"&&(M.to=_),R&&R!=="0x"&&(M.value=BigInt(R)),B&&B!=="0x"&&(M.data=B),M})}(o==null?void 0:o.length)!==0&&o!=="0x"&&(w.accessList=AP(o)),(b==null?void 0:b.length)!==0&&b!=="0x"&&(w.authorizationList=cP(b)),d!=="0x"&&d!==void 0&&(d==="0x00"||hu(d)?w.feePayerSignature=null:w.feePayerSignature=rI(d)),A&&(w.keyAuthorization=pP(A));const v=k?wa(k):void 0;return v&&(w={...w,signature:v}),fp(w),w}function NP(e,t={}){const{feePayerSignature:r,signature:n}=t,i=typeof e=="string"?RP(e):e;return fp(i),{...i,...n?{signature:fc(n)}:{},...r?{feePayerSignature:ff(r)}:{},type:"tempo"}}function Ka(e,t={}){const{accessList:r,authorizationList:n,calls:i,chainId:s,feeToken:a,gas:o,keyAuthorization:c,nonce:u,nonceKey:f,maxFeePerGas:l,maxPriorityFeePerGas:h,validBefore:d,validAfter:b}=e;fp(e);const g=SP(r),x=t.signature||e.signature,A=dP(n),k=i.map(S=>[S.to??"0x",S.value?te(S.value):"0x",S.data??"0x"]),w=(()=>{if(t.sender)return t.sender;const S=typeof t.feePayerSignature<"u"?t.feePayerSignature:e.feePayerSignature;return S===null?"0x00":S?iI(S):"0x"})(),v=[te(s),h?te(h):"0x",l?te(l):"0x",o?te(o):"0x",k,g,f?te(f):"0x",u?te(u):"0x",typeof d=="number"?te(d):"0x",typeof b=="number"?te(b):"0x",typeof a=="bigint"||typeof a=="string"?q2(a):"0x",w,A,...c?[mP(c)]:[],...x?[pf(fc(x))]:[]];return Je(t.format==="feePayer"?BP:CP,_T(v))}function UP(e){return FP(e,{presign:!0})}function FP(e,t={}){const r=Ka({...e,...t.presign?{signature:void 0}:{}});return cc(r)}function $P(e,t){const{sender:r}=t,n=Ka({...e,signature:void 0},{sender:r,format:"feePayer"});return cc(n)}class MP extends se{constructor(){super("Calls list cannot be empty."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TxEnvelopeTempo.CallsEmptyError"})}}class jP extends se{constructor({validBefore:t,validAfter:r}){super(`validBefore (${t}) must be greater than validAfter (${r}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TxEnvelopeTempo.InvalidValidityWindowError"})}}function J2(e){const t=e.account;return t!=null&&t.keyType&&t.keyType!=="secp256k1"||typeof e.calls<"u"||typeof e.feePayer<"u"||typeof e.feeToken<"u"||typeof e.keyAuthorization<"u"||typeof e.nonceKey<"u"||typeof e.signature<"u"||typeof e.validBefore<"u"||typeof e.validAfter<"u"?"tempo":e.type?e.type:I0(e)}function lp(e){try{return J2(e)==="tempo"}catch{return!1}}async function HP(e,t){if(!lp(e)){if(t&&"type"in t&&t.type!=="secp256k1")throw new Error("Unsupported signature type. Expected `secp256k1` but got `"+t.type+"`.");if(t&&"type"in t){const{r:n,s:i,yParity:s}=t==null?void 0:t.signature;return uh(e,{r:te(n,{size:32}),s:te(i,{size:32}),yParity:s})}return uh(e,t)}if(J2(e)==="tempo")return LP(e,t);throw new Error("Unsupported transaction type")}async function LP(e,t){var u;const r=(()=>{if(e.signature)return e.signature;if(t&&"type"in t)return t;if(t)return fc({r:BigInt(t.r),s:BigInt(t.s),yParity:Number(t.yParity)})})(),{chainId:n,feePayer:i,feePayerSignature:s,nonce:a,...o}=e,c={...o,calls:(u=o.calls)!=null&&u.length?o.calls:[{to:o.to||(!o.data||o.data==="0x"?"0x0000000000000000000000000000000000000000":void 0),value:o.value,data:o.data}],chainId:Number(n),feePayerSignature:s?{r:BigInt(s.r),s:BigInt(s.s),yParity:Number(s.yParity)}:i?null:void 0,type:"tempo",...a?{nonce:BigInt(a)}:{}};if(i===!0&&delete c.feeToken,r&&typeof e.feePayer=="object"){const f=NP(c,{signature:r}),l=(()=>{if(e.from)return e.from;if(r.type==="secp256k1")return A2({payload:UP(f),signature:r.signature});throw new Error("Unable to extract sender from transaction or signature.")})(),h=$P(f,{sender:l}),d=await e.feePayer.sign({hash:h});return Ka(f,{feePayerSignature:ff(d)})}if(i===!0){const f=Ka(c,{feePayerSignature:null,signature:r});return e.from&&r?Je(f,e.from,"0xfeefeefeefee"):f}return Ka({...c,...i?{feeToken:void 0}:{}},{feePayerSignature:void 0,signature:r})}function DP(e){if(!lp(e))return ha(e);const{feePayerSignature:t,gasPrice:r,nonce:n,...i}=vP(e);return{...i,accessList:i.accessList,feePayerSignature:t?{r:te(t.r,{size:32}),s:te(t.s,{size:32}),v:BigInt(t.v??27),yParity:t.yParity}:void 0,nonce:Number(n),typeHex:X2[i.type],type:i.type}}function zP(e){return sf(e)}function VP(e,t){const r=e,n=r.account?Me(r.account):void 0;if(!lp(r))return yn(e);t&&(r.calls=r.calls??[{to:e.to||(!e.data||e.data==="0x"?"0x0000000000000000000000000000000000000000":void 0),value:e.value,data:e.data}]),r.feePayer===!0&&delete r.feeToken;const i=xP({...r,type:"tempo"});t==="estimateGas"&&(i.maxFeePerGas=void 0,i.maxPriorityFeePerGas=void 0),i.to=void 0,i.data=void 0,i.value=void 0;const[s,a]=(()=>{const c=n&&"keyType"in n?n.keyType:n==null?void 0:n.source;return c?c==="webAuthn"?["webAuthn",`0x${"ff".repeat(1400)}`]:["p256","secp256k1"].includes(c)?[c,void 0]:[void 0,void 0]:[void 0,void 0]})(),o=n&&"accessKeyAddress"in n?n.accessKeyAddress:void 0;return{...i,...a?{keyData:a}:{},...o?{keyId:o}:{},...s?{keyType:s}:{},...r.feePayer?{feePayer:typeof r.feePayer=="object"?Me(r.feePayer):r.feePayer}:{}}}const GP=qP();function qP(){return new Map}function WP(e){return`${e.address.toLowerCase()}-${e.chainId}`}function Y2(e,t){const r=WP(t);let n=e.get(r);return n||(n={counter:0,resetScheduled:!1},e.set(r,n)),n}function KP(e,t){const r=Y2(e,t);r.counter=0,r.resetScheduled=!1}function XP(e,t){const r=Y2(e,t);r.resetScheduled||(r.resetScheduled=!0,queueMicrotask(()=>KP(e,t)));const n=r.counter;return r.counter++,n===0?0n:tt(dw(6))}const Z2={blockTime:1e3,extendSchema:xk(),formatters:{transaction:D1({exclude:["aaAuthorizationList"],format:DP}),transactionReceipt:_w({format:zP}),transactionRequest:u3({format:VP})},prepareTransactionRequest:[async(e,{phase:t})=>{var n,i;const r=e;return t==="afterFillParameters"?(r.feePayer&&((n=r.keyAuthorization)==null?void 0:n.signature.type)==="webAuthn"&&(r.gas=(r.gas??0n)+20000n),r):(r.nonceKey=(()=>{var o;if(typeof r.nonceKey<"u"&&r.nonceKey!=="random")return r.nonceKey;const s=((o=r.account)==null?void 0:o.address)??r.from;if(!s||!r.chain)return;const a=XP(GP,{address:s,chainId:r.chain.id});if(a!==0n)return a})(),r.nonce=(()=>{if(typeof r.nonce=="number")return r.nonce;if(r.nonceKey)return 0})(),!r.feeToken&&((i=r.chain)!=null&&i.feeToken)&&(r.feeToken=r.chain.feeToken),r)},{runAt:["beforeFillTransaction","afterFillParameters"]}],serializers:{transaction:(e,t)=>HP(e,t)},async verifyHash(e,t){const{address:r,hash:n,signature:i}=t;if(typeof i=="string"&&i.endsWith(qi.slice(2))){const s=wa(i);if(s.type!=="keychain"){const a=await du(e,{address:r,blockNumber:t.blockNumber,blockTag:t.blockTag});if(!a||a==="0xef01007702c00000000000000000000000000000000000")return nP(s,{address:r,payload:n})}}return await re(e,uc,"verifyHash")({...t,chain:null})}},JP=Ze({...Z2,id:4217,blockExplorers:{default:{name:"Tempo Explorer",url:"https://explore.mainnet.tempo.xyz"}},name:"Tempo Mainnet",nativeCurrency:{name:"USD",symbol:"USD",decimals:6},rpcUrls:{default:{http:["https://rpc.presto.tempo.xyz"],webSocket:["wss://rpc.presto.tempo.xyz"]}}}),YP=Ze({...Z2,id:42431,blockExplorers:{default:{name:"Tempo Explorer",url:"https://explore.moderato.tempo.xyz"}},name:"Tempo Testnet (Moderato)",nativeCurrency:{name:"USD",symbol:"USD",decimals:6},rpcUrls:{default:{http:["https://rpc.moderato.tempo.xyz"],webSocket:["wss://rpc.moderato.tempo.xyz"]}}}),$c=1,ZP=Ze({...pn,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:{...pn.contracts,multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:0},disputeGameFactory:{[$c]:{address:"0x2F12d621a16e2d3285929C9996f478508951dFe4"}},portal:{[$c]:{address:"0x0bd48f6B86a26D3a217d0Fa6FfE2B491B956A7a2"}},l1StandardBridge:{[$c]:{address:"0x81014F44b0a345033bB2b3B21C7a1A308B35fEeA"}}},sourceId:$c}),QP={...G_,rpcUrls:{default:{http:["https://ethereum-sepolia-rpc.publicnode.com"]}}},Q2={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/"]}}},e4={id:46630,name:"Robinhood Testnet",nativeCurrency:{name:"Ethereum",symbol:"ETH",decimals:18},blockExplorers:{default:{name:"Robinhood Testnet Explorer",url:"https://explorer.testnet.chain.robinhood.com"}},rpcUrls:{default:{http:["https://rpc.testnet.chain.robinhood.com"]}}},t4={id:4663,name:"Robinhood",nativeCurrency:{name:"Ethereum",symbol:"ETH",decimals:18},blockExplorers:{default:{name:"Robinhood Explorer",url:"https://robinhoodchain.blockscout.com"}},rpcUrls:{default:{http:["https://rpc.mainnet.chain.robinhood.com"]}}},Ah={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"]}}},Sh={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"]}}},e6={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"]}}},r4={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"]}}},n4={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},t6={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},yf={ethereum:z_,arbitrum:B_,ethereum_sepolia:QP,arbitrum_sepolia:C_,ethereum_localnet:D.EthereumLocalnet,arbitrum_localnet:D.ArbitrumLocalnet,base_sepolia:M2,base:$2,bera_testnet:N_,citrea:n4,citrea_testnet:$_,core:M_,bera:R_,monad:r4,monad_testnet:V_,hyperliquid_testnet:Ah,hyperevm:Sh,unichain:ZP,corn:H_,botanix:Q2,bnbchain:U_,bnbchain_testnet:F_,alpen_testnet:e6,hypercore:{},hypercore_testnet:{},arc_testnet:F2,hyperliquid:Sh,megaeth:t6,hyperevm_testnet:Ah,ink_sepolia:D_,ink:L_,robinhood_testnet:e4,robinhood:t4,tempo_testnet:YP,tempo:JP},r6=e=>{for(const[t,r]of Object.entries(yf))if(r.id===e)return t;return null},kh=async(e,t)=>{var i,s,a;const r=yf[e],n=await t.getChainId();if(r)try{if(r.id===n)return m.Ok({message:"Already on the network",walletClient:t});await t.switchChain({id:r.id});const o=ll({account:t.account,chain:r,transport:um(t.transport)});return m.Ok({message:"Switched chain",walletClient:o})}catch(o){if(i4(o))if(o.code===4902||o.code===-32603)try{await t.addChain({chain:r});const c=ll({account:t.account,chain:r,transport:um(t.transport)});return m.Ok({message:"Added network",walletClient:c})}catch{return m.Err("Failed to add network")}else if((s=(i=o.body)==null?void 0:i.method)!=null&&s.includes("wallet_switchEthereumChain")||(a=o.message)!=null&&a.includes("wallet_switchEthereumChain")){const c=ll({account:t.account,chain:r,transport:N2()});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")},i4=e=>typeof e=="object"&&e!=null&&("code"in e||"message"in e||"body"in e),s4=async(e,t)=>{if(!e.account)return m.Err("No account found");try{const r=await e.sendTransaction({account:e.account,to:m.with0x(t.to),value:BigInt(t.value),data:m.with0x(t.data),gas:BigInt(t.gas_limit),chain:e.chain}),n=await m.waitForTransactionReceipt(e,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 n6{constructor(t,r,n){this.wallet=r,this.auth=n,this.url=t instanceof m.Url?t:new m.Url(t),this.relayer=new xs(this.auth,this.url)}get htlcActorAddress(){if(!this.wallet.account)throw new Error("No account found");return this.wallet.account.address}async initiate(t){if(D.isEvmOrderResponse(t))return this.initiateFromAPI(t);if(!this.wallet.account)return m.Err("No account found");if(!D.isEVM(t.source_swap.chain))return m.Err("Not an EVM chain");if(this.wallet.account.address.toLowerCase()!==t.source_swap.initiator.toLowerCase())return m.Err("Account address and order initiator mismatch");const r=t.source_swap.chain,n=await kh(r,this.wallet);if(!n.ok)return m.Err(n.error);this.wallet=n.val.walletClient;const{source_swap:i}=t;if(!i.amount||!i.timelock||!i.redeemer||!i.secret_hash)return m.Err("Invalid order");const s=await Ys(i.asset,this.url,this.auth);if(!s.ok)return m.Err(s.error);const a=D.ChainAsset.fromString(i.asset),o={redeemer:m.with0x(i.redeemer),timelock:BigInt(i.timelock),amount:BigInt(i.amount),secretHash:m.with0x(i.secret_hash)};return D.isEvmNativeToken(a.chain,a.symbol)?E_(this.wallet,{...o,htlc:s.val.htlcAddress}):x_(this.wallet,this.url,this.auth,{...o,htlc:s.val.htlcAddress,token:s.val.tokenAddress,orderId:t.order_id})}async initiateFromAPI(t){const r=r6(t.initiate_transaction.chain_id);if(!r)return m.Err("Unsupported chain");const n=await kh(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(!t.typed_data){const a=t.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(t.core_to_evm_transfer){const a=await s4(this.wallet,t.core_to_evm_transfer);if(a.error)return m.Err(`Internal bridge failed: ${a.error}`);console.log("Internal bridge completed:",a.val)}if(t.approval_transaction){const a=await A_(this.wallet,t.approval_transaction);if(a.error)return m.Err(`Approval failed: ${a.error}`);console.log("Approval transaction completed:",a.val)}const i=await this.wallet.signTypedData({account:this.wallet.account,...t.typed_data}),s=await zb({wallet:this.wallet,attempt:()=>this.relayer.initiate(t.order_id,i)});if(s)return m.Ok(s);try{const a=D0({address:m.with0x(t.initiate_transaction.to),abi:U2,client:this.wallet}),o=t.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 Vh(a)?m.Ok("already initiated"):m.Err(`Failed to initiate via contract: ${String(a)}`)}}async redeem(t,r){const n=await this.relayer.redeem(t.order_id,r);if(n.error)return m.Err(n.error);try{const i=await this.relayer.redeem(t.order_id,r);if(i.error)return m.Err(i.error);const s=yf[t.destination_swap.chain],o=await t_({chain:s,transport:N2()}).waitForTransactionReceipt({hash:i.val,confirmations:1,timeout:3e5});return o&&o.status==="success"?m.Ok(i.val?i.val:"Redeem hash not found"):m.Err("Redeem failed: Transaction receipt not successful")}catch(i){return m.Err(String(i))}}async refund(){return m.Err("Refund not supported")}}const i6=[{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"}]}],s6=async(e,t,r,n,i)=>{try{const s=await Xa(e.address,t,r,i);if(!s.ok)return m.Err(s.error);if(s.val>=n)return m.Ok("Allowance already approved");const o=st.cairo.uint256(BigInt(n)),c=await e.execute([{contractAddress:m.with0x(t),entrypoint:"approve",calldata:[m.with0x(r),o.low,o.high]}]);await i.waitForTransaction(c.transaction_hash,{retryInterval:3e3,successStates:[st.TransactionExecutionStatus.SUCCEEDED]}),await m.sleep(2e3);for(let u=0;u<20;u++){const f=await Xa(e.address,t,r,i);if(!f.ok)return m.Err(f.error);if(f.val>=n)return m.Ok(c.transaction_hash);await m.sleep(2e3);let l=0n;for(let h=0;h<20;h++){const d=await Xa(e.address,t,r,i);if(!d.ok)return m.Err(d.error);if(l=d.val,l>=n)break;await m.sleep(2e3)}return l<n?m.Err("Allowance not approved"):m.Ok(c.transaction_hash)}return m.Err("Allowance not approved after transaction.")}catch(s){return m.Err(`Failed to check or approve allowance: ${s instanceof Error?s.message:String(s)}`)}},Xa=async(e,t,r,n)=>{try{const s=await new st.Contract({abi:i6,address:m.with0x(t),providerOrAccount:n}).call("allowance",[m.with0x(e),m.with0x(r)]);return m.Ok(BigInt((s==null?void 0:s.toString())||"0"))}catch(i){return m.Err(`Failed to check allowance: ${i instanceof Error?i.message:String(i)}`)}},a6=async(e,t,r,n,i)=>{const s=await Xa(e,t,r,n);return s.ok?m.Ok(s.val>=i):m.Err(s.error)},o6=[{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"}]}],a4={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 c6{constructor(t,r,n,i,s){this.url=t instanceof m.Url?t:new m.Url(t),this.starknetProvider=new st.RpcProvider({nodeUrl:s||ro[n].nodeUrl}),this.account=r,this.chainId=ro[n].chainId,this.auth=i,this.relayer=new xs(this.auth,this.url)}get htlcActorAddress(){if(!this.account.address)throw new Error("No account found");return this.account.address}async initiate(t){if(D.isStarknetOrderResponse(t))return this.initiateWithCreateOrderResponse(t);if(!this.account.address)return m.Err("No account address");const{source_swap:r}=t,{redeemer:n,amount:i}=r;if(!i||!n||!r.secret_hash||!r.timelock)return m.Err("Invalid order");const s=await Ys(r.asset,this.url,this.auth);if(!s.ok)return m.Err(s.error);try{const a=new st.Contract({providerOrAccount:this.starknetProvider,abi:o6,address:s.val.htlcAddress}),o=await(a==null?void 0:a.token()),c=st.num.toHex(o),u=await a6(this.account.address,c,s.val.htlcAddress,this.starknetProvider,BigInt(r.amount));return u.error?m.Err(u.error):u.val?this.initiateRelay(t):this.approveAndInitiate(c,t)}catch(a){return m.Err(String(a))}}async approveAndInitiate(t,r){const{source_swap:n}=r,{redeemer:i,amount:s}=n,{secret_hash:a,timelock:o}=n,c=n.asset;try{const u=st.cairo.uint256(BigInt(s)),f={contractAddress:m.with0x(t),entrypoint:"approve",calldata:[c,u.low,u.high]},l=st.cairo.uint256(s),h=m.hexToU128Array(a),d={contractAddress:m.with0x(c),entrypoint:"initiate",calldata:[i,o.toString(),l.low.toString(),l.high.toString(),...h.map(g=>g.toString())]},b=await this.account.execute([f,d]);return await this.starknetProvider.waitForTransaction(b.transaction_hash,{retryInterval:2e3,successStates:[st.TransactionExecutionStatus.SUCCEEDED]}),m.Ok(b.transaction_hash)}catch(u){return m.Err(`Failed to approve and initiate: ${String(u)}`)}}async initiateRelay(t){const{source_swap:r}=t,n=await Ys(r.asset,this.url,this.auth);if(!n.ok)return m.Err(n.error);const{redeemer:i,amount:s}=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:st.shortString.encodeShortString("2"),chainId:this.chainId,revision:st.TypedDataRevision.ACTIVE},c=m.hexToU128Array(a),u={domain:o,primaryType:"Initiate",types:a4,message:{redeemer:i,amount:st.cairo.uint256(s),timelock:t.source_swap.timelock.toString(),secretHash:c.map(f=>f.toString()),verifyingContract:n.val.htlcAddress}};try{const f=await this.account.signMessage(u),l=Mp(f);if(l.error||!l.val)return m.Err(l.error||"Invalid signature");const h=await this.relayer.initiate(t.order_id,l.val);return h.ok?m.Ok(h.val):m.Err(h.error)}catch(f){return m.Err(`Failed to initiate relayer: ${String(f)}`)}}async redeem(t,r){try{const n=await this.relayer.redeem(t.order_id,r);return n.error?m.Err(n.error):m.Ok(n.val)}catch(n){return m.Err(String(n))}}async executeApprovalTransaction(t){if(!this.account.address)return m.Err("No account address");if(!t.approval_transaction)return m.Ok("No approval transaction required");try{const r=t.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:[st.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(t){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(t);if(n.error)return m.Err(n.error);const{typed_data:i}=t;if(i===null){const c=t.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:[st.TransactionExecutionStatus.SUCCEEDED]}),m.Ok(u.transaction_hash)}const s=await this.account.signMessage(i),a=Mp(s);if(a.error)return m.Err(a.error);const o=await m.Fetcher.patch(this.url.endpoint("/v2/orders").endpoint(t.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 o4="2WXpY8havGjfRxme9LUxtjFHTh1EfU3ur4v6wiK4KdNC",c4={name:"solana_spl_swaps",version:"0.4.0",spec:"0.1.0",description:"Created with Anchor"},u4=[{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:[]}],f4=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],l4=[{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]}],d4=[{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"}],h4=[{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"}]}}],dm={address:o4,metadata:c4,instructions:u4,accounts:f4,events:l4,errors:d4,types:h4},p4="2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",y4={name:"solana_native_swaps",version:"0.3.0",spec:"0.1.0",description:"Created with Anchor"},m4=[{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:[]}],b4=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],g4=[{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]}],w4=[{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"}],v4=[{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]}}]}}],Th={address:p4,metadata:y4,instructions:m4,accounts:b4,events:g4,errors:w4,types:v4};var Un={},mf={};Object.defineProperty(mf,"__esModule",{value:!0});mf.encode=E4;mf.decode=x4;const hm=bs;function E4(e){return e.reduce((t,r)=>t+r.toString(16).padStart(2,"0"),"0x")}function x4(e){e.indexOf("0x")===0&&(e=e.substr(2)),e.length%2===1&&(e="0"+e);let t=e.match(/.{2}/g);return t===null?hm.Buffer.from([]):hm.Buffer.from(t.map(r=>parseInt(r,16)))}var bf={},ps={},dl;Object.defineProperty(ps,"__esModule",{value:!0});ps.isVersionedTransaction=ps.isBrowser=void 0;ps.chunks=A4;ps.isBrowser=process.env.ANCHOR_BROWSER||typeof window<"u"&&!(!((dl=window.process)===null||dl===void 0)&&dl.hasOwnProperty("type"));function A4(e,t){return Array.apply(0,new Array(Math.ceil(e.length/t))).map((r,n)=>e.slice(n*t,(n+1)*t))}const S4=e=>"version"in e;ps.isVersionedTransaction=S4;var hl={},pl={},yl,pm;function u6(){return pm||(pm=1,yl=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var t={},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 i=42;t[r]=i;for(var s in t)return!1;if(typeof Object.keys=="function"&&Object.keys(t).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(t).length!==0)return!1;var a=Object.getOwnPropertySymbols(t);if(a.length!==1||a[0]!==r||!Object.prototype.propertyIsEnumerable.call(t,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var o=Object.getOwnPropertyDescriptor(t,r);if(o.value!==i||o.enumerable!==!0)return!1}return!0}),yl}var ml,ym;function gf(){if(ym)return ml;ym=1;var e=u6();return ml=function(){return e()&&!!Symbol.toStringTag},ml}var bl,mm;function f6(){return mm||(mm=1,bl=Object),bl}var gl,bm;function k4(){return bm||(bm=1,gl=Error),gl}var wl,gm;function T4(){return gm||(gm=1,wl=EvalError),wl}var vl,wm;function I4(){return wm||(wm=1,vl=RangeError),vl}var El,vm;function _4(){return vm||(vm=1,El=ReferenceError),El}var xl,Em;function l6(){return Em||(Em=1,xl=SyntaxError),xl}var Al,xm;function lc(){return xm||(xm=1,Al=TypeError),Al}var Sl,Am;function P4(){return Am||(Am=1,Sl=URIError),Sl}var kl,Sm;function O4(){return Sm||(Sm=1,kl=Math.abs),kl}var Tl,km;function B4(){return km||(km=1,Tl=Math.floor),Tl}var Il,Tm;function C4(){return Tm||(Tm=1,Il=Math.max),Il}var _l,Im;function R4(){return Im||(Im=1,_l=Math.min),_l}var Pl,_m;function N4(){return _m||(_m=1,Pl=Math.pow),Pl}var Ol,Pm;function U4(){return Pm||(Pm=1,Ol=Math.round),Ol}var Bl,Om;function F4(){return Om||(Om=1,Bl=Number.isNaN||function(t){return t!==t}),Bl}var Cl,Bm;function $4(){if(Bm)return Cl;Bm=1;var e=F4();return Cl=function(r){return e(r)||r===0?r:r<0?-1:1},Cl}var Rl,Cm;function M4(){return Cm||(Cm=1,Rl=Object.getOwnPropertyDescriptor),Rl}var Nl,Rm;function va(){if(Rm)return Nl;Rm=1;var e=M4();if(e)try{e([],"length")}catch{e=null}return Nl=e,Nl}var Ul,Nm;function wf(){if(Nm)return Ul;Nm=1;var e=Object.defineProperty||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Ul=e,Ul}var Fl,Um;function j4(){if(Um)return Fl;Um=1;var e=typeof Symbol<"u"&&Symbol,t=u6();return Fl=function(){return typeof e!="function"||typeof Symbol!="function"||typeof e("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:t()},Fl}var $l,Fm;function d6(){return Fm||(Fm=1,$l=typeof Reflect<"u"&&Reflect.getPrototypeOf||null),$l}var Ml,$m;function h6(){if($m)return Ml;$m=1;var e=f6();return Ml=e.getPrototypeOf||null,Ml}var jl,Mm;function H4(){if(Mm)return jl;Mm=1;var e="Function.prototype.bind called on incompatible ",t=Object.prototype.toString,r=Math.max,n="[object Function]",i=function(c,u){for(var f=[],l=0;l<c.length;l+=1)f[l]=c[l];for(var h=0;h<u.length;h+=1)f[h+c.length]=u[h];return f},s=function(c,u){for(var f=[],l=u,h=0;l<c.length;l+=1,h+=1)f[h]=c[l];return f},a=function(o,c){for(var u="",f=0;f<o.length;f+=1)u+=o[f],f+1<o.length&&(u+=c);return u};return jl=function(c){var u=this;if(typeof u!="function"||t.apply(u)!==n)throw new TypeError(e+u);for(var f=s(arguments,1),l,h=function(){if(this instanceof l){var A=u.apply(this,i(f,arguments));return Object(A)===A?A:this}return u.apply(c,i(f,arguments))},d=r(0,u.length-f.length),b=[],g=0;g<d;g++)b[g]="$"+g;if(l=Function("binder","return function ("+a(b,",")+"){ return binder.apply(this,arguments); }")(h),u.prototype){var x=function(){};x.prototype=u.prototype,l.prototype=new x,x.prototype=null}return l},jl}var Hl,jm;function dc(){if(jm)return Hl;jm=1;var e=H4();return Hl=Function.prototype.bind||e,Hl}var Ll,Hm;function dp(){return Hm||(Hm=1,Ll=Function.prototype.call),Ll}var Dl,Lm;function hp(){return Lm||(Lm=1,Dl=Function.prototype.apply),Dl}var zl,Dm;function L4(){return Dm||(Dm=1,zl=typeof Reflect<"u"&&Reflect&&Reflect.apply),zl}var Vl,zm;function p6(){if(zm)return Vl;zm=1;var e=dc(),t=hp(),r=dp(),n=L4();return Vl=n||e.call(r,t),Vl}var Gl,Vm;function pp(){if(Vm)return Gl;Vm=1;var e=dc(),t=lc(),r=dp(),n=p6();return Gl=function(s){if(s.length<1||typeof s[0]!="function")throw new t("a function is required");return n(e,r,s)},Gl}var ql,Gm;function D4(){if(Gm)return ql;Gm=1;var e=pp(),t=va(),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&&t&&t(Object.prototype,"__proto__"),i=Object,s=i.getPrototypeOf;return ql=n&&typeof n.get=="function"?e([n.get]):typeof s=="function"?function(o){return s(o==null?o:i(o))}:!1,ql}var Wl,qm;function yp(){if(qm)return Wl;qm=1;var e=d6(),t=h6(),r=D4();return Wl=e?function(i){return e(i)}:t?function(i){if(!i||typeof i!="object"&&typeof i!="function")throw new TypeError("getProto: not an object");return t(i)}:r?function(i){return r(i)}:null,Wl}var Kl,Wm;function y6(){if(Wm)return Kl;Wm=1;var e=Function.prototype.call,t=Object.prototype.hasOwnProperty,r=dc();return Kl=r.call(e,t),Kl}var Xl,Km;function m6(){if(Km)return Xl;Km=1;var e,t=f6(),r=k4(),n=T4(),i=I4(),s=_4(),a=l6(),o=lc(),c=P4(),u=O4(),f=B4(),l=C4(),h=R4(),d=N4(),b=U4(),g=$4(),x=Function,A=function(oe){try{return x('"use strict"; return ('+oe+").constructor;")()}catch{}},k=va(),w=wf(),v=function(){throw new o},S=k?function(){try{return arguments.callee,v}catch{try{return k(arguments,"callee").get}catch{return v}}}():v,I=j4()(),_=yp(),R=h6(),B=d6(),M=hp(),F=dp(),H={},z=typeof Uint8Array>"u"||!_?e:_(Uint8Array),Q={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?e:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?e:ArrayBuffer,"%ArrayIteratorPrototype%":I&&_?_([][Symbol.iterator]()):e,"%AsyncFromSyncIteratorPrototype%":e,"%AsyncFunction%":H,"%AsyncGenerator%":H,"%AsyncGeneratorFunction%":H,"%AsyncIteratorPrototype%":H,"%Atomics%":typeof Atomics>"u"?e:Atomics,"%BigInt%":typeof BigInt>"u"?e:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?e:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?e:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?e:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":r,"%eval%":eval,"%EvalError%":n,"%Float16Array%":typeof Float16Array>"u"?e:Float16Array,"%Float32Array%":typeof Float32Array>"u"?e:Float32Array,"%Float64Array%":typeof Float64Array>"u"?e:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?e:FinalizationRegistry,"%Function%":x,"%GeneratorFunction%":H,"%Int8Array%":typeof Int8Array>"u"?e:Int8Array,"%Int16Array%":typeof Int16Array>"u"?e:Int16Array,"%Int32Array%":typeof Int32Array>"u"?e:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":I&&_?_(_([][Symbol.iterator]())):e,"%JSON%":typeof JSON=="object"?JSON:e,"%Map%":typeof Map>"u"?e:Map,"%MapIteratorPrototype%":typeof Map>"u"||!I||!_?e:_(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":t,"%Object.getOwnPropertyDescriptor%":k,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?e:Promise,"%Proxy%":typeof Proxy>"u"?e:Proxy,"%RangeError%":i,"%ReferenceError%":s,"%Reflect%":typeof Reflect>"u"?e:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?e:Set,"%SetIteratorPrototype%":typeof Set>"u"||!I||!_?e:_(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?e:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":I&&_?_(""[Symbol.iterator]()):e,"%Symbol%":I?Symbol:e,"%SyntaxError%":a,"%ThrowTypeError%":S,"%TypedArray%":z,"%TypeError%":o,"%Uint8Array%":typeof Uint8Array>"u"?e:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?e:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?e:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?e:Uint32Array,"%URIError%":c,"%WeakMap%":typeof WeakMap>"u"?e:WeakMap,"%WeakRef%":typeof WeakRef>"u"?e:WeakRef,"%WeakSet%":typeof WeakSet>"u"?e:WeakSet,"%Function.prototype.call%":F,"%Function.prototype.apply%":M,"%Object.defineProperty%":w,"%Object.getPrototypeOf%":R,"%Math.abs%":u,"%Math.floor%":f,"%Math.max%":l,"%Math.min%":h,"%Math.pow%":d,"%Math.round%":b,"%Math.sign%":g,"%Reflect.getPrototypeOf%":B};if(_)try{null.error}catch(oe){var U=_(_(oe));Q["%Error.prototype%"]=U}var K=function oe(ae){var ge;if(ae==="%AsyncFunction%")ge=A("async function () {}");else if(ae==="%GeneratorFunction%")ge=A("function* () {}");else if(ae==="%AsyncGeneratorFunction%")ge=A("async function* () {}");else if(ae==="%AsyncGenerator%"){var we=oe("%AsyncGeneratorFunction%");we&&(ge=we.prototype)}else if(ae==="%AsyncIteratorPrototype%"){var Ae=oe("%AsyncGenerator%");Ae&&_&&(ge=_(Ae.prototype))}return Q[ae]=ge,ge},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=dc(),O=y6(),L=q.call(F,Array.prototype.concat),Y=q.call(M,Array.prototype.splice),C=q.call(F,String.prototype.replace),$=q.call(F,String.prototype.slice),V=q.call(F,RegExp.prototype.exec),ie=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,ce=/\\(\\)?/g,de=function(ae){var ge=$(ae,0,1),we=$(ae,-1);if(ge==="%"&&we!=="%")throw new a("invalid intrinsic syntax, expected closing `%`");if(we==="%"&&ge!=="%")throw new a("invalid intrinsic syntax, expected opening `%`");var Ae=[];return C(ae,ie,function(_e,ct,Ne,Kr){Ae[Ae.length]=Ne?C(Kr,ce,"$1"):ct||_e}),Ae},le=function(ae,ge){var we=ae,Ae;if(O(ee,we)&&(Ae=ee[we],we="%"+Ae[0]+"%"),O(Q,we)){var _e=Q[we];if(_e===H&&(_e=K(we)),typeof _e>"u"&&!ge)throw new o("intrinsic "+ae+" exists, but is not available. Please file an issue!");return{alias:Ae,name:we,value:_e}}throw new a("intrinsic "+ae+" does not exist!")};return Xl=function(ae,ge){if(typeof ae!="string"||ae.length===0)throw new o("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof ge!="boolean")throw new o('"allowMissing" argument must be a boolean');if(V(/^%?[^%]*%?$/,ae)===null)throw new a("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var we=de(ae),Ae=we.length>0?we[0]:"",_e=le("%"+Ae+"%",ge),ct=_e.name,Ne=_e.value,Kr=!1,Fi=_e.alias;Fi&&(Ae=Fi[0],Y(we,L([0,1],Fi)));for(var X=1,Xr=!0;X<we.length;X+=1){var Ut=we[X],Ft=$(Ut,0,1),Wn=$(Ut,-1);if((Ft==='"'||Ft==="'"||Ft==="`"||Wn==='"'||Wn==="'"||Wn==="`")&&Ft!==Wn)throw new a("property names with quotes must have matching quotes");if((Ut==="constructor"||!Xr)&&(Kr=!0),Ae+="."+Ut,ct="%"+Ae+"%",O(Q,ct))Ne=Q[ct];else if(Ne!=null){if(!(Ut in Ne)){if(!ge)throw new o("base intrinsic for "+ae+" exists, but the property is not available.");return}if(k&&X+1>=we.length){var Ss=k(Ne,Ut);Xr=!!Ss,Xr&&"get"in Ss&&!("originalValue"in Ss.get)?Ne=Ss.get:Ne=Ne[Ut]}else Xr=O(Ne,Ut),Ne=Ne[Ut];Xr&&!Kr&&(Q[ct]=Ne)}}return Ne},Xl}var Jl,Xm;function hc(){if(Xm)return Jl;Xm=1;var e=m6(),t=pp(),r=t([e("%String.prototype.indexOf%")]);return Jl=function(i,s){var a=e(i,!!s);return typeof a=="function"&&r(i,".prototype.")>-1?t([a]):a},Jl}var Yl,Jm;function z4(){if(Jm)return Yl;Jm=1;var e=gf()(),t=hc(),r=t("Object.prototype.toString"),n=function(o){return e&&o&&typeof o=="object"&&Symbol.toStringTag in o?!1:r(o)==="[object Arguments]"},i=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]"},s=function(){return n(arguments)}();return n.isLegacyArguments=i,Yl=s?n:i,Yl}var Zl,Ym;function V4(){if(Ym)return Zl;Ym=1;var e=hc(),t=gf()(),r=y6(),n=va(),i;if(t){var s=e("RegExp.prototype.exec"),a={},o=function(){throw a},c={toString:o,valueOf:o};typeof Symbol.toPrimitive=="symbol"&&(c[Symbol.toPrimitive]=o),i=function(h){if(!h||typeof h!="object")return!1;var d=n(h,"lastIndex"),b=d&&r(d,"value");if(!b)return!1;try{s(h,c)}catch(g){return g===a}}}else{var u=e("Object.prototype.toString"),f="[object RegExp]";i=function(h){return!h||typeof h!="object"&&typeof h!="function"?!1:u(h)===f}}return Zl=i,Zl}var Ql,Zm;function G4(){if(Zm)return Ql;Zm=1;var e=hc(),t=V4(),r=e("RegExp.prototype.exec"),n=lc();return Ql=function(s){if(!t(s))throw new n("`regex` must be a RegExp");return function(o){return r(s,o)!==null}},Ql}var ed,Qm;function q4(){if(Qm)return ed;Qm=1;const e=(function*(){}).constructor;return ed=()=>e,ed}var td,eb;function W4(){if(eb)return td;eb=1;var e=hc(),t=G4(),r=t(/^\s*(?:function)?\*/),n=gf()(),i=yp(),s=e("Object.prototype.toString"),a=e("Function.prototype.toString"),o=q4();return td=function(u){if(typeof u!="function")return!1;if(r(a(u)))return!0;if(!n){var f=s(u);return f==="[object GeneratorFunction]"}if(!i)return!1;var l=o();return l&&i(u)===l.prototype},td}var rd,tb;function K4(){if(tb)return rd;tb=1;var e=Function.prototype.toString,t=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,r,n;if(typeof t=="function"&&typeof Object.defineProperty=="function")try{r=Object.defineProperty({},"length",{get:function(){throw n}}),n={},t(function(){throw 42},null,r)}catch(k){k!==n&&(t=null)}else t=null;var i=/^\s*class\b/,s=function(w){try{var v=e.call(w);return i.test(v)}catch{return!1}},a=function(w){try{return s(w)?!1:(e.call(w),!0)}catch{return!1}},o=Object.prototype.toString,c="[object Object]",u="[object Function]",f="[object GeneratorFunction]",l="[object HTMLAllCollection]",h="[object HTML document.all class]",d="[object HTMLCollection]",b=typeof Symbol=="function"&&!!Symbol.toStringTag,g=!(0 in[,]),x=function(){return!1};if(typeof document=="object"){var A=document.all;o.call(A)===o.call(document.all)&&(x=function(w){if((g||!w)&&(typeof w>"u"||typeof w=="object"))try{var v=o.call(w);return(v===l||v===h||v===d||v===c)&&w("")==null}catch{}return!1})}return rd=t?function(w){if(x(w))return!0;if(!w||typeof w!="function"&&typeof w!="object")return!1;try{t(w,null,r)}catch(v){if(v!==n)return!1}return!s(w)&&a(w)}:function(w){if(x(w))return!0;if(!w||typeof w!="function"&&typeof w!="object")return!1;if(b)return a(w);if(s(w))return!1;var v=o.call(w);return v!==u&&v!==f&&!/^\[object HTML/.test(v)?!1:a(w)},rd}var nd,rb;function X4(){if(rb)return nd;rb=1;var e=K4(),t=Object.prototype.toString,r=Object.prototype.hasOwnProperty,n=function(c,u,f){for(var l=0,h=c.length;l<h;l++)r.call(c,l)&&(f==null?u(c[l],l,c):u.call(f,c[l],l,c))},i=function(c,u,f){for(var l=0,h=c.length;l<h;l++)f==null?u(c.charAt(l),l,c):u.call(f,c.charAt(l),l,c)},s=function(c,u,f){for(var l in c)r.call(c,l)&&(f==null?u(c[l],l,c):u.call(f,c[l],l,c))};function a(o){return t.call(o)==="[object Array]"}return nd=function(c,u,f){if(!e(u))throw new TypeError("iterator must be a function");var l;arguments.length>=3&&(l=f),a(c)?n(c,u,l):typeof c=="string"?i(c,u,l):s(c,u,l)},nd}var id,nb;function J4(){return nb||(nb=1,id=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]),id}var sd,ib;function Y4(){if(ib)return sd;ib=1;var e=J4(),t=typeof globalThis>"u"?dn:globalThis;return sd=function(){for(var n=[],i=0;i<e.length;i++)typeof t[e[i]]=="function"&&(n[n.length]=e[i]);return n},sd}var ad={exports:{}},od,sb;function Z4(){if(sb)return od;sb=1;var e=wf(),t=l6(),r=lc(),n=va();return od=function(s,a,o){if(!s||typeof s!="object"&&typeof s!="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,f=arguments.length>5?arguments[5]:null,l=arguments.length>6?arguments[6]:!1,h=!!n&&n(s,a);if(e)e(s,a,{configurable:f===null&&h?h.configurable:!f,enumerable:c===null&&h?h.enumerable:!c,value:o,writable:u===null&&h?h.writable:!u});else if(l||!c&&!u&&!f)s[a]=o;else throw new t("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},od}var cd,ab;function Q4(){if(ab)return cd;ab=1;var e=wf(),t=function(){return!!e};return t.hasArrayLengthDefineBug=function(){if(!e)return null;try{return e([],"length",{value:1}).length!==1}catch{return!0}},cd=t,cd}var ud,ob;function eO(){if(ob)return ud;ob=1;var e=m6(),t=Z4(),r=Q4()(),n=va(),i=lc(),s=e("%Math.floor%");return ud=function(o,c){if(typeof o!="function")throw new i("`fn` is not a function");if(typeof c!="number"||c<0||c>4294967295||s(c)!==c)throw new i("`length` must be a positive 32-bit integer");var u=arguments.length>2&&!!arguments[2],f=!0,l=!0;if("length"in o&&n){var h=n(o,"length");h&&!h.configurable&&(f=!1),h&&!h.writable&&(l=!1)}return(f||l||!u)&&(r?t(o,"length",c,!0,!0):t(o,"length",c)),o},ud}var fd,cb;function tO(){if(cb)return fd;cb=1;var e=dc(),t=hp(),r=p6();return fd=function(){return r(e,t,arguments)},fd}var ub;function rO(){return ub||(ub=1,function(e){var t=eO(),r=wf(),n=pp(),i=tO();e.exports=function(a){var o=n(arguments),c=a.length-(arguments.length-1);return t(o,1+(c>0?c:0),!0)},r?r(e.exports,"apply",{value:i}):e.exports.apply=i}(ad)),ad.exports}var ld,fb;function b6(){if(fb)return ld;fb=1;var e=X4(),t=Y4(),r=rO(),n=hc(),i=va(),s=yp(),a=n("Object.prototype.toString"),o=gf()(),c=typeof globalThis>"u"?dn:globalThis,u=t(),f=n("String.prototype.slice"),l=n("Array.prototype.indexOf",!0)||function(x,A){for(var k=0;k<x.length;k+=1)if(x[k]===A)return k;return-1},h={__proto__:null};o&&i&&s?e(u,function(g){var x=new c[g];if(Symbol.toStringTag in x&&s){var A=s(x),k=i(A,Symbol.toStringTag);if(!k&&A){var w=s(A);k=i(w,Symbol.toStringTag)}if(k&&k.get){var v=r(k.get);h["$"+g]=v}}}):e(u,function(g){var x=new c[g],A=x.slice||x.set;if(A){var k=r(A);h["$"+g]=k}});var d=function(x){var A=!1;return e(h,function(k,w){if(!A)try{"$"+k(x)===w&&(A=f(w,1))}catch{}}),A},b=function(x){var A=!1;return e(h,function(k,w){if(!A)try{k(x),A=f(w,1)}catch{}}),A};return ld=function(x){if(!x||typeof x!="object")return!1;if(!o){var A=f(a(x),8,-1);return l(u,A)>-1?A:A!=="Object"?!1:b(x)}return i?d(x):null},ld}var dd,lb;function nO(){if(lb)return dd;lb=1;var e=b6();return dd=function(r){return!!e(r)},dd}var db;function iO(){return db||(db=1,function(e){var t=z4(),r=W4(),n=b6(),i=nO();function s(X){return X.call.bind(X)}var a=typeof BigInt<"u",o=typeof Symbol<"u",c=s(Object.prototype.toString),u=s(Number.prototype.valueOf),f=s(String.prototype.valueOf),l=s(Boolean.prototype.valueOf);if(a)var h=s(BigInt.prototype.valueOf);if(o)var d=s(Symbol.prototype.valueOf);function b(X,Xr){if(typeof X!="object")return!1;try{return Xr(X),!0}catch{return!1}}e.isArgumentsObject=t,e.isGeneratorFunction=r,e.isTypedArray=i;function g(X){return typeof Promise<"u"&&X instanceof Promise||X!==null&&typeof X=="object"&&typeof X.then=="function"&&typeof X.catch=="function"}e.isPromise=g;function x(X){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(X):i(X)||$(X)}e.isArrayBufferView=x;function A(X){return n(X)==="Uint8Array"}e.isUint8Array=A;function k(X){return n(X)==="Uint8ClampedArray"}e.isUint8ClampedArray=k;function w(X){return n(X)==="Uint16Array"}e.isUint16Array=w;function v(X){return n(X)==="Uint32Array"}e.isUint32Array=v;function S(X){return n(X)==="Int8Array"}e.isInt8Array=S;function I(X){return n(X)==="Int16Array"}e.isInt16Array=I;function _(X){return n(X)==="Int32Array"}e.isInt32Array=_;function R(X){return n(X)==="Float32Array"}e.isFloat32Array=R;function B(X){return n(X)==="Float64Array"}e.isFloat64Array=B;function M(X){return n(X)==="BigInt64Array"}e.isBigInt64Array=M;function F(X){return n(X)==="BigUint64Array"}e.isBigUint64Array=F;function H(X){return c(X)==="[object Map]"}H.working=typeof Map<"u"&&H(new Map);function z(X){return typeof Map>"u"?!1:H.working?H(X):X instanceof Map}e.isMap=z;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}e.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}e.isWeakMap=ee;function q(X){return c(X)==="[object WeakSet]"}q.working=typeof WeakSet<"u"&&q(new WeakSet);function O(X){return q(X)}e.isWeakSet=O;function L(X){return c(X)==="[object ArrayBuffer]"}L.working=typeof ArrayBuffer<"u"&&L(new ArrayBuffer);function Y(X){return typeof ArrayBuffer>"u"?!1:L.working?L(X):X instanceof ArrayBuffer}e.isArrayBuffer=Y;function C(X){return c(X)==="[object DataView]"}C.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&C(new DataView(new ArrayBuffer(1),0,1));function $(X){return typeof DataView>"u"?!1:C.working?C(X):X instanceof DataView}e.isDataView=$;var V=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function ie(X){return c(X)==="[object SharedArrayBuffer]"}function ce(X){return typeof V>"u"?!1:(typeof ie.working>"u"&&(ie.working=ie(new V)),ie.working?ie(X):X instanceof V)}e.isSharedArrayBuffer=ce;function de(X){return c(X)==="[object AsyncFunction]"}e.isAsyncFunction=de;function le(X){return c(X)==="[object Map Iterator]"}e.isMapIterator=le;function oe(X){return c(X)==="[object Set Iterator]"}e.isSetIterator=oe;function ae(X){return c(X)==="[object Generator]"}e.isGeneratorObject=ae;function ge(X){return c(X)==="[object WebAssembly.Module]"}e.isWebAssemblyCompiledModule=ge;function we(X){return b(X,u)}e.isNumberObject=we;function Ae(X){return b(X,f)}e.isStringObject=Ae;function _e(X){return b(X,l)}e.isBooleanObject=_e;function ct(X){return a&&b(X,h)}e.isBigIntObject=ct;function Ne(X){return o&&b(X,d)}e.isSymbolObject=Ne;function Kr(X){return we(X)||Ae(X)||_e(X)||ct(X)||Ne(X)}e.isBoxedPrimitive=Kr;function Fi(X){return typeof Uint8Array<"u"&&(Y(X)||ce(X))}e.isAnyArrayBuffer=Fi,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(X){Object.defineProperty(e,X,{enumerable:!1,value:function(){throw new Error(X+" is not supported in userland")}})})}(pl)),pl}var hd,hb;function sO(){return hb||(hb=1,hd=function(t){return t&&typeof t=="object"&&typeof t.copy=="function"&&typeof t.fill=="function"&&typeof t.readUInt8=="function"}),hd}var Mc={exports:{}},pb;function aO(){return pb||(pb=1,typeof Object.create=="function"?Mc.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:Mc.exports=function(t,r){if(r){t.super_=r;var n=function(){};n.prototype=r.prototype,t.prototype=new n,t.prototype.constructor=t}}),Mc.exports}var yb;function g6(){return yb||(yb=1,function(e){var t=Object.getOwnPropertyDescriptors||function($){for(var V=Object.keys($),ie={},ce=0;ce<V.length;ce++)ie[V[ce]]=Object.getOwnPropertyDescriptor($,V[ce]);return ie},r=/%[sdj%]/g;e.format=function(C){if(!S(C)){for(var $=[],V=0;V<arguments.length;V++)$.push(a(arguments[V]));return $.join(" ")}for(var V=1,ie=arguments,ce=ie.length,de=String(C).replace(r,function(oe){if(oe==="%%")return"%";if(V>=ce)return oe;switch(oe){case"%s":return String(ie[V++]);case"%d":return Number(ie[V++]);case"%j":try{return JSON.stringify(ie[V++])}catch{return"[Circular]"}default:return oe}}),le=ie[V];V<ce;le=ie[++V])k(le)||!B(le)?de+=" "+le:de+=" "+a(le);return de},e.deprecate=function(C,$){if(typeof process<"u"&&process.noDeprecation===!0)return C;if(typeof process>"u")return function(){return e.deprecate(C,$).apply(this,arguments)};var V=!1;function ie(){if(!V){if(process.throwDeprecation)throw new Error($);process.traceDeprecation?console.trace($):console.error($),V=!0}return C.apply(this,arguments)}return ie};var n={},i=/^$/;if(process.env.NODE_DEBUG){var s=process.env.NODE_DEBUG;s=s.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),i=new RegExp("^"+s+"$","i")}e.debuglog=function(C){if(C=C.toUpperCase(),!n[C])if(i.test(C)){var $=process.pid;n[C]=function(){var V=e.format.apply(e,arguments);console.error("%s %d: %s",C,$,V)}}else n[C]=function(){};return n[C]};function a(C,$){var V={seen:[],stylize:c};return arguments.length>=3&&(V.depth=arguments[2]),arguments.length>=4&&(V.colors=arguments[3]),A($)?V.showHidden=$:$&&e._extend(V,$),_(V.showHidden)&&(V.showHidden=!1),_(V.depth)&&(V.depth=2),_(V.colors)&&(V.colors=!1),_(V.customInspect)&&(V.customInspect=!0),V.colors&&(V.stylize=o),f(V,C,V.depth)}e.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(C,$){var V=a.styles[$];return V?"\x1B["+a.colors[V][0]+"m"+C+"\x1B["+a.colors[V][1]+"m":C}function c(C,$){return C}function u(C){var $={};return C.forEach(function(V,ie){$[V]=!0}),$}function f(C,$,V){if(C.customInspect&&$&&H($.inspect)&&$.inspect!==e.inspect&&!($.constructor&&$.constructor.prototype===$)){var ie=$.inspect(V,C);return S(ie)||(ie=f(C,ie,V)),ie}var ce=l(C,$);if(ce)return ce;var de=Object.keys($),le=u(de);if(C.showHidden&&(de=Object.getOwnPropertyNames($)),F($)&&(de.indexOf("message")>=0||de.indexOf("description")>=0))return h($);if(de.length===0){if(H($)){var oe=$.name?": "+$.name:"";return C.stylize("[Function"+oe+"]","special")}if(R($))return C.stylize(RegExp.prototype.toString.call($),"regexp");if(M($))return C.stylize(Date.prototype.toString.call($),"date");if(F($))return h($)}var ae="",ge=!1,we=["{","}"];if(x($)&&(ge=!0,we=["[","]"]),H($)){var Ae=$.name?": "+$.name:"";ae=" [Function"+Ae+"]"}if(R($)&&(ae=" "+RegExp.prototype.toString.call($)),M($)&&(ae=" "+Date.prototype.toUTCString.call($)),F($)&&(ae=" "+h($)),de.length===0&&(!ge||$.length==0))return we[0]+ae+we[1];if(V<0)return R($)?C.stylize(RegExp.prototype.toString.call($),"regexp"):C.stylize("[Object]","special");C.seen.push($);var _e;return ge?_e=d(C,$,V,le,de):_e=de.map(function(ct){return b(C,$,V,le,ct,ge)}),C.seen.pop(),g(_e,ae,we)}function l(C,$){if(_($))return C.stylize("undefined","undefined");if(S($)){var V="'"+JSON.stringify($).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return C.stylize(V,"string")}if(v($))return C.stylize(""+$,"number");if(A($))return C.stylize(""+$,"boolean");if(k($))return C.stylize("null","null")}function h(C){return"["+Error.prototype.toString.call(C)+"]"}function d(C,$,V,ie,ce){for(var de=[],le=0,oe=$.length;le<oe;++le)q($,String(le))?de.push(b(C,$,V,ie,String(le),!0)):de.push("");return ce.forEach(function(ae){ae.match(/^\d+$/)||de.push(b(C,$,V,ie,ae,!0))}),de}function b(C,$,V,ie,ce,de){var le,oe,ae;if(ae=Object.getOwnPropertyDescriptor($,ce)||{value:$[ce]},ae.get?ae.set?oe=C.stylize("[Getter/Setter]","special"):oe=C.stylize("[Getter]","special"):ae.set&&(oe=C.stylize("[Setter]","special")),q(ie,ce)||(le="["+ce+"]"),oe||(C.seen.indexOf(ae.value)<0?(k(V)?oe=f(C,ae.value,null):oe=f(C,ae.value,V-1),oe.indexOf(`
|
|
73
|
+
`)>-1&&(de?oe=oe.split(`
|
|
74
|
+
`).map(function(ge){return" "+ge}).join(`
|
|
75
|
+
`).slice(2):oe=`
|
|
76
|
+
`+oe.split(`
|
|
77
|
+
`).map(function(ge){return" "+ge}).join(`
|
|
78
|
+
`))):oe=C.stylize("[Circular]","special")),_(le)){if(de&&ce.match(/^\d+$/))return oe;le=JSON.stringify(""+ce),le.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(le=le.slice(1,-1),le=C.stylize(le,"name")):(le=le.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),le=C.stylize(le,"string"))}return le+": "+oe}function g(C,$,V){var ie=C.reduce(function(ce,de){return de.indexOf(`
|
|
79
|
+
`)>=0,ce+de.replace(/\u001b\[\d\d?m/g,"").length+1},0);return ie>60?V[0]+($===""?"":$+`
|
|
80
|
+
`)+" "+C.join(`,
|
|
81
|
+
`)+" "+V[1]:V[0]+$+" "+C.join(", ")+" "+V[1]}e.types=iO();function x(C){return Array.isArray(C)}e.isArray=x;function A(C){return typeof C=="boolean"}e.isBoolean=A;function k(C){return C===null}e.isNull=k;function w(C){return C==null}e.isNullOrUndefined=w;function v(C){return typeof C=="number"}e.isNumber=v;function S(C){return typeof C=="string"}e.isString=S;function I(C){return typeof C=="symbol"}e.isSymbol=I;function _(C){return C===void 0}e.isUndefined=_;function R(C){return B(C)&&Q(C)==="[object RegExp]"}e.isRegExp=R,e.types.isRegExp=R;function B(C){return typeof C=="object"&&C!==null}e.isObject=B;function M(C){return B(C)&&Q(C)==="[object Date]"}e.isDate=M,e.types.isDate=M;function F(C){return B(C)&&(Q(C)==="[object Error]"||C instanceof Error)}e.isError=F,e.types.isNativeError=F;function H(C){return typeof C=="function"}e.isFunction=H;function z(C){return C===null||typeof C=="boolean"||typeof C=="number"||typeof C=="string"||typeof C=="symbol"||typeof C>"u"}e.isPrimitive=z,e.isBuffer=sO();function Q(C){return Object.prototype.toString.call(C)}function U(C){return C<10?"0"+C.toString(10):C.toString(10)}var K=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ee(){var C=new Date,$=[U(C.getHours()),U(C.getMinutes()),U(C.getSeconds())].join(":");return[C.getDate(),K[C.getMonth()],$].join(" ")}e.log=function(){console.log("%s - %s",ee(),e.format.apply(e,arguments))},e.inherits=aO(),e._extend=function(C,$){if(!$||!B($))return C;for(var V=Object.keys($),ie=V.length;ie--;)C[V[ie]]=$[V[ie]];return C};function q(C,$){return Object.prototype.hasOwnProperty.call(C,$)}var O=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;e.promisify=function($){if(typeof $!="function")throw new TypeError('The "original" argument must be of type Function');if(O&&$[O]){var V=$[O];if(typeof V!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(V,O,{value:V,enumerable:!1,writable:!1,configurable:!0}),V}function V(){for(var ie,ce,de=new Promise(function(ae,ge){ie=ae,ce=ge}),le=[],oe=0;oe<arguments.length;oe++)le.push(arguments[oe]);le.push(function(ae,ge){ae?ce(ae):ie(ge)});try{$.apply(this,le)}catch(ae){ce(ae)}return de}return Object.setPrototypeOf(V,Object.getPrototypeOf($)),O&&Object.defineProperty(V,O,{value:V,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(V,t($))},e.promisify.custom=O;function L(C,$){if(!C){var V=new Error("Promise was rejected with a falsy value");V.reason=C,C=V}return $(C)}function Y(C){if(typeof C!="function")throw new TypeError('The "original" argument must be of type Function');function $(){for(var V=[],ie=0;ie<arguments.length;ie++)V.push(arguments[ie]);var ce=V.pop();if(typeof ce!="function")throw new TypeError("The last argument must be of type Function");var de=this,le=function(){return ce.apply(de,arguments)};C.apply(this,V).then(function(oe){process.nextTick(le.bind(null,null,oe))},function(oe){process.nextTick(L.bind(null,oe,le))})}return Object.setPrototypeOf($,Object.getPrototypeOf(C)),Object.defineProperties($,t(C)),$}e.callbackify=Y}(hl)),hl}Object.defineProperty(bf,"__esModule",{value:!0});bf.decode=oO;bf.encode=cO;const w6=ps;function oO(e){return(w6.isBrowser?new TextDecoder("utf-8"):new(g6()).TextDecoder("utf-8")).decode(e)}function cO(e){return(w6.isBrowser?new TextEncoder:new(g6()).TextEncoder("utf-8")).encode(e)}var vf={},Ih={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */(function(e,t){var r=bs,n=r.Buffer;function i(a,o){for(var c in a)o[c]=a[c]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=s);function s(a,o,c){return n(a,o,c)}s.prototype=Object.create(n.prototype),i(n,s),s.from=function(a,o,c){if(typeof a=="number")throw new TypeError("Argument must not be a number");return n(a,o,c)},s.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},s.allocUnsafe=function(a){if(typeof a!="number")throw new TypeError("Argument must be a number");return n(a)},s.allocUnsafeSlow=function(a){if(typeof a!="number")throw new TypeError("Argument must be a number");return r.SlowBuffer(a)}})(Ih,Ih.exports);var uO=Ih.exports,jc=uO.Buffer;function fO(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var n=0;n<e.length;n++){var i=e.charAt(n),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=n}var a=e.length,o=e.charAt(0),c=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(d){if((Array.isArray(d)||d instanceof Uint8Array)&&(d=jc.from(d)),!jc.isBuffer(d))throw new TypeError("Expected Buffer");if(d.length===0)return"";for(var b=0,g=0,x=0,A=d.length;x!==A&&d[x]===0;)x++,b++;for(var k=(A-x)*u+1>>>0,w=new Uint8Array(k);x!==A;){for(var v=d[x],S=0,I=k-1;(v!==0||S<g)&&I!==-1;I--,S++)v+=256*w[I]>>>0,w[I]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,x++}for(var _=k-g;_!==k&&w[_]===0;)_++;for(var R=o.repeat(b);_<k;++_)R+=e.charAt(w[_]);return R}function l(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return jc.alloc(0);for(var b=0,g=0,x=0;d[b]===o;)g++,b++;for(var A=(d.length-b)*c+1>>>0,k=new Uint8Array(A);b<d.length;){var w=d.charCodeAt(b);if(w>255)return;var v=t[w];if(v===255)return;for(var S=0,I=A-1;(v!==0||S<x)&&I!==-1;I--,S++)v+=a*k[I]>>>0,k[I]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");x=S,b++}for(var _=A-x;_!==A&&k[_]===0;)_++;var R=jc.allocUnsafe(g+(A-_));R.fill(0,0,g);for(var B=g;_!==A;)R[B++]=k[_++];return R}function h(d){var b=l(d);if(b)return b;throw new Error("Non-base"+a+" character")}return{encode:f,decodeUnsafe:l,decode:h}}var lO=fO,dO=lO,hO="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",pO=dO(hO),yO=dn&&dn.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(vf,"__esModule",{value:!0});vf.encode=mO;vf.decode=bO;const v6=yO(pO);function mO(e){return v6.default.encode(e)}function bO(e){return v6.default.decode(e)}var Ef={};Object.defineProperty(Ef,"__esModule",{value:!0});Ef.encode=wO;Ef.decode=vO;const gO=bs;function wO(e){return e.toString("base64")}function vO(e){return gO.Buffer.from(e,"base64")}var EO=dn&&dn.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),xO=dn&&dn.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),xf=dn&&dn.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&EO(t,e,r);return xO(t,e),t};Object.defineProperty(Un,"__esModule",{value:!0});Un.base64=Un.bs58=Un.utf8=E6=Un.hex=void 0;var E6=Un.hex=xf(mf);Un.utf8=xf(bf);Un.bs58=xf(vf);Un.base64=xf(Ef);class wi{constructor(t,r,n,i,s){try{this.swapId=Array.from(Buffer.from(t,"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 Or.web3.PublicKey(r)}catch(a){throw new Error("Error decoding redeemer. Ensure it is a valid base58 encoded",{cause:a})}try{this.amount=new _d.BigNumber(i.toString(10),10),this.expiresIn=new _d.BigNumber(s)}catch(a){throw new Error("Error decoding amount. Invalid value for amount",{cause:a})}if(!(Number.isInteger(s)&&s>0))throw new Error("expiresIn must be a positive integer.")}static from(t){let r;if(t.source_swap.chain.includes("solana"))r=t.source_swap;else if(t.destination_swap.chain.includes("solana"))r=t.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:i,secret_hash:s,timelock:a}=r,o=BigInt(r.amount);return new wi(n,i,s,o,a)}}function x6(e){let t;try{t=[...E6.decode(e)]}catch(r){throw new Error("Error decoding secret. Ensure it is a hex string",{cause:r})}if(t.length!=32)throw new Error("Invalid Secret size. Expected 32 bytes, got "+t.length);return t}class A6{constructor(t,r,n,i,s){var l,h;if(this.provider=t,this.url=r,!t)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?Pd.mainnet:Pd.staging,o={native:((l=s==null?void 0:s.programAddress)==null?void 0:l.native)??a.native,spl:((h=s==null?void 0:s.programAddress)==null?void 0:h.spl)??a.spl},c=(s==null?void 0:s.relayer)??Hb[n];this.auth=i;try{this.relayer=new Or.web3.PublicKey(c)}catch(d){throw new Error("Error decoding relayer public key. Ensure it is base58 encoded.",{cause:d})}this.relayerClient=new xs(this.auth,this.url);const u=o.spl?{...dm,metadata:{...dm.metadata??{}},address:o.spl}:void 0,f=o.native?{...Th,metadata:{...Th.metadata??{}},address:o.native}:void 0;try{this.splProgram=u?new Or.Program(u,this.provider):void 0,this.nativeProgram=f?new Or.Program(f,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(t){if(!t)return m.Err("Order is required");if(D.isSolanaOrderResponse(t))return this.initiateWithCreateOrderResponse(t);try{const r=D.ChainAsset.fromString(t.source_swap.asset);return D.isSolanaNativeToken(r.chain,r.symbol)?this.nativeProgram?await this.initiateNativeSwap(t):m.Err("Native program is not initialized"):this.splProgram?await this.initiateSplSwap(t):m.Err("SPL program is not initialized")}catch(r){return m.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async sendSplViaRelayer(t,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return m.Err(n.error);t.recentBlockhash=(await this.provider.connection.getLatestBlockhash()).blockhash,t.feePayer=this.relayer;const s=(await this.provider.wallet.signTransaction(t)).serialize({requireAllSignatures:!1}).toString("base64"),a=await m.Fetcher.post(this.url.endpoint("/initiate"),{body:JSON.stringify({order_id:r,serialized_tx:s}),headers:{...n.val,"Content-Type":"application/json"}});return a.error||!a.result?m.Err(`Error from Relayer: ${a.error}`):await bc(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(t,r){if(!r)return m.Err("Order is required");try{const n=await this.provider.sendAndConfirm(t);return n?await bc(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(t){if(!this.splProgram)return m.Err("SPL program is not initialized");try{const{redeemer:r,secretHash:n,amount:i,expiresIn:s}=wi.from(t),a=this.splProgram.methods.initiate(s,r,n,i,null),o=await Ys(t.source_swap.asset,this.url,this.auth);if(!o.ok)return m.Err(o.error);const{tokenAddress:c}=o.val,u=new Or.web3.PublicKey(c),f={initiator:this.provider.publicKey,mint:u,initiatorTokenAccount:ev.getAssociatedTokenAddressSync(u,this.provider.publicKey),sponsor:this.relayer},l=await a.accounts(f).transaction();return this.sendSplViaRelayer(l,t.order_id)}catch(r){return m.Err(`Error initiating SPL swap: ${r instanceof Error?r.message:String(r)}`)}}async initiateNativeSwap(t){if(!this.nativeProgram)return m.Err("Native program is not initialized");try{const{redeemer:r,secretHash:n,amount:i,expiresIn:s}=wi.from(t),a=await this.nativeProgram.methods.initiate(i,s,r,n).accounts({initiator:this.provider.publicKey}).transaction();return this.initiateViaHTLC(a,t)}catch(r){return m.Err(`Error initiating native swap: ${r instanceof Error?r.message:String(r)}`)}}async initiateWithCreateOrderResponse(t){if(!this.relayer)return m.Err("No relayer address");const{versioned_tx:r,versioned_tx_gasless:n}=t;if(n===null)try{const s=Buffer.from(r,"base64"),a=Or.web3.VersionedTransaction.deserialize(s),o=await this.provider.sendAndConfirm(a);return await bc(this.provider.connection,o)?m.Ok(o):m.Err("Failed to initiate HTLC transaction")}catch(s){return m.Err(`Error in non-gasless flow: ${s}`)}const i=await this.auth.getAuthHeaders();if(!i.ok)return m.Err(i.error);try{const s=Or.web3.VersionedTransaction.deserialize(Buffer.from(n,"base64")),a=await this.provider.wallet.signTransaction(s);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(t.order_id,c);return u.error?m.Err(u.error):u.val?m.Ok(u.val):m.Err("Initiate: No result found")}catch(s){return m.Err(`Error initiating with create order response: ${s}`)}}async redeem(t,r){try{const n=x6(r),i=await this.relayerClient.redeem(t.order_id,Buffer.from(n).toString("hex"));if(i.error||!i.val)return m.Err(`Redeem: Error from relayer: ${i.error}`);const s=i.val;return await bc(this.provider.connection,s)?m.Ok(s):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 S6="1.45.2",AO="1.62.0",SO={"-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 k6 extends Error{}class T6 extends k6{constructor(t,r){super(t),this.code=r,this.type=SO[r]??"ServerError"}}class kO extends k6{constructor(t,r,n){super(t),this.status=r,this.statusText=n}}var I6=e=>{throw TypeError(e)},mp=(e,t,r)=>t.has(e)||I6("Cannot "+r),ze=(e,t,r)=>(mp(e,t,"read from private field"),r?r.call(e):t.get(e)),Hi=(e,t,r)=>t.has(e)?I6("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Xs=(e,t,r,n)=>(mp(e,t,"write to private field"),t.set(e,r),r),_6=(e,t,r)=>(mp(e,t,"access private method"),r),TO=(e,t,r,n)=>({set _(i){Xs(e,t,i)},get _(){return ze(e,t,n)}}),ui,Ja,Bn,Wi,Co,Ki,yu,P6,O6;function IO(e){const t=new URL(e);return t.protocol=t.protocol.replace("http","ws"),t.toString()}const _O={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5};class PO{constructor(t,r={}){if(Hi(this,yu),Hi(this,ui,0),Hi(this,Ja,0),Hi(this,Bn,null),Hi(this,Wi,null),Hi(this,Co,new Set),Hi(this,Ki,new Map),this.endpoint=t,this.options={..._O,...r},!this.options.WebSocketConstructor)throw new Error("Missing WebSocket constructor");this.endpoint.startsWith("http")&&(this.endpoint=IO(this.endpoint))}async makeRequest(t,r,n){const i=await _6(this,yu,P6).call(this);return new Promise((s,a)=>{Xs(this,ui,ze(this,ui)+1),ze(this,Ki).set(ze(this,ui),{resolve:s,reject:a,timeout:setTimeout(()=>{ze(this,Ki).delete(ze(this,ui)),a(new Error(`Request timeout: ${t}`))},this.options.callTimeout)}),n==null||n.addEventListener("abort",()=>{ze(this,Ki).delete(ze(this,ui)),a(n.reason)}),i.send(JSON.stringify({jsonrpc:"2.0",id:ze(this,ui),method:t,params:r}))}).then(({error:s,result:a})=>{if(s)throw new T6(s.message,s.code);return a})}async subscribe(t){const r=new OO(t);return ze(this,Co).add(r),await r.subscribe(this),()=>r.unsubscribe(this)}}ui=new WeakMap;Ja=new WeakMap;Bn=new WeakMap;Wi=new WeakMap;Co=new WeakMap;Ki=new WeakMap;yu=new WeakSet;P6=function(){return ze(this,Wi)?ze(this,Wi):(Xs(this,Wi,new Promise(e=>{var t;(t=ze(this,Bn))==null||t.close(),Xs(this,Bn,new this.options.WebSocketConstructor(this.endpoint)),ze(this,Bn).addEventListener("open",()=>{Xs(this,Ja,0),e(ze(this,Bn))}),ze(this,Bn).addEventListener("close",()=>{TO(this,Ja)._++,ze(this,Ja)<=this.options.maxReconnects&&setTimeout(()=>{_6(this,yu,O6).call(this)},this.options.reconnectTimeout)}),ze(this,Bn).addEventListener("message",({data:r})=>{let n;try{n=JSON.parse(r)}catch(i){console.error(new Error(`Failed to parse RPC message: ${r}`,{cause:i}));return}if("id"in n&&n.id!=null&&ze(this,Ki).has(n.id)){const{resolve:i,timeout:s}=ze(this,Ki).get(n.id);clearTimeout(s),i(n)}else if("params"in n){const{params:i}=n;ze(this,Co).forEach(s=>{s.subscriptionId===i.subscription&&i.subscription===s.subscriptionId&&s.onMessage(i.result)})}})})),ze(this,Wi))};O6=async function(){var e;return(e=ze(this,Bn))==null||e.close(),Xs(this,Wi,null),Promise.allSettled([...ze(this,Co)].map(t=>t.subscribe(this)))};class OO{constructor(t){this.subscriptionId=null,this.subscribed=!1,this.input=t}onMessage(t){this.subscribed&&this.input.onMessage(t)}async unsubscribe(t){const{subscriptionId:r}=this;return this.subscribed=!1,r==null?!1:(this.subscriptionId=null,t.makeRequest(this.input.unsubscribe,[r]))}async subscribe(t){this.subscriptionId=null,this.subscribed=!0;const r=await t.makeRequest(this.input.method,this.input.params,this.input.signal);this.subscribed&&(this.subscriptionId=r)}}var B6=e=>{throw TypeError(e)},bp=(e,t,r)=>t.has(e)||B6("Cannot "+r),Er=(e,t,r)=>(bp(e,t,"read from private field"),r?r.call(e):t.get(e)),Hc=(e,t,r)=>t.has(e)?B6("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),_h=(e,t,r,n)=>(bp(e,t,"write to private field"),t.set(e,r),r),BO=(e,t,r)=>(bp(e,t,"access private method"),r),Da,Br,Ya,Ph,C6;class CO{constructor(t){Hc(this,Ph),Hc(this,Da,0),Hc(this,Br),Hc(this,Ya),_h(this,Br,t)}fetch(t,r){const n=Er(this,Br).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(t,r)}async request(t){var i,s;_h(this,Da,Er(this,Da)+1);const r=await this.fetch(((i=Er(this,Br).rpc)==null?void 0:i.url)??Er(this,Br).url,{method:"POST",signal:t.signal,headers:{"Content-Type":"application/json","Client-Sdk-Type":"typescript","Client-Sdk-Version":S6,"Client-Target-Api-Version":AO,"Client-Request-Method":t.method,...(s=Er(this,Br).rpc)==null?void 0:s.headers},body:JSON.stringify({jsonrpc:"2.0",id:Er(this,Da),method:t.method,params:t.params})});if(!r.ok)throw new kO(`Unexpected status code: ${r.status}`,r.status,r.statusText);const n=await r.json();if("error"in n&&n.error!=null)throw new T6(n.error.message,n.error.code);return n.result}async subscribe(t){const r=await BO(this,Ph,C6).call(this).subscribe(t);return t.signal&&(t.signal.throwIfAborted(),t.signal.addEventListener("abort",()=>{r()})),async()=>!!await r()}}Da=new WeakMap;Br=new WeakMap;Ya=new WeakMap;Ph=new WeakSet;C6=function(){var e;if(!Er(this,Ya)){const t=Er(this,Br).WebSocketConstructor??WebSocket;if(!t)throw new Error("The current environment does not support WebSocket, you can provide a WebSocketConstructor in the options for SuiHTTPTransport.");_h(this,Ya,new PO(((e=Er(this,Br).websocket)==null?void 0:e.url)??Er(this,Br).url,{WebSocketConstructor:t,...Er(this,Br).websocket}))}return Er(this,Ya)};function mb(e){switch(e){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: ${e}`)}}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function RO(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function R6(e,t){return Array.isArray(t)?t.length===0?!0:e?t.every(r=>typeof r=="string"):t.every(r=>Number.isSafeInteger(r)):!1}function Oh(e,t){if(typeof t!="string")throw new Error(`${e}: string expected`);return!0}function N6(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function Bh(e){if(!Array.isArray(e))throw new Error("array expected")}function U6(e,t){if(!R6(!0,t))throw new Error(`${e}: array of strings expected`)}function NO(e,t){if(!R6(!1,t))throw new Error(`${e}: array of numbers expected`)}function UO(...e){const t=s=>s,r=(s,a)=>o=>s(a(o)),n=e.map(s=>s.encode).reduceRight(r,t),i=e.map(s=>s.decode).reduce(r,t);return{encode:n,decode:i}}function FO(e){const t=typeof e=="string"?e.split(""):e,r=t.length;U6("alphabet",t);const n=new Map(t.map((i,s)=>[i,s]));return{encode:i=>(Bh(i),i.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${e}`);return t[s]})),decode:i=>(Bh(i),i.map(s=>{Oh("alphabet.decode",s);const a=n.get(s);if(a===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${e}`);return a}))}}function $O(e=""){return Oh("join",e),{encode:t=>(U6("join.decode",t),t.join(e)),decode:t=>(Oh("join.decode",t),t.split(e))}}function bb(e,t,r){if(t<2)throw new Error(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(Bh(e),!e.length)return[];let n=0;const i=[],s=Array.from(e,o=>{if(N6(o),o<0||o>=t)throw new Error(`invalid integer: ${o}`);return o}),a=s.length;for(;;){let o=0,c=!0;for(let u=n;u<a;u++){const f=s[u],l=t*o,h=l+f;if(!Number.isSafeInteger(h)||l/t!==o||h-f!==l)throw new Error("convertRadix: carry overflow");const d=h/r;o=h%r;const b=Math.floor(d);if(s[u]=b,!Number.isSafeInteger(b)||b*r+o!==h)throw new Error("convertRadix: carry overflow");if(c)b?c=!1:n=u;else continue}if(i.push(o),c)break}for(let o=0;o<e.length-1&&e[o]===0;o++)i.push(0);return i.reverse()}function MO(e){N6(e);const t=2**8;return{encode:r=>{if(!RO(r))throw new Error("radix.encode input should be Uint8Array");return bb(Array.from(r),t,e)},decode:r=>(NO("radix.decode",r),Uint8Array.from(bb(r,e,t)))}}const jO=e=>UO(MO(58),FO(e),$O("")),F6=jO("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),Af=e=>F6.encode(e),Ro=e=>F6.decode(e);function cr(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))}const pd=8192;function Bt(e){if(e.length<pd)return btoa(String.fromCharCode(...e));let t="";for(var r=0;r<e.length;r+=pd){const n=e.slice(r,r+pd);t+=String.fromCharCode(...n)}return btoa(t)}function $6(e){var i;const t=e.startsWith("0x")?e.slice(2):e,r=t.length%2===0?t:`0${t}`,n=((i=r.match(/[0-9a-fA-F]{2}/g))==null?void 0:i.map(s=>parseInt(s,16)))??[];if(n.length!==r.length/2)throw new Error(`Invalid hex string ${e}`);return Uint8Array.from(n)}function oa(e){return e.reduce((t,r)=>t+r.toString(16).padStart(2,"0"),"")}function Sf(e,t){return Array.from({length:Math.ceil(e.length/t)},(r,n)=>e.slice(n*t,(n+1)*t))}class M6{constructor(t,r){if(typeof t!="function")throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but got: ${t}.`);this._batchLoadFn=t,this._maxBatchSize=zO(r),this._batchScheduleFn=VO(r),this._cacheKeyFn=GO(r),this._cacheMap=qO(r),this._batch=null,this.name=WO(r)}load(t){if(t==null)throw new TypeError(`The loader.load() function must be called with a value, but got: ${String(t)}.`);const r=LO(this),n=this._cacheMap;let i;if(n){i=this._cacheKeyFn(t);const a=n.get(i);if(a){const o=r.cacheHits||(r.cacheHits=[]);return new Promise(c=>{o.push(()=>{c(a)})})}}r.keys.push(t);const s=new Promise((a,o)=>{r.callbacks.push({resolve:a,reject:o})});return n&&n.set(i,s),s}loadMany(t){if(!j6(t))throw new TypeError(`The loader.loadMany() function must be called with Array<key>, but got: ${t}.`);const r=[];for(let n=0;n<t.length;n++)r.push(this.load(t[n]).catch(i=>i));return Promise.all(r)}clear(t){const r=this._cacheMap;if(r){const n=this._cacheKeyFn(t);r.delete(n)}return this}clearAll(){const t=this._cacheMap;return t&&t.clear(),this}prime(t,r){const n=this._cacheMap;if(n){const i=this._cacheKeyFn(t);if(n.get(i)===void 0){let s;r instanceof Error?(s=Promise.reject(r),s.catch(()=>{})):s=Promise.resolve(r),n.set(i,s)}}return this}}const HO=typeof process=="object"&&typeof process.nextTick=="function"?function(e){yd||(yd=Promise.resolve()),yd.then(()=>{process.nextTick(e)})}:typeof setImmediate=="function"?function(e){setImmediate(e)}:function(e){setTimeout(e)};let yd;function LO(e){const t=e._batch;if(t!==null&&!t.hasDispatched&&t.keys.length<e._maxBatchSize)return t;const r={hasDispatched:!1,keys:[],callbacks:[]};return e._batch=r,e._batchScheduleFn(()=>{DO(e,r)}),r}function DO(e,t){if(t.hasDispatched=!0,t.keys.length===0){Ch(t);return}let r;try{r=e._batchLoadFn(t.keys)}catch(n){return md(e,t,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 md(e,t,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(!j6(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!==t.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.
|
|
82
|
+
|
|
83
|
+
Keys:
|
|
84
|
+
${String(t.keys)}
|
|
85
|
+
|
|
86
|
+
Values:
|
|
87
|
+
${String(n)}`);Ch(t);for(let i=0;i<t.callbacks.length;i++){const s=n[i];s instanceof Error?t.callbacks[i].reject(s):t.callbacks[i].resolve(s)}}).catch(n=>{md(e,t,n)})}function md(e,t,r){Ch(t);for(let n=0;n<t.keys.length;n++)e.clear(t.keys[n]),t.callbacks[n].reject(r)}function Ch(e){if(e.cacheHits)for(let t=0;t<e.cacheHits.length;t++)e.cacheHits[t]()}function zO(e){if(!(!e||e.batch!==!1))return 1;const r=e&&e.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 VO(e){const t=e&&e.batchScheduleFn;if(t===void 0)return HO;if(typeof t!="function")throw new TypeError(`batchScheduleFn must be a function: ${t}`);return t}function GO(e){const t=e&&e.cacheKeyFn;if(t===void 0)return r=>r;if(typeof t!="function")throw new TypeError(`cacheKeyFn must be a function: ${t}`);return t}function qO(e){if(!(!e||e.cache!==!1))return null;const r=e&&e.cacheMap;if(r===void 0)return new Map;if(r!==null){const i=["get","set","delete","clear"].filter(s=>r&&typeof r[s]!="function");if(i.length!==0)throw new TypeError("Custom cacheMap missing methods: "+i.join(", "))}return r}function WO(e){return e&&e.name?e.name:null}function j6(e){return typeof e=="object"&&e!==null&&"length"in e&&typeof e.length=="number"&&(e.length===0||e.length>0&&Object.prototype.hasOwnProperty.call(e,e.length-1))}function mu(e){let t=BigInt(e);const r=[];let n=0;if(t===0n)return[0];for(;t>0;)r[n]=Number(t&0x7fn),t>>=7n,t>0n&&(r[n]|=128),n+=1;return r}function KO(e){let t=0n,r=0n,n=0;for(;;){if(n>=e.length)throw new Error("ULEB decode error: buffer overflow");const i=e[n];if(n+=1,t+=BigInt(i&127)<<r,!(i&128))break;r+=7n}if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("ULEB decode error: value exceeds MAX_SAFE_INTEGER");return{value:Number(t),length:n}}class XO{constructor(t){this.bytePosition=0,this.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength)}shift(t){return this.bytePosition+=t,this}read8(){const t=this.dataView.getUint8(this.bytePosition);return this.shift(1),t}read16(){const t=this.dataView.getUint16(this.bytePosition,!0);return this.shift(2),t}read32(){const t=this.dataView.getUint32(this.bytePosition,!0);return this.shift(4),t}read64(){const t=this.read32(),n=this.read32().toString(16)+t.toString(16).padStart(8,"0");return BigInt("0x"+n).toString(10)}read128(){const t=BigInt(this.read64()),n=BigInt(this.read64()).toString(16)+t.toString(16).padStart(16,"0");return BigInt("0x"+n).toString(10)}read256(){const t=BigInt(this.read128()),n=BigInt(this.read128()).toString(16)+t.toString(16).padStart(32,"0");return BigInt("0x"+n).toString(10)}readBytes(t){const r=this.bytePosition+this.dataView.byteOffset,n=new Uint8Array(this.dataView.buffer,r,t);return this.shift(t),n}readULEB(){const t=this.bytePosition+this.dataView.byteOffset,r=new Uint8Array(this.dataView.buffer,t),{value:n,length:i}=KO(r);return this.shift(i),n}readVec(t){const r=this.readULEB(),n=[];for(let i=0;i<r;i++)n.push(t(this,i,r));return n}}function JO(e,t){switch(t){case"base58":return Af(e);case"base64":return Bt(e);case"hex":return oa(e);default:throw new Error("Unsupported encoding, supported values are: base64, hex")}}function H6(e,t=["<",">"]){const[r,n]=t,i=[];let s="",a=0;for(let o=0;o<e.length;o++){const c=e[o];if(c===r&&a++,c===n&&a--,a===0&&c===","){i.push(s.trim()),s="";continue}s+=c}return i.push(s.trim()),i}class YO{constructor({initialSize:t=1024,maxSize:r=1/0,allocateSize:n=1024}={}){this.bytePosition=0,this.size=t,this.maxSize=r,this.allocateSize=n,this.dataView=new DataView(new ArrayBuffer(t))}ensureSizeOrGrow(t){const r=this.bytePosition+t;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 i=new ArrayBuffer(this.size);new Uint8Array(i).set(new Uint8Array(this.dataView.buffer)),this.dataView=new DataView(i)}}shift(t){return this.bytePosition+=t,this}write8(t){return this.ensureSizeOrGrow(1),this.dataView.setUint8(this.bytePosition,Number(t)),this.shift(1)}writeBytes(t){this.ensureSizeOrGrow(t.length);for(let r=0;r<t.length;r++)this.dataView.setUint8(this.bytePosition+r,t[r]);return this.shift(t.length)}write16(t){return this.ensureSizeOrGrow(2),this.dataView.setUint16(this.bytePosition,Number(t),!0),this.shift(2)}write32(t){return this.ensureSizeOrGrow(4),this.dataView.setUint32(this.bytePosition,Number(t),!0),this.shift(4)}write64(t){return bd(BigInt(t),8).forEach(r=>this.write8(r)),this}write128(t){return bd(BigInt(t),16).forEach(r=>this.write8(r)),this}write256(t){return bd(BigInt(t),32).forEach(r=>this.write8(r)),this}writeULEB(t){return mu(t).forEach(r=>this.write8(r)),this}writeVec(t,r){return this.writeULEB(t.length),Array.from(t).forEach((n,i)=>r(this,n,i,t.length)),this}*[Symbol.iterator](){for(let t=0;t<this.bytePosition;t++)yield this.dataView.getUint8(t);return this.toBytes()}toBytes(){return new Uint8Array(this.dataView.buffer.slice(0,this.bytePosition))}toString(t){return JO(this.toBytes(),t)}}function bd(e,t){const r=new Uint8Array(t);let n=0;for(;e>0;)r[n]=Number(e%BigInt(256)),e=e/BigInt(256),n+=1;return r}var L6=e=>{throw TypeError(e)},D6=(e,t,r)=>t.has(e)||L6("Cannot "+r),Cr=(e,t,r)=>(D6(e,t,"read from private field"),r?r.call(e):t.get(e)),bu=(e,t,r)=>t.has(e)?L6("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),gu=(e,t,r,n)=>(D6(e,t,"write to private field"),t.set(e,r),r),Us,za,Zc,fi;const ZO=class z6{constructor(t){bu(this,Us),bu(this,za),this.name=t.name,this.read=t.read,this.serializedSize=t.serializedSize??(()=>null),gu(this,Us,t.write),gu(this,za,t.serialize??((r,n)=>{const i=new YO({initialSize:this.serializedSize(r)??void 0,...n});return Cr(this,Us).call(this,r,i),i.toBytes()})),this.validate=t.validate??(()=>{})}write(t,r){this.validate(t),Cr(this,Us).call(this,t,r)}serialize(t,r){return this.validate(t),new QO(this,Cr(this,za).call(this,t,r))}parse(t){const r=new XO(t);return this.read(r)}fromHex(t){return this.parse($6(t))}fromBase58(t){return this.parse(Ro(t))}fromBase64(t){return this.parse(cr(t))}transform({name:t,input:r,output:n,validate:i}){return new z6({name:t??this.name,read:s=>n?n(this.read(s)):this.read(s),write:(s,a)=>Cr(this,Us).call(this,r?r(s):s,a),serializedSize:s=>this.serializedSize(r?r(s):s),serialize:(s,a)=>Cr(this,za).call(this,r?r(s):s,a),validate:s=>{i==null||i(s),this.validate(r?r(s):s)}})}};Us=new WeakMap;za=new WeakMap;let mn=ZO;const V6=Symbol.for("@mysten/serialized-bcs");function gp(e){return!!e&&typeof e=="object"&&e[V6]===!0}class QO{constructor(t,r){bu(this,Zc),bu(this,fi),gu(this,Zc,t),gu(this,fi,r)}get[V6](){return!0}toBytes(){return Cr(this,fi)}toHex(){return oa(Cr(this,fi))}toBase64(){return Bt(Cr(this,fi))}toBase58(){return Af(Cr(this,fi))}parse(){return Cr(this,Zc).parse(Cr(this,fi))}}Zc=new WeakMap;fi=new WeakMap;function wu({size:e,...t}){return new mn({...t,serializedSize:()=>e})}function gd({readMethod:e,writeMethod:t,...r}){return wu({...r,read:n=>n[e](),write:(n,i)=>i[t](n),validate:n=>{var i;if(n<0||n>r.maxValue)throw new TypeError(`Invalid ${r.name} value: ${n}. Expected value in range 0-${r.maxValue}`);(i=r.validate)==null||i.call(r,n)}})}function wd({readMethod:e,writeMethod:t,...r}){return wu({...r,read:n=>n[e](),write:(n,i)=>i[t](BigInt(n)),validate:n=>{var s;const i=BigInt(n);if(i<0||i>r.maxValue)throw new TypeError(`Invalid ${r.name} value: ${i}. Expected value in range 0-${r.maxValue}`);(s=r.validate)==null||s.call(r,i)}})}function eB({serialize:e,...t}){const r=new mn({...t,serialize:e,write:(n,i)=>{for(const s of r.serialize(n).toBytes())i.write8(s)}});return r}function tB({toBytes:e,fromBytes:t,...r}){return new mn({...r,read:n=>{const i=n.readULEB(),s=n.readBytes(i);return t(s)},write:(n,i)=>{const s=e(n);i.writeULEB(s.length);for(let a=0;a<s.length;a++)i.write8(s[a])},serialize:n=>{const i=e(n),s=mu(i.length),a=new Uint8Array(s.length+i.length);return a.set(s,0),a.set(i,s.length),a},validate:n=>{var i;if(typeof n!="string")throw new TypeError(`Invalid ${r.name} value: ${n}. Expected string`);(i=r.validate)==null||i.call(r,n)}})}function rB(e){let t=null;function r(){return t||(t=e()),t}return new mn({name:"lazy",read:n=>r().read(n),serializedSize:n=>r().serializedSize(n),write:(n,i)=>r().write(n,i),serialize:(n,i)=>r().serialize(n,i).toBytes()})}class nB extends mn{constructor({name:t,fields:r,...n}){const i=Object.entries(r);super({name:t,serializedSize:s=>{let a=0;for(const[o,c]of i){const u=c.serializedSize(s[o]);if(u==null)return null;a+=u}return a},read:s=>{const a={};for(const[o,c]of i)a[o]=c.read(s);return a},write:(s,a)=>{for(const[o,c]of i)c.write(s[o],a)},...n,validate:s=>{var a;if((a=n==null?void 0:n.validate)==null||a.call(n,s),typeof s!="object"||s==null)throw new TypeError(`Expected object, found ${typeof s}`)}})}}class iB extends mn{constructor({fields:t,...r}){const n=Object.entries(t);super({read:i=>{const s=i.readULEB(),a=n[s];if(!a)throw new TypeError(`Unknown value ${s} for enum ${r.name}`);const[o,c]=a;return{[o]:(c==null?void 0:c.read(i))??!0,$kind:o}},write:(i,s)=>{const[a,o]=Object.entries(i).filter(([c])=>Object.hasOwn(t,c))[0];for(let c=0;c<n.length;c++){const[u,f]=n[c];if(u===a){s.writeULEB(c),f==null||f.write(o,s);return}}},...r,validate:i=>{var o;if((o=r==null?void 0:r.validate)==null||o.call(r,i),typeof i!="object"||i==null)throw new TypeError(`Expected object, found ${typeof i}`);const s=Object.keys(i).filter(c=>i[c]!==void 0&&Object.hasOwn(t,c));if(s.length!==1)throw new TypeError(`Expected object with one key, but found ${s.length} for type ${r.name}}`);const[a]=s;if(!Object.hasOwn(t,a))throw new TypeError(`Invalid enum variant ${a}`)}})}}class sB extends mn{constructor({fields:t,name:r,...n}){super({name:r??`(${t.map(i=>i.name).join(", ")})`,serializedSize:i=>{let s=0;for(let a=0;a<t.length;a++){const o=t[a].serializedSize(i[a]);if(o==null)return null;s+=o}return s},read:i=>{const s=[];for(const a of t)s.push(a.read(i));return s},write:(i,s)=>{for(let a=0;a<t.length;a++)t[a].write(i[a],s)},...n,validate:i=>{var s;if((s=n==null?void 0:n.validate)==null||s.call(n,i),!Array.isArray(i))throw new TypeError(`Expected array, found ${typeof i}`);if(i.length!==t.length)throw new TypeError(`Expected array of length ${t.length}, found ${i.length}`)}})}}function aB(e,t,r){return new mn({read:n=>{const i=new Array(e);for(let s=0;s<e;s++)i[s]=t.read(n);return i},write:(n,i)=>{for(const s of n)t.write(s,i)},...r,name:(r==null?void 0:r.name)??`${t.name}[${e}]`,validate:n=>{var i;if((i=r==null?void 0:r.validate)==null||i.call(r,n),!n||typeof n!="object"||!("length"in n))throw new TypeError(`Expected array, found ${typeof n}`);if(n.length!==e)throw new TypeError(`Expected array of length ${e}, found ${n.length}`)}})}function oB(e){return P.enum(`Option<${e.name}>`,{None:null,Some:e}).transform({input:t=>t==null?{None:!0}:{Some:t},output:t=>t.$kind==="Some"?t.Some:null})}function cB(e,t){return new mn({read:r=>{const n=r.readULEB(),i=new Array(n);for(let s=0;s<n;s++)i[s]=e.read(r);return i},write:(r,n)=>{n.writeULEB(r.length);for(const i of r)e.write(i,n)},...t,name:(t==null?void 0:t.name)??`vector<${e.name}>`,validate:r=>{var n;if((n=t==null?void 0:t.validate)==null||n.call(t,r),!r||typeof r!="object"||!("length"in r))throw new TypeError(`Expected array, found ${typeof r}`)}})}function uB(e,t){return P.vector(P.tuple([e,t])).transform({name:`Map<${e.name}, ${t.name}>`,input:r=>[...r.entries()],output:r=>{const n=new Map;for(const[i,s]of r)n.set(i,s);return n}})}const P={u8(e){return gd({readMethod:"read8",writeMethod:"write8",size:1,maxValue:2**8-1,...e,name:(e==null?void 0:e.name)??"u8"})},u16(e){return gd({readMethod:"read16",writeMethod:"write16",size:2,maxValue:2**16-1,...e,name:(e==null?void 0:e.name)??"u16"})},u32(e){return gd({readMethod:"read32",writeMethod:"write32",size:4,maxValue:2**32-1,...e,name:(e==null?void 0:e.name)??"u32"})},u64(e){return wd({readMethod:"read64",writeMethod:"write64",size:8,maxValue:2n**64n-1n,...e,name:(e==null?void 0:e.name)??"u64"})},u128(e){return wd({readMethod:"read128",writeMethod:"write128",size:16,maxValue:2n**128n-1n,...e,name:(e==null?void 0:e.name)??"u128"})},u256(e){return wd({readMethod:"read256",writeMethod:"write256",size:32,maxValue:2n**256n-1n,...e,name:(e==null?void 0:e.name)??"u256"})},bool(e){return wu({size:1,read:t=>t.read8()===1,write:(t,r)=>r.write8(t?1:0),...e,name:(e==null?void 0:e.name)??"bool",validate:t=>{var r;if((r=e==null?void 0:e.validate)==null||r.call(e,t),typeof t!="boolean")throw new TypeError(`Expected boolean, found ${typeof t}`)}})},uleb128(e){return eB({read:t=>t.readULEB(),serialize:t=>Uint8Array.from(mu(t)),...e,name:(e==null?void 0:e.name)??"uleb128"})},bytes(e,t){return wu({size:e,read:r=>r.readBytes(e),write:(r,n)=>{n.writeBytes(new Uint8Array(r))},...t,name:(t==null?void 0:t.name)??`bytes[${e}]`,validate:r=>{var n;if((n=t==null?void 0:t.validate)==null||n.call(t,r),!r||typeof r!="object"||!("length"in r))throw new TypeError(`Expected array, found ${typeof r}`);if(r.length!==e)throw new TypeError(`Expected array of length ${e}, found ${r.length}`)}})},byteVector(e){return new mn({read:t=>{const r=t.readULEB();return t.readBytes(r)},write:(t,r)=>{const n=new Uint8Array(t);r.writeULEB(n.length),r.writeBytes(n)},...e,name:(e==null?void 0:e.name)??"vector<u8>",serializedSize:t=>{const r="length"in t?t.length:null;return r==null?null:mu(r).length+r},validate:t=>{var r;if((r=e==null?void 0:e.validate)==null||r.call(e,t),!t||typeof t!="object"||!("length"in t))throw new TypeError(`Expected array, found ${typeof t}`)}})},string(e){return tB({toBytes:t=>new TextEncoder().encode(t),fromBytes:t=>new TextDecoder().decode(t),...e,name:(e==null?void 0:e.name)??"string"})},fixedArray:aB,option:oB,vector:cB,tuple(e,t){return new sB({fields:e,...t})},struct(e,t,r){return new nB({name:e,fields:t,...r})},enum(e,t,r){return new iB({name:e,fields:t,...r})},map:uB,lazy(e){return rB(e)}};var G6=e=>{throw TypeError(e)},q6=(e,t,r)=>t.has(e)||G6("Cannot "+r),_t=(e,t,r)=>(q6(e,t,"read from private field"),t.get(e)),gb=(e,t,r)=>t.has(e)?G6("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),wb=(e,t,r,n)=>(q6(e,t,"write to private field"),t.set(e,r),r),Di,Ht;const fB=class W6{constructor({prefix:t,cache:r}={}){gb(this,Di),gb(this,Ht),wb(this,Di,t??[]),wb(this,Ht,r??new Map)}read(t,r){const n=[_t(this,Di),...t].join(":");if(_t(this,Ht).has(n))return _t(this,Ht).get(n);const i=r();return _t(this,Ht).set(n,i),typeof i=="object"&&i!==null&&"then"in i?Promise.resolve(i).then(s=>(_t(this,Ht).set(n,s),s)).catch(s=>{throw _t(this,Ht).delete(n),s}):i}readSync(t,r){const n=[_t(this,Di),...t].join(":");if(_t(this,Ht).has(n))return _t(this,Ht).get(n);const i=r();return _t(this,Ht).set(n,i),i}clear(t){const r=[..._t(this,Di),...t??[]].join(":");if(!r){_t(this,Ht).clear();return}for(const n of _t(this,Ht).keys())n.startsWith(r)&&_t(this,Ht).delete(n)}scope(t){return new W6({prefix:[..._t(this,Di),...Array.isArray(t)?t:[t]],cache:_t(this,Ht)})}};Di=new WeakMap;Ht=new WeakMap;let lB=fB;class K6{constructor({network:t,base:r,cache:n=(r==null?void 0:r.cache)??new lB}){this.network=t,this.base=r??this,this.cache=n}$extend(...t){return Object.create(this,Object.fromEntries(t.map(r=>[r.name,{value:r.register(this)}])))}}let kn;function X6(e){return{lang:(e==null?void 0:e.lang)??(kn==null?void 0:kn.lang),message:e==null?void 0:e.message,abortEarly:(e==null?void 0:e.abortEarly)??(kn==null?void 0:kn.abortEarly),abortPipeEarly:(e==null?void 0:e.abortPipeEarly)??(kn==null?void 0:kn.abortPipeEarly)}}let vd;function dB(e){return vd==null?void 0:vd.get(e)}let Ed;function hB(e){return Ed==null?void 0:Ed.get(e)}let xd;function pB(e,t){var r;return(r=xd==null?void 0:xd.get(e))==null?void 0:r.get(t)}function J6(e){var r,n;const t=typeof e;return t==="string"?`"${e}"`:t==="number"||t==="bigint"||t==="boolean"?`${e}`:t==="object"||t==="function"?(e&&((n=(r=Object.getPrototypeOf(e))==null?void 0:r.constructor)==null?void 0:n.name))??"null":t}function Qt(e,t,r,n,i){const s=i&&"input"in i?i.input:r.value,a=(i==null?void 0:i.expected)??e.expects??null,o=(i==null?void 0:i.received)??J6(s),c={kind:e.kind,type:e.type,input:s,expected:a,received:o,message:`Invalid ${t}: ${a?`Expected ${a} but r`:"R"}eceived ${o}`,requirement:e.requirement,path:i==null?void 0:i.path,issues:i==null?void 0:i.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},u=e.kind==="schema",f=(i==null?void 0:i.message)??e.message??pB(e.reference,c.lang)??(u?hB(c.lang):null)??n.message??dB(c.lang);f!==void 0&&(c.message=typeof f=="function"?f(c):f),u&&(r.typed=!1),r.issues?r.issues.push(c):r.issues=[c]}function Nt(e){return{version:1,vendor:"valibot",validate(t){return e["~run"]({value:t},X6())}}}function yB(e,t){return Object.hasOwn(e,t)&&t!=="__proto__"&&t!=="prototype"&&t!=="constructor"}function mB(e,t){const r=[...new Set(e)];return r.length>1?`(${r.join(` ${t} `)})`:r[0]??"never"}var bB=class extends Error{constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}};function wp(e,t){return{kind:"validation",type:"check",reference:wp,async:!1,expects:null,requirement:e,message:t,"~run"(r,n){return r.typed&&!this.requirement(r.value)&&Qt(this,"input",r,n),r}}}function Xt(e){return{kind:"validation",type:"integer",reference:Xt,async:!1,expects:null,requirement:Number.isInteger,message:e,"~run"(t,r){return t.typed&&!this.requirement(t.value)&&Qt(this,"integer",t,r),t}}}function kf(e){return{kind:"transformation",type:"transform",reference:kf,async:!1,operation:e,"~run"(t){return t.value=this.operation(t.value),t}}}function gB(e,t,r){return typeof e.fallback=="function"?e.fallback(t,r):e.fallback}function Tf(e,t,r){return typeof e.default=="function"?e.default(t,r):e.default}function Rh(e,t){return!e["~run"]({value:t},{abortEarly:!0}).issues}function Te(e,t){return{kind:"schema",type:"array",reference:Te,expects:"Array",async:!1,item:e,message:t,get"~standard"(){return Nt(this)},"~run"(r,n){var s;const i=r.value;if(Array.isArray(i)){r.typed=!0,r.value=[];for(let a=0;a<i.length;a++){const o=i[a],c=this.item["~run"]({value:o},n);if(c.issues){const u={type:"array",origin:"value",input:i,key:a,value:o};for(const f of c.issues)f.path?f.path.unshift(u):f.path=[u],(s=r.issues)==null||s.push(f);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 Y6(e){return{kind:"schema",type:"bigint",reference:Y6,expects:"bigint",async:!1,message:e,get"~standard"(){return Nt(this)},"~run"(t,r){return typeof t.value=="bigint"?t.typed=!0:Qt(this,"type",t,r),t}}}function Ea(e){return{kind:"schema",type:"boolean",reference:Ea,expects:"boolean",async:!1,message:e,get"~standard"(){return Nt(this)},"~run"(t,r){return typeof t.value=="boolean"?t.typed=!0:Qt(this,"type",t,r),t}}}function Nh(e){return{kind:"schema",type:"lazy",reference:Nh,expects:"unknown",async:!1,getter:e,get"~standard"(){return Nt(this)},"~run"(t,r){return this.getter(t.value)["~run"](t,r)}}}function dt(e,t){return{kind:"schema",type:"literal",reference:dt,expects:J6(e),async:!1,literal:e,message:t,get"~standard"(){return Nt(this)},"~run"(r,n){return r.value===this.literal?r.typed=!0:Qt(this,"type",r,n),r}}}function Ye(e,t){return{kind:"schema",type:"nullable",reference:Ye,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,get"~standard"(){return Nt(this)},"~run"(r,n){return r.value===null&&(this.default!==void 0&&(r.value=Tf(this,r,n)),r.value===null)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}function No(e,t){return{kind:"schema",type:"nullish",reference:No,expects:`(${e.expects} | null | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return Nt(this)},"~run"(r,n){return(r.value===null||r.value===void 0)&&(this.default!==void 0&&(r.value=Tf(this,r,n)),r.value===null||r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}function Jt(e){return{kind:"schema",type:"number",reference:Jt,expects:"number",async:!1,message:e,get"~standard"(){return Nt(this)},"~run"(t,r){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:Qt(this,"type",t,r),t}}}function he(e,t){return{kind:"schema",type:"object",reference:he,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return Nt(this)},"~run"(r,n){var s;const i=r.value;if(i&&typeof i=="object"){r.typed=!0,r.value={};for(const a in this.entries){const o=this.entries[a];if(a in i||(o.type==="exact_optional"||o.type==="optional"||o.type==="nullish")&&o.default!==void 0){const c=a in i?i[a]:Tf(o),u=o["~run"]({value:c},n);if(u.issues){const f={type:"object",origin:"value",input:i,key:a,value:c};for(const l of u.issues)l.path?l.path.unshift(f):l.path=[f],(s=r.issues)==null||s.push(l);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]=gB(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:i,key:a,value:i[a]}]}),n.abortEarly))break}}else Qt(this,"type",r,n);return r}}}function or(e,t){return{kind:"schema",type:"optional",reference:or,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return Nt(this)},"~run"(r,n){return r.value===void 0&&(this.default!==void 0&&(r.value=Tf(this,r,n)),r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}function Uo(e,t,r){return{kind:"schema",type:"record",reference:Uo,expects:"Object",async:!1,key:e,value:t,message:r,get"~standard"(){return Nt(this)},"~run"(n,i){var a,o;const s=n.value;if(s&&typeof s=="object"){n.typed=!0,n.value={};for(const c in s)if(yB(s,c)){const u=s[c],f=this.key["~run"]({value:c},i);if(f.issues){const h={type:"object",origin:"key",input:s,key:c,value:u};for(const d of f.issues)d.path=[h],(a=n.issues)==null||a.push(d);if(n.issues||(n.issues=f.issues),i.abortEarly){n.typed=!1;break}}const l=this.value["~run"]({value:u},i);if(l.issues){const h={type:"object",origin:"value",input:s,key:c,value:u};for(const d of l.issues)d.path?d.path.unshift(h):d.path=[h],(o=n.issues)==null||o.push(d);if(n.issues||(n.issues=l.issues),i.abortEarly){n.typed=!1;break}}(!f.typed||!l.typed)&&(n.typed=!1),f.typed&&(n.value[f.value]=l.value)}}else Qt(this,"type",n,i);return n}}}function Pe(e){return{kind:"schema",type:"string",reference:Pe,expects:"string",async:!1,message:e,get"~standard"(){return Nt(this)},"~run"(t,r){return typeof t.value=="string"?t.typed=!0:Qt(this,"type",t,r),t}}}function vp(e,t){return{kind:"schema",type:"tuple",reference:vp,expects:"Array",async:!1,items:e,message:t,get"~standard"(){return Nt(this)},"~run"(r,n){var s;const i=r.value;if(Array.isArray(i)){r.typed=!0,r.value=[];for(let a=0;a<this.items.length;a++){const o=i[a],c=this.items[a]["~run"]({value:o},n);if(c.issues){const u={type:"array",origin:"value",input:i,key:a,value:o};for(const f of c.issues)f.path?f.path.unshift(u):f.path=[u],(s=r.issues)==null||s.push(f);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 vb(e){let t;if(e)for(const r of e)t?t.push(...r.issues):t=r.issues;return t}function bn(e,t){return{kind:"schema",type:"union",reference:bn,expects:mB(e.map(r=>r.expects),"|"),async:!1,options:e,message:t,get"~standard"(){return Nt(this)},"~run"(r,n){let i,s,a;for(const o of this.options){const c=o["~run"]({value:r.value},n);if(c.typed)if(c.issues)s?s.push(c):s=[c];else{i=c;break}else a?a.push(c):a=[c]}if(i)return i;if(s){if(s.length===1)return s[0];Qt(this,"type",r,n,{issues:vb(s)}),r.typed=!0}else{if((a==null?void 0:a.length)===1)return a[0];Qt(this,"type",r,n,{issues:vb(a)})}return r}}}function pc(){return{kind:"schema",type:"unknown",reference:pc,expects:"unknown",async:!1,get"~standard"(){return Nt(this)},"~run"(e){return e.typed=!0,e}}}function qe(e,t,r){const n=e["~run"]({value:t},X6(r));if(n.issues)throw new bB(n.issues);return n.value}function xt(...e){return{...e[0],pipe:e,get"~standard"(){return Nt(this)},"~run"(t,r){for(const n of e)if(n.kind!=="metadata"){if(t.issues&&(n.kind==="schema"||n.kind==="transformation")){t.typed=!1;break}(!t.issues||!r.abortEarly&&!r.abortPipeEarly)&&(t=n["~run"](t,r))}return t}}}const Z6=/^(?!.*(^(?!@)|[-.@])($|[-.@]))(?:[a-z0-9-]{0,63}(?:\.[a-z0-9-]{0,63})*)?@[a-z0-9-]{0,63}$/i,Q6=/^(?!.*(^|[-.])($|[-.]))(?:[a-z0-9-]{0,63}\.)+sui$/i,wB=235;function vB(e){return e.length>wB?!1:e.includes("@")?Z6.test(e):Q6.test(e)}function EB(e,t="at"){const r=e.toLowerCase();let n;if(r.includes("@")){if(!Z6.test(r))throw new Error(`Invalid SuiNS name ${e}`);const[i,s]=r.split("@");n=[...i?i.split("."):[],s]}else{if(!Q6.test(r))throw new Error(`Invalid SuiNS name ${e}`);n=r.split(".").slice(0,-1)}return t==="dot"?`${n.join(".")}.sui`:`${n.slice(0,-1).join(".")}@${n[n.length-1]}`}const xB=/^([a-z0-9]+(?:-[a-z0-9]+)*)$/,AB=/^\d+$/,SB=64,e5="/",nr=e=>{const t=e.split(e5);if(t.length<2||t.length>3)return!1;const[r,n,i]=t;return i!==void 0&&!AB.test(i)||!vB(r)?!1:xB.test(n)&&n.length<SB},kB=e=>{const t=e.split(/::|<|>|,/);for(const r of t)if(r.includes(e5)&&!nr(r))return!1;return!0},TB=32;function Eb(e){try{return Ro(e).length===TB}catch{return!1}}const If=32;function Rr(e){return _B(e)&&PB(e)===If}function Lc(e){return Rr(e)}function IB(e){return e.includes("::")?ys(e):e}function ys(e){const[t,r]=e.split("::"),n=nr(t),i=e.slice(t.length+r.length+4),s=i.includes("<")?i.slice(0,i.indexOf("<")):i,a=i.includes("<")?H6(i.slice(i.indexOf("<")+1,i.lastIndexOf(">"))).map(o=>IB(o.trim())):[];return{address:n?t:xe(t),module:r,name:s,typeParams:a}}function vu(e){const{address:t,module:r,name:n,typeParams:i}=typeof e=="string"?ys(e):e,s=(i==null?void 0:i.length)>0?`<${i.map(a=>typeof a=="string"?a:vu(a)).join(",")}>`:"";return`${t}::${r}::${n}${s}`}function xe(e,t=!1){let r=e.toLowerCase();return!t&&r.startsWith("0x")&&(r=r.slice(2)),`0x${r.padStart(If*2,"0")}`}function fn(e,t=!1){return xe(e,t)}function _B(e){return/^(0x|0X)?[a-fA-F0-9]+$/.test(e)&&e.length%2===0}function PB(e){return/^(0x|0X)/.test(e)?(e.length-2)/2:e.length/2}function As(e){const t=Object.entries(e).map(([r,n])=>he({[r]:n}));return xt(bn(t),kf(r=>({...r,$kind:Object.keys(r)[0]})))}const xa=xt(Pe(),kf(e=>xe(e)),wp(Rr)),ur=xa,ms=Pe(),er=xt(bn([Pe(),xt(Jt(),Xt())]),wp(e=>{try{return BigInt(e),BigInt(e)>=0&&BigInt(e)<=18446744073709551615n}catch{return!1}},"Invalid u64")),Oi=he({objectId:xa,version:er,digest:Pe()}),He=xt(bn([he({GasCoin:dt(!0)}),he({Input:xt(Jt(),Xt()),type:or(dt("pure"))}),he({Input:xt(Jt(),Xt()),type:or(dt("object"))}),he({Result:xt(Jt(),Xt())}),he({NestedResult:vp([xt(Jt(),Xt()),xt(Jt(),Xt())])})]),kf(e=>({...e,$kind:Object.keys(e)[0]}))),OB=he({budget:Ye(er),price:Ye(er),owner:Ye(xa),payment:Ye(Te(Oi))}),Uh=bn([dt("address"),dt("bool"),dt("u8"),dt("u16"),dt("u32"),dt("u64"),dt("u128"),dt("u256"),he({vector:Nh(()=>Uh)}),he({datatype:he({package:Pe(),module:Pe(),type:Pe(),typeParameters:Te(Nh(()=>Uh))})}),he({typeParameter:xt(Jt(),Xt())})]),BB=he({ref:Ye(bn([dt("&"),dt("&mut")])),body:Uh}),CB=he({package:ur,module:Pe(),function:Pe(),typeArguments:Te(Pe()),arguments:Te(He),_argumentTypes:or(Ye(Te(BB)))}),RB=he({name:Pe(),inputs:Uo(Pe(),bn([He,Te(He)])),data:Uo(Pe(),pc())}),NB=As({MoveCall:CB,TransferObjects:he({objects:Te(He),address:He}),SplitCoins:he({coin:He,amounts:Te(He)}),MergeCoins:he({destination:He,sources:Te(He)}),Publish:he({modules:Te(ms),dependencies:Te(ur)}),MakeMoveVec:he({type:Ye(Pe()),elements:Te(He)}),Upgrade:he({modules:Te(ms),dependencies:Te(ur),package:ur,ticket:He}),$Intent:RB}),t5=As({ImmOrOwnedObject:Oi,SharedObject:he({objectId:ur,initialSharedVersion:er,mutable:Ea()}),Receiving:Oi}),UB=As({Object:t5,Pure:he({bytes:ms}),UnresolvedPure:he({value:pc()}),UnresolvedObject:he({objectId:ur,version:or(Ye(er)),digest:or(Ye(Pe())),initialSharedVersion:or(Ye(er)),mutable:or(Ye(Ea()))})}),xb=As({Object:t5,Pure:he({bytes:ms})}),r5=As({None:dt(!0),Epoch:er}),Qc=he({version:dt(2),sender:No(xa),expiration:No(r5),gasData:OB,inputs:Te(UB),commands:Te(NB)}),Li={MoveCall(e){const[t,r="",n=""]="target"in e?e.target.split("::"):[e.package,e.module,e.function];return{$kind:"MoveCall",MoveCall:{package:t,module:r,function:n,typeArguments:e.typeArguments??[],arguments:e.arguments??[]}}},TransferObjects(e,t){return{$kind:"TransferObjects",TransferObjects:{objects:e.map(r=>qe(He,r)),address:qe(He,t)}}},SplitCoins(e,t){return{$kind:"SplitCoins",SplitCoins:{coin:qe(He,e),amounts:t.map(r=>qe(He,r))}}},MergeCoins(e,t){return{$kind:"MergeCoins",MergeCoins:{destination:qe(He,e),sources:t.map(r=>qe(He,r))}}},Publish({modules:e,dependencies:t}){return{$kind:"Publish",Publish:{modules:e.map(r=>typeof r=="string"?r:Bt(new Uint8Array(r))),dependencies:t.map(r=>fn(r))}}},Upgrade({modules:e,dependencies:t,package:r,ticket:n}){return{$kind:"Upgrade",Upgrade:{modules:e.map(i=>typeof i=="string"?i:Bt(new Uint8Array(i))),dependencies:t.map(i=>fn(i)),package:r,ticket:qe(He,n)}}},MakeMoveVec({type:e,elements:t}){return{$kind:"MakeMoveVec",MakeMoveVec:{type:e??null,elements:t.map(r=>qe(He,r))}}},Intent({name:e,inputs:t={},data:r={}}){return{$kind:"$Intent",$Intent:{name:e,inputs:Object.fromEntries(Object.entries(t).map(([n,i])=>[n,Array.isArray(i)?i.map(s=>qe(He,s)):qe(He,i)])),data:r}}}},FB=/^vector<(.+)>$/,$B=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;class Nr{static parseFromStr(t,r=!1){if(t==="address")return{address:null};if(t==="bool")return{bool:null};if(t==="u8")return{u8:null};if(t==="u16")return{u16:null};if(t==="u32")return{u32:null};if(t==="u64")return{u64:null};if(t==="u128")return{u128:null};if(t==="u256")return{u256:null};if(t==="signer")return{signer:null};const n=t.match(FB);if(n)return{vector:Nr.parseFromStr(n[1],r)};const i=t.match($B);if(i)return{struct:{address:r?xe(i[1]):i[1],module:i[2],name:i[3],typeParams:i[5]===void 0?[]:Nr.parseStructTypeArgs(i[5],r)}};throw new Error(`Encountered unexpected token when parsing type args for ${t}`)}static parseStructTypeArgs(t,r=!1){return H6(t).map(n=>Nr.parseFromStr(n,r))}static tagToString(t){if("bool"in t)return"bool";if("u8"in t)return"u8";if("u16"in t)return"u16";if("u32"in t)return"u32";if("u64"in t)return"u64";if("u128"in t)return"u128";if("u256"in t)return"u256";if("address"in t)return"address";if("signer"in t)return"signer";if("vector"in t)return`vector<${Nr.tagToString(t.vector)}>`;if("struct"in t){const r=t.struct,n=r.typeParams.map(Nr.tagToString).join(", ");return`${r.address}::${r.module}::${r.name}${n?`<${n}>`:""}`}throw new Error("Invalid TypeTag")}}function MB(e){return P.u64({name:"unsafe_u64",...e}).transform({input:t=>t,output:t=>Number(t)})}function jB(e){return P.enum("Option",{None:null,Some:e})}const Le=P.bytes(If).transform({validate:e=>{const t=typeof e=="string"?e:oa(e);if(!t||!Rr(xe(t)))throw new Error(`Invalid Sui address ${t}`)},input:e=>typeof e=="string"?$6(xe(e)):e,output:e=>xe(oa(e))}),Mr=P.byteVector().transform({name:"ObjectDigest",input:e=>Ro(e),output:e=>Af(new Uint8Array(e)),validate:e=>{if(Ro(e).length!==32)throw new Error("ObjectDigest must be 32 bytes")}}),vr=P.struct("SuiObjectRef",{objectId:Le,version:P.u64(),digest:Mr}),n5=P.struct("SharedObjectRef",{objectId:Le,initialSharedVersion:P.u64(),mutable:P.bool()}),i5=P.enum("ObjectArg",{ImmOrOwnedObject:vr,SharedObject:n5,Receiving:vr}),Xi=P.enum("Owner",{AddressOwner:Le,ObjectOwner:Le,Shared:P.struct("Shared",{initialSharedVersion:P.u64()}),Immutable:null,ConsensusAddressOwner:P.struct("ConsensusAddressOwner",{owner:Le,startVersion:P.u64()})}),s5=P.enum("CallArg",{Pure:P.struct("Pure",{bytes:P.byteVector().transform({input:e=>typeof e=="string"?cr(e):e,output:e=>Bt(new Uint8Array(e))})}),Object:i5}),Ep=P.enum("TypeTag",{bool:null,u8:null,u64:null,u128:null,address:null,signer:null,vector:P.lazy(()=>Ep),struct:P.lazy(()=>l5),u16:null,u32:null,u256:null}),xp=Ep.transform({input:e=>typeof e=="string"?Nr.parseFromStr(e,!0):e,output:e=>Nr.tagToString(e)}),on=P.enum("Argument",{GasCoin:null,Input:P.u16(),Result:P.u16(),NestedResult:P.tuple([P.u16(),P.u16()])}),a5=P.struct("ProgrammableMoveCall",{package:Le,module:P.string(),function:P.string(),typeArguments:P.vector(xp),arguments:P.vector(on)}),o5=P.enum("Command",{MoveCall:a5,TransferObjects:P.struct("TransferObjects",{objects:P.vector(on),address:on}),SplitCoins:P.struct("SplitCoins",{coin:on,amounts:P.vector(on)}),MergeCoins:P.struct("MergeCoins",{destination:on,sources:P.vector(on)}),Publish:P.struct("Publish",{modules:P.vector(P.byteVector().transform({input:e=>typeof e=="string"?cr(e):e,output:e=>Bt(new Uint8Array(e))})),dependencies:P.vector(Le)}),MakeMoveVec:P.struct("MakeMoveVec",{type:jB(xp).transform({input:e=>e===null?{None:!0}:{Some:e},output:e=>e.Some??null}),elements:P.vector(on)}),Upgrade:P.struct("Upgrade",{modules:P.vector(P.byteVector().transform({input:e=>typeof e=="string"?cr(e):e,output:e=>Bt(new Uint8Array(e))})),dependencies:P.vector(Le),package:Le,ticket:on})}),c5=P.struct("ProgrammableTransaction",{inputs:P.vector(s5),commands:P.vector(o5)}),u5=P.enum("TransactionKind",{ProgrammableTransaction:c5,ChangeEpoch:null,Genesis:null,ConsensusCommitPrologue:null}),f5=P.enum("TransactionExpiration",{None:null,Epoch:MB()}),l5=P.struct("StructTag",{address:Le,module:P.string(),name:P.string(),typeParams:P.vector(Ep)}),d5=P.struct("GasData",{payment:P.vector(vr),owner:Le,price:P.u64(),budget:P.u64()}),h5=P.struct("TransactionDataV1",{kind:u5,sender:Le,gasData:d5,expiration:f5}),p5=P.enum("TransactionData",{V1:h5}),y5=P.enum("IntentScope",{TransactionData:null,TransactionEffects:null,CheckpointSummary:null,PersonalMessage:null}),m5=P.enum("IntentVersion",{V0:null}),b5=P.enum("AppId",{Sui:null}),g5=P.struct("Intent",{scope:y5,version:m5,appId:b5});function w5(e){return P.struct(`IntentMessage<${e.name}>`,{intent:g5,value:e})}const v5=P.enum("CompressedSignature",{ED25519:P.bytes(64),Secp256k1:P.bytes(64),Secp256r1:P.bytes(64),ZkLogin:P.byteVector(),Passkey:P.byteVector()}),E5=P.enum("PublicKey",{ED25519:P.bytes(32),Secp256k1:P.bytes(33),Secp256r1:P.bytes(33),ZkLogin:P.byteVector(),Passkey:P.bytes(33)}),x5=P.struct("MultiSigPkMap",{pubKey:E5,weight:P.u8()}),A5=P.struct("MultiSigPublicKey",{pk_map:P.vector(x5),threshold:P.u16()}),HB=P.struct("MultiSig",{sigs:P.vector(v5),bitmap:P.u16(),multisig_pk:A5}),LB=P.byteVector().transform({input:e=>typeof e=="string"?cr(e):e,output:e=>Bt(new Uint8Array(e))}),S5=P.struct("SenderSignedTransaction",{intentMessage:w5(p5),txSignatures:P.vector(LB)}),DB=P.vector(S5,{name:"SenderSignedData"}),zB=P.struct("PasskeyAuthenticator",{authenticatorData:P.byteVector(),clientDataJson:P.string(),userSignature:P.byteVector()}),VB=P.enum("PackageUpgradeError",{UnableToFetchPackage:P.struct("UnableToFetchPackage",{packageId:Le}),NotAPackage:P.struct("NotAPackage",{objectId:Le}),IncompatibleUpgrade:null,DigestDoesNotMatch:P.struct("DigestDoesNotMatch",{digest:P.byteVector()}),UnknownUpgradePolicy:P.struct("UnknownUpgradePolicy",{policy:P.u8()}),PackageIDDoesNotMatch:P.struct("PackageIDDoesNotMatch",{packageId:Le,ticketId:Le})}),GB=P.struct("ModuleId",{address:Le,name:P.string()}),Ab=P.struct("MoveLocation",{module:GB,function:P.u16(),instruction:P.u16(),functionName:P.option(P.string())}),qB=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}),WB=P.enum("TypeArgumentError",{TypeNotFound:null,ConstraintNotSatisfied:null}),KB=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:Le}),InsufficientCoinBalance:null,CoinBalanceOverflow:null,PublishErrorNonZeroAddress:null,SuiMoveVerificationError:null,MovePrimitiveRuntimeError:P.option(Ab),MoveAbort:P.tuple([Ab,P.u64()]),VMVerificationOrDeserializationError:null,VMInvariantViolation:null,FunctionNotFound:null,ArityMismatch:null,TypeArityMismatch:null,NonEntryFunctionInvoked:null,CommandArgumentError:P.struct("CommandArgumentError",{argIdx:P.u16(),kind:qB}),TypeArgumentError:P.struct("TypeArgumentError",{argumentIdx:P.u16(),kind:WB}),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:VB}),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(Le)}),AddressDeniedForCoin:P.struct("AddressDeniedForCoin",{address:Le,coinType:P.string()}),CoinTypeGlobalPause:P.struct("CoinTypeGlobalPause",{coinType:P.string()}),ExecutionCancelledDueToRandomnessUnavailable:null}),k5=P.enum("ExecutionStatus",{Success:null,Failed:P.struct("ExecutionFailed",{error:KB,command:P.option(P.u64())})}),T5=P.struct("GasCostSummary",{computationCost:P.u64(),storageCost:P.u64(),storageRebate:P.u64(),nonRefundableStorageFee:P.u64()}),XB=P.struct("TransactionEffectsV1",{status:k5,executedEpoch:P.u64(),gasUsed:T5,modifiedAtVersions:P.vector(P.tuple([Le,P.u64()])),sharedObjects:P.vector(vr),transactionDigest:Mr,created:P.vector(P.tuple([vr,Xi])),mutated:P.vector(P.tuple([vr,Xi])),unwrapped:P.vector(P.tuple([vr,Xi])),deleted:P.vector(vr),unwrappedThenDeleted:P.vector(vr),wrapped:P.vector(vr),gasObject:P.tuple([vr,Xi]),eventsDigest:P.option(Mr),dependencies:P.vector(Mr)}),Ap=P.tuple([P.u64(),Mr]),JB=P.enum("ObjectIn",{NotExist:null,Exist:P.tuple([Ap,Xi])}),YB=P.enum("ObjectOut",{NotExist:null,ObjectWrite:P.tuple([Mr,Xi]),PackageWrite:Ap}),ZB=P.enum("IDOperation",{None:null,Created:null,Deleted:null}),QB=P.struct("EffectsObjectChange",{inputState:JB,outputState:YB,idOperation:ZB}),e9=P.enum("UnchangedSharedKind",{ReadOnlyRoot:Ap,MutateDeleted:P.u64(),ReadDeleted:P.u64(),Cancelled:P.u64(),PerEpochConfig:null}),t9=P.struct("TransactionEffectsV2",{status:k5,executedEpoch:P.u64(),gasUsed:T5,transactionDigest:Mr,gasObjectIndex:P.option(P.u32()),eventsDigest:P.option(Mr),dependencies:P.vector(Mr),lamportVersion:P.u64(),changedObjects:P.vector(P.tuple([Le,QB])),unchangedSharedObjects:P.vector(P.tuple([Le,e9])),auxDataDigest:P.option(Mr)}),r9=P.enum("TransactionEffects",{V1:XB,V2:t9});function Za(e){switch(e){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 Le}const t=e.match(/^(vector|option)<(.+)>$/);if(t){const[r,n]=t.slice(1);return r==="vector"?P.vector(Za(n)):P.option(Za(n))}throw new Error(`Invalid Pure type name: ${e}`)}const ye={...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:Le,AppId:b5,Argument:on,CallArg:s5,Command:o5,CompressedSignature:v5,GasData:d5,Intent:g5,IntentMessage:w5,IntentScope:y5,IntentVersion:m5,MultiSig:HB,MultiSigPkMap:x5,MultiSigPublicKey:A5,ObjectArg:i5,ObjectDigest:Mr,Owner:Xi,PasskeyAuthenticator:zB,ProgrammableMoveCall:a5,ProgrammableTransaction:c5,PublicKey:E5,SenderSignedData:DB,SenderSignedTransaction:S5,SharedObjectRef:n5,StructTag:l5,SuiObjectRef:vr,TransactionData:p5,TransactionDataV1:h5,TransactionEffects:r9,TransactionExpiration:f5,TransactionKind:u5,TypeTag:xp},Sb=he({digest:Pe(),objectId:Pe(),version:bn([xt(Jt(),Xt()),Pe(),Y6()])}),n9=As({ImmOrOwned:Sb,Shared:he({objectId:ur,initialSharedVersion:er,mutable:Ea()}),Receiving:Sb}),kb=As({Object:n9,Pure:Te(xt(Jt(),Xt()))});function Tb(e){var r;const t=e.inputs.map((n,i)=>{if(n.Object)return{kind:"Input",index:i,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:i,value:{Pure:Array.from(cr(n.Pure.bytes))},type:"pure"};if(n.UnresolvedPure)return{kind:"Input",type:"pure",index:i,value:n.UnresolvedPure.value};if(n.UnresolvedObject)return{kind:"Input",type:"object",index:i,value:n.UnresolvedObject.objectId};throw new Error("Invalid input")});return{version:1,sender:e.sender??void 0,expiration:((r=e.expiration)==null?void 0:r.$kind)==="Epoch"?{Epoch:Number(e.expiration.Epoch)}:e.expiration?{None:!0}:null,gasConfig:{owner:e.gasData.owner??void 0,budget:e.gasData.budget??void 0,price:e.gasData.price??void 0,payment:e.gasData.payment??void 0},inputs:t,transactions:e.commands.map(n=>{if(n.MakeMoveVec)return{kind:"MakeMoveVec",type:n.MakeMoveVec.type===null?{None:!0}:{Some:Nr.parseFromStr(n.MakeMoveVec.type)},objects:n.MakeMoveVec.elements.map(i=>Tn(i,t))};if(n.MergeCoins)return{kind:"MergeCoins",destination:Tn(n.MergeCoins.destination,t),sources:n.MergeCoins.sources.map(i=>Tn(i,t))};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(i=>Tn(i,t))};if(n.Publish)return{kind:"Publish",modules:n.Publish.modules.map(i=>Array.from(cr(i))),dependencies:n.Publish.dependencies};if(n.SplitCoins)return{kind:"SplitCoins",coin:Tn(n.SplitCoins.coin,t),amounts:n.SplitCoins.amounts.map(i=>Tn(i,t))};if(n.TransferObjects)return{kind:"TransferObjects",objects:n.TransferObjects.objects.map(i=>Tn(i,t)),address:Tn(n.TransferObjects.address,t)};if(n.Upgrade)return{kind:"Upgrade",modules:n.Upgrade.modules.map(i=>Array.from(cr(i))),dependencies:n.Upgrade.dependencies,packageId:n.Upgrade.package,ticket:Tn(n.Upgrade.ticket,t)};throw new Error(`Unknown transaction ${Object.keys(n)}`)})}}function Tn(e,t){if(e.$kind==="GasCoin")return{kind:"GasCoin"};if(e.$kind==="Result")return{kind:"Result",index:e.Result};if(e.$kind==="NestedResult")return{kind:"NestedResult",index:e.NestedResult[0],resultIndex:e.NestedResult[1]};if(e.$kind==="Input")return t[e.Input];throw new Error(`Invalid argument ${Object.keys(e)}`)}function i9(e){var t,r,n;return qe(Qc,{version:2,sender:e.sender??null,expiration:e.expiration?"Epoch"in e.expiration?{Epoch:e.expiration.Epoch}:{None:!0}:null,gasData:{owner:e.gasConfig.owner??null,budget:((t=e.gasConfig.budget)==null?void 0:t.toString())??null,price:((r=e.gasConfig.price)==null?void 0:r.toString())??null,payment:((n=e.gasConfig.payment)==null?void 0:n.map(i=>({digest:i.digest,objectId:i.objectId,version:i.version.toString()})))??null},inputs:e.inputs.map(i=>{if(i.kind==="Input"){if(Rh(kb,i.value)){const s=qe(kb,i.value);if(s.Object){if(s.Object.ImmOrOwned)return{Object:{ImmOrOwnedObject:{objectId:s.Object.ImmOrOwned.objectId,version:String(s.Object.ImmOrOwned.version),digest:s.Object.ImmOrOwned.digest}}};if(s.Object.Shared)return{Object:{SharedObject:{mutable:s.Object.Shared.mutable??null,initialSharedVersion:s.Object.Shared.initialSharedVersion,objectId:s.Object.Shared.objectId}}};if(s.Object.Receiving)return{Object:{Receiving:{digest:s.Object.Receiving.digest,version:String(s.Object.Receiving.version),objectId:s.Object.Receiving.objectId}}};throw new Error("Invalid object input")}return{Pure:{bytes:Bt(new Uint8Array(s.Pure))}}}return i.type==="object"?{UnresolvedObject:{objectId:i.value}}:{UnresolvedPure:{value:i.value}}}throw new Error("Invalid input")}),commands:e.transactions.map(i=>{switch(i.kind){case"MakeMoveVec":return{MakeMoveVec:{type:"Some"in i.type?Nr.tagToString(i.type.Some):null,elements:i.objects.map(s=>In(s))}};case"MergeCoins":return{MergeCoins:{destination:In(i.destination),sources:i.sources.map(s=>In(s))}};case"MoveCall":{const[s,a,o]=i.target.split("::");return{MoveCall:{package:s,module:a,function:o,typeArguments:i.typeArguments,arguments:i.arguments.map(c=>In(c))}}}case"Publish":return{Publish:{modules:i.modules.map(s=>Bt(Uint8Array.from(s))),dependencies:i.dependencies}};case"SplitCoins":return{SplitCoins:{coin:In(i.coin),amounts:i.amounts.map(s=>In(s))}};case"TransferObjects":return{TransferObjects:{objects:i.objects.map(s=>In(s)),address:In(i.address)}};case"Upgrade":return{Upgrade:{modules:i.modules.map(s=>Bt(Uint8Array.from(s))),dependencies:i.dependencies,package:i.packageId,ticket:In(i.ticket)}}}throw new Error(`Unknown transaction ${Object.keys(i)}`)})})}function In(e){switch(e.kind){case"GasCoin":return{GasCoin:!0};case"Result":return{Result:e.index};case"NestedResult":return{NestedResult:[e.index,e.resultIndex]};case"Input":return{Input:e.index}}}function yc(e){return bn(Object.entries(e).map(([t,r])=>he({[t]:r})))}const Pr=yc({GasCoin:dt(!0),Input:xt(Jt(),Xt()),Result:xt(Jt(),Xt()),NestedResult:vp([xt(Jt(),Xt()),xt(Jt(),Xt())])}),s9=he({budget:Ye(er),price:Ye(er),owner:Ye(xa),payment:Ye(Te(Oi))}),a9=he({package:ur,module:Pe(),function:Pe(),typeArguments:Te(Pe()),arguments:Te(Pr)}),o9=he({name:Pe(),inputs:Uo(Pe(),bn([Pr,Te(Pr)])),data:Uo(Pe(),pc())}),c9=yc({MoveCall:a9,TransferObjects:he({objects:Te(Pr),address:Pr}),SplitCoins:he({coin:Pr,amounts:Te(Pr)}),MergeCoins:he({destination:Pr,sources:Te(Pr)}),Publish:he({modules:Te(ms),dependencies:Te(ur)}),MakeMoveVec:he({type:Ye(Pe()),elements:Te(Pr)}),Upgrade:he({modules:Te(ms),dependencies:Te(ur),package:ur,ticket:Pr}),$Intent:o9}),u9=yc({ImmOrOwnedObject:Oi,SharedObject:he({objectId:ur,initialSharedVersion:er,mutable:Ea()}),Receiving:Oi}),f9=yc({Object:u9,Pure:he({bytes:ms}),UnresolvedPure:he({value:pc()}),UnresolvedObject:he({objectId:ur,version:or(Ye(er)),digest:or(Ye(Pe())),initialSharedVersion:or(Ye(er)),mutable:or(Ye(Ea()))})}),l9=yc({None:dt(!0),Epoch:er}),d9=he({version:dt(2),sender:No(xa),expiration:No(l9),gasData:s9,inputs:Te(f9),commands:Te(c9),digest:or(Ye(Pe()))});function h9(e){return{$kind:"Pure",Pure:{bytes:e instanceof Uint8Array?Bt(e):e.toBase64()}}}const jr={Pure:h9,ObjectRef({objectId:e,digest:t,version:r}){return{$kind:"Object",Object:{$kind:"ImmOrOwnedObject",ImmOrOwnedObject:{digest:t,version:r,objectId:xe(e)}}}},SharedObjectRef({objectId:e,mutable:t,initialSharedVersion:r}){return{$kind:"Object",Object:{$kind:"SharedObject",SharedObject:{mutable:t,initialSharedVersion:r,objectId:xe(e)}}}},ReceivingRef({objectId:e,digest:t,version:r}){return{$kind:"Object",Object:{$kind:"Receiving",Receiving:{digest:t,version:r,objectId:xe(e)}}}}};BigInt(1e9);const p9="0x1",I5="0x2",y9=fn("0x6"),m9=`${I5}::sui::SUI`;fn("0x5");fn("0x8");const b9=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]),ft=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),ne=new Uint32Array(32);function ai(e,t,r,n,i,s){const a=i[s],o=i[s+1];let c=ne[2*e],u=ne[2*e+1],f=ne[2*t],l=ne[2*t+1],h=ne[2*r],d=ne[2*r+1],b=ne[2*n],g=ne[2*n+1],x=a0(c,f,a);u=o0(x,u,l,o),c=x|0,{Dh:g,Dl:b}={Dh:g^u,Dl:b^c},{Dh:g,Dl:b}={Dh:$8(g,b),Dl:M8(g)},{h:d,l:h}=Ir(d,h,g,b),{Bh:l,Bl:f}={Bh:l^d,Bl:f^h},{Bh:l,Bl:f}={Bh:li(l,f,24),Bl:di(l,f,24)},ne[2*e]=c,ne[2*e+1]=u,ne[2*t]=f,ne[2*t+1]=l,ne[2*r]=h,ne[2*r+1]=d,ne[2*n]=b,ne[2*n+1]=g}function oi(e,t,r,n,i,s){const a=i[s],o=i[s+1];let c=ne[2*e],u=ne[2*e+1],f=ne[2*t],l=ne[2*t+1],h=ne[2*r],d=ne[2*r+1],b=ne[2*n],g=ne[2*n+1],x=a0(c,f,a);u=o0(x,u,l,o),c=x|0,{Dh:g,Dl:b}={Dh:g^u,Dl:b^c},{Dh:g,Dl:b}={Dh:li(g,b,16),Dl:di(g,b,16)},{h:d,l:h}=Ir(d,h,g,b),{Bh:l,Bl:f}={Bh:l^d,Bl:f^h},{Bh:l,Bl:f}={Bh:Ma(l,f,63),Bl:ja(l,f,63)},ne[2*e]=c,ne[2*e+1]=u,ne[2*t]=f,ne[2*t+1]=l,ne[2*r]=h,ne[2*r+1]=d,ne[2*n]=b,ne[2*n+1]=g}function g9(e,t={},r,n,i){if(ki(r),e<0||e>r)throw new Error("outputLen bigger than keyLen");const{key:s,salt:a,personalization:o}=t;if(s!==void 0&&(s.length<1||s.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!==i)throw new Error("personalization must be undefined or "+i)}class w9 extends Mu{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,ki(t),ki(r),this.blockLen=t,this.outputLen=r,this.buffer=new Uint8Array(t),this.buffer32=so(this.buffer)}update(t){Ii(this),t=$n(t),Ti(t);const{blockLen:r,buffer:n,buffer32:i}=this,s=t.length,a=t.byteOffset,o=t.buffer;for(let c=0;c<s;){this.pos===r&&(hi(i),this.compress(i,0,!1),hi(i),this.pos=0);const u=Math.min(r-this.pos,s-c),f=a+c;if(u===r&&!(f%4)&&c+u<s){const l=new Uint32Array(o,f,Math.floor((s-c)/4));hi(l);for(let h=0;c+r<s;h+=i.length,c+=r)this.length+=r,this.compress(l,h,!1);hi(l);continue}n.set(t.subarray(c,c+u),this.pos),this.pos+=u,this.length+=u,c+=u}return this}digestInto(t){Ii(this),c0(t,this);const{pos:r,buffer32:n}=this;this.finished=!0,zr(this.buffer.subarray(r)),hi(n),this.compress(n,0,!0),hi(n);const i=so(t);this.get().forEach((s,a)=>i[a]=Pn(s))}digest(){const{buffer:t,outputLen:r}=this;this.digestInto(t);const n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){const{buffer:r,length:n,finished:i,destroyed:s,outputLen:a,pos:o}=this;return t||(t=new this.constructor({dkLen:a})),t.set(...this.get()),t.buffer.set(r),t.destroyed=s,t.finished=i,t.length=n,t.pos=o,t.outputLen=a,t}clone(){return this._cloneInto()}}class v9 extends w9{constructor(t={}){const r=t.dkLen===void 0?64:t.dkLen;super(128,r),this.v0l=ft[0]|0,this.v0h=ft[1]|0,this.v1l=ft[2]|0,this.v1h=ft[3]|0,this.v2l=ft[4]|0,this.v2h=ft[5]|0,this.v3l=ft[6]|0,this.v3h=ft[7]|0,this.v4l=ft[8]|0,this.v4h=ft[9]|0,this.v5l=ft[10]|0,this.v5h=ft[11]|0,this.v6l=ft[12]|0,this.v6h=ft[13]|0,this.v7l=ft[14]|0,this.v7h=ft[15]|0,g9(r,t,64,16,16);let{key:n,personalization:i,salt:s}=t,a=0;if(n!==void 0&&(n=$n(n),a=n.length),this.v0l^=this.outputLen|a<<8|65536|1<<24,s!==void 0){s=$n(s);const o=so(s);this.v4l^=Pn(o[0]),this.v4h^=Pn(o[1]),this.v5l^=Pn(o[2]),this.v5h^=Pn(o[3])}if(i!==void 0){i=$n(i);const o=so(i);this.v6l^=Pn(o[0]),this.v6h^=Pn(o[1]),this.v7l^=Pn(o[2]),this.v7h^=Pn(o[3])}if(n!==void 0){const o=new Uint8Array(this.blockLen);o.set(n),this.update(o)}}get(){let{v0l:t,v0h:r,v1l:n,v1h:i,v2l:s,v2h:a,v3l:o,v3h:c,v4l:u,v4h:f,v5l:l,v5h:h,v6l:d,v6h:b,v7l:g,v7h:x}=this;return[t,r,n,i,s,a,o,c,u,f,l,h,d,b,g,x]}set(t,r,n,i,s,a,o,c,u,f,l,h,d,b,g,x){this.v0l=t|0,this.v0h=r|0,this.v1l=n|0,this.v1h=i|0,this.v2l=s|0,this.v2h=a|0,this.v3l=o|0,this.v3h=c|0,this.v4l=u|0,this.v4h=f|0,this.v5l=l|0,this.v5h=h|0,this.v6l=d|0,this.v6h=b|0,this.v7l=g|0,this.v7h=x|0}compress(t,r,n){this.get().forEach((c,u)=>ne[u]=c),ne.set(ft,16);let{h:i,l:s}=l1(BigInt(this.length));ne[24]=ft[8]^s,ne[25]=ft[9]^i,n&&(ne[28]=~ne[28],ne[29]=~ne[29]);let a=0;const o=b9;for(let c=0;c<12;c++)ai(0,4,8,12,t,r+2*o[a++]),oi(0,4,8,12,t,r+2*o[a++]),ai(1,5,9,13,t,r+2*o[a++]),oi(1,5,9,13,t,r+2*o[a++]),ai(2,6,10,14,t,r+2*o[a++]),oi(2,6,10,14,t,r+2*o[a++]),ai(3,7,11,15,t,r+2*o[a++]),oi(3,7,11,15,t,r+2*o[a++]),ai(0,5,10,15,t,r+2*o[a++]),oi(0,5,10,15,t,r+2*o[a++]),ai(1,6,11,12,t,r+2*o[a++]),oi(1,6,11,12,t,r+2*o[a++]),ai(2,7,8,13,t,r+2*o[a++]),oi(2,7,8,13,t,r+2*o[a++]),ai(3,4,9,14,t,r+2*o[a++]),oi(3,4,9,14,t,r+2*o[a++]);this.v0l^=ne[0]^ne[16],this.v0h^=ne[1]^ne[17],this.v1l^=ne[2]^ne[18],this.v1h^=ne[3]^ne[19],this.v2l^=ne[4]^ne[20],this.v2h^=ne[5]^ne[21],this.v3l^=ne[6]^ne[22],this.v3h^=ne[7]^ne[23],this.v4l^=ne[8]^ne[24],this.v4h^=ne[9]^ne[25],this.v5l^=ne[10]^ne[26],this.v5h^=ne[11]^ne[27],this.v6l^=ne[12]^ne[28],this.v6h^=ne[13]^ne[29],this.v7l^=ne[14]^ne[30],this.v7h^=ne[15]^ne[31],zr(ne)}destroy(){this.destroyed=!0,zr(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const E9=Z8(e=>new v9(e)),_5=E9;function x9(e,t,r){const n=ye.Address.serialize(e).toBytes(),i=ye.TypeTag.serialize(t).toBytes(),s=ye.u64().serialize(r.length).toBytes(),a=_5.create({dkLen:32});return a.update(new Uint8Array([240])),a.update(n),a.update(s),a.update(r),a.update(i),`0x${oa(a.digest().slice(0,32))}`}const A9="object",S9="ID",k9="ascii",T9="String",I9="string",_9="String",P9="option",O9="Option";function B9(e){const t=typeof e.body=="object"&&"datatype"in e.body?e.body.datatype:null;return!!t&&xe(t.package)===xe("0x2")&&t.module==="tx_context"&&t.type==="TxContext"}function Fh(e){if(typeof e=="string")switch(e){case"address":return ye.Address;case"bool":return ye.Bool;case"u8":return ye.U8;case"u16":return ye.U16;case"u32":return ye.U32;case"u64":return ye.U64;case"u128":return ye.U128;case"u256":return ye.U256;default:throw new Error(`Unknown type signature ${e}`)}if("vector"in e){if(e.vector==="u8")return ye.byteVector().transform({input:r=>typeof r=="string"?new TextEncoder().encode(r):r,output:r=>r});const t=Fh(e.vector);return t?ye.vector(t):null}if("datatype"in e){const t=xe(e.datatype.package);if(t===xe(p9)){if(e.datatype.module===k9&&e.datatype.type===T9||e.datatype.module===I9&&e.datatype.type===_9)return ye.String;if(e.datatype.module===P9&&e.datatype.type===O9){const r=Fh(e.datatype.typeParameters[0]);return r?ye.vector(r):null}}if(t===xe(I5)&&e.datatype.module===A9&&e.datatype.type===S9)return ye.Address}return null}function C9(e){return typeof e=="object"&&"Reference"in e?{ref:"&",body:Qa(e.Reference)}:typeof e=="object"&&"MutableReference"in e?{ref:"&mut",body:Qa(e.MutableReference)}:{ref:null,body:Qa(e)}}function Qa(e){if(typeof e=="string")switch(e){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 ${e}`)}if("Vector"in e)return{vector:Qa(e.Vector)};if("Struct"in e)return{datatype:{package:e.Struct.address,module:e.Struct.module,type:e.Struct.name,typeParameters:e.Struct.typeArguments.map(Qa)}};if("TypeParameter"in e)return{typeParameter:e.TypeParameter};throw new Error(`Unexpected type ${JSON.stringify(e)}`)}const R9=50,N9=1000n,U9=5e10;function P5(e){return async function(r,n,i){return await H9(r,e),await j9(r,e),n.onlyTransactionKind||(await F9(r,e),await $9(r,e),await M9(r,e)),await i()}}async function F9(e,t){e.gasConfig.price||(e.gasConfig.price=String(await t.getReferenceGasPrice()))}async function $9(e,t){if(e.gasConfig.budget)return;const r=await t.dryRunTransactionBlock({transactionBlock:e.build({overrides:{gasData:{budget:String(U9),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=N9*BigInt(e.gasConfig.price||1n),i=BigInt(r.effects.gasUsed.computationCost)+n,s=i+BigInt(r.effects.gasUsed.storageCost)-BigInt(r.effects.gasUsed.storageRebate);e.gasConfig.budget=String(s>i?s:i)}async function M9(e,t){if(!e.gasConfig.payment){const n=(await t.getCoins({owner:e.gasConfig.owner||e.sender,coinType:m9})).data.filter(i=>!e.inputs.find(a=>{var o;return(o=a.Object)!=null&&o.ImmOrOwnedObject?i.coinObjectId===a.Object.ImmOrOwnedObject.objectId:!1})).map(i=>({objectId:i.coinObjectId,digest:i.digest,version:i.version}));if(!n.length)throw new Error("No valid gas coins found for the transaction.");e.gasConfig.payment=n.map(i=>qe(Oi,i))}}async function j9(e,t){const r=e.inputs.filter(f=>{var l;return f.UnresolvedObject&&!(f.UnresolvedObject.version||(l=f.UnresolvedObject)!=null&&l.initialSharedVersion)}),n=[...new Set(r.map(f=>fn(f.UnresolvedObject.objectId)))],i=n.length?Sf(n,R9):[],s=(await Promise.all(i.map(f=>t.multiGetObjects({ids:f,options:{showOwner:!0}})))).flat(),a=new Map(n.map((f,l)=>[f,s[l]])),o=Array.from(a).filter(([f,l])=>l.error).map(([f,l])=>JSON.stringify(l.error));if(o.length)throw new Error(`The following input objects are invalid: ${o.join(", ")}`);const c=s.map(f=>{if(f.error||!f.data)throw new Error(`Failed to fetch object: ${f.error}`);const l=f.data.owner,h=l&&typeof l=="object"?"Shared"in l?l.Shared.initial_shared_version:"ConsensusAddressOwner"in l?l.ConsensusAddressOwner.start_version:null:null;return{objectId:f.data.objectId,digest:f.data.digest,version:f.data.version,initialSharedVersion:h}}),u=new Map(n.map((f,l)=>[f,c[l]]));for(const[f,l]of e.inputs.entries()){if(!l.UnresolvedObject)continue;let h;const d=xe(l.UnresolvedObject.objectId),b=u.get(d);l.UnresolvedObject.initialSharedVersion??(b==null?void 0:b.initialSharedVersion)?h=jr.SharedObjectRef({objectId:d,initialSharedVersion:l.UnresolvedObject.initialSharedVersion||(b==null?void 0:b.initialSharedVersion),mutable:l.UnresolvedObject.mutable||L9(e,f)}):D9(e,f)&&(h=jr.ReceivingRef({objectId:d,digest:l.UnresolvedObject.digest??(b==null?void 0:b.digest),version:l.UnresolvedObject.version??(b==null?void 0:b.version)})),e.inputs[e.inputs.indexOf(l)]=h??jr.ObjectRef({objectId:d,digest:l.UnresolvedObject.digest??(b==null?void 0:b.digest),version:l.UnresolvedObject.version??(b==null?void 0:b.version)})}}async function H9(e,t){const{inputs:r,commands:n}=e,i=[],s=new Set;n.forEach(o=>{if(o.MoveCall){if(o.MoveCall._argumentTypes)return;if(o.MoveCall.arguments.map(f=>f.$kind==="Input"?e.inputs[f.Input]:null).some(f=>(f==null?void 0:f.UnresolvedPure)||(f==null?void 0:f.UnresolvedObject)&&typeof(f==null?void 0:f.UnresolvedObject.mutable)!="boolean")){const f=`${o.MoveCall.package}::${o.MoveCall.module}::${o.MoveCall.function}`;s.add(f),i.push(o.MoveCall)}}});const a=new Map;s.size>0&&await Promise.all([...s].map(async o=>{const[c,u,f]=o.split("::"),l=await t.getNormalizedMoveFunction({package:c,module:u,function:f});a.set(o,l.parameters.map(h=>C9(h)))})),i.length&&await Promise.all(i.map(async o=>{const c=a.get(`${o.package}::${o.module}::${o.function}`);if(!c)return;const f=c.length>0&&B9(c.at(-1))?c.slice(0,c.length-1):c;o._argumentTypes=f})),n.forEach(o=>{if(!o.MoveCall)return;const c=o.MoveCall,u=`${c.package}::${c.module}::${c.function}`,f=c._argumentTypes;if(f){if(f.length!==o.MoveCall.arguments.length)throw new Error(`Incorrect number of arguments for ${u}`);f.forEach((l,h)=>{var k,w;const d=c.arguments[h];if(d.$kind!=="Input")return;const b=r[d.Input];if(!b.UnresolvedPure&&!b.UnresolvedObject)return;const g=((k=b.UnresolvedPure)==null?void 0:k.value)??((w=b.UnresolvedObject)==null?void 0:w.objectId),x=Fh(l.body);if(x){d.type="pure",r[r.indexOf(b)]=jr.Pure(x.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 A=b.UnresolvedPure?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:g}}:b;r[d.Input]=A})}})}function L9(e,t){let r=!1;return e.getInputUses(t,(n,i)=>{if(i.MoveCall&&i.MoveCall._argumentTypes){const s=i.MoveCall.arguments.indexOf(n);r=i.MoveCall._argumentTypes[s].ref!=="&"||r}(i.$kind==="MakeMoveVec"||i.$kind==="MergeCoins"||i.$kind==="SplitCoins"||i.$kind==="TransferObjects")&&(r=!0)}),r}function D9(e,t){let r=!1;return e.getInputUses(t,(n,i)=>{if(i.MoveCall&&i.MoveCall._argumentTypes){const s=i.MoveCall.arguments.indexOf(n);r=z9(i.MoveCall._argumentTypes[s])||r}}),r}function z9(e){return typeof e.body!="object"||!("datatype"in e.body)?!1:e.body.datatype.package==="0x2"&&e.body.datatype.module==="transfer"&&e.body.datatype.type==="Receiving"}function O5(e,t){return!!(e.inputs.some(r=>r.UnresolvedObject||r.UnresolvedPure)||!t.onlyTransactionKind&&(!e.gasConfig.price||!e.gasConfig.budget||!e.gasConfig.payment))}async function V9(e,t,r){var s;if(q9(e),!O5(e,t))return await Ib(e),r();const n=G9(t);return(((s=n.core)==null?void 0:s.resolveTransactionPlugin())??P5(n))(e,t,async()=>{await Ib(e),await r()})}function Ib(e){e.inputs.forEach((t,r)=>{if(t.$kind!=="Object"&&t.$kind!=="Pure")throw new Error(`Input at index ${r} has not been resolved. Expected a Pure or Object input, but found ${JSON.stringify(t)}`)})}function G9(e){if(!e.client)throw new Error("No sui client passed to Transaction#build, but transaction data was not sufficient to build offline.");return e.client}function q9(e){for(const t of e.commands)switch(t.$kind){case"SplitCoins":t.SplitCoins.amounts.forEach(r=>{_b(r,ye.U64,e)});break;case"TransferObjects":_b(t.TransferObjects.address,ye.Address,e);break}}function _b(e,t,r){if(e.$kind!=="Input")return;const n=r.inputs[e.Input];n.$kind==="UnresolvedPure"&&(r.inputs[e.Input]=jr.Pure(t.serialize(n.UnresolvedPure.value)))}function W9(e){function t(r){return e(r)}return t.system=r=>{const n=r==null?void 0:r.mutable;return t(n!==void 0?jr.SharedObjectRef({objectId:"0x5",initialSharedVersion:1,mutable:n}):{$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x5",initialSharedVersion:1}})},t.clock=()=>t(jr.SharedObjectRef({objectId:"0x6",initialSharedVersion:1,mutable:!1})),t.random=()=>t({$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x8",mutable:!1}}),t.denyList=r=>t({$kind:"UnresolvedObject",UnresolvedObject:{objectId:"0x403",mutable:r==null?void 0:r.mutable}}),t.option=({type:r,value:n})=>i=>i.moveCall({typeArguments:[r],target:`0x1::option::${n===null?"none":"some"}`,arguments:n===null?[]:[i.object(n)]}),t}function K9(e){function t(r,n){if(typeof r=="string")return e(Za(r).serialize(n));if(r instanceof Uint8Array||gp(r))return e(r);throw new Error("tx.pure must be called either a bcs type name, or a serialized bcs value")}return t.u8=r=>e(ye.U8.serialize(r)),t.u16=r=>e(ye.U16.serialize(r)),t.u32=r=>e(ye.U32.serialize(r)),t.u64=r=>e(ye.U64.serialize(r)),t.u128=r=>e(ye.U128.serialize(r)),t.u256=r=>e(ye.U256.serialize(r)),t.bool=r=>e(ye.Bool.serialize(r)),t.string=r=>e(ye.String.serialize(r)),t.address=r=>e(ye.Address.serialize(r)),t.id=t.address,t.vector=(r,n)=>e(ye.vector(Za(r)).serialize(n)),t.option=(r,n)=>e(ye.option(Za(r)).serialize(n)),t}function X9(e,t){const r=Array.from(`${e}::`).map(i=>i.charCodeAt(0)),n=new Uint8Array(r.length+t.length);return n.set(r),n.set(t,r.length),_5(n,{dkLen:32})}function Eu(e){if(typeof e=="string")return xe(e);if(e.Object)return e.Object.ImmOrOwnedObject?xe(e.Object.ImmOrOwnedObject.objectId):e.Object.Receiving?xe(e.Object.Receiving.objectId):xe(e.Object.SharedObject.objectId);if(e.UnresolvedObject)return xe(e.UnresolvedObject.objectId)}function J9(e,t,r){const n=i=>{switch(i.$kind){case"Input":{const s=t.get(i.Input);if(s===void 0)throw new Error(`Input ${i.Input} not found in input mapping`);return{...i,Input:s}}case"Result":{const s=r.get(i.Result);return s!==void 0?{...i,Result:s}:i}case"NestedResult":{const s=r.get(i.NestedResult[0]);return s!==void 0?{...i,NestedResult:[s,i.NestedResult[1]]}:i}default:return i}};switch(e.$kind){case"MoveCall":e.MoveCall.arguments=e.MoveCall.arguments.map(n);break;case"TransferObjects":e.TransferObjects.objects=e.TransferObjects.objects.map(n),e.TransferObjects.address=n(e.TransferObjects.address);break;case"SplitCoins":e.SplitCoins.coin=n(e.SplitCoins.coin),e.SplitCoins.amounts=e.SplitCoins.amounts.map(n);break;case"MergeCoins":e.MergeCoins.destination=n(e.MergeCoins.destination),e.MergeCoins.sources=e.MergeCoins.sources.map(n);break;case"MakeMoveVec":e.MakeMoveVec.elements=e.MakeMoveVec.elements.map(n);break;case"Upgrade":e.Upgrade.ticket=n(e.Upgrade.ticket);break;case"$Intent":{const i=e.$Intent.inputs;e.$Intent.inputs={};for(const[s,a]of Object.entries(i))e.$Intent.inputs[s]=Array.isArray(a)?a.map(n):n(a);break}}}function Pb(e){return xe(e).replace("0x","")}class Kt{constructor(t){this.version=2,this.sender=(t==null?void 0:t.sender)??null,this.expiration=(t==null?void 0:t.expiration)??null,this.inputs=(t==null?void 0:t.inputs)??[],this.commands=(t==null?void 0:t.commands)??[],this.gasData=(t==null?void 0:t.gasData)??{budget:null,price:null,owner:null,payment:null}}static fromKindBytes(t){const n=ye.TransactionKind.parse(t).ProgrammableTransaction;if(!n)throw new Error("Unable to deserialize from bytes.");return Kt.restore({version:2,sender:null,expiration:null,gasData:{budget:null,owner:null,payment:null,price:null},inputs:n.inputs,commands:n.commands})}static fromBytes(t){const r=ye.TransactionData.parse(t),n=r==null?void 0:r.V1,i=n.kind.ProgrammableTransaction;if(!n||!i)throw new Error("Unable to deserialize from bytes.");return Kt.restore({version:2,sender:n.sender,expiration:n.expiration,gasData:n.gasData,inputs:i.inputs,commands:i.commands})}static restore(t){return t.version===2?new Kt(qe(Qc,t)):new Kt(qe(Qc,i9(t)))}static getDigestFromBytes(t){const r=X9("TransactionData",t);return Af(r)}get gasConfig(){return this.gasData}set gasConfig(t){this.gasData=t}build({maxSizeBytes:t=1/0,overrides:r,onlyTransactionKind:n}={}){const i=this.inputs,s=this.commands,a={ProgrammableTransaction:{inputs:i,commands:s}};if(n)return ye.TransactionKind.serialize(a,{maxSize:t}).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 f={sender:Pb(c),expiration:o||{None:!0},gasData:{payment:u.payment,owner:Pb(this.gasData.owner??c),price:BigInt(u.price),budget:BigInt(u.budget)},kind:{ProgrammableTransaction:{inputs:i,commands:s}}};return ye.TransactionData.serialize({V1:f},{maxSize:t}).toBytes()}addInput(t,r){const n=this.inputs.length;return this.inputs.push(r),{Input:n,type:t,$kind:"Input"}}getInputUses(t,r){this.mapArguments((n,i)=>(n.$kind==="Input"&&n.Input===t&&r(n,i),n))}mapCommandArguments(t,r){const n=this.commands[t];switch(n.$kind){case"MoveCall":n.MoveCall.arguments=n.MoveCall.arguments.map(s=>r(s,n,t));break;case"TransferObjects":n.TransferObjects.objects=n.TransferObjects.objects.map(s=>r(s,n,t)),n.TransferObjects.address=r(n.TransferObjects.address,n,t);break;case"SplitCoins":n.SplitCoins.coin=r(n.SplitCoins.coin,n,t),n.SplitCoins.amounts=n.SplitCoins.amounts.map(s=>r(s,n,t));break;case"MergeCoins":n.MergeCoins.destination=r(n.MergeCoins.destination,n,t),n.MergeCoins.sources=n.MergeCoins.sources.map(s=>r(s,n,t));break;case"MakeMoveVec":n.MakeMoveVec.elements=n.MakeMoveVec.elements.map(s=>r(s,n,t));break;case"Upgrade":n.Upgrade.ticket=r(n.Upgrade.ticket,n,t);break;case"$Intent":const i=n.$Intent.inputs;n.$Intent.inputs={};for(const[s,a]of Object.entries(i))n.$Intent.inputs[s]=Array.isArray(a)?a.map(o=>r(o,n,t)):r(a,n,t);break;case"Publish":break;default:throw new Error(`Unexpected transaction kind: ${n.$kind}`)}}mapArguments(t){for(const r of this.commands.keys())this.mapCommandArguments(r,t)}replaceCommand(t,r,n=t){if(!Array.isArray(r)){this.commands[t]=r;return}const i=r.length-1;this.commands.splice(t,1,...structuredClone(r)),this.mapArguments((s,a,o)=>{if(o<t+r.length)return s;if(typeof n!="number"&&(s.$kind==="Result"&&s.Result===t||s.$kind==="NestedResult"&&s.NestedResult[0]===t)){if(!("NestedResult"in s)||s.NestedResult[1]===0)return qe(He,structuredClone(n));throw new Error(`Cannot replace command ${t} with a specific result type: NestedResult[${t}, ${s.NestedResult[1]}] references a nested element that cannot be mapped to the replacement result`)}switch(s.$kind){case"Result":s.Result===t&&typeof n=="number"&&(s.Result=n),s.Result>t&&(s.Result+=i);break;case"NestedResult":if(s.NestedResult[0]===t&&typeof n=="number")return{$kind:"NestedResult",NestedResult:[n,s.NestedResult[1]]};s.NestedResult[0]>t&&(s.NestedResult[0]+=i);break}return s})}replaceCommandWithTransaction(t,r,n){if(n.$kind!=="Result"&&n.$kind!=="NestedResult")throw new Error("Result must be of kind Result or NestedResult");this.insertTransaction(t,r),this.replaceCommand(t+r.commands.length,[],"Result"in n?{NestedResult:[n.Result+t,0]}:{NestedResult:[n.NestedResult[0]+t,n.NestedResult[1]]})}insertTransaction(t,r){var o,c;const n=new Map,i=new Map;for(let u=0;u<r.inputs.length;u++){const f=r.inputs[u],l=Eu(f);let h=-1;if(l!==void 0&&(h=this.inputs.findIndex(d=>Eu(d)===l),h!==-1&&((o=this.inputs[h].Object)!=null&&o.SharedObject)&&((c=f.Object)!=null&&c.SharedObject)&&(this.inputs[h].Object.SharedObject.mutable=this.inputs[h].Object.SharedObject.mutable||f.Object.SharedObject.mutable)),h!==-1)n.set(u,h);else{const d=this.inputs.length;this.inputs.push(f),n.set(u,d)}}for(let u=0;u<r.commands.length;u++)i.set(u,t+u);const s=[];for(let u=0;u<r.commands.length;u++){const f=structuredClone(r.commands[u]);J9(f,n,i),s.push(f)}this.commands.splice(t,0,...s);const a=s.length;a>0&&this.mapArguments((u,f,l)=>{if(l>=t&&l<t+s.length)return u;switch(u.$kind){case"Result":u.Result>=t&&(u.Result+=a);break;case"NestedResult":u.NestedResult[0]>=t&&(u.NestedResult[0]+=a);break}return u})}getDigest(){const t=this.build({onlyTransactionKind:!1});return Kt.getDigestFromBytes(t)}snapshot(){return qe(Qc,this)}shallowClone(){return new Kt({version:this.version,sender:this.sender,expiration:this.expiration,gasData:{...this.gasData},inputs:[...this.inputs],commands:[...this.commands]})}applyResolvedData(t){this.sender||(this.sender=t.sender??null),this.expiration||(this.expiration=t.expiration??null),this.gasData.budget||(this.gasData.budget=t.gasData.budget),this.gasData.owner||(this.gasData.owner=t.gasData.owner??null),this.gasData.payment||(this.gasData.payment=t.gasData.payment),this.gasData.price||(this.gasData.price=t.gasData.price);for(let r=0;r<this.inputs.length;r++){const n=this.inputs[r],i=t.inputs[r];switch(n.$kind){case"UnresolvedPure":if(i.$kind!=="Pure")throw new Error(`Expected input at index ${r} to resolve to a Pure argument, but got ${JSON.stringify(i)}`);this.inputs[r]=i;break;case"UnresolvedObject":if(i.$kind!=="Object")throw new Error(`Expected input at index ${r} to resolve to an Object argument, but got ${JSON.stringify(i)}`);if(i.Object.$kind==="ImmOrOwnedObject"||i.Object.$kind==="Receiving"){const s=n.UnresolvedObject,a=i.Object.ImmOrOwnedObject??i.Object.Receiving;if(xe(s.objectId)!==xe(a.objectId)||s.version!=null&&s.version!==a.version||s.digest!=null&&s.digest!==a.digest||s.mutable!=null||s.initialSharedVersion!=null)throw new Error(`Input at index ${r} did not match unresolved object. ${JSON.stringify(s)} is not compatible with ${JSON.stringify(a)}`)}else if(i.Object.$kind==="SharedObject"){const s=n.UnresolvedObject,a=i.Object.SharedObject;if(xe(s.objectId)!==xe(a.objectId)||s.initialSharedVersion!=null&&s.initialSharedVersion!==a.initialSharedVersion||s.mutable!=null&&s.mutable!==a.mutable||s.version!=null||s.digest!=null)throw new Error(`Input at index ${r} did not match unresolved object. ${JSON.stringify(s)} is not compatible with ${JSON.stringify(a)}`)}else throw new Error(`Input at index ${r} resolved to an unexpected Object kind: ${JSON.stringify(i.Object)}`);this.inputs[r]=i;break}}}}var B5=e=>{throw TypeError(e)},Sp=(e,t,r)=>t.has(e)||B5("Cannot "+r),ht=(e,t,r)=>(Sp(e,t,"read from private field"),r?r.call(e):t.get(e)),Ca=(e,t,r)=>t.has(e)?B5("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Dc=(e,t,r,n)=>(Sp(e,t,"write to private field"),t.set(e,r),r),_f=(e,t,r)=>(Sp(e,t,"access private method"),r),Fo,Vn,$o,pi,un,$h,Mh,C5,R5,kp;const Y9="/",Z9={"Mvr-Source":`@mysten/sui@${S6}`};class Q9{constructor({cache:t,url:r,pageSize:n=50,overrides:i}){Ca(this,un),Ca(this,Fo),Ca(this,Vn),Ca(this,$o),Ca(this,pi),Dc(this,Fo,t),Dc(this,Vn,r),Dc(this,$o,n),Dc(this,pi,{packages:i==null?void 0:i.packages,types:i==null?void 0:i.types}),eC(ht(this,pi))}async resolvePackage({package:t}){return Pt(t)?{package:await ht(this,un,$h).load(t)}:{package:t}}async resolveType({type:t}){if(!Pt(t))return{type:t};const r=[...jh(t)],n=await ht(this,un,Mh).loadMany(r),i={};for(let s=0;s<r.length;s++){const a=n[s];if(a instanceof Error)throw a;i[r[s]]=a}return{type:Hh(t,i)}}async resolve({types:t=[],packages:r=[]}){var f,l,h;const n=new Set;for(const d of t??[])jh(d,n);const i=[...n],[s,a]=await Promise.all([i.length>0?ht(this,un,Mh).loadMany(i):[],r.length>0?ht(this,un,$h).loadMany(r):[]]),o={...(f=ht(this,pi))==null?void 0:f.types};for(const[d,b]of i.entries()){const g=s[d];if(g instanceof Error)throw g;o[b]=g}const c={};for(const d of t??[]){const b=Hh(d,o);c[d]={type:b}}const u={};for(const[d,b]of(r??[]).entries()){const g=((h=(l=ht(this,pi))==null?void 0:l.packages)==null?void 0:h[b])??a[d];if(g instanceof Error)throw g;u[b]={package:g}}return{types:c,packages:u}}}Fo=new WeakMap;Vn=new WeakMap;$o=new WeakMap;pi=new WeakMap;un=new WeakSet;$h=function(){return ht(this,Fo).readSync(["#mvrPackageDataLoader",ht(this,Vn)??""],()=>{var r;const e=new M6(async n=>{if(!ht(this,Vn))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const i=await _f(this,un,C5).call(this,n);return n.map(s=>i[s]??new Error(`Failed to resolve package: ${s}`))}),t=(r=ht(this,pi))==null?void 0:r.packages;if(t)for(const[n,i]of Object.entries(t))e.prime(n,i);return e})};Mh=function(){return ht(this,Fo).readSync(["#mvrTypeDataLoader",ht(this,Vn)??""],()=>{var r;const e=new M6(async n=>{if(!ht(this,Vn))throw new Error(`MVR Api URL is not set for the current client (resolving ${n.join(", ")})`);const i=await _f(this,un,R5).call(this,n);return n.map(s=>i[s]??new Error(`Failed to resolve type: ${s}`))}),t=(r=ht(this,pi))==null?void 0:r.types;if(t)for(const[n,i]of Object.entries(t))e.prime(n,i);return e})};C5=async function(e){if(e.length===0)return{};const t=Sf(e,ht(this,$o)),r={};return await Promise.all(t.map(async n=>{var s;const i=await _f(this,un,kp).call(this,"/v1/resolution/bulk",{names:n});if(i!=null&&i.resolution)for(const a of Object.keys(i==null?void 0:i.resolution)){const o=(s=i.resolution[a])==null?void 0:s.package_id;o&&(r[a]=o)}})),r};R5=async function(e){if(e.length===0)return{};const t=Sf(e,ht(this,$o)),r={};return await Promise.all(t.map(async n=>{var s;const i=await _f(this,un,kp).call(this,"/v1/struct-definition/bulk",{types:n});if(i!=null&&i.resolution)for(const a of Object.keys(i==null?void 0:i.resolution)){const o=(s=i.resolution[a])==null?void 0:s.type_tag;o&&(r[a]=o)}})),r};kp=async function(e,t){if(!ht(this,Vn))throw new Error("MVR Api URL is not set for the current client");const r=await fetch(`${ht(this,Vn)}${e}`,{method:"POST",headers:{"Content-Type":"application/json",...Z9},body:JSON.stringify(t)});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 eC(e){if(e!=null&&e.packages)for(const[t,r]of Object.entries(e.packages)){if(!nr(t))throw new Error(`Invalid package name: ${t}`);if(!Rr(xe(r)))throw new Error(`Invalid package ID: ${r}`)}if(e!=null&&e.types)for(const[t,r]of Object.entries(e.types)){if(ys(t).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=ys(r);if(!Rr(n.address))throw new Error(`Invalid type: ${r}`)}}function jh(e,t=new Set){if(typeof e=="string"&&!Pt(e))return t;const r=N5(e)?e:ys(e);Pt(r.address)&&t.add(`${r.address}::${r.module}::${r.name}`);for(const n of r.typeParams)jh(n,t);return t}function Hh(e,t){const r=N5(e)?e:ys(e),n=`${r.address}::${r.module}::${r.name}`,i=t[n];return vu({...r,address:i?i.split("::")[0]:r.address,typeParams:r.typeParams.map(s=>Hh(s,t))})}function Pt(e){return e.includes(Y9)||e.includes("@")||e.includes(".sui")}function N5(e){return typeof e=="object"&&"address"in e&&"module"in e&&"name"in e&&"typeParams"in e}function tC(e){const t=new Set,r=new Set;for(const n of e.commands)switch(n.$kind){case"MakeMoveVec":n.MakeMoveVec.type&&Ob([n.MakeMoveVec.type]).forEach(a=>{r.add(a)});break;case"MoveCall":const i=n.MoveCall,s=i.package.split("::")[0];if(Pt(s)){if(!nr(s))throw new Error(`Invalid package name: ${s}`);t.add(s)}Ob(i.typeArguments??[]).forEach(a=>{r.add(a)});break}return{packages:[...t],types:[...r]}}function rC(e,t){var r;for(const n of e.commands){if((r=n.MakeMoveVec)!=null&&r.type){if(!Pt(n.MakeMoveVec.type))continue;if(!t.types[n.MakeMoveVec.type])throw new Error(`No resolution found for type: ${n.MakeMoveVec.type}`);n.MakeMoveVec.type=t.types[n.MakeMoveVec.type].type}const i=n.MoveCall;if(!i)continue;const s=i.package.split("::"),a=s[0];if(Pt(a)&&!t.packages[a])throw new Error(`No address found for package: ${a}`);Pt(a)&&(s[0]=t.packages[a].package,i.package=s.join("::"));const o=i.typeArguments;if(o){for(let c=0;c<o.length;c++)if(Pt(o[c])){if(!t.types[o[c]])throw new Error(`No resolution found for type: ${o[c]}`);o[c]=t.types[o[c]].type}i.typeArguments=o}}}function Ob(e){const t=new Set;for(const r of e)if(Pt(r)){if(!kB(r))throw new Error(`Invalid type with names: ${r}`);t.add(r)}return t}const nC=e=>async(t,r,n)=>{const i=tC(t);if(i.types.length===0&&i.packages.length===0)return n();const s=await iC(r).core.mvr.resolve({types:i.types,packages:i.packages});rC(t,s),await n()};function iC(e){if(!e.client)throw new Error("No sui client passed to Transaction#build, but transaction data was not sufficient to build offline.");return e.client}var U5=e=>{throw TypeError(e)},Tp=(e,t,r)=>t.has(e)||U5("Cannot "+r),Z=(e,t,r)=>(Tp(e,t,"read from private field"),r?r.call(e):t.get(e)),rn=(e,t,r)=>t.has(e)?U5("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Ce=(e,t,r,n)=>(Tp(e,t,"write to private field"),t.set(e,r),r),lt=(e,t,r)=>(Tp(e,t,"access private method"),r),Ji,ns,Cn,ln,sr,ar,Ur,yi,ue,et,F5,eu,tu,ru,xu,Lh,Ip,$5,M5;function Ad(e,t=1/0){const r={$kind:"Result",get Result(){return typeof e=="function"?e():e}},n=[],i=s=>n[s]??(n[s]={$kind:"NestedResult",get NestedResult(){return[typeof e=="function"?e():e,s]}});return new Proxy(r,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(s,a){if(a in s)return Reflect.get(s,a);if(a===Symbol.iterator)return function*(){let c=0;for(;c<t;)yield i(c),c++};if(typeof a=="symbol")return;const o=parseInt(a,10);if(!(Number.isNaN(o)||o<0))return i(o)}})}const j5=Symbol.for("@mysten/transaction");function H5(e){return!!e&&typeof e=="object"&&e[j5]===!0}const Bb={buildPlugins:new Map,serializationPlugins:new Map},Sd=Symbol.for("@mysten/transaction/registry");function Ra(){try{const e=globalThis;return e[Sd]||(e[Sd]=Bb),e[Sd]}catch{return Bb}}const L5=class Dh{constructor(){rn(this,et),rn(this,Ji),rn(this,ns),rn(this,Cn,new Map),rn(this,ln,[]),rn(this,sr,[]),rn(this,ar,new Set),rn(this,Ur,new Set),rn(this,yi,new Map),rn(this,ue),this.object=W9(r=>{var s,a;if(typeof r=="function")return this.object(this.add(r));if(typeof r=="object"&&Rh(He,r))return r;const n=Eu(r),i=Z(this,ue).inputs.find(o=>n===Eu(o));return(s=i==null?void 0:i.Object)!=null&&s.SharedObject&&typeof r=="object"&&((a=r.Object)!=null&&a.SharedObject)&&(i.Object.SharedObject.mutable=i.Object.SharedObject.mutable||r.Object.SharedObject.mutable),i?{$kind:"Input",Input:Z(this,ue).inputs.indexOf(i),type:"object"}:lt(this,et,tu).call(this,"object",typeof r=="string"?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:xe(r)}}:r)});const t=Ra();Ce(this,ue,new Kt),Ce(this,ns,[...t.buildPlugins.values()]),Ce(this,Ji,[...t.serializationPlugins.values()])}static fromKind(t){const r=new Dh;return Ce(r,ue,Kt.fromKindBytes(typeof t=="string"?cr(t):t)),Ce(r,ln,Z(r,ue).inputs.slice()),Ce(r,sr,Z(r,ue).commands.slice()),Ce(r,ar,new Set(Z(r,sr).map((n,i)=>i))),r}static from(t){const r=new Dh;return H5(t)?Ce(r,ue,Kt.restore(t.getData())):typeof t!="string"||!t.startsWith("{")?Ce(r,ue,Kt.fromBytes(typeof t=="string"?cr(t):t)):Ce(r,ue,Kt.restore(JSON.parse(t))),Ce(r,ln,Z(r,ue).inputs.slice()),Ce(r,sr,Z(r,ue).commands.slice()),Ce(r,ar,new Set(Z(r,sr).map((n,i)=>i))),r}static registerGlobalSerializationPlugin(t,r){Ra().serializationPlugins.set(t,r??t)}static unregisterGlobalSerializationPlugin(t){Ra().serializationPlugins.delete(t)}static registerGlobalBuildPlugin(t,r){Ra().buildPlugins.set(t,r??t)}static unregisterGlobalBuildPlugin(t){Ra().buildPlugins.delete(t)}addSerializationPlugin(t){Z(this,Ji).push(t)}addBuildPlugin(t){Z(this,ns).push(t)}addIntentResolver(t,r){if(Z(this,Cn).has(t)&&Z(this,Cn).get(t)!==r)throw new Error(`Intent resolver for ${t} already exists`);Z(this,Cn).set(t,r)}setSender(t){Z(this,ue).sender=t}setSenderIfNotSet(t){Z(this,ue).sender||(Z(this,ue).sender=t)}setExpiration(t){Z(this,ue).expiration=t?qe(r5,t):null}setGasPrice(t){Z(this,ue).gasConfig.price=String(t)}setGasBudget(t){Z(this,ue).gasConfig.budget=String(t)}setGasBudgetIfNotSet(t){Z(this,ue).gasData.budget==null&&(Z(this,ue).gasConfig.budget=String(t))}setGasOwner(t){Z(this,ue).gasConfig.owner=t}setGasPayment(t){Z(this,ue).gasConfig.payment=t.map(r=>qe(Oi,r))}get blockData(){return Tb(Z(this,ue).snapshot())}getData(){return Z(this,ue).snapshot()}get[j5](){return!0}get pure(){return Object.defineProperty(this,"pure",{enumerable:!1,value:K9(t=>gp(t)?lt(this,et,tu).call(this,"pure",{$kind:"Pure",Pure:{bytes:t.toBase64()}}):lt(this,et,tu).call(this,"pure",Rh(xb,t)?qe(xb,t):t instanceof Uint8Array?jr.Pure(t):{$kind:"UnresolvedPure",UnresolvedPure:{value:t}}))}),this.pure}get gas(){return{$kind:"GasCoin",GasCoin:!0}}objectRef(...t){return this.object(jr.ObjectRef(...t))}receivingRef(...t){return this.object(jr.ReceivingRef(...t))}sharedObjectRef(...t){return this.object(jr.SharedObjectRef(...t))}add(t){if(typeof t=="function"){if(Z(this,yi).has(t))return Z(this,yi).get(t);const r=lt(this,et,F5).call(this),n=t(r);if(!(n&&typeof n=="object"&&"then"in n))return Ce(this,ar,Z(r,ar)),Z(this,yi).set(t,n),n;const i=lt(this,et,eu).call(this,{$kind:"$Intent",$Intent:{name:"AsyncTransactionThunk",inputs:{},data:{resultIndex:Z(this,ue).commands.length,result:null}}});Z(this,Ur).add(Promise.resolve(n).then(a=>{i.$Intent.data.result=a}));const s=Ad(()=>i.$Intent.data.resultIndex);return Z(this,yi).set(t,s),s}else lt(this,et,eu).call(this,t);return Ad(Z(this,ue).commands.length-1)}splitCoins(t,r){const n=Li.SplitCoins(typeof t=="string"?this.object(t):lt(this,et,xu).call(this,t),r.map(i=>typeof i=="number"||typeof i=="bigint"||typeof i=="string"?this.pure.u64(i):lt(this,et,ru).call(this,i)));return lt(this,et,eu).call(this,n),Ad(Z(this,ue).commands.length-1,r.length)}mergeCoins(t,r){return this.add(Li.MergeCoins(this.object(t),r.map(n=>this.object(n))))}publish({modules:t,dependencies:r}){return this.add(Li.Publish({modules:t,dependencies:r}))}upgrade({modules:t,dependencies:r,package:n,ticket:i}){return this.add(Li.Upgrade({modules:t,dependencies:r,package:n,ticket:this.object(i)}))}moveCall({arguments:t,...r}){return this.add(Li.MoveCall({...r,arguments:t==null?void 0:t.map(n=>lt(this,et,ru).call(this,n))}))}transferObjects(t,r){return this.add(Li.TransferObjects(t.map(n=>this.object(n)),typeof r=="string"?this.pure.address(r):lt(this,et,ru).call(this,r)))}makeMoveVec({type:t,elements:r}){return this.add(Li.MakeMoveVec({type:t,elements:r.map(n=>this.object(n))}))}serialize(){return JSON.stringify(Tb(Z(this,ue).snapshot()))}async toJSON(t={}){await this.prepareForSerialization(t);const r=this.isFullyResolved();return JSON.stringify(qe(d9,r?{...Z(this,ue).snapshot(),digest:Z(this,ue).getDigest()}:Z(this,ue).snapshot()),(n,i)=>typeof i=="bigint"?i.toString():i,2)}async sign(t){const{signer:r,...n}=t,i=await this.build(n);return r.signTransaction(i)}isFullyResolved(){return!(!Z(this,ue).sender||Z(this,Ur).size>0||Z(this,ue).commands.some(t=>t.$Intent)||O5(Z(this,ue),{}))}async build(t={}){return await this.prepareForSerialization(t),await lt(this,et,Lh).call(this,t),Z(this,ue).build({onlyTransactionKind:t.onlyTransactionKind})}async getDigest(t={}){return await this.prepareForSerialization(t),await lt(this,et,Lh).call(this,t),Z(this,ue).getDigest()}async prepareForSerialization(t){var i;await lt(this,et,$5).call(this),lt(this,et,M5).call(this);const r=new Set;for(const s of Z(this,ue).commands)s.$Intent&&r.add(s.$Intent.name);const n=[...Z(this,Ji)];for(const s of r)if(!((i=t.supportedIntents)!=null&&i.includes(s))){if(!Z(this,Cn).has(s))throw new Error(`Missing intent resolver for ${s}`);n.push(Z(this,Cn).get(s))}n.push(nC()),await lt(this,et,Ip).call(this,n,t)}};Ji=new WeakMap;ns=new WeakMap;Cn=new WeakMap;ln=new WeakMap;sr=new WeakMap;ar=new WeakMap;Ur=new WeakMap;yi=new WeakMap;ue=new WeakMap;et=new WeakSet;F5=function(){const e=new L5;return Ce(e,ue,Z(this,ue)),Ce(e,Ji,Z(this,Ji)),Ce(e,ns,Z(this,ns)),Ce(e,Cn,Z(this,Cn)),Ce(e,Ur,Z(this,Ur)),Ce(e,ar,new Set(Z(this,ar))),Ce(e,yi,Z(this,yi)),Z(this,ln).push(Z(e,ln)),Z(this,sr).push(Z(e,sr)),e};eu=function(e){const t=Z(this,ue).commands.length;return Z(this,sr).push(e),Z(this,ar).add(t),Z(this,ue).commands.push(e),Z(this,ue).mapCommandArguments(t,r=>{if(r.$kind==="Result"&&!Z(this,ar).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,ar).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,ue).inputs.length)throw new Error(`Input { Input: ${r.Input} } references an input that does not exist in the current transaction`);return r}),e};tu=function(e,t){return Z(this,ln).push(t),Z(this,ue).addInput(e,t)};ru=function(e){return gp(e)?this.pure(e):lt(this,et,xu).call(this,e)};xu=function(e){if(typeof e=="function"){const t=this.add(e);return typeof t=="function"?lt(this,et,xu).call(this,t):qe(He,t)}return qe(He,e)};Lh=async function(e){if(!e.onlyTransactionKind&&!Z(this,ue).sender)throw new Error("Missing transaction sender");await lt(this,et,Ip).call(this,[...Z(this,ns),V9],e)};Ip=async function(e,t){try{const r=n=>{if(n>=e.length)return()=>{};const i=e[n];return async()=>{const s=r(n+1);let a=!1,o=!1;if(await i(Z(this,ue),t,async()=>{if(a)throw new Error(`next() was call multiple times in TransactionPlugin ${n}`);a=!0,await s(),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{Ce(this,ln,Z(this,ue).inputs.slice()),Ce(this,sr,Z(this,ue).commands.slice()),Ce(this,ar,new Set(Z(this,sr).map((r,n)=>n)))}};$5=async function(){for(;Z(this,Ur).size>0;){const e=Promise.all(Z(this,Ur));Z(this,Ur).clear(),Z(this,Ur).add(e),await e,Z(this,Ur).delete(e)}};M5=function(){var a;const e=Z(this,ue).commands,t=Z(this,ue).inputs,r=Z(this,sr).flat(1/0),n=Z(this,ln).flat(1/0);if(r.length!==e.length)throw new Error("Unexpected number of commands found in transaction data");if(n.length!==t.length)throw new Error("Unexpected number of inputs found in transaction data");const i=r.filter(o=>{var c;return((c=o.$Intent)==null?void 0:c.name)!=="AsyncTransactionThunk"});Z(this,ue).commands=i,Z(this,ue).inputs=n,Ce(this,sr,i),Ce(this,ln,n),Ce(this,ar,new Set(i.map((o,c)=>c)));function s(o){var f;const c=e[o];if(((f=c.$Intent)==null?void 0:f.name)==="AsyncTransactionThunk"){const l=c.$Intent.data.result;if(l==null)throw new Error("AsyncTransactionThunk has not been resolved");return s(l.Result)}const u=i.indexOf(c);if(u===-1)throw new Error("Unable to find original index for command");return u}Z(this,ue).mapArguments(o=>{if(o.$kind==="Input"){const c=n.indexOf(t[o.Input]);if(c===-1)throw new Error("Input has not been resolved");return{...o,Input:c}}else if(o.$kind==="Result"){const c=s(o.Result);return{...o,Result:c}}else if(o.$kind==="NestedResult"){const c=s(o.NestedResult[0]);return{...o,NestedResult:[c,o.NestedResult[1]]}}return o});for(const[o,c]of e.entries())if(((a=c.$Intent)==null?void 0:a.name)==="AsyncTransactionThunk")try{c.$Intent.data.resultIndex=s(o)}catch{}};let zh=L5;const sC={mainnet:"https://mainnet.mvr.mystenlabs.com",testnet:"https://testnet.mvr.mystenlabs.com"};class aC extends K6{constructor(t){var r,n,i;super(t),this.core=this,this.mvr=new Q9({cache:this.cache.scope("core.mvr"),url:((r=t.mvr)==null?void 0:r.url)??sC[this.network],pageSize:(n=t.mvr)==null?void 0:n.pageSize,overrides:(i=t.mvr)==null?void 0:i.overrides})}async getObject(t){const{objectId:r}=t,{objects:[n]}=await this.getObjects({objectIds:[r],signal:t.signal});if(n instanceof Error)throw n;return{object:n}}async getDynamicField(t){const r=Nr.parseFromStr((await this.core.mvr.resolveType({type:t.name.type})).type),n=x9(t.parentId,r,t.name.bcs),{objects:[i]}=await this.getObjects({objectIds:[n],signal:t.signal});if(i instanceof Error)throw i;const s=ys(i.type),a=await i.content;return{dynamicField:{id:i.id,digest:i.digest,version:i.version,type:i.type,previousTransaction:i.previousTransaction,name:{type:typeof s.typeParams[0]=="string"?s.typeParams[0]:vu(s.typeParams[0]),bcs:t.name.bcs},value:{type:typeof s.typeParams[1]=="string"?s.typeParams[1]:vu(s.typeParams[1]),bcs:a.slice(If+t.name.bcs.length)}}}}async waitForTransaction({signal:t,timeout:r=60*1e3,...n}){const i=t?AbortSignal.any([AbortSignal.timeout(r),t]):AbortSignal.timeout(r),s=new Promise((a,o)=>{i.addEventListener("abort",()=>o(i.reason))});for(s.catch(()=>{});;){i.throwIfAborted();try{return await this.getTransaction({...n,signal:i})}catch{await Promise.race([new Promise(a=>setTimeout(a,2e3)),s])}}}}class oC extends Error{}class mi extends oC{constructor(t,r){super(r),this.code=t}static fromResponse(t,r){switch(t.code){case"notExists":return new mi(t.code,`Object ${t.object_id} does not exist`);case"dynamicFieldNotFound":return new mi(t.code,`Dynamic field not found for object ${t.parent_object_id}`);case"deleted":return new mi(t.code,`Object ${t.object_id} has been deleted`);case"displayError":return new mi(t.code,`Display error: ${t.error}`);case"unknown":default:return new mi(t.code,`Unknown error while loading object${r?` ${r}`:""}`)}}}function cC(e){return{...Kt.fromBytes(e).snapshot(),bcs:e}}function uC(e){const t=ye.TransactionEffects.parse(e);switch(t.$kind){case"V1":return fC({effects:t.V1});case"V2":return lC({bytes:e,effects:t.V2});default:throw new Error(`Unknown transaction effects version: ${t.$kind}`)}}function fC(e){throw new Error("V1 effects are not supported yet")}function lC({bytes:e,effects:t}){const r=t.changedObjects.map(([n,i])=>{var s,a,o,c,u,f;return{id:n,inputState:i.inputState.$kind==="Exist"?"Exists":"DoesNotExist",inputVersion:((s=i.inputState.Exist)==null?void 0:s[0][0])??null,inputDigest:((a=i.inputState.Exist)==null?void 0:a[0][1])??null,inputOwner:((o=i.inputState.Exist)==null?void 0:o[1])??null,outputState:i.outputState.$kind==="NotExist"?"DoesNotExist":i.outputState.$kind,outputVersion:i.outputState.$kind==="PackageWrite"?(c=i.outputState.PackageWrite)==null?void 0:c[0]:i.outputState.ObjectWrite?t.lamportVersion:null,outputDigest:i.outputState.$kind==="PackageWrite"?(u=i.outputState.PackageWrite)==null?void 0:u[1]:((f=i.outputState.ObjectWrite)==null?void 0:f[0])??null,outputOwner:i.outputState.ObjectWrite?i.outputState.ObjectWrite[1]:null,idOperation:i.idOperation.$kind}});return{bcs:e,digest:t.transactionDigest,version:2,status:t.status.$kind==="Success"?{success:!0,error:null}:{success:!1,error:t.status.Failed.error.$kind},gasUsed:t.gasUsed,transactionDigest:t.transactionDigest,gasObject:t.gasObjectIndex===null?null:r[t.gasObjectIndex]??null,eventsDigest:t.eventsDigest,dependencies:t.dependencies,lamportVersion:t.lamportVersion,changedObjects:r,unchangedConsensusObjects:t.unchangedSharedObjects.map(([n,i])=>({kind:i.$kind==="MutateDeleted"?"MutateConsensusStreamEnded":i.$kind==="ReadDeleted"?"ReadConsensusStreamEnded":i.$kind,objectId:n,version:i.$kind==="ReadOnlyRoot"?i.ReadOnlyRoot[0]:i[i.$kind],digest:i.$kind==="ReadOnlyRoot"?i.ReadOnlyRoot[1]:null})),auxiliaryDataDigest:t.auxDataDigest}}var D5=e=>{throw TypeError(e)},z5=(e,t,r)=>t.has(e)||D5("Cannot "+r),qt=(e,t,r)=>(z5(e,t,"read from private field"),r?r.call(e):t.get(e)),dC=(e,t,r)=>t.has(e)?D5("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),hC=(e,t,r,n)=>(z5(e,t,"write to private field"),t.set(e,r),r),gt;class pC extends aC{constructor({jsonRpcClient:t,mvr:r}){super({network:t.network,base:t,mvr:r}),dC(this,gt),hC(this,gt,t)}async getObjects(t){const r=Sf(t.objectIds,50),n=[];for(const i of r){const s=await qt(this,gt).multiGetObjects({ids:i,options:{showOwner:!0,showType:!0,showBcs:!0,showPreviousTransaction:!0},signal:t.signal});for(const[a,o]of s.entries())o.error?n.push(mi.fromResponse(o.error,i[a])):n.push(Cb(o.data))}return{objects:n}}async getOwnedObjects(t){const r=await qt(this,gt).getOwnedObjects({owner:t.address,limit:t.limit,cursor:t.cursor,options:{showOwner:!0,showType:!0,showBcs:!0,showPreviousTransaction:!0},filter:t.type?{StructType:t.type}:null,signal:t.signal});return{objects:r.data.map(n=>{if(n.error)throw mi.fromResponse(n.error);return Cb(n.data)}),hasNextPage:r.hasNextPage,cursor:r.nextCursor??null}}async getCoins(t){const r=await qt(this,gt).getCoins({owner:t.address,coinType:t.coinType,limit:t.limit,cursor:t.cursor,signal:t.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(bC.serialize({id:n.coinObjectId,balance:{value:n.balance}}).toBytes()),owner:{$kind:"ObjectOwner",ObjectOwner:t.address},previousTransaction:n.previousTransaction})),hasNextPage:r.hasNextPage,cursor:r.nextCursor??null}}async getBalance(t){const r=await qt(this,gt).getBalance({owner:t.address,coinType:t.coinType,signal:t.signal});return{balance:{coinType:r.coinType,balance:r.totalBalance}}}async getAllBalances(t){return{balances:(await qt(this,gt).getAllBalances({owner:t.address,signal:t.signal})).map(n=>({coinType:n.coinType,balance:n.totalBalance})),hasNextPage:!1,cursor:null}}async getTransaction(t){const r=await qt(this,gt).getTransactionBlock({digest:t.digest,options:{showRawInput:!0,showObjectChanges:!0,showRawEffects:!0,showEvents:!0,showEffects:!0,showBalanceChanges:!0},signal:t.signal});return{transaction:Rb(r)}}async executeTransaction(t){const r=await qt(this,gt).executeTransactionBlock({transactionBlock:t.transaction,signature:t.signatures,options:{showRawEffects:!0,showEvents:!0,showObjectChanges:!0,showRawInput:!0,showEffects:!0,showBalanceChanges:!0},signal:t.signal});return{transaction:Rb(r)}}async dryRunTransaction(t){const r=zh.from(t.transaction),n=await qt(this,gt).dryRunTransactionBlock({transactionBlock:t.transaction,signal:t.signal}),{effects:i,objectTypes:s}=yC({effects:n.effects,objectChanges:n.objectChanges});return{transaction:{digest:await r.getDigest(),epoch:null,effects:i,objectTypes:Promise.resolve(s),signatures:[],transaction:cC(t.transaction),balanceChanges:n.balanceChanges.map(a=>({coinType:a.coinType,address:V5(a.owner),amount:a.amount}))}}}async getReferenceGasPrice(t){const r=await qt(this,gt).getReferenceGasPrice({signal:t==null?void 0:t.signal});return{referenceGasPrice:String(r)}}async getDynamicFields(t){const r=await qt(this,gt).getDynamicFields({parentId:t.parentId,limit:t.limit,cursor:t.cursor});return{dynamicFields:r.data.map(n=>({id:n.objectId,type:n.objectType,name:{type:n.name.type,bcs:cr(n.bcsName)}})),hasNextPage:r.hasNextPage,cursor:r.nextCursor}}async verifyZkLoginSignature(t){const r=await qt(this,gt).verifyZkLoginSignature({bytes:t.bytes,signature:t.signature,intentScope:t.intentScope,author:t.author});return{success:r.success,errors:r.errors}}async defaultNameServiceName(t){return{data:{name:(await qt(this,gt).resolveNameServiceNames(t)).data[0]}}}resolveTransactionPlugin(){return P5(qt(this,gt))}async getMoveFunction(t){const r=await qt(this,gt).getNormalizedMoveFunction({package:(await this.mvr.resolvePackage({package:t.packageId})).package,module:t.moduleName,function:t.name});return{function:{packageId:xe(t.packageId),moduleName:t.moduleName,name:t.name,visibility:wC(r.visibility),isEntry:r.isEntry,typeParameters:r.typeParameters.map(n=>({isPhantom:!1,constraints:gC(n)})),parameters:r.parameters.map(n=>Nb(n)),returns:r.return.map(n=>Nb(n))}}}}gt=new WeakMap;function Cb(e){var t;return{id:e.objectId,version:e.version,digest:e.digest,type:e.type,content:Promise.resolve(((t=e.bcs)==null?void 0:t.dataType)==="moveObject"?cr(e.bcs.bcsBytes):new Uint8Array),owner:Fs(e.owner),previousTransaction:e.previousTransaction??null}}function Fs(e){if(e==="Immutable")return{$kind:"Immutable",Immutable:!0};if("ConsensusAddressOwner"in e)return{$kind:"ConsensusAddressOwner",ConsensusAddressOwner:{owner:e.ConsensusAddressOwner.owner,startVersion:e.ConsensusAddressOwner.start_version}};if("AddressOwner"in e)return{$kind:"AddressOwner",AddressOwner:e.AddressOwner};if("ObjectOwner"in e)return{$kind:"ObjectOwner",ObjectOwner:e.ObjectOwner};if("Shared"in e)return{$kind:"Shared",Shared:{initialSharedVersion:e.Shared.initial_shared_version}};throw new Error(`Unknown owner type: ${JSON.stringify(e)}`)}function V5(e){if(e==="Immutable")return null;if("ConsensusAddressOwner"in e)return e.ConsensusAddressOwner.owner;if("AddressOwner"in e)return e.AddressOwner;if("ObjectOwner"in e)return e.ObjectOwner;if("Shared"in e)return null;throw new Error(`Unknown owner type: ${JSON.stringify(e)}`)}function Rb(e){var s,a,o;const t=ye.SenderSignedData.parse(cr(e.rawTransaction))[0],r={};(s=e.objectChanges)==null||s.forEach(c=>{c.type!=="published"&&(r[c.objectId]=c.objectType)});const n=ye.TransactionData.serialize(t.intentMessage.value).toBytes(),i=Kt.restore({version:2,sender:t.intentMessage.value.V1.sender,expiration:t.intentMessage.value.V1.expiration,gasData:t.intentMessage.value.V1.gasData,inputs:t.intentMessage.value.V1.kind.ProgrammableTransaction.inputs,commands:t.intentMessage.value.V1.kind.ProgrammableTransaction.commands});return{digest:e.digest,epoch:((a=e.effects)==null?void 0:a.executedEpoch)??null,effects:uC(new Uint8Array(e.rawEffects)),objectTypes:Promise.resolve(r),transaction:{...i,bcs:n},signatures:t.txSignatures,balanceChanges:((o=e.balanceChanges)==null?void 0:o.map(c=>({coinType:c.coinType,address:V5(c.owner),amount:c.amount})))??[]}}function yC({bytes:e,effects:t,objectChanges:r}){var a;const n=[],i=[],s={};return r==null||r.forEach(o=>{var c,u,f,l;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:Fs(o.recipient),idOperation:"None"}),s[o.objectId]=o.objectType;break;case"mutated":n.push({id:o.objectId,inputState:"Exists",inputVersion:o.previousVersion,inputDigest:null,inputOwner:Fs(o.owner),outputState:"ObjectWrite",outputVersion:o.version,outputDigest:o.digest,outputOwner:Fs(o.owner),idOperation:"None"}),s[o.objectId]=o.objectType;break;case"deleted":n.push({id:o.objectId,inputState:"Exists",inputVersion:o.version,inputDigest:((u=(c=t.deleted)==null?void 0:c.find(h=>h.objectId===o.objectId))==null?void 0:u.digest)??null,inputOwner:null,outputState:"DoesNotExist",outputVersion:null,outputDigest:null,outputOwner:null,idOperation:"Deleted"}),s[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:((l=(f=t.wrapped)==null?void 0:f.find(h=>h.objectId===o.objectId))==null?void 0:l.digest)??null,outputOwner:{$kind:"ObjectOwner",ObjectOwner:o.sender},idOperation:"None"}),s[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:Fs(o.owner),idOperation:"Created"}),s[o.objectId]=o.objectType;break}}),{objectTypes:s,effects:{bcs:e??null,digest:t.transactionDigest,version:2,status:t.status.status==="success"?{success:!0,error:null}:{success:!1,error:t.status.error},gasUsed:t.gasUsed,transactionDigest:t.transactionDigest,gasObject:{id:(a=t.gasObject)==null?void 0:a.reference.objectId,inputState:"Exists",inputVersion:null,inputDigest:null,inputOwner:null,outputState:"ObjectWrite",outputVersion:t.gasObject.reference.version,outputDigest:t.gasObject.reference.digest,outputOwner:Fs(t.gasObject.owner),idOperation:"None"},eventsDigest:t.eventsDigest??null,dependencies:t.dependencies??[],lamportVersion:t.gasObject.reference.version,changedObjects:n,unchangedConsensusObjects:i,auxiliaryDataDigest:null}}}const mC=ye.struct("Balance",{value:ye.u64()}),bC=ye.struct("Coin",{id:ye.Address,balance:mC});function Nb(e){if(typeof e!="string"){if("Reference"in e)return{reference:"immutable",body:eo(e.Reference)};if("MutableReference"in e)return{reference:"mutable",body:eo(e.MutableReference)}}return{reference:null,body:eo(e)}}function eo(e){switch(e){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 e=="string")throw new Error(`Unknown type: ${e}`);if("Vector"in e)return{$kind:"vector",vector:eo(e.Vector)};if("Struct"in e)return{$kind:"datatype",datatype:{typeName:`${xe(e.Struct.address)}::${e.Struct.module}::${e.Struct.name}`,typeParameters:e.Struct.typeArguments.map(t=>eo(t))}};if("TypeParameter"in e)return{$kind:"typeParameter",index:e.TypeParameter};throw new Error(`Unknown type: ${JSON.stringify(e)}`)}function gC(e){return e.abilities.map(t=>{switch(t){case"Copy":return"copy";case"Drop":return"drop";case"Store":return"store";case"Key":return"key";default:return"unknown"}})}function wC(e){switch(e){case"Public":return"public";case"Private":return"private";case"Friend":return"friend";default:return"unknown"}}const vC=Symbol.for("@mysten/SuiClient");class Ub extends K6{constructor(t){super({network:t.network??"unknown"}),this.jsonRpc=this,this.transport=t.transport??new CO({url:t.url}),this.core=new pC({jsonRpcClient:this,mvr:t.mvr})}get[vC](){return!0}async getRpcApiVersion({signal:t}={}){return(await this.transport.request({method:"rpc.discover",params:[],signal:t})).info.version}async getCoins({coinType:t,owner:r,cursor:n,limit:i,signal:s}){if(!r||!Rr(xe(r)))throw new Error("Invalid Sui address");return t&&Pt(t)&&(t=(await this.core.mvr.resolveType({type:t})).type),await this.transport.request({method:"suix_getCoins",params:[r,t,n,i],signal:s})}async getAllCoins(t){if(!t.owner||!Rr(xe(t.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getAllCoins",params:[t.owner,t.cursor,t.limit],signal:t.signal})}async getBalance({owner:t,coinType:r,signal:n}){if(!t||!Rr(xe(t)))throw new Error("Invalid Sui address");return r&&Pt(r)&&(r=(await this.core.mvr.resolveType({type:r})).type),await this.transport.request({method:"suix_getBalance",params:[t,r],signal:n})}async getAllBalances(t){if(!t.owner||!Rr(xe(t.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getAllBalances",params:[t.owner],signal:t.signal})}async getCoinMetadata({coinType:t,signal:r}){return t&&Pt(t)&&(t=(await this.core.mvr.resolveType({type:t})).type),await this.transport.request({method:"suix_getCoinMetadata",params:[t],signal:r})}async getTotalSupply({coinType:t,signal:r}){return t&&Pt(t)&&(t=(await this.core.mvr.resolveType({type:t})).type),await this.transport.request({method:"suix_getTotalSupply",params:[t],signal:r})}async call(t,r,{signal:n}={}){return await this.transport.request({method:t,params:r,signal:n})}async getMoveFunctionArgTypes({package:t,module:r,function:n,signal:i}){return t&&nr(t)&&(t=(await this.core.mvr.resolvePackage({package:t})).package),await this.transport.request({method:"sui_getMoveFunctionArgTypes",params:[t,r,n],signal:i})}async getNormalizedMoveModulesByPackage({package:t,signal:r}){return t&&nr(t)&&(t=(await this.core.mvr.resolvePackage({package:t})).package),await this.transport.request({method:"sui_getNormalizedMoveModulesByPackage",params:[t],signal:r})}async getNormalizedMoveModule({package:t,module:r,signal:n}){return t&&nr(t)&&(t=(await this.core.mvr.resolvePackage({package:t})).package),await this.transport.request({method:"sui_getNormalizedMoveModule",params:[t,r],signal:n})}async getNormalizedMoveFunction({package:t,module:r,function:n,signal:i}){return t&&nr(t)&&(t=(await this.core.mvr.resolvePackage({package:t})).package),await this.transport.request({method:"sui_getNormalizedMoveFunction",params:[t,r,n],signal:i})}async getNormalizedMoveStruct({package:t,module:r,struct:n,signal:i}){return t&&nr(t)&&(t=(await this.core.mvr.resolvePackage({package:t})).package),await this.transport.request({method:"sui_getNormalizedMoveStruct",params:[t,r,n],signal:i})}async getOwnedObjects(t){if(!t.owner||!Rr(xe(t.owner)))throw new Error("Invalid Sui address");const r=t.filter?{...t.filter}:void 0;return r&&"MoveModule"in r&&nr(r.MoveModule.package)?r.MoveModule={module:r.MoveModule.module,package:(await this.core.mvr.resolvePackage({package:r.MoveModule.package})).package}:r&&"StructType"in r&&Pt(r.StructType)&&(r.StructType=(await this.core.mvr.resolveType({type:r.StructType})).type),await this.transport.request({method:"suix_getOwnedObjects",params:[t.owner,{filter:r,options:t.options},t.cursor,t.limit],signal:t.signal})}async getObject(t){if(!t.id||!Lc(fn(t.id)))throw new Error("Invalid Sui Object id");return await this.transport.request({method:"sui_getObject",params:[t.id,t.options],signal:t.signal})}async tryGetPastObject(t){return await this.transport.request({method:"sui_tryGetPastObject",params:[t.id,t.version,t.options],signal:t.signal})}async multiGetObjects(t){if(t.ids.forEach(n=>{if(!n||!Lc(fn(n)))throw new Error(`Invalid Sui Object id ${n}`)}),t.ids.length!==new Set(t.ids).size)throw new Error(`Duplicate object ids in batch call ${t.ids}`);return await this.transport.request({method:"sui_multiGetObjects",params:[t.ids,t.options],signal:t.signal})}async queryTransactionBlocks({filter:t,options:r,cursor:n,limit:i,order:s,signal:a}){return t&&"MoveFunction"in t&&nr(t.MoveFunction.package)&&(t={...t,MoveFunction:{package:(await this.core.mvr.resolvePackage({package:t.MoveFunction.package})).package}}),await this.transport.request({method:"suix_queryTransactionBlocks",params:[{filter:t,options:r},n,i,(s||"descending")==="descending"],signal:a})}async getTransactionBlock(t){if(!Eb(t.digest))throw new Error("Invalid Transaction digest");return await this.transport.request({method:"sui_getTransactionBlock",params:[t.digest,t.options],signal:t.signal})}async multiGetTransactionBlocks(t){if(t.digests.forEach(n=>{if(!Eb(n))throw new Error(`Invalid Transaction digest ${n}`)}),t.digests.length!==new Set(t.digests).size)throw new Error(`Duplicate digests in batch call ${t.digests}`);return await this.transport.request({method:"sui_multiGetTransactionBlocks",params:[t.digests,t.options],signal:t.signal})}async executeTransactionBlock({transactionBlock:t,signature:r,options:n,requestType:i,signal:s}){const a=await this.transport.request({method:"sui_executeTransactionBlock",params:[typeof t=="string"?t:Bt(t),Array.isArray(r)?r:[r],n],signal:s});if(i==="WaitForLocalExecution")try{await this.waitForTransaction({digest:a.digest})}catch{}return a}async signAndExecuteTransaction({transaction:t,signer:r,...n}){let i;t instanceof Uint8Array?i=t:(t.setSenderIfNotSet(r.toSuiAddress()),i=await t.build({client:this}));const{signature:s,bytes:a}=await r.signTransaction(i);return this.executeTransactionBlock({transactionBlock:a,signature:s,...n})}async getTotalTransactionBlocks({signal:t}={}){const r=await this.transport.request({method:"sui_getTotalTransactionBlocks",params:[],signal:t});return BigInt(r)}async getReferenceGasPrice({signal:t}={}){const r=await this.transport.request({method:"suix_getReferenceGasPrice",params:[],signal:t});return BigInt(r)}async getStakes(t){if(!t.owner||!Rr(xe(t.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getStakes",params:[t.owner],signal:t.signal})}async getStakesByIds(t){return t.stakedSuiIds.forEach(r=>{if(!r||!Lc(fn(r)))throw new Error(`Invalid Sui Stake id ${r}`)}),await this.transport.request({method:"suix_getStakesByIds",params:[t.stakedSuiIds],signal:t.signal})}async getLatestSuiSystemState({signal:t}={}){return await this.transport.request({method:"suix_getLatestSuiSystemState",params:[],signal:t})}async queryEvents({query:t,cursor:r,limit:n,order:i,signal:s}){return t&&"MoveEventType"in t&&Pt(t.MoveEventType)&&(t={...t,MoveEventType:(await this.core.mvr.resolveType({type:t.MoveEventType})).type}),t&&"MoveEventModule"in t&&nr(t.MoveEventModule.package)&&(t={...t,MoveEventModule:{module:t.MoveEventModule.module,package:(await this.core.mvr.resolvePackage({package:t.MoveEventModule.package})).package}}),"MoveModule"in t&&nr(t.MoveModule.package)&&(t={...t,MoveModule:{module:t.MoveModule.module,package:(await this.core.mvr.resolvePackage({package:t.MoveModule.package})).package}}),await this.transport.request({method:"suix_queryEvents",params:[t,r,n,(i||"descending")==="descending"],signal:s})}async subscribeEvent(t){return this.transport.subscribe({method:"suix_subscribeEvent",unsubscribe:"suix_unsubscribeEvent",params:[t.filter],onMessage:t.onMessage,signal:t.signal})}async subscribeTransaction(t){return this.transport.subscribe({method:"suix_subscribeTransaction",unsubscribe:"suix_unsubscribeTransaction",params:[t.filter],onMessage:t.onMessage,signal:t.signal})}async devInspectTransactionBlock(t){var n,i;let r;if(H5(t.transactionBlock))t.transactionBlock.setSenderIfNotSet(t.sender),r=Bt(await t.transactionBlock.build({client:this,onlyTransactionKind:!0}));else if(typeof t.transactionBlock=="string")r=t.transactionBlock;else if(t.transactionBlock instanceof Uint8Array)r=Bt(t.transactionBlock);else throw new Error("Unknown transaction block format.");return(n=t.signal)==null||n.throwIfAborted(),await this.transport.request({method:"sui_devInspectTransactionBlock",params:[t.sender,r,(i=t.gasPrice)==null?void 0:i.toString(),t.epoch],signal:t.signal})}async dryRunTransactionBlock(t){return await this.transport.request({method:"sui_dryRunTransactionBlock",params:[typeof t.transactionBlock=="string"?t.transactionBlock:Bt(t.transactionBlock)]})}async getDynamicFields(t){if(!t.parentId||!Lc(fn(t.parentId)))throw new Error("Invalid Sui Object id");return await this.transport.request({method:"suix_getDynamicFields",params:[t.parentId,t.cursor,t.limit],signal:t.signal})}async getDynamicFieldObject(t){return await this.transport.request({method:"suix_getDynamicFieldObject",params:[t.parentId,t.name],signal:t.signal})}async getLatestCheckpointSequenceNumber({signal:t}={}){const r=await this.transport.request({method:"sui_getLatestCheckpointSequenceNumber",params:[],signal:t});return String(r)}async getCheckpoint(t){return await this.transport.request({method:"sui_getCheckpoint",params:[t.id],signal:t.signal})}async getCheckpoints(t){return await this.transport.request({method:"sui_getCheckpoints",params:[t.cursor,t==null?void 0:t.limit,t.descendingOrder],signal:t.signal})}async getCommitteeInfo(t){return await this.transport.request({method:"suix_getCommitteeInfo",params:[t==null?void 0:t.epoch],signal:t==null?void 0:t.signal})}async getNetworkMetrics({signal:t}={}){return await this.transport.request({method:"suix_getNetworkMetrics",params:[],signal:t})}async getAddressMetrics({signal:t}={}){return await this.transport.request({method:"suix_getLatestAddressMetrics",params:[],signal:t})}async getEpochMetrics(t){return await this.transport.request({method:"suix_getEpochMetrics",params:[t==null?void 0:t.cursor,t==null?void 0:t.limit,t==null?void 0:t.descendingOrder],signal:t==null?void 0:t.signal})}async getAllEpochAddressMetrics(t){return await this.transport.request({method:"suix_getAllEpochAddressMetrics",params:[t==null?void 0:t.descendingOrder],signal:t==null?void 0:t.signal})}async getEpochs(t){return await this.transport.request({method:"suix_getEpochs",params:[t==null?void 0:t.cursor,t==null?void 0:t.limit,t==null?void 0:t.descendingOrder],signal:t==null?void 0:t.signal})}async getMoveCallMetrics({signal:t}={}){return await this.transport.request({method:"suix_getMoveCallMetrics",params:[],signal:t})}async getCurrentEpoch({signal:t}={}){return await this.transport.request({method:"suix_getCurrentEpoch",params:[],signal:t})}async getValidatorsApy({signal:t}={}){return await this.transport.request({method:"suix_getValidatorsApy",params:[],signal:t})}async getChainIdentifier({signal:t}={}){const r=await this.getCheckpoint({id:"0",signal:t}),n=Ro(r.digest);return oa(n.slice(0,4))}async resolveNameServiceAddress(t){return await this.transport.request({method:"suix_resolveNameServiceAddress",params:[t.name],signal:t.signal})}async resolveNameServiceNames({format:t="dot",...r}){const{nextCursor:n,hasNextPage:i,data:s}=await this.transport.request({method:"suix_resolveNameServiceNames",params:[r.address,r.cursor,r.limit],signal:r.signal});return{hasNextPage:i,nextCursor:n,data:s.map(a=>EB(a,t))}}async getProtocolConfig(t){return await this.transport.request({method:"sui_getProtocolConfig",params:[t==null?void 0:t.version],signal:t==null?void 0:t.signal})}async verifyZkLoginSignature(t){return await this.transport.request({method:"sui_verifyZkLoginSignature",params:[t.bytes,t.signature,t.intentScope,t.author],signal:t.signal})}async waitForTransaction({signal:t,timeout:r=60*1e3,pollInterval:n=2*1e3,...i}){const s=AbortSignal.timeout(r),a=new Promise((o,c)=>{s.addEventListener("abort",()=>c(s.reason))});for(a.catch(()=>{});!s.aborted;){t==null||t.throwIfAborted();try{return await this.getTransactionBlock(i)}catch{await Promise.race([new Promise(o=>setTimeout(o,n)),a])}}throw s.throwIfAborted(),new Error("Unexpected error while waiting for transaction block.")}}class EC{constructor(t,r,n,i){this.client=new Ub({url:mb(n)}),this.url=t instanceof m.Url?t:new m.Url(t),this.account=r,this.network=n,this.auth=i,this.relayer=new xs(this.auth,this.url)}get htlcActorAddress(){var t,r;return"accounts"in this.account?((r=(t=this.account.accounts)==null?void 0:t[0])==null?void 0:r.address)??"":this.account.toSuiAddress()}async initiate(t){var r,n,i;if(!t)return m.Err("Order is required");if(D.isSuiOrderResponse(t))return this.initiateWithCreateOrderResponse(t);try{const{source_swap:s}=t,a=BigInt(s.amount),o=s.asset,c=s.redeemer,u=s.secret_hash,f=await Ys(s.asset,this.url,this.auth);if(!f.ok)return m.Err(f.error);const{tokenAddress:l}=f.val,h=new zh;h.setSender(this.htlcActorAddress);const[d]=h.splitCoins(h.gas,[a]);h.moveCall({target:`${Od[this.network].packageId}::${Od[this.network].moduleName}::initiate`,typeArguments:[l],arguments:[h.object(o),h.pure.address(this.htlcActorAddress),h.pure.address(c),h.pure.vector("u8",Buffer.from(u,"hex")),h.pure.u64(a),h.pure.u256(s.timelock),h.pure.vector("u8",Buffer.from("")),d,h.object(y9)]});const b=await h.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 x;if("features"in this.account?x=await((r=this.account.features[Bp.SuiSignAndExecuteTransaction])==null?void 0:r.signAndExecuteTransaction({transaction:h,account:this.account.accounts[0],chain:`sui:${this.network}`})):x=await this.client.signAndExecuteTransaction({signer:this.account,transaction:h,options:{showEffects:!0}}),!x)return m.Err("Failed to initiate");const A=await this.client.waitForTransaction({digest:x.digest,options:{showEffects:!0}});return((n=A.effects)==null?void 0:n.status.status)==="failure"?m.Err(`Failed to initiate: ${(i=A.effects)==null?void 0:i.status.error}`):m.Ok(A.digest)}catch(s){return m.Err(s)}}async initiateWithCreateOrderResponse(t){var o,c,u;const{ptb_bytes:r}=t,i=await new Ub({url:mb("testnet")}).getReferenceGasPrice(),s=1e7,a=zh.fromKind(new Uint8Array(r));a.setSender(this.htlcActorAddress),a.setGasPrice(i),a.setGasBudget(s);try{let f;if("features"in this.account?f=await((o=this.account.features[Bp.SuiSignAndExecuteTransaction])==null?void 0:o.signAndExecuteTransaction({transaction:a,account:this.account.accounts[0],chain:`sui:${this.network}`})):f=await this.client.signAndExecuteTransaction({signer:this.account,transaction:a,options:{showEffects:!0}}),!f)return m.Err("Failed to initiate");const l=await this.client.waitForTransaction({digest:f.digest,options:{showEffects:!0}});return((c=l.effects)==null?void 0:c.status.status)==="failure"?m.Err(`Failed to initiate: ${(u=l.effects)==null?void 0:u.status.error}`):m.Ok(l.digest)}catch(f){return m.Err(String(f))}}async redeem(t,r){const n=await this.relayer.redeem(t.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 Fb(e){let t=e.startsWith("0x")?e.slice(2):e;return t=t.toLowerCase(),t.length>64&&(t=t.slice(t.length-64)),t.length<64&&(t=t.padStart(64,"0")),`0x${t}`}class xC{constructor(t,r,n,i){this.url=typeof t=="string"?new m.Url(t):t,this.auth=n,i instanceof Cp.TronWeb?(this.wallet={tronweb:i},this.tronweb=i):(this.wallet={adapter:i},this.tronweb=new Cp.TronWeb({fullHost:Lb[r]})),this.relayer=new xs(this.auth,this.url)}get htlcActorAddress(){var t,r,n;return(t=this.wallet.adapter)!=null&&t.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(t){if(D.isEvmOrderResponse(t))return this.initiateDirectContractCall(t);try{const{source_swap:r}=t,n=await Ys(r.asset,this.url,this.auth);if(!n.ok)return m.Err(n.error);const{htlcAddress:i}=n.val;return await this.executeContractCall({contractAddress:i,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:Fb(String(r.secret_hash))},{type:"bytes",value:"0x"}],options:{}})}catch(r){return m.Err(`Failed to initiate: ${String(r)}`)}}async initiateDirectContractCall(t){var l;if(!this.htlcActorAddress)return m.Err("No HTLC actor address found");if(t.approval_transaction){const h=await this.executeApprovalTransaction(t);if(h.error)return m.Err(h.error)}if(!t.initiate_transaction)return m.Err("No initiate transaction data available for direct contract call");if(!((l=t.typed_data)!=null&&l.message))return m.Err("No typed data message found in order response");const{to:r,value:n,gas_limit:i}=t.initiate_transaction,{redeemer:s,timelock:a,amount:o,secretHash:c,destinationData:u}=t.typed_data.message,f=await this.executeContractCall({contractAddress:r,method:"initiate(address,uint256,uint256,bytes32,bytes)",parameters:[{type:"address",value:s},{type:"uint256",value:a},{type:"uint256",value:o},{type:"bytes32",value:Fb(String(c))},{type:"bytes",value:u}],options:{feeLimit:parseInt(i),callValue:n?parseInt(n):0}});return!f.val||f.error?m.Err("Failed to initiate"+(f.error||"")):await this.waitForTransactionConfirmation(f.val)}async executeApprovalTransaction(t){if(console.log("No Allowance found, Executing Approval"),!this.htlcActorAddress)return m.Err("No HTLC actor address found");const r=t.approval_transaction;if(!r)return m.Ok("No approval transaction required");try{const n="0x"+r.data.slice(10),i=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:i.spender},{type:"uint256",value:i.amount.toString()}],options:{feeLimit:Number(r.gas_limit),callValue:0}})}catch(n){return m.Err(`Approval transaction failed: ${String(n)}`)}}async executeContractCall({contractAddress:t,method:r,parameters:n,options:i}){try{const s=await this.tronweb.transactionBuilder.triggerSmartContract(t,r,i,n,this.htlcActorAddress);if(!(s!=null&&s.transaction))return m.Err("Failed to build transaction");const a=await this.signTransaction(s.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(s){return m.Err(`Failed to execute contract call: ${String(s)}`)}}async broadcastWithRetry(t){for(let n=0;n<5;n++)try{const i=await this.tronweb.trx.sendRawTransaction(t);if(i.result&&i.txid)return m.Ok(i.txid);const s=typeof i.code=="string"?parseInt(i.code):i.code;if(this.isRetryableError(s)&&n<4){await this.sleep(Math.min(1e3*Math.pow(2,n),8e3));continue}const a=i.message||`Error code: ${i.code}`;return m.Err(String(a))}catch(i){if(n<4){await this.sleep(Math.min(1e3*Math.pow(2,n),8e3));continue}return m.Err(String(i))}return m.Err("Max broadcast retries exceeded")}isRetryableError(t){if(t===void 0)return!0;const r=typeof t=="string"?parseInt(t):t;return r===8||r===9||r===10||r===11||r===4}sleep(t){return new Promise(r=>setTimeout(r,t))}async signTransaction(t){if(this.wallet.adapter)try{const r=await this.wallet.adapter.signTransaction(t);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(t);return m.Ok(r)}catch(r){return m.Err(`TronWeb signing failed: ${String(r)}`)}return m.Err("No signing method available")}async waitForTransactionConfirmation(t,r=15,n=3e3){var i,s,a,o;for(let c=0;c<r;c++){try{const u=await this.tronweb.trx.getTransaction(t);if(!u){await this.sleep(n);continue}if(((s=(i=u.ret)==null?void 0:i[0])==null?void 0:s.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(t,r){const n=await this.relayer.redeem(t.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 AC=25*60*60*1e3;class G5{constructor(t,r,n,i){this.url=typeof t=="string"?new m.Url(t):t,this.auth=n,this.wallet=i,this.client=new Rp.Client(Db[r],{}),this.relayer=new xs(this.auth,this.url)}isXrplWallet(t){return typeof t=="object"&&t!==null&&"classicAddress"in t&&typeof t.classicAddress=="string"}isCrossmarkWallet(t){var r;return typeof t=="object"&&t!==null&&"sync"in t&&"async"in t&&typeof t.sync=="object"&&typeof((r=t.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(t){try{return D.isXrplOrderResponse(t)?this.initiateFromOrderResponse(t):this.initiateFromOrder(t)}catch(r){return m.Err(`Failed to initiate: ${String(r)}`)}}async initiateFromOrderResponse(t){try{if(!this.htlcActorAddress)return m.Err("No HTLC actor address found");const n=t.escrow_create_tx,i={TransactionType:"EscrowCreate",Account:n.Account,Amount:n.Amount,Destination:n.Destination,Condition:n.Condition,CancelAfter:n.CancelAfter};return await this.submitTransaction(i)}catch(r){return m.Err(`Failed to initiate from order response: ${String(r)}`)}}async initiateFromOrder(t){try{const r=this.htlcActorAddress;if(!r)return m.Err("No HTLC actor address found");const{source_swap:n}=t,i=m.trim0x(n.secret_hash),s={Account:r,Amount:n.amount,Destination:n.redeemer,Condition:this.buildCondition(i),CancelAfter:Rp.isoTimeToRippleTime(new Date(new Date(n.created_at).getTime()+AC)),TransactionType:"EscrowCreate"};return await this.submitTransaction(s)}catch(r){return m.Err(`Failed to initiate from order: ${String(r)}`)}}async redeem(t,r){const n=await this.relayer.redeem(t.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(t){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(t);n.Account=r;const i=await this.signPreparedTransaction(n),s=await this.client.submitAndWait(i),a=s.result.meta;return(a==null?void 0:a.TransactionResult)==="tesSUCCESS"?m.Ok(s.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(t){if(this.isXrplWallet(this.wallet))return this.wallet.sign(t).tx_blob;if(this.isCrossmarkWallet(this.wallet))return this.wallet.sync.getAddress()||await this.wallet.async.signInAndWait(),(await this.wallet.async.signAndWait(t)).response.data.txBlob;throw new Error("Unsupported wallet type")}buildCondition(t){return"A0258020"+t.toUpperCase()+"810120"}}const SC=e=>{if(e)if(typeof e=="string"){const t=m.DigestKey.from(e);if(!t.ok)throw new Error(t.error);return t.val}else return e},kd=e=>typeof e=="string"?new m.ApiKey(e):e;class Mo extends m.EventBroker{get isInitialized(){return!!this.digestKey}constructor(t,r){super(),this.digestKey=t,this.walletClient=r}static fromDigestKey(t){return new Mo(m.trim0x(t))}static fromWalletClient(t){return new Mo(void 0,t)}async initialize(){if(this.digestKey)return m.Ok("Already initialized");const t=await this.deriveDigestKeyFromWalletClient();return t.error?m.Err(t.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 t=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(Ha(t)),this.emit("initialized",!0),m.Ok(this.digestKey)}catch(t){return m.Err("Failed to initialize: "+t)}}async getDigestKey(){if(!this.digestKey&&!this.walletClient)return m.Err("No private key or wallet client found");if(!this.digestKey&&this.walletClient){const t=await this.deriveDigestKeyFromWalletClient();if(t.error)return m.Err(t.error)}return this.digestKey?m.Ok(this.digestKey):m.Err("No private key found")}async generateSecret(t){const r=await this.signMessage(t);if(!r.ok)return m.Err(r.error);const n=Ha(m.with0x(r.val)),i=Ha(n);return m.Ok({secret:n,secretHash:i})}async signMessage(t){if(!this.digestKey){const u=await this.getDigestKey();if(!u.ok)return m.Err(u.error);this.digestKey=u.val}const r=zc.ECPairFactory(xr),n="Garden.fi"+t.toString(),i=Buffer.from(n,"utf8"),s=Ha(i),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(s),"hex"));return m.Ok(c.toString("hex"))}}class kC{constructor(t={}){const r={stdTTL:t.ttl?t.ttl/1e3:3600,checkperiod:600};this.cache=new Z5(r)}makeKey(t,r){return`${t}:${r}`}set(t,r,n,i){const s=this.makeKey(t,r);i?this.cache.set(s,n,i/1e3):this.cache.set(s,n)}get(t,r){const n=this.makeKey(t,r);return this.cache.get(n)}remove(t,r){const n=this.makeKey(t,r);this.cache.del(n)}clear(t){if(t){const r=this.cache.keys().filter(n=>n.startsWith(`${t}:`));this.cache.del(r)}else this.cache.flushAll()}setBitcoinRedeem(t,r,n){this.set("bitcoinRedeem",t,r,n)}getBitcoinRedeem(t){return this.get("bitcoinRedeem",t)}setOrderExecution(t,r,n,i,s){const a=this.makeOrderKey(t,r),o={txHash:n,timeStamp:Date.now(),btcRedeemUTXO:i};this.set("orderExecutor",a,o,s)}getOrderExecution(t,r){const n=this.makeOrderKey(t,r);return this.get("orderExecutor",n)}removeOrderExecution(t,r){const n=this.makeOrderKey(t,r);this.remove("orderExecutor",n)}makeOrderKey(t,r){return`${r}_${t.order_id??t.created_at}`}setSacpCache(t,r,n){this.set("refundSacp",t,r,n)}getSacpCache(t){return this.get("refundSacp",t)}has(t,r){const n=this.makeKey(t,r);return this.cache.has(n)}peek(t,r){return this.get(t,r)}getRemainingTTL(t,r){const n=this.makeKey(t,r),i=this.cache.getTtl(n);if(i===void 0)return-1;const s=Date.now();return Math.max(0,i-s)}}var jo,Ho,Lo,Fe,Js,bi;class TC{constructor(t,r,n,i,s,a){$i(this,jo);$i(this,Ho);$i(this,Lo);$i(this,Fe);$i(this,Js);$i(this,bi);this.isBackgroundServiceRunning=!1,this.stopBackgroundExecution=null,this.htlcs=r,this.events=a,Mi(this,jo,t),Mi(this,Ho,n),Mi(this,Lo,Mo.fromDigestKey(t.digestKey)),Mi(this,Fe,new kC),Mi(this,Js,i),Mi(this,bi,s)}async getAddressesFromHTLCs(){var n,i,s,a,o,c,u;const t=new Set;return[(n=this.htlcs.evm)==null?void 0:n.htlcActorAddress,(i=this.htlcs.sui)==null?void 0:i.htlcActorAddress,(s=this.htlcs.solana)==null?void 0:s.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(f=>!!f&&f.length>0).forEach(f=>t.add(f.toLowerCase())),Array.from(t)}start(t=5e3,r){this.isBackgroundServiceRunning||this.stopBackgroundExecution||(this.isBackgroundServiceRunning=!0,(async()=>{try{if(r){this.stop();return}const n=await this.execute(t);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(t=5e3){const r=await this.getAddressesFromHTLCs();r.length===0&&r.push(ke(this,jo).userId.toLowerCase());let n=!1,i=null;const s=async()=>{if(!n){n=!0;try{const a=r.map(async c=>{try{const u=await ke(this,Ho).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 s(),i=setInterval(s,t),()=>{i&&clearInterval(i)}}async processOrderActions(t){const r=new Set([D.OrderStatus.InitiateDetected,D.OrderStatus.AwaitingRefund,D.OrderStatus.Initiated,D.OrderStatus.RefundDetected,D.OrderStatus.Refunded,D.OrderStatus.Expired]),n=t.map(async i=>{try{D.isBitcoin(i.source_swap.chain)&&r.has(i.status)&&!D.isCompleted(i)&&await this.postRefundSACP(i),D.parseAction(i)===D.OrderAction.Redeem&&await this.handleRedeemAction(i)}catch(s){this.events.emit("error",i,`Error processing order ${i.order_id}: ${s}`)}});await Promise.all(n)}async handleRedeemAction(t){const r=await ke(this,Lo).generateSecret(t.nonce);if(!r.ok){this.events.emit("error",t,r.error);return}const n=m.trim0x(r.val.secretHash),i=m.trim0x(t.source_swap.secret_hash);if(n!==i){this.events.emit("log",t.order_id,"skipping redeem: secret hash mismatch");return}const s=r.val.secret,a=D.getBlockchainType(t.destination_swap.chain),c={[D.BlockchainType.evm]:()=>this.evmRedeem(t,s),[D.BlockchainType.bitcoin]:()=>this.btcRedeem(t,s),[D.BlockchainType.starknet]:()=>this.starknetRedeem(t,s),[D.BlockchainType.solana]:()=>this.solRedeem(t,s),[D.BlockchainType.xrpl]:()=>this.xrplRedeem(t,s),[D.BlockchainType.sui]:()=>this.suiRedeem(t,s),[D.BlockchainType.tron]:()=>this.tronRedeem(t,s)}[a];c?await c():this.events.emit("error",t,`Unsupported chain: ${t.destination_swap.chain}`)}async evmRedeem(t,r){if(this.events.emit("log",t.order_id,"executing evm redeem"),ke(this,Fe).getOrderExecution(t,D.OrderAction.Redeem)){this.events.emit("log",t.order_id,"already redeemed");return}if(!this.htlcs.evm){this.events.emit("error",t,"EVM HTLC is required");return}const i=await this.htlcs.evm.redeem(t,r);if(!i.ok){this.events.emit("error",t,i.error),i.error.includes("Order already redeemed")&&ke(this,Fe).setOrderExecution(t,D.OrderAction.Redeem,t.destination_swap.redeem_tx_hash);return}ke(this,Fe).setOrderExecution(t,D.OrderAction.Redeem,i.val),this.events.emit("success",t,D.OrderAction.Redeem,i.val)}async starknetRedeem(t,r){if(this.events.emit("log",t.order_id,"executing starknet redeem"),ke(this,Fe).getOrderExecution(t,D.OrderAction.Redeem)){this.events.emit("log",t.order_id,"already redeemed");return}if(!this.htlcs.starknet){this.events.emit("error",t,"Starknet HTLC is required");return}const i=await this.htlcs.starknet.redeem(t,r);if(!i.ok){this.events.emit("error",t,i.error),i.error.includes("Order already redeemed")&&ke(this,Fe).setOrderExecution(t,D.OrderAction.Redeem,t.destination_swap.redeem_tx_hash);return}i.val&&(ke(this,Fe).setOrderExecution(t,D.OrderAction.Redeem,i.val),this.events.emit("success",t,D.OrderAction.Redeem,i.val))}async solRedeem(t,r){if(this.events.emit("log",t.order_id,"executing sol redeem"),ke(this,Fe).getOrderExecution(t,D.OrderAction.Redeem)){this.events.emit("log",t.order_id,"already redeemed");return}if(!this.htlcs.solana){this.events.emit("error",t,"Solana HTLC is required");return}const i=await this.htlcs.solana.redeem(t,r);if(i.error){this.events.emit("error",t,i.error),i.error.includes("Order already redeemed")&&ke(this,Fe).setOrderExecution(t,D.OrderAction.Redeem,t.destination_swap.redeem_tx_hash);return}i.val&&(ke(this,Fe).setOrderExecution(t,D.OrderAction.Redeem,i.val),this.events.emit("success",t,D.OrderAction.Redeem,i.val))}async suiRedeem(t,r){if(this.events.emit("log",t.order_id,"executing sui redeem"),ke(this,Fe).getOrderExecution(t,D.OrderAction.Redeem)){this.events.emit("log",t.order_id,"already redeemed");return}if(!this.htlcs.sui){this.events.emit("error",t,"Sui HTLC is required");return}const i=await this.htlcs.sui.redeem(t,r);if(i.error){this.events.emit("error",t,i.error),i.error.includes("Order already redeemed")&&ke(this,Fe).setOrderExecution(t,D.OrderAction.Redeem,t.destination_swap.redeem_tx_hash);return}i.val&&(ke(this,Fe).setOrderExecution(t,D.OrderAction.Redeem,i.val),this.events.emit("success",t,D.OrderAction.Redeem,i.val))}async tronRedeem(t,r){if(this.events.emit("log",t.order_id,"executing tron redeem"),ke(this,Fe).getOrderExecution(t,D.OrderAction.Redeem)){this.events.emit("log",t.order_id,"already redeemed");return}if(!this.htlcs.tron){this.events.emit("error",t,"Tron HTLC is required");return}const i=await this.htlcs.tron.redeem(t,r);if(i.error){this.events.emit("error",t,i.error),i.error.includes("Order already redeemed")&&ke(this,Fe).setOrderExecution(t,D.OrderAction.Redeem,t.destination_swap.redeem_tx_hash);return}i.val&&(ke(this,Fe).setOrderExecution(t,D.OrderAction.Redeem,i.val),this.events.emit("success",t,D.OrderAction.Redeem,i.val))}async xrplRedeem(t,r){if(this.events.emit("log",t.order_id,"executing xrpl redeem"),ke(this,Fe).getOrderExecution(t,D.OrderAction.Redeem)){this.events.emit("log",t.order_id,"already redeemed");return}if(!this.htlcs.xrpl){this.events.emit("error",t,"XRPL HTLC is required");return}const i=await this.htlcs.xrpl.redeem(t,r);if(i.error){this.events.emit("error",t,i.error),i.error.includes("Order already redeemed")&&ke(this,Fe).setOrderExecution(t,D.OrderAction.Redeem,t.destination_swap.redeem_tx_hash);return}i.val&&(ke(this,Fe).setOrderExecution(t,D.OrderAction.Redeem,i.val),this.events.emit("success",t,D.OrderAction.Redeem,i.val))}async btcRedeem(t,r){var o,c;const n=(o=this.htlcs.bitcoin)==null?void 0:o.getProvider();if(!n){this.events.emit("error",t,"Bitcoin provider not found");return}const i=ke(this,Fe).getBitcoinRedeem(t.order_id),s=(c=t.destination_swap.initiate_tx_hash.split(",").at(-1))==null?void 0:c.split(":").at(0);if(!s){this.events.emit("error",t,"Failed to get initiate_tx_hash");return}let a=!1;if(i)if(i.redeemedFromUTXO&&i.redeemedFromUTXO!==s)a=!0,this.events.emit("log",t.order_id,"rbf btc redeem");else if(i.redeemedAt&&Date.now()-i.redeemedAt>1e3*60*15)this.events.emit("log",t.order_id,"redeem not confirmed in last 15 minutes"),a=!0;else{this.events.emit("log",t.order_id,"btcRedeem: already redeemed");return}else if(t.destination_swap.redeem_tx_hash&&!Number(t.destination_swap.redeem_block_number))try{const u=await(await n).getTransaction(t.destination_swap.redeem_tx_hash);let f=!1;for(const l of u.vin)if(l.txid===s){f=!0;break}if(f){this.events.emit("log",t.order_id,"already a valid redeem");let l=0;try{const[h]=await(await n).getTransactionTimes([t.destination_swap.redeem_tx_hash]);h!==0&&(l=h)}catch{l=Date.now()}ke(this,Fe).setBitcoinRedeem(t.order_id,{redeemedFromUTXO:s,redeemedAt:l,redeemTxHash:t.destination_swap.redeem_tx_hash});return}a=!0}catch(u){if(u.message.includes("Transaction not found"))a=!0;else{this.events.emit("error",t,"Failed to get redeem tx: "+u);return}}this.events.emit("log",t.order_id,"executing btc redeem");try{if(!this.htlcs.bitcoin){this.events.emit("error",t,"Bitcoin HTLC is required");return}const u=await this.htlcs.bitcoin.getRedeemHex(t,m.trim0x(r),a?[s]:[]);if(!u.ok){this.events.emit("error",t,"Failed to get redeem hex");return}const f=await this.broadcastRedeemTx(u.val,t.order_id);if(!f.ok){this.events.emit("error",t,f.error||"Failed to broadcast redeem tx");return}a?(this.events.emit("log",t.order_id,"rbf: btc redeem success"),this.events.emit("rbf",t,f.val)):this.events.emit("success",t,D.OrderAction.Redeem,f.val),ke(this,Fe).setBitcoinRedeem(t.order_id,{redeemedFromUTXO:s,redeemedAt:Date.now(),redeemTxHash:f.val})}catch(u){this.events.emit("error",t,"Failed btc redeem: "+u)}}async postRefundSACP(t){if(t.source_swap.delegate)try{if(!this.htlcs.bitcoin){this.events.emit("error",t,"Bitcoin HTLC is required");return}const n=await ke(this,Js).getAuthHeaders();if(n.error){this.events.emit("error",t,"Failed to get auth headers: "+n.error);return}const i=await m.Fetcher.post(new m.Url(ke(this,bi).baseurl).endpoint("relayer/bitcoin/instant-refund-hash"),{body:JSON.stringify({order_id:t.order_id}),headers:{"Content-Type":"application/json",...n.val}});if(i.error||!i.result){this.events.emit("error",t,"Failed to get hash while posting instant refund SACP: "+i.error);return}const s=await this.htlcs.bitcoin.generateInstantRefundSACPWithHash(i.result),a=new m.Url(ke(this,bi).baseurl).endpoint("relayer/bitcoin/instant-refund");(await m.Fetcher.post(a,{headers:{"Content-Type":"application/json",...n.val},body:JSON.stringify({order_id:t.order_id,signatures:s.val})})).ok&&ke(this,Fe).setSacpCache(t.order_id,{initTxHash:t.source_swap.initiate_tx_hash})}catch(n){this.events.emit("error",t,"Failed to generate and post SACP: "+n);return}}async broadcastRedeemTx(t,r){try{if(!ke(this,bi))return m.Err("API not found");const n=new m.Url(ke(this,bi).relayer).endpoint("/bitcoin/redeem "),i=await ke(this,Js).getAuthHeaders(),a=await(await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...i.val},body:JSON.stringify({redeem_tx_bytes:t,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)}}}jo=new WeakMap,Ho=new WeakMap,Lo=new WeakMap,Fe=new WeakMap,Js=new WeakMap,bi=new WeakMap;class IC extends m.EventBroker{emit(t,...r){super.emit(t,...r)}}class _p extends D.Orderbook{constructor(t){const{api:r}=Bd(t.environment);if(!r)throw new Error("API Key not found");super(new m.Url(r.baseurl),kd(t.apiKey)),this._redeemServiceEnabled=!0,this.executeInterval=5e3,this._api=r,this._digestKey=SC(t.digestKey),this._auth=kd(t.apiKey),this._quote=t.quote??new zg(this._api.baseurl,this._auth),this._htlcs=t.htlc??{},this._events=new IC,this._executor=this._digestKey?new TC(this._digestKey,this.htlcs,this,this._auth,this._api,this._events):void 0}static fromWallets(t){const r=kd(t.apiKey),{api:n,network:i}=Bd(t.environment);if(!n)throw new Error("API not found, invalid environment "+t.environment);const s=t.wallets?{evm:t.wallets.evm?new n6(n.baseurl,t.wallets.evm,r):void 0,starknet:t.wallets.starknet?new c6(n.baseurl,t.wallets.starknet,i,r):void 0,solana:t.wallets.solana?new A6(t.wallets.solana,new m.Url(n.baseurl),i,r,{programAddress:t.solanaProgramAddress}):void 0,sui:t.wallets.sui?new EC(n.baseurl,t.wallets.sui,i,r):void 0,bitcoin:t.wallets.bitcoin?new Sx(t.wallets.bitcoin,i):void 0,tron:t.wallets.tron?new xC(n.baseurl,i,r,t.wallets.tron):void 0,xrpl:t.wallets.xrpl?new G5(n.baseurl,i,r,t.wallets.xrpl):void 0}:{};return new _p({htlc:s,...t})}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(t,r){const n=D.ChainAsset.from(t.fromAsset).blockchainType,i=await yv(n,this._htlcs);if(!i.ok)return m.Err(i.error);const s=await this.createOrder(t);if(!s.ok)return m.Err(s.error);const a=s.val;switch(r==null||r(Ga.orderCreated),r==null||r(Ga.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(Ga.orderInitiated),m.Ok(a.order_id)}async createOrder(t){var k;if(m.hasKeys(t,["source","destination","nonce"]))return super.createOrder(t);const r=t,n=await this.validateAndFillParams(r);if(!n.ok)return m.Err(n.error??"Validation failed");const{sendAddress:i,receiveAddress:s,fromAsset:a,toAsset:o}=n.val,c=Date.now().toString();let u;if(!this.redeemServiceEnabled){const w=await this.secretManager.generateSecret(c);if(!w.ok)return m.Err(w.error);u=w.val.secretHash}const f=(k=r.addresses)==null?void 0:k.bitcoin,l=D.isBitcoin(D.ChainAsset.from(r.fromAsset).chain),h=D.isBitcoin(D.ChainAsset.from(r.toAsset).chain),d=!!u,b={source:{asset:a.toString(),owner:!r.sourceAddress&&l?f??i:i,delegate:d&&l?i:null,amount:r.sendAmount},destination:{asset:o.toString(),owner:!r.destinationAddress&&h?f??s:s,delegate:d&&h?s: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 x=D.ChainAsset.from(r.fromAsset).blockchainType,A=[D.BlockchainType.alpen_signet,D.BlockchainType.bitcoin,D.BlockchainType.litecoin,D.BlockchainType.spark].includes(x)?D.BlockchainType.bitcoin:[D.BlockchainType.tron].includes(x)?D.BlockchainType.evm:x;return g.val.type!==A&&g.val.type!==x?m.Err("Order response type does not match source blockchain type"):m.Ok(g.val)}async validateAndFillParams(t){var c;if(!t.fromAsset||!t.toAsset)return m.Err("Source and destination assets are required for swap");const r=D.ChainAsset.from(t.fromAsset),n=D.ChainAsset.from(t.toAsset);if(r.network!==n.network)return m.Err("Both assets should be on the same network (either mainnet or testnet)");const i=jp(t.sendAmount);if(!i.ok)return m.Err(i.error);const s=jp(t.receiveAmount);if(!s.ok)return m.Err(s.error);if(i<s)return m.Err("Send amount should be greater than receive amount");if(t.sourceAddress&&t.destinationAddress){const u=await this._getAddresses(r.blockchainType,{[r.blockchainType]:t.sourceAddress}),f=await this._getAddresses(n.blockchainType,{[n.blockchainType]:t.destinationAddress});return!u.ok||!f.ok?m.Err(u.error||f.error):m.Ok({sendAddress:u.val,receiveAddress:f.val,fromAsset:r,toAsset:n})}if((D.isBitcoin(D.ChainAsset.from(t.fromAsset).chain)||D.isBitcoin(D.ChainAsset.from(t.toAsset).chain))&&!((c=t.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,t.addresses);if(!a.ok)return m.Err(a.error);const o=await this._getAddresses(n.blockchainType,t.addresses);return o.ok?m.Ok({sendAddress:a.val,receiveAddress:o.val,fromAsset:r,toAsset:n}):m.Err(o.error)}async _getAddresses(t,r){var n;if(this._redeemServiceEnabled&&r&&r[t])return m.Ok(r[t]);switch(t){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 i=(n=this._htlcs.bitcoin)==null?void 0:n.getPublicKey;return!i||!ov(i)?m.Err("Invalid btc public key or pass Bitcoin address in SwapParams"):m.Ok(Ve(i))}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(t,r){return this._events.on(t,r),this}off(t,r){return this._events.off(t,r),this}}class _C{constructor(t,r,n){this.callData=new st.CallData(i6),this.account=t,this.starknetProvider=new st.RpcProvider({nodeUrl:r||(n?ro[n].nodeUrl:ro.mainnet.nodeUrl)})}get htlcActorAddress(){return this.account.address}async getHTLCContract(t,r=!1){const n=r?t.destination_swap.asset:t.source_swap.asset;return new st.Contract({abi:o6,address:n,providerOrAccount:this.account})}async initiate(t){try{const n=await(await this.getHTLCContract(t)).token();if(!n)throw new Error("Token address retrieval failed");const i=st.num.toHex(n),s=st.cairo.uint256(BigInt(t.source_swap.amount));try{const u=await s6(this.account,i,t.source_swap.asset,BigInt(t.source_swap.amount),this.starknetProvider);if(u.error)return m.Err(u.error)}catch(u){return m.Err(`Allowance check failed: ${u}`)}const a=t.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:t.source_swap.asset,entrypoint:"initiate",calldata:[t.source_swap.redeemer,t.source_swap.timelock.toString(),s.low.toString(),s.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(t,r){try{const n=await this.getHTLCContract(t,!0),i=t.source_swap.chain.includes("starknet")?t.source_swap.swap_id:t.destination_swap.swap_id,s=await this.account.execute({contractAddress:n.address,entrypoint:"redeem",calldata:st.CallData.compile({swap_id:i,secret:m.hexToU32Array(r)})});return s.transaction_hash?m.Ok(s.transaction_hash):m.Err("Failed to redeem HTLC transaction")}catch{return m.Err("HTLC Redeem Error")}}async refund(t){try{const r=t.source_swap.chain.includes("starknet")?t.source_swap.swap_id:t.destination_swap.swap_id,n=await this.getHTLCContract(t),i=await this.account.execute({contractAddress:n.address,entrypoint:"refund",calldata:{orderId:r}});return i.transaction_hash?m.Ok(i.transaction_hash):m.Err("Failed to refund HTLC transaction")}catch{return m.Err("HTLC Refund Error")}}}class PC{constructor(t){if(this.provider=t,!t)throw new Error("Provider is required");this.provider=t,this.program=new Or.Program(Th,t)}get htlcActorAddress(){if(!this.program.programId)throw new Error("No program found");return this.provider.publicKey.toBase58()}async initiate(t){if(!t)return m.Err("Order is required");try{const{redeemer:r,secretHash:n,amount:i,expiresIn:s}=wi.from(t),a=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Or.web3.PublicKey.findProgramAddressSync(a,this.program.programId)[0];const o=await this.program.methods.initiate(i,s,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(t,r){if(!t)return m.Err("Order is required");if(!r)return m.Err("Secret is required");const{secretHash:n}=wi.from(t),i=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Or.web3.PublicKey.findProgramAddressSync(i,this.program.programId)[0];try{const{redeemer:s}=wi.from(t);if(!this.swapAccount)return m.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const a=await this.program.methods.redeem(x6(r)).accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey,redeemer:s}).transaction(),o=await this.provider.sendAndConfirm(a);return o?m.Ok(o):m.Err("Failed to redeem HTLC transaction")}catch(s){return m.Err(`Error redeeming swap: ${s instanceof Error?s.message:String(s)}`)}}async refund(t){if(!t)return m.Err("Order is required");const{secretHash:r}=wi.from(t),n=[Buffer.from("swap_account"),Buffer.from(r)];this.swapAccount=Or.web3.PublicKey.findProgramAddressSync(n,this.program.programId)[0];try{if(console.log("Initiating refund for ::",t.source_swap.swap_id),!this.swapAccount)return m.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const i=await this.program.methods.refund().accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey}).transaction(),s=await this.provider.sendAndConfirm(i);return s?m.Ok(s):m.Err("Failed to refund HTLC transaction")}catch(i){return m.Err(`Error refunding swap: ${i instanceof Error?i.message:String(i)}`)}}}const OC=e=>e.map(t=>t),BC=e=>{if(e===m.Network.TESTNET)return CC;if(e===m.Network.LOCALNET)return NC;if(e===m.Network.MAINNET)return RC;throw new Error("Invalid network")},CC=["https://mempool.space/testnet4/api"],RC=["https://mempool.space/api","https://blockstream.info/api"],NC=["http://localhost:30000"],zi={INVALID_PK:"invalid private key",FEE_EXCEEDS_AMOUNT:(e,t)=>`fee exceeds amount: fee: ${e} > amount: ${t}`,SWAP_NOT_FOUND:"swap config not found, please set the swap config first",SCRIPT_NOT_FUNDED:"script not funded",SWAP_NOT_EXPIRED:e=>`swap not expired. Need ${e} more blocks`,MIN_AMOUNT:e=>`amount is too low. Minimum amount is ${e}`,INSUFFICIENT_FUNDS:(e,t)=>`insufficient funds, need ${t} but got ${e}`,AmtPlusFeeExceedsBalance:(e,t,r)=>`amount + fee exceeds balance. Need ${e+t} but got ${r}`},Va={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"},$b=e=>e.sort((t,r)=>t.status.confirmed!=r.status.confirmed?t.status.confirmed?-1:1:r.value-t.value);class UC{constructor(t,r){this.cacheTimeout=2e3,this.utxosCache=new Map,this.APIs=r?OC([r]):BC(t),this.network=dv(t)}async getTxIndex(t,r){const n=this.APIs.map(s=>`${s}/tx/${t}`),{vout:i}=await m.Fetcher.getWithFallback(n);for(let s=0;s<i.length;s++)if(i[s].scriptpubkey_address===r)return s;throw new Error("failed to get tx index")}async broadcast(t){if(!/^[0-9a-fA-F]+$/.test(t))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:t})}catch(n){if(r===4)throw n;await new Promise(i=>setTimeout(i,500))}throw new Error("failed to broadcast tx")}async getBalance(t){return(await this.getUTXOs(t)).reduce((r,n)=>r+n.value,0)}setTimeoutForCache(t){this.cacheTimeout=t}async getUTXOs(t,r){const n=this.utxosCache.get(t);if(n&&Date.now()-n.timestamp<this.cacheTimeout)return Mb(n.utxos,r);const i=await m.Fetcher.getWithFallback(this.APIs.map(s=>`${s}/address/${t}/utxo`),{signal:AbortSignal.timeout(5e3)});return this.utxosCache.set(t,{timestamp:Date.now(),utxos:i}),Mb(i,r)}async getTransactionHex(t){return m.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${t}/hex`))}async getTransaction(t){return m.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${t}`))}async getConfirmations(t){const r=await this.getTransaction(t);return!r.status.confirmed||!r.status.block_height?0:await this.getLatestTip()-r.status.block_height+1}async getFeeRates(){if(this.network===Hr.Regtest)return{fastestFee:8,halfHourFee:7,hourFee:6,economyFee:4,minimumFee:2};let t="";this.network===Hr.Testnet&&(t="testnet4/");const r=`https://mempool.space/${t}api/v1/fees/recommended`,n=`https://blockstream.info/${t}api/fee-estimates`,i=await m.Fetcher.getWithFallback([r,n],{signal:AbortSignal.timeout(5e3)});return"fastestFee"in i?i.fastestFee===1?{fastestFee:2,halfHourFee:2,hourFee:2,economyFee:2,minimumFee:2}:i:{fastestFee:i[1],halfHourFee:i[5],hourFee:i[10],economyFee:i[20],minimumFee:i[25]}}async getTransactions(t,r){const n=await m.Fetcher.getWithFallback(this.APIs.map(i=>`${i}/address/${t}/txs`));if(r===Gc.ALL)return n;if(r===Gc.IN)return n.filter(i=>i.vout.find(s=>s.scriptpubkey_address===t));if(r===Gc.OUT)return n.filter(i=>i.vin.find(s=>s.prevout.scriptpubkey_address===t));throw new Error("failed to get transactions: invalid bitcoin tx type")}getNetwork(){return this.network}async getLatestTip(){return m.Fetcher.getWithFallback(this.APIs.map(t=>`${t}/blocks/tip/height`))}async suggestFee(t,r,n){const s=(await this.getUTXOs(t,r)).length,a=2,o=await this.getFeeRates();return Math.floor(o[rv[n]]*1.05)*(s*70+a*31+10)}async getTransactionTimes(t){const r=t.map(i=>`txId[]=${i}`).join("&");return(await m.Fetcher.getWithFallback(this.APIs.map(i=>`${i}/v1/transaction-times?${r}`))).map(i=>i*1e3)}}const Mb=(e,t)=>{if(Array.isArray(e)){if(t){const r=e.reduce((s,a)=>s+a.value,0);if(r<t)throw new Error(zi.INSUFFICIENT_FUNDS(r,t));let n=BigInt(0);e.sort((s,a)=>a.value-s.value);const i=[];for(const s of e)if(n+=BigInt(s.value),i.push(s),n>=t)break;return $b(i)}return $b(e)}return[]},Na={p2wpkh:"p2wpkh","p2wpkh-p2sh":"p2wpkh-p2sh"},nu={ALL:be.Transaction.SIGHASH_ALL,NONE:be.Transaction.SIGHASH_NONE,SINGLE:be.Transaction.SIGHASH_SINGLE,ALL_ANYONECANPAY:be.Transaction.SIGHASH_ALL|be.Transaction.SIGHASH_ANYONECANPAY,NONE_ANYONECANPAY:be.Transaction.SIGHASH_NONE|be.Transaction.SIGHASH_ANYONECANPAY,SINGLE_ANYONECANPAY:be.Transaction.SIGHASH_SINGLE|be.Transaction.SIGHASH_ANYONECANPAY};class is{constructor(t,r){this._scriptType=t,this._sigHashType=r}get scriptType(){return this._scriptType}get sigHashType(){return this._sigHashType}toString(){return`${this._scriptType} ${this._sigHashType}`}static async fromString(t){const[r,n]=t.split(" "),i=await Np.mixed().oneOf(["segwitV0","segwitV1","p2shSignature"]).required().validate(r),s=await Np.mixed().oneOf(Object.values(nu)).required().validate(parseInt(n));return new is(i,s)}}const FC=(e,t,r=!1)=>{const n=a=>{try{a=be.address.fromBech32(a).data.toString("hex")}catch(o){if(Rd(o))(o.message.includes("Mixed-case string")||o.message.includes("too short"))&&(a=be.address.fromBase58Check(a).hash.toString("hex"));else throw new Error(String(o))}return a},i=be.script.fromASM(`
|
|
88
|
+
OP_IF
|
|
89
|
+
OP_SHA256
|
|
90
|
+
${e.secretHash}
|
|
91
|
+
OP_EQUALVERIFY
|
|
92
|
+
OP_DUP
|
|
93
|
+
OP_HASH160
|
|
94
|
+
${n(e.recipientAddress.address)}
|
|
95
|
+
OP_ELSE
|
|
96
|
+
${be.script.number.encode(e.expiryBlocks).toString("hex")}
|
|
97
|
+
OP_CHECKSEQUENCEVERIFY
|
|
98
|
+
OP_DROP
|
|
99
|
+
OP_DUP
|
|
100
|
+
OP_HASH160
|
|
101
|
+
${n(e.refundAddress.address)}
|
|
102
|
+
OP_ENDIF
|
|
103
|
+
OP_EQUALVERIFY
|
|
104
|
+
OP_CHECKSIG
|
|
105
|
+
`.trim().replace(/\s+/g," ")),s=be.payments[r?"p2sh":"p2wsh"]({redeem:{output:i},network:t});if(!s.address)throw new Error("Could not build address");return{script:i,address:s.address}},to={P2SH:"p2sh",P2WSH:"p2wsh",P2TR:"p2tr"};var q5=(e=>(e[e.Bitcoin=0]="Bitcoin",e[e.EVM=1]="EVM",e))(q5||{});class $C{addSignatureSegwitV0(t=nu.ALL){return new is("segwitV0",t)}addSignatureP2sh(t=nu.ALL){return new is("p2shSignature",t)}addSignatureSegwitV1(t=nu.ALL){return new is("segwitV1",t)}chain(){return q5.Bitcoin}async addAllInputs(t,r,n,i){const s=(i==null?void 0:i.utxos)||await n.getUTXOs(r);for(const a of s){const o=await n.getTxIndex(a.txid,r);t.addInput(Cd(a.txid),o,i==null?void 0:i.nSequence)}return t}async suggestFee(t,r){const n=await this.getAddress();return(await this.getProvider()).suggestFee(n,t,r)}async toOutputScript(t){return be.address.toOutputScript(t,await this.getNetwork())}totalValueFromUTXOs(t){return t.reduce((r,n)=>r+n.value,0)}async scriptToAddress(t){const r=be.payments.p2wsh({redeem:{output:t},network:await this.getNetwork()});if(!r.address)throw new Error("Could not generate p2wsh address");return r.address}async newSwap(t){if(t.secretHash=m.trim0x(t.secretHash),t.secretHash.length!==64)throw new Error(Va.INVALID_SECRET_HASH);const{script:r,address:n}=FC(t,await this.getNetwork());return new MC(this,{...t,redeemScript:r,scriptAddress:n})}getScriptType(t,r){try{if(be.address.fromBase58Check(t).version===r.scriptHash)return to.P2SH}catch{const i=be.address.fromBech32(t);if(i.prefix!==r.bech32)throw new Error("Invalid address");if(i.version===0){if(i.data.length===32)return to.P2WSH}else if(i.version===1&&i.data.length===32)return to.P2TR}throw new Error("Unsupported script type")}}class MC{constructor(t,r){if(r.secretHash=m.trim0x(r.secretHash),r.secretHash.length!==64)throw new Error(Va.INVALID_SECRET_HASH);this.wallet=t,this.swap=r}id(){return this.swap.scriptAddress}async init(){return this.wallet.send(this.swap.scriptAddress,+this.swap.amount.toString())}async redeem(t,r){t=m.trim0x(t);const n=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),Buffer.from(t,"hex"),be.script.number.encode(1),this.swap.redeemScript],i=be.payments.p2wsh({redeem:{output:this.swap.redeemScript},network:await this.wallet.getNetwork()}).address;if(!i)throw new Error("Could not generate p2wsh address for redeem script");try{return await this.wallet.spend(this.swap.redeemScript,i,{witness:n,toAddress:r})}catch(s){throw Rd(s)?s.message.includes("OP_EQUALVERIFY")?new Error(Va.INVALID_PUBKEY_OR_SECRET):new Error(s.message):new Error(String(s))}}async refund(t){const r=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),be.script.number.encode(0),this.swap.redeemScript];try{const n=be.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:t,witness:r,nSequence:this.swap.expiryBlocks})}catch(n){throw Rd(n)?n.message.includes("OP_EQUALVERIFY")?new Error(Va.INVALID_PUBKEY):n.message.includes("BIP")?new Error(Va.ORDER_NOT_EXPIRED):new Error(n.message):new Error(String(n))}}}const Td=(e,t,r,n)=>`m/${e}'/${t===Hr.Mainnet?0:1}'/${r}'/0/${n??0}`,W5={bip44:(e,t,r)=>Td("44",e,r??0,t),bip49:(e,t,r)=>Td("49",e,r??0,t),bip84:(e,t,r)=>Td("84",e,r??0,t)};function Id(e){if(e===Hr.Mainnet)return be.networks.bitcoin;if(e===Hr.Testnet)return be.networks.testnet;if(e===Hr.Regtest)return be.networks.regtest;throw new Error("Invalid network")}function jC(e,t,r){if(!Up.validateMnemonic(e))throw new Error("Invalid mnemonic");const n=(r==null?void 0:r.path)??W5.bip44(t,(r==null?void 0:r.index)??0),i=Q5.BIP32Factory(xr).fromSeed(Up.mnemonicToSeedSync(e));return HC(i,n)}const HC=(e,t)=>{const r=e.derivePath(t).privateKey;if(!r)throw new Error("Unable to derive private key from mnemonic");return r.toString("hex")};be.initEccLib(xr);class Hs extends $C{constructor({privateKey:t,provider:r,pkPath:n,pkType:i}){const s=zc.ECPairFactory(xr),a=Id(r.getNetwork()),o=Buffer.from(t,"hex");if(o.length===0)throw new Error("invalid private key");super(),this.minAmt=1e3,this.path=n||"",this.pkType=i,this.signer=s.fromPrivateKey(o,{network:a}),this.provider=r,this.network=a}static fromMnemonic(t,r,n){const i=W5.bip84(r.getNetwork(),n==null?void 0:n.index),s=jC(t,r.getNetwork(),{path:i});return new Hs({privateKey:s,provider:r,pkType:Na.p2wpkh,pkPath:i})}static fromPrivateKey(t,r,n){return new Hs({privateKey:t,provider:r,pkType:(n==null?void 0:n.pkType)??Na.p2wpkh,pkPath:(n==null?void 0:n.pkPath)??"unknown"})}static createRandom(t){const r=zc.ECPairFactory(xr),n=Id(t.getNetwork()),i=r.makeRandom({network:n});if(!i.privateKey)throw new Error("Failed to create random key");return new Hs({privateKey:i.privateKey.toString("hex"),provider:t,pkType:Na.p2wpkh,pkPath:"unknown"})}static fromWIF(t,r,n){const i=zc.ECPairFactory(xr),s=Id(r.getNetwork()),a=i.fromWIF(t,s);if(!a.privateKey)throw new Error("Invalid WIF");return Hs.fromPrivateKey(a.privateKey.toString("hex"),r,n)}walletConfig(){return{network:this.provider.getNetwork(),path:this.path,addressType:this.pkType}}async spend(t,r,{toAddress:n,fee:i,nSequence:s,unlockScript:a,witness:o}){var h;const c=this.getScriptType(r,this.network),u=await this.provider.getBalance(r);if(u===0)throw new Error(zi.SCRIPT_NOT_FUNDED);let f=new be.Transaction;if(f.version=2,i??(i=await this.provider.suggestFee(r,u,Ls.FAST)),i>u)throw new Error(zi.FEE_EXCEEDS_AMOUNT(i,u));const l=await this.provider.getUTXOs(r);f=await this.addAllInputs(f,r,this.provider,{nSequence:s,utxos:l}),f.addOutput(await this.toOutputScript(n??await this.getAddress()),u-i);for(let d=0;d<f.ins.length;d++)if(c===to.P2SH){if(!a)throw new Error("Unlock script is required for p2sh");const b=[];for(const x of a)if(x instanceof is){const A=x.sigHashType,k=f.hashForSignature(d,t,A);b.push(be.script.signature.encode(Buffer.from(await this.sign(k.toString("hex")),"hex"),A))}else b.push(x);const g=(h=be.payments.p2sh({redeem:{input:be.script.compile(b),output:t},network:this.network}).redeem)==null?void 0:h.input;f.setInputScript(d,g)}else if(c===to.P2WSH){if(!o)throw new Error("Witness is required for p2wsh");const b=[];for(const g of o)if(g instanceof is){const x=g.sigHashType,A=f.hashForWitnessV0(d,t,l[d].value,x);b.push(be.script.signature.encode(Buffer.from(await this.sign(A.toString("hex")),"hex"),x))}else b.push(g);f.setWitness(d,b)}else throw new Error("Invalid script type "+c);return this.provider.broadcast(f.toHex())}async getAddress(){if(this.pkType===Na["p2wpkh-p2sh"]){const{address:r}=be.payments.p2sh({redeem:be.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:t}=be.payments[this.pkType]({pubkey:this.signer.publicKey,network:this.network});if(!t)throw new Error("failed to get the p2wpkh address");return t}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(t,r,n,i,s,a){if(a||(a=await t.suggestFee(n,s,Ls.FAST)),a>s)throw new Error(zi.FEE_EXCEEDS_AMOUNT(a,s));const o=await t.getUTXOs(n,s+a),c=o.reduce((l,h)=>l+h.value,0);if(c<s+a)throw new Error(zi.INSUFFICIENT_FUNDS(c,s+a));const u=new be.Psbt({network:r});for(const l of o){const h=await t.getTransactionHex(l.txid);u.addInput({hash:Cd(l.txid),index:l.vout,nonWitnessUtxo:Buffer.from(h,"hex")})}const f=c-s-a;return u.addOutput({address:i,value:s}),f>546&&u.addOutput({address:n,value:f}),{txHex:u.toHex(),utxoCount:o.length}}async _send(t,r,n){var u;if(n||(n=await this.provider.suggestFee(await this.getAddress(),r,Ls.FAST)),n>r)throw new Error(zi.FEE_EXCEEDS_AMOUNT(n,r));if(r<this.minAmt)throw new Error(zi.MIN_AMOUNT(this.minAmt));const i=await this.getAddress(),s=await this.provider.getUTXOs(i,r+n),a=s.reduce((f,l)=>f+l.value,0),o=new be.Psbt({network:this.network});for(const f of s){const l=await this.provider.getTransactionHex(f.txid),h=await this.provider.getTransaction(f.txid);let d;this.pkType===Na["p2wpkh-p2sh"]&&(d={witnessUtxo:{script:Buffer.from(h.vout[f.vout].scriptpubkey,"hex"),value:f.value},redeemScript:(u=be.payments.p2sh({redeem:be.payments.p2wpkh({pubkey:this.signer.publicKey,network:this.network}),network:this.network}).redeem)==null?void 0:u.output}),o.addInput({hash:Cd(f.txid),index:f.vout,nonWitnessUtxo:Buffer.from(l,"hex"),...d})}const c=a-r-n;return o.addOutput({address:t,value:r}),c>0&&o.addOutput({address:i,value:c}),o.signAllInputs(this.signer).finalizeAllInputs(),o.extractTransaction().toHex()}async send(t,r,n){const i=await this._send(t,r,n);return this.provider.broadcast(i)}async sign(t){return t=t.startsWith("0x")?t.slice(2):t,this.signer.sign(Buffer.from(t,"hex")).toString("hex")}async signSchnorr(t){return this.signer.signSchnorr(t)}}exports.API=Vc;exports.BaseError=G;exports.BitcoinNetwork=Hr;exports.BitcoinProvider=UC;exports.BitcoinWallet=Hs;exports.DEFAULT_AFFILIATE_ASSET=tv;exports.EvmRelay=n6;exports.Garden=_p;exports.HttpRequestError=Gs;exports.OrderCreationStatus=Ga;exports.Quote=zg;exports.STARKNET_CONFIG=ro;exports.SUI_CONFIG=Od;exports.SecretManager=Mo;exports.SolanaHTLC=PC;exports.SolanaRelay=A6;exports.SolanaRelayerAddress=Hb;exports.StarknetHTLC=_C;exports.StarknetRelay=c6;exports.TRON_CONFIG=Lb;exports.XRPL_CONFIG=Db;exports.XrplRelay=G5;exports.alpenTestnet=e6;exports.arcTestnet=F2;exports.botanixMainnet=Q2;exports.call=ic;exports.checkAllowance=Xa;exports.checkAllowanceAndApprove=s6;exports.concat=lr;exports.decodeErrorResult=_1;exports.encodeAbiParameters=Ci;exports.evmToViemChainMap=yf;exports.getChainNameFromChainId=r6;exports.getUrl=Du;exports.hyperevm=Sh;exports.hyperliquidTestnet=Ah;exports.isAddressEqual=pa;exports.isAllowanceSufficient=a6;exports.isHex=Dr;exports.localBatchGatewayRequest=Fw;exports.localBatchGatewayUrl=ac;exports.megaethMainnet=t6;exports.resolveApiConfig=Bd;exports.solanaProgramAddress=Pd;exports.stringify=at;exports.switchOrAddNetwork=kh;exports.toXOnly=Ve;exports.validateBTCAddress=cv;exports.validateLTCAddress=fv;exports.validateLightningAddress=lv;exports.validateSparkAddress=uv;
|